tree.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Copyright 2020 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package repo
  5. import (
  6. "fmt"
  7. "github.com/gogs/git-module"
  8. "gogs.io/gogs/internal/context"
  9. "gogs.io/gogs/internal/gitutil"
  10. )
  11. type repoGitTree struct {
  12. Sha string `json:"sha"`
  13. URL string `json:"url"`
  14. Tree []*repoGitTreeEntry `json:"tree"`
  15. }
  16. type repoGitTreeEntry struct {
  17. Path string `json:"path"`
  18. Mode string `json:"mode"`
  19. Type string `json:"type"`
  20. Size int64 `json:"size"`
  21. Sha string `json:"sha"`
  22. URL string `json:"url"`
  23. }
  24. func GetRepoGitTree(c *context.APIContext) {
  25. gitTree, err := c.Repo.GitRepo.LsTree(c.Params(":sha"))
  26. if err != nil {
  27. c.NotFoundOrServerError("get tree", gitutil.IsErrRevisionNotExist, err)
  28. return
  29. }
  30. entries, err := gitTree.Entries()
  31. if err != nil {
  32. c.ServerError("list entries", err)
  33. return
  34. }
  35. templateURL := fmt.Sprintf("%s/repos/%s/%s/git/trees", c.BaseURL, c.Params(":username"), c.Params(":reponame"))
  36. if len(entries) == 0 {
  37. c.JSONSuccess(&repoGitTree{
  38. Sha: c.Params(":sha"),
  39. URL: fmt.Sprintf(templateURL+"/%s", c.Params(":sha")),
  40. })
  41. return
  42. }
  43. children := make([]*repoGitTreeEntry, 0, len(entries))
  44. for _, entry := range entries {
  45. var mode string
  46. switch entry.Type() {
  47. case git.ObjectCommit:
  48. mode = "160000"
  49. case git.ObjectTree:
  50. mode = "040000"
  51. case git.ObjectBlob:
  52. mode = "120000"
  53. case git.ObjectTag:
  54. mode = "100644"
  55. default:
  56. mode = ""
  57. }
  58. children = append(children, &repoGitTreeEntry{
  59. Path: entry.Name(),
  60. Mode: mode,
  61. Type: string(entry.Type()),
  62. Size: entry.Size(),
  63. Sha: entry.ID().String(),
  64. URL: fmt.Sprintf(templateURL+"/%s", entry.ID().String()),
  65. })
  66. }
  67. c.JSONSuccess(&repoGitTree{
  68. Sha: c.Params(":sha"),
  69. URL: fmt.Sprintf(templateURL+"/%s", c.Params(":sha")),
  70. Tree: children,
  71. })
  72. }