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_commit.go 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package git
  5. import (
  6. "bytes"
  7. "io"
  8. "strconv"
  9. "strings"
  10. "code.gitea.io/gitea/modules/cache"
  11. "code.gitea.io/gitea/modules/setting"
  12. )
  13. // GetBranchCommitID returns last commit ID string of given branch.
  14. func (repo *Repository) GetBranchCommitID(name string) (string, error) {
  15. return repo.GetRefCommitID(BranchPrefix + name)
  16. }
  17. // GetTagCommitID returns last commit ID string of given tag.
  18. func (repo *Repository) GetTagCommitID(name string) (string, error) {
  19. return repo.GetRefCommitID(TagPrefix + name)
  20. }
  21. // GetCommit returns commit object of by ID string.
  22. func (repo *Repository) GetCommit(commitID string) (*Commit, error) {
  23. id, err := repo.ConvertToGitID(commitID)
  24. if err != nil {
  25. return nil, err
  26. }
  27. return repo.getCommit(id)
  28. }
  29. // GetBranchCommit returns the last commit of given branch.
  30. func (repo *Repository) GetBranchCommit(name string) (*Commit, error) {
  31. commitID, err := repo.GetBranchCommitID(name)
  32. if err != nil {
  33. return nil, err
  34. }
  35. return repo.GetCommit(commitID)
  36. }
  37. // GetTagCommit get the commit of the specific tag via name
  38. func (repo *Repository) GetTagCommit(name string) (*Commit, error) {
  39. commitID, err := repo.GetTagCommitID(name)
  40. if err != nil {
  41. return nil, err
  42. }
  43. return repo.GetCommit(commitID)
  44. }
  45. func (repo *Repository) getCommitByPathWithID(id ObjectID, relpath string) (*Commit, error) {
  46. // File name starts with ':' must be escaped.
  47. if relpath[0] == ':' {
  48. relpath = `\` + relpath
  49. }
  50. stdout, _, runErr := NewCommand(repo.Ctx, "log", "-1", prettyLogFormat).AddDynamicArguments(id.String()).AddDashesAndList(relpath).RunStdString(&RunOpts{Dir: repo.Path})
  51. if runErr != nil {
  52. return nil, runErr
  53. }
  54. id, err := NewIDFromString(stdout)
  55. if err != nil {
  56. return nil, err
  57. }
  58. return repo.getCommit(id)
  59. }
  60. // GetCommitByPath returns the last commit of relative path.
  61. func (repo *Repository) GetCommitByPath(relpath string) (*Commit, error) {
  62. stdout, _, runErr := NewCommand(repo.Ctx, "log", "-1", prettyLogFormat).AddDashesAndList(relpath).RunStdBytes(&RunOpts{Dir: repo.Path})
  63. if runErr != nil {
  64. return nil, runErr
  65. }
  66. commits, err := repo.parsePrettyFormatLogToList(stdout)
  67. if err != nil {
  68. return nil, err
  69. }
  70. if len(commits) == 0 {
  71. return nil, ErrNotExist{ID: relpath}
  72. }
  73. return commits[0], nil
  74. }
  75. func (repo *Repository) commitsByRange(id ObjectID, page, pageSize int, not string) ([]*Commit, error) {
  76. cmd := NewCommand(repo.Ctx, "log").
  77. AddOptionFormat("--skip=%d", (page-1)*pageSize).
  78. AddOptionFormat("--max-count=%d", pageSize).
  79. AddArguments(prettyLogFormat).
  80. AddDynamicArguments(id.String())
  81. if not != "" {
  82. cmd.AddOptionValues("--not", not)
  83. }
  84. stdout, _, err := cmd.RunStdBytes(&RunOpts{Dir: repo.Path})
  85. if err != nil {
  86. return nil, err
  87. }
  88. return repo.parsePrettyFormatLogToList(stdout)
  89. }
  90. func (repo *Repository) searchCommits(id ObjectID, opts SearchCommitsOptions) ([]*Commit, error) {
  91. // add common arguments to git command
  92. addCommonSearchArgs := func(c *Command) {
  93. // ignore case
  94. c.AddArguments("-i")
  95. // add authors if present in search query
  96. for _, v := range opts.Authors {
  97. c.AddOptionFormat("--author=%s", v)
  98. }
  99. // add committers if present in search query
  100. for _, v := range opts.Committers {
  101. c.AddOptionFormat("--committer=%s", v)
  102. }
  103. // add time constraints if present in search query
  104. if len(opts.After) > 0 {
  105. c.AddOptionFormat("--after=%s", opts.After)
  106. }
  107. if len(opts.Before) > 0 {
  108. c.AddOptionFormat("--before=%s", opts.Before)
  109. }
  110. }
  111. // create new git log command with limit of 100 commits
  112. cmd := NewCommand(repo.Ctx, "log", "-100", prettyLogFormat).AddDynamicArguments(id.String())
  113. // pretend that all refs along with HEAD were listed on command line as <commis>
  114. // https://git-scm.com/docs/git-log#Documentation/git-log.txt---all
  115. // note this is done only for command created above
  116. if opts.All {
  117. cmd.AddArguments("--all")
  118. }
  119. // interpret search string keywords as string instead of regex
  120. cmd.AddArguments("--fixed-strings")
  121. // add remaining keywords from search string
  122. // note this is done only for command created above
  123. for _, v := range opts.Keywords {
  124. cmd.AddOptionFormat("--grep=%s", v)
  125. }
  126. // search for commits matching given constraints and keywords in commit msg
  127. addCommonSearchArgs(cmd)
  128. stdout, _, err := cmd.RunStdBytes(&RunOpts{Dir: repo.Path})
  129. if err != nil {
  130. return nil, err
  131. }
  132. if len(stdout) != 0 {
  133. stdout = append(stdout, '\n')
  134. }
  135. // if there are any keywords (ie not committer:, author:, time:)
  136. // then let's iterate over them
  137. for _, v := range opts.Keywords {
  138. // ignore anything not matching a valid sha pattern
  139. if id.Type().IsValid(v) {
  140. // create new git log command with 1 commit limit
  141. hashCmd := NewCommand(repo.Ctx, "log", "-1", prettyLogFormat)
  142. // add previous arguments except for --grep and --all
  143. addCommonSearchArgs(hashCmd)
  144. // add keyword as <commit>
  145. hashCmd.AddDynamicArguments(v)
  146. // search with given constraints for commit matching sha hash of v
  147. hashMatching, _, err := hashCmd.RunStdBytes(&RunOpts{Dir: repo.Path})
  148. if err != nil || bytes.Contains(stdout, hashMatching) {
  149. continue
  150. }
  151. stdout = append(stdout, hashMatching...)
  152. stdout = append(stdout, '\n')
  153. }
  154. }
  155. return repo.parsePrettyFormatLogToList(bytes.TrimSuffix(stdout, []byte{'\n'}))
  156. }
  157. // FileChangedBetweenCommits Returns true if the file changed between commit IDs id1 and id2
  158. // You must ensure that id1 and id2 are valid commit ids.
  159. func (repo *Repository) FileChangedBetweenCommits(filename, id1, id2 string) (bool, error) {
  160. stdout, _, err := NewCommand(repo.Ctx, "diff", "--name-only", "-z").AddDynamicArguments(id1, id2).AddDashesAndList(filename).RunStdBytes(&RunOpts{Dir: repo.Path})
  161. if err != nil {
  162. return false, err
  163. }
  164. return len(strings.TrimSpace(string(stdout))) > 0, nil
  165. }
  166. // FileCommitsCount return the number of files at a revision
  167. func (repo *Repository) FileCommitsCount(revision, file string) (int64, error) {
  168. return CommitsCount(repo.Ctx,
  169. CommitsCountOptions{
  170. RepoPath: repo.Path,
  171. Revision: []string{revision},
  172. RelPath: []string{file},
  173. })
  174. }
  175. type CommitsByFileAndRangeOptions struct {
  176. Revision string
  177. File string
  178. Not string
  179. Page int
  180. }
  181. // CommitsByFileAndRange return the commits according revision file and the page
  182. func (repo *Repository) CommitsByFileAndRange(opts CommitsByFileAndRangeOptions) ([]*Commit, error) {
  183. skip := (opts.Page - 1) * setting.Git.CommitsRangeSize
  184. stdoutReader, stdoutWriter := io.Pipe()
  185. defer func() {
  186. _ = stdoutReader.Close()
  187. _ = stdoutWriter.Close()
  188. }()
  189. go func() {
  190. stderr := strings.Builder{}
  191. gitCmd := NewCommand(repo.Ctx, "rev-list").
  192. AddOptionFormat("--max-count=%d", setting.Git.CommitsRangeSize*opts.Page).
  193. AddOptionFormat("--skip=%d", skip)
  194. gitCmd.AddDynamicArguments(opts.Revision)
  195. if opts.Not != "" {
  196. gitCmd.AddOptionValues("--not", opts.Not)
  197. }
  198. gitCmd.AddDashesAndList(opts.File)
  199. err := gitCmd.Run(&RunOpts{
  200. Dir: repo.Path,
  201. Stdout: stdoutWriter,
  202. Stderr: &stderr,
  203. })
  204. if err != nil {
  205. _ = stdoutWriter.CloseWithError(ConcatenateError(err, (&stderr).String()))
  206. } else {
  207. _ = stdoutWriter.Close()
  208. }
  209. }()
  210. len := repo.objectFormat.FullLength()
  211. commits := []*Commit{}
  212. shaline := make([]byte, len+1)
  213. for {
  214. n, err := io.ReadFull(stdoutReader, shaline)
  215. if err != nil || n < len {
  216. if err == io.EOF {
  217. err = nil
  218. }
  219. return commits, err
  220. }
  221. objectID, err := NewIDFromString(string(shaline[0:len]))
  222. if err != nil {
  223. return nil, err
  224. }
  225. commit, err := repo.getCommit(objectID)
  226. if err != nil {
  227. return nil, err
  228. }
  229. commits = append(commits, commit)
  230. }
  231. }
  232. // FilesCountBetween return the number of files changed between two commits
  233. func (repo *Repository) FilesCountBetween(startCommitID, endCommitID string) (int, error) {
  234. stdout, _, err := NewCommand(repo.Ctx, "diff", "--name-only").AddDynamicArguments(startCommitID + "..." + endCommitID).RunStdString(&RunOpts{Dir: repo.Path})
  235. if err != nil && strings.Contains(err.Error(), "no merge base") {
  236. // git >= 2.28 now returns an error if startCommitID and endCommitID have become unrelated.
  237. // previously it would return the results of git diff --name-only startCommitID endCommitID so let's try that...
  238. stdout, _, err = NewCommand(repo.Ctx, "diff", "--name-only").AddDynamicArguments(startCommitID, endCommitID).RunStdString(&RunOpts{Dir: repo.Path})
  239. }
  240. if err != nil {
  241. return 0, err
  242. }
  243. return len(strings.Split(stdout, "\n")) - 1, nil
  244. }
  245. // CommitsBetween returns a list that contains commits between [before, last).
  246. // If before is detached (removed by reset + push) it is not included.
  247. func (repo *Repository) CommitsBetween(last, before *Commit) ([]*Commit, error) {
  248. var stdout []byte
  249. var err error
  250. if before == nil {
  251. stdout, _, err = NewCommand(repo.Ctx, "rev-list").AddDynamicArguments(last.ID.String()).RunStdBytes(&RunOpts{Dir: repo.Path})
  252. } else {
  253. stdout, _, err = NewCommand(repo.Ctx, "rev-list").AddDynamicArguments(before.ID.String() + ".." + last.ID.String()).RunStdBytes(&RunOpts{Dir: repo.Path})
  254. if err != nil && strings.Contains(err.Error(), "no merge base") {
  255. // future versions of git >= 2.28 are likely to return an error if before and last have become unrelated.
  256. // previously it would return the results of git rev-list before last so let's try that...
  257. stdout, _, err = NewCommand(repo.Ctx, "rev-list").AddDynamicArguments(before.ID.String(), last.ID.String()).RunStdBytes(&RunOpts{Dir: repo.Path})
  258. }
  259. }
  260. if err != nil {
  261. return nil, err
  262. }
  263. return repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout))
  264. }
  265. // CommitsBetweenLimit returns a list that contains at most limit commits skipping the first skip commits between [before, last)
  266. func (repo *Repository) CommitsBetweenLimit(last, before *Commit, limit, skip int) ([]*Commit, error) {
  267. var stdout []byte
  268. var err error
  269. if before == nil {
  270. stdout, _, err = NewCommand(repo.Ctx, "rev-list").
  271. AddOptionValues("--max-count", strconv.Itoa(limit)).
  272. AddOptionValues("--skip", strconv.Itoa(skip)).
  273. AddDynamicArguments(last.ID.String()).RunStdBytes(&RunOpts{Dir: repo.Path})
  274. } else {
  275. stdout, _, err = NewCommand(repo.Ctx, "rev-list").
  276. AddOptionValues("--max-count", strconv.Itoa(limit)).
  277. AddOptionValues("--skip", strconv.Itoa(skip)).
  278. AddDynamicArguments(before.ID.String() + ".." + last.ID.String()).RunStdBytes(&RunOpts{Dir: repo.Path})
  279. if err != nil && strings.Contains(err.Error(), "no merge base") {
  280. // future versions of git >= 2.28 are likely to return an error if before and last have become unrelated.
  281. // previously it would return the results of git rev-list --max-count n before last so let's try that...
  282. stdout, _, err = NewCommand(repo.Ctx, "rev-list").
  283. AddOptionValues("--max-count", strconv.Itoa(limit)).
  284. AddOptionValues("--skip", strconv.Itoa(skip)).
  285. AddDynamicArguments(before.ID.String(), last.ID.String()).RunStdBytes(&RunOpts{Dir: repo.Path})
  286. }
  287. }
  288. if err != nil {
  289. return nil, err
  290. }
  291. return repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout))
  292. }
  293. // CommitsBetweenNotBase returns a list that contains commits between [before, last), excluding commits in baseBranch.
  294. // If before is detached (removed by reset + push) it is not included.
  295. func (repo *Repository) CommitsBetweenNotBase(last, before *Commit, baseBranch string) ([]*Commit, error) {
  296. var stdout []byte
  297. var err error
  298. if before == nil {
  299. stdout, _, err = NewCommand(repo.Ctx, "rev-list").AddDynamicArguments(last.ID.String()).AddOptionValues("--not", baseBranch).RunStdBytes(&RunOpts{Dir: repo.Path})
  300. } else {
  301. stdout, _, err = NewCommand(repo.Ctx, "rev-list").AddDynamicArguments(before.ID.String()+".."+last.ID.String()).AddOptionValues("--not", baseBranch).RunStdBytes(&RunOpts{Dir: repo.Path})
  302. if err != nil && strings.Contains(err.Error(), "no merge base") {
  303. // future versions of git >= 2.28 are likely to return an error if before and last have become unrelated.
  304. // previously it would return the results of git rev-list before last so let's try that...
  305. stdout, _, err = NewCommand(repo.Ctx, "rev-list").AddDynamicArguments(before.ID.String(), last.ID.String()).AddOptionValues("--not", baseBranch).RunStdBytes(&RunOpts{Dir: repo.Path})
  306. }
  307. }
  308. if err != nil {
  309. return nil, err
  310. }
  311. return repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout))
  312. }
  313. // CommitsBetweenIDs return commits between twoe commits
  314. func (repo *Repository) CommitsBetweenIDs(last, before string) ([]*Commit, error) {
  315. lastCommit, err := repo.GetCommit(last)
  316. if err != nil {
  317. return nil, err
  318. }
  319. if before == "" {
  320. return repo.CommitsBetween(lastCommit, nil)
  321. }
  322. beforeCommit, err := repo.GetCommit(before)
  323. if err != nil {
  324. return nil, err
  325. }
  326. return repo.CommitsBetween(lastCommit, beforeCommit)
  327. }
  328. // CommitsCountBetween return numbers of commits between two commits
  329. func (repo *Repository) CommitsCountBetween(start, end string) (int64, error) {
  330. count, err := CommitsCount(repo.Ctx, CommitsCountOptions{
  331. RepoPath: repo.Path,
  332. Revision: []string{start + ".." + end},
  333. })
  334. if err != nil && strings.Contains(err.Error(), "no merge base") {
  335. // future versions of git >= 2.28 are likely to return an error if before and last have become unrelated.
  336. // previously it would return the results of git rev-list before last so let's try that...
  337. return CommitsCount(repo.Ctx, CommitsCountOptions{
  338. RepoPath: repo.Path,
  339. Revision: []string{start, end},
  340. })
  341. }
  342. return count, err
  343. }
  344. // commitsBefore the limit is depth, not total number of returned commits.
  345. func (repo *Repository) commitsBefore(id ObjectID, limit int) ([]*Commit, error) {
  346. cmd := NewCommand(repo.Ctx, "log", prettyLogFormat)
  347. if limit > 0 {
  348. cmd.AddOptionFormat("-%d", limit)
  349. }
  350. cmd.AddDynamicArguments(id.String())
  351. stdout, _, runErr := cmd.RunStdBytes(&RunOpts{Dir: repo.Path})
  352. if runErr != nil {
  353. return nil, runErr
  354. }
  355. formattedLog, err := repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout))
  356. if err != nil {
  357. return nil, err
  358. }
  359. commits := make([]*Commit, 0, len(formattedLog))
  360. for _, commit := range formattedLog {
  361. branches, err := repo.getBranches(commit, 2)
  362. if err != nil {
  363. return nil, err
  364. }
  365. if len(branches) > 1 {
  366. break
  367. }
  368. commits = append(commits, commit)
  369. }
  370. return commits, nil
  371. }
  372. func (repo *Repository) getCommitsBefore(id ObjectID) ([]*Commit, error) {
  373. return repo.commitsBefore(id, 0)
  374. }
  375. func (repo *Repository) getCommitsBeforeLimit(id ObjectID, num int) ([]*Commit, error) {
  376. return repo.commitsBefore(id, num)
  377. }
  378. func (repo *Repository) getBranches(commit *Commit, limit int) ([]string, error) {
  379. if CheckGitVersionAtLeast("2.7.0") == nil {
  380. stdout, _, err := NewCommand(repo.Ctx, "for-each-ref", "--format=%(refname:strip=2)").
  381. AddOptionFormat("--count=%d", limit).
  382. AddOptionValues("--contains", commit.ID.String(), BranchPrefix).
  383. RunStdString(&RunOpts{Dir: repo.Path})
  384. if err != nil {
  385. return nil, err
  386. }
  387. branches := strings.Fields(stdout)
  388. return branches, nil
  389. }
  390. stdout, _, err := NewCommand(repo.Ctx, "branch").AddOptionValues("--contains", commit.ID.String()).RunStdString(&RunOpts{Dir: repo.Path})
  391. if err != nil {
  392. return nil, err
  393. }
  394. refs := strings.Split(stdout, "\n")
  395. var max int
  396. if len(refs) > limit {
  397. max = limit
  398. } else {
  399. max = len(refs) - 1
  400. }
  401. branches := make([]string, max)
  402. for i, ref := range refs[:max] {
  403. parts := strings.Fields(ref)
  404. branches[i] = parts[len(parts)-1]
  405. }
  406. return branches, nil
  407. }
  408. // GetCommitsFromIDs get commits from commit IDs
  409. func (repo *Repository) GetCommitsFromIDs(commitIDs []string) []*Commit {
  410. commits := make([]*Commit, 0, len(commitIDs))
  411. for _, commitID := range commitIDs {
  412. commit, err := repo.GetCommit(commitID)
  413. if err == nil && commit != nil {
  414. commits = append(commits, commit)
  415. }
  416. }
  417. return commits
  418. }
  419. // IsCommitInBranch check if the commit is on the branch
  420. func (repo *Repository) IsCommitInBranch(commitID, branch string) (r bool, err error) {
  421. stdout, _, err := NewCommand(repo.Ctx, "branch", "--contains").AddDynamicArguments(commitID, branch).RunStdString(&RunOpts{Dir: repo.Path})
  422. if err != nil {
  423. return false, err
  424. }
  425. return len(stdout) > 0, err
  426. }
  427. func (repo *Repository) AddLastCommitCache(cacheKey, fullName, sha string) error {
  428. if repo.LastCommitCache == nil {
  429. commitsCount, err := cache.GetInt64(cacheKey, func() (int64, error) {
  430. commit, err := repo.GetCommit(sha)
  431. if err != nil {
  432. return 0, err
  433. }
  434. return commit.CommitsCount()
  435. })
  436. if err != nil {
  437. return err
  438. }
  439. repo.LastCommitCache = NewLastCommitCache(commitsCount, fullName, repo, cache.GetCache())
  440. }
  441. return nil
  442. }