本站源代码
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

509 行
13KB

  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. func commitsCount(repoPath, revision, relpath string) (int64, error) {
  216. cmd := NewCommand("rev-list", "--count")
  217. cmd.AddArguments(revision)
  218. if len(relpath) > 0 {
  219. cmd.AddArguments("--", relpath)
  220. }
  221. stdout, err := cmd.RunInDir(repoPath)
  222. if err != nil {
  223. return 0, err
  224. }
  225. return strconv.ParseInt(strings.TrimSpace(stdout), 10, 64)
  226. }
  227. // CommitsCount returns number of total commits of until given revision.
  228. func CommitsCount(repoPath, revision string) (int64, error) {
  229. return commitsCount(repoPath, revision, "")
  230. }
  231. // CommitsCount returns number of total commits of until current revision.
  232. func (c *Commit) CommitsCount() (int64, error) {
  233. return CommitsCount(c.repo.Path, c.ID.String())
  234. }
  235. // CommitsByRange returns the specific page commits before current revision, every page's number default by CommitsRangeSize
  236. func (c *Commit) CommitsByRange(page int) (*list.List, error) {
  237. return c.repo.commitsByRange(c.ID, page)
  238. }
  239. // CommitsBefore returns all the commits before current revision
  240. func (c *Commit) CommitsBefore() (*list.List, error) {
  241. return c.repo.getCommitsBefore(c.ID)
  242. }
  243. // CommitsBeforeLimit returns num commits before current revision
  244. func (c *Commit) CommitsBeforeLimit(num int) (*list.List, error) {
  245. return c.repo.getCommitsBeforeLimit(c.ID, num)
  246. }
  247. // CommitsBeforeUntil returns the commits between commitID to current revision
  248. func (c *Commit) CommitsBeforeUntil(commitID string) (*list.List, error) {
  249. endCommit, err := c.repo.GetCommit(commitID)
  250. if err != nil {
  251. return nil, err
  252. }
  253. return c.repo.CommitsBetween(c, endCommit)
  254. }
  255. // SearchCommitsOptions specify the parameters for SearchCommits
  256. type SearchCommitsOptions struct {
  257. Keywords []string
  258. Authors, Committers []string
  259. After, Before string
  260. All bool
  261. }
  262. // NewSearchCommitsOptions construct a SearchCommitsOption from a space-delimited search string
  263. func NewSearchCommitsOptions(searchString string, forAllRefs bool) SearchCommitsOptions {
  264. var keywords, authors, committers []string
  265. var after, before string
  266. fields := strings.Fields(searchString)
  267. for _, k := range fields {
  268. switch {
  269. case strings.HasPrefix(k, "author:"):
  270. authors = append(authors, strings.TrimPrefix(k, "author:"))
  271. case strings.HasPrefix(k, "committer:"):
  272. committers = append(committers, strings.TrimPrefix(k, "committer:"))
  273. case strings.HasPrefix(k, "after:"):
  274. after = strings.TrimPrefix(k, "after:")
  275. case strings.HasPrefix(k, "before:"):
  276. before = strings.TrimPrefix(k, "before:")
  277. default:
  278. keywords = append(keywords, k)
  279. }
  280. }
  281. return SearchCommitsOptions{
  282. Keywords: keywords,
  283. Authors: authors,
  284. Committers: committers,
  285. After: after,
  286. Before: before,
  287. All: forAllRefs,
  288. }
  289. }
  290. // SearchCommits returns the commits match the keyword before current revision
  291. func (c *Commit) SearchCommits(opts SearchCommitsOptions) (*list.List, error) {
  292. return c.repo.searchCommits(c.ID, opts)
  293. }
  294. // GetFilesChangedSinceCommit get all changed file names between pastCommit to current revision
  295. func (c *Commit) GetFilesChangedSinceCommit(pastCommit string) ([]string, error) {
  296. return c.repo.getFilesChanged(pastCommit, c.ID.String())
  297. }
  298. // FileChangedSinceCommit Returns true if the file given has changed since the the past commit
  299. // YOU MUST ENSURE THAT pastCommit is a valid commit ID.
  300. func (c *Commit) FileChangedSinceCommit(filename, pastCommit string) (bool, error) {
  301. return c.repo.FileChangedBetweenCommits(filename, pastCommit, c.ID.String())
  302. }
  303. // HasFile returns true if the file given exists on this commit
  304. // This does only mean it's there - it does not mean the file was changed during the commit.
  305. func (c *Commit) HasFile(filename string) (bool, error) {
  306. _, err := c.GetBlobByPath(filename)
  307. if err != nil {
  308. return false, err
  309. }
  310. return true, nil
  311. }
  312. // GetSubModules get all the sub modules of current revision git tree
  313. func (c *Commit) GetSubModules() (*ObjectCache, error) {
  314. if c.submoduleCache != nil {
  315. return c.submoduleCache, nil
  316. }
  317. entry, err := c.GetTreeEntryByPath(".gitmodules")
  318. if err != nil {
  319. if _, ok := err.(ErrNotExist); ok {
  320. return nil, nil
  321. }
  322. return nil, err
  323. }
  324. rd, err := entry.Blob().DataAsync()
  325. if err != nil {
  326. return nil, err
  327. }
  328. defer rd.Close()
  329. scanner := bufio.NewScanner(rd)
  330. c.submoduleCache = newObjectCache()
  331. var ismodule bool
  332. var path string
  333. for scanner.Scan() {
  334. if strings.HasPrefix(scanner.Text(), "[submodule") {
  335. ismodule = true
  336. continue
  337. }
  338. if ismodule {
  339. fields := strings.Split(scanner.Text(), "=")
  340. k := strings.TrimSpace(fields[0])
  341. if k == "path" {
  342. path = strings.TrimSpace(fields[1])
  343. } else if k == "url" {
  344. c.submoduleCache.Set(path, &SubModule{path, strings.TrimSpace(fields[1])})
  345. ismodule = false
  346. }
  347. }
  348. }
  349. return c.submoduleCache, nil
  350. }
  351. // GetSubModule get the sub module according entryname
  352. func (c *Commit) GetSubModule(entryname string) (*SubModule, error) {
  353. modules, err := c.GetSubModules()
  354. if err != nil {
  355. return nil, err
  356. }
  357. if modules != nil {
  358. module, has := modules.Get(entryname)
  359. if has {
  360. return module.(*SubModule), nil
  361. }
  362. }
  363. return nil, nil
  364. }
  365. // GetBranchName gets the closes branch name (as returned by 'git name-rev')
  366. func (c *Commit) GetBranchName() (string, error) {
  367. data, err := NewCommand("name-rev", c.ID.String()).RunInDirBytes(c.repo.Path)
  368. if err != nil {
  369. return "", err
  370. }
  371. // name-rev commitID output will be "COMMIT_ID master" or "COMMIT_ID master~12"
  372. return strings.Split(strings.Split(string(data), " ")[1], "~")[0], nil
  373. }
  374. // CommitFileStatus represents status of files in a commit.
  375. type CommitFileStatus struct {
  376. Added []string
  377. Removed []string
  378. Modified []string
  379. }
  380. // NewCommitFileStatus creates a CommitFileStatus
  381. func NewCommitFileStatus() *CommitFileStatus {
  382. return &CommitFileStatus{
  383. []string{}, []string{}, []string{},
  384. }
  385. }
  386. // GetCommitFileStatus returns file status of commit in given repository.
  387. func GetCommitFileStatus(repoPath, commitID string) (*CommitFileStatus, error) {
  388. stdout, w := io.Pipe()
  389. done := make(chan struct{})
  390. fileStatus := NewCommitFileStatus()
  391. go func() {
  392. scanner := bufio.NewScanner(stdout)
  393. for scanner.Scan() {
  394. fields := strings.Fields(scanner.Text())
  395. if len(fields) < 2 {
  396. continue
  397. }
  398. switch fields[0][0] {
  399. case 'A':
  400. fileStatus.Added = append(fileStatus.Added, fields[1])
  401. case 'D':
  402. fileStatus.Removed = append(fileStatus.Removed, fields[1])
  403. case 'M':
  404. fileStatus.Modified = append(fileStatus.Modified, fields[1])
  405. }
  406. }
  407. done <- struct{}{}
  408. }()
  409. stderr := new(bytes.Buffer)
  410. err := NewCommand("show", "--name-status", "--pretty=format:''", commitID).RunInDirPipeline(repoPath, w, stderr)
  411. w.Close() // Close writer to exit parsing goroutine
  412. if err != nil {
  413. return nil, concatenateError(err, stderr.String())
  414. }
  415. <-done
  416. return fileStatus, nil
  417. }
  418. // GetFullCommitID returns full length (40) of commit ID by given short SHA in a repository.
  419. func GetFullCommitID(repoPath, shortID string) (string, error) {
  420. if len(shortID) >= 40 {
  421. return shortID, nil
  422. }
  423. commitID, err := NewCommand("rev-parse", shortID).RunInDir(repoPath)
  424. if err != nil {
  425. if strings.Contains(err.Error(), "exit status 128") {
  426. return "", ErrNotExist{shortID, ""}
  427. }
  428. return "", err
  429. }
  430. return strings.TrimSpace(commitID), nil
  431. }
  432. // GetRepositoryDefaultPublicGPGKey returns the default public key for this commit
  433. func (c *Commit) GetRepositoryDefaultPublicGPGKey(forceUpdate bool) (*GPGSettings, error) {
  434. if c.repo == nil {
  435. return nil, nil
  436. }
  437. return c.repo.GetDefaultPublicGPGKey(forceUpdate)
  438. }
上海开阖软件有限公司 沪ICP备12045867号-1