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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 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. "container/list"
  9. "fmt"
  10. "strconv"
  11. "strings"
  12. "github.com/mcuadros/go-version"
  13. "gopkg.in/src-d/go-git.v4/plumbing"
  14. "gopkg.in/src-d/go-git.v4/plumbing/object"
  15. )
  16. // GetRefCommitID returns the last commit ID string of given reference (branch or tag).
  17. func (repo *Repository) GetRefCommitID(name string) (string, error) {
  18. ref, err := repo.gogitRepo.Reference(plumbing.ReferenceName(name), true)
  19. if err != nil {
  20. if err == plumbing.ErrReferenceNotFound {
  21. return "", ErrNotExist{
  22. ID: name,
  23. }
  24. }
  25. return "", err
  26. }
  27. return ref.Hash().String(), nil
  28. }
  29. // IsCommitExist returns true if given commit exists in current repository.
  30. func (repo *Repository) IsCommitExist(name string) bool {
  31. hash := plumbing.NewHash(name)
  32. _, err := repo.gogitRepo.CommitObject(hash)
  33. return err == nil
  34. }
  35. // GetBranchCommitID returns last commit ID string of given branch.
  36. func (repo *Repository) GetBranchCommitID(name string) (string, error) {
  37. return repo.GetRefCommitID(BranchPrefix + name)
  38. }
  39. // GetTagCommitID returns last commit ID string of given tag.
  40. func (repo *Repository) GetTagCommitID(name string) (string, error) {
  41. stdout, err := NewCommand("rev-list", "-n", "1", name).RunInDir(repo.Path)
  42. if err != nil {
  43. if strings.Contains(err.Error(), "unknown revision or path") {
  44. return "", ErrNotExist{name, ""}
  45. }
  46. return "", err
  47. }
  48. return strings.TrimSpace(stdout), nil
  49. }
  50. func convertPGPSignatureForTag(t *object.Tag) *CommitGPGSignature {
  51. if t.PGPSignature == "" {
  52. return nil
  53. }
  54. var w strings.Builder
  55. var err error
  56. if _, err = fmt.Fprintf(&w,
  57. "object %s\ntype %s\ntag %s\ntagger ",
  58. t.Target.String(), t.TargetType.Bytes(), t.Name); err != nil {
  59. return nil
  60. }
  61. if err = t.Tagger.Encode(&w); err != nil {
  62. return nil
  63. }
  64. if _, err = fmt.Fprintf(&w, "\n\n"); err != nil {
  65. return nil
  66. }
  67. if _, err = fmt.Fprintf(&w, t.Message); err != nil {
  68. return nil
  69. }
  70. return &CommitGPGSignature{
  71. Signature: t.PGPSignature,
  72. Payload: strings.TrimSpace(w.String()) + "\n",
  73. }
  74. }
  75. func (repo *Repository) getCommit(id SHA1) (*Commit, error) {
  76. var tagObject *object.Tag
  77. gogitCommit, err := repo.gogitRepo.CommitObject(id)
  78. if err == plumbing.ErrObjectNotFound {
  79. tagObject, err = repo.gogitRepo.TagObject(id)
  80. if err == nil {
  81. gogitCommit, err = repo.gogitRepo.CommitObject(tagObject.Target)
  82. }
  83. }
  84. if err != nil {
  85. return nil, err
  86. }
  87. commit := convertCommit(gogitCommit)
  88. commit.repo = repo
  89. if tagObject != nil {
  90. commit.CommitMessage = strings.TrimSpace(tagObject.Message)
  91. commit.Author = &tagObject.Tagger
  92. commit.Signature = convertPGPSignatureForTag(tagObject)
  93. }
  94. tree, err := gogitCommit.Tree()
  95. if err != nil {
  96. return nil, err
  97. }
  98. commit.Tree.ID = tree.Hash
  99. commit.Tree.gogitTree = tree
  100. return commit, nil
  101. }
  102. // ConvertToSHA1 returns a Hash object from a potential ID string
  103. func (repo *Repository) ConvertToSHA1(commitID string) (SHA1, error) {
  104. if len(commitID) != 40 {
  105. var err error
  106. actualCommitID, err := NewCommand("rev-parse", "--verify", commitID).RunInDir(repo.Path)
  107. if err != nil {
  108. if strings.Contains(err.Error(), "unknown revision or path") ||
  109. strings.Contains(err.Error(), "fatal: Needed a single revision") {
  110. return SHA1{}, ErrNotExist{commitID, ""}
  111. }
  112. return SHA1{}, err
  113. }
  114. commitID = actualCommitID
  115. }
  116. return NewIDFromString(commitID)
  117. }
  118. // GetCommit returns commit object of by ID string.
  119. func (repo *Repository) GetCommit(commitID string) (*Commit, error) {
  120. id, err := repo.ConvertToSHA1(commitID)
  121. if err != nil {
  122. return nil, err
  123. }
  124. return repo.getCommit(id)
  125. }
  126. // GetBranchCommit returns the last commit of given branch.
  127. func (repo *Repository) GetBranchCommit(name string) (*Commit, error) {
  128. commitID, err := repo.GetBranchCommitID(name)
  129. if err != nil {
  130. return nil, err
  131. }
  132. return repo.GetCommit(commitID)
  133. }
  134. // GetTagCommit get the commit of the specific tag via name
  135. func (repo *Repository) GetTagCommit(name string) (*Commit, error) {
  136. commitID, err := repo.GetTagCommitID(name)
  137. if err != nil {
  138. return nil, err
  139. }
  140. return repo.GetCommit(commitID)
  141. }
  142. func (repo *Repository) getCommitByPathWithID(id SHA1, relpath string) (*Commit, error) {
  143. // File name starts with ':' must be escaped.
  144. if relpath[0] == ':' {
  145. relpath = `\` + relpath
  146. }
  147. stdout, err := NewCommand("log", "-1", prettyLogFormat, id.String(), "--", relpath).RunInDir(repo.Path)
  148. if err != nil {
  149. return nil, err
  150. }
  151. id, err = NewIDFromString(stdout)
  152. if err != nil {
  153. return nil, err
  154. }
  155. return repo.getCommit(id)
  156. }
  157. // GetCommitByPath returns the last commit of relative path.
  158. func (repo *Repository) GetCommitByPath(relpath string) (*Commit, error) {
  159. stdout, err := NewCommand("log", "-1", prettyLogFormat, "--", relpath).RunInDirBytes(repo.Path)
  160. if err != nil {
  161. return nil, err
  162. }
  163. commits, err := repo.parsePrettyFormatLogToList(stdout)
  164. if err != nil {
  165. return nil, err
  166. }
  167. return commits.Front().Value.(*Commit), nil
  168. }
  169. // CommitsRangeSize the default commits range size
  170. var CommitsRangeSize = 50
  171. func (repo *Repository) commitsByRange(id SHA1, page, pageSize int) (*list.List, error) {
  172. stdout, err := NewCommand("log", id.String(), "--skip="+strconv.Itoa((page-1)*pageSize),
  173. "--max-count="+strconv.Itoa(pageSize), prettyLogFormat).RunInDirBytes(repo.Path)
  174. if err != nil {
  175. return nil, err
  176. }
  177. return repo.parsePrettyFormatLogToList(stdout)
  178. }
  179. func (repo *Repository) searchCommits(id SHA1, opts SearchCommitsOptions) (*list.List, error) {
  180. cmd := NewCommand("log", id.String(), "-100", prettyLogFormat)
  181. args := []string{"-i"}
  182. if len(opts.Authors) > 0 {
  183. for _, v := range opts.Authors {
  184. args = append(args, "--author="+v)
  185. }
  186. }
  187. if len(opts.Committers) > 0 {
  188. for _, v := range opts.Committers {
  189. args = append(args, "--committer="+v)
  190. }
  191. }
  192. if len(opts.After) > 0 {
  193. args = append(args, "--after="+opts.After)
  194. }
  195. if len(opts.Before) > 0 {
  196. args = append(args, "--before="+opts.Before)
  197. }
  198. if opts.All {
  199. args = append(args, "--all")
  200. }
  201. if len(opts.Keywords) > 0 {
  202. for _, v := range opts.Keywords {
  203. cmd.AddArguments("--grep=" + v)
  204. }
  205. }
  206. cmd.AddArguments(args...)
  207. stdout, err := cmd.RunInDirBytes(repo.Path)
  208. if err != nil {
  209. return nil, err
  210. }
  211. if len(stdout) != 0 {
  212. stdout = append(stdout, '\n')
  213. }
  214. if len(opts.Keywords) > 0 {
  215. for _, v := range opts.Keywords {
  216. if len(v) >= 4 {
  217. hashCmd := NewCommand("log", "-1", prettyLogFormat)
  218. hashCmd.AddArguments(args...)
  219. hashCmd.AddArguments(v)
  220. hashMatching, err := hashCmd.RunInDirBytes(repo.Path)
  221. if err != nil || bytes.Contains(stdout, hashMatching) {
  222. continue
  223. }
  224. stdout = append(stdout, hashMatching...)
  225. stdout = append(stdout, '\n')
  226. }
  227. }
  228. }
  229. return repo.parsePrettyFormatLogToList(bytes.TrimSuffix(stdout, []byte{'\n'}))
  230. }
  231. func (repo *Repository) getFilesChanged(id1, id2 string) ([]string, error) {
  232. stdout, err := NewCommand("diff", "--name-only", id1, id2).RunInDirBytes(repo.Path)
  233. if err != nil {
  234. return nil, err
  235. }
  236. return strings.Split(string(stdout), "\n"), nil
  237. }
  238. // FileChangedBetweenCommits Returns true if the file changed between commit IDs id1 and id2
  239. // You must ensure that id1 and id2 are valid commit ids.
  240. func (repo *Repository) FileChangedBetweenCommits(filename, id1, id2 string) (bool, error) {
  241. stdout, err := NewCommand("diff", "--name-only", "-z", id1, id2, "--", filename).RunInDirBytes(repo.Path)
  242. if err != nil {
  243. return false, err
  244. }
  245. return len(strings.TrimSpace(string(stdout))) > 0, nil
  246. }
  247. // FileCommitsCount return the number of files at a revison
  248. func (repo *Repository) FileCommitsCount(revision, file string) (int64, error) {
  249. return commitsCount(repo.Path, revision, file)
  250. }
  251. // CommitsByFileAndRange return the commits according revison file and the page
  252. func (repo *Repository) CommitsByFileAndRange(revision, file string, page int) (*list.List, error) {
  253. stdout, err := NewCommand("log", revision, "--follow", "--skip="+strconv.Itoa((page-1)*50),
  254. "--max-count="+strconv.Itoa(CommitsRangeSize), prettyLogFormat, "--", file).RunInDirBytes(repo.Path)
  255. if err != nil {
  256. return nil, err
  257. }
  258. return repo.parsePrettyFormatLogToList(stdout)
  259. }
  260. // CommitsByFileAndRangeNoFollow return the commits according revison file and the page
  261. func (repo *Repository) CommitsByFileAndRangeNoFollow(revision, file string, page int) (*list.List, error) {
  262. stdout, err := NewCommand("log", revision, "--skip="+strconv.Itoa((page-1)*50),
  263. "--max-count="+strconv.Itoa(CommitsRangeSize), prettyLogFormat, "--", file).RunInDirBytes(repo.Path)
  264. if err != nil {
  265. return nil, err
  266. }
  267. return repo.parsePrettyFormatLogToList(stdout)
  268. }
  269. // FilesCountBetween return the number of files changed between two commits
  270. func (repo *Repository) FilesCountBetween(startCommitID, endCommitID string) (int, error) {
  271. stdout, err := NewCommand("diff", "--name-only", startCommitID+"..."+endCommitID).RunInDir(repo.Path)
  272. if err != nil {
  273. return 0, err
  274. }
  275. return len(strings.Split(stdout, "\n")) - 1, nil
  276. }
  277. // CommitsBetween returns a list that contains commits between [last, before).
  278. func (repo *Repository) CommitsBetween(last *Commit, before *Commit) (*list.List, error) {
  279. var stdout []byte
  280. var err error
  281. if before == nil {
  282. stdout, err = NewCommand("rev-list", last.ID.String()).RunInDirBytes(repo.Path)
  283. } else {
  284. stdout, err = NewCommand("rev-list", before.ID.String()+"..."+last.ID.String()).RunInDirBytes(repo.Path)
  285. }
  286. if err != nil {
  287. return nil, err
  288. }
  289. return repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout))
  290. }
  291. // CommitsBetweenLimit returns a list that contains at most limit commits skipping the first skip commits between [last, before)
  292. func (repo *Repository) CommitsBetweenLimit(last *Commit, before *Commit, limit, skip int) (*list.List, error) {
  293. var stdout []byte
  294. var err error
  295. if before == nil {
  296. stdout, err = NewCommand("rev-list", "--max-count", strconv.Itoa(limit), "--skip", strconv.Itoa(skip), last.ID.String()).RunInDirBytes(repo.Path)
  297. } else {
  298. stdout, err = NewCommand("rev-list", "--max-count", strconv.Itoa(limit), "--skip", strconv.Itoa(skip), before.ID.String()+"..."+last.ID.String()).RunInDirBytes(repo.Path)
  299. }
  300. if err != nil {
  301. return nil, err
  302. }
  303. return repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout))
  304. }
  305. // CommitsBetweenIDs return commits between twoe commits
  306. func (repo *Repository) CommitsBetweenIDs(last, before string) (*list.List, error) {
  307. lastCommit, err := repo.GetCommit(last)
  308. if err != nil {
  309. return nil, err
  310. }
  311. if before == "" {
  312. return repo.CommitsBetween(lastCommit, nil)
  313. }
  314. beforeCommit, err := repo.GetCommit(before)
  315. if err != nil {
  316. return nil, err
  317. }
  318. return repo.CommitsBetween(lastCommit, beforeCommit)
  319. }
  320. // CommitsCountBetween return numbers of commits between two commits
  321. func (repo *Repository) CommitsCountBetween(start, end string) (int64, error) {
  322. return commitsCount(repo.Path, start+"..."+end, "")
  323. }
  324. // commitsBefore the limit is depth, not total number of returned commits.
  325. func (repo *Repository) commitsBefore(id SHA1, limit int) (*list.List, error) {
  326. cmd := NewCommand("log")
  327. if limit > 0 {
  328. cmd.AddArguments("-"+strconv.Itoa(limit), prettyLogFormat, id.String())
  329. } else {
  330. cmd.AddArguments(prettyLogFormat, id.String())
  331. }
  332. stdout, err := cmd.RunInDirBytes(repo.Path)
  333. if err != nil {
  334. return nil, err
  335. }
  336. formattedLog, err := repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout))
  337. if err != nil {
  338. return nil, err
  339. }
  340. commits := list.New()
  341. for logEntry := formattedLog.Front(); logEntry != nil; logEntry = logEntry.Next() {
  342. commit := logEntry.Value.(*Commit)
  343. branches, err := repo.getBranches(commit, 2)
  344. if err != nil {
  345. return nil, err
  346. }
  347. if len(branches) > 1 {
  348. break
  349. }
  350. commits.PushBack(commit)
  351. }
  352. return commits, nil
  353. }
  354. func (repo *Repository) getCommitsBefore(id SHA1) (*list.List, error) {
  355. return repo.commitsBefore(id, 0)
  356. }
  357. func (repo *Repository) getCommitsBeforeLimit(id SHA1, num int) (*list.List, error) {
  358. return repo.commitsBefore(id, num)
  359. }
  360. func (repo *Repository) getBranches(commit *Commit, limit int) ([]string, error) {
  361. if version.Compare(gitVersion, "2.7.0", ">=") {
  362. stdout, err := NewCommand("for-each-ref", "--count="+strconv.Itoa(limit), "--format=%(refname:strip=2)", "--contains", commit.ID.String(), BranchPrefix).RunInDir(repo.Path)
  363. if err != nil {
  364. return nil, err
  365. }
  366. branches := strings.Fields(stdout)
  367. return branches, nil
  368. }
  369. stdout, err := NewCommand("branch", "--contains", commit.ID.String()).RunInDir(repo.Path)
  370. if err != nil {
  371. return nil, err
  372. }
  373. refs := strings.Split(stdout, "\n")
  374. var max int
  375. if len(refs) > limit {
  376. max = limit
  377. } else {
  378. max = len(refs) - 1
  379. }
  380. branches := make([]string, max)
  381. for i, ref := range refs[:max] {
  382. parts := strings.Fields(ref)
  383. branches[i] = parts[len(parts)-1]
  384. }
  385. return branches, nil
  386. }