You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

353 lines
9.1 KiB

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