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

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