commit.go 7.8 KB

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