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

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