You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

pull.go 22 kB

Improve listing performance by using go-git (#6478) * Use go-git for tree reading and commit info lookup. Signed-off-by: Filip Navara <navara@emclient.com> * Use TreeEntry.IsRegular() instead of ObjectType that was removed. Signed-off-by: Filip Navara <navara@emclient.com> * Use the treePath to optimize commit info search. Signed-off-by: Filip Navara <navara@emclient.com> * Extract the latest commit at treePath along with the other commits. Signed-off-by: Filip Navara <navara@emclient.com> * Fix listing commit info for a directory that was created in one commit and never modified after. Signed-off-by: Filip Navara <navara@emclient.com> * Avoid nearly all external 'git' invocations when doing directory listing (.editorconfig code path is still hit). Signed-off-by: Filip Navara <navara@emclient.com> * Use go-git for reading blobs. Signed-off-by: Filip Navara <navara@emclient.com> * Make SHA1 type alias for plumbing.Hash in go-git. Signed-off-by: Filip Navara <navara@emclient.com> * Make Signature type alias for object.Signature in go-git. Signed-off-by: Filip Navara <navara@emclient.com> * Fix GetCommitsInfo for repository with only one commit. Signed-off-by: Filip Navara <navara@emclient.com> * Fix PGP signature verification. Signed-off-by: Filip Navara <navara@emclient.com> * Fix issues with walking commit graph across merges. Signed-off-by: Filip Navara <navara@emclient.com> * Fix typo in condition. Signed-off-by: Filip Navara <navara@emclient.com> * Speed up loading branch list by keeping the repository reference (and thus all the loaded packfile indexes). Signed-off-by: Filip Navara <navara@emclient.com> * Fix lising submodules. Signed-off-by: Filip Navara <navara@emclient.com> * Fix build Signed-off-by: Filip Navara <navara@emclient.com> * Add back commit cache because of name-rev Signed-off-by: Filip Navara <navara@emclient.com> * Fix tests Signed-off-by: Filip Navara <navara@emclient.com> * Fix code style * Fix spelling * Address PR feedback Signed-off-by: Filip Navara <navara@emclient.com> * Update vendor module list Signed-off-by: Filip Navara <navara@emclient.com> * Fix getting trees by commit id Signed-off-by: Filip Navara <navara@emclient.com> * Fix remaining unit test failures * Fix GetTreeBySHA * Avoid running `git name-rev` if not necessary Signed-off-by: Filip Navara <navara@emclient.com> * Move Branch code to git module * Clean up GPG signature verification and fix it for tagged commits * Address PR feedback (import formatting, copyright headers) * Make blob lookup by SHA working * Update tests to use public API * Allow getting content from any type of object through the blob interface * Change test to actually expect the object content that is in the GIT repository * Change one more test to actually expect the object content that is in the GIT repository * Add comments
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
9 years ago
9 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Change target branch for pull request (#6488) * Adds functionality to change target branch of created pull requests Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use const instead of var in JavaScript additions Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Check if branches are equal and if PR already exists before changing target branch Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Make sure to check all commits Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Print error messages for user as error flash message Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Disallow changing target branch of closed or merged pull requests Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Resolve conflicts after merge of upstream/master Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Change order of branch select fields Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes duplicate check Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use ctx.Tr for translations Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Recompile JS Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use correct translation namespace Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Remove redundant if condition Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Moves most change branch logic into pull service Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Completes comment Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Add Ref to ChangesPayload for logging changed target branches instead of creating a new struct Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Revert changes to go.mod Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Directly use createComment method Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return 404 if pull request is not found. Move written check up Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Remove variable declaration Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return client errors on change pull request target errors Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return error in commit.HasPreviousCommit Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adds blank line Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Test patch before persisting new target branch Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Update patch before testing (not working) Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes patch calls when changeing pull request target Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes unneeded check for base name Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Moves ChangeTargetBranch completely to pull service. Update patch status. Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Set webhook mode after errors were validated Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Update PR in one transaction Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Move logic for check if head is equal with branch to pull model Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adds missing comment and simplify return Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adjust CreateComment method call Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com>
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 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 models
  6. import (
  7. "fmt"
  8. "io"
  9. "strings"
  10. "code.gitea.io/gitea/modules/git"
  11. "code.gitea.io/gitea/modules/log"
  12. "code.gitea.io/gitea/modules/setting"
  13. "code.gitea.io/gitea/modules/timeutil"
  14. )
  15. // PullRequestType defines pull request type
  16. type PullRequestType int
  17. // Enumerate all the pull request types
  18. const (
  19. PullRequestGitea PullRequestType = iota
  20. PullRequestGit
  21. )
  22. // PullRequestStatus defines pull request status
  23. type PullRequestStatus int
  24. // Enumerate all the pull request status
  25. const (
  26. PullRequestStatusConflict PullRequestStatus = iota
  27. PullRequestStatusChecking
  28. PullRequestStatusMergeable
  29. PullRequestStatusManuallyMerged
  30. PullRequestStatusError
  31. )
  32. // PullRequest represents relation between pull request and repositories.
  33. type PullRequest struct {
  34. ID int64 `xorm:"pk autoincr"`
  35. Type PullRequestType
  36. Status PullRequestStatus
  37. ConflictedFiles []string `xorm:"TEXT JSON"`
  38. IssueID int64 `xorm:"INDEX"`
  39. Issue *Issue `xorm:"-"`
  40. Index int64
  41. HeadRepoID int64 `xorm:"INDEX"`
  42. HeadRepo *Repository `xorm:"-"`
  43. BaseRepoID int64 `xorm:"INDEX"`
  44. BaseRepo *Repository `xorm:"-"`
  45. HeadBranch string
  46. BaseBranch string
  47. ProtectedBranch *ProtectedBranch `xorm:"-"`
  48. MergeBase string `xorm:"VARCHAR(40)"`
  49. HasMerged bool `xorm:"INDEX"`
  50. MergedCommitID string `xorm:"VARCHAR(40)"`
  51. MergerID int64 `xorm:"INDEX"`
  52. Merger *User `xorm:"-"`
  53. MergedUnix timeutil.TimeStamp `xorm:"updated INDEX"`
  54. }
  55. // MustHeadUserName returns the HeadRepo's username if failed return blank
  56. func (pr *PullRequest) MustHeadUserName() string {
  57. if err := pr.LoadHeadRepo(); err != nil {
  58. log.Error("LoadHeadRepo: %v", err)
  59. return ""
  60. }
  61. return pr.HeadRepo.OwnerName
  62. }
  63. // Note: don't try to get Issue because will end up recursive querying.
  64. func (pr *PullRequest) loadAttributes(e Engine) (err error) {
  65. if pr.HasMerged && pr.Merger == nil {
  66. pr.Merger, err = getUserByID(e, pr.MergerID)
  67. if IsErrUserNotExist(err) {
  68. pr.MergerID = -1
  69. pr.Merger = NewGhostUser()
  70. } else if err != nil {
  71. return fmt.Errorf("getUserByID [%d]: %v", pr.MergerID, err)
  72. }
  73. }
  74. return nil
  75. }
  76. // LoadAttributes loads pull request attributes from database
  77. func (pr *PullRequest) LoadAttributes() error {
  78. return pr.loadAttributes(x)
  79. }
  80. // LoadBaseRepo loads pull request base repository from database
  81. func (pr *PullRequest) LoadBaseRepo() error {
  82. if pr.BaseRepo == nil {
  83. if pr.HeadRepoID == pr.BaseRepoID && pr.HeadRepo != nil {
  84. pr.BaseRepo = pr.HeadRepo
  85. return nil
  86. }
  87. var repo Repository
  88. if has, err := x.ID(pr.BaseRepoID).Get(&repo); err != nil {
  89. return err
  90. } else if !has {
  91. return ErrRepoNotExist{ID: pr.BaseRepoID}
  92. }
  93. pr.BaseRepo = &repo
  94. }
  95. return nil
  96. }
  97. // LoadHeadRepo loads pull request head repository from database
  98. func (pr *PullRequest) LoadHeadRepo() error {
  99. if pr.HeadRepo == nil {
  100. if pr.HeadRepoID == pr.BaseRepoID && pr.BaseRepo != nil {
  101. pr.HeadRepo = pr.BaseRepo
  102. return nil
  103. }
  104. var repo Repository
  105. if has, err := x.ID(pr.HeadRepoID).Get(&repo); err != nil {
  106. return err
  107. } else if !has {
  108. return ErrRepoNotExist{ID: pr.HeadRepoID}
  109. }
  110. pr.HeadRepo = &repo
  111. }
  112. return nil
  113. }
  114. // LoadIssue loads issue information from database
  115. func (pr *PullRequest) LoadIssue() (err error) {
  116. return pr.loadIssue(x)
  117. }
  118. func (pr *PullRequest) loadIssue(e Engine) (err error) {
  119. if pr.Issue != nil {
  120. return nil
  121. }
  122. pr.Issue, err = getIssueByID(e, pr.IssueID)
  123. if err == nil {
  124. pr.Issue.PullRequest = pr
  125. }
  126. return err
  127. }
  128. // LoadProtectedBranch loads the protected branch of the base branch
  129. func (pr *PullRequest) LoadProtectedBranch() (err error) {
  130. return pr.loadProtectedBranch(x)
  131. }
  132. func (pr *PullRequest) loadProtectedBranch(e Engine) (err error) {
  133. if pr.ProtectedBranch == nil {
  134. if pr.BaseRepo == nil {
  135. if pr.BaseRepoID == 0 {
  136. return nil
  137. }
  138. pr.BaseRepo, err = getRepositoryByID(e, pr.BaseRepoID)
  139. if err != nil {
  140. return
  141. }
  142. }
  143. pr.ProtectedBranch, err = getProtectedBranchBy(e, pr.BaseRepo.ID, pr.BaseBranch)
  144. }
  145. return
  146. }
  147. // GetDefaultMergeMessage returns default message used when merging pull request
  148. func (pr *PullRequest) GetDefaultMergeMessage() string {
  149. if pr.HeadRepo == nil {
  150. var err error
  151. pr.HeadRepo, err = GetRepositoryByID(pr.HeadRepoID)
  152. if err != nil {
  153. log.Error("GetRepositoryById[%d]: %v", pr.HeadRepoID, err)
  154. return ""
  155. }
  156. }
  157. if err := pr.LoadIssue(); err != nil {
  158. log.Error("Cannot load issue %d for PR id %d: Error: %v", pr.IssueID, pr.ID, err)
  159. return ""
  160. }
  161. return fmt.Sprintf("Merge pull request '%s' (#%d) from %s/%s into %s", pr.Issue.Title, pr.Issue.Index, pr.MustHeadUserName(), pr.HeadBranch, pr.BaseBranch)
  162. }
  163. // GetCommitMessages returns the commit messages between head and merge base (if there is one)
  164. func (pr *PullRequest) GetCommitMessages() string {
  165. if err := pr.LoadIssue(); err != nil {
  166. log.Error("Cannot load issue %d for PR id %d: Error: %v", pr.IssueID, pr.ID, err)
  167. return ""
  168. }
  169. if err := pr.Issue.LoadPoster(); err != nil {
  170. log.Error("Cannot load poster %d for pr id %d, index %d Error: %v", pr.Issue.PosterID, pr.ID, pr.Index, err)
  171. return ""
  172. }
  173. if pr.HeadRepo == nil {
  174. var err error
  175. pr.HeadRepo, err = GetRepositoryByID(pr.HeadRepoID)
  176. if err != nil {
  177. log.Error("GetRepositoryById[%d]: %v", pr.HeadRepoID, err)
  178. return ""
  179. }
  180. }
  181. gitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  182. if err != nil {
  183. log.Error("Unable to open head repository: Error: %v", err)
  184. return ""
  185. }
  186. defer gitRepo.Close()
  187. headCommit, err := gitRepo.GetBranchCommit(pr.HeadBranch)
  188. if err != nil {
  189. log.Error("Unable to get head commit: %s Error: %v", pr.HeadBranch, err)
  190. return ""
  191. }
  192. mergeBase, err := gitRepo.GetCommit(pr.MergeBase)
  193. if err != nil {
  194. log.Error("Unable to get merge base commit: %s Error: %v", pr.MergeBase, err)
  195. return ""
  196. }
  197. limit := setting.Repository.PullRequest.DefaultMergeMessageCommitsLimit
  198. list, err := gitRepo.CommitsBetweenLimit(headCommit, mergeBase, limit, 0)
  199. if err != nil {
  200. log.Error("Unable to get commits between: %s %s Error: %v", pr.HeadBranch, pr.MergeBase, err)
  201. return ""
  202. }
  203. maxSize := setting.Repository.PullRequest.DefaultMergeMessageSize
  204. posterSig := pr.Issue.Poster.NewGitSig().String()
  205. authorsMap := map[string]bool{}
  206. authors := make([]string, 0, list.Len())
  207. stringBuilder := strings.Builder{}
  208. element := list.Front()
  209. for element != nil {
  210. commit := element.Value.(*git.Commit)
  211. if maxSize < 0 || stringBuilder.Len() < maxSize {
  212. toWrite := []byte(commit.CommitMessage)
  213. if len(toWrite) > maxSize-stringBuilder.Len() && maxSize > -1 {
  214. toWrite = append(toWrite[:maxSize-stringBuilder.Len()], "..."...)
  215. }
  216. if _, err := stringBuilder.Write(toWrite); err != nil {
  217. log.Error("Unable to write commit message Error: %v", err)
  218. return ""
  219. }
  220. if _, err := stringBuilder.WriteRune('\n'); err != nil {
  221. log.Error("Unable to write commit message Error: %v", err)
  222. return ""
  223. }
  224. }
  225. authorString := commit.Author.String()
  226. if !authorsMap[authorString] && authorString != posterSig {
  227. authors = append(authors, authorString)
  228. authorsMap[authorString] = true
  229. }
  230. element = element.Next()
  231. }
  232. // Consider collecting the remaining authors
  233. if limit >= 0 && setting.Repository.PullRequest.DefaultMergeMessageAllAuthors {
  234. skip := limit
  235. limit = 30
  236. for {
  237. list, err := gitRepo.CommitsBetweenLimit(headCommit, mergeBase, limit, skip)
  238. if err != nil {
  239. log.Error("Unable to get commits between: %s %s Error: %v", pr.HeadBranch, pr.MergeBase, err)
  240. return ""
  241. }
  242. if list.Len() == 0 {
  243. break
  244. }
  245. element := list.Front()
  246. for element != nil {
  247. commit := element.Value.(*git.Commit)
  248. authorString := commit.Author.String()
  249. if !authorsMap[authorString] && authorString != posterSig {
  250. authors = append(authors, authorString)
  251. authorsMap[authorString] = true
  252. }
  253. element = element.Next()
  254. }
  255. }
  256. }
  257. if len(authors) > 0 {
  258. if _, err := stringBuilder.WriteRune('\n'); err != nil {
  259. log.Error("Unable to write to string builder Error: %v", err)
  260. return ""
  261. }
  262. }
  263. for _, author := range authors {
  264. if _, err := stringBuilder.Write([]byte("Co-authored-by: ")); err != nil {
  265. log.Error("Unable to write to string builder Error: %v", err)
  266. return ""
  267. }
  268. if _, err := stringBuilder.Write([]byte(author)); err != nil {
  269. log.Error("Unable to write to string builder Error: %v", err)
  270. return ""
  271. }
  272. if _, err := stringBuilder.WriteRune('\n'); err != nil {
  273. log.Error("Unable to write to string builder Error: %v", err)
  274. return ""
  275. }
  276. }
  277. return stringBuilder.String()
  278. }
  279. // GetApprovers returns the approvers of the pull request
  280. func (pr *PullRequest) GetApprovers() string {
  281. stringBuilder := strings.Builder{}
  282. if err := pr.getReviewedByLines(&stringBuilder); err != nil {
  283. log.Error("Unable to getReviewedByLines: Error: %v", err)
  284. return ""
  285. }
  286. return stringBuilder.String()
  287. }
  288. func (pr *PullRequest) getReviewedByLines(writer io.Writer) error {
  289. maxReviewers := setting.Repository.PullRequest.DefaultMergeMessageMaxApprovers
  290. if maxReviewers == 0 {
  291. return nil
  292. }
  293. sess := x.NewSession()
  294. defer sess.Close()
  295. if err := sess.Begin(); err != nil {
  296. return err
  297. }
  298. // Note: This doesn't page as we only expect a very limited number of reviews
  299. reviews, err := findReviews(sess, FindReviewOptions{
  300. Type: ReviewTypeApprove,
  301. IssueID: pr.IssueID,
  302. OfficialOnly: setting.Repository.PullRequest.DefaultMergeMessageOfficialApproversOnly,
  303. })
  304. if err != nil {
  305. log.Error("Unable to FindReviews for PR ID %d: %v", pr.ID, err)
  306. return err
  307. }
  308. reviewersWritten := 0
  309. for _, review := range reviews {
  310. if maxReviewers > 0 && reviewersWritten > maxReviewers {
  311. break
  312. }
  313. if err := review.loadReviewer(sess); err != nil && !IsErrUserNotExist(err) {
  314. log.Error("Unable to LoadReviewer[%d] for PR ID %d : %v", review.ReviewerID, pr.ID, err)
  315. return err
  316. } else if review.Reviewer == nil {
  317. continue
  318. }
  319. if _, err := writer.Write([]byte("Reviewed-by: ")); err != nil {
  320. return err
  321. }
  322. if _, err := writer.Write([]byte(review.Reviewer.NewGitSig().String())); err != nil {
  323. return err
  324. }
  325. if _, err := writer.Write([]byte{'\n'}); err != nil {
  326. return err
  327. }
  328. reviewersWritten++
  329. }
  330. return sess.Commit()
  331. }
  332. // GetDefaultSquashMessage returns default message used when squash and merging pull request
  333. func (pr *PullRequest) GetDefaultSquashMessage() string {
  334. if err := pr.LoadIssue(); err != nil {
  335. log.Error("LoadIssue: %v", err)
  336. return ""
  337. }
  338. if err := pr.LoadBaseRepo(); err != nil {
  339. log.Error("LoadBaseRepo: %v", err)
  340. return ""
  341. }
  342. if pr.BaseRepo.UnitEnabled(UnitTypeExternalTracker) {
  343. return fmt.Sprintf("%s (!%d)", pr.Issue.Title, pr.Issue.Index)
  344. }
  345. return fmt.Sprintf("%s (#%d)", pr.Issue.Title, pr.Issue.Index)
  346. }
  347. // GetGitRefName returns git ref for hidden pull request branch
  348. func (pr *PullRequest) GetGitRefName() string {
  349. return fmt.Sprintf("refs/pull/%d/head", pr.Index)
  350. }
  351. func (pr *PullRequest) getHeadRepo(e Engine) (err error) {
  352. pr.HeadRepo, err = getRepositoryByID(e, pr.HeadRepoID)
  353. if err != nil && !IsErrRepoNotExist(err) {
  354. return fmt.Errorf("getRepositoryByID(head): %v", err)
  355. }
  356. return nil
  357. }
  358. // GetHeadRepo loads the head repository
  359. func (pr *PullRequest) GetHeadRepo() error {
  360. return pr.getHeadRepo(x)
  361. }
  362. // GetBaseRepo loads the target repository
  363. func (pr *PullRequest) GetBaseRepo() (err error) {
  364. if pr.BaseRepo != nil {
  365. return nil
  366. }
  367. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  368. if err != nil {
  369. return fmt.Errorf("GetRepositoryByID(base): %v", err)
  370. }
  371. return nil
  372. }
  373. // IsChecking returns true if this pull request is still checking conflict.
  374. func (pr *PullRequest) IsChecking() bool {
  375. return pr.Status == PullRequestStatusChecking
  376. }
  377. // CanAutoMerge returns true if this pull request can be merged automatically.
  378. func (pr *PullRequest) CanAutoMerge() bool {
  379. return pr.Status == PullRequestStatusMergeable
  380. }
  381. // GetLastCommitStatus returns the last commit status for this pull request.
  382. func (pr *PullRequest) GetLastCommitStatus() (status *CommitStatus, err error) {
  383. if err = pr.GetHeadRepo(); err != nil {
  384. return nil, err
  385. }
  386. if pr.HeadRepo == nil {
  387. return nil, ErrPullRequestHeadRepoMissing{pr.ID, pr.HeadRepoID}
  388. }
  389. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  390. if err != nil {
  391. return nil, err
  392. }
  393. defer headGitRepo.Close()
  394. lastCommitID, err := headGitRepo.GetBranchCommitID(pr.HeadBranch)
  395. if err != nil {
  396. return nil, err
  397. }
  398. err = pr.LoadBaseRepo()
  399. if err != nil {
  400. return nil, err
  401. }
  402. statusList, err := GetLatestCommitStatus(pr.BaseRepo, lastCommitID, 0)
  403. if err != nil {
  404. return nil, err
  405. }
  406. return CalcCommitStatus(statusList), nil
  407. }
  408. // MergeStyle represents the approach to merge commits into base branch.
  409. type MergeStyle string
  410. const (
  411. // MergeStyleMerge create merge commit
  412. MergeStyleMerge MergeStyle = "merge"
  413. // MergeStyleRebase rebase before merging
  414. MergeStyleRebase MergeStyle = "rebase"
  415. // MergeStyleRebaseMerge rebase before merging with merge commit (--no-ff)
  416. MergeStyleRebaseMerge MergeStyle = "rebase-merge"
  417. // MergeStyleSquash squash commits into single commit before merging
  418. MergeStyleSquash MergeStyle = "squash"
  419. )
  420. // SetMerged sets a pull request to merged and closes the corresponding issue
  421. func (pr *PullRequest) SetMerged() (err error) {
  422. if pr.HasMerged {
  423. return fmt.Errorf("PullRequest[%d] already merged", pr.Index)
  424. }
  425. if pr.MergedCommitID == "" || pr.MergedUnix == 0 || pr.Merger == nil {
  426. return fmt.Errorf("Unable to merge PullRequest[%d], some required fields are empty", pr.Index)
  427. }
  428. pr.HasMerged = true
  429. sess := x.NewSession()
  430. defer sess.Close()
  431. if err = sess.Begin(); err != nil {
  432. return err
  433. }
  434. if err = pr.loadIssue(sess); err != nil {
  435. return err
  436. }
  437. if err = pr.Issue.loadRepo(sess); err != nil {
  438. return err
  439. }
  440. if err = pr.Issue.Repo.getOwner(sess); err != nil {
  441. return err
  442. }
  443. if _, err = pr.Issue.changeStatus(sess, pr.Merger, true); err != nil {
  444. return fmt.Errorf("Issue.changeStatus: %v", err)
  445. }
  446. if _, err = sess.ID(pr.ID).Cols("has_merged, status, merged_commit_id, merger_id, merged_unix").Update(pr); err != nil {
  447. return fmt.Errorf("update pull request: %v", err)
  448. }
  449. if err = sess.Commit(); err != nil {
  450. return fmt.Errorf("Commit: %v", err)
  451. }
  452. return nil
  453. }
  454. // NewPullRequest creates new pull request with labels for repository.
  455. func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest) (err error) {
  456. // Retry several times in case INSERT fails due to duplicate key for (repo_id, index); see #7887
  457. i := 0
  458. for {
  459. if err = newPullRequestAttempt(repo, pull, labelIDs, uuids, pr); err == nil {
  460. return nil
  461. }
  462. if !IsErrNewIssueInsert(err) {
  463. return err
  464. }
  465. if i++; i == issueMaxDupIndexAttempts {
  466. break
  467. }
  468. log.Error("NewPullRequest: error attempting to insert the new issue; will retry. Original error: %v", err)
  469. }
  470. return fmt.Errorf("NewPullRequest: too many errors attempting to insert the new issue. Last error was: %v", err)
  471. }
  472. func newPullRequestAttempt(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest) (err error) {
  473. sess := x.NewSession()
  474. defer sess.Close()
  475. if err = sess.Begin(); err != nil {
  476. return err
  477. }
  478. if err = newIssue(sess, pull.Poster, NewIssueOptions{
  479. Repo: repo,
  480. Issue: pull,
  481. LabelIDs: labelIDs,
  482. Attachments: uuids,
  483. IsPull: true,
  484. }); err != nil {
  485. if IsErrUserDoesNotHaveAccessToRepo(err) || IsErrNewIssueInsert(err) {
  486. return err
  487. }
  488. return fmt.Errorf("newIssue: %v", err)
  489. }
  490. pr.Index = pull.Index
  491. pr.BaseRepo = repo
  492. pr.IssueID = pull.ID
  493. if _, err = sess.Insert(pr); err != nil {
  494. return fmt.Errorf("insert pull repo: %v", err)
  495. }
  496. if err = sess.Commit(); err != nil {
  497. return fmt.Errorf("Commit: %v", err)
  498. }
  499. return nil
  500. }
  501. // GetUnmergedPullRequest returns a pull request that is open and has not been merged
  502. // by given head/base and repo/branch.
  503. func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string) (*PullRequest, error) {
  504. pr := new(PullRequest)
  505. has, err := x.
  506. Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  507. headRepoID, headBranch, baseRepoID, baseBranch, false, false).
  508. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  509. Get(pr)
  510. if err != nil {
  511. return nil, err
  512. } else if !has {
  513. return nil, ErrPullRequestNotExist{0, 0, headRepoID, baseRepoID, headBranch, baseBranch}
  514. }
  515. return pr, nil
  516. }
  517. // GetLatestPullRequestByHeadInfo returns the latest pull request (regardless of its status)
  518. // by given head information (repo and branch).
  519. func GetLatestPullRequestByHeadInfo(repoID int64, branch string) (*PullRequest, error) {
  520. pr := new(PullRequest)
  521. has, err := x.
  522. Where("head_repo_id = ? AND head_branch = ?", repoID, branch).
  523. OrderBy("id DESC").
  524. Get(pr)
  525. if !has {
  526. return nil, err
  527. }
  528. return pr, err
  529. }
  530. // GetPullRequestByIndex returns a pull request by the given index
  531. func GetPullRequestByIndex(repoID int64, index int64) (*PullRequest, error) {
  532. pr := &PullRequest{
  533. BaseRepoID: repoID,
  534. Index: index,
  535. }
  536. has, err := x.Get(pr)
  537. if err != nil {
  538. return nil, err
  539. } else if !has {
  540. return nil, ErrPullRequestNotExist{0, 0, 0, repoID, "", ""}
  541. }
  542. if err = pr.LoadAttributes(); err != nil {
  543. return nil, err
  544. }
  545. if err = pr.LoadIssue(); err != nil {
  546. return nil, err
  547. }
  548. return pr, nil
  549. }
  550. func getPullRequestByID(e Engine, id int64) (*PullRequest, error) {
  551. pr := new(PullRequest)
  552. has, err := e.ID(id).Get(pr)
  553. if err != nil {
  554. return nil, err
  555. } else if !has {
  556. return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""}
  557. }
  558. return pr, pr.loadAttributes(e)
  559. }
  560. // GetPullRequestByID returns a pull request by given ID.
  561. func GetPullRequestByID(id int64) (*PullRequest, error) {
  562. return getPullRequestByID(x, id)
  563. }
  564. // GetPullRequestByIssueIDWithNoAttributes returns pull request with no attributes loaded by given issue ID.
  565. func GetPullRequestByIssueIDWithNoAttributes(issueID int64) (*PullRequest, error) {
  566. var pr PullRequest
  567. has, err := x.Where("issue_id = ?", issueID).Get(&pr)
  568. if err != nil {
  569. return nil, err
  570. }
  571. if !has {
  572. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  573. }
  574. return &pr, nil
  575. }
  576. func getPullRequestByIssueID(e Engine, issueID int64) (*PullRequest, error) {
  577. pr := &PullRequest{
  578. IssueID: issueID,
  579. }
  580. has, err := e.Get(pr)
  581. if err != nil {
  582. return nil, err
  583. } else if !has {
  584. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  585. }
  586. return pr, pr.loadAttributes(e)
  587. }
  588. // GetPullRequestByIssueID returns pull request by given issue ID.
  589. func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) {
  590. return getPullRequestByIssueID(x, issueID)
  591. }
  592. // Update updates all fields of pull request.
  593. func (pr *PullRequest) Update() error {
  594. _, err := x.ID(pr.ID).AllCols().Update(pr)
  595. return err
  596. }
  597. // UpdateCols updates specific fields of pull request.
  598. func (pr *PullRequest) UpdateCols(cols ...string) error {
  599. _, err := x.ID(pr.ID).Cols(cols...).Update(pr)
  600. return err
  601. }
  602. // IsWorkInProgress determine if the Pull Request is a Work In Progress by its title
  603. func (pr *PullRequest) IsWorkInProgress() bool {
  604. if err := pr.LoadIssue(); err != nil {
  605. log.Error("LoadIssue: %v", err)
  606. return false
  607. }
  608. for _, prefix := range setting.Repository.PullRequest.WorkInProgressPrefixes {
  609. if strings.HasPrefix(strings.ToUpper(pr.Issue.Title), prefix) {
  610. return true
  611. }
  612. }
  613. return false
  614. }
  615. // IsFilesConflicted determines if the Pull Request has changes conflicting with the target branch.
  616. func (pr *PullRequest) IsFilesConflicted() bool {
  617. return len(pr.ConflictedFiles) > 0
  618. }
  619. // GetWorkInProgressPrefix returns the prefix used to mark the pull request as a work in progress.
  620. // It returns an empty string when none were found
  621. func (pr *PullRequest) GetWorkInProgressPrefix() string {
  622. if err := pr.LoadIssue(); err != nil {
  623. log.Error("LoadIssue: %v", err)
  624. return ""
  625. }
  626. for _, prefix := range setting.Repository.PullRequest.WorkInProgressPrefixes {
  627. if strings.HasPrefix(strings.ToUpper(pr.Issue.Title), prefix) {
  628. return pr.Issue.Title[0:len(prefix)]
  629. }
  630. }
  631. return ""
  632. }
  633. // IsHeadEqualWithBranch returns if the commits of branchName are available in pull request head
  634. func (pr *PullRequest) IsHeadEqualWithBranch(branchName string) (bool, error) {
  635. var err error
  636. if err = pr.GetBaseRepo(); err != nil {
  637. return false, err
  638. }
  639. baseGitRepo, err := git.OpenRepository(pr.BaseRepo.RepoPath())
  640. if err != nil {
  641. return false, err
  642. }
  643. baseCommit, err := baseGitRepo.GetBranchCommit(branchName)
  644. if err != nil {
  645. return false, err
  646. }
  647. if err = pr.GetHeadRepo(); err != nil {
  648. return false, err
  649. }
  650. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  651. if err != nil {
  652. return false, err
  653. }
  654. headCommit, err := headGitRepo.GetBranchCommit(pr.HeadBranch)
  655. if err != nil {
  656. return false, err
  657. }
  658. return baseCommit.HasPreviousCommit(headCommit.ID)
  659. }
  660. // IsSameRepo returns true if base repo and head repo is the same
  661. func (pr *PullRequest) IsSameRepo() bool {
  662. return pr.BaseRepoID == pr.HeadRepoID
  663. }