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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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.Index(contentType, "image/") != -1 {
  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. var cmd *Command
  178. cmd = NewCommand("rev-list", "--count")
  179. cmd.AddArguments(revision)
  180. if len(relpath) > 0 {
  181. cmd.AddArguments("--", relpath)
  182. }
  183. stdout, err := cmd.RunInDir(repoPath)
  184. if err != nil {
  185. return 0, err
  186. }
  187. return strconv.ParseInt(strings.TrimSpace(stdout), 10, 64)
  188. }
  189. // CommitsCount returns number of total commits of until given revision.
  190. func CommitsCount(repoPath, revision string) (int64, error) {
  191. return commitsCount(repoPath, revision, "")
  192. }
  193. // CommitsCount returns number of total commits of until current revision.
  194. func (c *Commit) CommitsCount() (int64, error) {
  195. return CommitsCount(c.repo.Path, c.ID.String())
  196. }
  197. // CommitsByRange returns the specific page commits before current revision, every page's number default by CommitsRangeSize
  198. func (c *Commit) CommitsByRange(page int) (*list.List, error) {
  199. return c.repo.commitsByRange(c.ID, page)
  200. }
  201. // CommitsBefore returns all the commits before current revision
  202. func (c *Commit) CommitsBefore() (*list.List, error) {
  203. return c.repo.getCommitsBefore(c.ID)
  204. }
  205. // CommitsBeforeLimit returns num commits before current revision
  206. func (c *Commit) CommitsBeforeLimit(num int) (*list.List, error) {
  207. return c.repo.getCommitsBeforeLimit(c.ID, num)
  208. }
  209. // CommitsBeforeUntil returns the commits between commitID to current revision
  210. func (c *Commit) CommitsBeforeUntil(commitID string) (*list.List, error) {
  211. endCommit, err := c.repo.GetCommit(commitID)
  212. if err != nil {
  213. return nil, err
  214. }
  215. return c.repo.CommitsBetween(c, endCommit)
  216. }
  217. // SearchCommitsOptions specify the parameters for SearchCommits
  218. type SearchCommitsOptions struct {
  219. Keywords []string
  220. Authors, Committers []string
  221. After, Before string
  222. All bool
  223. }
  224. // NewSearchCommitsOptions contruct a SearchCommitsOption from a space-delimited search string
  225. func NewSearchCommitsOptions(searchString string, forAllRefs bool) SearchCommitsOptions {
  226. var keywords, authors, committers []string
  227. var after, before string
  228. fields := strings.Fields(searchString)
  229. for _, k := range fields {
  230. switch {
  231. case strings.HasPrefix(k, "author:"):
  232. authors = append(authors, strings.TrimPrefix(k, "author:"))
  233. case strings.HasPrefix(k, "committer:"):
  234. committers = append(committers, strings.TrimPrefix(k, "committer:"))
  235. case strings.HasPrefix(k, "after:"):
  236. after = strings.TrimPrefix(k, "after:")
  237. case strings.HasPrefix(k, "before:"):
  238. before = strings.TrimPrefix(k, "before:")
  239. default:
  240. keywords = append(keywords, k)
  241. }
  242. }
  243. return SearchCommitsOptions{
  244. Keywords: keywords,
  245. Authors: authors,
  246. Committers: committers,
  247. After: after,
  248. Before: before,
  249. All: forAllRefs,
  250. }
  251. }
  252. // SearchCommits returns the commits match the keyword before current revision
  253. func (c *Commit) SearchCommits(opts SearchCommitsOptions) (*list.List, error) {
  254. return c.repo.searchCommits(c.ID, opts)
  255. }
  256. // GetFilesChangedSinceCommit get all changed file names between pastCommit to current revision
  257. func (c *Commit) GetFilesChangedSinceCommit(pastCommit string) ([]string, error) {
  258. return c.repo.getFilesChanged(pastCommit, c.ID.String())
  259. }
  260. // FileChangedSinceCommit Returns true if the file given has changed since the the past commit
  261. func (c *Commit) FileChangedSinceCommit(filename, pastCommit string) (bool, error) {
  262. return c.repo.FileChangedBetweenCommits(filename, pastCommit, c.ID.String())
  263. }
  264. // GetSubModules get all the sub modules of current revision git tree
  265. func (c *Commit) GetSubModules() (*ObjectCache, error) {
  266. if c.submoduleCache != nil {
  267. return c.submoduleCache, nil
  268. }
  269. entry, err := c.GetTreeEntryByPath(".gitmodules")
  270. if err != nil {
  271. if _, ok := err.(ErrNotExist); ok {
  272. return nil, nil
  273. }
  274. return nil, err
  275. }
  276. rd, err := entry.Blob().DataAsync()
  277. if err != nil {
  278. return nil, err
  279. }
  280. defer rd.Close()
  281. scanner := bufio.NewScanner(rd)
  282. c.submoduleCache = newObjectCache()
  283. var ismodule bool
  284. var path string
  285. for scanner.Scan() {
  286. if strings.HasPrefix(scanner.Text(), "[submodule") {
  287. ismodule = true
  288. continue
  289. }
  290. if ismodule {
  291. fields := strings.Split(scanner.Text(), "=")
  292. k := strings.TrimSpace(fields[0])
  293. if k == "path" {
  294. path = strings.TrimSpace(fields[1])
  295. } else if k == "url" {
  296. c.submoduleCache.Set(path, &SubModule{path, strings.TrimSpace(fields[1])})
  297. ismodule = false
  298. }
  299. }
  300. }
  301. return c.submoduleCache, nil
  302. }
  303. // GetSubModule get the sub module according entryname
  304. func (c *Commit) GetSubModule(entryname string) (*SubModule, error) {
  305. modules, err := c.GetSubModules()
  306. if err != nil {
  307. return nil, err
  308. }
  309. if modules != nil {
  310. module, has := modules.Get(entryname)
  311. if has {
  312. return module.(*SubModule), nil
  313. }
  314. }
  315. return nil, nil
  316. }
  317. // GetBranchName gets the closes branch name (as returned by 'git name-rev')
  318. func (c *Commit) GetBranchName() (string, error) {
  319. data, err := NewCommand("name-rev", c.ID.String()).RunInDirBytes(c.repo.Path)
  320. if err != nil {
  321. return "", err
  322. }
  323. // name-rev commitID output will be "COMMIT_ID master" or "COMMIT_ID master~12"
  324. return strings.Split(strings.Split(string(data), " ")[1], "~")[0], nil
  325. }
  326. // CommitFileStatus represents status of files in a commit.
  327. type CommitFileStatus struct {
  328. Added []string
  329. Removed []string
  330. Modified []string
  331. }
  332. // NewCommitFileStatus creates a CommitFileStatus
  333. func NewCommitFileStatus() *CommitFileStatus {
  334. return &CommitFileStatus{
  335. []string{}, []string{}, []string{},
  336. }
  337. }
  338. // GetCommitFileStatus returns file status of commit in given repository.
  339. func GetCommitFileStatus(repoPath, commitID string) (*CommitFileStatus, error) {
  340. stdout, w := io.Pipe()
  341. done := make(chan struct{})
  342. fileStatus := NewCommitFileStatus()
  343. go func() {
  344. scanner := bufio.NewScanner(stdout)
  345. for scanner.Scan() {
  346. fields := strings.Fields(scanner.Text())
  347. if len(fields) < 2 {
  348. continue
  349. }
  350. switch fields[0][0] {
  351. case 'A':
  352. fileStatus.Added = append(fileStatus.Added, fields[1])
  353. case 'D':
  354. fileStatus.Removed = append(fileStatus.Removed, fields[1])
  355. case 'M':
  356. fileStatus.Modified = append(fileStatus.Modified, fields[1])
  357. }
  358. }
  359. done <- struct{}{}
  360. }()
  361. stderr := new(bytes.Buffer)
  362. err := NewCommand("show", "--name-status", "--pretty=format:''", commitID).RunInDirPipeline(repoPath, w, stderr)
  363. w.Close() // Close writer to exit parsing goroutine
  364. if err != nil {
  365. return nil, concatenateError(err, stderr.String())
  366. }
  367. <-done
  368. return fileStatus, nil
  369. }
  370. // GetFullCommitID returns full length (40) of commit ID by given short SHA in a repository.
  371. func GetFullCommitID(repoPath, shortID string) (string, error) {
  372. if len(shortID) >= 40 {
  373. return shortID, nil
  374. }
  375. commitID, err := NewCommand("rev-parse", shortID).RunInDir(repoPath)
  376. if err != nil {
  377. if strings.Contains(err.Error(), "exit status 128") {
  378. return "", ErrNotExist{shortID, ""}
  379. }
  380. return "", err
  381. }
  382. return strings.TrimSpace(commitID), nil
  383. }