Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

commit.go 9.4KB

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