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 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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. "context"
  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. )
  20. // GPGSettings represents the default GPG settings for this repository
  21. type GPGSettings struct {
  22. Sign bool
  23. KeyID string
  24. Email string
  25. Name string
  26. PublicKeyContent string
  27. }
  28. const prettyLogFormat = `--pretty=format:%H`
  29. // GetAllCommitsCount returns count of all commits in repository
  30. func (repo *Repository) GetAllCommitsCount() (int64, error) {
  31. return AllCommitsCount(repo.Path, false)
  32. }
  33. func (repo *Repository) parsePrettyFormatLogToList(logs []byte) ([]*Commit, error) {
  34. var commits []*Commit
  35. if len(logs) == 0 {
  36. return commits, nil
  37. }
  38. parts := bytes.Split(logs, []byte{'\n'})
  39. for _, commitID := range parts {
  40. commit, err := repo.GetCommit(string(commitID))
  41. if err != nil {
  42. return nil, err
  43. }
  44. commits = append(commits, commit)
  45. }
  46. return commits, nil
  47. }
  48. // IsRepoURLAccessible checks if given repository URL is accessible.
  49. func IsRepoURLAccessible(url string) bool {
  50. _, err := NewCommand("ls-remote", "-q", "-h", url, "HEAD").Run()
  51. return err == nil
  52. }
  53. // InitRepository initializes a new Git repository.
  54. func InitRepository(repoPath string, bare bool) error {
  55. err := os.MkdirAll(repoPath, os.ModePerm)
  56. if err != nil {
  57. return err
  58. }
  59. cmd := NewCommand("init")
  60. if bare {
  61. cmd.AddArguments("--bare")
  62. }
  63. _, err = cmd.RunInDir(repoPath)
  64. return err
  65. }
  66. // IsEmpty Check if repository is empty.
  67. func (repo *Repository) IsEmpty() (bool, error) {
  68. var errbuf strings.Builder
  69. if err := NewCommand("log", "-1").RunInDirPipeline(repo.Path, nil, &errbuf); err != nil {
  70. if strings.Contains(errbuf.String(), "fatal: bad default revision 'HEAD'") ||
  71. strings.Contains(errbuf.String(), "fatal: your current branch 'master' does not have any commits yet") {
  72. return true, nil
  73. }
  74. return true, fmt.Errorf("check empty: %v - %s", err, errbuf.String())
  75. }
  76. return false, nil
  77. }
  78. // CloneRepoOptions options when clone a repository
  79. type CloneRepoOptions struct {
  80. Timeout time.Duration
  81. Mirror bool
  82. Bare bool
  83. Quiet bool
  84. Branch string
  85. Shared bool
  86. NoCheckout bool
  87. Depth int
  88. }
  89. // Clone clones original repository to target path.
  90. func Clone(from, to string, opts CloneRepoOptions) error {
  91. return CloneWithContext(DefaultContext, from, to, opts)
  92. }
  93. // CloneWithContext clones original repository to target path.
  94. func CloneWithContext(ctx context.Context, from, to string, opts CloneRepoOptions) error {
  95. cargs := make([]string, len(GlobalCommandArgs))
  96. copy(cargs, GlobalCommandArgs)
  97. return CloneWithArgs(ctx, from, to, cargs, opts)
  98. }
  99. // CloneWithArgs original repository to target path.
  100. func CloneWithArgs(ctx context.Context, from, to string, args []string, opts CloneRepoOptions) (err error) {
  101. toDir := path.Dir(to)
  102. if err = os.MkdirAll(toDir, os.ModePerm); err != nil {
  103. return err
  104. }
  105. cmd := NewCommandContextNoGlobals(ctx, args...).AddArguments("clone")
  106. if opts.Mirror {
  107. cmd.AddArguments("--mirror")
  108. }
  109. if opts.Bare {
  110. cmd.AddArguments("--bare")
  111. }
  112. if opts.Quiet {
  113. cmd.AddArguments("--quiet")
  114. }
  115. if opts.Shared {
  116. cmd.AddArguments("-s")
  117. }
  118. if opts.NoCheckout {
  119. cmd.AddArguments("--no-checkout")
  120. }
  121. if opts.Depth > 0 {
  122. cmd.AddArguments("--depth", strconv.Itoa(opts.Depth))
  123. }
  124. if len(opts.Branch) > 0 {
  125. cmd.AddArguments("-b", opts.Branch)
  126. }
  127. cmd.AddArguments("--", from, to)
  128. if opts.Timeout <= 0 {
  129. opts.Timeout = -1
  130. }
  131. var envs = os.Environ()
  132. u, err := url.Parse(from)
  133. if err == nil && (strings.EqualFold(u.Scheme, "http") || strings.EqualFold(u.Scheme, "https")) {
  134. if proxy.Match(u.Host) {
  135. envs = append(envs, fmt.Sprintf("https_proxy=%s", proxy.GetProxyURL()))
  136. }
  137. }
  138. var stderr = new(bytes.Buffer)
  139. if err = cmd.RunWithContext(&RunContext{
  140. Timeout: opts.Timeout,
  141. Env: envs,
  142. Stdout: io.Discard,
  143. Stderr: stderr,
  144. }); err != nil {
  145. return ConcatenateError(err, stderr.String())
  146. }
  147. return nil
  148. }
  149. // PullRemoteOptions options when pull from remote
  150. type PullRemoteOptions struct {
  151. Timeout time.Duration
  152. All bool
  153. Rebase bool
  154. Remote string
  155. Branch string
  156. }
  157. // Pull pulls changes from remotes.
  158. func Pull(repoPath string, opts PullRemoteOptions) error {
  159. cmd := NewCommand("pull")
  160. if opts.Rebase {
  161. cmd.AddArguments("--rebase")
  162. }
  163. if opts.All {
  164. cmd.AddArguments("--all")
  165. } else {
  166. cmd.AddArguments("--", opts.Remote, opts.Branch)
  167. }
  168. if opts.Timeout <= 0 {
  169. opts.Timeout = -1
  170. }
  171. _, err := cmd.RunInDirTimeout(opts.Timeout, repoPath)
  172. return err
  173. }
  174. // PushOptions options when push to remote
  175. type PushOptions struct {
  176. Remote string
  177. Branch string
  178. Force bool
  179. Mirror bool
  180. Env []string
  181. Timeout time.Duration
  182. }
  183. // Push pushs local commits to given remote branch.
  184. func Push(repoPath string, opts PushOptions) error {
  185. cmd := NewCommand("push")
  186. if opts.Force {
  187. cmd.AddArguments("-f")
  188. }
  189. if opts.Mirror {
  190. cmd.AddArguments("--mirror")
  191. }
  192. cmd.AddArguments("--", opts.Remote)
  193. if len(opts.Branch) > 0 {
  194. cmd.AddArguments(opts.Branch)
  195. }
  196. var outbuf, errbuf strings.Builder
  197. if opts.Timeout == 0 {
  198. opts.Timeout = -1
  199. }
  200. err := cmd.RunInDirTimeoutEnvPipeline(opts.Env, opts.Timeout, repoPath, &outbuf, &errbuf)
  201. if err != nil {
  202. if strings.Contains(errbuf.String(), "non-fast-forward") {
  203. return &ErrPushOutOfDate{
  204. StdOut: outbuf.String(),
  205. StdErr: errbuf.String(),
  206. Err: err,
  207. }
  208. } else if strings.Contains(errbuf.String(), "! [remote rejected]") {
  209. err := &ErrPushRejected{
  210. StdOut: outbuf.String(),
  211. StdErr: errbuf.String(),
  212. Err: err,
  213. }
  214. err.GenerateMessage()
  215. return err
  216. } else if strings.Contains(errbuf.String(), "matches more than one") {
  217. err := &ErrMoreThanOne{
  218. StdOut: outbuf.String(),
  219. StdErr: errbuf.String(),
  220. Err: err,
  221. }
  222. return err
  223. }
  224. }
  225. if errbuf.Len() > 0 && err != nil {
  226. return fmt.Errorf("%v - %s", err, errbuf.String())
  227. }
  228. return err
  229. }
  230. // CheckoutOptions options when heck out some branch
  231. type CheckoutOptions struct {
  232. Timeout time.Duration
  233. Branch string
  234. OldBranch string
  235. }
  236. // Checkout checkouts a branch
  237. func Checkout(repoPath string, opts CheckoutOptions) error {
  238. cmd := NewCommand("checkout")
  239. if len(opts.OldBranch) > 0 {
  240. cmd.AddArguments("-b")
  241. }
  242. if opts.Timeout <= 0 {
  243. opts.Timeout = -1
  244. }
  245. cmd.AddArguments(opts.Branch)
  246. if len(opts.OldBranch) > 0 {
  247. cmd.AddArguments(opts.OldBranch)
  248. }
  249. _, err := cmd.RunInDirTimeout(opts.Timeout, repoPath)
  250. return err
  251. }
  252. // ResetHEAD resets HEAD to given revision or head of branch.
  253. func ResetHEAD(repoPath string, hard bool, revision string) error {
  254. cmd := NewCommand("reset")
  255. if hard {
  256. cmd.AddArguments("--hard")
  257. }
  258. _, err := cmd.AddArguments(revision).RunInDir(repoPath)
  259. return err
  260. }
  261. // MoveFile moves a file to another file or directory.
  262. func MoveFile(repoPath, oldTreeName, newTreeName string) error {
  263. _, err := NewCommand("mv").AddArguments(oldTreeName, newTreeName).RunInDir(repoPath)
  264. return err
  265. }
  266. // CountObject represents repository count objects report
  267. type CountObject struct {
  268. Count int64
  269. Size int64
  270. InPack int64
  271. Packs int64
  272. SizePack int64
  273. PrunePack int64
  274. Garbage int64
  275. SizeGarbage int64
  276. }
  277. const (
  278. statCount = "count: "
  279. statSize = "size: "
  280. statInpack = "in-pack: "
  281. statPacks = "packs: "
  282. statSizePack = "size-pack: "
  283. statPrunePackage = "prune-package: "
  284. statGarbage = "garbage: "
  285. statSizeGarbage = "size-garbage: "
  286. )
  287. // CountObjects returns the results of git count-objects on the repoPath
  288. func CountObjects(repoPath string) (*CountObject, error) {
  289. cmd := NewCommand("count-objects", "-v")
  290. stdout, err := cmd.RunInDir(repoPath)
  291. if err != nil {
  292. return nil, err
  293. }
  294. return parseSize(stdout), nil
  295. }
  296. // parseSize parses the output from count-objects and return a CountObject
  297. func parseSize(objects string) *CountObject {
  298. repoSize := new(CountObject)
  299. for _, line := range strings.Split(objects, "\n") {
  300. switch {
  301. case strings.HasPrefix(line, statCount):
  302. repoSize.Count, _ = strconv.ParseInt(line[7:], 10, 64)
  303. case strings.HasPrefix(line, statSize):
  304. repoSize.Size, _ = strconv.ParseInt(line[6:], 10, 64)
  305. repoSize.Size *= 1024
  306. case strings.HasPrefix(line, statInpack):
  307. repoSize.InPack, _ = strconv.ParseInt(line[9:], 10, 64)
  308. case strings.HasPrefix(line, statPacks):
  309. repoSize.Packs, _ = strconv.ParseInt(line[7:], 10, 64)
  310. case strings.HasPrefix(line, statSizePack):
  311. repoSize.Count, _ = strconv.ParseInt(line[11:], 10, 64)
  312. repoSize.Count *= 1024
  313. case strings.HasPrefix(line, statPrunePackage):
  314. repoSize.PrunePack, _ = strconv.ParseInt(line[16:], 10, 64)
  315. case strings.HasPrefix(line, statGarbage):
  316. repoSize.Garbage, _ = strconv.ParseInt(line[9:], 10, 64)
  317. case strings.HasPrefix(line, statSizeGarbage):
  318. repoSize.SizeGarbage, _ = strconv.ParseInt(line[14:], 10, 64)
  319. repoSize.SizeGarbage *= 1024
  320. }
  321. }
  322. return repoSize
  323. }
  324. // GetLatestCommitTime returns time for latest commit in repository (across all branches)
  325. func GetLatestCommitTime(repoPath string) (time.Time, error) {
  326. cmd := NewCommand("for-each-ref", "--sort=-committerdate", "refs/heads/", "--count", "1", "--format=%(committerdate)")
  327. stdout, err := cmd.RunInDir(repoPath)
  328. if err != nil {
  329. return time.Time{}, err
  330. }
  331. commitTime := strings.TrimSpace(stdout)
  332. return time.Parse(GitTimeLayout, commitTime)
  333. }
  334. // DivergeObject represents commit count diverging commits
  335. type DivergeObject struct {
  336. Ahead int
  337. Behind int
  338. }
  339. func checkDivergence(repoPath string, baseBranch string, targetBranch string) (int, error) {
  340. branches := fmt.Sprintf("%s..%s", baseBranch, targetBranch)
  341. cmd := NewCommand("rev-list", "--count", branches)
  342. stdout, err := cmd.RunInDir(repoPath)
  343. if err != nil {
  344. return -1, err
  345. }
  346. outInteger, errInteger := strconv.Atoi(strings.Trim(stdout, "\n"))
  347. if errInteger != nil {
  348. return -1, errInteger
  349. }
  350. return outInteger, nil
  351. }
  352. // GetDivergingCommits returns the number of commits a targetBranch is ahead or behind a baseBranch
  353. func GetDivergingCommits(repoPath string, baseBranch string, targetBranch string) (DivergeObject, error) {
  354. // $(git rev-list --count master..feature) commits ahead of master
  355. ahead, errorAhead := checkDivergence(repoPath, baseBranch, targetBranch)
  356. if errorAhead != nil {
  357. return DivergeObject{}, errorAhead
  358. }
  359. // $(git rev-list --count feature..master) commits behind master
  360. behind, errorBehind := checkDivergence(repoPath, targetBranch, baseBranch)
  361. if errorBehind != nil {
  362. return DivergeObject{}, errorBehind
  363. }
  364. return DivergeObject{ahead, behind}, nil
  365. }
  366. // CreateBundle create bundle content to the target path
  367. func (repo *Repository) CreateBundle(ctx context.Context, commit string, out io.Writer) error {
  368. tmp, err := os.MkdirTemp(os.TempDir(), "gitea-bundle")
  369. if err != nil {
  370. return err
  371. }
  372. defer os.RemoveAll(tmp)
  373. tmpFile := filepath.Join(tmp, "bundle")
  374. args := []string{
  375. "bundle",
  376. "create",
  377. tmpFile,
  378. commit,
  379. }
  380. _, err = NewCommandContext(ctx, args...).RunInDir(repo.Path)
  381. if err != nil {
  382. return err
  383. }
  384. fi, err := os.Open(tmpFile)
  385. if err != nil {
  386. return err
  387. }
  388. defer fi.Close()
  389. _, err = io.Copy(out, fi)
  390. return err
  391. }