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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package issues
  5. import (
  6. "context"
  7. "fmt"
  8. "io"
  9. "strconv"
  10. "strings"
  11. "code.gitea.io/gitea/models/db"
  12. git_model "code.gitea.io/gitea/models/git"
  13. pull_model "code.gitea.io/gitea/models/pull"
  14. repo_model "code.gitea.io/gitea/models/repo"
  15. user_model "code.gitea.io/gitea/models/user"
  16. "code.gitea.io/gitea/modules/git"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/setting"
  19. "code.gitea.io/gitea/modules/timeutil"
  20. "code.gitea.io/gitea/modules/util"
  21. "xorm.io/builder"
  22. )
  23. // ErrPullRequestNotExist represents a "PullRequestNotExist" kind of error.
  24. type ErrPullRequestNotExist struct {
  25. ID int64
  26. IssueID int64
  27. HeadRepoID int64
  28. BaseRepoID int64
  29. HeadBranch string
  30. BaseBranch string
  31. }
  32. // IsErrPullRequestNotExist checks if an error is a ErrPullRequestNotExist.
  33. func IsErrPullRequestNotExist(err error) bool {
  34. _, ok := err.(ErrPullRequestNotExist)
  35. return ok
  36. }
  37. func (err ErrPullRequestNotExist) Error() string {
  38. return fmt.Sprintf("pull request does not exist [id: %d, issue_id: %d, head_repo_id: %d, base_repo_id: %d, head_branch: %s, base_branch: %s]",
  39. err.ID, err.IssueID, err.HeadRepoID, err.BaseRepoID, err.HeadBranch, err.BaseBranch)
  40. }
  41. func (err ErrPullRequestNotExist) Unwrap() error {
  42. return util.ErrNotExist
  43. }
  44. // ErrPullRequestAlreadyExists represents a "PullRequestAlreadyExists"-error
  45. type ErrPullRequestAlreadyExists struct {
  46. ID int64
  47. IssueID int64
  48. HeadRepoID int64
  49. BaseRepoID int64
  50. HeadBranch string
  51. BaseBranch string
  52. }
  53. // IsErrPullRequestAlreadyExists checks if an error is a ErrPullRequestAlreadyExists.
  54. func IsErrPullRequestAlreadyExists(err error) bool {
  55. _, ok := err.(ErrPullRequestAlreadyExists)
  56. return ok
  57. }
  58. // Error does pretty-printing :D
  59. func (err ErrPullRequestAlreadyExists) Error() string {
  60. return fmt.Sprintf("pull request already exists for these targets [id: %d, issue_id: %d, head_repo_id: %d, base_repo_id: %d, head_branch: %s, base_branch: %s]",
  61. err.ID, err.IssueID, err.HeadRepoID, err.BaseRepoID, err.HeadBranch, err.BaseBranch)
  62. }
  63. func (err ErrPullRequestAlreadyExists) Unwrap() error {
  64. return util.ErrAlreadyExist
  65. }
  66. // ErrPullRequestHeadRepoMissing represents a "ErrPullRequestHeadRepoMissing" error
  67. type ErrPullRequestHeadRepoMissing struct {
  68. ID int64
  69. HeadRepoID int64
  70. }
  71. // IsErrErrPullRequestHeadRepoMissing checks if an error is a ErrPullRequestHeadRepoMissing.
  72. func IsErrErrPullRequestHeadRepoMissing(err error) bool {
  73. _, ok := err.(ErrPullRequestHeadRepoMissing)
  74. return ok
  75. }
  76. // Error does pretty-printing :D
  77. func (err ErrPullRequestHeadRepoMissing) Error() string {
  78. return fmt.Sprintf("pull request head repo missing [id: %d, head_repo_id: %d]",
  79. err.ID, err.HeadRepoID)
  80. }
  81. // ErrPullWasClosed is used close a closed pull request
  82. type ErrPullWasClosed struct {
  83. ID int64
  84. Index int64
  85. }
  86. // IsErrPullWasClosed checks if an error is a ErrErrPullWasClosed.
  87. func IsErrPullWasClosed(err error) bool {
  88. _, ok := err.(ErrPullWasClosed)
  89. return ok
  90. }
  91. func (err ErrPullWasClosed) Error() string {
  92. return fmt.Sprintf("Pull request [%d] %d was already closed", err.ID, err.Index)
  93. }
  94. // PullRequestType defines pull request type
  95. type PullRequestType int
  96. // Enumerate all the pull request types
  97. const (
  98. PullRequestGitea PullRequestType = iota
  99. PullRequestGit
  100. )
  101. // PullRequestStatus defines pull request status
  102. type PullRequestStatus int
  103. // Enumerate all the pull request status
  104. const (
  105. PullRequestStatusConflict PullRequestStatus = iota
  106. PullRequestStatusChecking
  107. PullRequestStatusMergeable
  108. PullRequestStatusManuallyMerged
  109. PullRequestStatusError
  110. PullRequestStatusEmpty
  111. PullRequestStatusAncestor
  112. )
  113. func (status PullRequestStatus) String() string {
  114. switch status {
  115. case PullRequestStatusConflict:
  116. return "CONFLICT"
  117. case PullRequestStatusChecking:
  118. return "CHECKING"
  119. case PullRequestStatusMergeable:
  120. return "MERGEABLE"
  121. case PullRequestStatusManuallyMerged:
  122. return "MANUALLY_MERGED"
  123. case PullRequestStatusError:
  124. return "ERROR"
  125. case PullRequestStatusEmpty:
  126. return "EMPTY"
  127. case PullRequestStatusAncestor:
  128. return "ANCESTOR"
  129. default:
  130. return strconv.Itoa(int(status))
  131. }
  132. }
  133. // PullRequestFlow the flow of pull request
  134. type PullRequestFlow int
  135. const (
  136. // PullRequestFlowGithub github flow from head branch to base branch
  137. PullRequestFlowGithub PullRequestFlow = iota
  138. // PullRequestFlowAGit Agit flow pull request, head branch is not exist
  139. PullRequestFlowAGit
  140. )
  141. // PullRequest represents relation between pull request and repositories.
  142. type PullRequest struct {
  143. ID int64 `xorm:"pk autoincr"`
  144. Type PullRequestType
  145. Status PullRequestStatus
  146. ConflictedFiles []string `xorm:"TEXT JSON"`
  147. CommitsAhead int
  148. CommitsBehind int
  149. ChangedProtectedFiles []string `xorm:"TEXT JSON"`
  150. IssueID int64 `xorm:"INDEX"`
  151. Issue *Issue `xorm:"-"`
  152. Index int64
  153. HeadRepoID int64 `xorm:"INDEX"`
  154. HeadRepo *repo_model.Repository `xorm:"-"`
  155. BaseRepoID int64 `xorm:"INDEX"`
  156. BaseRepo *repo_model.Repository `xorm:"-"`
  157. HeadBranch string
  158. HeadCommitID string `xorm:"-"`
  159. BaseBranch string
  160. MergeBase string `xorm:"VARCHAR(40)"`
  161. AllowMaintainerEdit bool `xorm:"NOT NULL DEFAULT false"`
  162. HasMerged bool `xorm:"INDEX"`
  163. MergedCommitID string `xorm:"VARCHAR(40)"`
  164. MergerID int64 `xorm:"INDEX"`
  165. Merger *user_model.User `xorm:"-"`
  166. MergedUnix timeutil.TimeStamp `xorm:"updated INDEX"`
  167. isHeadRepoLoaded bool `xorm:"-"`
  168. Flow PullRequestFlow `xorm:"NOT NULL DEFAULT 0"`
  169. }
  170. func init() {
  171. db.RegisterModel(new(PullRequest))
  172. }
  173. // DeletePullsByBaseRepoID deletes all pull requests by the base repository ID
  174. func DeletePullsByBaseRepoID(ctx context.Context, repoID int64) error {
  175. deleteCond := builder.Select("id").From("pull_request").Where(builder.Eq{"pull_request.base_repo_id": repoID})
  176. // Delete scheduled auto merges
  177. if _, err := db.GetEngine(ctx).In("pull_id", deleteCond).
  178. Delete(&pull_model.AutoMerge{}); err != nil {
  179. return err
  180. }
  181. // Delete review states
  182. if _, err := db.GetEngine(ctx).In("pull_id", deleteCond).
  183. Delete(&pull_model.ReviewState{}); err != nil {
  184. return err
  185. }
  186. _, err := db.DeleteByBean(ctx, &PullRequest{BaseRepoID: repoID})
  187. return err
  188. }
  189. // ColorFormat writes a colored string to identify this struct
  190. func (pr *PullRequest) ColorFormat(s fmt.State) {
  191. if pr == nil {
  192. log.ColorFprintf(s, "PR[%d]%s#%d[%s...%s:%s]",
  193. log.NewColoredIDValue(0),
  194. log.NewColoredValue("<nil>/<nil>"),
  195. log.NewColoredIDValue(0),
  196. log.NewColoredValue("<nil>"),
  197. log.NewColoredValue("<nil>/<nil>"),
  198. log.NewColoredValue("<nil>"),
  199. )
  200. return
  201. }
  202. log.ColorFprintf(s, "PR[%d]", log.NewColoredIDValue(pr.ID))
  203. if pr.BaseRepo != nil {
  204. log.ColorFprintf(s, "%s#%d[%s...", log.NewColoredValue(pr.BaseRepo.FullName()),
  205. log.NewColoredIDValue(pr.Index), log.NewColoredValue(pr.BaseBranch))
  206. } else {
  207. log.ColorFprintf(s, "Repo[%d]#%d[%s...", log.NewColoredIDValue(pr.BaseRepoID),
  208. log.NewColoredIDValue(pr.Index), log.NewColoredValue(pr.BaseBranch))
  209. }
  210. if pr.HeadRepoID == pr.BaseRepoID {
  211. log.ColorFprintf(s, "%s]", log.NewColoredValue(pr.HeadBranch))
  212. } else if pr.HeadRepo != nil {
  213. log.ColorFprintf(s, "%s:%s]", log.NewColoredValue(pr.HeadRepo.FullName()), log.NewColoredValue(pr.HeadBranch))
  214. } else {
  215. log.ColorFprintf(s, "Repo[%d]:%s]", log.NewColoredIDValue(pr.HeadRepoID), log.NewColoredValue(pr.HeadBranch))
  216. }
  217. }
  218. // String represents the pr as a simple string
  219. func (pr *PullRequest) String() string {
  220. return log.ColorFormatAsString(pr)
  221. }
  222. // MustHeadUserName returns the HeadRepo's username if failed return blank
  223. func (pr *PullRequest) MustHeadUserName(ctx context.Context) string {
  224. if err := pr.LoadHeadRepo(ctx); err != nil {
  225. if !repo_model.IsErrRepoNotExist(err) {
  226. log.Error("LoadHeadRepo: %v", err)
  227. } else {
  228. log.Warn("LoadHeadRepo %d but repository does not exist: %v", pr.HeadRepoID, err)
  229. }
  230. return ""
  231. }
  232. if pr.HeadRepo == nil {
  233. return ""
  234. }
  235. return pr.HeadRepo.OwnerName
  236. }
  237. // LoadAttributes loads pull request attributes from database
  238. // Note: don't try to get Issue because will end up recursive querying.
  239. func (pr *PullRequest) LoadAttributes(ctx context.Context) (err error) {
  240. if pr.HasMerged && pr.Merger == nil {
  241. pr.Merger, err = user_model.GetUserByID(ctx, pr.MergerID)
  242. if user_model.IsErrUserNotExist(err) {
  243. pr.MergerID = -1
  244. pr.Merger = user_model.NewGhostUser()
  245. } else if err != nil {
  246. return fmt.Errorf("getUserByID [%d]: %w", pr.MergerID, err)
  247. }
  248. }
  249. return nil
  250. }
  251. // LoadHeadRepo loads the head repository, pr.HeadRepo will remain nil if it does not exist
  252. // and thus ErrRepoNotExist will never be returned
  253. func (pr *PullRequest) LoadHeadRepo(ctx context.Context) (err error) {
  254. if !pr.isHeadRepoLoaded && pr.HeadRepo == nil && pr.HeadRepoID > 0 {
  255. if pr.HeadRepoID == pr.BaseRepoID {
  256. if pr.BaseRepo != nil {
  257. pr.HeadRepo = pr.BaseRepo
  258. return nil
  259. } else if pr.Issue != nil && pr.Issue.Repo != nil {
  260. pr.HeadRepo = pr.Issue.Repo
  261. return nil
  262. }
  263. }
  264. pr.HeadRepo, err = repo_model.GetRepositoryByID(ctx, pr.HeadRepoID)
  265. if err != nil && !repo_model.IsErrRepoNotExist(err) { // Head repo maybe deleted, but it should still work
  266. return fmt.Errorf("pr[%d].LoadHeadRepo[%d]: %w", pr.ID, pr.HeadRepoID, err)
  267. }
  268. pr.isHeadRepoLoaded = true
  269. }
  270. return nil
  271. }
  272. // LoadBaseRepo loads the target repository. ErrRepoNotExist may be returned.
  273. func (pr *PullRequest) LoadBaseRepo(ctx context.Context) (err error) {
  274. if pr.BaseRepo != nil {
  275. return nil
  276. }
  277. if pr.HeadRepoID == pr.BaseRepoID && pr.HeadRepo != nil {
  278. pr.BaseRepo = pr.HeadRepo
  279. return nil
  280. }
  281. if pr.Issue != nil && pr.Issue.Repo != nil {
  282. pr.BaseRepo = pr.Issue.Repo
  283. return nil
  284. }
  285. pr.BaseRepo, err = repo_model.GetRepositoryByID(ctx, pr.BaseRepoID)
  286. if err != nil {
  287. return fmt.Errorf("pr[%d].LoadBaseRepo[%d]: %w", pr.ID, pr.BaseRepoID, err)
  288. }
  289. return nil
  290. }
  291. // LoadIssue loads issue information from database
  292. func (pr *PullRequest) LoadIssue(ctx context.Context) (err error) {
  293. if pr.Issue != nil {
  294. return nil
  295. }
  296. pr.Issue, err = GetIssueByID(ctx, pr.IssueID)
  297. if err == nil {
  298. pr.Issue.PullRequest = pr
  299. }
  300. return err
  301. }
  302. // ReviewCount represents a count of Reviews
  303. type ReviewCount struct {
  304. IssueID int64
  305. Type ReviewType
  306. Count int64
  307. }
  308. // GetApprovalCounts returns the approval counts by type
  309. // FIXME: Only returns official counts due to double counting of non-official counts
  310. func (pr *PullRequest) GetApprovalCounts(ctx context.Context) ([]*ReviewCount, error) {
  311. rCounts := make([]*ReviewCount, 0, 6)
  312. sess := db.GetEngine(ctx).Where("issue_id = ?", pr.IssueID)
  313. return rCounts, sess.Select("issue_id, type, count(id) as `count`").Where("official = ? AND dismissed = ?", true, false).GroupBy("issue_id, type").Table("review").Find(&rCounts)
  314. }
  315. // GetApprovers returns the approvers of the pull request
  316. func (pr *PullRequest) GetApprovers() string {
  317. stringBuilder := strings.Builder{}
  318. if err := pr.getReviewedByLines(&stringBuilder); err != nil {
  319. log.Error("Unable to getReviewedByLines: Error: %v", err)
  320. return ""
  321. }
  322. return stringBuilder.String()
  323. }
  324. func (pr *PullRequest) getReviewedByLines(writer io.Writer) error {
  325. maxReviewers := setting.Repository.PullRequest.DefaultMergeMessageMaxApprovers
  326. if maxReviewers == 0 {
  327. return nil
  328. }
  329. ctx, committer, err := db.TxContext(db.DefaultContext)
  330. if err != nil {
  331. return err
  332. }
  333. defer committer.Close()
  334. // Note: This doesn't page as we only expect a very limited number of reviews
  335. reviews, err := FindReviews(ctx, FindReviewOptions{
  336. Type: ReviewTypeApprove,
  337. IssueID: pr.IssueID,
  338. OfficialOnly: setting.Repository.PullRequest.DefaultMergeMessageOfficialApproversOnly,
  339. })
  340. if err != nil {
  341. log.Error("Unable to FindReviews for PR ID %d: %v", pr.ID, err)
  342. return err
  343. }
  344. reviewersWritten := 0
  345. for _, review := range reviews {
  346. if maxReviewers > 0 && reviewersWritten > maxReviewers {
  347. break
  348. }
  349. if err := review.LoadReviewer(ctx); err != nil && !user_model.IsErrUserNotExist(err) {
  350. log.Error("Unable to LoadReviewer[%d] for PR ID %d : %v", review.ReviewerID, pr.ID, err)
  351. return err
  352. } else if review.Reviewer == nil {
  353. continue
  354. }
  355. if _, err := writer.Write([]byte("Reviewed-by: ")); err != nil {
  356. return err
  357. }
  358. if _, err := writer.Write([]byte(review.Reviewer.NewGitSig().String())); err != nil {
  359. return err
  360. }
  361. if _, err := writer.Write([]byte{'\n'}); err != nil {
  362. return err
  363. }
  364. reviewersWritten++
  365. }
  366. return committer.Commit()
  367. }
  368. // GetGitRefName returns git ref for hidden pull request branch
  369. func (pr *PullRequest) GetGitRefName() string {
  370. return fmt.Sprintf("%s%d/head", git.PullPrefix, pr.Index)
  371. }
  372. // IsChecking returns true if this pull request is still checking conflict.
  373. func (pr *PullRequest) IsChecking() bool {
  374. return pr.Status == PullRequestStatusChecking
  375. }
  376. // CanAutoMerge returns true if this pull request can be merged automatically.
  377. func (pr *PullRequest) CanAutoMerge() bool {
  378. return pr.Status == PullRequestStatusMergeable
  379. }
  380. // IsEmpty returns true if this pull request is empty.
  381. func (pr *PullRequest) IsEmpty() bool {
  382. return pr.Status == PullRequestStatusEmpty
  383. }
  384. // IsAncestor returns true if the Head Commit of this PR is an ancestor of the Base Commit
  385. func (pr *PullRequest) IsAncestor() bool {
  386. return pr.Status == PullRequestStatusAncestor
  387. }
  388. // IsFromFork return true if this PR is from a fork.
  389. func (pr *PullRequest) IsFromFork() bool {
  390. return pr.HeadRepoID != pr.BaseRepoID
  391. }
  392. // SetMerged sets a pull request to merged and closes the corresponding issue
  393. func (pr *PullRequest) SetMerged(ctx context.Context) (bool, error) {
  394. if pr.HasMerged {
  395. return false, fmt.Errorf("PullRequest[%d] already merged", pr.Index)
  396. }
  397. if pr.MergedCommitID == "" || pr.MergedUnix == 0 || pr.Merger == nil {
  398. return false, fmt.Errorf("Unable to merge PullRequest[%d], some required fields are empty", pr.Index)
  399. }
  400. pr.HasMerged = true
  401. sess := db.GetEngine(ctx)
  402. if _, err := sess.Exec("UPDATE `issue` SET `repo_id` = `repo_id` WHERE `id` = ?", pr.IssueID); err != nil {
  403. return false, err
  404. }
  405. if _, err := sess.Exec("UPDATE `pull_request` SET `issue_id` = `issue_id` WHERE `id` = ?", pr.ID); err != nil {
  406. return false, err
  407. }
  408. pr.Issue = nil
  409. if err := pr.LoadIssue(ctx); err != nil {
  410. return false, err
  411. }
  412. if tmpPr, err := GetPullRequestByID(ctx, pr.ID); err != nil {
  413. return false, err
  414. } else if tmpPr.HasMerged {
  415. if pr.Issue.IsClosed {
  416. return false, nil
  417. }
  418. return false, fmt.Errorf("PullRequest[%d] already merged but it's associated issue [%d] is not closed", pr.Index, pr.IssueID)
  419. } else if pr.Issue.IsClosed {
  420. return false, fmt.Errorf("PullRequest[%d] already closed", pr.Index)
  421. }
  422. if err := pr.Issue.LoadRepo(ctx); err != nil {
  423. return false, err
  424. }
  425. if err := pr.Issue.Repo.LoadOwner(ctx); err != nil {
  426. return false, err
  427. }
  428. if _, err := changeIssueStatus(ctx, pr.Issue, pr.Merger, true, true); err != nil {
  429. return false, fmt.Errorf("Issue.changeStatus: %w", err)
  430. }
  431. // reset the conflicted files as there cannot be any if we're merged
  432. pr.ConflictedFiles = []string{}
  433. // We need to save all of the data used to compute this merge as it may have already been changed by TestPatch. FIXME: need to set some state to prevent TestPatch from running whilst we are merging.
  434. if _, err := sess.Where("id = ?", pr.ID).Cols("has_merged, status, merge_base, merged_commit_id, merger_id, merged_unix, conflicted_files").Update(pr); err != nil {
  435. return false, fmt.Errorf("Failed to update pr[%d]: %w", pr.ID, err)
  436. }
  437. return true, nil
  438. }
  439. // NewPullRequest creates new pull request with labels for repository.
  440. func NewPullRequest(outerCtx context.Context, repo *repo_model.Repository, issue *Issue, labelIDs []int64, uuids []string, pr *PullRequest) (err error) {
  441. ctx, committer, err := db.TxContext(outerCtx)
  442. if err != nil {
  443. return err
  444. }
  445. defer committer.Close()
  446. ctx.WithContext(outerCtx)
  447. idx, err := db.GetNextResourceIndex(ctx, "issue_index", repo.ID)
  448. if err != nil {
  449. return fmt.Errorf("generate pull request index failed: %w", err)
  450. }
  451. issue.Index = idx
  452. if err = NewIssueWithIndex(ctx, issue.Poster, NewIssueOptions{
  453. Repo: repo,
  454. Issue: issue,
  455. LabelIDs: labelIDs,
  456. Attachments: uuids,
  457. IsPull: true,
  458. }); err != nil {
  459. if repo_model.IsErrUserDoesNotHaveAccessToRepo(err) || IsErrNewIssueInsert(err) {
  460. return err
  461. }
  462. return fmt.Errorf("newIssue: %w", err)
  463. }
  464. pr.Index = issue.Index
  465. pr.BaseRepo = repo
  466. pr.IssueID = issue.ID
  467. if err = db.Insert(ctx, pr); err != nil {
  468. return fmt.Errorf("insert pull repo: %w", err)
  469. }
  470. if err = committer.Commit(); err != nil {
  471. return fmt.Errorf("Commit: %w", err)
  472. }
  473. return nil
  474. }
  475. // GetUnmergedPullRequest returns a pull request that is open and has not been merged
  476. // by given head/base and repo/branch.
  477. func GetUnmergedPullRequest(ctx context.Context, headRepoID, baseRepoID int64, headBranch, baseBranch string, flow PullRequestFlow) (*PullRequest, error) {
  478. pr := new(PullRequest)
  479. has, err := db.GetEngine(ctx).
  480. Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND flow = ? AND issue.is_closed=?",
  481. headRepoID, headBranch, baseRepoID, baseBranch, false, flow, false).
  482. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  483. Get(pr)
  484. if err != nil {
  485. return nil, err
  486. } else if !has {
  487. return nil, ErrPullRequestNotExist{0, 0, headRepoID, baseRepoID, headBranch, baseBranch}
  488. }
  489. return pr, nil
  490. }
  491. // GetLatestPullRequestByHeadInfo returns the latest pull request (regardless of its status)
  492. // by given head information (repo and branch).
  493. func GetLatestPullRequestByHeadInfo(repoID int64, branch string) (*PullRequest, error) {
  494. pr := new(PullRequest)
  495. has, err := db.GetEngine(db.DefaultContext).
  496. Where("head_repo_id = ? AND head_branch = ? AND flow = ?", repoID, branch, PullRequestFlowGithub).
  497. OrderBy("id DESC").
  498. Get(pr)
  499. if !has {
  500. return nil, err
  501. }
  502. return pr, err
  503. }
  504. // GetPullRequestByIndex returns a pull request by the given index
  505. func GetPullRequestByIndex(ctx context.Context, repoID, index int64) (*PullRequest, error) {
  506. if index < 1 {
  507. return nil, ErrPullRequestNotExist{}
  508. }
  509. pr := &PullRequest{
  510. BaseRepoID: repoID,
  511. Index: index,
  512. }
  513. has, err := db.GetEngine(ctx).Get(pr)
  514. if err != nil {
  515. return nil, err
  516. } else if !has {
  517. return nil, ErrPullRequestNotExist{0, 0, 0, repoID, "", ""}
  518. }
  519. if err = pr.LoadAttributes(ctx); err != nil {
  520. return nil, err
  521. }
  522. if err = pr.LoadIssue(ctx); err != nil {
  523. return nil, err
  524. }
  525. return pr, nil
  526. }
  527. // GetPullRequestByID returns a pull request by given ID.
  528. func GetPullRequestByID(ctx context.Context, id int64) (*PullRequest, error) {
  529. pr := new(PullRequest)
  530. has, err := db.GetEngine(ctx).ID(id).Get(pr)
  531. if err != nil {
  532. return nil, err
  533. } else if !has {
  534. return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""}
  535. }
  536. return pr, pr.LoadAttributes(ctx)
  537. }
  538. // GetPullRequestByIssueIDWithNoAttributes returns pull request with no attributes loaded by given issue ID.
  539. func GetPullRequestByIssueIDWithNoAttributes(issueID int64) (*PullRequest, error) {
  540. var pr PullRequest
  541. has, err := db.GetEngine(db.DefaultContext).Where("issue_id = ?", issueID).Get(&pr)
  542. if err != nil {
  543. return nil, err
  544. }
  545. if !has {
  546. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  547. }
  548. return &pr, nil
  549. }
  550. // GetPullRequestByIssueID returns pull request by given issue ID.
  551. func GetPullRequestByIssueID(ctx context.Context, issueID int64) (*PullRequest, error) {
  552. pr := &PullRequest{
  553. IssueID: issueID,
  554. }
  555. has, err := db.GetByBean(ctx, pr)
  556. if err != nil {
  557. return nil, err
  558. } else if !has {
  559. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  560. }
  561. return pr, pr.LoadAttributes(ctx)
  562. }
  563. // GetAllUnmergedAgitPullRequestByPoster get all unmerged agit flow pull request
  564. // By poster id.
  565. func GetAllUnmergedAgitPullRequestByPoster(uid int64) ([]*PullRequest, error) {
  566. pulls := make([]*PullRequest, 0, 10)
  567. err := db.GetEngine(db.DefaultContext).
  568. Where("has_merged=? AND flow = ? AND issue.is_closed=? AND issue.poster_id=?",
  569. false, PullRequestFlowAGit, false, uid).
  570. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  571. Find(&pulls)
  572. return pulls, err
  573. }
  574. // Update updates all fields of pull request.
  575. func (pr *PullRequest) Update() error {
  576. _, err := db.GetEngine(db.DefaultContext).ID(pr.ID).AllCols().Update(pr)
  577. return err
  578. }
  579. // UpdateCols updates specific fields of pull request.
  580. func (pr *PullRequest) UpdateCols(cols ...string) error {
  581. _, err := db.GetEngine(db.DefaultContext).ID(pr.ID).Cols(cols...).Update(pr)
  582. return err
  583. }
  584. // UpdateColsIfNotMerged updates specific fields of a pull request if it has not been merged
  585. func (pr *PullRequest) UpdateColsIfNotMerged(ctx context.Context, cols ...string) error {
  586. _, err := db.GetEngine(ctx).Where("id = ? AND has_merged = ?", pr.ID, false).Cols(cols...).Update(pr)
  587. return err
  588. }
  589. // IsWorkInProgress determine if the Pull Request is a Work In Progress by its title
  590. // Issue must be set before this method can be called.
  591. func (pr *PullRequest) IsWorkInProgress() bool {
  592. if err := pr.LoadIssue(db.DefaultContext); err != nil {
  593. log.Error("LoadIssue: %v", err)
  594. return false
  595. }
  596. return HasWorkInProgressPrefix(pr.Issue.Title)
  597. }
  598. // HasWorkInProgressPrefix determines if the given PR title has a Work In Progress prefix
  599. func HasWorkInProgressPrefix(title string) bool {
  600. for _, prefix := range setting.Repository.PullRequest.WorkInProgressPrefixes {
  601. if strings.HasPrefix(strings.ToUpper(title), strings.ToUpper(prefix)) {
  602. return true
  603. }
  604. }
  605. return false
  606. }
  607. // IsFilesConflicted determines if the Pull Request has changes conflicting with the target branch.
  608. func (pr *PullRequest) IsFilesConflicted() bool {
  609. return len(pr.ConflictedFiles) > 0
  610. }
  611. // GetWorkInProgressPrefix returns the prefix used to mark the pull request as a work in progress.
  612. // It returns an empty string when none were found
  613. func (pr *PullRequest) GetWorkInProgressPrefix(ctx context.Context) string {
  614. if err := pr.LoadIssue(ctx); err != nil {
  615. log.Error("LoadIssue: %v", err)
  616. return ""
  617. }
  618. for _, prefix := range setting.Repository.PullRequest.WorkInProgressPrefixes {
  619. if strings.HasPrefix(strings.ToUpper(pr.Issue.Title), strings.ToUpper(prefix)) {
  620. return pr.Issue.Title[0:len(prefix)]
  621. }
  622. }
  623. return ""
  624. }
  625. // UpdateCommitDivergence update Divergence of a pull request
  626. func (pr *PullRequest) UpdateCommitDivergence(ctx context.Context, ahead, behind int) error {
  627. if pr.ID == 0 {
  628. return fmt.Errorf("pull ID is 0")
  629. }
  630. pr.CommitsAhead = ahead
  631. pr.CommitsBehind = behind
  632. _, err := db.GetEngine(ctx).ID(pr.ID).Cols("commits_ahead", "commits_behind").Update(pr)
  633. return err
  634. }
  635. // IsSameRepo returns true if base repo and head repo is the same
  636. func (pr *PullRequest) IsSameRepo() bool {
  637. return pr.BaseRepoID == pr.HeadRepoID
  638. }
  639. // GetPullRequestsByHeadBranch returns all prs by head branch
  640. // Since there could be multiple prs with the same head branch, this function returns a slice of prs
  641. func GetPullRequestsByHeadBranch(ctx context.Context, headBranch string, headRepoID int64) ([]*PullRequest, error) {
  642. log.Trace("GetPullRequestsByHeadBranch: headBranch: '%s', headRepoID: '%d'", headBranch, headRepoID)
  643. prs := make([]*PullRequest, 0, 2)
  644. if err := db.GetEngine(ctx).Where(builder.Eq{"head_branch": headBranch, "head_repo_id": headRepoID}).
  645. Find(&prs); err != nil {
  646. return nil, err
  647. }
  648. return prs, nil
  649. }
  650. // GetBaseBranchLink returns the relative URL of the base branch
  651. func (pr *PullRequest) GetBaseBranchLink() string {
  652. if err := pr.LoadBaseRepo(db.DefaultContext); err != nil {
  653. log.Error("LoadBaseRepo: %v", err)
  654. return ""
  655. }
  656. if pr.BaseRepo == nil {
  657. return ""
  658. }
  659. return pr.BaseRepo.Link() + "/src/branch/" + util.PathEscapeSegments(pr.BaseBranch)
  660. }
  661. // GetHeadBranchLink returns the relative URL of the head branch
  662. func (pr *PullRequest) GetHeadBranchLink() string {
  663. if pr.Flow == PullRequestFlowAGit {
  664. return ""
  665. }
  666. if err := pr.LoadHeadRepo(db.DefaultContext); err != nil {
  667. log.Error("LoadHeadRepo: %v", err)
  668. return ""
  669. }
  670. if pr.HeadRepo == nil {
  671. return ""
  672. }
  673. return pr.HeadRepo.Link() + "/src/branch/" + util.PathEscapeSegments(pr.HeadBranch)
  674. }
  675. // UpdateAllowEdits update if PR can be edited from maintainers
  676. func UpdateAllowEdits(ctx context.Context, pr *PullRequest) error {
  677. if _, err := db.GetEngine(ctx).ID(pr.ID).Cols("allow_maintainer_edit").Update(pr); err != nil {
  678. return err
  679. }
  680. return nil
  681. }
  682. // Mergeable returns if the pullrequest is mergeable.
  683. func (pr *PullRequest) Mergeable() bool {
  684. // If a pull request isn't mergable if it's:
  685. // - Being conflict checked.
  686. // - Has a conflict.
  687. // - Received a error while being conflict checked.
  688. // - Is a work-in-progress pull request.
  689. return pr.Status != PullRequestStatusChecking && pr.Status != PullRequestStatusConflict &&
  690. pr.Status != PullRequestStatusError && !pr.IsWorkInProgress()
  691. }
  692. // HasEnoughApprovals returns true if pr has enough granted approvals.
  693. func HasEnoughApprovals(ctx context.Context, protectBranch *git_model.ProtectedBranch, pr *PullRequest) bool {
  694. if protectBranch.RequiredApprovals == 0 {
  695. return true
  696. }
  697. return GetGrantedApprovalsCount(ctx, protectBranch, pr) >= protectBranch.RequiredApprovals
  698. }
  699. // GetGrantedApprovalsCount returns the number of granted approvals for pr. A granted approval must be authored by a user in an approval whitelist.
  700. func GetGrantedApprovalsCount(ctx context.Context, protectBranch *git_model.ProtectedBranch, pr *PullRequest) int64 {
  701. sess := db.GetEngine(ctx).Where("issue_id = ?", pr.IssueID).
  702. And("type = ?", ReviewTypeApprove).
  703. And("official = ?", true).
  704. And("dismissed = ?", false)
  705. if protectBranch.DismissStaleApprovals {
  706. sess = sess.And("stale = ?", false)
  707. }
  708. approvals, err := sess.Count(new(Review))
  709. if err != nil {
  710. log.Error("GetGrantedApprovalsCount: %v", err)
  711. return 0
  712. }
  713. return approvals
  714. }
  715. // MergeBlockedByRejectedReview returns true if merge is blocked by rejected reviews
  716. func MergeBlockedByRejectedReview(ctx context.Context, protectBranch *git_model.ProtectedBranch, pr *PullRequest) bool {
  717. if !protectBranch.BlockOnRejectedReviews {
  718. return false
  719. }
  720. rejectExist, err := db.GetEngine(ctx).Where("issue_id = ?", pr.IssueID).
  721. And("type = ?", ReviewTypeReject).
  722. And("official = ?", true).
  723. And("dismissed = ?", false).
  724. Exist(new(Review))
  725. if err != nil {
  726. log.Error("MergeBlockedByRejectedReview: %v", err)
  727. return true
  728. }
  729. return rejectExist
  730. }
  731. // MergeBlockedByOfficialReviewRequests block merge because of some review request to official reviewer
  732. // of from official review
  733. func MergeBlockedByOfficialReviewRequests(ctx context.Context, protectBranch *git_model.ProtectedBranch, pr *PullRequest) bool {
  734. if !protectBranch.BlockOnOfficialReviewRequests {
  735. return false
  736. }
  737. has, err := db.GetEngine(ctx).Where("issue_id = ?", pr.IssueID).
  738. And("type = ?", ReviewTypeRequest).
  739. And("official = ?", true).
  740. Exist(new(Review))
  741. if err != nil {
  742. log.Error("MergeBlockedByOfficialReviewRequests: %v", err)
  743. return true
  744. }
  745. return has
  746. }
  747. // MergeBlockedByOutdatedBranch returns true if merge is blocked by an outdated head branch
  748. func MergeBlockedByOutdatedBranch(protectBranch *git_model.ProtectedBranch, pr *PullRequest) bool {
  749. return protectBranch.BlockOnOutdatedBranch && pr.CommitsBehind > 0
  750. }