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 21KB

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