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.

commit.go 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2018 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. "bufio"
  8. "bytes"
  9. "container/list"
  10. "fmt"
  11. "io"
  12. "net/http"
  13. "strconv"
  14. "strings"
  15. "gopkg.in/src-d/go-git.v4/plumbing/object"
  16. )
  17. // Commit represents a git commit.
  18. type Commit struct {
  19. Branch string // Branch this commit belongs to
  20. Tree
  21. ID SHA1 // The ID of this commit object
  22. Author *Signature
  23. Committer *Signature
  24. CommitMessage string
  25. Signature *CommitGPGSignature
  26. parents []SHA1 // SHA1 strings
  27. submoduleCache *ObjectCache
  28. }
  29. // CommitGPGSignature represents a git commit signature part.
  30. type CommitGPGSignature struct {
  31. Signature string
  32. Payload string //TODO check if can be reconstruct from the rest of commit information to not have duplicate data
  33. }
  34. func convertPGPSignature(c *object.Commit) *CommitGPGSignature {
  35. if c.PGPSignature == "" {
  36. return nil
  37. }
  38. var w strings.Builder
  39. var err error
  40. if _, err = fmt.Fprintf(&w, "tree %s\n", c.TreeHash.String()); err != nil {
  41. return nil
  42. }
  43. for _, parent := range c.ParentHashes {
  44. if _, err = fmt.Fprintf(&w, "parent %s\n", parent.String()); err != nil {
  45. return nil
  46. }
  47. }
  48. if _, err = fmt.Fprint(&w, "author "); err != nil {
  49. return nil
  50. }
  51. if err = c.Author.Encode(&w); err != nil {
  52. return nil
  53. }
  54. if _, err = fmt.Fprint(&w, "\ncommitter "); err != nil {
  55. return nil
  56. }
  57. if err = c.Committer.Encode(&w); err != nil {
  58. return nil
  59. }
  60. if _, err = fmt.Fprintf(&w, "\n\n%s", c.Message); err != nil {
  61. return nil
  62. }
  63. return &CommitGPGSignature{
  64. Signature: c.PGPSignature,
  65. Payload: w.String(),
  66. }
  67. }
  68. func convertCommit(c *object.Commit) *Commit {
  69. return &Commit{
  70. ID: c.Hash,
  71. CommitMessage: c.Message,
  72. Committer: &c.Committer,
  73. Author: &c.Author,
  74. Signature: convertPGPSignature(c),
  75. parents: c.ParentHashes,
  76. }
  77. }
  78. // Message returns the commit message. Same as retrieving CommitMessage directly.
  79. func (c *Commit) Message() string {
  80. return c.CommitMessage
  81. }
  82. // Summary returns first line of commit message.
  83. func (c *Commit) Summary() string {
  84. return strings.Split(strings.TrimSpace(c.CommitMessage), "\n")[0]
  85. }
  86. // ParentID returns oid of n-th parent (0-based index).
  87. // It returns nil if no such parent exists.
  88. func (c *Commit) ParentID(n int) (SHA1, error) {
  89. if n >= len(c.parents) {
  90. return SHA1{}, ErrNotExist{"", ""}
  91. }
  92. return c.parents[n], nil
  93. }
  94. // Parent returns n-th parent (0-based index) of the commit.
  95. func (c *Commit) Parent(n int) (*Commit, error) {
  96. id, err := c.ParentID(n)
  97. if err != nil {
  98. return nil, err
  99. }
  100. parent, err := c.repo.getCommit(id)
  101. if err != nil {
  102. return nil, err
  103. }
  104. return parent, nil
  105. }
  106. // ParentCount returns number of parents of the commit.
  107. // 0 if this is the root commit, otherwise 1,2, etc.
  108. func (c *Commit) ParentCount() int {
  109. return len(c.parents)
  110. }
  111. func isImageFile(data []byte) (string, bool) {
  112. contentType := http.DetectContentType(data)
  113. if strings.Contains(contentType, "image/") {
  114. return contentType, true
  115. }
  116. return contentType, false
  117. }
  118. // IsImageFile is a file image type
  119. func (c *Commit) IsImageFile(name string) bool {
  120. blob, err := c.GetBlobByPath(name)
  121. if err != nil {
  122. return false
  123. }
  124. dataRc, err := blob.DataAsync()
  125. if err != nil {
  126. return false
  127. }
  128. defer dataRc.Close()
  129. buf := make([]byte, 1024)
  130. n, _ := dataRc.Read(buf)
  131. buf = buf[:n]
  132. _, isImage := isImageFile(buf)
  133. return isImage
  134. }
  135. // GetCommitByPath return the commit of relative path object.
  136. func (c *Commit) GetCommitByPath(relpath string) (*Commit, error) {
  137. return c.repo.getCommitByPathWithID(c.ID, relpath)
  138. }
  139. // AddChanges marks local changes to be ready for commit.
  140. func AddChanges(repoPath string, all bool, files ...string) error {
  141. cmd := NewCommand("add")
  142. if all {
  143. cmd.AddArguments("--all")
  144. }
  145. _, err := cmd.AddArguments(files...).RunInDir(repoPath)
  146. return err
  147. }
  148. // CommitChangesOptions the options when a commit created
  149. type CommitChangesOptions struct {
  150. Committer *Signature
  151. Author *Signature
  152. Message string
  153. }
  154. // CommitChanges commits local changes with given committer, author and message.
  155. // If author is nil, it will be the same as committer.
  156. func CommitChanges(repoPath string, opts CommitChangesOptions) error {
  157. cmd := NewCommand()
  158. if opts.Committer != nil {
  159. cmd.AddArguments("-c", "user.name="+opts.Committer.Name, "-c", "user.email="+opts.Committer.Email)
  160. }
  161. cmd.AddArguments("commit")
  162. if opts.Author == nil {
  163. opts.Author = opts.Committer
  164. }
  165. if opts.Author != nil {
  166. cmd.AddArguments(fmt.Sprintf("--author='%s <%s>'", opts.Author.Name, opts.Author.Email))
  167. }
  168. cmd.AddArguments("-m", opts.Message)
  169. _, err := cmd.RunInDir(repoPath)
  170. // No stderr but exit status 1 means nothing to commit.
  171. if err != nil && err.Error() == "exit status 1" {
  172. return nil
  173. }
  174. return err
  175. }
  176. func commitsCount(repoPath, revision, relpath string) (int64, error) {
  177. cmd := NewCommand("rev-list", "--count")
  178. cmd.AddArguments(revision)
  179. if len(relpath) > 0 {
  180. cmd.AddArguments("--", relpath)
  181. }
  182. stdout, err := cmd.RunInDir(repoPath)
  183. if err != nil {
  184. return 0, err
  185. }
  186. return strconv.ParseInt(strings.TrimSpace(stdout), 10, 64)
  187. }
  188. // CommitsCount returns number of total commits of until given revision.
  189. func CommitsCount(repoPath, revision string) (int64, error) {
  190. return commitsCount(repoPath, revision, "")
  191. }
  192. // CommitsCount returns number of total commits of until current revision.
  193. func (c *Commit) CommitsCount() (int64, error) {
  194. return CommitsCount(c.repo.Path, c.ID.String())
  195. }
  196. // CommitsByRange returns the specific page commits before current revision, every page's number default by CommitsRangeSize
  197. func (c *Commit) CommitsByRange(page int) (*list.List, error) {
  198. return c.repo.commitsByRange(c.ID, page)
  199. }
  200. // CommitsBefore returns all the commits before current revision
  201. func (c *Commit) CommitsBefore() (*list.List, error) {
  202. return c.repo.getCommitsBefore(c.ID)
  203. }
  204. // CommitsBeforeLimit returns num commits before current revision
  205. func (c *Commit) CommitsBeforeLimit(num int) (*list.List, error) {
  206. return c.repo.getCommitsBeforeLimit(c.ID, num)
  207. }
  208. // CommitsBeforeUntil returns the commits between commitID to current revision
  209. func (c *Commit) CommitsBeforeUntil(commitID string) (*list.List, error) {
  210. endCommit, err := c.repo.GetCommit(commitID)
  211. if err != nil {
  212. return nil, err
  213. }
  214. return c.repo.CommitsBetween(c, endCommit)
  215. }
  216. // SearchCommitsOptions specify the parameters for SearchCommits
  217. type SearchCommitsOptions struct {
  218. Keywords []string
  219. Authors, Committers []string
  220. After, Before string
  221. All bool
  222. }
  223. // NewSearchCommitsOptions construct a SearchCommitsOption from a space-delimited search string
  224. func NewSearchCommitsOptions(searchString string, forAllRefs bool) SearchCommitsOptions {
  225. var keywords, authors, committers []string
  226. var after, before string
  227. fields := strings.Fields(searchString)
  228. for _, k := range fields {
  229. switch {
  230. case strings.HasPrefix(k, "author:"):
  231. authors = append(authors, strings.TrimPrefix(k, "author:"))
  232. case strings.HasPrefix(k, "committer:"):
  233. committers = append(committers, strings.TrimPrefix(k, "committer:"))
  234. case strings.HasPrefix(k, "after:"):
  235. after = strings.TrimPrefix(k, "after:")
  236. case strings.HasPrefix(k, "before:"):
  237. before = strings.TrimPrefix(k, "before:")
  238. default:
  239. keywords = append(keywords, k)
  240. }
  241. }
  242. return SearchCommitsOptions{
  243. Keywords: keywords,
  244. Authors: authors,
  245. Committers: committers,
  246. After: after,
  247. Before: before,
  248. All: forAllRefs,
  249. }
  250. }
  251. // SearchCommits returns the commits match the keyword before current revision
  252. func (c *Commit) SearchCommits(opts SearchCommitsOptions) (*list.List, error) {
  253. return c.repo.searchCommits(c.ID, opts)
  254. }
  255. // GetFilesChangedSinceCommit get all changed file names between pastCommit to current revision
  256. func (c *Commit) GetFilesChangedSinceCommit(pastCommit string) ([]string, error) {
  257. return c.repo.getFilesChanged(pastCommit, c.ID.String())
  258. }
  259. // FileChangedSinceCommit Returns true if the file given has changed since the the past commit
  260. func (c *Commit) FileChangedSinceCommit(filename, pastCommit string) (bool, error) {
  261. return c.repo.FileChangedBetweenCommits(filename, pastCommit, c.ID.String())
  262. }
  263. // GetSubModules get all the sub modules of current revision git tree
  264. func (c *Commit) GetSubModules() (*ObjectCache, error) {
  265. if c.submoduleCache != nil {
  266. return c.submoduleCache, nil
  267. }
  268. entry, err := c.GetTreeEntryByPath(".gitmodules")
  269. if err != nil {
  270. if _, ok := err.(ErrNotExist); ok {
  271. return nil, nil
  272. }
  273. return nil, err
  274. }
  275. rd, err := entry.Blob().DataAsync()
  276. if err != nil {
  277. return nil, err
  278. }
  279. defer rd.Close()
  280. scanner := bufio.NewScanner(rd)
  281. c.submoduleCache = newObjectCache()
  282. var ismodule bool
  283. var path string
  284. for scanner.Scan() {
  285. if strings.HasPrefix(scanner.Text(), "[submodule") {
  286. ismodule = true
  287. continue
  288. }
  289. if ismodule {
  290. fields := strings.Split(scanner.Text(), "=")
  291. k := strings.TrimSpace(fields[0])
  292. if k == "path" {
  293. path = strings.TrimSpace(fields[1])
  294. } else if k == "url" {
  295. c.submoduleCache.Set(path, &SubModule{path, strings.TrimSpace(fields[1])})
  296. ismodule = false
  297. }
  298. }
  299. }
  300. return c.submoduleCache, nil
  301. }
  302. // GetSubModule get the sub module according entryname
  303. func (c *Commit) GetSubModule(entryname string) (*SubModule, error) {
  304. modules, err := c.GetSubModules()
  305. if err != nil {
  306. return nil, err
  307. }
  308. if modules != nil {
  309. module, has := modules.Get(entryname)
  310. if has {
  311. return module.(*SubModule), nil
  312. }
  313. }
  314. return nil, nil
  315. }
  316. // GetBranchName gets the closes branch name (as returned by 'git name-rev')
  317. func (c *Commit) GetBranchName() (string, error) {
  318. data, err := NewCommand("name-rev", c.ID.String()).RunInDirBytes(c.repo.Path)
  319. if err != nil {
  320. return "", err
  321. }
  322. // name-rev commitID output will be "COMMIT_ID master" or "COMMIT_ID master~12"
  323. return strings.Split(strings.Split(string(data), " ")[1], "~")[0], nil
  324. }
  325. // CommitFileStatus represents status of files in a commit.
  326. type CommitFileStatus struct {
  327. Added []string
  328. Removed []string
  329. Modified []string
  330. }
  331. // NewCommitFileStatus creates a CommitFileStatus
  332. func NewCommitFileStatus() *CommitFileStatus {
  333. return &CommitFileStatus{
  334. []string{}, []string{}, []string{},
  335. }
  336. }
  337. // GetCommitFileStatus returns file status of commit in given repository.
  338. func GetCommitFileStatus(repoPath, commitID string) (*CommitFileStatus, error) {
  339. stdout, w := io.Pipe()
  340. done := make(chan struct{})
  341. fileStatus := NewCommitFileStatus()
  342. go func() {
  343. scanner := bufio.NewScanner(stdout)
  344. for scanner.Scan() {
  345. fields := strings.Fields(scanner.Text())
  346. if len(fields) < 2 {
  347. continue
  348. }
  349. switch fields[0][0] {
  350. case 'A':
  351. fileStatus.Added = append(fileStatus.Added, fields[1])
  352. case 'D':
  353. fileStatus.Removed = append(fileStatus.Removed, fields[1])
  354. case 'M':
  355. fileStatus.Modified = append(fileStatus.Modified, fields[1])
  356. }
  357. }
  358. done <- struct{}{}
  359. }()
  360. stderr := new(bytes.Buffer)
  361. err := NewCommand("show", "--name-status", "--pretty=format:''", commitID).RunInDirPipeline(repoPath, w, stderr)
  362. w.Close() // Close writer to exit parsing goroutine
  363. if err != nil {
  364. return nil, concatenateError(err, stderr.String())
  365. }
  366. <-done
  367. return fileStatus, nil
  368. }
  369. // GetFullCommitID returns full length (40) of commit ID by given short SHA in a repository.
  370. func GetFullCommitID(repoPath, shortID string) (string, error) {
  371. if len(shortID) >= 40 {
  372. return shortID, nil
  373. }
  374. commitID, err := NewCommand("rev-parse", shortID).RunInDir(repoPath)
  375. if err != nil {
  376. if strings.Contains(err.Error(), "exit status 128") {
  377. return "", ErrNotExist{shortID, ""}
  378. }
  379. return "", err
  380. }
  381. return strings.TrimSpace(commitID), nil
  382. }