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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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. objectFormat, err := repo.GetObjectFormat()
  211. if err != nil {
  212. return nil, err
  213. }
  214. length := objectFormat.FullLength()
  215. commits := []*Commit{}
  216. shaline := make([]byte, length+1)
  217. for {
  218. n, err := io.ReadFull(stdoutReader, shaline)
  219. if err != nil || n < length {
  220. if err == io.EOF {
  221. err = nil
  222. }
  223. return commits, err
  224. }
  225. objectID, err := NewIDFromString(string(shaline[0:length]))
  226. if err != nil {
  227. return nil, err
  228. }
  229. commit, err := repo.getCommit(objectID)
  230. if err != nil {
  231. return nil, err
  232. }
  233. commits = append(commits, commit)
  234. }
  235. }
  236. // FilesCountBetween return the number of files changed between two commits
  237. func (repo *Repository) FilesCountBetween(startCommitID, endCommitID string) (int, error) {
  238. stdout, _, err := NewCommand(repo.Ctx, "diff", "--name-only").AddDynamicArguments(startCommitID + "..." + endCommitID).RunStdString(&RunOpts{Dir: repo.Path})
  239. if err != nil && strings.Contains(err.Error(), "no merge base") {
  240. // git >= 2.28 now returns an error if startCommitID and endCommitID have become unrelated.
  241. // previously it would return the results of git diff --name-only startCommitID endCommitID so let's try that...
  242. stdout, _, err = NewCommand(repo.Ctx, "diff", "--name-only").AddDynamicArguments(startCommitID, endCommitID).RunStdString(&RunOpts{Dir: repo.Path})
  243. }
  244. if err != nil {
  245. return 0, err
  246. }
  247. return len(strings.Split(stdout, "\n")) - 1, nil
  248. }
  249. // CommitsBetween returns a list that contains commits between [before, last).
  250. // If before is detached (removed by reset + push) it is not included.
  251. func (repo *Repository) CommitsBetween(last, before *Commit) ([]*Commit, error) {
  252. var stdout []byte
  253. var err error
  254. if before == nil {
  255. stdout, _, err = NewCommand(repo.Ctx, "rev-list").AddDynamicArguments(last.ID.String()).RunStdBytes(&RunOpts{Dir: repo.Path})
  256. } else {
  257. stdout, _, err = NewCommand(repo.Ctx, "rev-list").AddDynamicArguments(before.ID.String() + ".." + last.ID.String()).RunStdBytes(&RunOpts{Dir: repo.Path})
  258. if err != nil && strings.Contains(err.Error(), "no merge base") {
  259. // future versions of git >= 2.28 are likely to return an error if before and last have become unrelated.
  260. // previously it would return the results of git rev-list before last so let's try that...
  261. stdout, _, err = NewCommand(repo.Ctx, "rev-list").AddDynamicArguments(before.ID.String(), last.ID.String()).RunStdBytes(&RunOpts{Dir: repo.Path})
  262. }
  263. }
  264. if err != nil {
  265. return nil, err
  266. }
  267. return repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout))
  268. }
  269. // CommitsBetweenLimit returns a list that contains at most limit commits skipping the first skip commits between [before, last)
  270. func (repo *Repository) CommitsBetweenLimit(last, before *Commit, limit, skip int) ([]*Commit, error) {
  271. var stdout []byte
  272. var err error
  273. if before == nil {
  274. stdout, _, err = NewCommand(repo.Ctx, "rev-list").
  275. AddOptionValues("--max-count", strconv.Itoa(limit)).
  276. AddOptionValues("--skip", strconv.Itoa(skip)).
  277. AddDynamicArguments(last.ID.String()).RunStdBytes(&RunOpts{Dir: repo.Path})
  278. } else {
  279. stdout, _, err = NewCommand(repo.Ctx, "rev-list").
  280. AddOptionValues("--max-count", strconv.Itoa(limit)).
  281. AddOptionValues("--skip", strconv.Itoa(skip)).
  282. AddDynamicArguments(before.ID.String() + ".." + last.ID.String()).RunStdBytes(&RunOpts{Dir: repo.Path})
  283. if err != nil && strings.Contains(err.Error(), "no merge base") {
  284. // future versions of git >= 2.28 are likely to return an error if before and last have become unrelated.
  285. // previously it would return the results of git rev-list --max-count n before last so let's try that...
  286. stdout, _, err = NewCommand(repo.Ctx, "rev-list").
  287. AddOptionValues("--max-count", strconv.Itoa(limit)).
  288. AddOptionValues("--skip", strconv.Itoa(skip)).
  289. AddDynamicArguments(before.ID.String(), last.ID.String()).RunStdBytes(&RunOpts{Dir: repo.Path})
  290. }
  291. }
  292. if err != nil {
  293. return nil, err
  294. }
  295. return repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout))
  296. }
  297. // CommitsBetweenNotBase returns a list that contains commits between [before, last), excluding commits in baseBranch.
  298. // If before is detached (removed by reset + push) it is not included.
  299. func (repo *Repository) CommitsBetweenNotBase(last, before *Commit, baseBranch string) ([]*Commit, error) {
  300. var stdout []byte
  301. var err error
  302. if before == nil {
  303. stdout, _, err = NewCommand(repo.Ctx, "rev-list").AddDynamicArguments(last.ID.String()).AddOptionValues("--not", baseBranch).RunStdBytes(&RunOpts{Dir: repo.Path})
  304. } else {
  305. stdout, _, err = NewCommand(repo.Ctx, "rev-list").AddDynamicArguments(before.ID.String()+".."+last.ID.String()).AddOptionValues("--not", baseBranch).RunStdBytes(&RunOpts{Dir: repo.Path})
  306. if err != nil && strings.Contains(err.Error(), "no merge base") {
  307. // future versions of git >= 2.28 are likely to return an error if before and last have become unrelated.
  308. // previously it would return the results of git rev-list before last so let's try that...
  309. stdout, _, err = NewCommand(repo.Ctx, "rev-list").AddDynamicArguments(before.ID.String(), last.ID.String()).AddOptionValues("--not", baseBranch).RunStdBytes(&RunOpts{Dir: repo.Path})
  310. }
  311. }
  312. if err != nil {
  313. return nil, err
  314. }
  315. return repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout))
  316. }
  317. // CommitsBetweenIDs return commits between twoe commits
  318. func (repo *Repository) CommitsBetweenIDs(last, before string) ([]*Commit, error) {
  319. lastCommit, err := repo.GetCommit(last)
  320. if err != nil {
  321. return nil, err
  322. }
  323. if before == "" {
  324. return repo.CommitsBetween(lastCommit, nil)
  325. }
  326. beforeCommit, err := repo.GetCommit(before)
  327. if err != nil {
  328. return nil, err
  329. }
  330. return repo.CommitsBetween(lastCommit, beforeCommit)
  331. }
  332. // CommitsCountBetween return numbers of commits between two commits
  333. func (repo *Repository) CommitsCountBetween(start, end string) (int64, error) {
  334. count, err := CommitsCount(repo.Ctx, CommitsCountOptions{
  335. RepoPath: repo.Path,
  336. Revision: []string{start + ".." + end},
  337. })
  338. if err != nil && strings.Contains(err.Error(), "no merge base") {
  339. // future versions of git >= 2.28 are likely to return an error if before and last have become unrelated.
  340. // previously it would return the results of git rev-list before last so let's try that...
  341. return CommitsCount(repo.Ctx, CommitsCountOptions{
  342. RepoPath: repo.Path,
  343. Revision: []string{start, end},
  344. })
  345. }
  346. return count, err
  347. }
  348. // commitsBefore the limit is depth, not total number of returned commits.
  349. func (repo *Repository) commitsBefore(id ObjectID, limit int) ([]*Commit, error) {
  350. cmd := NewCommand(repo.Ctx, "log", prettyLogFormat)
  351. if limit > 0 {
  352. cmd.AddOptionFormat("-%d", limit)
  353. }
  354. cmd.AddDynamicArguments(id.String())
  355. stdout, _, runErr := cmd.RunStdBytes(&RunOpts{Dir: repo.Path})
  356. if runErr != nil {
  357. return nil, runErr
  358. }
  359. formattedLog, err := repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout))
  360. if err != nil {
  361. return nil, err
  362. }
  363. commits := make([]*Commit, 0, len(formattedLog))
  364. for _, commit := range formattedLog {
  365. branches, err := repo.getBranches(commit, 2)
  366. if err != nil {
  367. return nil, err
  368. }
  369. if len(branches) > 1 {
  370. break
  371. }
  372. commits = append(commits, commit)
  373. }
  374. return commits, nil
  375. }
  376. func (repo *Repository) getCommitsBefore(id ObjectID) ([]*Commit, error) {
  377. return repo.commitsBefore(id, 0)
  378. }
  379. func (repo *Repository) getCommitsBeforeLimit(id ObjectID, num int) ([]*Commit, error) {
  380. return repo.commitsBefore(id, num)
  381. }
  382. func (repo *Repository) getBranches(commit *Commit, limit int) ([]string, error) {
  383. if CheckGitVersionAtLeast("2.7.0") == nil {
  384. stdout, _, err := NewCommand(repo.Ctx, "for-each-ref", "--format=%(refname:strip=2)").
  385. AddOptionFormat("--count=%d", limit).
  386. AddOptionValues("--contains", commit.ID.String(), BranchPrefix).
  387. RunStdString(&RunOpts{Dir: repo.Path})
  388. if err != nil {
  389. return nil, err
  390. }
  391. branches := strings.Fields(stdout)
  392. return branches, nil
  393. }
  394. stdout, _, err := NewCommand(repo.Ctx, "branch").AddOptionValues("--contains", commit.ID.String()).RunStdString(&RunOpts{Dir: repo.Path})
  395. if err != nil {
  396. return nil, err
  397. }
  398. refs := strings.Split(stdout, "\n")
  399. var max int
  400. if len(refs) > limit {
  401. max = limit
  402. } else {
  403. max = len(refs) - 1
  404. }
  405. branches := make([]string, max)
  406. for i, ref := range refs[:max] {
  407. parts := strings.Fields(ref)
  408. branches[i] = parts[len(parts)-1]
  409. }
  410. return branches, nil
  411. }
  412. // GetCommitsFromIDs get commits from commit IDs
  413. func (repo *Repository) GetCommitsFromIDs(commitIDs []string) []*Commit {
  414. commits := make([]*Commit, 0, len(commitIDs))
  415. for _, commitID := range commitIDs {
  416. commit, err := repo.GetCommit(commitID)
  417. if err == nil && commit != nil {
  418. commits = append(commits, commit)
  419. }
  420. }
  421. return commits
  422. }
  423. // IsCommitInBranch check if the commit is on the branch
  424. func (repo *Repository) IsCommitInBranch(commitID, branch string) (r bool, err error) {
  425. stdout, _, err := NewCommand(repo.Ctx, "branch", "--contains").AddDynamicArguments(commitID, branch).RunStdString(&RunOpts{Dir: repo.Path})
  426. if err != nil {
  427. return false, err
  428. }
  429. return len(stdout) > 0, err
  430. }
  431. func (repo *Repository) AddLastCommitCache(cacheKey, fullName, sha string) error {
  432. if repo.LastCommitCache == nil {
  433. commitsCount, err := cache.GetInt64(cacheKey, func() (int64, error) {
  434. commit, err := repo.GetCommit(sha)
  435. if err != nil {
  436. return 0, err
  437. }
  438. return commit.CommitsCount()
  439. })
  440. if err != nil {
  441. return err
  442. }
  443. repo.LastCommitCache = NewLastCommitCache(commitsCount, fullName, repo, cache.GetCache())
  444. }
  445. return nil
  446. }