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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  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 string, revision, relpath []string) (int64, error) {
  235. cmd := NewCommand("rev-list", "--count")
  236. cmd.AddArguments(revision...)
  237. if len(relpath) > 0 {
  238. cmd.AddArguments("--")
  239. cmd.AddArguments(relpath...)
  240. }
  241. stdout, err := cmd.RunInDir(repoPath)
  242. if err != nil {
  243. return 0, err
  244. }
  245. return strconv.ParseInt(strings.TrimSpace(stdout), 10, 64)
  246. }
  247. // CommitsCount returns number of total commits of until given revision.
  248. func CommitsCount(repoPath, revision string) (int64, error) {
  249. return commitsCount(repoPath, []string{revision}, []string{})
  250. }
  251. // CommitsCount returns number of total commits of until current revision.
  252. func (c *Commit) CommitsCount() (int64, error) {
  253. return CommitsCount(c.repo.Path, c.ID.String())
  254. }
  255. // CommitsByRange returns the specific page commits before current revision, every page's number default by CommitsRangeSize
  256. func (c *Commit) CommitsByRange(page, pageSize int) (*list.List, error) {
  257. return c.repo.commitsByRange(c.ID, page, pageSize)
  258. }
  259. // CommitsBefore returns all the commits before current revision
  260. func (c *Commit) CommitsBefore() (*list.List, error) {
  261. return c.repo.getCommitsBefore(c.ID)
  262. }
  263. // HasPreviousCommit returns true if a given commitHash is contained in commit's parents
  264. func (c *Commit) HasPreviousCommit(commitHash SHA1) (bool, error) {
  265. for i := 0; i < c.ParentCount(); i++ {
  266. commit, err := c.Parent(i)
  267. if err != nil {
  268. return false, err
  269. }
  270. if commit.ID == commitHash {
  271. return true, nil
  272. }
  273. commitInParentCommit, err := commit.HasPreviousCommit(commitHash)
  274. if err != nil {
  275. return false, err
  276. }
  277. if commitInParentCommit {
  278. return true, nil
  279. }
  280. }
  281. return false, nil
  282. }
  283. // CommitsBeforeLimit returns num commits before current revision
  284. func (c *Commit) CommitsBeforeLimit(num int) (*list.List, error) {
  285. return c.repo.getCommitsBeforeLimit(c.ID, num)
  286. }
  287. // CommitsBeforeUntil returns the commits between commitID to current revision
  288. func (c *Commit) CommitsBeforeUntil(commitID string) (*list.List, error) {
  289. endCommit, err := c.repo.GetCommit(commitID)
  290. if err != nil {
  291. return nil, err
  292. }
  293. return c.repo.CommitsBetween(c, endCommit)
  294. }
  295. // SearchCommitsOptions specify the parameters for SearchCommits
  296. type SearchCommitsOptions struct {
  297. Keywords []string
  298. Authors, Committers []string
  299. After, Before string
  300. All bool
  301. }
  302. // NewSearchCommitsOptions construct a SearchCommitsOption from a space-delimited search string
  303. func NewSearchCommitsOptions(searchString string, forAllRefs bool) SearchCommitsOptions {
  304. var keywords, authors, committers []string
  305. var after, before string
  306. fields := strings.Fields(searchString)
  307. for _, k := range fields {
  308. switch {
  309. case strings.HasPrefix(k, "author:"):
  310. authors = append(authors, strings.TrimPrefix(k, "author:"))
  311. case strings.HasPrefix(k, "committer:"):
  312. committers = append(committers, strings.TrimPrefix(k, "committer:"))
  313. case strings.HasPrefix(k, "after:"):
  314. after = strings.TrimPrefix(k, "after:")
  315. case strings.HasPrefix(k, "before:"):
  316. before = strings.TrimPrefix(k, "before:")
  317. default:
  318. keywords = append(keywords, k)
  319. }
  320. }
  321. return SearchCommitsOptions{
  322. Keywords: keywords,
  323. Authors: authors,
  324. Committers: committers,
  325. After: after,
  326. Before: before,
  327. All: forAllRefs,
  328. }
  329. }
  330. // SearchCommits returns the commits match the keyword before current revision
  331. func (c *Commit) SearchCommits(opts SearchCommitsOptions) (*list.List, error) {
  332. return c.repo.searchCommits(c.ID, opts)
  333. }
  334. // GetFilesChangedSinceCommit get all changed file names between pastCommit to current revision
  335. func (c *Commit) GetFilesChangedSinceCommit(pastCommit string) ([]string, error) {
  336. return c.repo.getFilesChanged(pastCommit, c.ID.String())
  337. }
  338. // FileChangedSinceCommit Returns true if the file given has changed since the the past commit
  339. // YOU MUST ENSURE THAT pastCommit is a valid commit ID.
  340. func (c *Commit) FileChangedSinceCommit(filename, pastCommit string) (bool, error) {
  341. return c.repo.FileChangedBetweenCommits(filename, pastCommit, c.ID.String())
  342. }
  343. // HasFile returns true if the file given exists on this commit
  344. // This does only mean it's there - it does not mean the file was changed during the commit.
  345. func (c *Commit) HasFile(filename string) (bool, error) {
  346. _, err := c.GetBlobByPath(filename)
  347. if err != nil {
  348. return false, err
  349. }
  350. return true, nil
  351. }
  352. // GetSubModules get all the sub modules of current revision git tree
  353. func (c *Commit) GetSubModules() (*ObjectCache, error) {
  354. if c.submoduleCache != nil {
  355. return c.submoduleCache, nil
  356. }
  357. entry, err := c.GetTreeEntryByPath(".gitmodules")
  358. if err != nil {
  359. if _, ok := err.(ErrNotExist); ok {
  360. return nil, nil
  361. }
  362. return nil, err
  363. }
  364. rd, err := entry.Blob().DataAsync()
  365. if err != nil {
  366. return nil, err
  367. }
  368. defer rd.Close()
  369. scanner := bufio.NewScanner(rd)
  370. c.submoduleCache = newObjectCache()
  371. var ismodule bool
  372. var path string
  373. for scanner.Scan() {
  374. if strings.HasPrefix(scanner.Text(), "[submodule") {
  375. ismodule = true
  376. continue
  377. }
  378. if ismodule {
  379. fields := strings.Split(scanner.Text(), "=")
  380. k := strings.TrimSpace(fields[0])
  381. if k == "path" {
  382. path = strings.TrimSpace(fields[1])
  383. } else if k == "url" {
  384. c.submoduleCache.Set(path, &SubModule{path, strings.TrimSpace(fields[1])})
  385. ismodule = false
  386. }
  387. }
  388. }
  389. return c.submoduleCache, nil
  390. }
  391. // GetSubModule get the sub module according entryname
  392. func (c *Commit) GetSubModule(entryname string) (*SubModule, error) {
  393. modules, err := c.GetSubModules()
  394. if err != nil {
  395. return nil, err
  396. }
  397. if modules != nil {
  398. module, has := modules.Get(entryname)
  399. if has {
  400. return module.(*SubModule), nil
  401. }
  402. }
  403. return nil, nil
  404. }
  405. // GetBranchName gets the closest branch name (as returned by 'git name-rev --name-only')
  406. func (c *Commit) GetBranchName() (string, error) {
  407. err := LoadGitVersion()
  408. if err != nil {
  409. return "", fmt.Errorf("Git version missing: %v", err)
  410. }
  411. args := []string{
  412. "name-rev",
  413. }
  414. if CheckGitVersionAtLeast("2.13.0") == nil {
  415. args = append(args, "--exclude", "refs/tags/*")
  416. }
  417. args = append(args, "--name-only", "--no-undefined", c.ID.String())
  418. data, err := NewCommand(args...).RunInDir(c.repo.Path)
  419. if err != nil {
  420. // handle special case where git can not describe commit
  421. if strings.Contains(err.Error(), "cannot describe") {
  422. return "", nil
  423. }
  424. return "", err
  425. }
  426. // name-rev commitID output will be "master" or "master~12"
  427. return strings.SplitN(strings.TrimSpace(data), "~", 2)[0], nil
  428. }
  429. // LoadBranchName load branch name for commit
  430. func (c *Commit) LoadBranchName() (err error) {
  431. if len(c.Branch) != 0 {
  432. return
  433. }
  434. c.Branch, err = c.GetBranchName()
  435. return
  436. }
  437. // GetTagName gets the current tag name for given commit
  438. func (c *Commit) GetTagName() (string, error) {
  439. data, err := NewCommand("describe", "--exact-match", "--tags", "--always", c.ID.String()).RunInDir(c.repo.Path)
  440. if err != nil {
  441. // handle special case where there is no tag for this commit
  442. if strings.Contains(err.Error(), "no tag exactly matches") {
  443. return "", nil
  444. }
  445. return "", err
  446. }
  447. return strings.TrimSpace(data), nil
  448. }
  449. // CommitFileStatus represents status of files in a commit.
  450. type CommitFileStatus struct {
  451. Added []string
  452. Removed []string
  453. Modified []string
  454. }
  455. // NewCommitFileStatus creates a CommitFileStatus
  456. func NewCommitFileStatus() *CommitFileStatus {
  457. return &CommitFileStatus{
  458. []string{}, []string{}, []string{},
  459. }
  460. }
  461. // GetCommitFileStatus returns file status of commit in given repository.
  462. func GetCommitFileStatus(repoPath, commitID string) (*CommitFileStatus, error) {
  463. stdout, w := io.Pipe()
  464. done := make(chan struct{})
  465. fileStatus := NewCommitFileStatus()
  466. go func() {
  467. scanner := bufio.NewScanner(stdout)
  468. for scanner.Scan() {
  469. fields := strings.Fields(scanner.Text())
  470. if len(fields) < 2 {
  471. continue
  472. }
  473. switch fields[0][0] {
  474. case 'A':
  475. fileStatus.Added = append(fileStatus.Added, fields[1])
  476. case 'D':
  477. fileStatus.Removed = append(fileStatus.Removed, fields[1])
  478. case 'M':
  479. fileStatus.Modified = append(fileStatus.Modified, fields[1])
  480. }
  481. }
  482. done <- struct{}{}
  483. }()
  484. stderr := new(bytes.Buffer)
  485. err := NewCommand("show", "--name-status", "--pretty=format:''", commitID).RunInDirPipeline(repoPath, w, stderr)
  486. w.Close() // Close writer to exit parsing goroutine
  487. if err != nil {
  488. return nil, concatenateError(err, stderr.String())
  489. }
  490. <-done
  491. return fileStatus, nil
  492. }
  493. // GetFullCommitID returns full length (40) of commit ID by given short SHA in a repository.
  494. func GetFullCommitID(repoPath, shortID string) (string, error) {
  495. commitID, err := NewCommand("rev-parse", shortID).RunInDir(repoPath)
  496. if err != nil {
  497. if strings.Contains(err.Error(), "exit status 128") {
  498. return "", ErrNotExist{shortID, ""}
  499. }
  500. return "", err
  501. }
  502. return strings.TrimSpace(commitID), nil
  503. }
  504. // GetRepositoryDefaultPublicGPGKey returns the default public key for this commit
  505. func (c *Commit) GetRepositoryDefaultPublicGPGKey(forceUpdate bool) (*GPGSettings, error) {
  506. if c.repo == nil {
  507. return nil, nil
  508. }
  509. return c.repo.GetDefaultPublicGPGKey(forceUpdate)
  510. }