Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

pull.go 34KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215
  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) (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); 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) (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. }); err != nil {
  631. if IsErrUserDoesNotHaveAccessToRepo(err) || IsErrNewIssueInsert(err) {
  632. return err
  633. }
  634. return fmt.Errorf("newIssue: %v", err)
  635. }
  636. pr.Index = pull.Index
  637. pr.BaseRepo = repo
  638. pr.Status = PullRequestStatusChecking
  639. if len(patch) > 0 {
  640. if err = repo.savePatch(sess, pr.Index, patch); err != nil {
  641. return fmt.Errorf("SavePatch: %v", err)
  642. }
  643. if err = pr.testPatch(sess); err != nil {
  644. return fmt.Errorf("testPatch: %v", err)
  645. }
  646. }
  647. // No conflict appears after test means mergeable.
  648. if pr.Status == PullRequestStatusChecking {
  649. pr.Status = PullRequestStatusMergeable
  650. }
  651. pr.IssueID = pull.ID
  652. if _, err = sess.Insert(pr); err != nil {
  653. return fmt.Errorf("insert pull repo: %v", err)
  654. }
  655. if err = sess.Commit(); err != nil {
  656. return fmt.Errorf("Commit: %v", err)
  657. }
  658. return nil
  659. }
  660. // PullRequestsOptions holds the options for PRs
  661. type PullRequestsOptions struct {
  662. Page int
  663. State string
  664. SortType string
  665. Labels []string
  666. MilestoneID int64
  667. }
  668. func listPullRequestStatement(baseRepoID int64, opts *PullRequestsOptions) (*xorm.Session, error) {
  669. sess := x.Where("pull_request.base_repo_id=?", baseRepoID)
  670. sess.Join("INNER", "issue", "pull_request.issue_id = issue.id")
  671. switch opts.State {
  672. case "closed", "open":
  673. sess.And("issue.is_closed=?", opts.State == "closed")
  674. }
  675. if labelIDs, err := base.StringsToInt64s(opts.Labels); err != nil {
  676. return nil, err
  677. } else if len(labelIDs) > 0 {
  678. sess.Join("INNER", "issue_label", "issue.id = issue_label.issue_id").
  679. In("issue_label.label_id", labelIDs)
  680. }
  681. if opts.MilestoneID > 0 {
  682. sess.And("issue.milestone_id=?", opts.MilestoneID)
  683. }
  684. return sess, nil
  685. }
  686. // PullRequests returns all pull requests for a base Repo by the given conditions
  687. func PullRequests(baseRepoID int64, opts *PullRequestsOptions) ([]*PullRequest, int64, error) {
  688. if opts.Page <= 0 {
  689. opts.Page = 1
  690. }
  691. countSession, err := listPullRequestStatement(baseRepoID, opts)
  692. if err != nil {
  693. log.Error("listPullRequestStatement: %v", err)
  694. return nil, 0, err
  695. }
  696. maxResults, err := countSession.Count(new(PullRequest))
  697. if err != nil {
  698. log.Error("Count PRs: %v", err)
  699. return nil, maxResults, err
  700. }
  701. prs := make([]*PullRequest, 0, ItemsPerPage)
  702. findSession, err := listPullRequestStatement(baseRepoID, opts)
  703. sortIssuesSession(findSession, opts.SortType)
  704. if err != nil {
  705. log.Error("listPullRequestStatement: %v", err)
  706. return nil, maxResults, err
  707. }
  708. findSession.Limit(ItemsPerPage, (opts.Page-1)*ItemsPerPage)
  709. return prs, maxResults, findSession.Find(&prs)
  710. }
  711. // GetUnmergedPullRequest returns a pull request that is open and has not been merged
  712. // by given head/base and repo/branch.
  713. func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string) (*PullRequest, error) {
  714. pr := new(PullRequest)
  715. has, err := x.
  716. Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  717. headRepoID, headBranch, baseRepoID, baseBranch, false, false).
  718. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  719. Get(pr)
  720. if err != nil {
  721. return nil, err
  722. } else if !has {
  723. return nil, ErrPullRequestNotExist{0, 0, headRepoID, baseRepoID, headBranch, baseBranch}
  724. }
  725. return pr, nil
  726. }
  727. // GetUnmergedPullRequestsByHeadInfo returns all pull requests that are open and has not been merged
  728. // by given head information (repo and branch).
  729. func GetUnmergedPullRequestsByHeadInfo(repoID int64, branch string) ([]*PullRequest, error) {
  730. prs := make([]*PullRequest, 0, 2)
  731. return prs, x.
  732. Where("head_repo_id = ? AND head_branch = ? AND has_merged = ? AND issue.is_closed = ?",
  733. repoID, branch, false, false).
  734. Join("INNER", "issue", "issue.id = pull_request.issue_id").
  735. Find(&prs)
  736. }
  737. // GetLatestPullRequestByHeadInfo returns the latest pull request (regardless of its status)
  738. // by given head information (repo and branch).
  739. func GetLatestPullRequestByHeadInfo(repoID int64, branch string) (*PullRequest, error) {
  740. pr := new(PullRequest)
  741. has, err := x.
  742. Where("head_repo_id = ? AND head_branch = ?", repoID, branch).
  743. OrderBy("id DESC").
  744. Get(pr)
  745. if !has {
  746. return nil, err
  747. }
  748. return pr, err
  749. }
  750. // GetUnmergedPullRequestsByBaseInfo returns all pull requests that are open and has not been merged
  751. // by given base information (repo and branch).
  752. func GetUnmergedPullRequestsByBaseInfo(repoID int64, branch string) ([]*PullRequest, error) {
  753. prs := make([]*PullRequest, 0, 2)
  754. return prs, x.
  755. Where("base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  756. repoID, branch, false, false).
  757. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  758. Find(&prs)
  759. }
  760. // GetPullRequestByIndex returns a pull request by the given index
  761. func GetPullRequestByIndex(repoID int64, index int64) (*PullRequest, error) {
  762. pr := &PullRequest{
  763. BaseRepoID: repoID,
  764. Index: index,
  765. }
  766. has, err := x.Get(pr)
  767. if err != nil {
  768. return nil, err
  769. } else if !has {
  770. return nil, ErrPullRequestNotExist{0, 0, 0, repoID, "", ""}
  771. }
  772. if err = pr.LoadAttributes(); err != nil {
  773. return nil, err
  774. }
  775. if err = pr.LoadIssue(); err != nil {
  776. return nil, err
  777. }
  778. return pr, nil
  779. }
  780. func getPullRequestByID(e Engine, id int64) (*PullRequest, error) {
  781. pr := new(PullRequest)
  782. has, err := e.ID(id).Get(pr)
  783. if err != nil {
  784. return nil, err
  785. } else if !has {
  786. return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""}
  787. }
  788. return pr, pr.loadAttributes(e)
  789. }
  790. // GetPullRequestByID returns a pull request by given ID.
  791. func GetPullRequestByID(id int64) (*PullRequest, error) {
  792. return getPullRequestByID(x, id)
  793. }
  794. func getPullRequestByIssueID(e Engine, issueID int64) (*PullRequest, error) {
  795. pr := &PullRequest{
  796. IssueID: issueID,
  797. }
  798. has, err := e.Get(pr)
  799. if err != nil {
  800. return nil, err
  801. } else if !has {
  802. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  803. }
  804. return pr, pr.loadAttributes(e)
  805. }
  806. // GetPullRequestByIssueID returns pull request by given issue ID.
  807. func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) {
  808. return getPullRequestByIssueID(x, issueID)
  809. }
  810. // Update updates all fields of pull request.
  811. func (pr *PullRequest) Update() error {
  812. _, err := x.ID(pr.ID).AllCols().Update(pr)
  813. return err
  814. }
  815. // UpdateCols updates specific fields of pull request.
  816. func (pr *PullRequest) UpdateCols(cols ...string) error {
  817. _, err := x.ID(pr.ID).Cols(cols...).Update(pr)
  818. return err
  819. }
  820. // UpdatePatch generates and saves a new patch.
  821. func (pr *PullRequest) UpdatePatch() (err error) {
  822. if err = pr.GetHeadRepo(); err != nil {
  823. return fmt.Errorf("GetHeadRepo: %v", err)
  824. } else if pr.HeadRepo == nil {
  825. log.Trace("PullRequest[%d].UpdatePatch: ignored corrupted data", pr.ID)
  826. return nil
  827. }
  828. if err = pr.GetBaseRepo(); err != nil {
  829. return fmt.Errorf("GetBaseRepo: %v", err)
  830. }
  831. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  832. if err != nil {
  833. return fmt.Errorf("OpenRepository: %v", err)
  834. }
  835. // Add a temporary remote.
  836. tmpRemote := com.ToStr(time.Now().UnixNano())
  837. if err = headGitRepo.AddRemote(tmpRemote, RepoPath(pr.BaseRepo.MustOwner().Name, pr.BaseRepo.Name), true); err != nil {
  838. return fmt.Errorf("AddRemote: %v", err)
  839. }
  840. defer func() {
  841. if err := headGitRepo.RemoveRemote(tmpRemote); err != nil {
  842. log.Error("UpdatePatch: RemoveRemote: %s", err)
  843. }
  844. }()
  845. pr.MergeBase, _, err = headGitRepo.GetMergeBase(tmpRemote, pr.BaseBranch, pr.HeadBranch)
  846. if err != nil {
  847. return fmt.Errorf("GetMergeBase: %v", err)
  848. } else if err = pr.Update(); err != nil {
  849. return fmt.Errorf("Update: %v", err)
  850. }
  851. patch, err := headGitRepo.GetPatch(pr.MergeBase, pr.HeadBranch)
  852. if err != nil {
  853. return fmt.Errorf("GetPatch: %v", err)
  854. }
  855. if err = pr.BaseRepo.SavePatch(pr.Index, patch); err != nil {
  856. return fmt.Errorf("BaseRepo.SavePatch: %v", err)
  857. }
  858. return nil
  859. }
  860. // PushToBaseRepo pushes commits from branches of head repository to
  861. // corresponding branches of base repository.
  862. // FIXME: Only push branches that are actually updates?
  863. func (pr *PullRequest) PushToBaseRepo() (err error) {
  864. log.Trace("PushToBaseRepo[%d]: pushing commits to base repo '%s'", pr.BaseRepoID, pr.GetGitRefName())
  865. headRepoPath := pr.HeadRepo.RepoPath()
  866. headGitRepo, err := git.OpenRepository(headRepoPath)
  867. if err != nil {
  868. return fmt.Errorf("OpenRepository: %v", err)
  869. }
  870. tmpRemoteName := fmt.Sprintf("tmp-pull-%d", pr.ID)
  871. if err = headGitRepo.AddRemote(tmpRemoteName, pr.BaseRepo.RepoPath(), false); err != nil {
  872. return fmt.Errorf("headGitRepo.AddRemote: %v", err)
  873. }
  874. // Make sure to remove the remote even if the push fails
  875. defer func() {
  876. if err := headGitRepo.RemoveRemote(tmpRemoteName); err != nil {
  877. log.Error("PushToBaseRepo: RemoveRemote: %s", err)
  878. }
  879. }()
  880. headFile := pr.GetGitRefName()
  881. // Remove head in case there is a conflict.
  882. file := path.Join(pr.BaseRepo.RepoPath(), headFile)
  883. _ = os.Remove(file)
  884. if err = git.Push(headRepoPath, git.PushOptions{
  885. Remote: tmpRemoteName,
  886. Branch: fmt.Sprintf("%s:%s", pr.HeadBranch, headFile),
  887. Force: true,
  888. }); err != nil {
  889. return fmt.Errorf("Push: %v", err)
  890. }
  891. return nil
  892. }
  893. // AddToTaskQueue adds itself to pull request test task queue.
  894. func (pr *PullRequest) AddToTaskQueue() {
  895. go pullRequestQueue.AddFunc(pr.ID, func() {
  896. pr.Status = PullRequestStatusChecking
  897. if err := pr.UpdateCols("status"); err != nil {
  898. log.Error("AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
  899. }
  900. })
  901. }
  902. // PullRequestList defines a list of pull requests
  903. type PullRequestList []*PullRequest
  904. func (prs PullRequestList) loadAttributes(e Engine) error {
  905. if len(prs) == 0 {
  906. return nil
  907. }
  908. // Load issues.
  909. issueIDs := prs.getIssueIDs()
  910. issues := make([]*Issue, 0, len(issueIDs))
  911. if err := e.
  912. Where("id > 0").
  913. In("id", issueIDs).
  914. Find(&issues); err != nil {
  915. return fmt.Errorf("find issues: %v", err)
  916. }
  917. set := make(map[int64]*Issue)
  918. for i := range issues {
  919. set[issues[i].ID] = issues[i]
  920. }
  921. for i := range prs {
  922. prs[i].Issue = set[prs[i].IssueID]
  923. }
  924. return nil
  925. }
  926. func (prs PullRequestList) getIssueIDs() []int64 {
  927. issueIDs := make([]int64, 0, len(prs))
  928. for i := range prs {
  929. issueIDs = append(issueIDs, prs[i].IssueID)
  930. }
  931. return issueIDs
  932. }
  933. // LoadAttributes load all the prs attributes
  934. func (prs PullRequestList) LoadAttributes() error {
  935. return prs.loadAttributes(x)
  936. }
  937. func (prs PullRequestList) invalidateCodeComments(e Engine, doer *User, repo *git.Repository, branch string) error {
  938. if len(prs) == 0 {
  939. return nil
  940. }
  941. issueIDs := prs.getIssueIDs()
  942. var codeComments []*Comment
  943. if err := e.
  944. Where("type = ? and invalidated = ?", CommentTypeCode, false).
  945. In("issue_id", issueIDs).
  946. Find(&codeComments); err != nil {
  947. return fmt.Errorf("find code comments: %v", err)
  948. }
  949. for _, comment := range codeComments {
  950. if err := comment.CheckInvalidation(repo, doer, branch); err != nil {
  951. return err
  952. }
  953. }
  954. return nil
  955. }
  956. // InvalidateCodeComments will lookup the prs for code comments which got invalidated by change
  957. func (prs PullRequestList) InvalidateCodeComments(doer *User, repo *git.Repository, branch string) error {
  958. return prs.invalidateCodeComments(x, doer, repo, branch)
  959. }
  960. // checkAndUpdateStatus checks if pull request is possible to leaving checking status,
  961. // and set to be either conflict or mergeable.
  962. func (pr *PullRequest) checkAndUpdateStatus() {
  963. // Status is not changed to conflict means mergeable.
  964. if pr.Status == PullRequestStatusChecking {
  965. pr.Status = PullRequestStatusMergeable
  966. }
  967. // Make sure there is no waiting test to process before leaving the checking status.
  968. if !pullRequestQueue.Exist(pr.ID) {
  969. if err := pr.UpdateCols("status, conflicted_files"); err != nil {
  970. log.Error("Update[%d]: %v", pr.ID, err)
  971. }
  972. }
  973. }
  974. // IsWorkInProgress determine if the Pull Request is a Work In Progress by its title
  975. func (pr *PullRequest) IsWorkInProgress() bool {
  976. if err := pr.LoadIssue(); err != nil {
  977. log.Error("LoadIssue: %v", err)
  978. return false
  979. }
  980. for _, prefix := range setting.Repository.PullRequest.WorkInProgressPrefixes {
  981. if strings.HasPrefix(strings.ToUpper(pr.Issue.Title), prefix) {
  982. return true
  983. }
  984. }
  985. return false
  986. }
  987. // IsFilesConflicted determines if the Pull Request has changes conflicting with the target branch.
  988. func (pr *PullRequest) IsFilesConflicted() bool {
  989. return len(pr.ConflictedFiles) > 0
  990. }
  991. // GetWorkInProgressPrefix returns the prefix used to mark the pull request as a work in progress.
  992. // It returns an empty string when none were found
  993. func (pr *PullRequest) GetWorkInProgressPrefix() string {
  994. if err := pr.LoadIssue(); err != nil {
  995. log.Error("LoadIssue: %v", err)
  996. return ""
  997. }
  998. for _, prefix := range setting.Repository.PullRequest.WorkInProgressPrefixes {
  999. if strings.HasPrefix(strings.ToUpper(pr.Issue.Title), prefix) {
  1000. return pr.Issue.Title[0:len(prefix)]
  1001. }
  1002. }
  1003. return ""
  1004. }
  1005. // TestPullRequests checks and tests untested patches of pull requests.
  1006. // TODO: test more pull requests at same time.
  1007. func TestPullRequests() {
  1008. prs := make([]*PullRequest, 0, 10)
  1009. err := x.Where("status = ?", PullRequestStatusChecking).Find(&prs)
  1010. if err != nil {
  1011. log.Error("Find Checking PRs: %v", err)
  1012. return
  1013. }
  1014. var checkedPRs = make(map[int64]struct{})
  1015. // Update pull request status.
  1016. for _, pr := range prs {
  1017. checkedPRs[pr.ID] = struct{}{}
  1018. if err := pr.GetBaseRepo(); err != nil {
  1019. log.Error("GetBaseRepo: %v", err)
  1020. continue
  1021. }
  1022. if pr.manuallyMerged() {
  1023. continue
  1024. }
  1025. if err := pr.testPatch(x); err != nil {
  1026. log.Error("testPatch: %v", err)
  1027. continue
  1028. }
  1029. pr.checkAndUpdateStatus()
  1030. }
  1031. // Start listening on new test requests.
  1032. for prID := range pullRequestQueue.Queue() {
  1033. log.Trace("TestPullRequests[%v]: processing test task", prID)
  1034. pullRequestQueue.Remove(prID)
  1035. id := com.StrTo(prID).MustInt64()
  1036. if _, ok := checkedPRs[id]; ok {
  1037. continue
  1038. }
  1039. pr, err := GetPullRequestByID(id)
  1040. if err != nil {
  1041. log.Error("GetPullRequestByID[%s]: %v", prID, err)
  1042. continue
  1043. } else if pr.manuallyMerged() {
  1044. continue
  1045. } else if err = pr.testPatch(x); err != nil {
  1046. log.Error("testPatch[%d]: %v", pr.ID, err)
  1047. continue
  1048. }
  1049. pr.checkAndUpdateStatus()
  1050. }
  1051. }
  1052. // InitTestPullRequests runs the task to test all the checking status pull requests
  1053. func InitTestPullRequests() {
  1054. go TestPullRequests()
  1055. }