repo_commit.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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. "fmt"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "github.com/mcuadros/go-version"
  13. )
  14. const REMOTE_PREFIX = "refs/remotes/"
  15. // getRefCommitID returns the last commit ID string of given reference (branch or tag).
  16. func (repo *Repository) getRefCommitID(name string) (string, error) {
  17. stdout, err := NewCommand("show-ref", "--verify", name).RunInDir(repo.Path)
  18. if err != nil {
  19. if strings.Contains(err.Error(), "not a valid ref") {
  20. return "", ErrNotExist{name, ""}
  21. }
  22. return "", err
  23. }
  24. return strings.Split(stdout, " ")[0], nil
  25. }
  26. // GetBranchCommitID returns last commit ID string of given branch.
  27. func (repo *Repository) GetBranchCommitID(name string) (string, error) {
  28. return repo.getRefCommitID(BRANCH_PREFIX + name)
  29. }
  30. // GetTagCommitID returns last commit ID string of given tag.
  31. func (repo *Repository) GetTagCommitID(name string) (string, error) {
  32. return repo.getRefCommitID(TAG_PREFIX + name)
  33. }
  34. // GetRemoteBranchCommitID returns last commit ID string of given remote branch.
  35. func (repo *Repository) GetRemoteBranchCommitID(name string) (string, error) {
  36. return repo.getRefCommitID(REMOTE_PREFIX + name)
  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. }
  81. nextline += eol + 1
  82. case eol == 0:
  83. commit.CommitMessage = string(data[nextline+1:])
  84. break l
  85. default:
  86. break l
  87. }
  88. }
  89. return commit, nil
  90. }
  91. func (repo *Repository) getCommit(id sha1) (*Commit, error) {
  92. c, ok := repo.commitCache.Get(id.String())
  93. if ok {
  94. log("Hit cache: %s", id)
  95. return c.(*Commit), nil
  96. }
  97. data, err := NewCommand("cat-file", "commit", id.String()).RunInDirBytes(repo.Path)
  98. if err != nil {
  99. if strings.Contains(err.Error(), "exit status 128") {
  100. return nil, ErrNotExist{id.String(), ""}
  101. }
  102. return nil, err
  103. }
  104. commit, err := parseCommitData(data)
  105. if err != nil {
  106. return nil, err
  107. }
  108. commit.repo = repo
  109. commit.ID = id
  110. repo.commitCache.Set(id.String(), commit)
  111. return commit, nil
  112. }
  113. // GetCommit returns commit object of by ID string.
  114. func (repo *Repository) GetCommit(commitID string) (*Commit, error) {
  115. var err error
  116. commitID, err = GetFullCommitID(repo.Path, commitID)
  117. if err != nil {
  118. return nil, err
  119. }
  120. id, err := NewIDFromString(commitID)
  121. if err != nil {
  122. return nil, err
  123. }
  124. return repo.getCommit(id)
  125. }
  126. // GetBranchCommit returns the last commit of given branch.
  127. func (repo *Repository) GetBranchCommit(name string) (*Commit, error) {
  128. commitID, err := repo.GetBranchCommitID(name)
  129. if err != nil {
  130. return nil, err
  131. }
  132. return repo.GetCommit(commitID)
  133. }
  134. // GetTagCommit returns the commit of given tag.
  135. func (repo *Repository) GetTagCommit(name string) (*Commit, error) {
  136. commitID, err := repo.GetTagCommitID(name)
  137. if err != nil {
  138. return nil, err
  139. }
  140. return repo.GetCommit(commitID)
  141. }
  142. // GetRemoteBranchCommit returns the last commit of given remote branch.
  143. func (repo *Repository) GetRemoteBranchCommit(name string) (*Commit, error) {
  144. commitID, err := repo.GetRemoteBranchCommitID(name)
  145. if err != nil {
  146. return nil, err
  147. }
  148. return repo.GetCommit(commitID)
  149. }
  150. func (repo *Repository) getCommitByPathWithID(id sha1, relpath string) (*Commit, error) {
  151. // File name starts with ':' must be escaped.
  152. if relpath[0] == ':' {
  153. relpath = `\` + relpath
  154. }
  155. stdout, err := NewCommand("log", "-1", _PRETTY_LOG_FORMAT, id.String(), "--", relpath).RunInDir(repo.Path)
  156. if err != nil {
  157. return nil, err
  158. }
  159. id, err = NewIDFromString(stdout)
  160. if err != nil {
  161. return nil, err
  162. }
  163. return repo.getCommit(id)
  164. }
  165. // GetCommitByPath returns the last commit of relative path.
  166. func (repo *Repository) GetCommitByPath(relpath string) (*Commit, error) {
  167. stdout, err := NewCommand("log", "-1", _PRETTY_LOG_FORMAT, "--", relpath).RunInDirBytes(repo.Path)
  168. if err != nil {
  169. return nil, err
  170. }
  171. commits, err := repo.parsePrettyFormatLogToList(stdout)
  172. if err != nil {
  173. return nil, err
  174. }
  175. return commits.Front().Value.(*Commit), nil
  176. }
  177. func (repo *Repository) CommitsByRangeSize(revision string, page, size int) (*list.List, error) {
  178. stdout, err := NewCommand("log", revision, "--skip="+strconv.Itoa((page-1)*size),
  179. "--max-count="+strconv.Itoa(size), _PRETTY_LOG_FORMAT).RunInDirBytes(repo.Path)
  180. if err != nil {
  181. return nil, err
  182. }
  183. return repo.parsePrettyFormatLogToList(stdout)
  184. }
  185. var DefaultCommitsPageSize = 30
  186. func (repo *Repository) CommitsByRange(revision string, page int) (*list.List, error) {
  187. return repo.CommitsByRangeSize(revision, page, DefaultCommitsPageSize)
  188. }
  189. func (repo *Repository) searchCommits(id sha1, keyword string) (*list.List, error) {
  190. stdout, err := NewCommand("log", id.String(), "-100", "-i", "--grep="+keyword, _PRETTY_LOG_FORMAT).RunInDirBytes(repo.Path)
  191. if err != nil {
  192. return nil, err
  193. }
  194. return repo.parsePrettyFormatLogToList(stdout)
  195. }
  196. func (repo *Repository) getFilesChanged(id1 string, id2 string) ([]string, error) {
  197. stdout, err := NewCommand("diff", "--name-only", id1, id2).RunInDirBytes(repo.Path)
  198. if err != nil {
  199. return nil, err
  200. }
  201. return strings.Split(string(stdout), "\n"), nil
  202. }
  203. func (repo *Repository) FileCommitsCount(revision, file string) (int64, error) {
  204. return commitsCount(repo.Path, revision, file)
  205. }
  206. func (repo *Repository) CommitsByFileAndRangeSize(revision, file string, page, size int) (*list.List, error) {
  207. stdout, err := NewCommand("log", revision, "--skip="+strconv.Itoa((page-1)*size),
  208. "--max-count="+strconv.Itoa(size), _PRETTY_LOG_FORMAT, "--", file).RunInDirBytes(repo.Path)
  209. if err != nil {
  210. return nil, err
  211. }
  212. return repo.parsePrettyFormatLogToList(stdout)
  213. }
  214. func (repo *Repository) CommitsByFileAndRange(revision, file string, page int) (*list.List, error) {
  215. return repo.CommitsByFileAndRangeSize(revision, file, page, DefaultCommitsPageSize)
  216. }
  217. func (repo *Repository) FilesCountBetween(startCommitID, endCommitID string) (int, error) {
  218. stdout, err := NewCommand("diff", "--name-only", startCommitID+"..."+endCommitID).RunInDir(repo.Path)
  219. if err != nil {
  220. return 0, err
  221. }
  222. return len(strings.Split(stdout, "\n")) - 1, nil
  223. }
  224. // CommitsBetween returns a list that contains commits between [last, before).
  225. func (repo *Repository) CommitsBetween(last *Commit, before *Commit) (*list.List, error) {
  226. if version.Compare(gitVersion, "1.8.0", ">=") {
  227. stdout, err := NewCommand("rev-list", before.ID.String()+"..."+last.ID.String()).RunInDirBytes(repo.Path)
  228. if err != nil {
  229. return nil, err
  230. }
  231. return repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout))
  232. }
  233. // Fallback to stupid solution, which iterates all commits of the repository
  234. // if before is not an ancestor of last.
  235. l := list.New()
  236. if last == nil || last.ParentCount() == 0 {
  237. return l, nil
  238. }
  239. var err error
  240. cur := last
  241. for {
  242. if cur.ID.Equal(before.ID) {
  243. break
  244. }
  245. l.PushBack(cur)
  246. if cur.ParentCount() == 0 {
  247. break
  248. }
  249. cur, err = cur.Parent(0)
  250. if err != nil {
  251. return nil, err
  252. }
  253. }
  254. return l, nil
  255. }
  256. func (repo *Repository) CommitsBetweenIDs(last, before string) (*list.List, error) {
  257. lastCommit, err := repo.GetCommit(last)
  258. if err != nil {
  259. return nil, err
  260. }
  261. beforeCommit, err := repo.GetCommit(before)
  262. if err != nil {
  263. return nil, err
  264. }
  265. return repo.CommitsBetween(lastCommit, beforeCommit)
  266. }
  267. func (repo *Repository) CommitsCountBetween(start, end string) (int64, error) {
  268. return commitsCount(repo.Path, start+"..."+end, "")
  269. }
  270. // The limit is depth, not total number of returned commits.
  271. func (repo *Repository) commitsBefore(l *list.List, parent *list.Element, id sha1, current, limit int) error {
  272. // Reach the limit
  273. if limit > 0 && current > limit {
  274. return nil
  275. }
  276. commit, err := repo.getCommit(id)
  277. if err != nil {
  278. return fmt.Errorf("getCommit: %v", err)
  279. }
  280. var e *list.Element
  281. if parent == nil {
  282. e = l.PushBack(commit)
  283. } else {
  284. var in = parent
  285. for {
  286. if in == nil {
  287. break
  288. } else if in.Value.(*Commit).ID.Equal(commit.ID) {
  289. return nil
  290. } else if in.Next() == nil {
  291. break
  292. }
  293. if in.Value.(*Commit).Committer.When.Equal(commit.Committer.When) {
  294. break
  295. }
  296. if in.Value.(*Commit).Committer.When.After(commit.Committer.When) &&
  297. in.Next().Value.(*Commit).Committer.When.Before(commit.Committer.When) {
  298. break
  299. }
  300. in = in.Next()
  301. }
  302. e = l.InsertAfter(commit, in)
  303. }
  304. pr := parent
  305. if commit.ParentCount() > 1 {
  306. pr = e
  307. }
  308. for i := 0; i < commit.ParentCount(); i++ {
  309. id, err := commit.ParentID(i)
  310. if err != nil {
  311. return err
  312. }
  313. err = repo.commitsBefore(l, pr, id, current+1, limit)
  314. if err != nil {
  315. return err
  316. }
  317. }
  318. return nil
  319. }
  320. func (repo *Repository) getCommitsBefore(id sha1) (*list.List, error) {
  321. l := list.New()
  322. return l, repo.commitsBefore(l, nil, id, 1, 0)
  323. }
  324. func (repo *Repository) getCommitsBeforeLimit(id sha1, num int) (*list.List, error) {
  325. l := list.New()
  326. return l, repo.commitsBefore(l, nil, id, 1, num)
  327. }
  328. // CommitsAfterDate returns a list of commits which committed after given date.
  329. // The format of date should be in RFC3339.
  330. func (repo *Repository) CommitsAfterDate(date string) (*list.List, error) {
  331. stdout, err := NewCommand("log", _PRETTY_LOG_FORMAT, "--since="+date).RunInDirBytes(repo.Path)
  332. if err != nil {
  333. return nil, err
  334. }
  335. return repo.parsePrettyFormatLogToList(stdout)
  336. }
  337. // CommitsCount returns number of total commits of until given revision.
  338. func CommitsCount(repoPath, revision string) (int64, error) {
  339. return commitsCount(repoPath, revision, "")
  340. }
  341. // GetLatestCommitDate returns the date of latest commit of repository.
  342. // If branch is empty, it returns the latest commit across all branches.
  343. func GetLatestCommitDate(repoPath, branch string) (time.Time, error) {
  344. cmd := NewCommand("for-each-ref", "--count=1", "--sort=-committerdate", "--format=%(committerdate:iso8601)")
  345. if len(branch) > 0 {
  346. cmd.AddArguments("refs/heads/" + branch)
  347. }
  348. stdout, err := cmd.RunInDir(repoPath)
  349. if err != nil {
  350. return time.Time{}, err
  351. }
  352. return time.Parse("2006-01-02 15:04:05 -0700", strings.TrimSpace(stdout))
  353. }