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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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. "context"
  10. "errors"
  11. "fmt"
  12. "io"
  13. "os/exec"
  14. "strconv"
  15. "strings"
  16. "code.gitea.io/gitea/modules/log"
  17. "code.gitea.io/gitea/modules/util"
  18. )
  19. // Commit represents a git commit.
  20. type Commit struct {
  21. Branch string // Branch this commit belongs to
  22. Tree
  23. ID SHA1 // The ID of this commit object
  24. Author *Signature
  25. Committer *Signature
  26. CommitMessage string
  27. Signature *CommitGPGSignature
  28. Parents []SHA1 // SHA1 strings
  29. submoduleCache *ObjectCache
  30. }
  31. // CommitGPGSignature represents a git commit signature part.
  32. type CommitGPGSignature struct {
  33. Signature string
  34. Payload string // TODO check if can be reconstruct from the rest of commit information to not have duplicate data
  35. }
  36. // Message returns the commit message. Same as retrieving CommitMessage directly.
  37. func (c *Commit) Message() string {
  38. return c.CommitMessage
  39. }
  40. // Summary returns first line of commit message.
  41. func (c *Commit) Summary() string {
  42. return strings.Split(strings.TrimSpace(c.CommitMessage), "\n")[0]
  43. }
  44. // ParentID returns oid of n-th parent (0-based index).
  45. // It returns nil if no such parent exists.
  46. func (c *Commit) ParentID(n int) (SHA1, error) {
  47. if n >= len(c.Parents) {
  48. return SHA1{}, ErrNotExist{"", ""}
  49. }
  50. return c.Parents[n], nil
  51. }
  52. // Parent returns n-th parent (0-based index) of the commit.
  53. func (c *Commit) Parent(n int) (*Commit, error) {
  54. id, err := c.ParentID(n)
  55. if err != nil {
  56. return nil, err
  57. }
  58. parent, err := c.repo.getCommit(id)
  59. if err != nil {
  60. return nil, err
  61. }
  62. return parent, nil
  63. }
  64. // ParentCount returns number of parents of the commit.
  65. // 0 if this is the root commit, otherwise 1,2, etc.
  66. func (c *Commit) ParentCount() int {
  67. return len(c.Parents)
  68. }
  69. // GetCommitByPath return the commit of relative path object.
  70. func (c *Commit) GetCommitByPath(relpath string) (*Commit, error) {
  71. if c.repo.LastCommitCache != nil {
  72. return c.repo.LastCommitCache.GetCommitByPath(c.ID.String(), relpath)
  73. }
  74. return c.repo.getCommitByPathWithID(c.ID, relpath)
  75. }
  76. // AddChanges marks local changes to be ready for commit.
  77. func AddChanges(repoPath string, all bool, files ...string) error {
  78. return AddChangesWithArgs(repoPath, globalCommandArgs, all, files...)
  79. }
  80. // AddChangesWithArgs marks local changes to be ready for commit.
  81. func AddChangesWithArgs(repoPath string, globalArgs []string, all bool, files ...string) error {
  82. cmd := NewCommandNoGlobals(append(globalArgs, "add")...)
  83. if all {
  84. cmd.AddArguments("--all")
  85. }
  86. cmd.AddArguments("--")
  87. _, _, err := cmd.AddArguments(files...).RunStdString(&RunOpts{Dir: repoPath})
  88. return err
  89. }
  90. // CommitChangesOptions the options when a commit created
  91. type CommitChangesOptions struct {
  92. Committer *Signature
  93. Author *Signature
  94. Message string
  95. }
  96. // CommitChanges commits local changes with given committer, author and message.
  97. // If author is nil, it will be the same as committer.
  98. func CommitChanges(repoPath string, opts CommitChangesOptions) error {
  99. cargs := make([]string, len(globalCommandArgs))
  100. copy(cargs, globalCommandArgs)
  101. return CommitChangesWithArgs(repoPath, cargs, opts)
  102. }
  103. // CommitChangesWithArgs commits local changes with given committer, author and message.
  104. // If author is nil, it will be the same as committer.
  105. func CommitChangesWithArgs(repoPath string, args []string, opts CommitChangesOptions) error {
  106. cmd := NewCommandNoGlobals(args...)
  107. if opts.Committer != nil {
  108. cmd.AddArguments("-c", "user.name="+opts.Committer.Name, "-c", "user.email="+opts.Committer.Email)
  109. }
  110. cmd.AddArguments("commit")
  111. if opts.Author == nil {
  112. opts.Author = opts.Committer
  113. }
  114. if opts.Author != nil {
  115. cmd.AddArguments(fmt.Sprintf("--author='%s <%s>'", opts.Author.Name, opts.Author.Email))
  116. }
  117. cmd.AddArguments("-m", opts.Message)
  118. _, _, err := cmd.RunStdString(&RunOpts{Dir: repoPath})
  119. // No stderr but exit status 1 means nothing to commit.
  120. if err != nil && err.Error() == "exit status 1" {
  121. return nil
  122. }
  123. return err
  124. }
  125. // AllCommitsCount returns count of all commits in repository
  126. func AllCommitsCount(ctx context.Context, repoPath string, hidePRRefs bool, files ...string) (int64, error) {
  127. args := []string{"--all", "--count"}
  128. if hidePRRefs {
  129. args = append([]string{"--exclude=" + PullPrefix + "*"}, args...)
  130. }
  131. cmd := NewCommand(ctx, "rev-list")
  132. cmd.AddArguments(args...)
  133. if len(files) > 0 {
  134. cmd.AddArguments("--")
  135. cmd.AddArguments(files...)
  136. }
  137. stdout, _, err := cmd.RunStdString(&RunOpts{Dir: repoPath})
  138. if err != nil {
  139. return 0, err
  140. }
  141. return strconv.ParseInt(strings.TrimSpace(stdout), 10, 64)
  142. }
  143. // CommitsCountFiles returns number of total commits of until given revision.
  144. func CommitsCountFiles(ctx context.Context, repoPath string, revision, relpath []string) (int64, error) {
  145. cmd := NewCommand(ctx, "rev-list", "--count")
  146. cmd.AddArguments(revision...)
  147. if len(relpath) > 0 {
  148. cmd.AddArguments("--")
  149. cmd.AddArguments(relpath...)
  150. }
  151. stdout, _, err := cmd.RunStdString(&RunOpts{Dir: repoPath})
  152. if err != nil {
  153. return 0, err
  154. }
  155. return strconv.ParseInt(strings.TrimSpace(stdout), 10, 64)
  156. }
  157. // CommitsCount returns number of total commits of until given revision.
  158. func CommitsCount(ctx context.Context, repoPath string, revision ...string) (int64, error) {
  159. return CommitsCountFiles(ctx, repoPath, revision, []string{})
  160. }
  161. // CommitsCount returns number of total commits of until current revision.
  162. func (c *Commit) CommitsCount() (int64, error) {
  163. return CommitsCount(c.repo.Ctx, c.repo.Path, c.ID.String())
  164. }
  165. // CommitsByRange returns the specific page commits before current revision, every page's number default by CommitsRangeSize
  166. func (c *Commit) CommitsByRange(page, pageSize int) ([]*Commit, error) {
  167. return c.repo.commitsByRange(c.ID, page, pageSize)
  168. }
  169. // CommitsBefore returns all the commits before current revision
  170. func (c *Commit) CommitsBefore() ([]*Commit, error) {
  171. return c.repo.getCommitsBefore(c.ID)
  172. }
  173. // HasPreviousCommit returns true if a given commitHash is contained in commit's parents
  174. func (c *Commit) HasPreviousCommit(commitHash SHA1) (bool, error) {
  175. this := c.ID.String()
  176. that := commitHash.String()
  177. if this == that {
  178. return false, nil
  179. }
  180. _, _, err := NewCommand(c.repo.Ctx, "merge-base", "--is-ancestor", that, this).RunStdString(&RunOpts{Dir: c.repo.Path})
  181. if err == nil {
  182. return true, nil
  183. }
  184. var exitError *exec.ExitError
  185. if errors.As(err, &exitError) {
  186. if exitError.ProcessState.ExitCode() == 1 && len(exitError.Stderr) == 0 {
  187. return false, nil
  188. }
  189. }
  190. return false, err
  191. }
  192. // CommitsBeforeLimit returns num commits before current revision
  193. func (c *Commit) CommitsBeforeLimit(num int) ([]*Commit, error) {
  194. return c.repo.getCommitsBeforeLimit(c.ID, num)
  195. }
  196. // CommitsBeforeUntil returns the commits between commitID to current revision
  197. func (c *Commit) CommitsBeforeUntil(commitID string) ([]*Commit, error) {
  198. endCommit, err := c.repo.GetCommit(commitID)
  199. if err != nil {
  200. return nil, err
  201. }
  202. return c.repo.CommitsBetween(c, endCommit)
  203. }
  204. // SearchCommitsOptions specify the parameters for SearchCommits
  205. type SearchCommitsOptions struct {
  206. Keywords []string
  207. Authors, Committers []string
  208. After, Before string
  209. All bool
  210. }
  211. // NewSearchCommitsOptions construct a SearchCommitsOption from a space-delimited search string
  212. func NewSearchCommitsOptions(searchString string, forAllRefs bool) SearchCommitsOptions {
  213. var keywords, authors, committers []string
  214. var after, before string
  215. fields := strings.Fields(searchString)
  216. for _, k := range fields {
  217. switch {
  218. case strings.HasPrefix(k, "author:"):
  219. authors = append(authors, strings.TrimPrefix(k, "author:"))
  220. case strings.HasPrefix(k, "committer:"):
  221. committers = append(committers, strings.TrimPrefix(k, "committer:"))
  222. case strings.HasPrefix(k, "after:"):
  223. after = strings.TrimPrefix(k, "after:")
  224. case strings.HasPrefix(k, "before:"):
  225. before = strings.TrimPrefix(k, "before:")
  226. default:
  227. keywords = append(keywords, k)
  228. }
  229. }
  230. return SearchCommitsOptions{
  231. Keywords: keywords,
  232. Authors: authors,
  233. Committers: committers,
  234. After: after,
  235. Before: before,
  236. All: forAllRefs,
  237. }
  238. }
  239. // SearchCommits returns the commits match the keyword before current revision
  240. func (c *Commit) SearchCommits(opts SearchCommitsOptions) ([]*Commit, error) {
  241. return c.repo.searchCommits(c.ID, opts)
  242. }
  243. // GetFilesChangedSinceCommit get all changed file names between pastCommit to current revision
  244. func (c *Commit) GetFilesChangedSinceCommit(pastCommit string) ([]string, error) {
  245. return c.repo.getFilesChanged(pastCommit, c.ID.String())
  246. }
  247. // FileChangedSinceCommit Returns true if the file given has changed since the the past commit
  248. // YOU MUST ENSURE THAT pastCommit is a valid commit ID.
  249. func (c *Commit) FileChangedSinceCommit(filename, pastCommit string) (bool, error) {
  250. return c.repo.FileChangedBetweenCommits(filename, pastCommit, c.ID.String())
  251. }
  252. // HasFile returns true if the file given exists on this commit
  253. // This does only mean it's there - it does not mean the file was changed during the commit.
  254. func (c *Commit) HasFile(filename string) (bool, error) {
  255. _, err := c.GetBlobByPath(filename)
  256. if err != nil {
  257. return false, err
  258. }
  259. return true, nil
  260. }
  261. // GetFileContent reads a file content as a string or returns false if this was not possible
  262. func (c *Commit) GetFileContent(filename string, limit int) (string, error) {
  263. entry, err := c.GetTreeEntryByPath(filename)
  264. if err != nil {
  265. return "", err
  266. }
  267. r, err := entry.Blob().DataAsync()
  268. if err != nil {
  269. return "", err
  270. }
  271. defer r.Close()
  272. if limit > 0 {
  273. bs := make([]byte, limit)
  274. n, err := util.ReadAtMost(r, bs)
  275. if err != nil {
  276. return "", err
  277. }
  278. return string(bs[:n]), nil
  279. }
  280. bytes, err := io.ReadAll(r)
  281. if err != nil {
  282. return "", err
  283. }
  284. return string(bytes), nil
  285. }
  286. // GetSubModules get all the sub modules of current revision git tree
  287. func (c *Commit) GetSubModules() (*ObjectCache, error) {
  288. if c.submoduleCache != nil {
  289. return c.submoduleCache, nil
  290. }
  291. entry, err := c.GetTreeEntryByPath(".gitmodules")
  292. if err != nil {
  293. if _, ok := err.(ErrNotExist); ok {
  294. return nil, nil
  295. }
  296. return nil, err
  297. }
  298. rd, err := entry.Blob().DataAsync()
  299. if err != nil {
  300. return nil, err
  301. }
  302. defer rd.Close()
  303. scanner := bufio.NewScanner(rd)
  304. c.submoduleCache = newObjectCache()
  305. var ismodule bool
  306. var path string
  307. for scanner.Scan() {
  308. if strings.HasPrefix(scanner.Text(), "[submodule") {
  309. ismodule = true
  310. continue
  311. }
  312. if ismodule {
  313. fields := strings.Split(scanner.Text(), "=")
  314. k := strings.TrimSpace(fields[0])
  315. if k == "path" {
  316. path = strings.TrimSpace(fields[1])
  317. } else if k == "url" {
  318. c.submoduleCache.Set(path, &SubModule{path, strings.TrimSpace(fields[1])})
  319. ismodule = false
  320. }
  321. }
  322. }
  323. return c.submoduleCache, nil
  324. }
  325. // GetSubModule get the sub module according entryname
  326. func (c *Commit) GetSubModule(entryname string) (*SubModule, error) {
  327. modules, err := c.GetSubModules()
  328. if err != nil {
  329. return nil, err
  330. }
  331. if modules != nil {
  332. module, has := modules.Get(entryname)
  333. if has {
  334. return module.(*SubModule), nil
  335. }
  336. }
  337. return nil, nil
  338. }
  339. // GetBranchName gets the closest branch name (as returned by 'git name-rev --name-only')
  340. func (c *Commit) GetBranchName() (string, error) {
  341. args := []string{
  342. "name-rev",
  343. }
  344. if CheckGitVersionAtLeast("2.13.0") == nil {
  345. args = append(args, "--exclude", "refs/tags/*")
  346. }
  347. args = append(args, "--name-only", "--no-undefined", c.ID.String())
  348. data, _, err := NewCommand(c.repo.Ctx, args...).RunStdString(&RunOpts{Dir: c.repo.Path})
  349. if err != nil {
  350. // handle special case where git can not describe commit
  351. if strings.Contains(err.Error(), "cannot describe") {
  352. return "", nil
  353. }
  354. return "", err
  355. }
  356. // name-rev commitID output will be "master" or "master~12"
  357. return strings.SplitN(strings.TrimSpace(data), "~", 2)[0], nil
  358. }
  359. // LoadBranchName load branch name for commit
  360. func (c *Commit) LoadBranchName() (err error) {
  361. if len(c.Branch) != 0 {
  362. return
  363. }
  364. c.Branch, err = c.GetBranchName()
  365. return err
  366. }
  367. // GetTagName gets the current tag name for given commit
  368. func (c *Commit) GetTagName() (string, error) {
  369. data, _, err := NewCommand(c.repo.Ctx, "describe", "--exact-match", "--tags", "--always", c.ID.String()).RunStdString(&RunOpts{Dir: c.repo.Path})
  370. if err != nil {
  371. // handle special case where there is no tag for this commit
  372. if strings.Contains(err.Error(), "no tag exactly matches") {
  373. return "", nil
  374. }
  375. return "", err
  376. }
  377. return strings.TrimSpace(data), nil
  378. }
  379. // CommitFileStatus represents status of files in a commit.
  380. type CommitFileStatus struct {
  381. Added []string
  382. Removed []string
  383. Modified []string
  384. }
  385. // NewCommitFileStatus creates a CommitFileStatus
  386. func NewCommitFileStatus() *CommitFileStatus {
  387. return &CommitFileStatus{
  388. []string{}, []string{}, []string{},
  389. }
  390. }
  391. func parseCommitFileStatus(fileStatus *CommitFileStatus, stdout io.Reader) {
  392. rd := bufio.NewReader(stdout)
  393. peek, err := rd.Peek(1)
  394. if err != nil {
  395. if err != io.EOF {
  396. log.Error("Unexpected error whilst reading from git log --name-status. Error: %v", err)
  397. }
  398. return
  399. }
  400. if peek[0] == '\n' || peek[0] == '\x00' {
  401. _, _ = rd.Discard(1)
  402. }
  403. for {
  404. modifier, err := rd.ReadSlice('\x00')
  405. if err != nil {
  406. if err != io.EOF {
  407. log.Error("Unexpected error whilst reading from git log --name-status. Error: %v", err)
  408. }
  409. return
  410. }
  411. file, err := rd.ReadString('\x00')
  412. if err != nil {
  413. if err != io.EOF {
  414. log.Error("Unexpected error whilst reading from git log --name-status. Error: %v", err)
  415. }
  416. return
  417. }
  418. file = file[:len(file)-1]
  419. switch modifier[0] {
  420. case 'A':
  421. fileStatus.Added = append(fileStatus.Added, file)
  422. case 'D':
  423. fileStatus.Removed = append(fileStatus.Removed, file)
  424. case 'M':
  425. fileStatus.Modified = append(fileStatus.Modified, file)
  426. }
  427. }
  428. }
  429. // GetCommitFileStatus returns file status of commit in given repository.
  430. func GetCommitFileStatus(ctx context.Context, repoPath, commitID string) (*CommitFileStatus, error) {
  431. stdout, w := io.Pipe()
  432. done := make(chan struct{})
  433. fileStatus := NewCommitFileStatus()
  434. go func() {
  435. parseCommitFileStatus(fileStatus, stdout)
  436. close(done)
  437. }()
  438. stderr := new(bytes.Buffer)
  439. args := []string{"log", "--name-status", "-c", "--pretty=format:", "--parents", "--no-renames", "-z", "-1", commitID}
  440. err := NewCommand(ctx, args...).Run(&RunOpts{
  441. Dir: repoPath,
  442. Stdout: w,
  443. Stderr: stderr,
  444. })
  445. w.Close() // Close writer to exit parsing goroutine
  446. if err != nil {
  447. return nil, ConcatenateError(err, stderr.String())
  448. }
  449. <-done
  450. return fileStatus, nil
  451. }
  452. // GetFullCommitID returns full length (40) of commit ID by given short SHA in a repository.
  453. func GetFullCommitID(ctx context.Context, repoPath, shortID string) (string, error) {
  454. commitID, _, err := NewCommand(ctx, "rev-parse", shortID).RunStdString(&RunOpts{Dir: repoPath})
  455. if err != nil {
  456. if strings.Contains(err.Error(), "exit status 128") {
  457. return "", ErrNotExist{shortID, ""}
  458. }
  459. return "", err
  460. }
  461. return strings.TrimSpace(commitID), nil
  462. }
  463. // GetRepositoryDefaultPublicGPGKey returns the default public key for this commit
  464. func (c *Commit) GetRepositoryDefaultPublicGPGKey(forceUpdate bool) (*GPGSettings, error) {
  465. if c.repo == nil {
  466. return nil, nil
  467. }
  468. return c.repo.GetDefaultPublicGPGKey(forceUpdate)
  469. }