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.

436 lines
11 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
Sign merges, CRUD, Wiki and Repository initialisation with gpg key (#7631) This PR fixes #7598 by providing a configurable way of signing commits across the Gitea instance. Per repository configurability and import/generation of trusted secure keys is not provided by this PR - from a security PoV that's probably impossible to do properly. Similarly web-signing, that is asking the user to sign something, is not implemented - this could be done at a later stage however. ## Features - [x] If commit.gpgsign is set in .gitconfig sign commits and files created through repofiles. (merges should already have been signed.) - [x] Verify commits signed with the default gpg as valid - [x] Signer, Committer and Author can all be different - [x] Allow signer to be arbitrarily different - We still require the key to have an activated email on Gitea. A more complete implementation would be to use a keyserver and mark external-or-unactivated with an "unknown" trust level icon. - [x] Add a signing-key.gpg endpoint to get the default gpg pub key if available - Rather than add a fake web-flow user I've added this as an endpoint on /api/v1/signing-key.gpg - [x] Try to match the default key with a user on gitea - this is done at verification time - [x] Make things configurable? - app.ini configuration done - [x] when checking commits are signed need to check if they're actually verifiable too - [x] Add documentation I have decided that adjusting the docker to create a default gpg key is not the correct thing to do and therefore have not implemented this.
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. gitealog "code.gitea.io/gitea/modules/log"
  18. "github.com/go-git/go-billy/v5/osfs"
  19. gogit "github.com/go-git/go-git/v5"
  20. "github.com/go-git/go-git/v5/plumbing/cache"
  21. "github.com/go-git/go-git/v5/storage/filesystem"
  22. "github.com/unknwon/com"
  23. )
  24. // Repository represents a Git repository.
  25. type Repository struct {
  26. Path string
  27. tagCache *ObjectCache
  28. gogitRepo *gogit.Repository
  29. gogitStorage *filesystem.Storage
  30. gpgSettings *GPGSettings
  31. }
  32. // GPGSettings represents the default GPG settings for this repository
  33. type GPGSettings struct {
  34. Sign bool
  35. KeyID string
  36. Email string
  37. Name string
  38. PublicKeyContent string
  39. }
  40. const prettyLogFormat = `--pretty=format:%H`
  41. // GetAllCommitsCount returns count of all commits in repository
  42. func (repo *Repository) GetAllCommitsCount() (int64, error) {
  43. return AllCommitsCount(repo.Path)
  44. }
  45. func (repo *Repository) parsePrettyFormatLogToList(logs []byte) (*list.List, error) {
  46. l := list.New()
  47. if len(logs) == 0 {
  48. return l, nil
  49. }
  50. parts := bytes.Split(logs, []byte{'\n'})
  51. for _, commitID := range parts {
  52. commit, err := repo.GetCommit(string(commitID))
  53. if err != nil {
  54. return nil, err
  55. }
  56. l.PushBack(commit)
  57. }
  58. return l, nil
  59. }
  60. // IsRepoURLAccessible checks if given repository URL is accessible.
  61. func IsRepoURLAccessible(url string) bool {
  62. _, err := NewCommand("ls-remote", "-q", "-h", url, "HEAD").Run()
  63. return err == nil
  64. }
  65. // InitRepository initializes a new Git repository.
  66. func InitRepository(repoPath string, bare bool) error {
  67. err := os.MkdirAll(repoPath, os.ModePerm)
  68. if err != nil {
  69. return err
  70. }
  71. cmd := NewCommand("init")
  72. if bare {
  73. cmd.AddArguments("--bare")
  74. }
  75. _, err = cmd.RunInDir(repoPath)
  76. return err
  77. }
  78. // OpenRepository opens the repository at the given path.
  79. func OpenRepository(repoPath string) (*Repository, error) {
  80. repoPath, err := filepath.Abs(repoPath)
  81. if err != nil {
  82. return nil, err
  83. } else if !isDir(repoPath) {
  84. return nil, errors.New("no such file or directory")
  85. }
  86. fs := osfs.New(repoPath)
  87. _, err = fs.Stat(".git")
  88. if err == nil {
  89. fs, err = fs.Chroot(".git")
  90. if err != nil {
  91. return nil, err
  92. }
  93. }
  94. storage := filesystem.NewStorageWithOptions(fs, cache.NewObjectLRUDefault(), filesystem.Options{KeepDescriptors: true})
  95. gogitRepo, err := gogit.Open(storage, fs)
  96. if err != nil {
  97. return nil, err
  98. }
  99. return &Repository{
  100. Path: repoPath,
  101. gogitRepo: gogitRepo,
  102. gogitStorage: storage,
  103. tagCache: newObjectCache(),
  104. }, nil
  105. }
  106. // Close this repository, in particular close the underlying gogitStorage if this is not nil
  107. func (repo *Repository) Close() {
  108. if repo == nil || repo.gogitStorage == nil {
  109. return
  110. }
  111. if err := repo.gogitStorage.Close(); err != nil {
  112. gitealog.Error("Error closing storage: %v", err)
  113. }
  114. }
  115. // GoGitRepo gets the go-git repo representation
  116. func (repo *Repository) GoGitRepo() *gogit.Repository {
  117. return repo.gogitRepo
  118. }
  119. // IsEmpty Check if repository is empty.
  120. func (repo *Repository) IsEmpty() (bool, error) {
  121. var errbuf strings.Builder
  122. if err := NewCommand("log", "-1").RunInDirPipeline(repo.Path, nil, &errbuf); err != nil {
  123. if strings.Contains(errbuf.String(), "fatal: bad default revision 'HEAD'") ||
  124. strings.Contains(errbuf.String(), "fatal: your current branch 'master' does not have any commits yet") {
  125. return true, nil
  126. }
  127. return true, fmt.Errorf("check empty: %v - %s", err, errbuf.String())
  128. }
  129. return false, nil
  130. }
  131. // CloneRepoOptions options when clone a repository
  132. type CloneRepoOptions struct {
  133. Timeout time.Duration
  134. Mirror bool
  135. Bare bool
  136. Quiet bool
  137. Branch string
  138. Shared bool
  139. NoCheckout bool
  140. Depth int
  141. }
  142. // Clone clones original repository to target path.
  143. func Clone(from, to string, opts CloneRepoOptions) (err error) {
  144. cargs := make([]string, len(GlobalCommandArgs))
  145. copy(cargs, GlobalCommandArgs)
  146. return CloneWithArgs(from, to, cargs, opts)
  147. }
  148. // CloneWithArgs original repository to target path.
  149. func CloneWithArgs(from, to string, args []string, opts CloneRepoOptions) (err error) {
  150. toDir := path.Dir(to)
  151. if err = os.MkdirAll(toDir, os.ModePerm); err != nil {
  152. return err
  153. }
  154. cmd := NewCommandNoGlobals(args...).AddArguments("clone")
  155. if opts.Mirror {
  156. cmd.AddArguments("--mirror")
  157. }
  158. if opts.Bare {
  159. cmd.AddArguments("--bare")
  160. }
  161. if opts.Quiet {
  162. cmd.AddArguments("--quiet")
  163. }
  164. if opts.Shared {
  165. cmd.AddArguments("-s")
  166. }
  167. if opts.NoCheckout {
  168. cmd.AddArguments("--no-checkout")
  169. }
  170. if opts.Depth > 0 {
  171. cmd.AddArguments("--depth", strconv.Itoa(opts.Depth))
  172. }
  173. if len(opts.Branch) > 0 {
  174. cmd.AddArguments("-b", opts.Branch)
  175. }
  176. cmd.AddArguments("--", from, to)
  177. if opts.Timeout <= 0 {
  178. opts.Timeout = -1
  179. }
  180. _, err = cmd.RunTimeout(opts.Timeout)
  181. return err
  182. }
  183. // PullRemoteOptions options when pull from remote
  184. type PullRemoteOptions struct {
  185. Timeout time.Duration
  186. All bool
  187. Rebase bool
  188. Remote string
  189. Branch string
  190. }
  191. // Pull pulls changes from remotes.
  192. func Pull(repoPath string, opts PullRemoteOptions) error {
  193. cmd := NewCommand("pull")
  194. if opts.Rebase {
  195. cmd.AddArguments("--rebase")
  196. }
  197. if opts.All {
  198. cmd.AddArguments("--all")
  199. } else {
  200. cmd.AddArguments("--", opts.Remote, opts.Branch)
  201. }
  202. if opts.Timeout <= 0 {
  203. opts.Timeout = -1
  204. }
  205. _, err := cmd.RunInDirTimeout(opts.Timeout, repoPath)
  206. return err
  207. }
  208. // PushOptions options when push to remote
  209. type PushOptions struct {
  210. Remote string
  211. Branch string
  212. Force bool
  213. Env []string
  214. }
  215. // Push pushs local commits to given remote branch.
  216. func Push(repoPath string, opts PushOptions) error {
  217. cmd := NewCommand("push")
  218. if opts.Force {
  219. cmd.AddArguments("-f")
  220. }
  221. cmd.AddArguments("--", opts.Remote, opts.Branch)
  222. var outbuf, errbuf strings.Builder
  223. err := cmd.RunInDirTimeoutEnvPipeline(opts.Env, -1, repoPath, &outbuf, &errbuf)
  224. if err != nil {
  225. if strings.Contains(errbuf.String(), "non-fast-forward") {
  226. return &ErrPushOutOfDate{
  227. StdOut: outbuf.String(),
  228. StdErr: errbuf.String(),
  229. Err: err,
  230. }
  231. } else if strings.Contains(errbuf.String(), "! [remote rejected]") {
  232. err := &ErrPushRejected{
  233. StdOut: outbuf.String(),
  234. StdErr: errbuf.String(),
  235. Err: err,
  236. }
  237. err.GenerateMessage()
  238. return err
  239. }
  240. }
  241. if errbuf.Len() > 0 && err != nil {
  242. return fmt.Errorf("%v - %s", err, errbuf.String())
  243. }
  244. return err
  245. }
  246. // CheckoutOptions options when heck out some branch
  247. type CheckoutOptions struct {
  248. Timeout time.Duration
  249. Branch string
  250. OldBranch string
  251. }
  252. // Checkout checkouts a branch
  253. func Checkout(repoPath string, opts CheckoutOptions) error {
  254. cmd := NewCommand("checkout")
  255. if len(opts.OldBranch) > 0 {
  256. cmd.AddArguments("-b")
  257. }
  258. if opts.Timeout <= 0 {
  259. opts.Timeout = -1
  260. }
  261. cmd.AddArguments(opts.Branch)
  262. if len(opts.OldBranch) > 0 {
  263. cmd.AddArguments(opts.OldBranch)
  264. }
  265. _, err := cmd.RunInDirTimeout(opts.Timeout, repoPath)
  266. return err
  267. }
  268. // ResetHEAD resets HEAD to given revision or head of branch.
  269. func ResetHEAD(repoPath string, hard bool, revision string) error {
  270. cmd := NewCommand("reset")
  271. if hard {
  272. cmd.AddArguments("--hard")
  273. }
  274. _, err := cmd.AddArguments(revision).RunInDir(repoPath)
  275. return err
  276. }
  277. // MoveFile moves a file to another file or directory.
  278. func MoveFile(repoPath, oldTreeName, newTreeName string) error {
  279. _, err := NewCommand("mv").AddArguments(oldTreeName, newTreeName).RunInDir(repoPath)
  280. return err
  281. }
  282. // CountObject represents repository count objects report
  283. type CountObject struct {
  284. Count int64
  285. Size int64
  286. InPack int64
  287. Packs int64
  288. SizePack int64
  289. PrunePack int64
  290. Garbage int64
  291. SizeGarbage int64
  292. }
  293. const (
  294. statCount = "count: "
  295. statSize = "size: "
  296. statInpack = "in-pack: "
  297. statPacks = "packs: "
  298. statSizePack = "size-pack: "
  299. statPrunePackage = "prune-package: "
  300. statGarbage = "garbage: "
  301. statSizeGarbage = "size-garbage: "
  302. )
  303. // CountObjects returns the results of git count-objects on the repoPath
  304. func CountObjects(repoPath string) (*CountObject, error) {
  305. cmd := NewCommand("count-objects", "-v")
  306. stdout, err := cmd.RunInDir(repoPath)
  307. if err != nil {
  308. return nil, err
  309. }
  310. return parseSize(stdout), nil
  311. }
  312. // parseSize parses the output from count-objects and return a CountObject
  313. func parseSize(objects string) *CountObject {
  314. repoSize := new(CountObject)
  315. for _, line := range strings.Split(objects, "\n") {
  316. switch {
  317. case strings.HasPrefix(line, statCount):
  318. repoSize.Count = com.StrTo(line[7:]).MustInt64()
  319. case strings.HasPrefix(line, statSize):
  320. repoSize.Size = com.StrTo(line[6:]).MustInt64() * 1024
  321. case strings.HasPrefix(line, statInpack):
  322. repoSize.InPack = com.StrTo(line[9:]).MustInt64()
  323. case strings.HasPrefix(line, statPacks):
  324. repoSize.Packs = com.StrTo(line[7:]).MustInt64()
  325. case strings.HasPrefix(line, statSizePack):
  326. repoSize.SizePack = com.StrTo(line[11:]).MustInt64() * 1024
  327. case strings.HasPrefix(line, statPrunePackage):
  328. repoSize.PrunePack = com.StrTo(line[16:]).MustInt64()
  329. case strings.HasPrefix(line, statGarbage):
  330. repoSize.Garbage = com.StrTo(line[9:]).MustInt64()
  331. case strings.HasPrefix(line, statSizeGarbage):
  332. repoSize.SizeGarbage = com.StrTo(line[14:]).MustInt64() * 1024
  333. }
  334. }
  335. return repoSize
  336. }
  337. // GetLatestCommitTime returns time for latest commit in repository (across all branches)
  338. func GetLatestCommitTime(repoPath string) (time.Time, error) {
  339. cmd := NewCommand("for-each-ref", "--sort=-committerdate", "refs/heads/", "--count", "1", "--format=%(committerdate)")
  340. stdout, err := cmd.RunInDir(repoPath)
  341. if err != nil {
  342. return time.Time{}, err
  343. }
  344. commitTime := strings.TrimSpace(stdout)
  345. return time.Parse(GitTimeLayout, commitTime)
  346. }
  347. // DivergeObject represents commit count diverging commits
  348. type DivergeObject struct {
  349. Ahead int
  350. Behind int
  351. }
  352. func checkDivergence(repoPath string, baseBranch string, targetBranch string) (int, error) {
  353. branches := fmt.Sprintf("%s..%s", baseBranch, targetBranch)
  354. cmd := NewCommand("rev-list", "--count", branches)
  355. stdout, err := cmd.RunInDir(repoPath)
  356. if err != nil {
  357. return -1, err
  358. }
  359. outInteger, errInteger := strconv.Atoi(strings.Trim(stdout, "\n"))
  360. if errInteger != nil {
  361. return -1, errInteger
  362. }
  363. return outInteger, nil
  364. }
  365. // GetDivergingCommits returns the number of commits a targetBranch is ahead or behind a baseBranch
  366. func GetDivergingCommits(repoPath string, baseBranch string, targetBranch string) (DivergeObject, error) {
  367. // $(git rev-list --count master..feature) commits ahead of master
  368. ahead, errorAhead := checkDivergence(repoPath, baseBranch, targetBranch)
  369. if errorAhead != nil {
  370. return DivergeObject{}, errorAhead
  371. }
  372. // $(git rev-list --count feature..master) commits behind master
  373. behind, errorBehind := checkDivergence(repoPath, targetBranch, baseBranch)
  374. if errorBehind != nil {
  375. return DivergeObject{}, errorBehind
  376. }
  377. return DivergeObject{ahead, behind}, nil
  378. }