You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

371 lines
9.1 KiB

Improve listing performance by using go-git (#6478) * Use go-git for tree reading and commit info lookup. Signed-off-by: Filip Navara <navara@emclient.com> * Use TreeEntry.IsRegular() instead of ObjectType that was removed. Signed-off-by: Filip Navara <navara@emclient.com> * Use the treePath to optimize commit info search. Signed-off-by: Filip Navara <navara@emclient.com> * Extract the latest commit at treePath along with the other commits. Signed-off-by: Filip Navara <navara@emclient.com> * Fix listing commit info for a directory that was created in one commit and never modified after. Signed-off-by: Filip Navara <navara@emclient.com> * Avoid nearly all external 'git' invocations when doing directory listing (.editorconfig code path is still hit). Signed-off-by: Filip Navara <navara@emclient.com> * Use go-git for reading blobs. Signed-off-by: Filip Navara <navara@emclient.com> * Make SHA1 type alias for plumbing.Hash in go-git. Signed-off-by: Filip Navara <navara@emclient.com> * Make Signature type alias for object.Signature in go-git. Signed-off-by: Filip Navara <navara@emclient.com> * Fix GetCommitsInfo for repository with only one commit. Signed-off-by: Filip Navara <navara@emclient.com> * Fix PGP signature verification. Signed-off-by: Filip Navara <navara@emclient.com> * Fix issues with walking commit graph across merges. Signed-off-by: Filip Navara <navara@emclient.com> * Fix typo in condition. Signed-off-by: Filip Navara <navara@emclient.com> * Speed up loading branch list by keeping the repository reference (and thus all the loaded packfile indexes). Signed-off-by: Filip Navara <navara@emclient.com> * Fix lising submodules. Signed-off-by: Filip Navara <navara@emclient.com> * Fix build Signed-off-by: Filip Navara <navara@emclient.com> * Add back commit cache because of name-rev Signed-off-by: Filip Navara <navara@emclient.com> * Fix tests Signed-off-by: Filip Navara <navara@emclient.com> * Fix code style * Fix spelling * Address PR feedback Signed-off-by: Filip Navara <navara@emclient.com> * Update vendor module list Signed-off-by: Filip Navara <navara@emclient.com> * Fix getting trees by commit id Signed-off-by: Filip Navara <navara@emclient.com> * Fix remaining unit test failures * Fix GetTreeBySHA * Avoid running `git name-rev` if not necessary Signed-off-by: Filip Navara <navara@emclient.com> * Move Branch code to git module * Clean up GPG signature verification and fix it for tagged commits * Address PR feedback (import formatting, copyright headers) * Make blob lookup by SHA working * Update tests to use public API * Allow getting content from any type of object through the blob interface * Change test to actually expect the object content that is in the GIT repository * Change one more test to actually expect the object content that is in the GIT repository * Add comments
5 years ago
Improve listing performance by using go-git (#6478) * Use go-git for tree reading and commit info lookup. Signed-off-by: Filip Navara <navara@emclient.com> * Use TreeEntry.IsRegular() instead of ObjectType that was removed. Signed-off-by: Filip Navara <navara@emclient.com> * Use the treePath to optimize commit info search. Signed-off-by: Filip Navara <navara@emclient.com> * Extract the latest commit at treePath along with the other commits. Signed-off-by: Filip Navara <navara@emclient.com> * Fix listing commit info for a directory that was created in one commit and never modified after. Signed-off-by: Filip Navara <navara@emclient.com> * Avoid nearly all external 'git' invocations when doing directory listing (.editorconfig code path is still hit). Signed-off-by: Filip Navara <navara@emclient.com> * Use go-git for reading blobs. Signed-off-by: Filip Navara <navara@emclient.com> * Make SHA1 type alias for plumbing.Hash in go-git. Signed-off-by: Filip Navara <navara@emclient.com> * Make Signature type alias for object.Signature in go-git. Signed-off-by: Filip Navara <navara@emclient.com> * Fix GetCommitsInfo for repository with only one commit. Signed-off-by: Filip Navara <navara@emclient.com> * Fix PGP signature verification. Signed-off-by: Filip Navara <navara@emclient.com> * Fix issues with walking commit graph across merges. Signed-off-by: Filip Navara <navara@emclient.com> * Fix typo in condition. Signed-off-by: Filip Navara <navara@emclient.com> * Speed up loading branch list by keeping the repository reference (and thus all the loaded packfile indexes). Signed-off-by: Filip Navara <navara@emclient.com> * Fix lising submodules. Signed-off-by: Filip Navara <navara@emclient.com> * Fix build Signed-off-by: Filip Navara <navara@emclient.com> * Add back commit cache because of name-rev Signed-off-by: Filip Navara <navara@emclient.com> * Fix tests Signed-off-by: Filip Navara <navara@emclient.com> * Fix code style * Fix spelling * Address PR feedback Signed-off-by: Filip Navara <navara@emclient.com> * Update vendor module list Signed-off-by: Filip Navara <navara@emclient.com> * Fix getting trees by commit id Signed-off-by: Filip Navara <navara@emclient.com> * Fix remaining unit test failures * Fix GetTreeBySHA * Avoid running `git name-rev` if not necessary Signed-off-by: Filip Navara <navara@emclient.com> * Move Branch code to git module * Clean up GPG signature verification and fix it for tagged commits * Address PR feedback (import formatting, copyright headers) * Make blob lookup by SHA working * Update tests to use public API * Allow getting content from any type of object through the blob interface * Change test to actually expect the object content that is in the GIT repository * Change one more test to actually expect the object content that is in the GIT repository * Add comments
5 years ago
Improve listing performance by using go-git (#6478) * Use go-git for tree reading and commit info lookup. Signed-off-by: Filip Navara <navara@emclient.com> * Use TreeEntry.IsRegular() instead of ObjectType that was removed. Signed-off-by: Filip Navara <navara@emclient.com> * Use the treePath to optimize commit info search. Signed-off-by: Filip Navara <navara@emclient.com> * Extract the latest commit at treePath along with the other commits. Signed-off-by: Filip Navara <navara@emclient.com> * Fix listing commit info for a directory that was created in one commit and never modified after. Signed-off-by: Filip Navara <navara@emclient.com> * Avoid nearly all external 'git' invocations when doing directory listing (.editorconfig code path is still hit). Signed-off-by: Filip Navara <navara@emclient.com> * Use go-git for reading blobs. Signed-off-by: Filip Navara <navara@emclient.com> * Make SHA1 type alias for plumbing.Hash in go-git. Signed-off-by: Filip Navara <navara@emclient.com> * Make Signature type alias for object.Signature in go-git. Signed-off-by: Filip Navara <navara@emclient.com> * Fix GetCommitsInfo for repository with only one commit. Signed-off-by: Filip Navara <navara@emclient.com> * Fix PGP signature verification. Signed-off-by: Filip Navara <navara@emclient.com> * Fix issues with walking commit graph across merges. Signed-off-by: Filip Navara <navara@emclient.com> * Fix typo in condition. Signed-off-by: Filip Navara <navara@emclient.com> * Speed up loading branch list by keeping the repository reference (and thus all the loaded packfile indexes). Signed-off-by: Filip Navara <navara@emclient.com> * Fix lising submodules. Signed-off-by: Filip Navara <navara@emclient.com> * Fix build Signed-off-by: Filip Navara <navara@emclient.com> * Add back commit cache because of name-rev Signed-off-by: Filip Navara <navara@emclient.com> * Fix tests Signed-off-by: Filip Navara <navara@emclient.com> * Fix code style * Fix spelling * Address PR feedback Signed-off-by: Filip Navara <navara@emclient.com> * Update vendor module list Signed-off-by: Filip Navara <navara@emclient.com> * Fix getting trees by commit id Signed-off-by: Filip Navara <navara@emclient.com> * Fix remaining unit test failures * Fix GetTreeBySHA * Avoid running `git name-rev` if not necessary Signed-off-by: Filip Navara <navara@emclient.com> * Move Branch code to git module * Clean up GPG signature verification and fix it for tagged commits * Address PR feedback (import formatting, copyright headers) * Make blob lookup by SHA working * Update tests to use public API * Allow getting content from any type of object through the blob interface * Change test to actually expect the object content that is in the GIT repository * Change one more test to actually expect the object content that is in the GIT repository * Add comments
5 years ago
Improve listing performance by using go-git (#6478) * Use go-git for tree reading and commit info lookup. Signed-off-by: Filip Navara <navara@emclient.com> * Use TreeEntry.IsRegular() instead of ObjectType that was removed. Signed-off-by: Filip Navara <navara@emclient.com> * Use the treePath to optimize commit info search. Signed-off-by: Filip Navara <navara@emclient.com> * Extract the latest commit at treePath along with the other commits. Signed-off-by: Filip Navara <navara@emclient.com> * Fix listing commit info for a directory that was created in one commit and never modified after. Signed-off-by: Filip Navara <navara@emclient.com> * Avoid nearly all external 'git' invocations when doing directory listing (.editorconfig code path is still hit). Signed-off-by: Filip Navara <navara@emclient.com> * Use go-git for reading blobs. Signed-off-by: Filip Navara <navara@emclient.com> * Make SHA1 type alias for plumbing.Hash in go-git. Signed-off-by: Filip Navara <navara@emclient.com> * Make Signature type alias for object.Signature in go-git. Signed-off-by: Filip Navara <navara@emclient.com> * Fix GetCommitsInfo for repository with only one commit. Signed-off-by: Filip Navara <navara@emclient.com> * Fix PGP signature verification. Signed-off-by: Filip Navara <navara@emclient.com> * Fix issues with walking commit graph across merges. Signed-off-by: Filip Navara <navara@emclient.com> * Fix typo in condition. Signed-off-by: Filip Navara <navara@emclient.com> * Speed up loading branch list by keeping the repository reference (and thus all the loaded packfile indexes). Signed-off-by: Filip Navara <navara@emclient.com> * Fix lising submodules. Signed-off-by: Filip Navara <navara@emclient.com> * Fix build Signed-off-by: Filip Navara <navara@emclient.com> * Add back commit cache because of name-rev Signed-off-by: Filip Navara <navara@emclient.com> * Fix tests Signed-off-by: Filip Navara <navara@emclient.com> * Fix code style * Fix spelling * Address PR feedback Signed-off-by: Filip Navara <navara@emclient.com> * Update vendor module list Signed-off-by: Filip Navara <navara@emclient.com> * Fix getting trees by commit id Signed-off-by: Filip Navara <navara@emclient.com> * Fix remaining unit test failures * Fix GetTreeBySHA * Avoid running `git name-rev` if not necessary Signed-off-by: Filip Navara <navara@emclient.com> * Move Branch code to git module * Clean up GPG signature verification and fix it for tagged commits * Address PR feedback (import formatting, copyright headers) * Make blob lookup by SHA working * Update tests to use public API * Allow getting content from any type of object through the blob interface * Change test to actually expect the object content that is in the GIT repository * Change one more test to actually expect the object content that is in the GIT repository * Add comments
5 years ago
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2017 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package git
  6. import (
  7. "bytes"
  8. "container/list"
  9. "errors"
  10. "fmt"
  11. "os"
  12. "path"
  13. "path/filepath"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "github.com/Unknwon/com"
  18. "gopkg.in/src-d/go-billy.v4/osfs"
  19. gogit "gopkg.in/src-d/go-git.v4"
  20. "gopkg.in/src-d/go-git.v4/plumbing/cache"
  21. "gopkg.in/src-d/go-git.v4/storage/filesystem"
  22. )
  23. // Repository represents a Git repository.
  24. type Repository struct {
  25. Path string
  26. tagCache *ObjectCache
  27. gogitRepo *gogit.Repository
  28. gogitStorage *filesystem.Storage
  29. }
  30. const prettyLogFormat = `--pretty=format:%H`
  31. func (repo *Repository) parsePrettyFormatLogToList(logs []byte) (*list.List, error) {
  32. l := list.New()
  33. if len(logs) == 0 {
  34. return l, nil
  35. }
  36. parts := bytes.Split(logs, []byte{'\n'})
  37. for _, commitID := range parts {
  38. commit, err := repo.GetCommit(string(commitID))
  39. if err != nil {
  40. return nil, err
  41. }
  42. l.PushBack(commit)
  43. }
  44. return l, nil
  45. }
  46. // IsRepoURLAccessible checks if given repository URL is accessible.
  47. func IsRepoURLAccessible(url string) bool {
  48. _, err := NewCommand("ls-remote", "-q", "-h", url, "HEAD").Run()
  49. return err == nil
  50. }
  51. // InitRepository initializes a new Git repository.
  52. func InitRepository(repoPath string, bare bool) error {
  53. err := os.MkdirAll(repoPath, os.ModePerm)
  54. if err != nil {
  55. return err
  56. }
  57. cmd := NewCommand("init")
  58. if bare {
  59. cmd.AddArguments("--bare")
  60. }
  61. _, err = cmd.RunInDir(repoPath)
  62. return err
  63. }
  64. // OpenRepository opens the repository at the given path.
  65. func OpenRepository(repoPath string) (*Repository, error) {
  66. repoPath, err := filepath.Abs(repoPath)
  67. if err != nil {
  68. return nil, err
  69. } else if !isDir(repoPath) {
  70. return nil, errors.New("no such file or directory")
  71. }
  72. fs := osfs.New(repoPath)
  73. _, err = fs.Stat(".git")
  74. if err == nil {
  75. fs, err = fs.Chroot(".git")
  76. if err != nil {
  77. return nil, err
  78. }
  79. }
  80. storage := filesystem.NewStorageWithOptions(fs, cache.NewObjectLRUDefault(), filesystem.Options{KeepDescriptors: true})
  81. gogitRepo, err := gogit.Open(storage, fs)
  82. if err != nil {
  83. return nil, err
  84. }
  85. return &Repository{
  86. Path: repoPath,
  87. gogitRepo: gogitRepo,
  88. gogitStorage: storage,
  89. tagCache: newObjectCache(),
  90. }, nil
  91. }
  92. // IsEmpty Check if repository is empty.
  93. func (repo *Repository) IsEmpty() (bool, error) {
  94. var errbuf strings.Builder
  95. if err := NewCommand("log", "-1").RunInDirPipeline(repo.Path, nil, &errbuf); err != nil {
  96. if strings.Contains(errbuf.String(), "fatal: bad default revision 'HEAD'") ||
  97. strings.Contains(errbuf.String(), "fatal: your current branch 'master' does not have any commits yet") {
  98. return true, nil
  99. }
  100. return true, fmt.Errorf("check empty: %v - %s", err, errbuf.String())
  101. }
  102. return false, nil
  103. }
  104. // CloneRepoOptions options when clone a repository
  105. type CloneRepoOptions struct {
  106. Timeout time.Duration
  107. Mirror bool
  108. Bare bool
  109. Quiet bool
  110. Branch string
  111. Shared bool
  112. NoCheckout bool
  113. }
  114. // Clone clones original repository to target path.
  115. func Clone(from, to string, opts CloneRepoOptions) (err error) {
  116. toDir := path.Dir(to)
  117. if err = os.MkdirAll(toDir, os.ModePerm); err != nil {
  118. return err
  119. }
  120. cmd := NewCommand("clone")
  121. if opts.Mirror {
  122. cmd.AddArguments("--mirror")
  123. }
  124. if opts.Bare {
  125. cmd.AddArguments("--bare")
  126. }
  127. if opts.Quiet {
  128. cmd.AddArguments("--quiet")
  129. }
  130. if opts.Shared {
  131. cmd.AddArguments("-s")
  132. }
  133. if opts.NoCheckout {
  134. cmd.AddArguments("--no-checkout")
  135. }
  136. if len(opts.Branch) > 0 {
  137. cmd.AddArguments("-b", opts.Branch)
  138. }
  139. cmd.AddArguments("--", from, to)
  140. if opts.Timeout <= 0 {
  141. opts.Timeout = -1
  142. }
  143. _, err = cmd.RunTimeout(opts.Timeout)
  144. return err
  145. }
  146. // PullRemoteOptions options when pull from remote
  147. type PullRemoteOptions struct {
  148. Timeout time.Duration
  149. All bool
  150. Rebase bool
  151. Remote string
  152. Branch string
  153. }
  154. // Pull pulls changes from remotes.
  155. func Pull(repoPath string, opts PullRemoteOptions) error {
  156. cmd := NewCommand("pull")
  157. if opts.Rebase {
  158. cmd.AddArguments("--rebase")
  159. }
  160. if opts.All {
  161. cmd.AddArguments("--all")
  162. } else {
  163. cmd.AddArguments(opts.Remote)
  164. cmd.AddArguments(opts.Branch)
  165. }
  166. if opts.Timeout <= 0 {
  167. opts.Timeout = -1
  168. }
  169. _, err := cmd.RunInDirTimeout(opts.Timeout, repoPath)
  170. return err
  171. }
  172. // PushOptions options when push to remote
  173. type PushOptions struct {
  174. Remote string
  175. Branch string
  176. Force bool
  177. Env []string
  178. }
  179. // Push pushs local commits to given remote branch.
  180. func Push(repoPath string, opts PushOptions) error {
  181. cmd := NewCommand("push")
  182. if opts.Force {
  183. cmd.AddArguments("-f")
  184. }
  185. cmd.AddArguments(opts.Remote, opts.Branch)
  186. _, err := cmd.RunInDirWithEnv(repoPath, opts.Env)
  187. return err
  188. }
  189. // CheckoutOptions options when heck out some branch
  190. type CheckoutOptions struct {
  191. Timeout time.Duration
  192. Branch string
  193. OldBranch string
  194. }
  195. // Checkout checkouts a branch
  196. func Checkout(repoPath string, opts CheckoutOptions) error {
  197. cmd := NewCommand("checkout")
  198. if len(opts.OldBranch) > 0 {
  199. cmd.AddArguments("-b")
  200. }
  201. if opts.Timeout <= 0 {
  202. opts.Timeout = -1
  203. }
  204. cmd.AddArguments(opts.Branch)
  205. if len(opts.OldBranch) > 0 {
  206. cmd.AddArguments(opts.OldBranch)
  207. }
  208. _, err := cmd.RunInDirTimeout(opts.Timeout, repoPath)
  209. return err
  210. }
  211. // ResetHEAD resets HEAD to given revision or head of branch.
  212. func ResetHEAD(repoPath string, hard bool, revision string) error {
  213. cmd := NewCommand("reset")
  214. if hard {
  215. cmd.AddArguments("--hard")
  216. }
  217. _, err := cmd.AddArguments(revision).RunInDir(repoPath)
  218. return err
  219. }
  220. // MoveFile moves a file to another file or directory.
  221. func MoveFile(repoPath, oldTreeName, newTreeName string) error {
  222. _, err := NewCommand("mv").AddArguments(oldTreeName, newTreeName).RunInDir(repoPath)
  223. return err
  224. }
  225. // CountObject represents repository count objects report
  226. type CountObject struct {
  227. Count int64
  228. Size int64
  229. InPack int64
  230. Packs int64
  231. SizePack int64
  232. PrunePack int64
  233. Garbage int64
  234. SizeGarbage int64
  235. }
  236. const (
  237. statCount = "count: "
  238. statSize = "size: "
  239. statInpack = "in-pack: "
  240. statPacks = "packs: "
  241. statSizePack = "size-pack: "
  242. statPrunePackage = "prune-package: "
  243. statGarbage = "garbage: "
  244. statSizeGarbage = "size-garbage: "
  245. )
  246. // GetRepoSize returns disk consumption for repo in path
  247. func GetRepoSize(repoPath string) (*CountObject, error) {
  248. cmd := NewCommand("count-objects", "-v")
  249. stdout, err := cmd.RunInDir(repoPath)
  250. if err != nil {
  251. return nil, err
  252. }
  253. return parseSize(stdout), nil
  254. }
  255. // parseSize parses the output from count-objects and return a CountObject
  256. func parseSize(objects string) *CountObject {
  257. repoSize := new(CountObject)
  258. for _, line := range strings.Split(objects, "\n") {
  259. switch {
  260. case strings.HasPrefix(line, statCount):
  261. repoSize.Count = com.StrTo(line[7:]).MustInt64()
  262. case strings.HasPrefix(line, statSize):
  263. repoSize.Size = com.StrTo(line[6:]).MustInt64() * 1024
  264. case strings.HasPrefix(line, statInpack):
  265. repoSize.InPack = com.StrTo(line[9:]).MustInt64()
  266. case strings.HasPrefix(line, statPacks):
  267. repoSize.Packs = com.StrTo(line[7:]).MustInt64()
  268. case strings.HasPrefix(line, statSizePack):
  269. repoSize.SizePack = com.StrTo(line[11:]).MustInt64() * 1024
  270. case strings.HasPrefix(line, statPrunePackage):
  271. repoSize.PrunePack = com.StrTo(line[16:]).MustInt64()
  272. case strings.HasPrefix(line, statGarbage):
  273. repoSize.Garbage = com.StrTo(line[9:]).MustInt64()
  274. case strings.HasPrefix(line, statSizeGarbage):
  275. repoSize.SizeGarbage = com.StrTo(line[14:]).MustInt64() * 1024
  276. }
  277. }
  278. return repoSize
  279. }
  280. // GetLatestCommitTime returns time for latest commit in repository (across all branches)
  281. func GetLatestCommitTime(repoPath string) (time.Time, error) {
  282. cmd := NewCommand("for-each-ref", "--sort=-committerdate", "refs/heads/", "--count", "1", "--format=%(committerdate)")
  283. stdout, err := cmd.RunInDir(repoPath)
  284. if err != nil {
  285. return time.Time{}, err
  286. }
  287. commitTime := strings.TrimSpace(stdout)
  288. return time.Parse(GitTimeLayout, commitTime)
  289. }
  290. // DivergeObject represents commit count diverging commits
  291. type DivergeObject struct {
  292. Ahead int
  293. Behind int
  294. }
  295. func checkDivergence(repoPath string, baseBranch string, targetBranch string) (int, error) {
  296. branches := fmt.Sprintf("%s..%s", baseBranch, targetBranch)
  297. cmd := NewCommand("rev-list", "--count", branches)
  298. stdout, err := cmd.RunInDir(repoPath)
  299. if err != nil {
  300. return -1, err
  301. }
  302. outInteger, errInteger := strconv.Atoi(strings.Trim(stdout, "\n"))
  303. if errInteger != nil {
  304. return -1, errInteger
  305. }
  306. return outInteger, nil
  307. }
  308. // GetDivergingCommits returns the number of commits a targetBranch is ahead or behind a baseBranch
  309. func GetDivergingCommits(repoPath string, baseBranch string, targetBranch string) (DivergeObject, error) {
  310. // $(git rev-list --count master..feature) commits ahead of master
  311. ahead, errorAhead := checkDivergence(repoPath, baseBranch, targetBranch)
  312. if errorAhead != nil {
  313. return DivergeObject{}, errorAhead
  314. }
  315. // $(git rev-list --count feature..master) commits behind master
  316. behind, errorBehind := checkDivergence(repoPath, targetBranch, baseBranch)
  317. if errorBehind != nil {
  318. return DivergeObject{}, errorBehind
  319. }
  320. return DivergeObject{ahead, behind}, nil
  321. }