gitea源码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2017 The Gitea Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package git
  5. import (
  6. "bytes"
  7. "context"
  8. "fmt"
  9. "io"
  10. "net/url"
  11. "os"
  12. "path"
  13. "path/filepath"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "code.gitea.io/gitea/modules/git/gitcmd"
  18. "code.gitea.io/gitea/modules/proxy"
  19. "code.gitea.io/gitea/modules/setting"
  20. )
  21. // GPGSettings represents the default GPG settings for this repository
  22. type GPGSettings struct {
  23. Sign bool
  24. KeyID string
  25. Email string
  26. Name string
  27. PublicKeyContent string
  28. Format string
  29. }
  30. const prettyLogFormat = `--pretty=format:%H`
  31. // GetAllCommitsCount returns count of all commits in repository
  32. func (repo *Repository) GetAllCommitsCount() (int64, error) {
  33. return AllCommitsCount(repo.Ctx, repo.Path, false)
  34. }
  35. func (repo *Repository) ShowPrettyFormatLogToList(ctx context.Context, revisionRange string) ([]*Commit, error) {
  36. // avoid: ambiguous argument 'refs/a...refs/b': unknown revision or path not in the working tree. Use '--': 'git <command> [<revision>...] -- [<file>...]'
  37. logs, _, err := gitcmd.NewCommand("log").AddArguments(prettyLogFormat).
  38. AddDynamicArguments(revisionRange).AddArguments("--").
  39. RunStdBytes(ctx, &gitcmd.RunOpts{Dir: repo.Path})
  40. if err != nil {
  41. return nil, err
  42. }
  43. return repo.parsePrettyFormatLogToList(logs)
  44. }
  45. func (repo *Repository) parsePrettyFormatLogToList(logs []byte) ([]*Commit, error) {
  46. var commits []*Commit
  47. if len(logs) == 0 {
  48. return commits, nil
  49. }
  50. parts := bytes.SplitSeq(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. commits = append(commits, commit)
  57. }
  58. return commits, nil
  59. }
  60. // IsRepoURLAccessible checks if given repository URL is accessible.
  61. func IsRepoURLAccessible(ctx context.Context, url string) bool {
  62. _, _, err := gitcmd.NewCommand("ls-remote", "-q", "-h").AddDynamicArguments(url, "HEAD").RunStdString(ctx, nil)
  63. return err == nil
  64. }
  65. // InitRepository initializes a new Git repository.
  66. func InitRepository(ctx context.Context, repoPath string, bare bool, objectFormatName string) error {
  67. err := os.MkdirAll(repoPath, os.ModePerm)
  68. if err != nil {
  69. return err
  70. }
  71. cmd := gitcmd.NewCommand("init")
  72. if !IsValidObjectFormat(objectFormatName) {
  73. return fmt.Errorf("invalid object format: %s", objectFormatName)
  74. }
  75. if DefaultFeatures().SupportHashSha256 {
  76. cmd.AddOptionValues("--object-format", objectFormatName)
  77. }
  78. if bare {
  79. cmd.AddArguments("--bare")
  80. }
  81. _, _, err = cmd.RunStdString(ctx, &gitcmd.RunOpts{Dir: repoPath})
  82. return err
  83. }
  84. // IsEmpty Check if repository is empty.
  85. func (repo *Repository) IsEmpty() (bool, error) {
  86. var errbuf, output strings.Builder
  87. if err := gitcmd.NewCommand().AddOptionFormat("--git-dir=%s", repo.Path).AddArguments("rev-list", "-n", "1", "--all").
  88. Run(repo.Ctx, &gitcmd.RunOpts{
  89. Dir: repo.Path,
  90. Stdout: &output,
  91. Stderr: &errbuf,
  92. }); err != nil {
  93. if (err.Error() == "exit status 1" && strings.TrimSpace(errbuf.String()) == "") || err.Error() == "exit status 129" {
  94. // git 2.11 exits with 129 if the repo is empty
  95. return true, nil
  96. }
  97. return true, fmt.Errorf("check empty: %w - %s", err, errbuf.String())
  98. }
  99. return strings.TrimSpace(output.String()) == "", nil
  100. }
  101. // CloneRepoOptions options when clone a repository
  102. type CloneRepoOptions struct {
  103. Timeout time.Duration
  104. Mirror bool
  105. Bare bool
  106. Quiet bool
  107. Branch string
  108. Shared bool
  109. NoCheckout bool
  110. Depth int
  111. Filter string
  112. SkipTLSVerify bool
  113. }
  114. // Clone clones original repository to target path.
  115. func Clone(ctx context.Context, from, to string, opts CloneRepoOptions) error {
  116. toDir := path.Dir(to)
  117. if err := os.MkdirAll(toDir, os.ModePerm); err != nil {
  118. return err
  119. }
  120. cmd := gitcmd.NewCommand().AddArguments("clone")
  121. if opts.SkipTLSVerify {
  122. cmd.AddArguments("-c", "http.sslVerify=false")
  123. }
  124. if opts.Mirror {
  125. cmd.AddArguments("--mirror")
  126. }
  127. if opts.Bare {
  128. cmd.AddArguments("--bare")
  129. }
  130. if opts.Quiet {
  131. cmd.AddArguments("--quiet")
  132. }
  133. if opts.Shared {
  134. cmd.AddArguments("-s")
  135. }
  136. if opts.NoCheckout {
  137. cmd.AddArguments("--no-checkout")
  138. }
  139. if opts.Depth > 0 {
  140. cmd.AddArguments("--depth").AddDynamicArguments(strconv.Itoa(opts.Depth))
  141. }
  142. if opts.Filter != "" {
  143. cmd.AddArguments("--filter").AddDynamicArguments(opts.Filter)
  144. }
  145. if len(opts.Branch) > 0 {
  146. cmd.AddArguments("-b").AddDynamicArguments(opts.Branch)
  147. }
  148. cmd.AddDashesAndList(from, to)
  149. if opts.Timeout <= 0 {
  150. opts.Timeout = -1
  151. }
  152. envs := os.Environ()
  153. u, err := url.Parse(from)
  154. if err == nil {
  155. envs = proxy.EnvWithProxy(u)
  156. }
  157. stderr := new(bytes.Buffer)
  158. if err = cmd.Run(ctx, &gitcmd.RunOpts{
  159. Timeout: opts.Timeout,
  160. Env: envs,
  161. Stdout: io.Discard,
  162. Stderr: stderr,
  163. }); err != nil {
  164. return gitcmd.ConcatenateError(err, stderr.String())
  165. }
  166. return nil
  167. }
  168. // PushOptions options when push to remote
  169. type PushOptions struct {
  170. Remote string
  171. Branch string
  172. Force bool
  173. Mirror bool
  174. Env []string
  175. Timeout time.Duration
  176. }
  177. // Push pushs local commits to given remote branch.
  178. func Push(ctx context.Context, repoPath string, opts PushOptions) error {
  179. cmd := gitcmd.NewCommand("push")
  180. if opts.Force {
  181. cmd.AddArguments("-f")
  182. }
  183. if opts.Mirror {
  184. cmd.AddArguments("--mirror")
  185. }
  186. remoteBranchArgs := []string{opts.Remote}
  187. if len(opts.Branch) > 0 {
  188. remoteBranchArgs = append(remoteBranchArgs, opts.Branch)
  189. }
  190. cmd.AddDashesAndList(remoteBranchArgs...)
  191. stdout, stderr, err := cmd.RunStdString(ctx, &gitcmd.RunOpts{Env: opts.Env, Timeout: opts.Timeout, Dir: repoPath})
  192. if err != nil {
  193. if strings.Contains(stderr, "non-fast-forward") {
  194. return &ErrPushOutOfDate{StdOut: stdout, StdErr: stderr, Err: err}
  195. } else if strings.Contains(stderr, "! [remote rejected]") || strings.Contains(stderr, "! [rejected]") {
  196. err := &ErrPushRejected{StdOut: stdout, StdErr: stderr, Err: err}
  197. err.GenerateMessage()
  198. return err
  199. } else if strings.Contains(stderr, "matches more than one") {
  200. return &ErrMoreThanOne{StdOut: stdout, StdErr: stderr, Err: err}
  201. }
  202. return fmt.Errorf("push failed: %w - %s\n%s", err, stderr, stdout)
  203. }
  204. return nil
  205. }
  206. // GetLatestCommitTime returns time for latest commit in repository (across all branches)
  207. func GetLatestCommitTime(ctx context.Context, repoPath string) (time.Time, error) {
  208. cmd := gitcmd.NewCommand("for-each-ref", "--sort=-committerdate", BranchPrefix, "--count", "1", "--format=%(committerdate)")
  209. stdout, _, err := cmd.RunStdString(ctx, &gitcmd.RunOpts{Dir: repoPath})
  210. if err != nil {
  211. return time.Time{}, err
  212. }
  213. commitTime := strings.TrimSpace(stdout)
  214. return time.Parse("Mon Jan _2 15:04:05 2006 -0700", commitTime)
  215. }
  216. // DivergeObject represents commit count diverging commits
  217. type DivergeObject struct {
  218. Ahead int
  219. Behind int
  220. }
  221. // GetDivergingCommits returns the number of commits a targetBranch is ahead or behind a baseBranch
  222. func GetDivergingCommits(ctx context.Context, repoPath, baseBranch, targetBranch string) (do DivergeObject, err error) {
  223. cmd := gitcmd.NewCommand("rev-list", "--count", "--left-right").
  224. AddDynamicArguments(baseBranch + "..." + targetBranch).AddArguments("--")
  225. stdout, _, err := cmd.RunStdString(ctx, &gitcmd.RunOpts{Dir: repoPath})
  226. if err != nil {
  227. return do, err
  228. }
  229. left, right, found := strings.Cut(strings.Trim(stdout, "\n"), "\t")
  230. if !found {
  231. return do, fmt.Errorf("git rev-list output is missing a tab: %q", stdout)
  232. }
  233. do.Behind, err = strconv.Atoi(left)
  234. if err != nil {
  235. return do, err
  236. }
  237. do.Ahead, err = strconv.Atoi(right)
  238. if err != nil {
  239. return do, err
  240. }
  241. return do, nil
  242. }
  243. // CreateBundle create bundle content to the target path
  244. func (repo *Repository) CreateBundle(ctx context.Context, commit string, out io.Writer) error {
  245. tmp, cleanup, err := setting.AppDataTempDir("git-repo-content").MkdirTempRandom("gitea-bundle")
  246. if err != nil {
  247. return err
  248. }
  249. defer cleanup()
  250. env := append(os.Environ(), "GIT_OBJECT_DIRECTORY="+filepath.Join(repo.Path, "objects"))
  251. _, _, err = gitcmd.NewCommand("init", "--bare").RunStdString(ctx, &gitcmd.RunOpts{Dir: tmp, Env: env})
  252. if err != nil {
  253. return err
  254. }
  255. _, _, err = gitcmd.NewCommand("reset", "--soft").AddDynamicArguments(commit).RunStdString(ctx, &gitcmd.RunOpts{Dir: tmp, Env: env})
  256. if err != nil {
  257. return err
  258. }
  259. _, _, err = gitcmd.NewCommand("branch", "-m", "bundle").RunStdString(ctx, &gitcmd.RunOpts{Dir: tmp, Env: env})
  260. if err != nil {
  261. return err
  262. }
  263. tmpFile := filepath.Join(tmp, "bundle")
  264. _, _, err = gitcmd.NewCommand("bundle", "create").AddDynamicArguments(tmpFile, "bundle", "HEAD").RunStdString(ctx, &gitcmd.RunOpts{Dir: tmp, Env: env})
  265. if err != nil {
  266. return err
  267. }
  268. fi, err := os.Open(tmpFile)
  269. if err != nil {
  270. return err
  271. }
  272. defer fi.Close()
  273. _, err = io.Copy(out, fi)
  274. return err
  275. }