repo_commit.go 11 KB

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