repo_commit.go 9.6 KB

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