repo_commit.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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. )
  13. const RemotePrefix = "refs/remotes/"
  14. // getRefCommitID returns the last commit ID string of given reference (branch or tag).
  15. func (repo *Repository) getRefCommitID(name string) (string, error) {
  16. stdout, err := NewCommand("show-ref", "--verify", name).RunInDir(repo.Path)
  17. if err != nil {
  18. if strings.Contains(err.Error(), "not a valid ref") {
  19. return "", ErrNotExist{name, ""}
  20. }
  21. return "", err
  22. }
  23. return strings.Split(stdout, " ")[0], nil
  24. }
  25. // GetBranchCommitID returns last commit ID string of given branch.
  26. func (repo *Repository) GetBranchCommitID(name string) (string, error) {
  27. return repo.getRefCommitID(BranchPrefix + name)
  28. }
  29. // GetTagCommitID returns last commit ID string of given tag.
  30. func (repo *Repository) GetTagCommitID(name string) (string, error) {
  31. return repo.getRefCommitID(TagPrefix + name)
  32. }
  33. // GetRemoteBranchCommitID returns last commit ID string of given remote branch.
  34. func (repo *Repository) GetRemoteBranchCommitID(name string) (string, error) {
  35. return repo.getRefCommitID(RemotePrefix + name)
  36. }
  37. // parseCommitData parses commit information from the (uncompressed) raw
  38. // data from the commit object.
  39. // \n\n separate headers from message
  40. func parseCommitData(data []byte) (*Commit, error) {
  41. commit := new(Commit)
  42. commit.parents = make([]sha1, 0, 1)
  43. // we now have the contents of the commit object. Let's investigate...
  44. nextline := 0
  45. l:
  46. for {
  47. eol := bytes.IndexByte(data[nextline:], '\n')
  48. switch {
  49. case eol > 0:
  50. line := data[nextline : nextline+eol]
  51. spacepos := bytes.IndexByte(line, ' ')
  52. reftype := line[:spacepos]
  53. switch string(reftype) {
  54. case "tree", "object":
  55. id, err := NewIDFromString(string(line[spacepos+1:]))
  56. if err != nil {
  57. return nil, err
  58. }
  59. commit.Tree.ID = id
  60. case "parent":
  61. // A commit can have one or more parents
  62. oid, err := NewIDFromString(string(line[spacepos+1:]))
  63. if err != nil {
  64. return nil, err
  65. }
  66. commit.parents = append(commit.parents, oid)
  67. case "author", "tagger":
  68. sig, err := newSignatureFromCommitline(line[spacepos+1:])
  69. if err != nil {
  70. return nil, err
  71. }
  72. commit.Author = sig
  73. case "committer":
  74. sig, err := newSignatureFromCommitline(line[spacepos+1:])
  75. if err != nil {
  76. return nil, err
  77. }
  78. commit.Committer = sig
  79. }
  80. nextline += eol + 1
  81. case eol == 0:
  82. commit.CommitMessage = string(data[nextline+1:])
  83. break l
  84. default:
  85. break l
  86. }
  87. }
  88. return commit, nil
  89. }
  90. func (repo *Repository) getCommit(id sha1) (*Commit, error) {
  91. c, ok := repo.commitCache.Get(id.String())
  92. if ok {
  93. log("Hit cache: %s", id)
  94. return c.(*Commit), nil
  95. }
  96. data, err := NewCommand("cat-file", "commit", id.String()).RunInDirBytes(repo.Path)
  97. if err != nil {
  98. if strings.Contains(err.Error(), "exit status 128") {
  99. return nil, ErrNotExist{id.String(), ""}
  100. }
  101. return nil, err
  102. }
  103. commit, err := parseCommitData(data)
  104. if err != nil {
  105. return nil, err
  106. }
  107. commit.repo = repo
  108. commit.ID = id
  109. repo.commitCache.Set(id.String(), commit)
  110. return commit, nil
  111. }
  112. // GetCommit returns commit object of by ID string.
  113. func (repo *Repository) GetCommit(commitID string) (*Commit, error) {
  114. var err error
  115. commitID, err = GetFullCommitID(repo.Path, commitID)
  116. if err != nil {
  117. return nil, err
  118. }
  119. id, err := NewIDFromString(commitID)
  120. if err != nil {
  121. return nil, err
  122. }
  123. return repo.getCommit(id)
  124. }
  125. // GetBranchCommit returns the last commit of given branch.
  126. func (repo *Repository) GetBranchCommit(name string) (*Commit, error) {
  127. commitID, err := repo.GetBranchCommitID(name)
  128. if err != nil {
  129. return nil, err
  130. }
  131. return repo.GetCommit(commitID)
  132. }
  133. // GetTagCommit returns the commit of given tag.
  134. func (repo *Repository) GetTagCommit(name string) (*Commit, error) {
  135. commitID, err := repo.GetTagCommitID(name)
  136. if err != nil {
  137. return nil, err
  138. }
  139. return repo.GetCommit(commitID)
  140. }
  141. // GetRemoteBranchCommit returns the last commit of given remote branch.
  142. func (repo *Repository) GetRemoteBranchCommit(name string) (*Commit, error) {
  143. commitID, err := repo.GetRemoteBranchCommitID(name)
  144. if err != nil {
  145. return nil, err
  146. }
  147. return repo.GetCommit(commitID)
  148. }
  149. func (repo *Repository) getCommitByPathWithID(id sha1, relpath string) (*Commit, error) {
  150. // File name starts with ':' must be escaped.
  151. if relpath[0] == ':' {
  152. relpath = `\` + relpath
  153. }
  154. stdout, err := NewCommand("log", "-1", prettyLogFormat, id.String(), "--", relpath).RunInDir(repo.Path)
  155. if err != nil {
  156. return nil, err
  157. }
  158. id, err = NewIDFromString(stdout)
  159. if err != nil {
  160. return nil, err
  161. }
  162. return repo.getCommit(id)
  163. }
  164. // GetCommitByPath returns the last commit of relative path.
  165. func (repo *Repository) GetCommitByPath(relpath string) (*Commit, error) {
  166. stdout, err := NewCommand("log", "-1", prettyLogFormat, "--", relpath).RunInDirBytes(repo.Path)
  167. if err != nil {
  168. return nil, err
  169. }
  170. commits, err := repo.parsePrettyFormatLogToList(stdout)
  171. if err != nil {
  172. return nil, err
  173. }
  174. return commits.Front().Value.(*Commit), nil
  175. }
  176. func (repo *Repository) CommitsByRangeSize(revision string, page, size int) (*list.List, error) {
  177. stdout, err := NewCommand("log", revision, "--skip="+strconv.Itoa((page-1)*size),
  178. "--max-count="+strconv.Itoa(size), prettyLogFormat).RunInDirBytes(repo.Path)
  179. if err != nil {
  180. return nil, err
  181. }
  182. return repo.parsePrettyFormatLogToList(stdout)
  183. }
  184. var DefaultCommitsPageSize = 30
  185. func (repo *Repository) CommitsByRange(revision string, page int) (*list.List, error) {
  186. return repo.CommitsByRangeSize(revision, page, DefaultCommitsPageSize)
  187. }
  188. func (repo *Repository) searchCommits(id sha1, keyword string) (*list.List, error) {
  189. stdout, err := NewCommand("log", id.String(), "-100", "-i", "--grep="+keyword, prettyLogFormat).RunInDirBytes(repo.Path)
  190. if err != nil {
  191. return nil, err
  192. }
  193. return repo.parsePrettyFormatLogToList(stdout)
  194. }
  195. func (repo *Repository) getFilesChanged(id1 string, id2 string) ([]string, error) {
  196. stdout, err := NewCommand("diff", "--name-only", id1, id2).RunInDirBytes(repo.Path)
  197. if err != nil {
  198. return nil, err
  199. }
  200. return strings.Split(string(stdout), "\n"), nil
  201. }
  202. func (repo *Repository) FileCommitsCount(revision, file string) (int64, error) {
  203. return commitsCount(repo.Path, revision, file)
  204. }
  205. func (repo *Repository) CommitsByFileAndRangeSize(revision, file string, page, size int) (*list.List, error) {
  206. stdout, err := NewCommand("log", revision, "--skip="+strconv.Itoa((page-1)*size),
  207. "--max-count="+strconv.Itoa(size), prettyLogFormat, "--", file).RunInDirBytes(repo.Path)
  208. if err != nil {
  209. return nil, err
  210. }
  211. return repo.parsePrettyFormatLogToList(stdout)
  212. }
  213. func (repo *Repository) CommitsByFileAndRange(revision, file string, page int) (*list.List, error) {
  214. return repo.CommitsByFileAndRangeSize(revision, file, page, DefaultCommitsPageSize)
  215. }
  216. func (repo *Repository) FilesCountBetween(startCommitID, endCommitID string) (int, error) {
  217. stdout, err := NewCommand("diff", "--name-only", startCommitID+"..."+endCommitID).RunInDir(repo.Path)
  218. if err != nil {
  219. return 0, err
  220. }
  221. return len(strings.Split(stdout, "\n")) - 1, nil
  222. }
  223. // CommitsBetween returns a list that contains commits between [last, before).
  224. func (repo *Repository) CommitsBetween(last *Commit, before *Commit) (*list.List, error) {
  225. stdout, err := NewCommand("rev-list", before.ID.String()+"..."+last.ID.String()).RunInDirBytes(repo.Path)
  226. if err != nil {
  227. return nil, err
  228. }
  229. return repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout))
  230. }
  231. func (repo *Repository) CommitsBetweenIDs(last, before string) (*list.List, error) {
  232. lastCommit, err := repo.GetCommit(last)
  233. if err != nil {
  234. return nil, err
  235. }
  236. beforeCommit, err := repo.GetCommit(before)
  237. if err != nil {
  238. return nil, err
  239. }
  240. return repo.CommitsBetween(lastCommit, beforeCommit)
  241. }
  242. func (repo *Repository) CommitsCountBetween(start, end string) (int64, error) {
  243. return commitsCount(repo.Path, start+"..."+end, "")
  244. }
  245. // The limit is depth, not total number of returned commits.
  246. func (repo *Repository) commitsBefore(l *list.List, parent *list.Element, id sha1, current, limit int) error {
  247. // Reach the limit
  248. if limit > 0 && current > limit {
  249. return nil
  250. }
  251. commit, err := repo.getCommit(id)
  252. if err != nil {
  253. return fmt.Errorf("getCommit: %v", err)
  254. }
  255. var e *list.Element
  256. if parent == nil {
  257. e = l.PushBack(commit)
  258. } else {
  259. var in = parent
  260. for {
  261. if in == nil {
  262. break
  263. } else if in.Value.(*Commit).ID.Equal(commit.ID) {
  264. return nil
  265. } else if in.Next() == nil {
  266. break
  267. }
  268. if in.Value.(*Commit).Committer.When.Equal(commit.Committer.When) {
  269. break
  270. }
  271. if in.Value.(*Commit).Committer.When.After(commit.Committer.When) &&
  272. in.Next().Value.(*Commit).Committer.When.Before(commit.Committer.When) {
  273. break
  274. }
  275. in = in.Next()
  276. }
  277. e = l.InsertAfter(commit, in)
  278. }
  279. pr := parent
  280. if commit.ParentCount() > 1 {
  281. pr = e
  282. }
  283. for i := 0; i < commit.ParentCount(); i++ {
  284. id, err := commit.ParentID(i)
  285. if err != nil {
  286. return err
  287. }
  288. err = repo.commitsBefore(l, pr, id, current+1, limit)
  289. if err != nil {
  290. return err
  291. }
  292. }
  293. return nil
  294. }
  295. func (repo *Repository) getCommitsBefore(id sha1) (*list.List, error) {
  296. l := list.New()
  297. return l, repo.commitsBefore(l, nil, id, 1, 0)
  298. }
  299. func (repo *Repository) getCommitsBeforeLimit(id sha1, num int) (*list.List, error) {
  300. l := list.New()
  301. return l, repo.commitsBefore(l, nil, id, 1, num)
  302. }
  303. // CommitsAfterDate returns a list of commits which committed after given date.
  304. // The format of date should be in RFC3339.
  305. func (repo *Repository) CommitsAfterDate(date string) (*list.List, error) {
  306. stdout, err := NewCommand("log", prettyLogFormat, "--since="+date).RunInDirBytes(repo.Path)
  307. if err != nil {
  308. return nil, err
  309. }
  310. return repo.parsePrettyFormatLogToList(stdout)
  311. }
  312. // CommitsCount returns number of total commits of until given revision.
  313. func CommitsCount(repoPath, revision string) (int64, error) {
  314. return commitsCount(repoPath, revision, "")
  315. }
  316. // GetLatestCommitDate returns the date of latest commit of repository.
  317. // If branch is empty, it returns the latest commit across all branches.
  318. func GetLatestCommitDate(repoPath, branch string) (time.Time, error) {
  319. cmd := NewCommand("for-each-ref", "--count=1", "--sort=-committerdate", "--format=%(committerdate:iso8601)")
  320. if len(branch) > 0 {
  321. cmd.AddArguments("refs/heads/" + branch)
  322. }
  323. stdout, err := cmd.RunInDir(repoPath)
  324. if err != nil {
  325. return time.Time{}, err
  326. }
  327. return time.Parse("2006-01-02 15:04:05 -0700", strings.TrimSpace(stdout))
  328. }