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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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. )
  16. // Commit represents a git commit.
  17. type Commit struct {
  18. Branch string // Branch this commit belongs to
  19. Tree
  20. ID SHA1 // The ID of this commit object
  21. Author *Signature
  22. Committer *Signature
  23. CommitMessage string
  24. Signature *CommitGPGSignature
  25. parents []SHA1 // SHA1 strings
  26. submoduleCache *ObjectCache
  27. }
  28. // CommitGPGSignature represents a git commit signature part.
  29. type CommitGPGSignature struct {
  30. Signature string
  31. Payload string //TODO check if can be reconstruct from the rest of commit information to not have duplicate data
  32. }
  33. // similar to https://github.com/git/git/blob/3bc53220cb2dcf709f7a027a3f526befd021d858/commit.c#L1128
  34. func newGPGSignatureFromCommitline(data []byte, signatureStart int, tag bool) (*CommitGPGSignature, error) {
  35. sig := new(CommitGPGSignature)
  36. signatureEnd := bytes.LastIndex(data, []byte("-----END PGP SIGNATURE-----"))
  37. if signatureEnd == -1 {
  38. return nil, fmt.Errorf("end of commit signature not found")
  39. }
  40. sig.Signature = strings.Replace(string(data[signatureStart:signatureEnd+27]), "\n ", "\n", -1)
  41. if tag {
  42. sig.Payload = string(data[:signatureStart-1])
  43. } else {
  44. sig.Payload = string(data[:signatureStart-8]) + string(data[signatureEnd+27:])
  45. }
  46. return sig, nil
  47. }
  48. // Message returns the commit message. Same as retrieving CommitMessage directly.
  49. func (c *Commit) Message() string {
  50. return c.CommitMessage
  51. }
  52. // Summary returns first line of commit message.
  53. func (c *Commit) Summary() string {
  54. return strings.Split(strings.TrimSpace(c.CommitMessage), "\n")[0]
  55. }
  56. // ParentID returns oid of n-th parent (0-based index).
  57. // It returns nil if no such parent exists.
  58. func (c *Commit) ParentID(n int) (SHA1, error) {
  59. if n >= len(c.parents) {
  60. return SHA1{}, ErrNotExist{"", ""}
  61. }
  62. return c.parents[n], nil
  63. }
  64. // Parent returns n-th parent (0-based index) of the commit.
  65. func (c *Commit) Parent(n int) (*Commit, error) {
  66. id, err := c.ParentID(n)
  67. if err != nil {
  68. return nil, err
  69. }
  70. parent, err := c.repo.getCommit(id)
  71. if err != nil {
  72. return nil, err
  73. }
  74. return parent, nil
  75. }
  76. // ParentCount returns number of parents of the commit.
  77. // 0 if this is the root commit, otherwise 1,2, etc.
  78. func (c *Commit) ParentCount() int {
  79. return len(c.parents)
  80. }
  81. func isImageFile(data []byte) (string, bool) {
  82. contentType := http.DetectContentType(data)
  83. if strings.Index(contentType, "image/") != -1 {
  84. return contentType, true
  85. }
  86. return contentType, false
  87. }
  88. // IsImageFile is a file image type
  89. func (c *Commit) IsImageFile(name string) bool {
  90. blob, err := c.GetBlobByPath(name)
  91. if err != nil {
  92. return false
  93. }
  94. dataRc, err := blob.DataAsync()
  95. if err != nil {
  96. return false
  97. }
  98. defer dataRc.Close()
  99. buf := make([]byte, 1024)
  100. n, _ := dataRc.Read(buf)
  101. buf = buf[:n]
  102. _, isImage := isImageFile(buf)
  103. return isImage
  104. }
  105. // GetCommitByPath return the commit of relative path object.
  106. func (c *Commit) GetCommitByPath(relpath string) (*Commit, error) {
  107. return c.repo.getCommitByPathWithID(c.ID, relpath)
  108. }
  109. // AddChanges marks local changes to be ready for commit.
  110. func AddChanges(repoPath string, all bool, files ...string) error {
  111. cmd := NewCommand("add")
  112. if all {
  113. cmd.AddArguments("--all")
  114. }
  115. _, err := cmd.AddArguments(files...).RunInDir(repoPath)
  116. return err
  117. }
  118. // CommitChangesOptions the options when a commit created
  119. type CommitChangesOptions struct {
  120. Committer *Signature
  121. Author *Signature
  122. Message string
  123. }
  124. // CommitChanges commits local changes with given committer, author and message.
  125. // If author is nil, it will be the same as committer.
  126. func CommitChanges(repoPath string, opts CommitChangesOptions) error {
  127. cmd := NewCommand()
  128. if opts.Committer != nil {
  129. cmd.AddArguments("-c", "user.name="+opts.Committer.Name, "-c", "user.email="+opts.Committer.Email)
  130. }
  131. cmd.AddArguments("commit")
  132. if opts.Author == nil {
  133. opts.Author = opts.Committer
  134. }
  135. if opts.Author != nil {
  136. cmd.AddArguments(fmt.Sprintf("--author='%s <%s>'", opts.Author.Name, opts.Author.Email))
  137. }
  138. cmd.AddArguments("-m", opts.Message)
  139. _, err := cmd.RunInDir(repoPath)
  140. // No stderr but exit status 1 means nothing to commit.
  141. if err != nil && err.Error() == "exit status 1" {
  142. return nil
  143. }
  144. return err
  145. }
  146. func commitsCount(repoPath, revision, relpath string) (int64, error) {
  147. var cmd *Command
  148. cmd = NewCommand("rev-list", "--count")
  149. cmd.AddArguments(revision)
  150. if len(relpath) > 0 {
  151. cmd.AddArguments("--", relpath)
  152. }
  153. stdout, err := cmd.RunInDir(repoPath)
  154. if err != nil {
  155. return 0, err
  156. }
  157. return strconv.ParseInt(strings.TrimSpace(stdout), 10, 64)
  158. }
  159. // CommitsCount returns number of total commits of until given revision.
  160. func CommitsCount(repoPath, revision string) (int64, error) {
  161. return commitsCount(repoPath, revision, "")
  162. }
  163. // CommitsCount returns number of total commits of until current revision.
  164. func (c *Commit) CommitsCount() (int64, error) {
  165. return CommitsCount(c.repo.Path, c.ID.String())
  166. }
  167. // CommitsByRange returns the specific page commits before current revision, every page's number default by CommitsRangeSize
  168. func (c *Commit) CommitsByRange(page int) (*list.List, error) {
  169. return c.repo.commitsByRange(c.ID, page)
  170. }
  171. // CommitsBefore returns all the commits before current revision
  172. func (c *Commit) CommitsBefore() (*list.List, error) {
  173. return c.repo.getCommitsBefore(c.ID)
  174. }
  175. // CommitsBeforeLimit returns num commits before current revision
  176. func (c *Commit) CommitsBeforeLimit(num int) (*list.List, error) {
  177. return c.repo.getCommitsBeforeLimit(c.ID, num)
  178. }
  179. // CommitsBeforeUntil returns the commits between commitID to current revision
  180. func (c *Commit) CommitsBeforeUntil(commitID string) (*list.List, error) {
  181. endCommit, err := c.repo.GetCommit(commitID)
  182. if err != nil {
  183. return nil, err
  184. }
  185. return c.repo.CommitsBetween(c, endCommit)
  186. }
  187. // SearchCommitsOptions specify the parameters for SearchCommits
  188. type SearchCommitsOptions struct {
  189. Keywords []string
  190. Authors, Committers []string
  191. After, Before string
  192. All bool
  193. }
  194. // NewSearchCommitsOptions contruct a SearchCommitsOption from a space-delimited search string
  195. func NewSearchCommitsOptions(searchString string, forAllRefs bool) SearchCommitsOptions {
  196. var keywords, authors, committers []string
  197. var after, before string
  198. fields := strings.Fields(searchString)
  199. for _, k := range fields {
  200. switch {
  201. case strings.HasPrefix(k, "author:"):
  202. authors = append(authors, strings.TrimPrefix(k, "author:"))
  203. case strings.HasPrefix(k, "committer:"):
  204. committers = append(committers, strings.TrimPrefix(k, "committer:"))
  205. case strings.HasPrefix(k, "after:"):
  206. after = strings.TrimPrefix(k, "after:")
  207. case strings.HasPrefix(k, "before:"):
  208. before = strings.TrimPrefix(k, "before:")
  209. default:
  210. keywords = append(keywords, k)
  211. }
  212. }
  213. return SearchCommitsOptions{
  214. Keywords: keywords,
  215. Authors: authors,
  216. Committers: committers,
  217. After: after,
  218. Before: before,
  219. All: forAllRefs,
  220. }
  221. }
  222. // SearchCommits returns the commits match the keyword before current revision
  223. func (c *Commit) SearchCommits(opts SearchCommitsOptions) (*list.List, error) {
  224. return c.repo.searchCommits(c.ID, opts)
  225. }
  226. // GetFilesChangedSinceCommit get all changed file names between pastCommit to current revision
  227. func (c *Commit) GetFilesChangedSinceCommit(pastCommit string) ([]string, error) {
  228. return c.repo.getFilesChanged(pastCommit, c.ID.String())
  229. }
  230. // FileChangedSinceCommit Returns true if the file given has changed since the the past commit
  231. func (c *Commit) FileChangedSinceCommit(filename, pastCommit string) (bool, error) {
  232. return c.repo.FileChangedBetweenCommits(filename, pastCommit, c.ID.String())
  233. }
  234. // GetSubModules get all the sub modules of current revision git tree
  235. func (c *Commit) GetSubModules() (*ObjectCache, error) {
  236. if c.submoduleCache != nil {
  237. return c.submoduleCache, nil
  238. }
  239. entry, err := c.GetTreeEntryByPath(".gitmodules")
  240. if err != nil {
  241. if _, ok := err.(ErrNotExist); ok {
  242. return nil, nil
  243. }
  244. return nil, err
  245. }
  246. rd, err := entry.Blob().Data()
  247. if err != nil {
  248. return nil, err
  249. }
  250. scanner := bufio.NewScanner(rd)
  251. c.submoduleCache = newObjectCache()
  252. var ismodule bool
  253. var path string
  254. for scanner.Scan() {
  255. if strings.HasPrefix(scanner.Text(), "[submodule") {
  256. ismodule = true
  257. continue
  258. }
  259. if ismodule {
  260. fields := strings.Split(scanner.Text(), "=")
  261. k := strings.TrimSpace(fields[0])
  262. if k == "path" {
  263. path = strings.TrimSpace(fields[1])
  264. } else if k == "url" {
  265. c.submoduleCache.Set(path, &SubModule{path, strings.TrimSpace(fields[1])})
  266. ismodule = false
  267. }
  268. }
  269. }
  270. return c.submoduleCache, nil
  271. }
  272. // GetSubModule get the sub module according entryname
  273. func (c *Commit) GetSubModule(entryname string) (*SubModule, error) {
  274. modules, err := c.GetSubModules()
  275. if err != nil {
  276. return nil, err
  277. }
  278. if modules != nil {
  279. module, has := modules.Get(entryname)
  280. if has {
  281. return module.(*SubModule), nil
  282. }
  283. }
  284. return nil, nil
  285. }
  286. // CommitFileStatus represents status of files in a commit.
  287. type CommitFileStatus struct {
  288. Added []string
  289. Removed []string
  290. Modified []string
  291. }
  292. // NewCommitFileStatus creates a CommitFileStatus
  293. func NewCommitFileStatus() *CommitFileStatus {
  294. return &CommitFileStatus{
  295. []string{}, []string{}, []string{},
  296. }
  297. }
  298. // GetCommitFileStatus returns file status of commit in given repository.
  299. func GetCommitFileStatus(repoPath, commitID string) (*CommitFileStatus, error) {
  300. stdout, w := io.Pipe()
  301. done := make(chan struct{})
  302. fileStatus := NewCommitFileStatus()
  303. go func() {
  304. scanner := bufio.NewScanner(stdout)
  305. for scanner.Scan() {
  306. fields := strings.Fields(scanner.Text())
  307. if len(fields) < 2 {
  308. continue
  309. }
  310. switch fields[0][0] {
  311. case 'A':
  312. fileStatus.Added = append(fileStatus.Added, fields[1])
  313. case 'D':
  314. fileStatus.Removed = append(fileStatus.Removed, fields[1])
  315. case 'M':
  316. fileStatus.Modified = append(fileStatus.Modified, fields[1])
  317. }
  318. }
  319. done <- struct{}{}
  320. }()
  321. stderr := new(bytes.Buffer)
  322. err := NewCommand("show", "--name-status", "--pretty=format:''", commitID).RunInDirPipeline(repoPath, w, stderr)
  323. w.Close() // Close writer to exit parsing goroutine
  324. if err != nil {
  325. return nil, concatenateError(err, stderr.String())
  326. }
  327. <-done
  328. return fileStatus, nil
  329. }
  330. // GetFullCommitID returns full length (40) of commit ID by given short SHA in a repository.
  331. func GetFullCommitID(repoPath, shortID string) (string, error) {
  332. if len(shortID) >= 40 {
  333. return shortID, nil
  334. }
  335. commitID, err := NewCommand("rev-parse", shortID).RunInDir(repoPath)
  336. if err != nil {
  337. if strings.Contains(err.Error(), "exit status 128") {
  338. return "", ErrNotExist{shortID, ""}
  339. }
  340. return "", err
  341. }
  342. return strings.TrimSpace(commitID), nil
  343. }