Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

repo_commit.go 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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, pageSize int) (*list.List, error) {
  167. stdout, err := NewCommand("log", id.String(), "--skip="+strconv.Itoa((page-1)*pageSize),
  168. "--max-count="+strconv.Itoa(pageSize), 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. var stdout []byte
  275. var err error
  276. if before == nil {
  277. stdout, err = NewCommand("rev-list", last.ID.String()).RunInDirBytes(repo.Path)
  278. } else {
  279. stdout, err = NewCommand("rev-list", before.ID.String()+"..."+last.ID.String()).RunInDirBytes(repo.Path)
  280. }
  281. if err != nil {
  282. return nil, err
  283. }
  284. return repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout))
  285. }
  286. // CommitsBetweenLimit returns a list that contains at most limit commits skipping the first skip commits between [last, before)
  287. func (repo *Repository) CommitsBetweenLimit(last *Commit, before *Commit, limit, skip int) (*list.List, error) {
  288. var stdout []byte
  289. var err error
  290. if before == nil {
  291. stdout, err = NewCommand("rev-list", "--max-count", strconv.Itoa(limit), "--skip", strconv.Itoa(skip), last.ID.String()).RunInDirBytes(repo.Path)
  292. } else {
  293. stdout, err = NewCommand("rev-list", "--max-count", strconv.Itoa(limit), "--skip", strconv.Itoa(skip), before.ID.String()+"..."+last.ID.String()).RunInDirBytes(repo.Path)
  294. }
  295. if err != nil {
  296. return nil, err
  297. }
  298. return repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout))
  299. }
  300. // CommitsBetweenIDs return commits between twoe commits
  301. func (repo *Repository) CommitsBetweenIDs(last, before string) (*list.List, error) {
  302. lastCommit, err := repo.GetCommit(last)
  303. if err != nil {
  304. return nil, err
  305. }
  306. if before == "" {
  307. return repo.CommitsBetween(lastCommit, nil)
  308. }
  309. beforeCommit, err := repo.GetCommit(before)
  310. if err != nil {
  311. return nil, err
  312. }
  313. return repo.CommitsBetween(lastCommit, beforeCommit)
  314. }
  315. // CommitsCountBetween return numbers of commits between two commits
  316. func (repo *Repository) CommitsCountBetween(start, end string) (int64, error) {
  317. return commitsCount(repo.Path, start+"..."+end, "")
  318. }
  319. // commitsBefore the limit is depth, not total number of returned commits.
  320. func (repo *Repository) commitsBefore(id SHA1, limit int) (*list.List, error) {
  321. cmd := NewCommand("log")
  322. if limit > 0 {
  323. cmd.AddArguments("-"+strconv.Itoa(limit), prettyLogFormat, id.String())
  324. } else {
  325. cmd.AddArguments(prettyLogFormat, id.String())
  326. }
  327. stdout, err := cmd.RunInDirBytes(repo.Path)
  328. if err != nil {
  329. return nil, err
  330. }
  331. formattedLog, err := repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout))
  332. if err != nil {
  333. return nil, err
  334. }
  335. commits := list.New()
  336. for logEntry := formattedLog.Front(); logEntry != nil; logEntry = logEntry.Next() {
  337. commit := logEntry.Value.(*Commit)
  338. branches, err := repo.getBranches(commit, 2)
  339. if err != nil {
  340. return nil, err
  341. }
  342. if len(branches) > 1 {
  343. break
  344. }
  345. commits.PushBack(commit)
  346. }
  347. return commits, nil
  348. }
  349. func (repo *Repository) getCommitsBefore(id SHA1) (*list.List, error) {
  350. return repo.commitsBefore(id, 0)
  351. }
  352. func (repo *Repository) getCommitsBeforeLimit(id SHA1, num int) (*list.List, error) {
  353. return repo.commitsBefore(id, num)
  354. }
  355. func (repo *Repository) getBranches(commit *Commit, limit int) ([]string, error) {
  356. if version.Compare(gitVersion, "2.7.0", ">=") {
  357. stdout, err := NewCommand("for-each-ref", "--count="+strconv.Itoa(limit), "--format=%(refname:strip=2)", "--contains", commit.ID.String(), BranchPrefix).RunInDir(repo.Path)
  358. if err != nil {
  359. return nil, err
  360. }
  361. branches := strings.Fields(stdout)
  362. return branches, nil
  363. }
  364. stdout, err := NewCommand("branch", "--contains", commit.ID.String()).RunInDir(repo.Path)
  365. if err != nil {
  366. return nil, err
  367. }
  368. refs := strings.Split(stdout, "\n")
  369. var max int
  370. if len(refs) > limit {
  371. max = limit
  372. } else {
  373. max = len(refs) - 1
  374. }
  375. branches := make([]string, max)
  376. for i, ref := range refs[:max] {
  377. parts := strings.Fields(ref)
  378. branches[i] = parts[len(parts)-1]
  379. }
  380. return branches, nil
  381. }