Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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/go-git/go-git/v5/plumbing"
  13. "github.com/go-git/go-git/v5/plumbing/object"
  14. "github.com/mcuadros/go-version"
  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. if err == plumbing.ErrReferenceNotFound {
  21. return "", ErrNotExist{
  22. ID: name,
  23. }
  24. }
  25. return "", err
  26. }
  27. return ref.Hash().String(), nil
  28. }
  29. // IsCommitExist returns true if given commit exists in current repository.
  30. func (repo *Repository) IsCommitExist(name string) bool {
  31. hash := plumbing.NewHash(name)
  32. _, err := repo.gogitRepo.CommitObject(hash)
  33. return err == nil
  34. }
  35. // GetBranchCommitID returns last commit ID string of given branch.
  36. func (repo *Repository) GetBranchCommitID(name string) (string, error) {
  37. return repo.GetRefCommitID(BranchPrefix + name)
  38. }
  39. // GetTagCommitID returns last commit ID string of given tag.
  40. func (repo *Repository) GetTagCommitID(name string) (string, error) {
  41. stdout, err := NewCommand("rev-list", "-n", "1", name).RunInDir(repo.Path)
  42. if err != nil {
  43. if strings.Contains(err.Error(), "unknown revision or path") {
  44. return "", ErrNotExist{name, ""}
  45. }
  46. return "", err
  47. }
  48. return strings.TrimSpace(stdout), nil
  49. }
  50. func convertPGPSignatureForTag(t *object.Tag) *CommitGPGSignature {
  51. if t.PGPSignature == "" {
  52. return nil
  53. }
  54. var w strings.Builder
  55. var err error
  56. if _, err = fmt.Fprintf(&w,
  57. "object %s\ntype %s\ntag %s\ntagger ",
  58. t.Target.String(), t.TargetType.Bytes(), t.Name); err != nil {
  59. return nil
  60. }
  61. if err = t.Tagger.Encode(&w); err != nil {
  62. return nil
  63. }
  64. if _, err = fmt.Fprintf(&w, "\n\n"); err != nil {
  65. return nil
  66. }
  67. if _, err = fmt.Fprintf(&w, t.Message); err != nil {
  68. return nil
  69. }
  70. return &CommitGPGSignature{
  71. Signature: t.PGPSignature,
  72. Payload: strings.TrimSpace(w.String()) + "\n",
  73. }
  74. }
  75. func (repo *Repository) getCommit(id SHA1) (*Commit, error) {
  76. var tagObject *object.Tag
  77. gogitCommit, err := repo.gogitRepo.CommitObject(id)
  78. if err == plumbing.ErrObjectNotFound {
  79. tagObject, err = repo.gogitRepo.TagObject(id)
  80. if err == plumbing.ErrObjectNotFound {
  81. return nil, ErrNotExist{
  82. ID: id.String(),
  83. }
  84. }
  85. if err == nil {
  86. gogitCommit, err = repo.gogitRepo.CommitObject(tagObject.Target)
  87. }
  88. // if we get a plumbing.ErrObjectNotFound here then the repository is broken and it should be 500
  89. }
  90. if err != nil {
  91. return nil, err
  92. }
  93. commit := convertCommit(gogitCommit)
  94. commit.repo = repo
  95. if tagObject != nil {
  96. commit.CommitMessage = strings.TrimSpace(tagObject.Message)
  97. commit.Author = &tagObject.Tagger
  98. commit.Signature = convertPGPSignatureForTag(tagObject)
  99. }
  100. tree, err := gogitCommit.Tree()
  101. if err != nil {
  102. return nil, err
  103. }
  104. commit.Tree.ID = tree.Hash
  105. commit.Tree.gogitTree = tree
  106. return commit, nil
  107. }
  108. // ConvertToSHA1 returns a Hash object from a potential ID string
  109. func (repo *Repository) ConvertToSHA1(commitID string) (SHA1, error) {
  110. if len(commitID) != 40 {
  111. var err error
  112. actualCommitID, err := NewCommand("rev-parse", "--verify", commitID).RunInDir(repo.Path)
  113. if err != nil {
  114. if strings.Contains(err.Error(), "unknown revision or path") ||
  115. strings.Contains(err.Error(), "fatal: Needed a single revision") {
  116. return SHA1{}, ErrNotExist{commitID, ""}
  117. }
  118. return SHA1{}, err
  119. }
  120. commitID = actualCommitID
  121. }
  122. return NewIDFromString(commitID)
  123. }
  124. // GetCommit returns commit object of by ID string.
  125. func (repo *Repository) GetCommit(commitID string) (*Commit, error) {
  126. id, err := repo.ConvertToSHA1(commitID)
  127. if err != nil {
  128. return nil, err
  129. }
  130. return repo.getCommit(id)
  131. }
  132. // GetBranchCommit returns the last commit of given branch.
  133. func (repo *Repository) GetBranchCommit(name string) (*Commit, error) {
  134. commitID, err := repo.GetBranchCommitID(name)
  135. if err != nil {
  136. return nil, err
  137. }
  138. return repo.GetCommit(commitID)
  139. }
  140. // GetTagCommit get the commit of the specific tag via name
  141. func (repo *Repository) GetTagCommit(name string) (*Commit, error) {
  142. commitID, err := repo.GetTagCommitID(name)
  143. if err != nil {
  144. return nil, err
  145. }
  146. return repo.GetCommit(commitID)
  147. }
  148. func (repo *Repository) getCommitByPathWithID(id SHA1, relpath string) (*Commit, error) {
  149. // File name starts with ':' must be escaped.
  150. if relpath[0] == ':' {
  151. relpath = `\` + relpath
  152. }
  153. stdout, err := NewCommand("log", "-1", prettyLogFormat, id.String(), "--", relpath).RunInDir(repo.Path)
  154. if err != nil {
  155. return nil, err
  156. }
  157. id, err = NewIDFromString(stdout)
  158. if err != nil {
  159. return nil, err
  160. }
  161. return repo.getCommit(id)
  162. }
  163. // GetCommitByPath returns the last commit of relative path.
  164. func (repo *Repository) GetCommitByPath(relpath string) (*Commit, error) {
  165. stdout, err := NewCommand("log", "-1", prettyLogFormat, "--", relpath).RunInDirBytes(repo.Path)
  166. if err != nil {
  167. return nil, err
  168. }
  169. commits, err := repo.parsePrettyFormatLogToList(stdout)
  170. if err != nil {
  171. return nil, err
  172. }
  173. return commits.Front().Value.(*Commit), nil
  174. }
  175. // CommitsRangeSize the default commits range size
  176. var CommitsRangeSize = 50
  177. func (repo *Repository) commitsByRange(id SHA1, page int) (*list.List, error) {
  178. stdout, err := NewCommand("log", id.String(), "--skip="+strconv.Itoa((page-1)*CommitsRangeSize),
  179. "--max-count="+strconv.Itoa(CommitsRangeSize), prettyLogFormat).RunInDirBytes(repo.Path)
  180. if err != nil {
  181. return nil, err
  182. }
  183. return repo.parsePrettyFormatLogToList(stdout)
  184. }
  185. func (repo *Repository) searchCommits(id SHA1, opts SearchCommitsOptions) (*list.List, error) {
  186. cmd := NewCommand("log", id.String(), "-100", prettyLogFormat)
  187. args := []string{"-i"}
  188. if len(opts.Authors) > 0 {
  189. for _, v := range opts.Authors {
  190. args = append(args, "--author="+v)
  191. }
  192. }
  193. if len(opts.Committers) > 0 {
  194. for _, v := range opts.Committers {
  195. args = append(args, "--committer="+v)
  196. }
  197. }
  198. if len(opts.After) > 0 {
  199. args = append(args, "--after="+opts.After)
  200. }
  201. if len(opts.Before) > 0 {
  202. args = append(args, "--before="+opts.Before)
  203. }
  204. if opts.All {
  205. args = append(args, "--all")
  206. }
  207. if len(opts.Keywords) > 0 {
  208. for _, v := range opts.Keywords {
  209. cmd.AddArguments("--grep=" + v)
  210. }
  211. }
  212. cmd.AddArguments(args...)
  213. stdout, err := cmd.RunInDirBytes(repo.Path)
  214. if err != nil {
  215. return nil, err
  216. }
  217. if len(stdout) != 0 {
  218. stdout = append(stdout, '\n')
  219. }
  220. if len(opts.Keywords) > 0 {
  221. for _, v := range opts.Keywords {
  222. if len(v) >= 4 {
  223. hashCmd := NewCommand("log", "-1", prettyLogFormat)
  224. hashCmd.AddArguments(args...)
  225. hashCmd.AddArguments(v)
  226. hashMatching, err := hashCmd.RunInDirBytes(repo.Path)
  227. if err != nil || bytes.Contains(stdout, hashMatching) {
  228. continue
  229. }
  230. stdout = append(stdout, hashMatching...)
  231. stdout = append(stdout, '\n')
  232. }
  233. }
  234. }
  235. return repo.parsePrettyFormatLogToList(bytes.TrimSuffix(stdout, []byte{'\n'}))
  236. }
  237. func (repo *Repository) getFilesChanged(id1, id2 string) ([]string, error) {
  238. stdout, err := NewCommand("diff", "--name-only", id1, id2).RunInDirBytes(repo.Path)
  239. if err != nil {
  240. return nil, err
  241. }
  242. return strings.Split(string(stdout), "\n"), nil
  243. }
  244. // FileChangedBetweenCommits Returns true if the file changed between commit IDs id1 and id2
  245. // You must ensure that id1 and id2 are valid commit ids.
  246. func (repo *Repository) FileChangedBetweenCommits(filename, id1, id2 string) (bool, error) {
  247. stdout, err := NewCommand("diff", "--name-only", "-z", id1, id2, "--", filename).RunInDirBytes(repo.Path)
  248. if err != nil {
  249. return false, err
  250. }
  251. return len(strings.TrimSpace(string(stdout))) > 0, nil
  252. }
  253. // FileCommitsCount return the number of files at a revison
  254. func (repo *Repository) FileCommitsCount(revision, file string) (int64, error) {
  255. return commitsCount(repo.Path, revision, file)
  256. }
  257. // CommitsByFileAndRange return the commits according revison file and the page
  258. func (repo *Repository) CommitsByFileAndRange(revision, file string, page int) (*list.List, error) {
  259. stdout, err := NewCommand("log", revision, "--follow", "--skip="+strconv.Itoa((page-1)*50),
  260. "--max-count="+strconv.Itoa(CommitsRangeSize), prettyLogFormat, "--", file).RunInDirBytes(repo.Path)
  261. if err != nil {
  262. return nil, err
  263. }
  264. return repo.parsePrettyFormatLogToList(stdout)
  265. }
  266. // CommitsByFileAndRangeNoFollow return the commits according revison file and the page
  267. func (repo *Repository) CommitsByFileAndRangeNoFollow(revision, file string, page int) (*list.List, error) {
  268. stdout, err := NewCommand("log", revision, "--skip="+strconv.Itoa((page-1)*50),
  269. "--max-count="+strconv.Itoa(CommitsRangeSize), prettyLogFormat, "--", file).RunInDirBytes(repo.Path)
  270. if err != nil {
  271. return nil, err
  272. }
  273. return repo.parsePrettyFormatLogToList(stdout)
  274. }
  275. // FilesCountBetween return the number of files changed between two commits
  276. func (repo *Repository) FilesCountBetween(startCommitID, endCommitID string) (int, error) {
  277. stdout, err := NewCommand("diff", "--name-only", startCommitID+"..."+endCommitID).RunInDir(repo.Path)
  278. if err != nil {
  279. return 0, err
  280. }
  281. return len(strings.Split(stdout, "\n")) - 1, nil
  282. }
  283. // CommitsBetween returns a list that contains commits between [last, before).
  284. func (repo *Repository) CommitsBetween(last *Commit, before *Commit) (*list.List, error) {
  285. var stdout []byte
  286. var err error
  287. if before == nil {
  288. stdout, err = NewCommand("rev-list", last.ID.String()).RunInDirBytes(repo.Path)
  289. } else {
  290. stdout, err = NewCommand("rev-list", before.ID.String()+"..."+last.ID.String()).RunInDirBytes(repo.Path)
  291. }
  292. if err != nil {
  293. return nil, err
  294. }
  295. return repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout))
  296. }
  297. // CommitsBetweenLimit returns a list that contains at most limit commits skipping the first skip commits between [last, before)
  298. func (repo *Repository) CommitsBetweenLimit(last *Commit, before *Commit, limit, skip int) (*list.List, error) {
  299. var stdout []byte
  300. var err error
  301. if before == nil {
  302. stdout, err = NewCommand("rev-list", "--max-count", strconv.Itoa(limit), "--skip", strconv.Itoa(skip), last.ID.String()).RunInDirBytes(repo.Path)
  303. } else {
  304. stdout, err = NewCommand("rev-list", "--max-count", strconv.Itoa(limit), "--skip", strconv.Itoa(skip), before.ID.String()+"..."+last.ID.String()).RunInDirBytes(repo.Path)
  305. }
  306. if err != nil {
  307. return nil, err
  308. }
  309. return repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout))
  310. }
  311. // CommitsBetweenIDs return commits between twoe commits
  312. func (repo *Repository) CommitsBetweenIDs(last, before string) (*list.List, error) {
  313. lastCommit, err := repo.GetCommit(last)
  314. if err != nil {
  315. return nil, err
  316. }
  317. if before == "" {
  318. return repo.CommitsBetween(lastCommit, nil)
  319. }
  320. beforeCommit, err := repo.GetCommit(before)
  321. if err != nil {
  322. return nil, err
  323. }
  324. return repo.CommitsBetween(lastCommit, beforeCommit)
  325. }
  326. // CommitsCountBetween return numbers of commits between two commits
  327. func (repo *Repository) CommitsCountBetween(start, end string) (int64, error) {
  328. return commitsCount(repo.Path, start+"..."+end, "")
  329. }
  330. // commitsBefore the limit is depth, not total number of returned commits.
  331. func (repo *Repository) commitsBefore(id SHA1, limit int) (*list.List, error) {
  332. cmd := NewCommand("log")
  333. if limit > 0 {
  334. cmd.AddArguments("-"+strconv.Itoa(limit), prettyLogFormat, id.String())
  335. } else {
  336. cmd.AddArguments(prettyLogFormat, id.String())
  337. }
  338. stdout, err := cmd.RunInDirBytes(repo.Path)
  339. if err != nil {
  340. return nil, err
  341. }
  342. formattedLog, err := repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout))
  343. if err != nil {
  344. return nil, err
  345. }
  346. commits := list.New()
  347. for logEntry := formattedLog.Front(); logEntry != nil; logEntry = logEntry.Next() {
  348. commit := logEntry.Value.(*Commit)
  349. branches, err := repo.getBranches(commit, 2)
  350. if err != nil {
  351. return nil, err
  352. }
  353. if len(branches) > 1 {
  354. break
  355. }
  356. commits.PushBack(commit)
  357. }
  358. return commits, nil
  359. }
  360. func (repo *Repository) getCommitsBefore(id SHA1) (*list.List, error) {
  361. return repo.commitsBefore(id, 0)
  362. }
  363. func (repo *Repository) getCommitsBeforeLimit(id SHA1, num int) (*list.List, error) {
  364. return repo.commitsBefore(id, num)
  365. }
  366. func (repo *Repository) getBranches(commit *Commit, limit int) ([]string, error) {
  367. if version.Compare(gitVersion, "2.7.0", ">=") {
  368. stdout, err := NewCommand("for-each-ref", "--count="+strconv.Itoa(limit), "--format=%(refname:strip=2)", "--contains", commit.ID.String(), BranchPrefix).RunInDir(repo.Path)
  369. if err != nil {
  370. return nil, err
  371. }
  372. branches := strings.Fields(stdout)
  373. return branches, nil
  374. }
  375. stdout, err := NewCommand("branch", "--contains", commit.ID.String()).RunInDir(repo.Path)
  376. if err != nil {
  377. return nil, err
  378. }
  379. refs := strings.Split(stdout, "\n")
  380. var max int
  381. if len(refs) > limit {
  382. max = limit
  383. } else {
  384. max = len(refs) - 1
  385. }
  386. branches := make([]string, max)
  387. for i, ref := range refs[:max] {
  388. parts := strings.Fields(ref)
  389. branches[i] = parts[len(parts)-1]
  390. }
  391. return branches, nil
  392. }