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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  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. "github.com/go-git/go-git/v5/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. return AddChangesWithArgs(repoPath, GlobalCommandArgs, all, files...)
  180. }
  181. // AddChangesWithArgs marks local changes to be ready for commit.
  182. func AddChangesWithArgs(repoPath string, gloablArgs []string, all bool, files ...string) error {
  183. cmd := NewCommandNoGlobals(append(gloablArgs, "add")...)
  184. if all {
  185. cmd.AddArguments("--all")
  186. }
  187. cmd.AddArguments("--")
  188. _, err := cmd.AddArguments(files...).RunInDir(repoPath)
  189. return err
  190. }
  191. // CommitChangesOptions the options when a commit created
  192. type CommitChangesOptions struct {
  193. Committer *Signature
  194. Author *Signature
  195. Message string
  196. }
  197. // CommitChanges commits local changes with given committer, author and message.
  198. // If author is nil, it will be the same as committer.
  199. func CommitChanges(repoPath string, opts CommitChangesOptions) error {
  200. cargs := make([]string, len(GlobalCommandArgs))
  201. copy(cargs, GlobalCommandArgs)
  202. return CommitChangesWithArgs(repoPath, cargs, opts)
  203. }
  204. // CommitChangesWithArgs commits local changes with given committer, author and message.
  205. // If author is nil, it will be the same as committer.
  206. func CommitChangesWithArgs(repoPath string, args []string, opts CommitChangesOptions) error {
  207. cmd := NewCommandNoGlobals(args...)
  208. if opts.Committer != nil {
  209. cmd.AddArguments("-c", "user.name="+opts.Committer.Name, "-c", "user.email="+opts.Committer.Email)
  210. }
  211. cmd.AddArguments("commit")
  212. if opts.Author == nil {
  213. opts.Author = opts.Committer
  214. }
  215. if opts.Author != nil {
  216. cmd.AddArguments(fmt.Sprintf("--author='%s <%s>'", opts.Author.Name, opts.Author.Email))
  217. }
  218. cmd.AddArguments("-m", opts.Message)
  219. _, err := cmd.RunInDir(repoPath)
  220. // No stderr but exit status 1 means nothing to commit.
  221. if err != nil && err.Error() == "exit status 1" {
  222. return nil
  223. }
  224. return err
  225. }
  226. // AllCommitsCount returns count of all commits in repository
  227. func AllCommitsCount(repoPath string) (int64, error) {
  228. stdout, err := NewCommand("rev-list", "--all", "--count").RunInDir(repoPath)
  229. if err != nil {
  230. return 0, err
  231. }
  232. return strconv.ParseInt(strings.TrimSpace(stdout), 10, 64)
  233. }
  234. func commitsCount(repoPath, revision, relpath string) (int64, error) {
  235. cmd := NewCommand("rev-list", "--count")
  236. cmd.AddArguments(revision)
  237. if len(relpath) > 0 {
  238. cmd.AddArguments("--", relpath)
  239. }
  240. stdout, err := cmd.RunInDir(repoPath)
  241. if err != nil {
  242. return 0, err
  243. }
  244. return strconv.ParseInt(strings.TrimSpace(stdout), 10, 64)
  245. }
  246. // CommitsCount returns number of total commits of until given revision.
  247. func CommitsCount(repoPath, revision string) (int64, error) {
  248. return commitsCount(repoPath, revision, "")
  249. }
  250. // CommitsCount returns number of total commits of until current revision.
  251. func (c *Commit) CommitsCount() (int64, error) {
  252. return CommitsCount(c.repo.Path, c.ID.String())
  253. }
  254. // CommitsByRange returns the specific page commits before current revision, every page's number default by CommitsRangeSize
  255. func (c *Commit) CommitsByRange(page, pageSize int) (*list.List, error) {
  256. return c.repo.commitsByRange(c.ID, page, pageSize)
  257. }
  258. // CommitsBefore returns all the commits before current revision
  259. func (c *Commit) CommitsBefore() (*list.List, error) {
  260. return c.repo.getCommitsBefore(c.ID)
  261. }
  262. // HasPreviousCommit returns true if a given commitHash is contained in commit's parents
  263. func (c *Commit) HasPreviousCommit(commitHash SHA1) (bool, error) {
  264. for i := 0; i < c.ParentCount(); i++ {
  265. commit, err := c.Parent(i)
  266. if err != nil {
  267. return false, err
  268. }
  269. if commit.ID == commitHash {
  270. return true, nil
  271. }
  272. commitInParentCommit, err := commit.HasPreviousCommit(commitHash)
  273. if err != nil {
  274. return false, err
  275. }
  276. if commitInParentCommit {
  277. return true, nil
  278. }
  279. }
  280. return false, nil
  281. }
  282. // CommitsBeforeLimit returns num commits before current revision
  283. func (c *Commit) CommitsBeforeLimit(num int) (*list.List, error) {
  284. return c.repo.getCommitsBeforeLimit(c.ID, num)
  285. }
  286. // CommitsBeforeUntil returns the commits between commitID to current revision
  287. func (c *Commit) CommitsBeforeUntil(commitID string) (*list.List, error) {
  288. endCommit, err := c.repo.GetCommit(commitID)
  289. if err != nil {
  290. return nil, err
  291. }
  292. return c.repo.CommitsBetween(c, endCommit)
  293. }
  294. // SearchCommitsOptions specify the parameters for SearchCommits
  295. type SearchCommitsOptions struct {
  296. Keywords []string
  297. Authors, Committers []string
  298. After, Before string
  299. All bool
  300. }
  301. // NewSearchCommitsOptions construct a SearchCommitsOption from a space-delimited search string
  302. func NewSearchCommitsOptions(searchString string, forAllRefs bool) SearchCommitsOptions {
  303. var keywords, authors, committers []string
  304. var after, before string
  305. fields := strings.Fields(searchString)
  306. for _, k := range fields {
  307. switch {
  308. case strings.HasPrefix(k, "author:"):
  309. authors = append(authors, strings.TrimPrefix(k, "author:"))
  310. case strings.HasPrefix(k, "committer:"):
  311. committers = append(committers, strings.TrimPrefix(k, "committer:"))
  312. case strings.HasPrefix(k, "after:"):
  313. after = strings.TrimPrefix(k, "after:")
  314. case strings.HasPrefix(k, "before:"):
  315. before = strings.TrimPrefix(k, "before:")
  316. default:
  317. keywords = append(keywords, k)
  318. }
  319. }
  320. return SearchCommitsOptions{
  321. Keywords: keywords,
  322. Authors: authors,
  323. Committers: committers,
  324. After: after,
  325. Before: before,
  326. All: forAllRefs,
  327. }
  328. }
  329. // SearchCommits returns the commits match the keyword before current revision
  330. func (c *Commit) SearchCommits(opts SearchCommitsOptions) (*list.List, error) {
  331. return c.repo.searchCommits(c.ID, opts)
  332. }
  333. // GetFilesChangedSinceCommit get all changed file names between pastCommit to current revision
  334. func (c *Commit) GetFilesChangedSinceCommit(pastCommit string) ([]string, error) {
  335. return c.repo.getFilesChanged(pastCommit, c.ID.String())
  336. }
  337. // FileChangedSinceCommit Returns true if the file given has changed since the the past commit
  338. // YOU MUST ENSURE THAT pastCommit is a valid commit ID.
  339. func (c *Commit) FileChangedSinceCommit(filename, pastCommit string) (bool, error) {
  340. return c.repo.FileChangedBetweenCommits(filename, pastCommit, c.ID.String())
  341. }
  342. // HasFile returns true if the file given exists on this commit
  343. // This does only mean it's there - it does not mean the file was changed during the commit.
  344. func (c *Commit) HasFile(filename string) (bool, error) {
  345. _, err := c.GetBlobByPath(filename)
  346. if err != nil {
  347. return false, err
  348. }
  349. return true, nil
  350. }
  351. // GetSubModules get all the sub modules of current revision git tree
  352. func (c *Commit) GetSubModules() (*ObjectCache, error) {
  353. if c.submoduleCache != nil {
  354. return c.submoduleCache, nil
  355. }
  356. entry, err := c.GetTreeEntryByPath(".gitmodules")
  357. if err != nil {
  358. if _, ok := err.(ErrNotExist); ok {
  359. return nil, nil
  360. }
  361. return nil, err
  362. }
  363. rd, err := entry.Blob().DataAsync()
  364. if err != nil {
  365. return nil, err
  366. }
  367. defer rd.Close()
  368. scanner := bufio.NewScanner(rd)
  369. c.submoduleCache = newObjectCache()
  370. var ismodule bool
  371. var path string
  372. for scanner.Scan() {
  373. if strings.HasPrefix(scanner.Text(), "[submodule") {
  374. ismodule = true
  375. continue
  376. }
  377. if ismodule {
  378. fields := strings.Split(scanner.Text(), "=")
  379. k := strings.TrimSpace(fields[0])
  380. if k == "path" {
  381. path = strings.TrimSpace(fields[1])
  382. } else if k == "url" {
  383. c.submoduleCache.Set(path, &SubModule{path, strings.TrimSpace(fields[1])})
  384. ismodule = false
  385. }
  386. }
  387. }
  388. return c.submoduleCache, nil
  389. }
  390. // GetSubModule get the sub module according entryname
  391. func (c *Commit) GetSubModule(entryname string) (*SubModule, error) {
  392. modules, err := c.GetSubModules()
  393. if err != nil {
  394. return nil, err
  395. }
  396. if modules != nil {
  397. module, has := modules.Get(entryname)
  398. if has {
  399. return module.(*SubModule), nil
  400. }
  401. }
  402. return nil, nil
  403. }
  404. // GetBranchName gets the closes branch name (as returned by 'git name-rev --name-only')
  405. func (c *Commit) GetBranchName() (string, error) {
  406. data, err := NewCommand("name-rev", "--name-only", c.ID.String()).RunInDir(c.repo.Path)
  407. if err != nil {
  408. return "", err
  409. }
  410. // name-rev commitID output will be "master" or "master~12"
  411. return strings.SplitN(strings.TrimSpace(data), "~", 2)[0], nil
  412. }
  413. // CommitFileStatus represents status of files in a commit.
  414. type CommitFileStatus struct {
  415. Added []string
  416. Removed []string
  417. Modified []string
  418. }
  419. // NewCommitFileStatus creates a CommitFileStatus
  420. func NewCommitFileStatus() *CommitFileStatus {
  421. return &CommitFileStatus{
  422. []string{}, []string{}, []string{},
  423. }
  424. }
  425. // GetCommitFileStatus returns file status of commit in given repository.
  426. func GetCommitFileStatus(repoPath, commitID string) (*CommitFileStatus, error) {
  427. stdout, w := io.Pipe()
  428. done := make(chan struct{})
  429. fileStatus := NewCommitFileStatus()
  430. go func() {
  431. scanner := bufio.NewScanner(stdout)
  432. for scanner.Scan() {
  433. fields := strings.Fields(scanner.Text())
  434. if len(fields) < 2 {
  435. continue
  436. }
  437. switch fields[0][0] {
  438. case 'A':
  439. fileStatus.Added = append(fileStatus.Added, fields[1])
  440. case 'D':
  441. fileStatus.Removed = append(fileStatus.Removed, fields[1])
  442. case 'M':
  443. fileStatus.Modified = append(fileStatus.Modified, fields[1])
  444. }
  445. }
  446. done <- struct{}{}
  447. }()
  448. stderr := new(bytes.Buffer)
  449. err := NewCommand("show", "--name-status", "--pretty=format:''", commitID).RunInDirPipeline(repoPath, w, stderr)
  450. w.Close() // Close writer to exit parsing goroutine
  451. if err != nil {
  452. return nil, concatenateError(err, stderr.String())
  453. }
  454. <-done
  455. return fileStatus, nil
  456. }
  457. // GetFullCommitID returns full length (40) of commit ID by given short SHA in a repository.
  458. func GetFullCommitID(repoPath, shortID string) (string, error) {
  459. commitID, err := NewCommand("rev-parse", shortID).RunInDir(repoPath)
  460. if err != nil {
  461. if strings.Contains(err.Error(), "exit status 128") {
  462. return "", ErrNotExist{shortID, ""}
  463. }
  464. return "", err
  465. }
  466. return strings.TrimSpace(commitID), nil
  467. }
  468. // GetRepositoryDefaultPublicGPGKey returns the default public key for this commit
  469. func (c *Commit) GetRepositoryDefaultPublicGPGKey(forceUpdate bool) (*GPGSettings, error) {
  470. if c.repo == nil {
  471. return nil, nil
  472. }
  473. return c.repo.GetDefaultPublicGPGKey(forceUpdate)
  474. }