repo_commit.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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. func (repo *Repository) CommitsByRangeSize(revision string, page, size int) (*list.List, error) {
  179. stdout, err := NewCommand("log", revision, "--skip="+strconv.Itoa((page-1)*size),
  180. "--max-count="+strconv.Itoa(size), _PRETTY_LOG_FORMAT).RunInDirBytes(repo.Path)
  181. if err != nil {
  182. return nil, err
  183. }
  184. return repo.parsePrettyFormatLogToList(stdout)
  185. }
  186. const DEFAULT_COMMITS_PAGE_SIZE = 30
  187. func (repo *Repository) CommitsByRange(revision string, page int) (*list.List, error) {
  188. return repo.CommitsByRangeSize(revision, page, DEFAULT_COMMITS_PAGE_SIZE)
  189. }
  190. func (repo *Repository) searchCommits(id sha1, keyword string) (*list.List, error) {
  191. stdout, err := NewCommand("log", id.String(), "-100", "-i", "--grep="+keyword, _PRETTY_LOG_FORMAT).RunInDirBytes(repo.Path)
  192. if err != nil {
  193. return nil, err
  194. }
  195. return repo.parsePrettyFormatLogToList(stdout)
  196. }
  197. func (repo *Repository) getFilesChanged(id1 string, id2 string) ([]string, error) {
  198. stdout, err := NewCommand("diff", "--name-only", id1, id2).RunInDirBytes(repo.Path)
  199. if err != nil {
  200. return nil, err
  201. }
  202. return strings.Split(string(stdout), "\n"), nil
  203. }
  204. func (repo *Repository) FileCommitsCount(revision, file string) (int64, error) {
  205. return commitsCount(repo.Path, revision, file)
  206. }
  207. func (repo *Repository) CommitsByFileAndRangeSize(revision, file string, page, size int) (*list.List, error) {
  208. stdout, err := NewCommand("log", revision, "--skip="+strconv.Itoa((page-1)*size),
  209. "--max-count="+strconv.Itoa(size), _PRETTY_LOG_FORMAT, "--", file).RunInDirBytes(repo.Path)
  210. if err != nil {
  211. return nil, err
  212. }
  213. return repo.parsePrettyFormatLogToList(stdout)
  214. }
  215. func (repo *Repository) CommitsByFileAndRange(revision, file string, page int) (*list.List, error) {
  216. return repo.CommitsByFileAndRangeSize(revision, file, page, DEFAULT_COMMITS_PAGE_SIZE)
  217. }
  218. func (repo *Repository) FilesCountBetween(startCommitID, endCommitID string) (int, error) {
  219. stdout, err := NewCommand("diff", "--name-only", startCommitID+"..."+endCommitID).RunInDir(repo.Path)
  220. if err != nil {
  221. return 0, err
  222. }
  223. return len(strings.Split(stdout, "\n")) - 1, nil
  224. }
  225. // CommitsBetween returns a list that contains commits between [last, before).
  226. func (repo *Repository) CommitsBetween(last *Commit, before *Commit) (*list.List, error) {
  227. if version.Compare(gitVersion, "1.8.0", ">=") {
  228. stdout, err := NewCommand("rev-list", before.ID.String()+"..."+last.ID.String()).RunInDirBytes(repo.Path)
  229. if err != nil {
  230. return nil, err
  231. }
  232. return repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout))
  233. }
  234. // Fallback to stupid solution, which iterates all commits of the repository
  235. // if before is not an ancestor of last.
  236. l := list.New()
  237. if last == nil || last.ParentCount() == 0 {
  238. return l, nil
  239. }
  240. var err error
  241. cur := last
  242. for {
  243. if cur.ID.Equal(before.ID) {
  244. break
  245. }
  246. l.PushBack(cur)
  247. if cur.ParentCount() == 0 {
  248. break
  249. }
  250. cur, err = cur.Parent(0)
  251. if err != nil {
  252. return nil, err
  253. }
  254. }
  255. return l, nil
  256. }
  257. func (repo *Repository) CommitsBetweenIDs(last, before string) (*list.List, error) {
  258. lastCommit, err := repo.GetCommit(last)
  259. if err != nil {
  260. return nil, err
  261. }
  262. beforeCommit, err := repo.GetCommit(before)
  263. if err != nil {
  264. return nil, err
  265. }
  266. return repo.CommitsBetween(lastCommit, beforeCommit)
  267. }
  268. func (repo *Repository) CommitsCountBetween(start, end string) (int64, error) {
  269. return commitsCount(repo.Path, start+"..."+end, "")
  270. }
  271. // The limit is depth, not total number of returned commits.
  272. func (repo *Repository) commitsBefore(l *list.List, parent *list.Element, id sha1, current, limit int) error {
  273. // Reach the limit
  274. if limit > 0 && current > limit {
  275. return nil
  276. }
  277. commit, err := repo.getCommit(id)
  278. if err != nil {
  279. return fmt.Errorf("getCommit: %v", err)
  280. }
  281. var e *list.Element
  282. if parent == nil {
  283. e = l.PushBack(commit)
  284. } else {
  285. var in = parent
  286. for {
  287. if in == nil {
  288. break
  289. } else if in.Value.(*Commit).ID.Equal(commit.ID) {
  290. return nil
  291. } else if in.Next() == nil {
  292. break
  293. }
  294. if in.Value.(*Commit).Committer.When.Equal(commit.Committer.When) {
  295. break
  296. }
  297. if in.Value.(*Commit).Committer.When.After(commit.Committer.When) &&
  298. in.Next().Value.(*Commit).Committer.When.Before(commit.Committer.When) {
  299. break
  300. }
  301. in = in.Next()
  302. }
  303. e = l.InsertAfter(commit, in)
  304. }
  305. pr := parent
  306. if commit.ParentCount() > 1 {
  307. pr = e
  308. }
  309. for i := 0; i < commit.ParentCount(); i++ {
  310. id, err := commit.ParentID(i)
  311. if err != nil {
  312. return err
  313. }
  314. err = repo.commitsBefore(l, pr, id, current+1, limit)
  315. if err != nil {
  316. return err
  317. }
  318. }
  319. return nil
  320. }
  321. func (repo *Repository) getCommitsBefore(id sha1) (*list.List, error) {
  322. l := list.New()
  323. return l, repo.commitsBefore(l, nil, id, 1, 0)
  324. }
  325. func (repo *Repository) getCommitsBeforeLimit(id sha1, num int) (*list.List, error) {
  326. l := list.New()
  327. return l, repo.commitsBefore(l, nil, id, 1, num)
  328. }