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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308
  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/go-xorm/xorm"
  25. "github.com/unknwon/com"
  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. defer headGitRepo.Close()
  344. lastCommitID, err := headGitRepo.GetBranchCommitID(pr.HeadBranch)
  345. if err != nil {
  346. return nil, err
  347. }
  348. err = pr.LoadBaseRepo()
  349. if err != nil {
  350. return nil, err
  351. }
  352. statusList, err := GetLatestCommitStatus(pr.BaseRepo, lastCommitID, 0)
  353. if err != nil {
  354. return nil, err
  355. }
  356. return CalcCommitStatus(statusList), nil
  357. }
  358. // MergeStyle represents the approach to merge commits into base branch.
  359. type MergeStyle string
  360. const (
  361. // MergeStyleMerge create merge commit
  362. MergeStyleMerge MergeStyle = "merge"
  363. // MergeStyleRebase rebase before merging
  364. MergeStyleRebase MergeStyle = "rebase"
  365. // MergeStyleRebaseMerge rebase before merging with merge commit (--no-ff)
  366. MergeStyleRebaseMerge MergeStyle = "rebase-merge"
  367. // MergeStyleSquash squash commits into single commit before merging
  368. MergeStyleSquash MergeStyle = "squash"
  369. )
  370. // CheckUserAllowedToMerge checks whether the user is allowed to merge
  371. func (pr *PullRequest) CheckUserAllowedToMerge(doer *User) (err error) {
  372. if doer == nil {
  373. return ErrNotAllowedToMerge{
  374. "Not signed in",
  375. }
  376. }
  377. if pr.BaseRepo == nil {
  378. if err = pr.GetBaseRepo(); err != nil {
  379. return fmt.Errorf("GetBaseRepo: %v", err)
  380. }
  381. }
  382. if protected, err := pr.BaseRepo.IsProtectedBranchForMerging(pr, pr.BaseBranch, doer); err != nil {
  383. return fmt.Errorf("IsProtectedBranch: %v", err)
  384. } else if protected {
  385. return ErrNotAllowedToMerge{
  386. "The branch is protected",
  387. }
  388. }
  389. return nil
  390. }
  391. // SetMerged sets a pull request to merged and closes the corresponding issue
  392. func (pr *PullRequest) SetMerged() (err error) {
  393. if pr.HasMerged {
  394. return fmt.Errorf("PullRequest[%d] already merged", pr.Index)
  395. }
  396. if pr.MergedCommitID == "" || pr.MergedUnix == 0 || pr.Merger == nil {
  397. return fmt.Errorf("Unable to merge PullRequest[%d], some required fields are empty", pr.Index)
  398. }
  399. pr.HasMerged = true
  400. sess := x.NewSession()
  401. defer sess.Close()
  402. if err = sess.Begin(); err != nil {
  403. return err
  404. }
  405. if err = pr.loadIssue(sess); err != nil {
  406. return err
  407. }
  408. if err = pr.Issue.loadRepo(sess); err != nil {
  409. return err
  410. }
  411. if err = pr.Issue.Repo.getOwner(sess); err != nil {
  412. return err
  413. }
  414. if err = pr.Issue.changeStatus(sess, pr.Merger, true); err != nil {
  415. return fmt.Errorf("Issue.changeStatus: %v", err)
  416. }
  417. if _, err = sess.ID(pr.ID).Cols("has_merged, status, merged_commit_id, merger_id, merged_unix").Update(pr); err != nil {
  418. return fmt.Errorf("update pull request: %v", err)
  419. }
  420. if err = sess.Commit(); err != nil {
  421. return fmt.Errorf("Commit: %v", err)
  422. }
  423. return nil
  424. }
  425. // manuallyMerged checks if a pull request got manually merged
  426. // When a pull request got manually merged mark the pull request as merged
  427. func (pr *PullRequest) manuallyMerged() bool {
  428. commit, err := pr.getMergeCommit()
  429. if err != nil {
  430. log.Error("PullRequest[%d].getMergeCommit: %v", pr.ID, err)
  431. return false
  432. }
  433. if commit != nil {
  434. pr.MergedCommitID = commit.ID.String()
  435. pr.MergedUnix = timeutil.TimeStamp(commit.Author.When.Unix())
  436. pr.Status = PullRequestStatusManuallyMerged
  437. merger, _ := GetUserByEmail(commit.Author.Email)
  438. // When the commit author is unknown set the BaseRepo owner as merger
  439. if merger == nil {
  440. if pr.BaseRepo.Owner == nil {
  441. if err = pr.BaseRepo.getOwner(x); err != nil {
  442. log.Error("BaseRepo.getOwner[%d]: %v", pr.ID, err)
  443. return false
  444. }
  445. }
  446. merger = pr.BaseRepo.Owner
  447. }
  448. pr.Merger = merger
  449. pr.MergerID = merger.ID
  450. if err = pr.SetMerged(); err != nil {
  451. log.Error("PullRequest[%d].setMerged : %v", pr.ID, err)
  452. return false
  453. }
  454. 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())
  455. return true
  456. }
  457. return false
  458. }
  459. // getMergeCommit checks if a pull request got merged
  460. // Returns the git.Commit of the pull request if merged
  461. func (pr *PullRequest) getMergeCommit() (*git.Commit, error) {
  462. if pr.BaseRepo == nil {
  463. var err error
  464. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  465. if err != nil {
  466. return nil, fmt.Errorf("GetRepositoryByID: %v", err)
  467. }
  468. }
  469. indexTmpPath := filepath.Join(os.TempDir(), "gitea-"+pr.BaseRepo.Name+"-"+strconv.Itoa(time.Now().Nanosecond()))
  470. defer os.Remove(indexTmpPath)
  471. headFile := pr.GetGitRefName()
  472. // Check if a pull request is merged into BaseBranch
  473. _, stderr, err := process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("isMerged (git merge-base --is-ancestor): %d", pr.BaseRepo.ID),
  474. []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()},
  475. git.GitExecutable, "merge-base", "--is-ancestor", headFile, pr.BaseBranch)
  476. if err != nil {
  477. // Errors are signaled by a non-zero status that is not 1
  478. if strings.Contains(err.Error(), "exit status 1") {
  479. return nil, nil
  480. }
  481. return nil, fmt.Errorf("git merge-base --is-ancestor: %v %v", stderr, err)
  482. }
  483. commitIDBytes, err := ioutil.ReadFile(pr.BaseRepo.RepoPath() + "/" + headFile)
  484. if err != nil {
  485. return nil, fmt.Errorf("ReadFile(%s): %v", headFile, err)
  486. }
  487. commitID := string(commitIDBytes)
  488. if len(commitID) < 40 {
  489. return nil, fmt.Errorf(`ReadFile(%s): invalid commit-ID "%s"`, headFile, commitID)
  490. }
  491. cmd := commitID[:40] + ".." + pr.BaseBranch
  492. // Get the commit from BaseBranch where the pull request got merged
  493. mergeCommit, stderr, err := process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("isMerged (git rev-list --ancestry-path --merges --reverse): %d", pr.BaseRepo.ID),
  494. []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()},
  495. git.GitExecutable, "rev-list", "--ancestry-path", "--merges", "--reverse", cmd)
  496. if err != nil {
  497. return nil, fmt.Errorf("git rev-list --ancestry-path --merges --reverse: %v %v", stderr, err)
  498. } else if len(mergeCommit) < 40 {
  499. // PR was fast-forwarded, so just use last commit of PR
  500. mergeCommit = commitID[:40]
  501. }
  502. gitRepo, err := git.OpenRepository(pr.BaseRepo.RepoPath())
  503. if err != nil {
  504. return nil, fmt.Errorf("OpenRepository: %v", err)
  505. }
  506. defer gitRepo.Close()
  507. commit, err := gitRepo.GetCommit(mergeCommit[:40])
  508. if err != nil {
  509. return nil, fmt.Errorf("GetCommit: %v", err)
  510. }
  511. return commit, nil
  512. }
  513. // patchConflicts is a list of conflict description from Git.
  514. var patchConflicts = []string{
  515. "patch does not apply",
  516. "already exists in working directory",
  517. "unrecognized input",
  518. "error:",
  519. }
  520. // testPatch checks if patch can be merged to base repository without conflict.
  521. func (pr *PullRequest) testPatch(e Engine) (err error) {
  522. if pr.BaseRepo == nil {
  523. pr.BaseRepo, err = getRepositoryByID(e, pr.BaseRepoID)
  524. if err != nil {
  525. return fmt.Errorf("GetRepositoryByID: %v", err)
  526. }
  527. }
  528. patchPath, err := pr.BaseRepo.patchPath(e, pr.Index)
  529. if err != nil {
  530. return fmt.Errorf("BaseRepo.PatchPath: %v", err)
  531. }
  532. // Fast fail if patch does not exist, this assumes data is corrupted.
  533. if !com.IsFile(patchPath) {
  534. log.Trace("PullRequest[%d].testPatch: ignored corrupted data", pr.ID)
  535. return nil
  536. }
  537. repoWorkingPool.CheckIn(com.ToStr(pr.BaseRepoID))
  538. defer repoWorkingPool.CheckOut(com.ToStr(pr.BaseRepoID))
  539. log.Trace("PullRequest[%d].testPatch (patchPath): %s", pr.ID, patchPath)
  540. pr.Status = PullRequestStatusChecking
  541. indexTmpPath := filepath.Join(os.TempDir(), "gitea-"+pr.BaseRepo.Name+"-"+strconv.Itoa(time.Now().Nanosecond()))
  542. defer os.Remove(indexTmpPath)
  543. var stderr string
  544. _, stderr, err = process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("testPatch (git read-tree): %d", pr.BaseRepo.ID),
  545. []string{"GIT_DIR=" + pr.BaseRepo.RepoPath(), "GIT_INDEX_FILE=" + indexTmpPath},
  546. git.GitExecutable, "read-tree", pr.BaseBranch)
  547. if err != nil {
  548. return fmt.Errorf("git read-tree --index-output=%s %s: %v - %s", indexTmpPath, pr.BaseBranch, err, stderr)
  549. }
  550. prUnit, err := pr.BaseRepo.getUnit(e, UnitTypePullRequests)
  551. if err != nil {
  552. return err
  553. }
  554. prConfig := prUnit.PullRequestsConfig()
  555. args := []string{"apply", "--check", "--cached"}
  556. if prConfig.IgnoreWhitespaceConflicts {
  557. args = append(args, "--ignore-whitespace")
  558. }
  559. args = append(args, patchPath)
  560. pr.ConflictedFiles = []string{}
  561. _, stderr, err = process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("testPatch (git apply --check): %d", pr.BaseRepo.ID),
  562. []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()},
  563. git.GitExecutable, args...)
  564. if err != nil {
  565. for i := range patchConflicts {
  566. if strings.Contains(stderr, patchConflicts[i]) {
  567. log.Trace("PullRequest[%d].testPatch (apply): has conflict: %s", pr.ID, stderr)
  568. const prefix = "error: patch failed:"
  569. pr.Status = PullRequestStatusConflict
  570. pr.ConflictedFiles = make([]string, 0, 5)
  571. scanner := bufio.NewScanner(strings.NewReader(stderr))
  572. for scanner.Scan() {
  573. line := scanner.Text()
  574. if strings.HasPrefix(line, prefix) {
  575. var found bool
  576. var filepath = strings.TrimSpace(strings.Split(line[len(prefix):], ":")[0])
  577. for _, f := range pr.ConflictedFiles {
  578. if f == filepath {
  579. found = true
  580. break
  581. }
  582. }
  583. if !found {
  584. pr.ConflictedFiles = append(pr.ConflictedFiles, filepath)
  585. }
  586. }
  587. // only list 10 conflicted files
  588. if len(pr.ConflictedFiles) >= 10 {
  589. break
  590. }
  591. }
  592. if len(pr.ConflictedFiles) > 0 {
  593. log.Trace("Found %d files conflicted: %v", len(pr.ConflictedFiles), pr.ConflictedFiles)
  594. }
  595. return nil
  596. }
  597. }
  598. return fmt.Errorf("git apply --check: %v - %s", err, stderr)
  599. }
  600. return nil
  601. }
  602. // NewPullRequest creates new pull request with labels for repository.
  603. func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest, patch []byte, assigneeIDs []int64) (err error) {
  604. // Retry several times in case INSERT fails due to duplicate key for (repo_id, index); see #7887
  605. i := 0
  606. for {
  607. if err = newPullRequestAttempt(repo, pull, labelIDs, uuids, pr, patch, assigneeIDs); err == nil {
  608. return nil
  609. }
  610. if !IsErrNewIssueInsert(err) {
  611. return err
  612. }
  613. if i++; i == issueMaxDupIndexAttempts {
  614. break
  615. }
  616. log.Error("NewPullRequest: error attempting to insert the new issue; will retry. Original error: %v", err)
  617. }
  618. return fmt.Errorf("NewPullRequest: too many errors attempting to insert the new issue. Last error was: %v", err)
  619. }
  620. func newPullRequestAttempt(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest, patch []byte, assigneeIDs []int64) (err error) {
  621. sess := x.NewSession()
  622. defer sess.Close()
  623. if err = sess.Begin(); err != nil {
  624. return err
  625. }
  626. if err = newIssue(sess, pull.Poster, NewIssueOptions{
  627. Repo: repo,
  628. Issue: pull,
  629. LabelIDs: labelIDs,
  630. Attachments: uuids,
  631. IsPull: true,
  632. AssigneeIDs: assigneeIDs,
  633. }); err != nil {
  634. if IsErrUserDoesNotHaveAccessToRepo(err) || IsErrNewIssueInsert(err) {
  635. return err
  636. }
  637. return fmt.Errorf("newIssue: %v", err)
  638. }
  639. pr.Index = pull.Index
  640. pr.BaseRepo = repo
  641. pr.Status = PullRequestStatusChecking
  642. if len(patch) > 0 {
  643. if err = repo.savePatch(sess, pr.Index, patch); err != nil {
  644. return fmt.Errorf("SavePatch: %v", err)
  645. }
  646. if err = pr.testPatch(sess); err != nil {
  647. return fmt.Errorf("testPatch: %v", err)
  648. }
  649. }
  650. // No conflict appears after test means mergeable.
  651. if pr.Status == PullRequestStatusChecking {
  652. pr.Status = PullRequestStatusMergeable
  653. }
  654. pr.IssueID = pull.ID
  655. if _, err = sess.Insert(pr); err != nil {
  656. return fmt.Errorf("insert pull repo: %v", err)
  657. }
  658. if err = sess.Commit(); err != nil {
  659. return fmt.Errorf("Commit: %v", err)
  660. }
  661. return nil
  662. }
  663. // PullRequestsOptions holds the options for PRs
  664. type PullRequestsOptions struct {
  665. Page int
  666. State string
  667. SortType string
  668. Labels []string
  669. MilestoneID int64
  670. }
  671. func listPullRequestStatement(baseRepoID int64, opts *PullRequestsOptions) (*xorm.Session, error) {
  672. sess := x.Where("pull_request.base_repo_id=?", baseRepoID)
  673. sess.Join("INNER", "issue", "pull_request.issue_id = issue.id")
  674. switch opts.State {
  675. case "closed", "open":
  676. sess.And("issue.is_closed=?", opts.State == "closed")
  677. }
  678. if labelIDs, err := base.StringsToInt64s(opts.Labels); err != nil {
  679. return nil, err
  680. } else if len(labelIDs) > 0 {
  681. sess.Join("INNER", "issue_label", "issue.id = issue_label.issue_id").
  682. In("issue_label.label_id", labelIDs)
  683. }
  684. if opts.MilestoneID > 0 {
  685. sess.And("issue.milestone_id=?", opts.MilestoneID)
  686. }
  687. return sess, nil
  688. }
  689. // PullRequests returns all pull requests for a base Repo by the given conditions
  690. func PullRequests(baseRepoID int64, opts *PullRequestsOptions) ([]*PullRequest, int64, error) {
  691. if opts.Page <= 0 {
  692. opts.Page = 1
  693. }
  694. countSession, err := listPullRequestStatement(baseRepoID, opts)
  695. if err != nil {
  696. log.Error("listPullRequestStatement: %v", err)
  697. return nil, 0, err
  698. }
  699. maxResults, err := countSession.Count(new(PullRequest))
  700. if err != nil {
  701. log.Error("Count PRs: %v", err)
  702. return nil, maxResults, err
  703. }
  704. prs := make([]*PullRequest, 0, ItemsPerPage)
  705. findSession, err := listPullRequestStatement(baseRepoID, opts)
  706. sortIssuesSession(findSession, opts.SortType)
  707. if err != nil {
  708. log.Error("listPullRequestStatement: %v", err)
  709. return nil, maxResults, err
  710. }
  711. findSession.Limit(ItemsPerPage, (opts.Page-1)*ItemsPerPage)
  712. return prs, maxResults, findSession.Find(&prs)
  713. }
  714. // GetUnmergedPullRequest returns a pull request that is open and has not been merged
  715. // by given head/base and repo/branch.
  716. func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string) (*PullRequest, error) {
  717. pr := new(PullRequest)
  718. has, err := x.
  719. Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  720. headRepoID, headBranch, baseRepoID, baseBranch, false, false).
  721. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  722. Get(pr)
  723. if err != nil {
  724. return nil, err
  725. } else if !has {
  726. return nil, ErrPullRequestNotExist{0, 0, headRepoID, baseRepoID, headBranch, baseBranch}
  727. }
  728. return pr, nil
  729. }
  730. // GetUnmergedPullRequestsByHeadInfo returns all pull requests that are open and has not been merged
  731. // by given head information (repo and branch).
  732. func GetUnmergedPullRequestsByHeadInfo(repoID int64, branch string) ([]*PullRequest, error) {
  733. prs := make([]*PullRequest, 0, 2)
  734. return prs, x.
  735. Where("head_repo_id = ? AND head_branch = ? AND has_merged = ? AND issue.is_closed = ?",
  736. repoID, branch, false, false).
  737. Join("INNER", "issue", "issue.id = pull_request.issue_id").
  738. Find(&prs)
  739. }
  740. // GetLatestPullRequestByHeadInfo returns the latest pull request (regardless of its status)
  741. // by given head information (repo and branch).
  742. func GetLatestPullRequestByHeadInfo(repoID int64, branch string) (*PullRequest, error) {
  743. pr := new(PullRequest)
  744. has, err := x.
  745. Where("head_repo_id = ? AND head_branch = ?", repoID, branch).
  746. OrderBy("id DESC").
  747. Get(pr)
  748. if !has {
  749. return nil, err
  750. }
  751. return pr, err
  752. }
  753. // GetUnmergedPullRequestsByBaseInfo returns all pull requests that are open and has not been merged
  754. // by given base information (repo and branch).
  755. func GetUnmergedPullRequestsByBaseInfo(repoID int64, branch string) ([]*PullRequest, error) {
  756. prs := make([]*PullRequest, 0, 2)
  757. return prs, x.
  758. Where("base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  759. repoID, branch, false, false).
  760. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  761. Find(&prs)
  762. }
  763. // GetPullRequestByIndex returns a pull request by the given index
  764. func GetPullRequestByIndex(repoID int64, index int64) (*PullRequest, error) {
  765. pr := &PullRequest{
  766. BaseRepoID: repoID,
  767. Index: index,
  768. }
  769. has, err := x.Get(pr)
  770. if err != nil {
  771. return nil, err
  772. } else if !has {
  773. return nil, ErrPullRequestNotExist{0, 0, 0, repoID, "", ""}
  774. }
  775. if err = pr.LoadAttributes(); err != nil {
  776. return nil, err
  777. }
  778. if err = pr.LoadIssue(); err != nil {
  779. return nil, err
  780. }
  781. return pr, nil
  782. }
  783. func getPullRequestByID(e Engine, id int64) (*PullRequest, error) {
  784. pr := new(PullRequest)
  785. has, err := e.ID(id).Get(pr)
  786. if err != nil {
  787. return nil, err
  788. } else if !has {
  789. return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""}
  790. }
  791. return pr, pr.loadAttributes(e)
  792. }
  793. // GetPullRequestByID returns a pull request by given ID.
  794. func GetPullRequestByID(id int64) (*PullRequest, error) {
  795. return getPullRequestByID(x, id)
  796. }
  797. func getPullRequestByIssueID(e Engine, issueID int64) (*PullRequest, error) {
  798. pr := &PullRequest{
  799. IssueID: issueID,
  800. }
  801. has, err := e.Get(pr)
  802. if err != nil {
  803. return nil, err
  804. } else if !has {
  805. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  806. }
  807. return pr, pr.loadAttributes(e)
  808. }
  809. // GetPullRequestByIssueID returns pull request by given issue ID.
  810. func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) {
  811. return getPullRequestByIssueID(x, issueID)
  812. }
  813. // Update updates all fields of pull request.
  814. func (pr *PullRequest) Update() error {
  815. _, err := x.ID(pr.ID).AllCols().Update(pr)
  816. return err
  817. }
  818. // UpdateCols updates specific fields of pull request.
  819. func (pr *PullRequest) UpdateCols(cols ...string) error {
  820. _, err := x.ID(pr.ID).Cols(cols...).Update(pr)
  821. return err
  822. }
  823. // UpdatePatch generates and saves a new patch.
  824. func (pr *PullRequest) UpdatePatch() (err error) {
  825. if err = pr.GetHeadRepo(); err != nil {
  826. return fmt.Errorf("GetHeadRepo: %v", err)
  827. } else if pr.HeadRepo == nil {
  828. log.Trace("PullRequest[%d].UpdatePatch: ignored corrupted data", pr.ID)
  829. return nil
  830. }
  831. if err = pr.GetBaseRepo(); err != nil {
  832. return fmt.Errorf("GetBaseRepo: %v", err)
  833. }
  834. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  835. if err != nil {
  836. return fmt.Errorf("OpenRepository: %v", err)
  837. }
  838. defer headGitRepo.Close()
  839. // Add a temporary remote.
  840. tmpRemote := com.ToStr(time.Now().UnixNano())
  841. if err = headGitRepo.AddRemote(tmpRemote, RepoPath(pr.BaseRepo.MustOwner().Name, pr.BaseRepo.Name), true); err != nil {
  842. return fmt.Errorf("AddRemote: %v", err)
  843. }
  844. defer func() {
  845. if err := headGitRepo.RemoveRemote(tmpRemote); err != nil {
  846. log.Error("UpdatePatch: RemoveRemote: %s", err)
  847. }
  848. }()
  849. pr.MergeBase, _, err = headGitRepo.GetMergeBase(tmpRemote, pr.BaseBranch, pr.HeadBranch)
  850. if err != nil {
  851. return fmt.Errorf("GetMergeBase: %v", err)
  852. } else if err = pr.Update(); err != nil {
  853. return fmt.Errorf("Update: %v", err)
  854. }
  855. patch, err := headGitRepo.GetPatch(pr.MergeBase, pr.HeadBranch)
  856. if err != nil {
  857. return fmt.Errorf("GetPatch: %v", err)
  858. }
  859. if err = pr.BaseRepo.SavePatch(pr.Index, patch); err != nil {
  860. return fmt.Errorf("BaseRepo.SavePatch: %v", err)
  861. }
  862. return nil
  863. }
  864. // PushToBaseRepo pushes commits from branches of head repository to
  865. // corresponding branches of base repository.
  866. // FIXME: Only push branches that are actually updates?
  867. func (pr *PullRequest) PushToBaseRepo() (err error) {
  868. log.Trace("PushToBaseRepo[%d]: pushing commits to base repo '%s'", pr.BaseRepoID, pr.GetGitRefName())
  869. headRepoPath := pr.HeadRepo.RepoPath()
  870. headGitRepo, err := git.OpenRepository(headRepoPath)
  871. if err != nil {
  872. return fmt.Errorf("OpenRepository: %v", err)
  873. }
  874. defer headGitRepo.Close()
  875. tmpRemoteName := fmt.Sprintf("tmp-pull-%d", pr.ID)
  876. if err = headGitRepo.AddRemote(tmpRemoteName, pr.BaseRepo.RepoPath(), false); err != nil {
  877. return fmt.Errorf("headGitRepo.AddRemote: %v", err)
  878. }
  879. // Make sure to remove the remote even if the push fails
  880. defer func() {
  881. if err := headGitRepo.RemoveRemote(tmpRemoteName); err != nil {
  882. log.Error("PushToBaseRepo: RemoveRemote: %s", err)
  883. }
  884. }()
  885. headFile := pr.GetGitRefName()
  886. // Remove head in case there is a conflict.
  887. file := path.Join(pr.BaseRepo.RepoPath(), headFile)
  888. _ = os.Remove(file)
  889. if err = git.Push(headRepoPath, git.PushOptions{
  890. Remote: tmpRemoteName,
  891. Branch: fmt.Sprintf("%s:%s", pr.HeadBranch, headFile),
  892. Force: true,
  893. }); err != nil {
  894. return fmt.Errorf("Push: %v", err)
  895. }
  896. return nil
  897. }
  898. // AddToTaskQueue adds itself to pull request test task queue.
  899. func (pr *PullRequest) AddToTaskQueue() {
  900. go pullRequestQueue.AddFunc(pr.ID, func() {
  901. pr.Status = PullRequestStatusChecking
  902. if err := pr.UpdateCols("status"); err != nil {
  903. log.Error("AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
  904. }
  905. })
  906. }
  907. // PullRequestList defines a list of pull requests
  908. type PullRequestList []*PullRequest
  909. func (prs PullRequestList) loadAttributes(e Engine) error {
  910. if len(prs) == 0 {
  911. return nil
  912. }
  913. // Load issues.
  914. issueIDs := prs.getIssueIDs()
  915. issues := make([]*Issue, 0, len(issueIDs))
  916. if err := e.
  917. Where("id > 0").
  918. In("id", issueIDs).
  919. Find(&issues); err != nil {
  920. return fmt.Errorf("find issues: %v", err)
  921. }
  922. set := make(map[int64]*Issue)
  923. for i := range issues {
  924. set[issues[i].ID] = issues[i]
  925. }
  926. for i := range prs {
  927. prs[i].Issue = set[prs[i].IssueID]
  928. }
  929. return nil
  930. }
  931. func (prs PullRequestList) getIssueIDs() []int64 {
  932. issueIDs := make([]int64, 0, len(prs))
  933. for i := range prs {
  934. issueIDs = append(issueIDs, prs[i].IssueID)
  935. }
  936. return issueIDs
  937. }
  938. // LoadAttributes load all the prs attributes
  939. func (prs PullRequestList) LoadAttributes() error {
  940. return prs.loadAttributes(x)
  941. }
  942. func (prs PullRequestList) invalidateCodeComments(e Engine, doer *User, repo *git.Repository, branch string) error {
  943. if len(prs) == 0 {
  944. return nil
  945. }
  946. issueIDs := prs.getIssueIDs()
  947. var codeComments []*Comment
  948. if err := e.
  949. Where("type = ? and invalidated = ?", CommentTypeCode, false).
  950. In("issue_id", issueIDs).
  951. Find(&codeComments); err != nil {
  952. return fmt.Errorf("find code comments: %v", err)
  953. }
  954. for _, comment := range codeComments {
  955. if err := comment.CheckInvalidation(repo, doer, branch); err != nil {
  956. return err
  957. }
  958. }
  959. return nil
  960. }
  961. // InvalidateCodeComments will lookup the prs for code comments which got invalidated by change
  962. func (prs PullRequestList) InvalidateCodeComments(doer *User, repo *git.Repository, branch string) error {
  963. return prs.invalidateCodeComments(x, doer, repo, branch)
  964. }
  965. func addHeadRepoTasks(prs []*PullRequest) {
  966. for _, pr := range prs {
  967. log.Trace("addHeadRepoTasks[%d]: composing new test task", pr.ID)
  968. if err := pr.UpdatePatch(); err != nil {
  969. log.Error("UpdatePatch: %v", err)
  970. continue
  971. } else if err := pr.PushToBaseRepo(); err != nil {
  972. log.Error("PushToBaseRepo: %v", err)
  973. continue
  974. }
  975. pr.AddToTaskQueue()
  976. }
  977. }
  978. // AddTestPullRequestTask adds new test tasks by given head/base repository and head/base branch,
  979. // and generate new patch for testing as needed.
  980. func AddTestPullRequestTask(doer *User, repoID int64, branch string, isSync bool) {
  981. log.Trace("AddTestPullRequestTask [head_repo_id: %d, head_branch: %s]: finding pull requests", repoID, branch)
  982. prs, err := GetUnmergedPullRequestsByHeadInfo(repoID, branch)
  983. if err != nil {
  984. log.Error("Find pull requests [head_repo_id: %d, head_branch: %s]: %v", repoID, branch, err)
  985. return
  986. }
  987. if isSync {
  988. requests := PullRequestList(prs)
  989. if err = requests.LoadAttributes(); err != nil {
  990. log.Error("PullRequestList.LoadAttributes: %v", err)
  991. }
  992. if invalidationErr := checkForInvalidation(requests, repoID, doer, branch); invalidationErr != nil {
  993. log.Error("checkForInvalidation: %v", invalidationErr)
  994. }
  995. if err == nil {
  996. for _, pr := range prs {
  997. pr.Issue.PullRequest = pr
  998. if err = pr.Issue.LoadAttributes(); err != nil {
  999. log.Error("LoadAttributes: %v", err)
  1000. continue
  1001. }
  1002. if err = PrepareWebhooks(pr.Issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  1003. Action: api.HookIssueSynchronized,
  1004. Index: pr.Issue.Index,
  1005. PullRequest: pr.Issue.PullRequest.APIFormat(),
  1006. Repository: pr.Issue.Repo.APIFormat(AccessModeNone),
  1007. Sender: doer.APIFormat(),
  1008. }); err != nil {
  1009. log.Error("PrepareWebhooks [pull_id: %v]: %v", pr.ID, err)
  1010. continue
  1011. }
  1012. go HookQueue.Add(pr.Issue.Repo.ID)
  1013. }
  1014. }
  1015. }
  1016. addHeadRepoTasks(prs)
  1017. log.Trace("AddTestPullRequestTask [base_repo_id: %d, base_branch: %s]: finding pull requests", repoID, branch)
  1018. prs, err = GetUnmergedPullRequestsByBaseInfo(repoID, branch)
  1019. if err != nil {
  1020. log.Error("Find pull requests [base_repo_id: %d, base_branch: %s]: %v", repoID, branch, err)
  1021. return
  1022. }
  1023. for _, pr := range prs {
  1024. pr.AddToTaskQueue()
  1025. }
  1026. }
  1027. func checkForInvalidation(requests PullRequestList, repoID int64, doer *User, branch string) error {
  1028. repo, err := GetRepositoryByID(repoID)
  1029. if err != nil {
  1030. return fmt.Errorf("GetRepositoryByID: %v", err)
  1031. }
  1032. gitRepo, err := git.OpenRepository(repo.RepoPath())
  1033. if err != nil {
  1034. return fmt.Errorf("git.OpenRepository: %v", err)
  1035. }
  1036. go func() {
  1037. err := requests.InvalidateCodeComments(doer, gitRepo, branch)
  1038. if err != nil {
  1039. log.Error("PullRequestList.InvalidateCodeComments: %v", err)
  1040. }
  1041. gitRepo.Close()
  1042. }()
  1043. return nil
  1044. }
  1045. // checkAndUpdateStatus checks if pull request is possible to leaving checking status,
  1046. // and set to be either conflict or mergeable.
  1047. func (pr *PullRequest) checkAndUpdateStatus() {
  1048. // Status is not changed to conflict means mergeable.
  1049. if pr.Status == PullRequestStatusChecking {
  1050. pr.Status = PullRequestStatusMergeable
  1051. }
  1052. // Make sure there is no waiting test to process before leaving the checking status.
  1053. if !pullRequestQueue.Exist(pr.ID) {
  1054. if err := pr.UpdateCols("status, conflicted_files"); err != nil {
  1055. log.Error("Update[%d]: %v", pr.ID, err)
  1056. }
  1057. }
  1058. }
  1059. // IsWorkInProgress determine if the Pull Request is a Work In Progress by its title
  1060. func (pr *PullRequest) IsWorkInProgress() bool {
  1061. if err := pr.LoadIssue(); err != nil {
  1062. log.Error("LoadIssue: %v", err)
  1063. return false
  1064. }
  1065. for _, prefix := range setting.Repository.PullRequest.WorkInProgressPrefixes {
  1066. if strings.HasPrefix(strings.ToUpper(pr.Issue.Title), prefix) {
  1067. return true
  1068. }
  1069. }
  1070. return false
  1071. }
  1072. // IsFilesConflicted determines if the Pull Request has changes conflicting with the target branch.
  1073. func (pr *PullRequest) IsFilesConflicted() bool {
  1074. return len(pr.ConflictedFiles) > 0
  1075. }
  1076. // GetWorkInProgressPrefix returns the prefix used to mark the pull request as a work in progress.
  1077. // It returns an empty string when none were found
  1078. func (pr *PullRequest) GetWorkInProgressPrefix() string {
  1079. if err := pr.LoadIssue(); err != nil {
  1080. log.Error("LoadIssue: %v", err)
  1081. return ""
  1082. }
  1083. for _, prefix := range setting.Repository.PullRequest.WorkInProgressPrefixes {
  1084. if strings.HasPrefix(strings.ToUpper(pr.Issue.Title), prefix) {
  1085. return pr.Issue.Title[0:len(prefix)]
  1086. }
  1087. }
  1088. return ""
  1089. }
  1090. // TestPullRequests checks and tests untested patches of pull requests.
  1091. // TODO: test more pull requests at same time.
  1092. func TestPullRequests() {
  1093. prs := make([]*PullRequest, 0, 10)
  1094. err := x.Where("status = ?", PullRequestStatusChecking).Find(&prs)
  1095. if err != nil {
  1096. log.Error("Find Checking PRs: %v", err)
  1097. return
  1098. }
  1099. var checkedPRs = make(map[int64]struct{})
  1100. // Update pull request status.
  1101. for _, pr := range prs {
  1102. checkedPRs[pr.ID] = struct{}{}
  1103. if err := pr.GetBaseRepo(); err != nil {
  1104. log.Error("GetBaseRepo: %v", err)
  1105. continue
  1106. }
  1107. if pr.manuallyMerged() {
  1108. continue
  1109. }
  1110. if err := pr.testPatch(x); err != nil {
  1111. log.Error("testPatch: %v", err)
  1112. continue
  1113. }
  1114. pr.checkAndUpdateStatus()
  1115. }
  1116. // Start listening on new test requests.
  1117. for prID := range pullRequestQueue.Queue() {
  1118. log.Trace("TestPullRequests[%v]: processing test task", prID)
  1119. pullRequestQueue.Remove(prID)
  1120. id := com.StrTo(prID).MustInt64()
  1121. if _, ok := checkedPRs[id]; ok {
  1122. continue
  1123. }
  1124. pr, err := GetPullRequestByID(id)
  1125. if err != nil {
  1126. log.Error("GetPullRequestByID[%s]: %v", prID, err)
  1127. continue
  1128. } else if pr.manuallyMerged() {
  1129. continue
  1130. } else if err = pr.testPatch(x); err != nil {
  1131. log.Error("testPatch[%d]: %v", pr.ID, err)
  1132. continue
  1133. }
  1134. pr.checkAndUpdateStatus()
  1135. }
  1136. }
  1137. // InitTestPullRequests runs the task to test all the checking status pull requests
  1138. func InitTestPullRequests() {
  1139. go TestPullRequests()
  1140. }