tree.go 1.9 KB

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