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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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. cmd.AddArguments("--")
  146. _, err := cmd.AddArguments(files...).RunInDir(repoPath)
  147. return err
  148. }
  149. // CommitChangesOptions the options when a commit created
  150. type CommitChangesOptions struct {
  151. Committer *Signature
  152. Author *Signature
  153. Message string
  154. }
  155. // CommitChanges commits local changes with given committer, author and message.
  156. // If author is nil, it will be the same as committer.
  157. func CommitChanges(repoPath string, opts CommitChangesOptions) error {
  158. cmd := NewCommand()
  159. if opts.Committer != nil {
  160. cmd.AddArguments("-c", "user.name="+opts.Committer.Name, "-c", "user.email="+opts.Committer.Email)
  161. }
  162. cmd.AddArguments("commit")
  163. if opts.Author == nil {
  164. opts.Author = opts.Committer
  165. }
  166. if opts.Author != nil {
  167. cmd.AddArguments(fmt.Sprintf("--author='%s <%s>'", opts.Author.Name, opts.Author.Email))
  168. }
  169. cmd.AddArguments("-m", opts.Message)
  170. _, err := cmd.RunInDir(repoPath)
  171. // No stderr but exit status 1 means nothing to commit.
  172. if err != nil && err.Error() == "exit status 1" {
  173. return nil
  174. }
  175. return err
  176. }
  177. func commitsCount(repoPath, revision, relpath string) (int64, error) {
  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 construct 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. // YOU MUST ENSURE THAT pastCommit is a valid commit ID.
  262. func (c *Commit) FileChangedSinceCommit(filename, pastCommit string) (bool, error) {
  263. return c.repo.FileChangedBetweenCommits(filename, pastCommit, c.ID.String())
  264. }
  265. // GetSubModules get all the sub modules of current revision git tree
  266. func (c *Commit) GetSubModules() (*ObjectCache, error) {
  267. if c.submoduleCache != nil {
  268. return c.submoduleCache, nil
  269. }
  270. entry, err := c.GetTreeEntryByPath(".gitmodules")
  271. if err != nil {
  272. if _, ok := err.(ErrNotExist); ok {
  273. return nil, nil
  274. }
  275. return nil, err
  276. }
  277. rd, err := entry.Blob().DataAsync()
  278. if err != nil {
  279. return nil, err
  280. }
  281. defer rd.Close()
  282. scanner := bufio.NewScanner(rd)
  283. c.submoduleCache = newObjectCache()
  284. var ismodule bool
  285. var path string
  286. for scanner.Scan() {
  287. if strings.HasPrefix(scanner.Text(), "[submodule") {
  288. ismodule = true
  289. continue
  290. }
  291. if ismodule {
  292. fields := strings.Split(scanner.Text(), "=")
  293. k := strings.TrimSpace(fields[0])
  294. if k == "path" {
  295. path = strings.TrimSpace(fields[1])
  296. } else if k == "url" {
  297. c.submoduleCache.Set(path, &SubModule{path, strings.TrimSpace(fields[1])})
  298. ismodule = false
  299. }
  300. }
  301. }
  302. return c.submoduleCache, nil
  303. }
  304. // GetSubModule get the sub module according entryname
  305. func (c *Commit) GetSubModule(entryname string) (*SubModule, error) {
  306. modules, err := c.GetSubModules()
  307. if err != nil {
  308. return nil, err
  309. }
  310. if modules != nil {
  311. module, has := modules.Get(entryname)
  312. if has {
  313. return module.(*SubModule), nil
  314. }
  315. }
  316. return nil, nil
  317. }
  318. // GetBranchName gets the closes branch name (as returned by 'git name-rev')
  319. func (c *Commit) GetBranchName() (string, error) {
  320. data, err := NewCommand("name-rev", c.ID.String()).RunInDirBytes(c.repo.Path)
  321. if err != nil {
  322. return "", err
  323. }
  324. // name-rev commitID output will be "COMMIT_ID master" or "COMMIT_ID master~12"
  325. return strings.Split(strings.Split(string(data), " ")[1], "~")[0], nil
  326. }
  327. // CommitFileStatus represents status of files in a commit.
  328. type CommitFileStatus struct {
  329. Added []string
  330. Removed []string
  331. Modified []string
  332. }
  333. // NewCommitFileStatus creates a CommitFileStatus
  334. func NewCommitFileStatus() *CommitFileStatus {
  335. return &CommitFileStatus{
  336. []string{}, []string{}, []string{},
  337. }
  338. }
  339. // GetCommitFileStatus returns file status of commit in given repository.
  340. func GetCommitFileStatus(repoPath, commitID string) (*CommitFileStatus, error) {
  341. stdout, w := io.Pipe()
  342. done := make(chan struct{})
  343. fileStatus := NewCommitFileStatus()
  344. go func() {
  345. scanner := bufio.NewScanner(stdout)
  346. for scanner.Scan() {
  347. fields := strings.Fields(scanner.Text())
  348. if len(fields) < 2 {
  349. continue
  350. }
  351. switch fields[0][0] {
  352. case 'A':
  353. fileStatus.Added = append(fileStatus.Added, fields[1])
  354. case 'D':
  355. fileStatus.Removed = append(fileStatus.Removed, fields[1])
  356. case 'M':
  357. fileStatus.Modified = append(fileStatus.Modified, fields[1])
  358. }
  359. }
  360. done <- struct{}{}
  361. }()
  362. stderr := new(bytes.Buffer)
  363. err := NewCommand("show", "--name-status", "--pretty=format:''", commitID).RunInDirPipeline(repoPath, w, stderr)
  364. w.Close() // Close writer to exit parsing goroutine
  365. if err != nil {
  366. return nil, concatenateError(err, stderr.String())
  367. }
  368. <-done
  369. return fileStatus, nil
  370. }
  371. // GetFullCommitID returns full length (40) of commit ID by given short SHA in a repository.
  372. func GetFullCommitID(repoPath, shortID string) (string, error) {
  373. if len(shortID) >= 40 {
  374. return shortID, nil
  375. }
  376. commitID, err := NewCommand("rev-parse", shortID).RunInDir(repoPath)
  377. if err != nil {
  378. if strings.Contains(err.Error(), "exit status 128") {
  379. return "", ErrNotExist{shortID, ""}
  380. }
  381. return "", err
  382. }
  383. return strings.TrimSpace(commitID), nil
  384. }