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 13KB

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