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

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