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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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. version "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 string, 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. // FileCommitsCount return the number of files at a revison
  252. func (repo *Repository) FileCommitsCount(revision, file string) (int64, error) {
  253. return commitsCount(repo.Path, revision, file)
  254. }
  255. // CommitsByFileAndRange return the commits according revison file and the page
  256. func (repo *Repository) CommitsByFileAndRange(revision, file string, page int) (*list.List, error) {
  257. stdout, err := NewCommand("log", revision, "--follow", "--skip="+strconv.Itoa((page-1)*50),
  258. "--max-count="+strconv.Itoa(CommitsRangeSize), prettyLogFormat, "--", file).RunInDirBytes(repo.Path)
  259. if err != nil {
  260. return nil, err
  261. }
  262. return repo.parsePrettyFormatLogToList(stdout)
  263. }
  264. // FilesCountBetween return the number of files changed between two commits
  265. func (repo *Repository) FilesCountBetween(startCommitID, endCommitID string) (int, error) {
  266. stdout, err := NewCommand("diff", "--name-only", startCommitID+"..."+endCommitID).RunInDir(repo.Path)
  267. if err != nil {
  268. return 0, err
  269. }
  270. return len(strings.Split(stdout, "\n")) - 1, nil
  271. }
  272. // CommitsBetween returns a list that contains commits between [last, before).
  273. func (repo *Repository) CommitsBetween(last *Commit, before *Commit) (*list.List, error) {
  274. stdout, err := NewCommand("rev-list", before.ID.String()+"..."+last.ID.String()).RunInDirBytes(repo.Path)
  275. if err != nil {
  276. return nil, err
  277. }
  278. return repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout))
  279. }
  280. // CommitsBetweenIDs return commits between twoe commits
  281. func (repo *Repository) CommitsBetweenIDs(last, before string) (*list.List, error) {
  282. lastCommit, err := repo.GetCommit(last)
  283. if err != nil {
  284. return nil, err
  285. }
  286. beforeCommit, err := repo.GetCommit(before)
  287. if err != nil {
  288. return nil, err
  289. }
  290. return repo.CommitsBetween(lastCommit, beforeCommit)
  291. }
  292. // CommitsCountBetween return numbers of commits between two commits
  293. func (repo *Repository) CommitsCountBetween(start, end string) (int64, error) {
  294. return commitsCount(repo.Path, start+"..."+end, "")
  295. }
  296. // commitsBefore the limit is depth, not total number of returned commits.
  297. func (repo *Repository) commitsBefore(id SHA1, limit int) (*list.List, error) {
  298. cmd := NewCommand("log")
  299. if limit > 0 {
  300. cmd.AddArguments("-"+strconv.Itoa(limit), prettyLogFormat, id.String())
  301. } else {
  302. cmd.AddArguments(prettyLogFormat, id.String())
  303. }
  304. stdout, err := cmd.RunInDirBytes(repo.Path)
  305. if err != nil {
  306. return nil, err
  307. }
  308. formattedLog, err := repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout))
  309. if err != nil {
  310. return nil, err
  311. }
  312. commits := list.New()
  313. for logEntry := formattedLog.Front(); logEntry != nil; logEntry = logEntry.Next() {
  314. commit := logEntry.Value.(*Commit)
  315. branches, err := repo.getBranches(commit, 2)
  316. if err != nil {
  317. return nil, err
  318. }
  319. if len(branches) > 1 {
  320. break
  321. }
  322. commits.PushBack(commit)
  323. }
  324. return commits, nil
  325. }
  326. func (repo *Repository) getCommitsBefore(id SHA1) (*list.List, error) {
  327. return repo.commitsBefore(id, 0)
  328. }
  329. func (repo *Repository) getCommitsBeforeLimit(id SHA1, num int) (*list.List, error) {
  330. return repo.commitsBefore(id, num)
  331. }
  332. func (repo *Repository) getBranches(commit *Commit, limit int) ([]string, error) {
  333. if version.Compare(gitVersion, "2.7.0", ">=") {
  334. stdout, err := NewCommand("for-each-ref", "--count="+strconv.Itoa(limit), "--format=%(refname:strip=2)", "--contains", commit.ID.String(), BranchPrefix).RunInDir(repo.Path)
  335. if err != nil {
  336. return nil, err
  337. }
  338. branches := strings.Fields(stdout)
  339. return branches, nil
  340. }
  341. stdout, err := NewCommand("branch", "--contains", commit.ID.String()).RunInDir(repo.Path)
  342. if err != nil {
  343. return nil, err
  344. }
  345. refs := strings.Split(stdout, "\n")
  346. var max int
  347. if len(refs) > limit {
  348. max = limit
  349. } else {
  350. max = len(refs) - 1
  351. }
  352. branches := make([]string, max)
  353. for i, ref := range refs[:max] {
  354. parts := strings.Fields(ref)
  355. branches[i] = parts[len(parts)-1]
  356. }
  357. return branches, nil
  358. }