tree.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package repo
  2. import (
  3. "fmt"
  4. "github.com/gogs/git-module"
  5. "gogs.io/gogs/internal/context"
  6. "gogs.io/gogs/internal/gitutil"
  7. )
  8. func GetRepoGitTree(c *context.APIContext) {
  9. gitRepo, err := git.Open(c.Repo.Repository.RepoPath())
  10. if err != nil {
  11. c.Error(err, "open repository")
  12. return
  13. }
  14. sha := c.Params(":sha")
  15. tree, err := gitRepo.LsTree(sha, git.LsTreeOptions{Verbatim: true})
  16. if err != nil {
  17. c.NotFoundOrError(gitutil.NewError(err), "get tree")
  18. return
  19. }
  20. entries, err := tree.Entries(git.LsTreeOptions{Verbatim: true})
  21. if err != nil {
  22. c.Error(err, "list entries")
  23. return
  24. }
  25. type repoGitTreeEntry struct {
  26. Path string `json:"path"`
  27. Mode string `json:"mode"`
  28. Type string `json:"type"`
  29. Size int64 `json:"size"`
  30. Sha string `json:"sha"`
  31. URL string `json:"url"`
  32. }
  33. type repoGitTree struct {
  34. Sha string `json:"sha"`
  35. URL string `json:"url"`
  36. Tree []*repoGitTreeEntry `json:"tree"`
  37. }
  38. treesURL := fmt.Sprintf("%s/repos/%s/%s/git/trees", c.BaseURL, c.Params(":username"), c.Params(":reponame"))
  39. if len(entries) == 0 {
  40. c.JSONSuccess(&repoGitTree{
  41. Sha: sha,
  42. URL: fmt.Sprintf(treesURL+"/%s", sha),
  43. })
  44. return
  45. }
  46. children := make([]*repoGitTreeEntry, 0, len(entries))
  47. for _, entry := range entries {
  48. var mode string
  49. switch entry.Type() {
  50. case git.ObjectCommit:
  51. mode = "160000"
  52. case git.ObjectTree:
  53. mode = "040000"
  54. case git.ObjectBlob:
  55. mode = "120000"
  56. case git.ObjectTag:
  57. mode = "100644"
  58. default:
  59. panic("unreachable")
  60. }
  61. children = append(children, &repoGitTreeEntry{
  62. Path: entry.Name(),
  63. Mode: mode,
  64. Type: string(entry.Type()),
  65. Size: entry.Size(),
  66. Sha: entry.ID().String(),
  67. URL: fmt.Sprintf(treesURL+"/%s", entry.ID().String()),
  68. })
  69. }
  70. c.JSONSuccess(&repoGitTree{
  71. Sha: c.Params(":sha"),
  72. URL: fmt.Sprintf(treesURL+"/%s", sha),
  73. Tree: children,
  74. })
  75. }