repo_commit.go 11 KB

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