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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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. // ConvertToSHA1 returns a Hash object from a potential ID string
  98. func (repo *Repository) ConvertToSHA1(commitID string) (SHA1, error) {
  99. if len(commitID) != 40 {
  100. var err error
  101. actualCommitID, err := NewCommand("rev-parse", "--verify", commitID).RunInDir(repo.Path)
  102. if err != nil {
  103. if strings.Contains(err.Error(), "unknown revision or path") ||
  104. strings.Contains(err.Error(), "fatal: Needed a single revision") {
  105. return SHA1{}, ErrNotExist{commitID, ""}
  106. }
  107. return SHA1{}, err
  108. }
  109. commitID = actualCommitID
  110. }
  111. return NewIDFromString(commitID)
  112. }
  113. // GetCommit returns commit object of by ID string.
  114. func (repo *Repository) GetCommit(commitID string) (*Commit, error) {
  115. id, err := repo.ConvertToSHA1(commitID)
  116. if err != nil {
  117. return nil, err
  118. }
  119. return repo.getCommit(id)
  120. }
  121. // GetBranchCommit returns the last commit of given branch.
  122. func (repo *Repository) GetBranchCommit(name string) (*Commit, error) {
  123. commitID, err := repo.GetBranchCommitID(name)
  124. if err != nil {
  125. return nil, err
  126. }
  127. return repo.GetCommit(commitID)
  128. }
  129. // GetTagCommit get the commit of the specific tag via name
  130. func (repo *Repository) GetTagCommit(name string) (*Commit, error) {
  131. commitID, err := repo.GetTagCommitID(name)
  132. if err != nil {
  133. return nil, err
  134. }
  135. return repo.GetCommit(commitID)
  136. }
  137. func (repo *Repository) getCommitByPathWithID(id SHA1, relpath string) (*Commit, error) {
  138. // File name starts with ':' must be escaped.
  139. if relpath[0] == ':' {
  140. relpath = `\` + relpath
  141. }
  142. stdout, err := NewCommand("log", "-1", prettyLogFormat, id.String(), "--", relpath).RunInDir(repo.Path)
  143. if err != nil {
  144. return nil, err
  145. }
  146. id, err = NewIDFromString(stdout)
  147. if err != nil {
  148. return nil, err
  149. }
  150. return repo.getCommit(id)
  151. }
  152. // GetCommitByPath returns the last commit of relative path.
  153. func (repo *Repository) GetCommitByPath(relpath string) (*Commit, error) {
  154. stdout, err := NewCommand("log", "-1", prettyLogFormat, "--", relpath).RunInDirBytes(repo.Path)
  155. if err != nil {
  156. return nil, err
  157. }
  158. commits, err := repo.parsePrettyFormatLogToList(stdout)
  159. if err != nil {
  160. return nil, err
  161. }
  162. return commits.Front().Value.(*Commit), nil
  163. }
  164. // CommitsRangeSize the default commits range size
  165. var CommitsRangeSize = 50
  166. func (repo *Repository) commitsByRange(id SHA1, page int) (*list.List, error) {
  167. stdout, err := NewCommand("log", id.String(), "--skip="+strconv.Itoa((page-1)*CommitsRangeSize),
  168. "--max-count="+strconv.Itoa(CommitsRangeSize), prettyLogFormat).RunInDirBytes(repo.Path)
  169. if err != nil {
  170. return nil, err
  171. }
  172. return repo.parsePrettyFormatLogToList(stdout)
  173. }
  174. func (repo *Repository) searchCommits(id SHA1, opts SearchCommitsOptions) (*list.List, error) {
  175. cmd := NewCommand("log", id.String(), "-100", "-i", prettyLogFormat)
  176. if len(opts.Keywords) > 0 {
  177. for _, v := range opts.Keywords {
  178. cmd.AddArguments("--grep=" + v)
  179. }
  180. }
  181. if len(opts.Authors) > 0 {
  182. for _, v := range opts.Authors {
  183. cmd.AddArguments("--author=" + v)
  184. }
  185. }
  186. if len(opts.Committers) > 0 {
  187. for _, v := range opts.Committers {
  188. cmd.AddArguments("--committer=" + v)
  189. }
  190. }
  191. if len(opts.After) > 0 {
  192. cmd.AddArguments("--after=" + opts.After)
  193. }
  194. if len(opts.Before) > 0 {
  195. cmd.AddArguments("--before=" + opts.Before)
  196. }
  197. if opts.All {
  198. cmd.AddArguments("--all")
  199. }
  200. stdout, err := cmd.RunInDirBytes(repo.Path)
  201. if err != nil {
  202. return nil, err
  203. }
  204. return repo.parsePrettyFormatLogToList(stdout)
  205. }
  206. func (repo *Repository) getFilesChanged(id1, id2 string) ([]string, error) {
  207. stdout, err := NewCommand("diff", "--name-only", id1, id2).RunInDirBytes(repo.Path)
  208. if err != nil {
  209. return nil, err
  210. }
  211. return strings.Split(string(stdout), "\n"), nil
  212. }
  213. // FileChangedBetweenCommits Returns true if the file changed between commit IDs id1 and id2
  214. // You must ensure that id1 and id2 are valid commit ids.
  215. func (repo *Repository) FileChangedBetweenCommits(filename, id1, id2 string) (bool, error) {
  216. stdout, err := NewCommand("diff", "--name-only", "-z", id1, id2, "--", filename).RunInDirBytes(repo.Path)
  217. if err != nil {
  218. return false, err
  219. }
  220. return len(strings.TrimSpace(string(stdout))) > 0, nil
  221. }
  222. // FileCommitsCount return the number of files at a revison
  223. func (repo *Repository) FileCommitsCount(revision, file string) (int64, error) {
  224. return commitsCount(repo.Path, revision, file)
  225. }
  226. // CommitsByFileAndRange return the commits according revison file and the page
  227. func (repo *Repository) CommitsByFileAndRange(revision, file string, page int) (*list.List, error) {
  228. stdout, err := NewCommand("log", revision, "--follow", "--skip="+strconv.Itoa((page-1)*50),
  229. "--max-count="+strconv.Itoa(CommitsRangeSize), prettyLogFormat, "--", file).RunInDirBytes(repo.Path)
  230. if err != nil {
  231. return nil, err
  232. }
  233. return repo.parsePrettyFormatLogToList(stdout)
  234. }
  235. // FilesCountBetween return the number of files changed between two commits
  236. func (repo *Repository) FilesCountBetween(startCommitID, endCommitID string) (int, error) {
  237. stdout, err := NewCommand("diff", "--name-only", startCommitID+"..."+endCommitID).RunInDir(repo.Path)
  238. if err != nil {
  239. return 0, err
  240. }
  241. return len(strings.Split(stdout, "\n")) - 1, nil
  242. }
  243. // CommitsBetween returns a list that contains commits between [last, before).
  244. func (repo *Repository) CommitsBetween(last *Commit, before *Commit) (*list.List, error) {
  245. stdout, err := NewCommand("rev-list", before.ID.String()+"..."+last.ID.String()).RunInDirBytes(repo.Path)
  246. if err != nil {
  247. return nil, err
  248. }
  249. return repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout))
  250. }
  251. // CommitsBetweenIDs return commits between twoe commits
  252. func (repo *Repository) CommitsBetweenIDs(last, before string) (*list.List, error) {
  253. lastCommit, err := repo.GetCommit(last)
  254. if err != nil {
  255. return nil, err
  256. }
  257. beforeCommit, err := repo.GetCommit(before)
  258. if err != nil {
  259. return nil, err
  260. }
  261. return repo.CommitsBetween(lastCommit, beforeCommit)
  262. }
  263. // CommitsCountBetween return numbers of commits between two commits
  264. func (repo *Repository) CommitsCountBetween(start, end string) (int64, error) {
  265. return commitsCount(repo.Path, start+"..."+end, "")
  266. }
  267. // commitsBefore the limit is depth, not total number of returned commits.
  268. func (repo *Repository) commitsBefore(id SHA1, limit int) (*list.List, error) {
  269. cmd := NewCommand("log")
  270. if limit > 0 {
  271. cmd.AddArguments("-"+strconv.Itoa(limit), prettyLogFormat, id.String())
  272. } else {
  273. cmd.AddArguments(prettyLogFormat, id.String())
  274. }
  275. stdout, err := cmd.RunInDirBytes(repo.Path)
  276. if err != nil {
  277. return nil, err
  278. }
  279. formattedLog, err := repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout))
  280. if err != nil {
  281. return nil, err
  282. }
  283. commits := list.New()
  284. for logEntry := formattedLog.Front(); logEntry != nil; logEntry = logEntry.Next() {
  285. commit := logEntry.Value.(*Commit)
  286. branches, err := repo.getBranches(commit, 2)
  287. if err != nil {
  288. return nil, err
  289. }
  290. if len(branches) > 1 {
  291. break
  292. }
  293. commits.PushBack(commit)
  294. }
  295. return commits, nil
  296. }
  297. func (repo *Repository) getCommitsBefore(id SHA1) (*list.List, error) {
  298. return repo.commitsBefore(id, 0)
  299. }
  300. func (repo *Repository) getCommitsBeforeLimit(id SHA1, num int) (*list.List, error) {
  301. return repo.commitsBefore(id, num)
  302. }
  303. func (repo *Repository) getBranches(commit *Commit, limit int) ([]string, error) {
  304. if version.Compare(gitVersion, "2.7.0", ">=") {
  305. stdout, err := NewCommand("for-each-ref", "--count="+strconv.Itoa(limit), "--format=%(refname:strip=2)", "--contains", commit.ID.String(), BranchPrefix).RunInDir(repo.Path)
  306. if err != nil {
  307. return nil, err
  308. }
  309. branches := strings.Fields(stdout)
  310. return branches, nil
  311. }
  312. stdout, err := NewCommand("branch", "--contains", commit.ID.String()).RunInDir(repo.Path)
  313. if err != nil {
  314. return nil, err
  315. }
  316. refs := strings.Split(stdout, "\n")
  317. var max int
  318. if len(refs) > limit {
  319. max = limit
  320. } else {
  321. max = len(refs) - 1
  322. }
  323. branches := make([]string, max)
  324. for i, ref := range refs[:max] {
  325. parts := strings.Fields(ref)
  326. branches[i] = parts[len(parts)-1]
  327. }
  328. return branches, nil
  329. }