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

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