repo_commit.go 10 KB

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