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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package git
  5. import (
  6. "bytes"
  7. "container/list"
  8. "strconv"
  9. "strings"
  10. "github.com/mcuadros/go-version"
  11. )
  12. // GetRefCommitID returns the last commit ID string of given reference (branch or tag).
  13. func (repo *Repository) GetRefCommitID(name string) (string, error) {
  14. stdout, err := NewCommand("show-ref", "--verify", name).RunInDir(repo.Path)
  15. if err != nil {
  16. if strings.Contains(err.Error(), "not a valid ref") {
  17. return "", ErrNotExist{name, ""}
  18. }
  19. return "", err
  20. }
  21. return strings.Split(stdout, " ")[0], nil
  22. }
  23. // GetBranchCommitID returns last commit ID string of given branch.
  24. func (repo *Repository) GetBranchCommitID(name string) (string, error) {
  25. return repo.GetRefCommitID(BranchPrefix + name)
  26. }
  27. // GetTagCommitID returns last commit ID string of given tag.
  28. func (repo *Repository) GetTagCommitID(name string) (string, error) {
  29. stdout, err := NewCommand("rev-list", "-n", "1", name).RunInDir(repo.Path)
  30. if err != nil {
  31. if strings.Contains(err.Error(), "unknown revision or path") {
  32. return "", ErrNotExist{name, ""}
  33. }
  34. return "", err
  35. }
  36. return strings.TrimSpace(stdout), nil
  37. }
  38. // parseCommitData parses commit information from the (uncompressed) raw
  39. // data from the commit object.
  40. // \n\n separate headers from message
  41. func parseCommitData(data []byte) (*Commit, error) {
  42. commit := new(Commit)
  43. commit.parents = make([]SHA1, 0, 1)
  44. // we now have the contents of the commit object. Let's investigate...
  45. nextline := 0
  46. l:
  47. for {
  48. eol := bytes.IndexByte(data[nextline:], '\n')
  49. switch {
  50. case eol > 0:
  51. line := data[nextline : nextline+eol]
  52. spacepos := bytes.IndexByte(line, ' ')
  53. reftype := line[:spacepos]
  54. switch string(reftype) {
  55. case "tree", "object":
  56. id, err := NewIDFromString(string(line[spacepos+1:]))
  57. if err != nil {
  58. return nil, err
  59. }
  60. commit.Tree.ID = id
  61. case "parent":
  62. // A commit can have one or more parents
  63. oid, err := NewIDFromString(string(line[spacepos+1:]))
  64. if err != nil {
  65. return nil, err
  66. }
  67. commit.parents = append(commit.parents, oid)
  68. case "author", "tagger":
  69. sig, err := newSignatureFromCommitline(line[spacepos+1:])
  70. if err != nil {
  71. return nil, err
  72. }
  73. commit.Author = sig
  74. case "committer":
  75. sig, err := newSignatureFromCommitline(line[spacepos+1:])
  76. if err != nil {
  77. return nil, err
  78. }
  79. commit.Committer = sig
  80. case "gpgsig":
  81. sig, err := newGPGSignatureFromCommitline(data, nextline+spacepos+1, false)
  82. if err != nil {
  83. return nil, err
  84. }
  85. commit.Signature = sig
  86. }
  87. nextline += eol + 1
  88. case eol == 0:
  89. cm := string(data[nextline+1:])
  90. // Tag GPG signatures are stored below the commit message
  91. sigindex := strings.Index(cm, "-----BEGIN PGP SIGNATURE-----")
  92. if sigindex != -1 {
  93. sig, err := newGPGSignatureFromCommitline(data, (nextline+1)+sigindex, true)
  94. if err == nil && sig != nil {
  95. // remove signature from commit message
  96. if sigindex == 0 {
  97. cm = ""
  98. } else {
  99. cm = cm[:sigindex-1]
  100. }
  101. commit.Signature = sig
  102. }
  103. }
  104. commit.CommitMessage = cm
  105. break l
  106. default:
  107. break l
  108. }
  109. }
  110. return commit, nil
  111. }
  112. func (repo *Repository) getCommit(id SHA1) (*Commit, error) {
  113. c, ok := repo.commitCache.Get(id.String())
  114. if ok {
  115. log("Hit cache: %s", id)
  116. return c.(*Commit), nil
  117. }
  118. data, err := NewCommand("cat-file", "-p", id.String()).RunInDirBytes(repo.Path)
  119. if err != nil {
  120. if strings.Contains(err.Error(), "fatal: Not a valid object name") {
  121. return nil, ErrNotExist{id.String(), ""}
  122. }
  123. return nil, err
  124. }
  125. commit, err := parseCommitData(data)
  126. if err != nil {
  127. return nil, err
  128. }
  129. commit.repo = repo
  130. commit.ID = id
  131. data, err = NewCommand("name-rev", id.String()).RunInDirBytes(repo.Path)
  132. if err != nil {
  133. return nil, err
  134. }
  135. // name-rev commitID output will be "COMMIT_ID master" or "COMMIT_ID master~12"
  136. commit.Branch = strings.Split(strings.Split(string(data), " ")[1], "~")[0]
  137. repo.commitCache.Set(id.String(), commit)
  138. return commit, nil
  139. }
  140. // GetCommit returns commit object of by ID string.
  141. func (repo *Repository) GetCommit(commitID string) (*Commit, error) {
  142. if len(commitID) != 40 {
  143. var err error
  144. actualCommitID, err := NewCommand("rev-parse", commitID).RunInDir(repo.Path)
  145. if err != nil {
  146. if strings.Contains(err.Error(), "unknown revision or path") {
  147. return nil, ErrNotExist{commitID, ""}
  148. }
  149. return nil, err
  150. }
  151. commitID = actualCommitID
  152. }
  153. id, err := NewIDFromString(commitID)
  154. if err != nil {
  155. return nil, err
  156. }
  157. return repo.getCommit(id)
  158. }
  159. // GetBranchCommit returns the last commit of given branch.
  160. func (repo *Repository) GetBranchCommit(name string) (*Commit, error) {
  161. commitID, err := repo.GetBranchCommitID(name)
  162. if err != nil {
  163. return nil, err
  164. }
  165. return repo.GetCommit(commitID)
  166. }
  167. // GetTagCommit get the commit of the specific tag via name
  168. func (repo *Repository) GetTagCommit(name string) (*Commit, error) {
  169. commitID, err := repo.GetTagCommitID(name)
  170. if err != nil {
  171. return nil, err
  172. }
  173. return repo.GetCommit(commitID)
  174. }
  175. func (repo *Repository) getCommitByPathWithID(id SHA1, relpath string) (*Commit, error) {
  176. // File name starts with ':' must be escaped.
  177. if relpath[0] == ':' {
  178. relpath = `\` + relpath
  179. }
  180. stdout, err := NewCommand("log", "-1", prettyLogFormat, id.String(), "--", relpath).RunInDir(repo.Path)
  181. if err != nil {
  182. return nil, err
  183. }
  184. id, err = NewIDFromString(stdout)
  185. if err != nil {
  186. return nil, err
  187. }
  188. return repo.getCommit(id)
  189. }
  190. // GetCommitByPath returns the last commit of relative path.
  191. func (repo *Repository) GetCommitByPath(relpath string) (*Commit, error) {
  192. stdout, err := NewCommand("log", "-1", prettyLogFormat, "--", relpath).RunInDirBytes(repo.Path)
  193. if err != nil {
  194. return nil, err
  195. }
  196. commits, err := repo.parsePrettyFormatLogToList(stdout)
  197. if err != nil {
  198. return nil, err
  199. }
  200. return commits.Front().Value.(*Commit), nil
  201. }
  202. // CommitsRangeSize the default commits range size
  203. var CommitsRangeSize = 50
  204. func (repo *Repository) commitsByRange(id SHA1, page int) (*list.List, error) {
  205. stdout, err := NewCommand("log", id.String(), "--skip="+strconv.Itoa((page-1)*CommitsRangeSize),
  206. "--max-count="+strconv.Itoa(CommitsRangeSize), prettyLogFormat).RunInDirBytes(repo.Path)
  207. if err != nil {
  208. return nil, err
  209. }
  210. return repo.parsePrettyFormatLogToList(stdout)
  211. }
  212. func (repo *Repository) searchCommits(id SHA1, opts SearchCommitsOptions) (*list.List, error) {
  213. cmd := NewCommand("log", id.String(), "-100", "-i", prettyLogFormat)
  214. if len(opts.Keywords) > 0 {
  215. for _, v := range opts.Keywords {
  216. cmd.AddArguments("--grep=" + v)
  217. }
  218. }
  219. if len(opts.Authors) > 0 {
  220. for _, v := range opts.Authors {
  221. cmd.AddArguments("--author=" + v)
  222. }
  223. }
  224. if len(opts.Committers) > 0 {
  225. for _, v := range opts.Committers {
  226. cmd.AddArguments("--committer=" + v)
  227. }
  228. }
  229. if len(opts.After) > 0 {
  230. cmd.AddArguments("--after=" + opts.After)
  231. }
  232. if len(opts.Before) > 0 {
  233. cmd.AddArguments("--before=" + opts.Before)
  234. }
  235. if opts.All {
  236. cmd.AddArguments("--all")
  237. }
  238. stdout, err := cmd.RunInDirBytes(repo.Path)
  239. if err != nil {
  240. return nil, err
  241. }
  242. return repo.parsePrettyFormatLogToList(stdout)
  243. }
  244. func (repo *Repository) getFilesChanged(id1, id2 string) ([]string, error) {
  245. stdout, err := NewCommand("diff", "--name-only", id1, id2).RunInDirBytes(repo.Path)
  246. if err != nil {
  247. return nil, err
  248. }
  249. return strings.Split(string(stdout), "\n"), nil
  250. }
  251. // FileChangedBetweenCommits Returns true if the file changed between commit IDs id1 and id2
  252. func (repo *Repository) FileChangedBetweenCommits(filename, id1, id2 string) (bool, error) {
  253. stdout, err := NewCommand("diff", "--name-only", "-z", id1, id2, "--", filename).RunInDirBytes(repo.Path)
  254. if err != nil {
  255. return false, err
  256. }
  257. return len(strings.TrimSpace(string(stdout))) > 0, nil
  258. }
  259. // FileCommitsCount return the number of files at a revison
  260. func (repo *Repository) FileCommitsCount(revision, file string) (int64, error) {
  261. return commitsCount(repo.Path, revision, file)
  262. }
  263. // CommitsByFileAndRange return the commits according revison file and the page
  264. func (repo *Repository) CommitsByFileAndRange(revision, file string, page int) (*list.List, error) {
  265. stdout, err := NewCommand("log", revision, "--follow", "--skip="+strconv.Itoa((page-1)*50),
  266. "--max-count="+strconv.Itoa(CommitsRangeSize), prettyLogFormat, "--", file).RunInDirBytes(repo.Path)
  267. if err != nil {
  268. return nil, err
  269. }
  270. return repo.parsePrettyFormatLogToList(stdout)
  271. }
  272. // FilesCountBetween return the number of files changed between two commits
  273. func (repo *Repository) FilesCountBetween(startCommitID, endCommitID string) (int, error) {
  274. stdout, err := NewCommand("diff", "--name-only", startCommitID+"..."+endCommitID).RunInDir(repo.Path)
  275. if err != nil {
  276. return 0, err
  277. }
  278. return len(strings.Split(stdout, "\n")) - 1, nil
  279. }
  280. // CommitsBetween returns a list that contains commits between [last, before).
  281. func (repo *Repository) CommitsBetween(last *Commit, before *Commit) (*list.List, error) {
  282. stdout, err := NewCommand("rev-list", before.ID.String()+"..."+last.ID.String()).RunInDirBytes(repo.Path)
  283. if err != nil {
  284. return nil, err
  285. }
  286. return repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout))
  287. }
  288. // CommitsBetweenIDs return commits between twoe commits
  289. func (repo *Repository) CommitsBetweenIDs(last, before string) (*list.List, error) {
  290. lastCommit, err := repo.GetCommit(last)
  291. if err != nil {
  292. return nil, err
  293. }
  294. beforeCommit, err := repo.GetCommit(before)
  295. if err != nil {
  296. return nil, err
  297. }
  298. return repo.CommitsBetween(lastCommit, beforeCommit)
  299. }
  300. // CommitsCountBetween return numbers of commits between two commits
  301. func (repo *Repository) CommitsCountBetween(start, end string) (int64, error) {
  302. return commitsCount(repo.Path, start+"..."+end, "")
  303. }
  304. // commitsBefore the limit is depth, not total number of returned commits.
  305. func (repo *Repository) commitsBefore(id SHA1, limit int) (*list.List, error) {
  306. cmd := NewCommand("log")
  307. if limit > 0 {
  308. cmd.AddArguments("-"+strconv.Itoa(limit), prettyLogFormat, id.String())
  309. } else {
  310. cmd.AddArguments(prettyLogFormat, id.String())
  311. }
  312. stdout, err := cmd.RunInDirBytes(repo.Path)
  313. if err != nil {
  314. return nil, err
  315. }
  316. formattedLog, err := repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout))
  317. if err != nil {
  318. return nil, err
  319. }
  320. commits := list.New()
  321. for logEntry := formattedLog.Front(); logEntry != nil; logEntry = logEntry.Next() {
  322. commit := logEntry.Value.(*Commit)
  323. branches, err := repo.getBranches(commit, 2)
  324. if err != nil {
  325. return nil, err
  326. }
  327. if len(branches) > 1 {
  328. break
  329. }
  330. commits.PushBack(commit)
  331. }
  332. return commits, nil
  333. }
  334. func (repo *Repository) getCommitsBefore(id SHA1) (*list.List, error) {
  335. return repo.commitsBefore(id, 0)
  336. }
  337. func (repo *Repository) getCommitsBeforeLimit(id SHA1, num int) (*list.List, error) {
  338. return repo.commitsBefore(id, num)
  339. }
  340. func (repo *Repository) getBranches(commit *Commit, limit int) ([]string, error) {
  341. if version.Compare(gitVersion, "2.7.0", ">=") {
  342. stdout, err := NewCommand("for-each-ref", "--count="+strconv.Itoa(limit), "--format=%(refname:strip=2)", "--contains", commit.ID.String(), BranchPrefix).RunInDir(repo.Path)
  343. if err != nil {
  344. return nil, err
  345. }
  346. branches := strings.Fields(stdout)
  347. return branches, nil
  348. }
  349. stdout, err := NewCommand("branch", "--contains", commit.ID.String()).RunInDir(repo.Path)
  350. if err != nil {
  351. return nil, err
  352. }
  353. refs := strings.Split(stdout, "\n")
  354. var max int
  355. if len(refs) > limit {
  356. max = limit
  357. } else {
  358. max = len(refs) - 1
  359. }
  360. branches := make([]string, max)
  361. for i, ref := range refs[:max] {
  362. parts := strings.Fields(ref)
  363. branches[i] = parts[len(parts)-1]
  364. }
  365. return branches, nil
  366. }