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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  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. // IsFromFork return true if this PR is from a fork.
  334. func (pr *PullRequest) IsFromFork() bool {
  335. return pr.HeadRepoID != pr.BaseRepoID
  336. }
  337. // SetMerged sets a pull request to merged and closes the corresponding issue
  338. func (pr *PullRequest) SetMerged(ctx context.Context) (bool, error) {
  339. if pr.HasMerged {
  340. return false, fmt.Errorf("PullRequest[%d] already merged", pr.Index)
  341. }
  342. if pr.MergedCommitID == "" || pr.MergedUnix == 0 || pr.Merger == nil {
  343. return false, fmt.Errorf("Unable to merge PullRequest[%d], some required fields are empty", pr.Index)
  344. }
  345. pr.HasMerged = true
  346. sess := db.GetEngine(ctx)
  347. if _, err := sess.Exec("UPDATE `issue` SET `repo_id` = `repo_id` WHERE `id` = ?", pr.IssueID); err != nil {
  348. return false, err
  349. }
  350. if _, err := sess.Exec("UPDATE `pull_request` SET `issue_id` = `issue_id` WHERE `id` = ?", pr.ID); err != nil {
  351. return false, err
  352. }
  353. pr.Issue = nil
  354. if err := pr.LoadIssue(ctx); err != nil {
  355. return false, err
  356. }
  357. if tmpPr, err := GetPullRequestByID(ctx, pr.ID); err != nil {
  358. return false, err
  359. } else if tmpPr.HasMerged {
  360. if pr.Issue.IsClosed {
  361. return false, nil
  362. }
  363. return false, fmt.Errorf("PullRequest[%d] already merged but it's associated issue [%d] is not closed", pr.Index, pr.IssueID)
  364. } else if pr.Issue.IsClosed {
  365. return false, fmt.Errorf("PullRequest[%d] already closed", pr.Index)
  366. }
  367. if err := pr.Issue.LoadRepo(ctx); err != nil {
  368. return false, err
  369. }
  370. if err := pr.Issue.Repo.GetOwner(ctx); err != nil {
  371. return false, err
  372. }
  373. if _, err := changeIssueStatus(ctx, pr.Issue, pr.Merger, true, true); err != nil {
  374. return false, fmt.Errorf("Issue.changeStatus: %w", err)
  375. }
  376. // reset the conflicted files as there cannot be any if we're merged
  377. pr.ConflictedFiles = []string{}
  378. // 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.
  379. 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 {
  380. return false, fmt.Errorf("Failed to update pr[%d]: %w", pr.ID, err)
  381. }
  382. return true, nil
  383. }
  384. // NewPullRequest creates new pull request with labels for repository.
  385. func NewPullRequest(outerCtx context.Context, repo *repo_model.Repository, issue *Issue, labelIDs []int64, uuids []string, pr *PullRequest) (err error) {
  386. ctx, committer, err := db.TxContext(outerCtx)
  387. if err != nil {
  388. return err
  389. }
  390. defer committer.Close()
  391. ctx.WithContext(outerCtx)
  392. idx, err := db.GetNextResourceIndex(ctx, "issue_index", repo.ID)
  393. if err != nil {
  394. return fmt.Errorf("generate pull request index failed: %w", err)
  395. }
  396. issue.Index = idx
  397. if err = NewIssueWithIndex(ctx, issue.Poster, NewIssueOptions{
  398. Repo: repo,
  399. Issue: issue,
  400. LabelIDs: labelIDs,
  401. Attachments: uuids,
  402. IsPull: true,
  403. }); err != nil {
  404. if repo_model.IsErrUserDoesNotHaveAccessToRepo(err) || IsErrNewIssueInsert(err) {
  405. return err
  406. }
  407. return fmt.Errorf("newIssue: %w", err)
  408. }
  409. pr.Index = issue.Index
  410. pr.BaseRepo = repo
  411. pr.IssueID = issue.ID
  412. if err = db.Insert(ctx, pr); err != nil {
  413. return fmt.Errorf("insert pull repo: %w", err)
  414. }
  415. if err = committer.Commit(); err != nil {
  416. return fmt.Errorf("Commit: %w", err)
  417. }
  418. return nil
  419. }
  420. // GetUnmergedPullRequest returns a pull request that is open and has not been merged
  421. // by given head/base and repo/branch.
  422. func GetUnmergedPullRequest(ctx context.Context, headRepoID, baseRepoID int64, headBranch, baseBranch string, flow PullRequestFlow) (*PullRequest, error) {
  423. pr := new(PullRequest)
  424. has, err := db.GetEngine(ctx).
  425. Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND flow = ? AND issue.is_closed=?",
  426. headRepoID, headBranch, baseRepoID, baseBranch, false, flow, false).
  427. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  428. Get(pr)
  429. if err != nil {
  430. return nil, err
  431. } else if !has {
  432. return nil, ErrPullRequestNotExist{0, 0, headRepoID, baseRepoID, headBranch, baseBranch}
  433. }
  434. return pr, nil
  435. }
  436. // GetLatestPullRequestByHeadInfo returns the latest pull request (regardless of its status)
  437. // by given head information (repo and branch).
  438. func GetLatestPullRequestByHeadInfo(repoID int64, branch string) (*PullRequest, error) {
  439. pr := new(PullRequest)
  440. has, err := db.GetEngine(db.DefaultContext).
  441. Where("head_repo_id = ? AND head_branch = ? AND flow = ?", repoID, branch, PullRequestFlowGithub).
  442. OrderBy("id DESC").
  443. Get(pr)
  444. if !has {
  445. return nil, err
  446. }
  447. return pr, err
  448. }
  449. // GetPullRequestByIndex returns a pull request by the given index
  450. func GetPullRequestByIndex(ctx context.Context, repoID, index int64) (*PullRequest, error) {
  451. if index < 1 {
  452. return nil, ErrPullRequestNotExist{}
  453. }
  454. pr := &PullRequest{
  455. BaseRepoID: repoID,
  456. Index: index,
  457. }
  458. has, err := db.GetEngine(ctx).Get(pr)
  459. if err != nil {
  460. return nil, err
  461. } else if !has {
  462. return nil, ErrPullRequestNotExist{0, 0, 0, repoID, "", ""}
  463. }
  464. if err = pr.LoadAttributes(ctx); err != nil {
  465. return nil, err
  466. }
  467. if err = pr.LoadIssue(ctx); err != nil {
  468. return nil, err
  469. }
  470. return pr, nil
  471. }
  472. // GetPullRequestByID returns a pull request by given ID.
  473. func GetPullRequestByID(ctx context.Context, id int64) (*PullRequest, error) {
  474. pr := new(PullRequest)
  475. has, err := db.GetEngine(ctx).ID(id).Get(pr)
  476. if err != nil {
  477. return nil, err
  478. } else if !has {
  479. return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""}
  480. }
  481. return pr, pr.LoadAttributes(ctx)
  482. }
  483. // GetPullRequestByIssueIDWithNoAttributes returns pull request with no attributes loaded by given issue ID.
  484. func GetPullRequestByIssueIDWithNoAttributes(issueID int64) (*PullRequest, error) {
  485. var pr PullRequest
  486. has, err := db.GetEngine(db.DefaultContext).Where("issue_id = ?", issueID).Get(&pr)
  487. if err != nil {
  488. return nil, err
  489. }
  490. if !has {
  491. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  492. }
  493. return &pr, nil
  494. }
  495. // GetPullRequestByIssueID returns pull request by given issue ID.
  496. func GetPullRequestByIssueID(ctx context.Context, issueID int64) (*PullRequest, error) {
  497. pr := &PullRequest{
  498. IssueID: issueID,
  499. }
  500. has, err := db.GetByBean(ctx, pr)
  501. if err != nil {
  502. return nil, err
  503. } else if !has {
  504. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  505. }
  506. return pr, pr.LoadAttributes(ctx)
  507. }
  508. // GetAllUnmergedAgitPullRequestByPoster get all unmerged agit flow pull request
  509. // By poster id.
  510. func GetAllUnmergedAgitPullRequestByPoster(uid int64) ([]*PullRequest, error) {
  511. pulls := make([]*PullRequest, 0, 10)
  512. err := db.GetEngine(db.DefaultContext).
  513. Where("has_merged=? AND flow = ? AND issue.is_closed=? AND issue.poster_id=?",
  514. false, PullRequestFlowAGit, false, uid).
  515. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  516. Find(&pulls)
  517. return pulls, err
  518. }
  519. // Update updates all fields of pull request.
  520. func (pr *PullRequest) Update() error {
  521. _, err := db.GetEngine(db.DefaultContext).ID(pr.ID).AllCols().Update(pr)
  522. return err
  523. }
  524. // UpdateCols updates specific fields of pull request.
  525. func (pr *PullRequest) UpdateCols(cols ...string) error {
  526. _, err := db.GetEngine(db.DefaultContext).ID(pr.ID).Cols(cols...).Update(pr)
  527. return err
  528. }
  529. // UpdateColsIfNotMerged updates specific fields of a pull request if it has not been merged
  530. func (pr *PullRequest) UpdateColsIfNotMerged(ctx context.Context, cols ...string) error {
  531. _, err := db.GetEngine(ctx).Where("id = ? AND has_merged = ?", pr.ID, false).Cols(cols...).Update(pr)
  532. return err
  533. }
  534. // IsWorkInProgress determine if the Pull Request is a Work In Progress by its title
  535. // Issue must be set before this method can be called.
  536. func (pr *PullRequest) IsWorkInProgress() bool {
  537. if err := pr.LoadIssue(db.DefaultContext); err != nil {
  538. log.Error("LoadIssue: %v", err)
  539. return false
  540. }
  541. return HasWorkInProgressPrefix(pr.Issue.Title)
  542. }
  543. // HasWorkInProgressPrefix determines if the given PR title has a Work In Progress prefix
  544. func HasWorkInProgressPrefix(title string) bool {
  545. for _, prefix := range setting.Repository.PullRequest.WorkInProgressPrefixes {
  546. if strings.HasPrefix(strings.ToUpper(title), strings.ToUpper(prefix)) {
  547. return true
  548. }
  549. }
  550. return false
  551. }
  552. // IsFilesConflicted determines if the Pull Request has changes conflicting with the target branch.
  553. func (pr *PullRequest) IsFilesConflicted() bool {
  554. return len(pr.ConflictedFiles) > 0
  555. }
  556. // GetWorkInProgressPrefix returns the prefix used to mark the pull request as a work in progress.
  557. // It returns an empty string when none were found
  558. func (pr *PullRequest) GetWorkInProgressPrefix(ctx context.Context) string {
  559. if err := pr.LoadIssue(ctx); err != nil {
  560. log.Error("LoadIssue: %v", err)
  561. return ""
  562. }
  563. for _, prefix := range setting.Repository.PullRequest.WorkInProgressPrefixes {
  564. if strings.HasPrefix(strings.ToUpper(pr.Issue.Title), strings.ToUpper(prefix)) {
  565. return pr.Issue.Title[0:len(prefix)]
  566. }
  567. }
  568. return ""
  569. }
  570. // UpdateCommitDivergence update Divergence of a pull request
  571. func (pr *PullRequest) UpdateCommitDivergence(ctx context.Context, ahead, behind int) error {
  572. if pr.ID == 0 {
  573. return fmt.Errorf("pull ID is 0")
  574. }
  575. pr.CommitsAhead = ahead
  576. pr.CommitsBehind = behind
  577. _, err := db.GetEngine(ctx).ID(pr.ID).Cols("commits_ahead", "commits_behind").Update(pr)
  578. return err
  579. }
  580. // IsSameRepo returns true if base repo and head repo is the same
  581. func (pr *PullRequest) IsSameRepo() bool {
  582. return pr.BaseRepoID == pr.HeadRepoID
  583. }
  584. // GetPullRequestsByHeadBranch returns all prs by head branch
  585. // Since there could be multiple prs with the same head branch, this function returns a slice of prs
  586. func GetPullRequestsByHeadBranch(ctx context.Context, headBranch string, headRepoID int64) ([]*PullRequest, error) {
  587. log.Trace("GetPullRequestsByHeadBranch: headBranch: '%s', headRepoID: '%d'", headBranch, headRepoID)
  588. prs := make([]*PullRequest, 0, 2)
  589. if err := db.GetEngine(ctx).Where(builder.Eq{"head_branch": headBranch, "head_repo_id": headRepoID}).
  590. Find(&prs); err != nil {
  591. return nil, err
  592. }
  593. return prs, nil
  594. }
  595. // GetBaseBranchHTMLURL returns the HTML URL of the base branch
  596. func (pr *PullRequest) GetBaseBranchHTMLURL() string {
  597. if err := pr.LoadBaseRepo(db.DefaultContext); err != nil {
  598. log.Error("LoadBaseRepo: %v", err)
  599. return ""
  600. }
  601. if pr.BaseRepo == nil {
  602. return ""
  603. }
  604. return pr.BaseRepo.HTMLURL() + "/src/branch/" + util.PathEscapeSegments(pr.BaseBranch)
  605. }
  606. // GetHeadBranchHTMLURL returns the HTML URL of the head branch
  607. func (pr *PullRequest) GetHeadBranchHTMLURL() string {
  608. if pr.Flow == PullRequestFlowAGit {
  609. return ""
  610. }
  611. if err := pr.LoadHeadRepo(db.DefaultContext); err != nil {
  612. log.Error("LoadHeadRepo: %v", err)
  613. return ""
  614. }
  615. if pr.HeadRepo == nil {
  616. return ""
  617. }
  618. return pr.HeadRepo.HTMLURL() + "/src/branch/" + util.PathEscapeSegments(pr.HeadBranch)
  619. }
  620. // UpdateAllowEdits update if PR can be edited from maintainers
  621. func UpdateAllowEdits(ctx context.Context, pr *PullRequest) error {
  622. if _, err := db.GetEngine(ctx).ID(pr.ID).Cols("allow_maintainer_edit").Update(pr); err != nil {
  623. return err
  624. }
  625. return nil
  626. }
  627. // Mergeable returns if the pullrequest is mergeable.
  628. func (pr *PullRequest) Mergeable() bool {
  629. // If a pull request isn't mergable if it's:
  630. // - Being conflict checked.
  631. // - Has a conflict.
  632. // - Received a error while being conflict checked.
  633. // - Is a work-in-progress pull request.
  634. return pr.Status != PullRequestStatusChecking && pr.Status != PullRequestStatusConflict &&
  635. pr.Status != PullRequestStatusError && !pr.IsWorkInProgress()
  636. }
  637. // HasEnoughApprovals returns true if pr has enough granted approvals.
  638. func HasEnoughApprovals(ctx context.Context, protectBranch *git_model.ProtectedBranch, pr *PullRequest) bool {
  639. if protectBranch.RequiredApprovals == 0 {
  640. return true
  641. }
  642. return GetGrantedApprovalsCount(ctx, protectBranch, pr) >= protectBranch.RequiredApprovals
  643. }
  644. // GetGrantedApprovalsCount returns the number of granted approvals for pr. A granted approval must be authored by a user in an approval whitelist.
  645. func GetGrantedApprovalsCount(ctx context.Context, protectBranch *git_model.ProtectedBranch, pr *PullRequest) int64 {
  646. sess := db.GetEngine(ctx).Where("issue_id = ?", pr.IssueID).
  647. And("type = ?", ReviewTypeApprove).
  648. And("official = ?", true).
  649. And("dismissed = ?", false)
  650. if protectBranch.DismissStaleApprovals {
  651. sess = sess.And("stale = ?", false)
  652. }
  653. approvals, err := sess.Count(new(Review))
  654. if err != nil {
  655. log.Error("GetGrantedApprovalsCount: %v", err)
  656. return 0
  657. }
  658. return approvals
  659. }
  660. // MergeBlockedByRejectedReview returns true if merge is blocked by rejected reviews
  661. func MergeBlockedByRejectedReview(ctx context.Context, protectBranch *git_model.ProtectedBranch, pr *PullRequest) bool {
  662. if !protectBranch.BlockOnRejectedReviews {
  663. return false
  664. }
  665. rejectExist, err := db.GetEngine(ctx).Where("issue_id = ?", pr.IssueID).
  666. And("type = ?", ReviewTypeReject).
  667. And("official = ?", true).
  668. And("dismissed = ?", false).
  669. Exist(new(Review))
  670. if err != nil {
  671. log.Error("MergeBlockedByRejectedReview: %v", err)
  672. return true
  673. }
  674. return rejectExist
  675. }
  676. // MergeBlockedByOfficialReviewRequests block merge because of some review request to official reviewer
  677. // of from official review
  678. func MergeBlockedByOfficialReviewRequests(ctx context.Context, protectBranch *git_model.ProtectedBranch, pr *PullRequest) bool {
  679. if !protectBranch.BlockOnOfficialReviewRequests {
  680. return false
  681. }
  682. has, err := db.GetEngine(ctx).Where("issue_id = ?", pr.IssueID).
  683. And("type = ?", ReviewTypeRequest).
  684. And("official = ?", true).
  685. Exist(new(Review))
  686. if err != nil {
  687. log.Error("MergeBlockedByOfficialReviewRequests: %v", err)
  688. return true
  689. }
  690. return has
  691. }
  692. // MergeBlockedByOutdatedBranch returns true if merge is blocked by an outdated head branch
  693. func MergeBlockedByOutdatedBranch(protectBranch *git_model.ProtectedBranch, pr *PullRequest) bool {
  694. return protectBranch.BlockOnOutdatedBranch && pr.CommitsBehind > 0
  695. }