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.

repo.go 9.5KB

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