commit.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package git
  5. import (
  6. "bufio"
  7. "bytes"
  8. "container/list"
  9. "fmt"
  10. "io"
  11. "net/http"
  12. "strconv"
  13. "strings"
  14. )
  15. // Commit represents a git commit.
  16. type Commit struct {
  17. Tree
  18. ID sha1 // The ID of this commit object
  19. Author *Signature
  20. Committer *Signature
  21. CommitMessage string
  22. parents []sha1 // SHA1 strings
  23. submoduleCache *objectCache
  24. }
  25. // Message returns the commit message. Same as retrieving CommitMessage directly.
  26. func (c *Commit) Message() string {
  27. return c.CommitMessage
  28. }
  29. // Summary returns first line of commit message.
  30. func (c *Commit) Summary() string {
  31. return strings.Split(c.CommitMessage, "\n")[0]
  32. }
  33. // ParentID returns oid of n-th parent (0-based index).
  34. // It returns nil if no such parent exists.
  35. func (c *Commit) ParentID(n int) (sha1, error) {
  36. if n >= len(c.parents) {
  37. return sha1{}, ErrNotExist{"", ""}
  38. }
  39. return c.parents[n], nil
  40. }
  41. // Parent returns n-th parent (0-based index) of the commit.
  42. func (c *Commit) Parent(n int) (*Commit, error) {
  43. id, err := c.ParentID(n)
  44. if err != nil {
  45. return nil, err
  46. }
  47. parent, err := c.repo.getCommit(id)
  48. if err != nil {
  49. return nil, err
  50. }
  51. return parent, nil
  52. }
  53. // ParentCount returns number of parents of the commit.
  54. // 0 if this is the root commit, otherwise 1,2, etc.
  55. func (c *Commit) ParentCount() int {
  56. return len(c.parents)
  57. }
  58. func isImageFile(data []byte) (string, bool) {
  59. contentType := http.DetectContentType(data)
  60. if strings.Index(contentType, "image/") != -1 {
  61. return contentType, true
  62. }
  63. return contentType, false
  64. }
  65. func (c *Commit) IsImageFile(name string) bool {
  66. blob, err := c.GetBlobByPath(name)
  67. if err != nil {
  68. return false
  69. }
  70. dataRc, err := blob.Data()
  71. if err != nil {
  72. return false
  73. }
  74. buf := make([]byte, 1024)
  75. n, _ := dataRc.Read(buf)
  76. buf = buf[:n]
  77. _, isImage := isImageFile(buf)
  78. return isImage
  79. }
  80. // GetCommitByPath return the commit of relative path object.
  81. func (c *Commit) GetCommitByPath(relpath string) (*Commit, error) {
  82. return c.repo.getCommitByPathWithID(c.ID, relpath)
  83. }
  84. // AddChanges marks local changes to be ready for commit.
  85. func AddChanges(repoPath string, all bool, files ...string) error {
  86. cmd := NewCommand("add")
  87. if all {
  88. cmd.AddArguments("--all")
  89. }
  90. _, err := cmd.AddArguments(files...).RunInDir(repoPath)
  91. return err
  92. }
  93. type CommitChangesOptions struct {
  94. Committer *Signature
  95. Author *Signature
  96. Message string
  97. }
  98. // CommitChanges commits local changes with given committer, author and message.
  99. // If author is nil, it will be the same as committer.
  100. func CommitChanges(repoPath string, opts CommitChangesOptions) error {
  101. cmd := NewCommand()
  102. if opts.Committer != nil {
  103. cmd.AddEnvs("GIT_COMMITTER_NAME="+opts.Committer.Name, "GIT_COMMITTER_EMAIL="+opts.Committer.Email)
  104. }
  105. cmd.AddArguments("commit")
  106. if opts.Author == nil {
  107. opts.Author = opts.Committer
  108. }
  109. if opts.Author != nil {
  110. cmd.AddArguments(fmt.Sprintf("--author='%s <%s>'", opts.Author.Name, opts.Author.Email))
  111. }
  112. cmd.AddArguments("-m", opts.Message)
  113. _, err := cmd.RunInDir(repoPath)
  114. // No stderr but exit status 1 means nothing to commit.
  115. if err != nil && err.Error() == "exit status 1" {
  116. return nil
  117. }
  118. return err
  119. }
  120. func commitsCount(repoPath, revision, relpath string) (int64, error) {
  121. var cmd *Command
  122. cmd = NewCommand("rev-list", "--count").AddArguments(revision)
  123. if len(relpath) > 0 {
  124. cmd.AddArguments("--", relpath)
  125. }
  126. stdout, err := cmd.RunInDir(repoPath)
  127. if err != nil {
  128. return 0, err
  129. }
  130. return strconv.ParseInt(strings.TrimSpace(stdout), 10, 64)
  131. }
  132. func (c *Commit) CommitsCount() (int64, error) {
  133. return CommitsCount(c.repo.Path, c.ID.String())
  134. }
  135. func (c *Commit) CommitsByRangeSize(page, size int) (*list.List, error) {
  136. return c.repo.CommitsByRangeSize(c.ID.String(), page, size)
  137. }
  138. func (c *Commit) CommitsByRange(page int) (*list.List, error) {
  139. return c.repo.CommitsByRange(c.ID.String(), page)
  140. }
  141. func (c *Commit) CommitsBefore() (*list.List, error) {
  142. return c.repo.getCommitsBefore(c.ID)
  143. }
  144. func (c *Commit) CommitsBeforeLimit(num int) (*list.List, error) {
  145. return c.repo.getCommitsBeforeLimit(c.ID, num)
  146. }
  147. func (c *Commit) CommitsBeforeUntil(commitID string) (*list.List, error) {
  148. endCommit, err := c.repo.GetCommit(commitID)
  149. if err != nil {
  150. return nil, err
  151. }
  152. return c.repo.CommitsBetween(c, endCommit)
  153. }
  154. func (c *Commit) SearchCommits(keyword string) (*list.List, error) {
  155. return c.repo.searchCommits(c.ID, keyword)
  156. }
  157. func (c *Commit) GetFilesChangedSinceCommit(pastCommit string) ([]string, error) {
  158. return c.repo.getFilesChanged(pastCommit, c.ID.String())
  159. }
  160. func (c *Commit) GetSubModules() (*objectCache, error) {
  161. if c.submoduleCache != nil {
  162. return c.submoduleCache, nil
  163. }
  164. entry, err := c.GetTreeEntryByPath(".gitmodules")
  165. if err != nil {
  166. return nil, err
  167. }
  168. rd, err := entry.Blob().Data()
  169. if err != nil {
  170. return nil, err
  171. }
  172. scanner := bufio.NewScanner(rd)
  173. c.submoduleCache = newObjectCache()
  174. var ismodule bool
  175. var path string
  176. for scanner.Scan() {
  177. if strings.HasPrefix(scanner.Text(), "[submodule") {
  178. ismodule = true
  179. continue
  180. }
  181. if ismodule {
  182. fields := strings.Split(scanner.Text(), "=")
  183. k := strings.TrimSpace(fields[0])
  184. if k == "path" {
  185. path = strings.TrimSpace(fields[1])
  186. } else if k == "url" {
  187. c.submoduleCache.Set(path, &SubModule{path, strings.TrimSpace(fields[1])})
  188. ismodule = false
  189. }
  190. }
  191. }
  192. return c.submoduleCache, nil
  193. }
  194. func (c *Commit) GetSubModule(entryname string) (*SubModule, error) {
  195. modules, err := c.GetSubModules()
  196. if err != nil {
  197. return nil, err
  198. }
  199. module, has := modules.Get(entryname)
  200. if has {
  201. return module.(*SubModule), nil
  202. }
  203. return nil, nil
  204. }
  205. // CommitFileStatus represents status of files in a commit.
  206. type CommitFileStatus struct {
  207. Added []string
  208. Removed []string
  209. Modified []string
  210. }
  211. func NewCommitFileStatus() *CommitFileStatus {
  212. return &CommitFileStatus{
  213. []string{}, []string{}, []string{},
  214. }
  215. }
  216. // GetCommitFileStatus returns file status of commit in given repository.
  217. func GetCommitFileStatus(repoPath, commitID string) (*CommitFileStatus, error) {
  218. stdout, w := io.Pipe()
  219. done := make(chan struct{})
  220. fileStatus := NewCommitFileStatus()
  221. go func() {
  222. scanner := bufio.NewScanner(stdout)
  223. for scanner.Scan() {
  224. fields := strings.Fields(scanner.Text())
  225. if len(fields) < 2 {
  226. continue
  227. }
  228. switch fields[0][0] {
  229. case 'A':
  230. fileStatus.Added = append(fileStatus.Added, fields[1])
  231. case 'D':
  232. fileStatus.Removed = append(fileStatus.Removed, fields[1])
  233. case 'M':
  234. fileStatus.Modified = append(fileStatus.Modified, fields[1])
  235. }
  236. }
  237. done <- struct{}{}
  238. }()
  239. stderr := new(bytes.Buffer)
  240. err := NewCommand("show", "--name-status", "--pretty=format:''", commitID).RunInDirPipeline(repoPath, w, stderr)
  241. w.Close() // Close writer to exit parsing goroutine
  242. if err != nil {
  243. return nil, concatenateError(err, stderr.String())
  244. }
  245. <-done
  246. return fileStatus, nil
  247. }
  248. // FileStatus returns file status of commit.
  249. func (c *Commit) FileStatus() (*CommitFileStatus, error) {
  250. return GetCommitFileStatus(c.repo.Path, c.ID.String())
  251. }
  252. // GetFullCommitID returns full length (40) of commit ID by given short SHA in a repository.
  253. func GetFullCommitID(repoPath, shortID string) (string, error) {
  254. if len(shortID) >= 40 {
  255. return shortID, nil
  256. }
  257. commitID, err := NewCommand("rev-parse", shortID).RunInDir(repoPath)
  258. if err != nil {
  259. if strings.Contains(err.Error(), "exit status 128") {
  260. return "", ErrNotExist{shortID, ""}
  261. }
  262. return "", err
  263. }
  264. return strings.TrimSpace(commitID), nil
  265. }