您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216
  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. "bufio"
  8. "fmt"
  9. "io/ioutil"
  10. "os"
  11. "path"
  12. "path/filepath"
  13. "strconv"
  14. "strings"
  15. "time"
  16. "code.gitea.io/gitea/modules/base"
  17. "code.gitea.io/gitea/modules/git"
  18. "code.gitea.io/gitea/modules/log"
  19. "code.gitea.io/gitea/modules/process"
  20. "code.gitea.io/gitea/modules/setting"
  21. api "code.gitea.io/gitea/modules/structs"
  22. "code.gitea.io/gitea/modules/sync"
  23. "code.gitea.io/gitea/modules/timeutil"
  24. "github.com/unknwon/com"
  25. "xorm.io/xorm"
  26. )
  27. var pullRequestQueue = sync.NewUniqueQueue(setting.Repository.PullRequestQueueLength)
  28. // PullRequestType defines pull request type
  29. type PullRequestType int
  30. // Enumerate all the pull request types
  31. const (
  32. PullRequestGitea PullRequestType = iota
  33. PullRequestGit
  34. )
  35. // PullRequestStatus defines pull request status
  36. type PullRequestStatus int
  37. // Enumerate all the pull request status
  38. const (
  39. PullRequestStatusConflict PullRequestStatus = iota
  40. PullRequestStatusChecking
  41. PullRequestStatusMergeable
  42. PullRequestStatusManuallyMerged
  43. )
  44. // PullRequest represents relation between pull request and repositories.
  45. type PullRequest struct {
  46. ID int64 `xorm:"pk autoincr"`
  47. Type PullRequestType
  48. Status PullRequestStatus
  49. ConflictedFiles []string `xorm:"TEXT JSON"`
  50. IssueID int64 `xorm:"INDEX"`
  51. Issue *Issue `xorm:"-"`
  52. Index int64
  53. HeadRepoID int64 `xorm:"INDEX"`
  54. HeadRepo *Repository `xorm:"-"`
  55. BaseRepoID int64 `xorm:"INDEX"`
  56. BaseRepo *Repository `xorm:"-"`
  57. HeadBranch string
  58. BaseBranch string
  59. ProtectedBranch *ProtectedBranch `xorm:"-"`
  60. MergeBase string `xorm:"VARCHAR(40)"`
  61. HasMerged bool `xorm:"INDEX"`
  62. MergedCommitID string `xorm:"VARCHAR(40)"`
  63. MergerID int64 `xorm:"INDEX"`
  64. Merger *User `xorm:"-"`
  65. MergedUnix timeutil.TimeStamp `xorm:"updated INDEX"`
  66. }
  67. // MustHeadUserName returns the HeadRepo's username if failed return blank
  68. func (pr *PullRequest) MustHeadUserName() string {
  69. if err := pr.LoadHeadRepo(); err != nil {
  70. log.Error("LoadHeadRepo: %v", err)
  71. return ""
  72. }
  73. return pr.HeadRepo.MustOwnerName()
  74. }
  75. // Note: don't try to get Issue because will end up recursive querying.
  76. func (pr *PullRequest) loadAttributes(e Engine) (err error) {
  77. if pr.HasMerged && pr.Merger == nil {
  78. pr.Merger, err = getUserByID(e, pr.MergerID)
  79. if IsErrUserNotExist(err) {
  80. pr.MergerID = -1
  81. pr.Merger = NewGhostUser()
  82. } else if err != nil {
  83. return fmt.Errorf("getUserByID [%d]: %v", pr.MergerID, err)
  84. }
  85. }
  86. return nil
  87. }
  88. // LoadAttributes loads pull request attributes from database
  89. func (pr *PullRequest) LoadAttributes() error {
  90. return pr.loadAttributes(x)
  91. }
  92. // LoadBaseRepo loads pull request base repository from database
  93. func (pr *PullRequest) LoadBaseRepo() error {
  94. if pr.BaseRepo == nil {
  95. if pr.HeadRepoID == pr.BaseRepoID && pr.HeadRepo != nil {
  96. pr.BaseRepo = pr.HeadRepo
  97. return nil
  98. }
  99. var repo Repository
  100. if has, err := x.ID(pr.BaseRepoID).Get(&repo); err != nil {
  101. return err
  102. } else if !has {
  103. return ErrRepoNotExist{ID: pr.BaseRepoID}
  104. }
  105. pr.BaseRepo = &repo
  106. }
  107. return nil
  108. }
  109. // LoadHeadRepo loads pull request head repository from database
  110. func (pr *PullRequest) LoadHeadRepo() error {
  111. if pr.HeadRepo == nil {
  112. if pr.HeadRepoID == pr.BaseRepoID && pr.BaseRepo != nil {
  113. pr.HeadRepo = pr.BaseRepo
  114. return nil
  115. }
  116. var repo Repository
  117. if has, err := x.ID(pr.HeadRepoID).Get(&repo); err != nil {
  118. return err
  119. } else if !has {
  120. return ErrRepoNotExist{ID: pr.BaseRepoID}
  121. }
  122. pr.HeadRepo = &repo
  123. }
  124. return nil
  125. }
  126. // LoadIssue loads issue information from database
  127. func (pr *PullRequest) LoadIssue() (err error) {
  128. return pr.loadIssue(x)
  129. }
  130. func (pr *PullRequest) loadIssue(e Engine) (err error) {
  131. if pr.Issue != nil {
  132. return nil
  133. }
  134. pr.Issue, err = getIssueByID(e, pr.IssueID)
  135. return err
  136. }
  137. // LoadProtectedBranch loads the protected branch of the base branch
  138. func (pr *PullRequest) LoadProtectedBranch() (err error) {
  139. if pr.BaseRepo == nil {
  140. if pr.BaseRepoID == 0 {
  141. return nil
  142. }
  143. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  144. if err != nil {
  145. return
  146. }
  147. }
  148. pr.ProtectedBranch, err = GetProtectedBranchBy(pr.BaseRepo.ID, pr.BaseBranch)
  149. return
  150. }
  151. // GetDefaultMergeMessage returns default message used when merging pull request
  152. func (pr *PullRequest) GetDefaultMergeMessage() string {
  153. if pr.HeadRepo == nil {
  154. var err error
  155. pr.HeadRepo, err = GetRepositoryByID(pr.HeadRepoID)
  156. if err != nil {
  157. log.Error("GetRepositoryById[%d]: %v", pr.HeadRepoID, err)
  158. return ""
  159. }
  160. }
  161. return fmt.Sprintf("Merge branch '%s' of %s/%s into %s", pr.HeadBranch, pr.MustHeadUserName(), pr.HeadRepo.Name, pr.BaseBranch)
  162. }
  163. // GetDefaultSquashMessage returns default message used when squash and merging pull request
  164. func (pr *PullRequest) GetDefaultSquashMessage() string {
  165. if err := pr.LoadIssue(); err != nil {
  166. log.Error("LoadIssue: %v", err)
  167. return ""
  168. }
  169. return fmt.Sprintf("%s (#%d)", pr.Issue.Title, pr.Issue.Index)
  170. }
  171. // GetGitRefName returns git ref for hidden pull request branch
  172. func (pr *PullRequest) GetGitRefName() string {
  173. return fmt.Sprintf("refs/pull/%d/head", pr.Index)
  174. }
  175. // APIFormat assumes following fields have been assigned with valid values:
  176. // Required - Issue
  177. // Optional - Merger
  178. func (pr *PullRequest) APIFormat() *api.PullRequest {
  179. return pr.apiFormat(x)
  180. }
  181. func (pr *PullRequest) apiFormat(e Engine) *api.PullRequest {
  182. var (
  183. baseBranch *git.Branch
  184. headBranch *git.Branch
  185. baseCommit *git.Commit
  186. headCommit *git.Commit
  187. err error
  188. )
  189. if err = pr.Issue.loadRepo(e); err != nil {
  190. log.Error("loadRepo[%d]: %v", pr.ID, err)
  191. return nil
  192. }
  193. apiIssue := pr.Issue.apiFormat(e)
  194. if pr.BaseRepo == nil {
  195. pr.BaseRepo, err = getRepositoryByID(e, pr.BaseRepoID)
  196. if err != nil {
  197. log.Error("GetRepositoryById[%d]: %v", pr.ID, err)
  198. return nil
  199. }
  200. }
  201. if pr.HeadRepo == nil {
  202. pr.HeadRepo, err = getRepositoryByID(e, pr.HeadRepoID)
  203. if err != nil {
  204. log.Error("GetRepositoryById[%d]: %v", pr.ID, err)
  205. return nil
  206. }
  207. }
  208. if err = pr.Issue.loadRepo(e); err != nil {
  209. log.Error("pr.Issue.loadRepo[%d]: %v", pr.ID, err)
  210. return nil
  211. }
  212. apiPullRequest := &api.PullRequest{
  213. ID: pr.ID,
  214. URL: pr.Issue.HTMLURL(),
  215. Index: pr.Index,
  216. Poster: apiIssue.Poster,
  217. Title: apiIssue.Title,
  218. Body: apiIssue.Body,
  219. Labels: apiIssue.Labels,
  220. Milestone: apiIssue.Milestone,
  221. Assignee: apiIssue.Assignee,
  222. Assignees: apiIssue.Assignees,
  223. State: apiIssue.State,
  224. Comments: apiIssue.Comments,
  225. HTMLURL: pr.Issue.HTMLURL(),
  226. DiffURL: pr.Issue.DiffURL(),
  227. PatchURL: pr.Issue.PatchURL(),
  228. HasMerged: pr.HasMerged,
  229. MergeBase: pr.MergeBase,
  230. Deadline: apiIssue.Deadline,
  231. Created: pr.Issue.CreatedUnix.AsTimePtr(),
  232. Updated: pr.Issue.UpdatedUnix.AsTimePtr(),
  233. }
  234. baseBranch, err = pr.BaseRepo.GetBranch(pr.BaseBranch)
  235. if err != nil {
  236. if git.IsErrBranchNotExist(err) {
  237. apiPullRequest.Base = nil
  238. } else {
  239. log.Error("GetBranch[%s]: %v", pr.BaseBranch, err)
  240. return nil
  241. }
  242. } else {
  243. apiBaseBranchInfo := &api.PRBranchInfo{
  244. Name: pr.BaseBranch,
  245. Ref: pr.BaseBranch,
  246. RepoID: pr.BaseRepoID,
  247. Repository: pr.BaseRepo.innerAPIFormat(e, AccessModeNone, false),
  248. }
  249. baseCommit, err = baseBranch.GetCommit()
  250. if err != nil {
  251. if git.IsErrNotExist(err) {
  252. apiBaseBranchInfo.Sha = ""
  253. } else {
  254. log.Error("GetCommit[%s]: %v", baseBranch.Name, err)
  255. return nil
  256. }
  257. } else {
  258. apiBaseBranchInfo.Sha = baseCommit.ID.String()
  259. }
  260. apiPullRequest.Base = apiBaseBranchInfo
  261. }
  262. headBranch, err = pr.HeadRepo.GetBranch(pr.HeadBranch)
  263. if err != nil {
  264. if git.IsErrBranchNotExist(err) {
  265. apiPullRequest.Head = nil
  266. } else {
  267. log.Error("GetBranch[%s]: %v", pr.HeadBranch, err)
  268. return nil
  269. }
  270. } else {
  271. apiHeadBranchInfo := &api.PRBranchInfo{
  272. Name: pr.HeadBranch,
  273. Ref: pr.HeadBranch,
  274. RepoID: pr.HeadRepoID,
  275. Repository: pr.HeadRepo.innerAPIFormat(e, AccessModeNone, false),
  276. }
  277. headCommit, err = headBranch.GetCommit()
  278. if err != nil {
  279. if git.IsErrNotExist(err) {
  280. apiHeadBranchInfo.Sha = ""
  281. } else {
  282. log.Error("GetCommit[%s]: %v", headBranch.Name, err)
  283. return nil
  284. }
  285. } else {
  286. apiHeadBranchInfo.Sha = headCommit.ID.String()
  287. }
  288. apiPullRequest.Head = apiHeadBranchInfo
  289. }
  290. if pr.Status != PullRequestStatusChecking {
  291. mergeable := pr.Status != PullRequestStatusConflict && !pr.IsWorkInProgress()
  292. apiPullRequest.Mergeable = mergeable
  293. }
  294. if pr.HasMerged {
  295. apiPullRequest.Merged = pr.MergedUnix.AsTimePtr()
  296. apiPullRequest.MergedCommitID = &pr.MergedCommitID
  297. apiPullRequest.MergedBy = pr.Merger.APIFormat()
  298. }
  299. return apiPullRequest
  300. }
  301. func (pr *PullRequest) getHeadRepo(e Engine) (err error) {
  302. pr.HeadRepo, err = getRepositoryByID(e, pr.HeadRepoID)
  303. if err != nil && !IsErrRepoNotExist(err) {
  304. return fmt.Errorf("getRepositoryByID(head): %v", err)
  305. }
  306. return nil
  307. }
  308. // GetHeadRepo loads the head repository
  309. func (pr *PullRequest) GetHeadRepo() error {
  310. return pr.getHeadRepo(x)
  311. }
  312. // GetBaseRepo loads the target repository
  313. func (pr *PullRequest) GetBaseRepo() (err error) {
  314. if pr.BaseRepo != nil {
  315. return nil
  316. }
  317. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  318. if err != nil {
  319. return fmt.Errorf("GetRepositoryByID(base): %v", err)
  320. }
  321. return nil
  322. }
  323. // IsChecking returns true if this pull request is still checking conflict.
  324. func (pr *PullRequest) IsChecking() bool {
  325. return pr.Status == PullRequestStatusChecking
  326. }
  327. // CanAutoMerge returns true if this pull request can be merged automatically.
  328. func (pr *PullRequest) CanAutoMerge() bool {
  329. return pr.Status == PullRequestStatusMergeable
  330. }
  331. // GetLastCommitStatus returns the last commit status for this pull request.
  332. func (pr *PullRequest) GetLastCommitStatus() (status *CommitStatus, err error) {
  333. if err = pr.GetHeadRepo(); err != nil {
  334. return nil, err
  335. }
  336. if pr.HeadRepo == nil {
  337. return nil, ErrPullRequestHeadRepoMissing{pr.ID, pr.HeadRepoID}
  338. }
  339. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  340. if err != nil {
  341. return nil, err
  342. }
  343. lastCommitID, err := headGitRepo.GetBranchCommitID(pr.HeadBranch)
  344. if err != nil {
  345. return nil, err
  346. }
  347. err = pr.LoadBaseRepo()
  348. if err != nil {
  349. return nil, err
  350. }
  351. statusList, err := GetLatestCommitStatus(pr.BaseRepo, lastCommitID, 0)
  352. if err != nil {
  353. return nil, err
  354. }
  355. return CalcCommitStatus(statusList), nil
  356. }
  357. // MergeStyle represents the approach to merge commits into base branch.
  358. type MergeStyle string
  359. const (
  360. // MergeStyleMerge create merge commit
  361. MergeStyleMerge MergeStyle = "merge"
  362. // MergeStyleRebase rebase before merging
  363. MergeStyleRebase MergeStyle = "rebase"
  364. // MergeStyleRebaseMerge rebase before merging with merge commit (--no-ff)
  365. MergeStyleRebaseMerge MergeStyle = "rebase-merge"
  366. // MergeStyleSquash squash commits into single commit before merging
  367. MergeStyleSquash MergeStyle = "squash"
  368. )
  369. // CheckUserAllowedToMerge checks whether the user is allowed to merge
  370. func (pr *PullRequest) CheckUserAllowedToMerge(doer *User) (err error) {
  371. if doer == nil {
  372. return ErrNotAllowedToMerge{
  373. "Not signed in",
  374. }
  375. }
  376. if pr.BaseRepo == nil {
  377. if err = pr.GetBaseRepo(); err != nil {
  378. return fmt.Errorf("GetBaseRepo: %v", err)
  379. }
  380. }
  381. if protected, err := pr.BaseRepo.IsProtectedBranchForMerging(pr, pr.BaseBranch, doer); err != nil {
  382. return fmt.Errorf("IsProtectedBranch: %v", err)
  383. } else if protected {
  384. return ErrNotAllowedToMerge{
  385. "The branch is protected",
  386. }
  387. }
  388. return nil
  389. }
  390. // SetMerged sets a pull request to merged and closes the corresponding issue
  391. func (pr *PullRequest) SetMerged() (err error) {
  392. if pr.HasMerged {
  393. return fmt.Errorf("PullRequest[%d] already merged", pr.Index)
  394. }
  395. if pr.MergedCommitID == "" || pr.MergedUnix == 0 || pr.Merger == nil {
  396. return fmt.Errorf("Unable to merge PullRequest[%d], some required fields are empty", pr.Index)
  397. }
  398. pr.HasMerged = true
  399. sess := x.NewSession()
  400. defer sess.Close()
  401. if err = sess.Begin(); err != nil {
  402. return err
  403. }
  404. if err = pr.loadIssue(sess); err != nil {
  405. return err
  406. }
  407. if err = pr.Issue.loadRepo(sess); err != nil {
  408. return err
  409. }
  410. if err = pr.Issue.Repo.getOwner(sess); err != nil {
  411. return err
  412. }
  413. if err = pr.Issue.changeStatus(sess, pr.Merger, true); err != nil {
  414. return fmt.Errorf("Issue.changeStatus: %v", err)
  415. }
  416. if _, err = sess.ID(pr.ID).Cols("has_merged, status, merged_commit_id, merger_id, merged_unix").Update(pr); err != nil {
  417. return fmt.Errorf("update pull request: %v", err)
  418. }
  419. if err = sess.Commit(); err != nil {
  420. return fmt.Errorf("Commit: %v", err)
  421. }
  422. return nil
  423. }
  424. // manuallyMerged checks if a pull request got manually merged
  425. // When a pull request got manually merged mark the pull request as merged
  426. func (pr *PullRequest) manuallyMerged() bool {
  427. commit, err := pr.getMergeCommit()
  428. if err != nil {
  429. log.Error("PullRequest[%d].getMergeCommit: %v", pr.ID, err)
  430. return false
  431. }
  432. if commit != nil {
  433. pr.MergedCommitID = commit.ID.String()
  434. pr.MergedUnix = timeutil.TimeStamp(commit.Author.When.Unix())
  435. pr.Status = PullRequestStatusManuallyMerged
  436. merger, _ := GetUserByEmail(commit.Author.Email)
  437. // When the commit author is unknown set the BaseRepo owner as merger
  438. if merger == nil {
  439. if pr.BaseRepo.Owner == nil {
  440. if err = pr.BaseRepo.getOwner(x); err != nil {
  441. log.Error("BaseRepo.getOwner[%d]: %v", pr.ID, err)
  442. return false
  443. }
  444. }
  445. merger = pr.BaseRepo.Owner
  446. }
  447. pr.Merger = merger
  448. pr.MergerID = merger.ID
  449. if err = pr.SetMerged(); err != nil {
  450. log.Error("PullRequest[%d].setMerged : %v", pr.ID, err)
  451. return false
  452. }
  453. log.Info("manuallyMerged[%d]: Marked as manually merged into %s/%s by commit id: %s", pr.ID, pr.BaseRepo.Name, pr.BaseBranch, commit.ID.String())
  454. return true
  455. }
  456. return false
  457. }
  458. // getMergeCommit checks if a pull request got merged
  459. // Returns the git.Commit of the pull request if merged
  460. func (pr *PullRequest) getMergeCommit() (*git.Commit, error) {
  461. if pr.BaseRepo == nil {
  462. var err error
  463. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  464. if err != nil {
  465. return nil, fmt.Errorf("GetRepositoryByID: %v", err)
  466. }
  467. }
  468. indexTmpPath := filepath.Join(os.TempDir(), "gitea-"+pr.BaseRepo.Name+"-"+strconv.Itoa(time.Now().Nanosecond()))
  469. defer os.Remove(indexTmpPath)
  470. headFile := pr.GetGitRefName()
  471. // Check if a pull request is merged into BaseBranch
  472. _, stderr, err := process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("isMerged (git merge-base --is-ancestor): %d", pr.BaseRepo.ID),
  473. []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()},
  474. git.GitExecutable, "merge-base", "--is-ancestor", headFile, pr.BaseBranch)
  475. if err != nil {
  476. // Errors are signaled by a non-zero status that is not 1
  477. if strings.Contains(err.Error(), "exit status 1") {
  478. return nil, nil
  479. }
  480. return nil, fmt.Errorf("git merge-base --is-ancestor: %v %v", stderr, err)
  481. }
  482. commitIDBytes, err := ioutil.ReadFile(pr.BaseRepo.RepoPath() + "/" + headFile)
  483. if err != nil {
  484. return nil, fmt.Errorf("ReadFile(%s): %v", headFile, err)
  485. }
  486. commitID := string(commitIDBytes)
  487. if len(commitID) < 40 {
  488. return nil, fmt.Errorf(`ReadFile(%s): invalid commit-ID "%s"`, headFile, commitID)
  489. }
  490. cmd := commitID[:40] + ".." + pr.BaseBranch
  491. // Get the commit from BaseBranch where the pull request got merged
  492. mergeCommit, stderr, err := process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("isMerged (git rev-list --ancestry-path --merges --reverse): %d", pr.BaseRepo.ID),
  493. []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()},
  494. git.GitExecutable, "rev-list", "--ancestry-path", "--merges", "--reverse", cmd)
  495. if err != nil {
  496. return nil, fmt.Errorf("git rev-list --ancestry-path --merges --reverse: %v %v", stderr, err)
  497. } else if len(mergeCommit) < 40 {
  498. // PR was fast-forwarded, so just use last commit of PR
  499. mergeCommit = commitID[:40]
  500. }
  501. gitRepo, err := git.OpenRepository(pr.BaseRepo.RepoPath())
  502. if err != nil {
  503. return nil, fmt.Errorf("OpenRepository: %v", err)
  504. }
  505. commit, err := gitRepo.GetCommit(mergeCommit[:40])
  506. if err != nil {
  507. return nil, fmt.Errorf("GetCommit: %v", err)
  508. }
  509. return commit, nil
  510. }
  511. // patchConflicts is a list of conflict description from Git.
  512. var patchConflicts = []string{
  513. "patch does not apply",
  514. "already exists in working directory",
  515. "unrecognized input",
  516. "error:",
  517. }
  518. // testPatch checks if patch can be merged to base repository without conflict.
  519. func (pr *PullRequest) testPatch(e Engine) (err error) {
  520. if pr.BaseRepo == nil {
  521. pr.BaseRepo, err = getRepositoryByID(e, pr.BaseRepoID)
  522. if err != nil {
  523. return fmt.Errorf("GetRepositoryByID: %v", err)
  524. }
  525. }
  526. patchPath, err := pr.BaseRepo.patchPath(e, pr.Index)
  527. if err != nil {
  528. return fmt.Errorf("BaseRepo.PatchPath: %v", err)
  529. }
  530. // Fast fail if patch does not exist, this assumes data is corrupted.
  531. if !com.IsFile(patchPath) {
  532. log.Trace("PullRequest[%d].testPatch: ignored corrupted data", pr.ID)
  533. return nil
  534. }
  535. repoWorkingPool.CheckIn(com.ToStr(pr.BaseRepoID))
  536. defer repoWorkingPool.CheckOut(com.ToStr(pr.BaseRepoID))
  537. log.Trace("PullRequest[%d].testPatch (patchPath): %s", pr.ID, patchPath)
  538. pr.Status = PullRequestStatusChecking
  539. indexTmpPath := filepath.Join(os.TempDir(), "gitea-"+pr.BaseRepo.Name+"-"+strconv.Itoa(time.Now().Nanosecond()))
  540. defer os.Remove(indexTmpPath)
  541. var stderr string
  542. _, stderr, err = process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("testPatch (git read-tree): %d", pr.BaseRepo.ID),
  543. []string{"GIT_DIR=" + pr.BaseRepo.RepoPath(), "GIT_INDEX_FILE=" + indexTmpPath},
  544. git.GitExecutable, "read-tree", pr.BaseBranch)
  545. if err != nil {
  546. return fmt.Errorf("git read-tree --index-output=%s %s: %v - %s", indexTmpPath, pr.BaseBranch, err, stderr)
  547. }
  548. prUnit, err := pr.BaseRepo.getUnit(e, UnitTypePullRequests)
  549. if err != nil {
  550. return err
  551. }
  552. prConfig := prUnit.PullRequestsConfig()
  553. args := []string{"apply", "--check", "--cached"}
  554. if prConfig.IgnoreWhitespaceConflicts {
  555. args = append(args, "--ignore-whitespace")
  556. }
  557. args = append(args, patchPath)
  558. pr.ConflictedFiles = []string{}
  559. _, stderr, err = process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("testPatch (git apply --check): %d", pr.BaseRepo.ID),
  560. []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()},
  561. git.GitExecutable, args...)
  562. if err != nil {
  563. for i := range patchConflicts {
  564. if strings.Contains(stderr, patchConflicts[i]) {
  565. log.Trace("PullRequest[%d].testPatch (apply): has conflict: %s", pr.ID, stderr)
  566. const prefix = "error: patch failed:"
  567. pr.Status = PullRequestStatusConflict
  568. pr.ConflictedFiles = make([]string, 0, 5)
  569. scanner := bufio.NewScanner(strings.NewReader(stderr))
  570. for scanner.Scan() {
  571. line := scanner.Text()
  572. if strings.HasPrefix(line, prefix) {
  573. var found bool
  574. var filepath = strings.TrimSpace(strings.Split(line[len(prefix):], ":")[0])
  575. for _, f := range pr.ConflictedFiles {
  576. if f == filepath {
  577. found = true
  578. break
  579. }
  580. }
  581. if !found {
  582. pr.ConflictedFiles = append(pr.ConflictedFiles, filepath)
  583. }
  584. }
  585. // only list 10 conflicted files
  586. if len(pr.ConflictedFiles) >= 10 {
  587. break
  588. }
  589. }
  590. if len(pr.ConflictedFiles) > 0 {
  591. log.Trace("Found %d files conflicted: %v", len(pr.ConflictedFiles), pr.ConflictedFiles)
  592. }
  593. return nil
  594. }
  595. }
  596. return fmt.Errorf("git apply --check: %v - %s", err, stderr)
  597. }
  598. return nil
  599. }
  600. // NewPullRequest creates new pull request with labels for repository.
  601. func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest, patch []byte, assigneeIDs []int64) (err error) {
  602. // Retry several times in case INSERT fails due to duplicate key for (repo_id, index); see #7887
  603. i := 0
  604. for {
  605. if err = newPullRequestAttempt(repo, pull, labelIDs, uuids, pr, patch, assigneeIDs); err == nil {
  606. return nil
  607. }
  608. if !IsErrNewIssueInsert(err) {
  609. return err
  610. }
  611. if i++; i == issueMaxDupIndexAttempts {
  612. break
  613. }
  614. log.Error("NewPullRequest: error attempting to insert the new issue; will retry. Original error: %v", err)
  615. }
  616. return fmt.Errorf("NewPullRequest: too many errors attempting to insert the new issue. Last error was: %v", err)
  617. }
  618. func newPullRequestAttempt(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest, patch []byte, assigneeIDs []int64) (err error) {
  619. sess := x.NewSession()
  620. defer sess.Close()
  621. if err = sess.Begin(); err != nil {
  622. return err
  623. }
  624. if err = newIssue(sess, pull.Poster, NewIssueOptions{
  625. Repo: repo,
  626. Issue: pull,
  627. LabelIDs: labelIDs,
  628. Attachments: uuids,
  629. IsPull: true,
  630. AssigneeIDs: assigneeIDs,
  631. }); err != nil {
  632. if IsErrUserDoesNotHaveAccessToRepo(err) || IsErrNewIssueInsert(err) {
  633. return err
  634. }
  635. return fmt.Errorf("newIssue: %v", err)
  636. }
  637. pr.Index = pull.Index
  638. pr.BaseRepo = repo
  639. pr.Status = PullRequestStatusChecking
  640. if len(patch) > 0 {
  641. if err = repo.savePatch(sess, pr.Index, patch); err != nil {
  642. return fmt.Errorf("SavePatch: %v", err)
  643. }
  644. if err = pr.testPatch(sess); err != nil {
  645. return fmt.Errorf("testPatch: %v", err)
  646. }
  647. }
  648. // No conflict appears after test means mergeable.
  649. if pr.Status == PullRequestStatusChecking {
  650. pr.Status = PullRequestStatusMergeable
  651. }
  652. pr.IssueID = pull.ID
  653. if _, err = sess.Insert(pr); err != nil {
  654. return fmt.Errorf("insert pull repo: %v", err)
  655. }
  656. if err = sess.Commit(); err != nil {
  657. return fmt.Errorf("Commit: %v", err)
  658. }
  659. return nil
  660. }
  661. // PullRequestsOptions holds the options for PRs
  662. type PullRequestsOptions struct {
  663. Page int
  664. State string
  665. SortType string
  666. Labels []string
  667. MilestoneID int64
  668. }
  669. func listPullRequestStatement(baseRepoID int64, opts *PullRequestsOptions) (*xorm.Session, error) {
  670. sess := x.Where("pull_request.base_repo_id=?", baseRepoID)
  671. sess.Join("INNER", "issue", "pull_request.issue_id = issue.id")
  672. switch opts.State {
  673. case "closed", "open":
  674. sess.And("issue.is_closed=?", opts.State == "closed")
  675. }
  676. if labelIDs, err := base.StringsToInt64s(opts.Labels); err != nil {
  677. return nil, err
  678. } else if len(labelIDs) > 0 {
  679. sess.Join("INNER", "issue_label", "issue.id = issue_label.issue_id").
  680. In("issue_label.label_id", labelIDs)
  681. }
  682. if opts.MilestoneID > 0 {
  683. sess.And("issue.milestone_id=?", opts.MilestoneID)
  684. }
  685. return sess, nil
  686. }
  687. // PullRequests returns all pull requests for a base Repo by the given conditions
  688. func PullRequests(baseRepoID int64, opts *PullRequestsOptions) ([]*PullRequest, int64, error) {
  689. if opts.Page <= 0 {
  690. opts.Page = 1
  691. }
  692. countSession, err := listPullRequestStatement(baseRepoID, opts)
  693. if err != nil {
  694. log.Error("listPullRequestStatement: %v", err)
  695. return nil, 0, err
  696. }
  697. maxResults, err := countSession.Count(new(PullRequest))
  698. if err != nil {
  699. log.Error("Count PRs: %v", err)
  700. return nil, maxResults, err
  701. }
  702. prs := make([]*PullRequest, 0, ItemsPerPage)
  703. findSession, err := listPullRequestStatement(baseRepoID, opts)
  704. sortIssuesSession(findSession, opts.SortType)
  705. if err != nil {
  706. log.Error("listPullRequestStatement: %v", err)
  707. return nil, maxResults, err
  708. }
  709. findSession.Limit(ItemsPerPage, (opts.Page-1)*ItemsPerPage)
  710. return prs, maxResults, findSession.Find(&prs)
  711. }
  712. // GetUnmergedPullRequest returns a pull request that is open and has not been merged
  713. // by given head/base and repo/branch.
  714. func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string) (*PullRequest, error) {
  715. pr := new(PullRequest)
  716. has, err := x.
  717. Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  718. headRepoID, headBranch, baseRepoID, baseBranch, false, false).
  719. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  720. Get(pr)
  721. if err != nil {
  722. return nil, err
  723. } else if !has {
  724. return nil, ErrPullRequestNotExist{0, 0, headRepoID, baseRepoID, headBranch, baseBranch}
  725. }
  726. return pr, nil
  727. }
  728. // GetUnmergedPullRequestsByHeadInfo returns all pull requests that are open and has not been merged
  729. // by given head information (repo and branch).
  730. func GetUnmergedPullRequestsByHeadInfo(repoID int64, branch string) ([]*PullRequest, error) {
  731. prs := make([]*PullRequest, 0, 2)
  732. return prs, x.
  733. Where("head_repo_id = ? AND head_branch = ? AND has_merged = ? AND issue.is_closed = ?",
  734. repoID, branch, false, false).
  735. Join("INNER", "issue", "issue.id = pull_request.issue_id").
  736. Find(&prs)
  737. }
  738. // GetLatestPullRequestByHeadInfo returns the latest pull request (regardless of its status)
  739. // by given head information (repo and branch).
  740. func GetLatestPullRequestByHeadInfo(repoID int64, branch string) (*PullRequest, error) {
  741. pr := new(PullRequest)
  742. has, err := x.
  743. Where("head_repo_id = ? AND head_branch = ?", repoID, branch).
  744. OrderBy("id DESC").
  745. Get(pr)
  746. if !has {
  747. return nil, err
  748. }
  749. return pr, err
  750. }
  751. // GetUnmergedPullRequestsByBaseInfo returns all pull requests that are open and has not been merged
  752. // by given base information (repo and branch).
  753. func GetUnmergedPullRequestsByBaseInfo(repoID int64, branch string) ([]*PullRequest, error) {
  754. prs := make([]*PullRequest, 0, 2)
  755. return prs, x.
  756. Where("base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  757. repoID, branch, false, false).
  758. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  759. Find(&prs)
  760. }
  761. // GetPullRequestByIndex returns a pull request by the given index
  762. func GetPullRequestByIndex(repoID int64, index int64) (*PullRequest, error) {
  763. pr := &PullRequest{
  764. BaseRepoID: repoID,
  765. Index: index,
  766. }
  767. has, err := x.Get(pr)
  768. if err != nil {
  769. return nil, err
  770. } else if !has {
  771. return nil, ErrPullRequestNotExist{0, 0, 0, repoID, "", ""}
  772. }
  773. if err = pr.LoadAttributes(); err != nil {
  774. return nil, err
  775. }
  776. if err = pr.LoadIssue(); err != nil {
  777. return nil, err
  778. }
  779. return pr, nil
  780. }
  781. func getPullRequestByID(e Engine, id int64) (*PullRequest, error) {
  782. pr := new(PullRequest)
  783. has, err := e.ID(id).Get(pr)
  784. if err != nil {
  785. return nil, err
  786. } else if !has {
  787. return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""}
  788. }
  789. return pr, pr.loadAttributes(e)
  790. }
  791. // GetPullRequestByID returns a pull request by given ID.
  792. func GetPullRequestByID(id int64) (*PullRequest, error) {
  793. return getPullRequestByID(x, id)
  794. }
  795. func getPullRequestByIssueID(e Engine, issueID int64) (*PullRequest, error) {
  796. pr := &PullRequest{
  797. IssueID: issueID,
  798. }
  799. has, err := e.Get(pr)
  800. if err != nil {
  801. return nil, err
  802. } else if !has {
  803. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  804. }
  805. return pr, pr.loadAttributes(e)
  806. }
  807. // GetPullRequestByIssueID returns pull request by given issue ID.
  808. func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) {
  809. return getPullRequestByIssueID(x, issueID)
  810. }
  811. // Update updates all fields of pull request.
  812. func (pr *PullRequest) Update() error {
  813. _, err := x.ID(pr.ID).AllCols().Update(pr)
  814. return err
  815. }
  816. // UpdateCols updates specific fields of pull request.
  817. func (pr *PullRequest) UpdateCols(cols ...string) error {
  818. _, err := x.ID(pr.ID).Cols(cols...).Update(pr)
  819. return err
  820. }
  821. // UpdatePatch generates and saves a new patch.
  822. func (pr *PullRequest) UpdatePatch() (err error) {
  823. if err = pr.GetHeadRepo(); err != nil {
  824. return fmt.Errorf("GetHeadRepo: %v", err)
  825. } else if pr.HeadRepo == nil {
  826. log.Trace("PullRequest[%d].UpdatePatch: ignored corrupted data", pr.ID)
  827. return nil
  828. }
  829. if err = pr.GetBaseRepo(); err != nil {
  830. return fmt.Errorf("GetBaseRepo: %v", err)
  831. }
  832. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  833. if err != nil {
  834. return fmt.Errorf("OpenRepository: %v", err)
  835. }
  836. // Add a temporary remote.
  837. tmpRemote := com.ToStr(time.Now().UnixNano())
  838. if err = headGitRepo.AddRemote(tmpRemote, RepoPath(pr.BaseRepo.MustOwner().Name, pr.BaseRepo.Name), true); err != nil {
  839. return fmt.Errorf("AddRemote: %v", err)
  840. }
  841. defer func() {
  842. if err := headGitRepo.RemoveRemote(tmpRemote); err != nil {
  843. log.Error("UpdatePatch: RemoveRemote: %s", err)
  844. }
  845. }()
  846. pr.MergeBase, _, err = headGitRepo.GetMergeBase(tmpRemote, pr.BaseBranch, pr.HeadBranch)
  847. if err != nil {
  848. return fmt.Errorf("GetMergeBase: %v", err)
  849. } else if err = pr.Update(); err != nil {
  850. return fmt.Errorf("Update: %v", err)
  851. }
  852. patch, err := headGitRepo.GetPatch(pr.MergeBase, pr.HeadBranch)
  853. if err != nil {
  854. return fmt.Errorf("GetPatch: %v", err)
  855. }
  856. if err = pr.BaseRepo.SavePatch(pr.Index, patch); err != nil {
  857. return fmt.Errorf("BaseRepo.SavePatch: %v", err)
  858. }
  859. return nil
  860. }
  861. // PushToBaseRepo pushes commits from branches of head repository to
  862. // corresponding branches of base repository.
  863. // FIXME: Only push branches that are actually updates?
  864. func (pr *PullRequest) PushToBaseRepo() (err error) {
  865. log.Trace("PushToBaseRepo[%d]: pushing commits to base repo '%s'", pr.BaseRepoID, pr.GetGitRefName())
  866. headRepoPath := pr.HeadRepo.RepoPath()
  867. headGitRepo, err := git.OpenRepository(headRepoPath)
  868. if err != nil {
  869. return fmt.Errorf("OpenRepository: %v", err)
  870. }
  871. tmpRemoteName := fmt.Sprintf("tmp-pull-%d", pr.ID)
  872. if err = headGitRepo.AddRemote(tmpRemoteName, pr.BaseRepo.RepoPath(), false); err != nil {
  873. return fmt.Errorf("headGitRepo.AddRemote: %v", err)
  874. }
  875. // Make sure to remove the remote even if the push fails
  876. defer func() {
  877. if err := headGitRepo.RemoveRemote(tmpRemoteName); err != nil {
  878. log.Error("PushToBaseRepo: RemoveRemote: %s", err)
  879. }
  880. }()
  881. headFile := pr.GetGitRefName()
  882. // Remove head in case there is a conflict.
  883. file := path.Join(pr.BaseRepo.RepoPath(), headFile)
  884. _ = os.Remove(file)
  885. if err = git.Push(headRepoPath, git.PushOptions{
  886. Remote: tmpRemoteName,
  887. Branch: fmt.Sprintf("%s:%s", pr.HeadBranch, headFile),
  888. Force: true,
  889. }); err != nil {
  890. return fmt.Errorf("Push: %v", err)
  891. }
  892. return nil
  893. }
  894. // AddToTaskQueue adds itself to pull request test task queue.
  895. func (pr *PullRequest) AddToTaskQueue() {
  896. go pullRequestQueue.AddFunc(pr.ID, func() {
  897. pr.Status = PullRequestStatusChecking
  898. if err := pr.UpdateCols("status"); err != nil {
  899. log.Error("AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
  900. }
  901. })
  902. }
  903. // PullRequestList defines a list of pull requests
  904. type PullRequestList []*PullRequest
  905. func (prs PullRequestList) loadAttributes(e Engine) error {
  906. if len(prs) == 0 {
  907. return nil
  908. }
  909. // Load issues.
  910. issueIDs := prs.getIssueIDs()
  911. issues := make([]*Issue, 0, len(issueIDs))
  912. if err := e.
  913. Where("id > 0").
  914. In("id", issueIDs).
  915. Find(&issues); err != nil {
  916. return fmt.Errorf("find issues: %v", err)
  917. }
  918. set := make(map[int64]*Issue)
  919. for i := range issues {
  920. set[issues[i].ID] = issues[i]
  921. }
  922. for i := range prs {
  923. prs[i].Issue = set[prs[i].IssueID]
  924. }
  925. return nil
  926. }
  927. func (prs PullRequestList) getIssueIDs() []int64 {
  928. issueIDs := make([]int64, 0, len(prs))
  929. for i := range prs {
  930. issueIDs = append(issueIDs, prs[i].IssueID)
  931. }
  932. return issueIDs
  933. }
  934. // LoadAttributes load all the prs attributes
  935. func (prs PullRequestList) LoadAttributes() error {
  936. return prs.loadAttributes(x)
  937. }
  938. func (prs PullRequestList) invalidateCodeComments(e Engine, doer *User, repo *git.Repository, branch string) error {
  939. if len(prs) == 0 {
  940. return nil
  941. }
  942. issueIDs := prs.getIssueIDs()
  943. var codeComments []*Comment
  944. if err := e.
  945. Where("type = ? and invalidated = ?", CommentTypeCode, false).
  946. In("issue_id", issueIDs).
  947. Find(&codeComments); err != nil {
  948. return fmt.Errorf("find code comments: %v", err)
  949. }
  950. for _, comment := range codeComments {
  951. if err := comment.CheckInvalidation(repo, doer, branch); err != nil {
  952. return err
  953. }
  954. }
  955. return nil
  956. }
  957. // InvalidateCodeComments will lookup the prs for code comments which got invalidated by change
  958. func (prs PullRequestList) InvalidateCodeComments(doer *User, repo *git.Repository, branch string) error {
  959. return prs.invalidateCodeComments(x, doer, repo, branch)
  960. }
  961. // checkAndUpdateStatus checks if pull request is possible to leaving checking status,
  962. // and set to be either conflict or mergeable.
  963. func (pr *PullRequest) checkAndUpdateStatus() {
  964. // Status is not changed to conflict means mergeable.
  965. if pr.Status == PullRequestStatusChecking {
  966. pr.Status = PullRequestStatusMergeable
  967. }
  968. // Make sure there is no waiting test to process before leaving the checking status.
  969. if !pullRequestQueue.Exist(pr.ID) {
  970. if err := pr.UpdateCols("status, conflicted_files"); err != nil {
  971. log.Error("Update[%d]: %v", pr.ID, err)
  972. }
  973. }
  974. }
  975. // IsWorkInProgress determine if the Pull Request is a Work In Progress by its title
  976. func (pr *PullRequest) IsWorkInProgress() bool {
  977. if err := pr.LoadIssue(); err != nil {
  978. log.Error("LoadIssue: %v", err)
  979. return false
  980. }
  981. for _, prefix := range setting.Repository.PullRequest.WorkInProgressPrefixes {
  982. if strings.HasPrefix(strings.ToUpper(pr.Issue.Title), prefix) {
  983. return true
  984. }
  985. }
  986. return false
  987. }
  988. // IsFilesConflicted determines if the Pull Request has changes conflicting with the target branch.
  989. func (pr *PullRequest) IsFilesConflicted() bool {
  990. return len(pr.ConflictedFiles) > 0
  991. }
  992. // GetWorkInProgressPrefix returns the prefix used to mark the pull request as a work in progress.
  993. // It returns an empty string when none were found
  994. func (pr *PullRequest) GetWorkInProgressPrefix() string {
  995. if err := pr.LoadIssue(); err != nil {
  996. log.Error("LoadIssue: %v", err)
  997. return ""
  998. }
  999. for _, prefix := range setting.Repository.PullRequest.WorkInProgressPrefixes {
  1000. if strings.HasPrefix(strings.ToUpper(pr.Issue.Title), prefix) {
  1001. return pr.Issue.Title[0:len(prefix)]
  1002. }
  1003. }
  1004. return ""
  1005. }
  1006. // TestPullRequests checks and tests untested patches of pull requests.
  1007. // TODO: test more pull requests at same time.
  1008. func TestPullRequests() {
  1009. prs := make([]*PullRequest, 0, 10)
  1010. err := x.Where("status = ?", PullRequestStatusChecking).Find(&prs)
  1011. if err != nil {
  1012. log.Error("Find Checking PRs: %v", err)
  1013. return
  1014. }
  1015. var checkedPRs = make(map[int64]struct{})
  1016. // Update pull request status.
  1017. for _, pr := range prs {
  1018. checkedPRs[pr.ID] = struct{}{}
  1019. if err := pr.GetBaseRepo(); err != nil {
  1020. log.Error("GetBaseRepo: %v", err)
  1021. continue
  1022. }
  1023. if pr.manuallyMerged() {
  1024. continue
  1025. }
  1026. if err := pr.testPatch(x); err != nil {
  1027. log.Error("testPatch: %v", err)
  1028. continue
  1029. }
  1030. pr.checkAndUpdateStatus()
  1031. }
  1032. // Start listening on new test requests.
  1033. for prID := range pullRequestQueue.Queue() {
  1034. log.Trace("TestPullRequests[%v]: processing test task", prID)
  1035. pullRequestQueue.Remove(prID)
  1036. id := com.StrTo(prID).MustInt64()
  1037. if _, ok := checkedPRs[id]; ok {
  1038. continue
  1039. }
  1040. pr, err := GetPullRequestByID(id)
  1041. if err != nil {
  1042. log.Error("GetPullRequestByID[%s]: %v", prID, err)
  1043. continue
  1044. } else if pr.manuallyMerged() {
  1045. continue
  1046. } else if err = pr.testPatch(x); err != nil {
  1047. log.Error("testPatch[%d]: %v", pr.ID, err)
  1048. continue
  1049. }
  1050. pr.checkAndUpdateStatus()
  1051. }
  1052. }
  1053. // InitTestPullRequests runs the task to test all the checking status pull requests
  1054. func InitTestPullRequests() {
  1055. go TestPullRequests()
  1056. }