Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  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(sess db.Engine, 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 := sess.In("pull_id", deleteCond).
  85. Delete(&pull_model.AutoMerge{}); err != nil {
  86. return err
  87. }
  88. // Delete review states
  89. if _, err := sess.In("pull_id", deleteCond).
  90. Delete(&pull_model.ReviewState{}); err != nil {
  91. return err
  92. }
  93. _, err := sess.Delete(&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(e db.Engine) (err error) {
  113. if pr.HasMerged && pr.Merger == nil {
  114. pr.Merger, err = user_model.GetUserByIDEngine(e, 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.GetEngine(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(db.GetEngine(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(db.GetEngine(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() ([]*ReviewCount, error) {
  219. return pr.getApprovalCounts(db.GetEngine(db.DefaultContext))
  220. }
  221. func (pr *PullRequest) getApprovalCounts(e db.Engine) ([]*ReviewCount, error) {
  222. rCounts := make([]*ReviewCount, 0, 6)
  223. sess := e.Where("issue_id = ?", pr.IssueID)
  224. 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)
  225. }
  226. // GetApprovers returns the approvers of the pull request
  227. func (pr *PullRequest) GetApprovers() string {
  228. stringBuilder := strings.Builder{}
  229. if err := pr.getReviewedByLines(&stringBuilder); err != nil {
  230. log.Error("Unable to getReviewedByLines: Error: %v", err)
  231. return ""
  232. }
  233. return stringBuilder.String()
  234. }
  235. func (pr *PullRequest) getReviewedByLines(writer io.Writer) error {
  236. maxReviewers := setting.Repository.PullRequest.DefaultMergeMessageMaxApprovers
  237. if maxReviewers == 0 {
  238. return nil
  239. }
  240. ctx, committer, err := db.TxContext()
  241. if err != nil {
  242. return err
  243. }
  244. defer committer.Close()
  245. sess := db.GetEngine(ctx)
  246. // Note: This doesn't page as we only expect a very limited number of reviews
  247. reviews, err := findReviews(sess, FindReviewOptions{
  248. Type: ReviewTypeApprove,
  249. IssueID: pr.IssueID,
  250. OfficialOnly: setting.Repository.PullRequest.DefaultMergeMessageOfficialApproversOnly,
  251. })
  252. if err != nil {
  253. log.Error("Unable to FindReviews for PR ID %d: %v", pr.ID, err)
  254. return err
  255. }
  256. reviewersWritten := 0
  257. for _, review := range reviews {
  258. if maxReviewers > 0 && reviewersWritten > maxReviewers {
  259. break
  260. }
  261. if err := review.loadReviewer(sess); err != nil && !user_model.IsErrUserNotExist(err) {
  262. log.Error("Unable to LoadReviewer[%d] for PR ID %d : %v", review.ReviewerID, pr.ID, err)
  263. return err
  264. } else if review.Reviewer == nil {
  265. continue
  266. }
  267. if _, err := writer.Write([]byte("Reviewed-by: ")); err != nil {
  268. return err
  269. }
  270. if _, err := writer.Write([]byte(review.Reviewer.NewGitSig().String())); err != nil {
  271. return err
  272. }
  273. if _, err := writer.Write([]byte{'\n'}); err != nil {
  274. return err
  275. }
  276. reviewersWritten++
  277. }
  278. return committer.Commit()
  279. }
  280. // GetGitRefName returns git ref for hidden pull request branch
  281. func (pr *PullRequest) GetGitRefName() string {
  282. return fmt.Sprintf("%s%d/head", git.PullPrefix, pr.Index)
  283. }
  284. // IsChecking returns true if this pull request is still checking conflict.
  285. func (pr *PullRequest) IsChecking() bool {
  286. return pr.Status == PullRequestStatusChecking
  287. }
  288. // CanAutoMerge returns true if this pull request can be merged automatically.
  289. func (pr *PullRequest) CanAutoMerge() bool {
  290. return pr.Status == PullRequestStatusMergeable
  291. }
  292. // IsEmpty returns true if this pull request is empty.
  293. func (pr *PullRequest) IsEmpty() bool {
  294. return pr.Status == PullRequestStatusEmpty
  295. }
  296. // SetMerged sets a pull request to merged and closes the corresponding issue
  297. func (pr *PullRequest) SetMerged(ctx context.Context) (bool, error) {
  298. if pr.HasMerged {
  299. return false, fmt.Errorf("PullRequest[%d] already merged", pr.Index)
  300. }
  301. if pr.MergedCommitID == "" || pr.MergedUnix == 0 || pr.Merger == nil {
  302. return false, fmt.Errorf("Unable to merge PullRequest[%d], some required fields are empty", pr.Index)
  303. }
  304. pr.HasMerged = true
  305. sess := db.GetEngine(ctx)
  306. if _, err := sess.Exec("UPDATE `issue` SET `repo_id` = `repo_id` WHERE `id` = ?", pr.IssueID); err != nil {
  307. return false, err
  308. }
  309. if _, err := sess.Exec("UPDATE `pull_request` SET `issue_id` = `issue_id` WHERE `id` = ?", pr.ID); err != nil {
  310. return false, err
  311. }
  312. pr.Issue = nil
  313. if err := pr.LoadIssueCtx(ctx); err != nil {
  314. return false, err
  315. }
  316. if tmpPr, err := getPullRequestByID(sess, pr.ID); err != nil {
  317. return false, err
  318. } else if tmpPr.HasMerged {
  319. if pr.Issue.IsClosed {
  320. return false, nil
  321. }
  322. return false, fmt.Errorf("PullRequest[%d] already merged but it's associated issue [%d] is not closed", pr.Index, pr.IssueID)
  323. } else if pr.Issue.IsClosed {
  324. return false, fmt.Errorf("PullRequest[%d] already closed", pr.Index)
  325. }
  326. if err := pr.Issue.LoadRepo(ctx); err != nil {
  327. return false, err
  328. }
  329. if err := pr.Issue.Repo.GetOwner(ctx); err != nil {
  330. return false, err
  331. }
  332. if _, err := changeIssueStatus(ctx, pr.Issue, pr.Merger, true, true); err != nil {
  333. return false, fmt.Errorf("Issue.changeStatus: %v", err)
  334. }
  335. // reset the conflicted files as there cannot be any if we're merged
  336. pr.ConflictedFiles = []string{}
  337. // 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.
  338. 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 {
  339. return false, fmt.Errorf("Failed to update pr[%d]: %v", pr.ID, err)
  340. }
  341. return true, nil
  342. }
  343. // NewPullRequest creates new pull request with labels for repository.
  344. func NewPullRequest(outerCtx context.Context, repo *repo_model.Repository, issue *Issue, labelIDs []int64, uuids []string, pr *PullRequest) (err error) {
  345. idx, err := db.GetNextResourceIndex("issue_index", repo.ID)
  346. if err != nil {
  347. return fmt.Errorf("generate pull request index failed: %v", err)
  348. }
  349. issue.Index = idx
  350. ctx, committer, err := db.TxContext()
  351. if err != nil {
  352. return err
  353. }
  354. defer committer.Close()
  355. ctx.WithContext(outerCtx)
  356. if err = newIssue(ctx, issue.Poster, NewIssueOptions{
  357. Repo: repo,
  358. Issue: issue,
  359. LabelIDs: labelIDs,
  360. Attachments: uuids,
  361. IsPull: true,
  362. }); err != nil {
  363. if IsErrUserDoesNotHaveAccessToRepo(err) || IsErrNewIssueInsert(err) {
  364. return err
  365. }
  366. return fmt.Errorf("newIssue: %v", err)
  367. }
  368. pr.Index = issue.Index
  369. pr.BaseRepo = repo
  370. pr.IssueID = issue.ID
  371. if err = db.Insert(ctx, pr); err != nil {
  372. return fmt.Errorf("insert pull repo: %v", err)
  373. }
  374. if err = committer.Commit(); err != nil {
  375. return fmt.Errorf("Commit: %v", err)
  376. }
  377. return nil
  378. }
  379. // GetUnmergedPullRequest returns a pull request that is open and has not been merged
  380. // by given head/base and repo/branch.
  381. func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string, flow PullRequestFlow) (*PullRequest, error) {
  382. pr := new(PullRequest)
  383. has, err := db.GetEngine(db.DefaultContext).
  384. Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND flow = ? AND issue.is_closed=?",
  385. headRepoID, headBranch, baseRepoID, baseBranch, false, flow, false).
  386. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  387. Get(pr)
  388. if err != nil {
  389. return nil, err
  390. } else if !has {
  391. return nil, ErrPullRequestNotExist{0, 0, headRepoID, baseRepoID, headBranch, baseBranch}
  392. }
  393. return pr, nil
  394. }
  395. // GetLatestPullRequestByHeadInfo returns the latest pull request (regardless of its status)
  396. // by given head information (repo and branch).
  397. func GetLatestPullRequestByHeadInfo(repoID int64, branch string) (*PullRequest, error) {
  398. pr := new(PullRequest)
  399. has, err := db.GetEngine(db.DefaultContext).
  400. Where("head_repo_id = ? AND head_branch = ? AND flow = ?", repoID, branch, PullRequestFlowGithub).
  401. OrderBy("id DESC").
  402. Get(pr)
  403. if !has {
  404. return nil, err
  405. }
  406. return pr, err
  407. }
  408. // GetPullRequestByIndex returns a pull request by the given index
  409. func GetPullRequestByIndex(repoID, index int64) (*PullRequest, error) {
  410. return GetPullRequestByIndexCtx(db.DefaultContext, repoID, index)
  411. }
  412. // GetPullRequestByIndexCtx returns a pull request by the given index
  413. func GetPullRequestByIndexCtx(ctx context.Context, repoID, index int64) (*PullRequest, error) {
  414. if index < 1 {
  415. return nil, ErrPullRequestNotExist{}
  416. }
  417. pr := &PullRequest{
  418. BaseRepoID: repoID,
  419. Index: index,
  420. }
  421. has, err := db.GetEngine(ctx).Get(pr)
  422. if err != nil {
  423. return nil, err
  424. } else if !has {
  425. return nil, ErrPullRequestNotExist{0, 0, 0, repoID, "", ""}
  426. }
  427. if err = pr.loadAttributes(db.GetEngine(ctx)); err != nil {
  428. return nil, err
  429. }
  430. if err = pr.LoadIssueCtx(ctx); err != nil {
  431. return nil, err
  432. }
  433. return pr, nil
  434. }
  435. func getPullRequestByID(e db.Engine, id int64) (*PullRequest, error) {
  436. pr := new(PullRequest)
  437. has, err := e.ID(id).Get(pr)
  438. if err != nil {
  439. return nil, err
  440. } else if !has {
  441. return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""}
  442. }
  443. return pr, pr.loadAttributes(e)
  444. }
  445. // GetPullRequestByID returns a pull request by given ID.
  446. func GetPullRequestByID(ctx context.Context, id int64) (*PullRequest, error) {
  447. return getPullRequestByID(db.GetEngine(ctx), id)
  448. }
  449. // GetPullRequestByIssueIDWithNoAttributes returns pull request with no attributes loaded by given issue ID.
  450. func GetPullRequestByIssueIDWithNoAttributes(issueID int64) (*PullRequest, error) {
  451. var pr PullRequest
  452. has, err := db.GetEngine(db.DefaultContext).Where("issue_id = ?", issueID).Get(&pr)
  453. if err != nil {
  454. return nil, err
  455. }
  456. if !has {
  457. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  458. }
  459. return &pr, nil
  460. }
  461. func getPullRequestByIssueID(e db.Engine, issueID int64) (*PullRequest, error) {
  462. pr := &PullRequest{
  463. IssueID: issueID,
  464. }
  465. has, err := e.Get(pr)
  466. if err != nil {
  467. return nil, err
  468. } else if !has {
  469. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  470. }
  471. return pr, pr.loadAttributes(e)
  472. }
  473. // GetAllUnmergedAgitPullRequestByPoster get all unmerged agit flow pull request
  474. // By poster id.
  475. func GetAllUnmergedAgitPullRequestByPoster(uid int64) ([]*PullRequest, error) {
  476. pulls := make([]*PullRequest, 0, 10)
  477. err := db.GetEngine(db.DefaultContext).
  478. Where("has_merged=? AND flow = ? AND issue.is_closed=? AND issue.poster_id=?",
  479. false, PullRequestFlowAGit, false, uid).
  480. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  481. Find(&pulls)
  482. return pulls, err
  483. }
  484. // GetPullRequestByIssueID returns pull request by given issue ID.
  485. func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) {
  486. return getPullRequestByIssueID(db.GetEngine(db.DefaultContext), issueID)
  487. }
  488. // Update updates all fields of pull request.
  489. func (pr *PullRequest) Update() error {
  490. _, err := db.GetEngine(db.DefaultContext).ID(pr.ID).AllCols().Update(pr)
  491. return err
  492. }
  493. // UpdateCols updates specific fields of pull request.
  494. func (pr *PullRequest) UpdateCols(cols ...string) error {
  495. _, err := db.GetEngine(db.DefaultContext).ID(pr.ID).Cols(cols...).Update(pr)
  496. return err
  497. }
  498. // UpdateColsIfNotMerged updates specific fields of a pull request if it has not been merged
  499. func (pr *PullRequest) UpdateColsIfNotMerged(cols ...string) error {
  500. _, err := db.GetEngine(db.DefaultContext).Where("id = ? AND has_merged = ?", pr.ID, false).Cols(cols...).Update(pr)
  501. return err
  502. }
  503. // IsWorkInProgress determine if the Pull Request is a Work In Progress by its title
  504. func (pr *PullRequest) IsWorkInProgress() bool {
  505. if err := pr.LoadIssue(); err != nil {
  506. log.Error("LoadIssue: %v", err)
  507. return false
  508. }
  509. return HasWorkInProgressPrefix(pr.Issue.Title)
  510. }
  511. // HasWorkInProgressPrefix determines if the given PR title has a Work In Progress prefix
  512. func HasWorkInProgressPrefix(title string) bool {
  513. for _, prefix := range setting.Repository.PullRequest.WorkInProgressPrefixes {
  514. if strings.HasPrefix(strings.ToUpper(title), prefix) {
  515. return true
  516. }
  517. }
  518. return false
  519. }
  520. // IsFilesConflicted determines if the Pull Request has changes conflicting with the target branch.
  521. func (pr *PullRequest) IsFilesConflicted() bool {
  522. return len(pr.ConflictedFiles) > 0
  523. }
  524. // GetWorkInProgressPrefix returns the prefix used to mark the pull request as a work in progress.
  525. // It returns an empty string when none were found
  526. func (pr *PullRequest) GetWorkInProgressPrefix() string {
  527. if err := pr.LoadIssue(); err != nil {
  528. log.Error("LoadIssue: %v", err)
  529. return ""
  530. }
  531. for _, prefix := range setting.Repository.PullRequest.WorkInProgressPrefixes {
  532. if strings.HasPrefix(strings.ToUpper(pr.Issue.Title), prefix) {
  533. return pr.Issue.Title[0:len(prefix)]
  534. }
  535. }
  536. return ""
  537. }
  538. // UpdateCommitDivergence update Divergence of a pull request
  539. func (pr *PullRequest) UpdateCommitDivergence(ahead, behind int) error {
  540. return pr.updateCommitDivergence(db.GetEngine(db.DefaultContext), ahead, behind)
  541. }
  542. func (pr *PullRequest) updateCommitDivergence(e db.Engine, ahead, behind int) error {
  543. if pr.ID == 0 {
  544. return fmt.Errorf("pull ID is 0")
  545. }
  546. pr.CommitsAhead = ahead
  547. pr.CommitsBehind = behind
  548. _, err := e.ID(pr.ID).Cols("commits_ahead", "commits_behind").Update(pr)
  549. return err
  550. }
  551. // IsSameRepo returns true if base repo and head repo is the same
  552. func (pr *PullRequest) IsSameRepo() bool {
  553. return pr.BaseRepoID == pr.HeadRepoID
  554. }
  555. // GetPullRequestsByHeadBranch returns all prs by head branch
  556. // Since there could be multiple prs with the same head branch, this function returns a slice of prs
  557. func GetPullRequestsByHeadBranch(ctx context.Context, headBranch string, headRepoID int64) ([]*PullRequest, error) {
  558. log.Trace("GetPullRequestsByHeadBranch: headBranch: '%s', headRepoID: '%d'", headBranch, headRepoID)
  559. prs := make([]*PullRequest, 0, 2)
  560. if err := db.GetEngine(ctx).Where(builder.Eq{"head_branch": headBranch, "head_repo_id": headRepoID}).
  561. Find(&prs); err != nil {
  562. return nil, err
  563. }
  564. return prs, nil
  565. }
  566. // GetBaseBranchHTMLURL returns the HTML URL of the base branch
  567. func (pr *PullRequest) GetBaseBranchHTMLURL() string {
  568. if err := pr.LoadBaseRepo(); err != nil {
  569. log.Error("LoadBaseRepo: %v", err)
  570. return ""
  571. }
  572. if pr.BaseRepo == nil {
  573. return ""
  574. }
  575. return pr.BaseRepo.HTMLURL() + "/src/branch/" + util.PathEscapeSegments(pr.BaseBranch)
  576. }
  577. // GetHeadBranchHTMLURL returns the HTML URL of the head branch
  578. func (pr *PullRequest) GetHeadBranchHTMLURL() string {
  579. if pr.Flow == PullRequestFlowAGit {
  580. return ""
  581. }
  582. if err := pr.LoadHeadRepo(); err != nil {
  583. log.Error("LoadHeadRepo: %v", err)
  584. return ""
  585. }
  586. if pr.HeadRepo == nil {
  587. return ""
  588. }
  589. return pr.HeadRepo.HTMLURL() + "/src/branch/" + util.PathEscapeSegments(pr.HeadBranch)
  590. }
  591. // UpdateAllowEdits update if PR can be edited from maintainers
  592. func UpdateAllowEdits(ctx context.Context, pr *PullRequest) error {
  593. if _, err := db.GetEngine(ctx).ID(pr.ID).Cols("allow_maintainer_edit").Update(pr); err != nil {
  594. return err
  595. }
  596. return nil
  597. }
  598. // Mergeable returns if the pullrequest is mergeable.
  599. func (pr *PullRequest) Mergeable() bool {
  600. // If a pull request isn't mergable if it's:
  601. // - Being conflict checked.
  602. // - Has a conflict.
  603. // - Received a error while being conflict checked.
  604. // - Is a work-in-progress pull request.
  605. return pr.Status != PullRequestStatusChecking && pr.Status != PullRequestStatusConflict &&
  606. pr.Status != PullRequestStatusError && !pr.IsWorkInProgress()
  607. }