commit.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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. // CommitsCount returns number of total commits of until given revision.
  144. func CommitsCount(repoPath, revision string) (int64, error) {
  145. return commitsCount(repoPath, revision, "")
  146. }
  147. func (c *Commit) CommitsCount() (int64, error) {
  148. return CommitsCount(c.repo.Path, c.ID.String())
  149. }
  150. func (c *Commit) CommitsByRangeSize(page, size int) (*list.List, error) {
  151. return c.repo.CommitsByRangeSize(c.ID.String(), page, size)
  152. }
  153. func (c *Commit) CommitsByRange(page int) (*list.List, error) {
  154. return c.repo.CommitsByRange(c.ID.String(), page)
  155. }
  156. func (c *Commit) CommitsBefore() (*list.List, error) {
  157. return c.repo.getCommitsBefore(c.ID)
  158. }
  159. func (c *Commit) CommitsBeforeLimit(num int) (*list.List, error) {
  160. return c.repo.getCommitsBeforeLimit(c.ID, num)
  161. }
  162. func (c *Commit) CommitsBeforeUntil(commitID string) (*list.List, error) {
  163. endCommit, err := c.repo.GetCommit(commitID)
  164. if err != nil {
  165. return nil, err
  166. }
  167. return c.repo.CommitsBetween(c, endCommit)
  168. }
  169. func (c *Commit) SearchCommits(keyword string) (*list.List, error) {
  170. return c.repo.searchCommits(c.ID, keyword)
  171. }
  172. func (c *Commit) GetFilesChangedSinceCommit(pastCommit string) ([]string, error) {
  173. return c.repo.getFilesChanged(pastCommit, c.ID.String())
  174. }
  175. func (c *Commit) GetSubModules() (*objectCache, error) {
  176. if c.submoduleCache != nil {
  177. return c.submoduleCache, nil
  178. }
  179. entry, err := c.GetTreeEntryByPath(".gitmodules")
  180. if err != nil {
  181. return nil, err
  182. }
  183. rd, err := entry.Blob().Data()
  184. if err != nil {
  185. return nil, err
  186. }
  187. scanner := bufio.NewScanner(rd)
  188. c.submoduleCache = newObjectCache()
  189. var ismodule bool
  190. var path string
  191. for scanner.Scan() {
  192. if strings.HasPrefix(scanner.Text(), "[submodule") {
  193. ismodule = true
  194. continue
  195. }
  196. if ismodule {
  197. fields := strings.Split(scanner.Text(), "=")
  198. k := strings.TrimSpace(fields[0])
  199. if k == "path" {
  200. path = strings.TrimSpace(fields[1])
  201. } else if k == "url" {
  202. c.submoduleCache.Set(path, &SubModule{path, strings.TrimSpace(fields[1])})
  203. ismodule = false
  204. }
  205. }
  206. }
  207. return c.submoduleCache, nil
  208. }
  209. func (c *Commit) GetSubModule(entryname string) (*SubModule, error) {
  210. modules, err := c.GetSubModules()
  211. if err != nil {
  212. return nil, err
  213. }
  214. module, has := modules.Get(entryname)
  215. if has {
  216. return module.(*SubModule), nil
  217. }
  218. return nil, nil
  219. }
  220. // CommitFileStatus represents status of files in a commit.
  221. type CommitFileStatus struct {
  222. Added []string
  223. Removed []string
  224. Modified []string
  225. }
  226. func NewCommitFileStatus() *CommitFileStatus {
  227. return &CommitFileStatus{
  228. []string{}, []string{}, []string{},
  229. }
  230. }
  231. // GetCommitFileStatus returns file status of commit in given repository.
  232. func GetCommitFileStatus(repoPath, commitID string) (*CommitFileStatus, error) {
  233. stdout, w := io.Pipe()
  234. defer stdout.Close()
  235. stderr := new(bytes.Buffer)
  236. fileStatus := NewCommitFileStatus()
  237. go func() {
  238. scanner := bufio.NewScanner(stdout)
  239. for scanner.Scan() {
  240. fields := strings.Fields(scanner.Text())
  241. if len(fields) < 2 {
  242. continue
  243. }
  244. switch fields[0][0] {
  245. case 'A':
  246. fileStatus.Added = append(fileStatus.Added, fields[1])
  247. case 'D':
  248. fileStatus.Removed = append(fileStatus.Removed, fields[1])
  249. case 'M':
  250. fileStatus.Modified = append(fileStatus.Modified, fields[1])
  251. }
  252. }
  253. }()
  254. if err := NewCommand("log", "-1", "--name-status", "--pretty=format:''", commitID).RunInDirPipeline(repoPath, w, stderr); err != nil {
  255. return nil, concatenateError(err, stderr.String())
  256. }
  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. }