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.

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