本站源代码
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

421 lines
12KB

  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package git
  6. import (
  7. "bytes"
  8. "container/list"
  9. "fmt"
  10. "strconv"
  11. "strings"
  12. "github.com/mcuadros/go-version"
  13. "gopkg.in/src-d/go-git.v4/plumbing"
  14. "gopkg.in/src-d/go-git.v4/plumbing/object"
  15. )
  16. // GetRefCommitID returns the last commit ID string of given reference (branch or tag).
  17. func (repo *Repository) GetRefCommitID(name string) (string, error) {
  18. ref, err := repo.gogitRepo.Reference(plumbing.ReferenceName(name), true)
  19. if err != nil {
  20. return "", err
  21. }
  22. return ref.Hash().String(), nil
  23. }
  24. // IsCommitExist returns true if given commit exists in current repository.
  25. func (repo *Repository) IsCommitExist(name string) bool {
  26. hash := plumbing.NewHash(name)
  27. _, err := repo.gogitRepo.CommitObject(hash)
  28. return err == nil
  29. }
  30. // GetBranchCommitID returns last commit ID string of given branch.
  31. func (repo *Repository) GetBranchCommitID(name string) (string, error) {
  32. return repo.GetRefCommitID(BranchPrefix + name)
  33. }
  34. // GetTagCommitID returns last commit ID string of given tag.
  35. func (repo *Repository) GetTagCommitID(name string) (string, error) {
  36. stdout, err := NewCommand("rev-list", "-n", "1", name).RunInDir(repo.Path)
  37. if err != nil {
  38. if strings.Contains(err.Error(), "unknown revision or path") {
  39. return "", ErrNotExist{name, ""}
  40. }
  41. return "", err
  42. }
  43. return strings.TrimSpace(stdout), nil
  44. }
  45. func convertPGPSignatureForTag(t *object.Tag) *CommitGPGSignature {
  46. if t.PGPSignature == "" {
  47. return nil
  48. }
  49. var w strings.Builder
  50. var err error
  51. if _, err = fmt.Fprintf(&w,
  52. "object %s\ntype %s\ntag %s\ntagger ",
  53. t.Target.String(), t.TargetType.Bytes(), t.Name); err != nil {
  54. return nil
  55. }
  56. if err = t.Tagger.Encode(&w); err != nil {
  57. return nil
  58. }
  59. if _, err = fmt.Fprintf(&w, "\n\n"); err != nil {
  60. return nil
  61. }
  62. if _, err = fmt.Fprintf(&w, t.Message); err != nil {
  63. return nil
  64. }
  65. return &CommitGPGSignature{
  66. Signature: t.PGPSignature,
  67. Payload: strings.TrimSpace(w.String()) + "\n",
  68. }
  69. }
  70. func (repo *Repository) getCommit(id SHA1) (*Commit, error) {
  71. var tagObject *object.Tag
  72. gogitCommit, err := repo.gogitRepo.CommitObject(id)
  73. if err == plumbing.ErrObjectNotFound {
  74. tagObject, err = repo.gogitRepo.TagObject(id)
  75. if err == nil {
  76. gogitCommit, err = repo.gogitRepo.CommitObject(tagObject.Target)
  77. }
  78. }
  79. if err != nil {
  80. return nil, err
  81. }
  82. commit := convertCommit(gogitCommit)
  83. commit.repo = repo
  84. if tagObject != nil {
  85. commit.CommitMessage = strings.TrimSpace(tagObject.Message)
  86. commit.Author = &tagObject.Tagger
  87. commit.Signature = convertPGPSignatureForTag(tagObject)
  88. }
  89. tree, err := gogitCommit.Tree()
  90. if err != nil {
  91. return nil, err
  92. }
  93. commit.Tree.ID = tree.Hash
  94. commit.Tree.gogitTree = tree
  95. return commit, nil
  96. }
  97. // ConvertToSHA1 returns a Hash object from a potential ID string
  98. func (repo *Repository) ConvertToSHA1(commitID string) (SHA1, error) {
  99. if len(commitID) != 40 {
  100. var err error
  101. actualCommitID, err := NewCommand("rev-parse", "--verify", commitID).RunInDir(repo.Path)
  102. if err != nil {
  103. if strings.Contains(err.Error(), "unknown revision or path") ||
  104. strings.Contains(err.Error(), "fatal: Needed a single revision") {
  105. return SHA1{}, ErrNotExist{commitID, ""}
  106. }
  107. return SHA1{}, err
  108. }
  109. commitID = actualCommitID
  110. }
  111. return NewIDFromString(commitID)
  112. }
  113. // GetCommit returns commit object of by ID string.
  114. func (repo *Repository) GetCommit(commitID string) (*Commit, error) {
  115. id, err := repo.ConvertToSHA1(commitID)
  116. if err != nil {
  117. return nil, err
  118. }
  119. return repo.getCommit(id)
  120. }
  121. // GetBranchCommit returns the last commit of given branch.
  122. func (repo *Repository) GetBranchCommit(name string) (*Commit, error) {
  123. commitID, err := repo.GetBranchCommitID(name)
  124. if err != nil {
  125. return nil, err
  126. }
  127. return repo.GetCommit(commitID)
  128. }
  129. // GetTagCommit get the commit of the specific tag via name
  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", prettyLogFormat, 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", prettyLogFormat, "--", 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. // CommitsRangeSize the default commits range size
  165. var CommitsRangeSize = 50
  166. func (repo *Repository) commitsByRange(id SHA1, page int) (*list.List, error) {
  167. stdout, err := NewCommand("log", id.String(), "--skip="+strconv.Itoa((page-1)*CommitsRangeSize),
  168. "--max-count="+strconv.Itoa(CommitsRangeSize), prettyLogFormat).RunInDirBytes(repo.Path)
  169. if err != nil {
  170. return nil, err
  171. }
  172. return repo.parsePrettyFormatLogToList(stdout)
  173. }
  174. func (repo *Repository) searchCommits(id SHA1, opts SearchCommitsOptions) (*list.List, error) {
  175. cmd := NewCommand("log", id.String(), "-100", prettyLogFormat)
  176. args := []string{"-i"}
  177. if len(opts.Authors) > 0 {
  178. for _, v := range opts.Authors {
  179. args = append(args, "--author="+v)
  180. }
  181. }
  182. if len(opts.Committers) > 0 {
  183. for _, v := range opts.Committers {
  184. args = append(args, "--committer="+v)
  185. }
  186. }
  187. if len(opts.After) > 0 {
  188. args = append(args, "--after="+opts.After)
  189. }
  190. if len(opts.Before) > 0 {
  191. args = append(args, "--before="+opts.Before)
  192. }
  193. if opts.All {
  194. args = append(args, "--all")
  195. }
  196. if len(opts.Keywords) > 0 {
  197. for _, v := range opts.Keywords {
  198. cmd.AddArguments("--grep=" + v)
  199. }
  200. }
  201. cmd.AddArguments(args...)
  202. stdout, err := cmd.RunInDirBytes(repo.Path)
  203. if err != nil {
  204. return nil, err
  205. }
  206. if len(stdout) != 0 {
  207. stdout = append(stdout, '\n')
  208. }
  209. if len(opts.Keywords) > 0 {
  210. for _, v := range opts.Keywords {
  211. if len(v) >= 4 {
  212. hashCmd := NewCommand("log", "-1", prettyLogFormat)
  213. hashCmd.AddArguments(args...)
  214. hashCmd.AddArguments(v)
  215. hashMatching, err := hashCmd.RunInDirBytes(repo.Path)
  216. if err != nil || bytes.Contains(stdout, hashMatching) {
  217. continue
  218. }
  219. stdout = append(stdout, hashMatching...)
  220. stdout = append(stdout, '\n')
  221. }
  222. }
  223. }
  224. return repo.parsePrettyFormatLogToList(bytes.TrimSuffix(stdout, []byte{'\n'}))
  225. }
  226. func (repo *Repository) getFilesChanged(id1, id2 string) ([]string, error) {
  227. stdout, err := NewCommand("diff", "--name-only", id1, id2).RunInDirBytes(repo.Path)
  228. if err != nil {
  229. return nil, err
  230. }
  231. return strings.Split(string(stdout), "\n"), nil
  232. }
  233. // FileChangedBetweenCommits Returns true if the file changed between commit IDs id1 and id2
  234. // You must ensure that id1 and id2 are valid commit ids.
  235. func (repo *Repository) FileChangedBetweenCommits(filename, id1, id2 string) (bool, error) {
  236. stdout, err := NewCommand("diff", "--name-only", "-z", id1, id2, "--", filename).RunInDirBytes(repo.Path)
  237. if err != nil {
  238. return false, err
  239. }
  240. return len(strings.TrimSpace(string(stdout))) > 0, nil
  241. }
  242. // FileCommitsCount return the number of files at a revison
  243. func (repo *Repository) FileCommitsCount(revision, file string) (int64, error) {
  244. return commitsCount(repo.Path, revision, file)
  245. }
  246. // CommitsByFileAndRange return the commits according revison file and the page
  247. func (repo *Repository) CommitsByFileAndRange(revision, file string, page int) (*list.List, error) {
  248. stdout, err := NewCommand("log", revision, "--follow", "--skip="+strconv.Itoa((page-1)*50),
  249. "--max-count="+strconv.Itoa(CommitsRangeSize), prettyLogFormat, "--", file).RunInDirBytes(repo.Path)
  250. if err != nil {
  251. return nil, err
  252. }
  253. return repo.parsePrettyFormatLogToList(stdout)
  254. }
  255. // CommitsByFileAndRangeNoFollow return the commits according revison file and the page
  256. func (repo *Repository) CommitsByFileAndRangeNoFollow(revision, file string, page int) (*list.List, error) {
  257. stdout, err := NewCommand("log", revision, "--skip="+strconv.Itoa((page-1)*50),
  258. "--max-count="+strconv.Itoa(CommitsRangeSize), prettyLogFormat, "--", file).RunInDirBytes(repo.Path)
  259. if err != nil {
  260. return nil, err
  261. }
  262. return repo.parsePrettyFormatLogToList(stdout)
  263. }
  264. // FilesCountBetween return the number of files changed between two commits
  265. func (repo *Repository) FilesCountBetween(startCommitID, endCommitID string) (int, error) {
  266. stdout, err := NewCommand("diff", "--name-only", startCommitID+"..."+endCommitID).RunInDir(repo.Path)
  267. if err != nil {
  268. return 0, err
  269. }
  270. return len(strings.Split(stdout, "\n")) - 1, nil
  271. }
  272. // CommitsBetween returns a list that contains commits between [last, before).
  273. func (repo *Repository) CommitsBetween(last *Commit, before *Commit) (*list.List, error) {
  274. stdout, err := NewCommand("rev-list", before.ID.String()+"..."+last.ID.String()).RunInDirBytes(repo.Path)
  275. if err != nil {
  276. return nil, err
  277. }
  278. return repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout))
  279. }
  280. // CommitsBetweenIDs return commits between twoe commits
  281. func (repo *Repository) CommitsBetweenIDs(last, before string) (*list.List, error) {
  282. lastCommit, err := repo.GetCommit(last)
  283. if err != nil {
  284. return nil, err
  285. }
  286. beforeCommit, err := repo.GetCommit(before)
  287. if err != nil {
  288. return nil, err
  289. }
  290. return repo.CommitsBetween(lastCommit, beforeCommit)
  291. }
  292. // CommitsCountBetween return numbers of commits between two commits
  293. func (repo *Repository) CommitsCountBetween(start, end string) (int64, error) {
  294. return commitsCount(repo.Path, start+"..."+end, "")
  295. }
  296. // commitsBefore the limit is depth, not total number of returned commits.
  297. func (repo *Repository) commitsBefore(id SHA1, limit int) (*list.List, error) {
  298. cmd := NewCommand("log")
  299. if limit > 0 {
  300. cmd.AddArguments("-"+strconv.Itoa(limit), prettyLogFormat, id.String())
  301. } else {
  302. cmd.AddArguments(prettyLogFormat, id.String())
  303. }
  304. stdout, err := cmd.RunInDirBytes(repo.Path)
  305. if err != nil {
  306. return nil, err
  307. }
  308. formattedLog, err := repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout))
  309. if err != nil {
  310. return nil, err
  311. }
  312. commits := list.New()
  313. for logEntry := formattedLog.Front(); logEntry != nil; logEntry = logEntry.Next() {
  314. commit := logEntry.Value.(*Commit)
  315. branches, err := repo.getBranches(commit, 2)
  316. if err != nil {
  317. return nil, err
  318. }
  319. if len(branches) > 1 {
  320. break
  321. }
  322. commits.PushBack(commit)
  323. }
  324. return commits, nil
  325. }
  326. func (repo *Repository) getCommitsBefore(id SHA1) (*list.List, error) {
  327. return repo.commitsBefore(id, 0)
  328. }
  329. func (repo *Repository) getCommitsBeforeLimit(id SHA1, num int) (*list.List, error) {
  330. return repo.commitsBefore(id, num)
  331. }
  332. func (repo *Repository) getBranches(commit *Commit, limit int) ([]string, error) {
  333. if version.Compare(gitVersion, "2.7.0", ">=") {
  334. stdout, err := NewCommand("for-each-ref", "--count="+strconv.Itoa(limit), "--format=%(refname:strip=2)", "--contains", commit.ID.String(), BranchPrefix).RunInDir(repo.Path)
  335. if err != nil {
  336. return nil, err
  337. }
  338. branches := strings.Fields(stdout)
  339. return branches, nil
  340. }
  341. stdout, err := NewCommand("branch", "--contains", commit.ID.String()).RunInDir(repo.Path)
  342. if err != nil {
  343. return nil, err
  344. }
  345. refs := strings.Split(stdout, "\n")
  346. var max int
  347. if len(refs) > limit {
  348. max = limit
  349. } else {
  350. max = len(refs) - 1
  351. }
  352. branches := make([]string, max)
  353. for i, ref := range refs[:max] {
  354. parts := strings.Fields(ref)
  355. branches[i] = parts[len(parts)-1]
  356. }
  357. return branches, nil
  358. }
上海开阖软件有限公司 沪ICP备12045867号-1