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.

pull.go 25KB

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