You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

pull.go 37 kB

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