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

pull.go 37KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245
  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. Deadline: apiIssue.Deadline,
  188. Created: pr.Issue.CreatedUnix.AsTimePtr(),
  189. Updated: pr.Issue.UpdatedUnix.AsTimePtr(),
  190. }
  191. if pr.Status != PullRequestStatusChecking {
  192. mergeable := pr.Status != PullRequestStatusConflict
  193. apiPullRequest.Mergeable = mergeable
  194. }
  195. if pr.HasMerged {
  196. apiPullRequest.Merged = pr.MergedUnix.AsTimePtr()
  197. apiPullRequest.MergedCommitID = &pr.MergedCommitID
  198. apiPullRequest.MergedBy = pr.Merger.APIFormat()
  199. }
  200. return apiPullRequest
  201. }
  202. func (pr *PullRequest) getHeadRepo(e Engine) (err error) {
  203. pr.HeadRepo, err = getRepositoryByID(e, pr.HeadRepoID)
  204. if err != nil && !IsErrRepoNotExist(err) {
  205. return fmt.Errorf("getRepositoryByID(head): %v", err)
  206. }
  207. return nil
  208. }
  209. // GetHeadRepo loads the head repository
  210. func (pr *PullRequest) GetHeadRepo() error {
  211. return pr.getHeadRepo(x)
  212. }
  213. // GetBaseRepo loads the target repository
  214. func (pr *PullRequest) GetBaseRepo() (err error) {
  215. if pr.BaseRepo != nil {
  216. return nil
  217. }
  218. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  219. if err != nil {
  220. return fmt.Errorf("GetRepositoryByID(base): %v", err)
  221. }
  222. return nil
  223. }
  224. // IsChecking returns true if this pull request is still checking conflict.
  225. func (pr *PullRequest) IsChecking() bool {
  226. return pr.Status == PullRequestStatusChecking
  227. }
  228. // CanAutoMerge returns true if this pull request can be merged automatically.
  229. func (pr *PullRequest) CanAutoMerge() bool {
  230. return pr.Status == PullRequestStatusMergeable
  231. }
  232. // MergeStyle represents the approach to merge commits into base branch.
  233. type MergeStyle string
  234. const (
  235. // MergeStyleMerge create merge commit
  236. MergeStyleMerge MergeStyle = "merge"
  237. // MergeStyleRebase rebase before merging
  238. MergeStyleRebase MergeStyle = "rebase"
  239. // MergeStyleSquash squash commits into single commit before merging
  240. MergeStyleSquash MergeStyle = "squash"
  241. )
  242. // CheckUserAllowedToMerge checks whether the user is allowed to merge
  243. func (pr *PullRequest) CheckUserAllowedToMerge(doer *User) (err error) {
  244. if doer == nil {
  245. return ErrNotAllowedToMerge{
  246. "Not signed in",
  247. }
  248. }
  249. if pr.BaseRepo == nil {
  250. if err = pr.GetBaseRepo(); err != nil {
  251. return fmt.Errorf("GetBaseRepo: %v", err)
  252. }
  253. }
  254. if protected, err := pr.BaseRepo.IsProtectedBranchForMerging(pr.BaseBranch, doer); err != nil {
  255. return fmt.Errorf("IsProtectedBranch: %v", err)
  256. } else if protected {
  257. return ErrNotAllowedToMerge{
  258. "The branch is protected",
  259. }
  260. }
  261. return nil
  262. }
  263. // Merge merges pull request to base repository.
  264. // FIXME: add repoWorkingPull make sure two merges does not happen at same time.
  265. func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository, mergeStyle MergeStyle, message string) (err error) {
  266. if err = pr.GetHeadRepo(); err != nil {
  267. return fmt.Errorf("GetHeadRepo: %v", err)
  268. } else if err = pr.GetBaseRepo(); err != nil {
  269. return fmt.Errorf("GetBaseRepo: %v", err)
  270. }
  271. prUnit, err := pr.BaseRepo.GetUnit(UnitTypePullRequests)
  272. if err != nil {
  273. return err
  274. }
  275. prConfig := prUnit.PullRequestsConfig()
  276. if err := pr.CheckUserAllowedToMerge(doer); err != nil {
  277. return fmt.Errorf("CheckUserAllowedToMerge: %v", err)
  278. }
  279. // Check if merge style is correct and allowed
  280. if !prConfig.IsMergeStyleAllowed(mergeStyle) {
  281. return ErrInvalidMergeStyle{pr.BaseRepo.ID, mergeStyle}
  282. }
  283. defer func() {
  284. go HookQueue.Add(pr.BaseRepo.ID)
  285. go AddTestPullRequestTask(doer, pr.BaseRepo.ID, pr.BaseBranch, false)
  286. }()
  287. headRepoPath := RepoPath(pr.HeadUserName, pr.HeadRepo.Name)
  288. // Clone base repo.
  289. tmpBasePath := path.Join(LocalCopyPath(), "merge-"+com.ToStr(time.Now().Nanosecond())+".git")
  290. if err := os.MkdirAll(path.Dir(tmpBasePath), os.ModePerm); err != nil {
  291. return fmt.Errorf("Failed to create dir %s: %v", tmpBasePath, err)
  292. }
  293. defer os.RemoveAll(path.Dir(tmpBasePath))
  294. var stderr string
  295. if _, stderr, err = process.GetManager().ExecTimeout(5*time.Minute,
  296. fmt.Sprintf("PullRequest.Merge (git clone): %s", tmpBasePath),
  297. "git", "clone", baseGitRepo.Path, tmpBasePath); err != nil {
  298. return fmt.Errorf("git clone: %s", stderr)
  299. }
  300. // Check out base branch.
  301. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  302. fmt.Sprintf("PullRequest.Merge (git checkout): %s", tmpBasePath),
  303. "git", "checkout", pr.BaseBranch); err != nil {
  304. return fmt.Errorf("git checkout: %s", stderr)
  305. }
  306. // Add head repo remote.
  307. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  308. fmt.Sprintf("PullRequest.Merge (git remote add): %s", tmpBasePath),
  309. "git", "remote", "add", "head_repo", headRepoPath); err != nil {
  310. return fmt.Errorf("git remote add [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  311. }
  312. // Merge commits.
  313. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  314. fmt.Sprintf("PullRequest.Merge (git fetch): %s", tmpBasePath),
  315. "git", "fetch", "head_repo"); err != nil {
  316. return fmt.Errorf("git fetch [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  317. }
  318. switch mergeStyle {
  319. case MergeStyleMerge:
  320. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  321. fmt.Sprintf("PullRequest.Merge (git merge --no-ff --no-commit): %s", tmpBasePath),
  322. "git", "merge", "--no-ff", "--no-commit", "head_repo/"+pr.HeadBranch); err != nil {
  323. return fmt.Errorf("git merge --no-ff --no-commit [%s]: %v - %s", tmpBasePath, err, stderr)
  324. }
  325. sig := doer.NewGitSig()
  326. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  327. fmt.Sprintf("PullRequest.Merge (git merge): %s", tmpBasePath),
  328. "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  329. "-m", message); err != nil {
  330. return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, stderr)
  331. }
  332. case MergeStyleRebase:
  333. // Checkout head branch
  334. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  335. fmt.Sprintf("PullRequest.Merge (git checkout): %s", tmpBasePath),
  336. "git", "checkout", "-b", "head_repo_"+pr.HeadBranch, "head_repo/"+pr.HeadBranch); err != nil {
  337. return fmt.Errorf("git checkout: %s", stderr)
  338. }
  339. // Rebase before merging
  340. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  341. fmt.Sprintf("PullRequest.Merge (git rebase): %s", tmpBasePath),
  342. "git", "rebase", "-q", pr.BaseBranch); err != nil {
  343. return fmt.Errorf("git rebase [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  344. }
  345. // Checkout base branch again
  346. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  347. fmt.Sprintf("PullRequest.Merge (git checkout): %s", tmpBasePath),
  348. "git", "checkout", pr.BaseBranch); err != nil {
  349. return fmt.Errorf("git checkout: %s", stderr)
  350. }
  351. // Merge fast forward
  352. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  353. fmt.Sprintf("PullRequest.Merge (git rebase): %s", tmpBasePath),
  354. "git", "merge", "--ff-only", "-q", "head_repo_"+pr.HeadBranch); err != nil {
  355. return fmt.Errorf("git merge --ff-only [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  356. }
  357. case MergeStyleSquash:
  358. // Merge with squash
  359. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  360. fmt.Sprintf("PullRequest.Merge (git squash): %s", tmpBasePath),
  361. "git", "merge", "-q", "--squash", "head_repo/"+pr.HeadBranch); err != nil {
  362. return fmt.Errorf("git merge --squash [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  363. }
  364. sig := pr.Issue.Poster.NewGitSig()
  365. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  366. fmt.Sprintf("PullRequest.Merge (git squash): %s", tmpBasePath),
  367. "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  368. "-m", message); err != nil {
  369. return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, stderr)
  370. }
  371. default:
  372. return ErrInvalidMergeStyle{pr.BaseRepo.ID, mergeStyle}
  373. }
  374. // Push back to upstream.
  375. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  376. fmt.Sprintf("PullRequest.Merge (git push): %s", tmpBasePath),
  377. "git", "push", baseGitRepo.Path, pr.BaseBranch); err != nil {
  378. return fmt.Errorf("git push: %s", stderr)
  379. }
  380. pr.MergedCommitID, err = baseGitRepo.GetBranchCommitID(pr.BaseBranch)
  381. if err != nil {
  382. return fmt.Errorf("GetBranchCommit: %v", err)
  383. }
  384. pr.MergedUnix = util.TimeStampNow()
  385. pr.Merger = doer
  386. pr.MergerID = doer.ID
  387. if err = pr.setMerged(); err != nil {
  388. log.Error(4, "setMerged [%d]: %v", pr.ID, err)
  389. }
  390. if err = MergePullRequestAction(doer, pr.Issue.Repo, pr.Issue); err != nil {
  391. log.Error(4, "MergePullRequestAction [%d]: %v", pr.ID, err)
  392. }
  393. // Reset cached commit count
  394. cache.Remove(pr.Issue.Repo.GetCommitsCountCacheKey(pr.BaseBranch, true))
  395. // Reload pull request information.
  396. if err = pr.LoadAttributes(); err != nil {
  397. log.Error(4, "LoadAttributes: %v", err)
  398. return nil
  399. }
  400. if err = PrepareWebhooks(pr.Issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  401. Action: api.HookIssueClosed,
  402. Index: pr.Index,
  403. PullRequest: pr.APIFormat(),
  404. Repository: pr.Issue.Repo.APIFormat(AccessModeNone),
  405. Sender: doer.APIFormat(),
  406. }); err != nil {
  407. log.Error(4, "PrepareWebhooks: %v", err)
  408. return nil
  409. }
  410. l, err := baseGitRepo.CommitsBetweenIDs(pr.MergedCommitID, pr.MergeBase)
  411. if err != nil {
  412. log.Error(4, "CommitsBetweenIDs: %v", err)
  413. return nil
  414. }
  415. // It is possible that head branch is not fully sync with base branch for merge commits,
  416. // so we need to get latest head commit and append merge commit manually
  417. // to avoid strange diff commits produced.
  418. mergeCommit, err := baseGitRepo.GetBranchCommit(pr.BaseBranch)
  419. if err != nil {
  420. log.Error(4, "GetBranchCommit: %v", err)
  421. return nil
  422. }
  423. if mergeStyle == MergeStyleMerge {
  424. l.PushFront(mergeCommit)
  425. }
  426. p := &api.PushPayload{
  427. Ref: git.BranchPrefix + pr.BaseBranch,
  428. Before: pr.MergeBase,
  429. After: mergeCommit.ID.String(),
  430. CompareURL: setting.AppURL + pr.BaseRepo.ComposeCompareURL(pr.MergeBase, pr.MergedCommitID),
  431. Commits: ListToPushCommits(l).ToAPIPayloadCommits(pr.BaseRepo.HTMLURL()),
  432. Repo: pr.BaseRepo.APIFormat(AccessModeNone),
  433. Pusher: pr.HeadRepo.MustOwner().APIFormat(),
  434. Sender: doer.APIFormat(),
  435. }
  436. if err = PrepareWebhooks(pr.BaseRepo, HookEventPush, p); err != nil {
  437. return fmt.Errorf("PrepareWebhooks: %v", err)
  438. }
  439. return nil
  440. }
  441. // setMerged sets a pull request to merged and closes the corresponding issue
  442. func (pr *PullRequest) setMerged() (err error) {
  443. if pr.HasMerged {
  444. return fmt.Errorf("PullRequest[%d] already merged", pr.Index)
  445. }
  446. if pr.MergedCommitID == "" || pr.MergedUnix == 0 || pr.Merger == nil {
  447. return fmt.Errorf("Unable to merge PullRequest[%d], some required fields are empty", pr.Index)
  448. }
  449. pr.HasMerged = true
  450. sess := x.NewSession()
  451. defer sess.Close()
  452. if err = sess.Begin(); err != nil {
  453. return err
  454. }
  455. if err = pr.loadIssue(sess); err != nil {
  456. return err
  457. }
  458. if err = pr.Issue.loadRepo(sess); err != nil {
  459. return err
  460. }
  461. if err = pr.Issue.Repo.getOwner(sess); err != nil {
  462. return err
  463. }
  464. if err = pr.Issue.changeStatus(sess, pr.Merger, pr.Issue.Repo, true); err != nil {
  465. return fmt.Errorf("Issue.changeStatus: %v", err)
  466. }
  467. if _, err = sess.ID(pr.ID).Cols("has_merged, status, merged_commit_id, merger_id, merged_unix").Update(pr); err != nil {
  468. return fmt.Errorf("update pull request: %v", err)
  469. }
  470. if err = sess.Commit(); err != nil {
  471. return fmt.Errorf("Commit: %v", err)
  472. }
  473. return nil
  474. }
  475. // manuallyMerged checks if a pull request got manually merged
  476. // When a pull request got manually merged mark the pull request as merged
  477. func (pr *PullRequest) manuallyMerged() bool {
  478. commit, err := pr.getMergeCommit()
  479. if err != nil {
  480. log.Error(4, "PullRequest[%d].getMergeCommit: %v", pr.ID, err)
  481. return false
  482. }
  483. if commit != nil {
  484. pr.MergedCommitID = commit.ID.String()
  485. pr.MergedUnix = util.TimeStamp(commit.Author.When.Unix())
  486. pr.Status = PullRequestStatusManuallyMerged
  487. merger, _ := GetUserByEmail(commit.Author.Email)
  488. // When the commit author is unknown set the BaseRepo owner as merger
  489. if merger == nil {
  490. if pr.BaseRepo.Owner == nil {
  491. if err = pr.BaseRepo.getOwner(x); err != nil {
  492. log.Error(4, "BaseRepo.getOwner[%d]: %v", pr.ID, err)
  493. return false
  494. }
  495. }
  496. merger = pr.BaseRepo.Owner
  497. }
  498. pr.Merger = merger
  499. pr.MergerID = merger.ID
  500. if err = pr.setMerged(); err != nil {
  501. log.Error(4, "PullRequest[%d].setMerged : %v", pr.ID, err)
  502. return false
  503. }
  504. 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())
  505. return true
  506. }
  507. return false
  508. }
  509. // getMergeCommit checks if a pull request got merged
  510. // Returns the git.Commit of the pull request if merged
  511. func (pr *PullRequest) getMergeCommit() (*git.Commit, error) {
  512. if pr.BaseRepo == nil {
  513. var err error
  514. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  515. if err != nil {
  516. return nil, fmt.Errorf("GetRepositoryByID: %v", err)
  517. }
  518. }
  519. indexTmpPath := filepath.Join(os.TempDir(), "gitea-"+pr.BaseRepo.Name+"-"+strconv.Itoa(time.Now().Nanosecond()))
  520. defer os.Remove(indexTmpPath)
  521. headFile := pr.GetGitRefName()
  522. // Check if a pull request is merged into BaseBranch
  523. _, stderr, err := process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("isMerged (git merge-base --is-ancestor): %d", pr.BaseRepo.ID),
  524. []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()},
  525. "git", "merge-base", "--is-ancestor", headFile, pr.BaseBranch)
  526. if err != nil {
  527. // Errors are signaled by a non-zero status that is not 1
  528. if strings.Contains(err.Error(), "exit status 1") {
  529. return nil, nil
  530. }
  531. return nil, fmt.Errorf("git merge-base --is-ancestor: %v %v", stderr, err)
  532. }
  533. commitIDBytes, err := ioutil.ReadFile(pr.BaseRepo.RepoPath() + "/" + headFile)
  534. if err != nil {
  535. return nil, fmt.Errorf("ReadFile(%s): %v", headFile, err)
  536. }
  537. commitID := string(commitIDBytes)
  538. if len(commitID) < 40 {
  539. return nil, fmt.Errorf(`ReadFile(%s): invalid commit-ID "%s"`, headFile, commitID)
  540. }
  541. cmd := commitID[:40] + ".." + pr.BaseBranch
  542. // Get the commit from BaseBranch where the pull request got merged
  543. mergeCommit, stderr, err := process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("isMerged (git rev-list --ancestry-path --merges --reverse): %d", pr.BaseRepo.ID),
  544. []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()},
  545. "git", "rev-list", "--ancestry-path", "--merges", "--reverse", cmd)
  546. if err != nil {
  547. return nil, fmt.Errorf("git rev-list --ancestry-path --merges --reverse: %v %v", stderr, err)
  548. } else if len(mergeCommit) < 40 {
  549. // PR was fast-forwarded, so just use last commit of PR
  550. mergeCommit = commitID[:40]
  551. }
  552. gitRepo, err := git.OpenRepository(pr.BaseRepo.RepoPath())
  553. if err != nil {
  554. return nil, fmt.Errorf("OpenRepository: %v", err)
  555. }
  556. commit, err := gitRepo.GetCommit(mergeCommit[:40])
  557. if err != nil {
  558. return nil, fmt.Errorf("GetCommit: %v", err)
  559. }
  560. return commit, nil
  561. }
  562. // patchConflicts is a list of conflict description from Git.
  563. var patchConflicts = []string{
  564. "patch does not apply",
  565. "already exists in working directory",
  566. "unrecognized input",
  567. "error:",
  568. }
  569. // testPatch checks if patch can be merged to base repository without conflict.
  570. func (pr *PullRequest) testPatch() (err error) {
  571. if pr.BaseRepo == nil {
  572. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  573. if err != nil {
  574. return fmt.Errorf("GetRepositoryByID: %v", err)
  575. }
  576. }
  577. patchPath, err := pr.BaseRepo.PatchPath(pr.Index)
  578. if err != nil {
  579. return fmt.Errorf("BaseRepo.PatchPath: %v", err)
  580. }
  581. // Fast fail if patch does not exist, this assumes data is corrupted.
  582. if !com.IsFile(patchPath) {
  583. log.Trace("PullRequest[%d].testPatch: ignored corrupted data", pr.ID)
  584. return nil
  585. }
  586. repoWorkingPool.CheckIn(com.ToStr(pr.BaseRepoID))
  587. defer repoWorkingPool.CheckOut(com.ToStr(pr.BaseRepoID))
  588. log.Trace("PullRequest[%d].testPatch (patchPath): %s", pr.ID, patchPath)
  589. pr.Status = PullRequestStatusChecking
  590. indexTmpPath := filepath.Join(os.TempDir(), "gitea-"+pr.BaseRepo.Name+"-"+strconv.Itoa(time.Now().Nanosecond()))
  591. defer os.Remove(indexTmpPath)
  592. var stderr string
  593. _, stderr, err = process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("testPatch (git read-tree): %d", pr.BaseRepo.ID),
  594. []string{"GIT_DIR=" + pr.BaseRepo.RepoPath(), "GIT_INDEX_FILE=" + indexTmpPath},
  595. "git", "read-tree", pr.BaseBranch)
  596. if err != nil {
  597. return fmt.Errorf("git read-tree --index-output=%s %s: %v - %s", indexTmpPath, pr.BaseBranch, err, stderr)
  598. }
  599. prUnit, err := pr.BaseRepo.GetUnit(UnitTypePullRequests)
  600. if err != nil {
  601. return err
  602. }
  603. prConfig := prUnit.PullRequestsConfig()
  604. args := []string{"apply", "--check", "--cached"}
  605. if prConfig.IgnoreWhitespaceConflicts {
  606. args = append(args, "--ignore-whitespace")
  607. }
  608. args = append(args, patchPath)
  609. _, stderr, err = process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("testPatch (git apply --check): %d", pr.BaseRepo.ID),
  610. []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()},
  611. "git", args...)
  612. if err != nil {
  613. for i := range patchConflicts {
  614. if strings.Contains(stderr, patchConflicts[i]) {
  615. log.Trace("PullRequest[%d].testPatch (apply): has conflict", pr.ID)
  616. fmt.Println(stderr)
  617. pr.Status = PullRequestStatusConflict
  618. return nil
  619. }
  620. }
  621. return fmt.Errorf("git apply --check: %v - %s", err, stderr)
  622. }
  623. return nil
  624. }
  625. // NewPullRequest creates new pull request with labels for repository.
  626. func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest, patch []byte) (err error) {
  627. sess := x.NewSession()
  628. defer sess.Close()
  629. if err = sess.Begin(); err != nil {
  630. return err
  631. }
  632. if err = newIssue(sess, pull.Poster, NewIssueOptions{
  633. Repo: repo,
  634. Issue: pull,
  635. LabelIDs: labelIDs,
  636. Attachments: uuids,
  637. IsPull: true,
  638. }); err != nil {
  639. return fmt.Errorf("newIssue: %v", err)
  640. }
  641. pr.Index = pull.Index
  642. if err = repo.SavePatch(pr.Index, patch); err != nil {
  643. return fmt.Errorf("SavePatch: %v", err)
  644. }
  645. pr.BaseRepo = repo
  646. if err = pr.testPatch(); err != nil {
  647. return fmt.Errorf("testPatch: %v", err)
  648. }
  649. // No conflict appears after test means mergeable.
  650. if pr.Status == PullRequestStatusChecking {
  651. pr.Status = PullRequestStatusMergeable
  652. }
  653. pr.IssueID = pull.ID
  654. if _, err = sess.Insert(pr); err != nil {
  655. return fmt.Errorf("insert pull repo: %v", err)
  656. }
  657. if err = sess.Commit(); err != nil {
  658. return fmt.Errorf("Commit: %v", err)
  659. }
  660. UpdateIssueIndexer(pull.ID)
  661. if err = NotifyWatchers(&Action{
  662. ActUserID: pull.Poster.ID,
  663. ActUser: pull.Poster,
  664. OpType: ActionCreatePullRequest,
  665. Content: fmt.Sprintf("%d|%s", pull.Index, pull.Title),
  666. RepoID: repo.ID,
  667. Repo: repo,
  668. IsPrivate: repo.IsPrivate,
  669. }); err != nil {
  670. log.Error(4, "NotifyWatchers: %v", err)
  671. } else if err = pull.MailParticipants(); err != nil {
  672. log.Error(4, "MailParticipants: %v", err)
  673. }
  674. pr.Issue = pull
  675. pull.PullRequest = pr
  676. if err = PrepareWebhooks(repo, HookEventPullRequest, &api.PullRequestPayload{
  677. Action: api.HookIssueOpened,
  678. Index: pull.Index,
  679. PullRequest: pr.APIFormat(),
  680. Repository: repo.APIFormat(AccessModeNone),
  681. Sender: pull.Poster.APIFormat(),
  682. }); err != nil {
  683. log.Error(4, "PrepareWebhooks: %v", err)
  684. }
  685. go HookQueue.Add(repo.ID)
  686. return nil
  687. }
  688. // PullRequestsOptions holds the options for PRs
  689. type PullRequestsOptions struct {
  690. Page int
  691. State string
  692. SortType string
  693. Labels []string
  694. MilestoneID int64
  695. }
  696. func listPullRequestStatement(baseRepoID int64, opts *PullRequestsOptions) (*xorm.Session, error) {
  697. sess := x.Where("pull_request.base_repo_id=?", baseRepoID)
  698. sess.Join("INNER", "issue", "pull_request.issue_id = issue.id")
  699. switch opts.State {
  700. case "closed", "open":
  701. sess.And("issue.is_closed=?", opts.State == "closed")
  702. }
  703. if labelIDs, err := base.StringsToInt64s(opts.Labels); err != nil {
  704. return nil, err
  705. } else if len(labelIDs) > 0 {
  706. sess.Join("INNER", "issue_label", "issue.id = issue_label.issue_id").
  707. In("issue_label.label_id", labelIDs)
  708. }
  709. if opts.MilestoneID > 0 {
  710. sess.And("issue.milestone_id=?", opts.MilestoneID)
  711. }
  712. return sess, nil
  713. }
  714. // PullRequests returns all pull requests for a base Repo by the given conditions
  715. func PullRequests(baseRepoID int64, opts *PullRequestsOptions) ([]*PullRequest, int64, error) {
  716. if opts.Page <= 0 {
  717. opts.Page = 1
  718. }
  719. countSession, err := listPullRequestStatement(baseRepoID, opts)
  720. if err != nil {
  721. log.Error(4, "listPullRequestStatement", err)
  722. return nil, 0, err
  723. }
  724. maxResults, err := countSession.Count(new(PullRequest))
  725. if err != nil {
  726. log.Error(4, "Count PRs", err)
  727. return nil, maxResults, err
  728. }
  729. prs := make([]*PullRequest, 0, ItemsPerPage)
  730. findSession, err := listPullRequestStatement(baseRepoID, opts)
  731. sortIssuesSession(findSession, opts.SortType)
  732. if err != nil {
  733. log.Error(4, "listPullRequestStatement", err)
  734. return nil, maxResults, err
  735. }
  736. findSession.Limit(ItemsPerPage, (opts.Page-1)*ItemsPerPage)
  737. return prs, maxResults, findSession.Find(&prs)
  738. }
  739. // GetUnmergedPullRequest returns a pull request that is open and has not been merged
  740. // by given head/base and repo/branch.
  741. func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string) (*PullRequest, error) {
  742. pr := new(PullRequest)
  743. has, err := x.
  744. Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  745. headRepoID, headBranch, baseRepoID, baseBranch, false, false).
  746. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  747. Get(pr)
  748. if err != nil {
  749. return nil, err
  750. } else if !has {
  751. return nil, ErrPullRequestNotExist{0, 0, headRepoID, baseRepoID, headBranch, baseBranch}
  752. }
  753. return pr, nil
  754. }
  755. // GetUnmergedPullRequestsByHeadInfo returns all pull requests that are open and has not been merged
  756. // by given head information (repo and branch).
  757. func GetUnmergedPullRequestsByHeadInfo(repoID int64, branch string) ([]*PullRequest, error) {
  758. prs := make([]*PullRequest, 0, 2)
  759. return prs, x.
  760. Where("head_repo_id = ? AND head_branch = ? AND has_merged = ? AND issue.is_closed = ?",
  761. repoID, branch, false, false).
  762. Join("INNER", "issue", "issue.id = pull_request.issue_id").
  763. Find(&prs)
  764. }
  765. // GetUnmergedPullRequestsByBaseInfo returns all pull requests that are open and has not been merged
  766. // by given base information (repo and branch).
  767. func GetUnmergedPullRequestsByBaseInfo(repoID int64, branch string) ([]*PullRequest, error) {
  768. prs := make([]*PullRequest, 0, 2)
  769. return prs, x.
  770. Where("base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  771. repoID, branch, false, false).
  772. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  773. Find(&prs)
  774. }
  775. // GetPullRequestByIndex returns a pull request by the given index
  776. func GetPullRequestByIndex(repoID int64, index int64) (*PullRequest, error) {
  777. pr := &PullRequest{
  778. BaseRepoID: repoID,
  779. Index: index,
  780. }
  781. has, err := x.Get(pr)
  782. if err != nil {
  783. return nil, err
  784. } else if !has {
  785. return nil, ErrPullRequestNotExist{0, 0, 0, repoID, "", ""}
  786. }
  787. if err = pr.LoadAttributes(); err != nil {
  788. return nil, err
  789. }
  790. if err = pr.LoadIssue(); err != nil {
  791. return nil, err
  792. }
  793. return pr, nil
  794. }
  795. func getPullRequestByID(e Engine, id int64) (*PullRequest, error) {
  796. pr := new(PullRequest)
  797. has, err := e.ID(id).Get(pr)
  798. if err != nil {
  799. return nil, err
  800. } else if !has {
  801. return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""}
  802. }
  803. return pr, pr.loadAttributes(e)
  804. }
  805. // GetPullRequestByID returns a pull request by given ID.
  806. func GetPullRequestByID(id int64) (*PullRequest, error) {
  807. return getPullRequestByID(x, id)
  808. }
  809. func getPullRequestByIssueID(e Engine, issueID int64) (*PullRequest, error) {
  810. pr := &PullRequest{
  811. IssueID: issueID,
  812. }
  813. has, err := e.Get(pr)
  814. if err != nil {
  815. return nil, err
  816. } else if !has {
  817. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  818. }
  819. return pr, pr.loadAttributes(e)
  820. }
  821. // GetPullRequestByIssueID returns pull request by given issue ID.
  822. func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) {
  823. return getPullRequestByIssueID(x, issueID)
  824. }
  825. // Update updates all fields of pull request.
  826. func (pr *PullRequest) Update() error {
  827. _, err := x.ID(pr.ID).AllCols().Update(pr)
  828. return err
  829. }
  830. // UpdateCols updates specific fields of pull request.
  831. func (pr *PullRequest) UpdateCols(cols ...string) error {
  832. _, err := x.ID(pr.ID).Cols(cols...).Update(pr)
  833. return err
  834. }
  835. // UpdatePatch generates and saves a new patch.
  836. func (pr *PullRequest) UpdatePatch() (err error) {
  837. if err = pr.GetHeadRepo(); err != nil {
  838. return fmt.Errorf("GetHeadRepo: %v", err)
  839. } else if pr.HeadRepo == nil {
  840. log.Trace("PullRequest[%d].UpdatePatch: ignored cruppted data", pr.ID)
  841. return nil
  842. }
  843. if err = pr.GetBaseRepo(); err != nil {
  844. return fmt.Errorf("GetBaseRepo: %v", err)
  845. }
  846. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  847. if err != nil {
  848. return fmt.Errorf("OpenRepository: %v", err)
  849. }
  850. // Add a temporary remote.
  851. tmpRemote := com.ToStr(time.Now().UnixNano())
  852. if err = headGitRepo.AddRemote(tmpRemote, RepoPath(pr.BaseRepo.MustOwner().Name, pr.BaseRepo.Name), true); err != nil {
  853. return fmt.Errorf("AddRemote: %v", err)
  854. }
  855. defer func() {
  856. headGitRepo.RemoveRemote(tmpRemote)
  857. }()
  858. remoteBranch := "remotes/" + tmpRemote + "/" + pr.BaseBranch
  859. pr.MergeBase, err = headGitRepo.GetMergeBase(remoteBranch, pr.HeadBranch)
  860. if err != nil {
  861. return fmt.Errorf("GetMergeBase: %v", err)
  862. } else if err = pr.Update(); err != nil {
  863. return fmt.Errorf("Update: %v", err)
  864. }
  865. patch, err := headGitRepo.GetPatch(pr.MergeBase, pr.HeadBranch)
  866. if err != nil {
  867. return fmt.Errorf("GetPatch: %v", err)
  868. }
  869. if err = pr.BaseRepo.SavePatch(pr.Index, patch); err != nil {
  870. return fmt.Errorf("BaseRepo.SavePatch: %v", err)
  871. }
  872. return nil
  873. }
  874. // PushToBaseRepo pushes commits from branches of head repository to
  875. // corresponding branches of base repository.
  876. // FIXME: Only push branches that are actually updates?
  877. func (pr *PullRequest) PushToBaseRepo() (err error) {
  878. log.Trace("PushToBaseRepo[%d]: pushing commits to base repo '%s'", pr.BaseRepoID, pr.GetGitRefName())
  879. headRepoPath := pr.HeadRepo.RepoPath()
  880. headGitRepo, err := git.OpenRepository(headRepoPath)
  881. if err != nil {
  882. return fmt.Errorf("OpenRepository: %v", err)
  883. }
  884. tmpRemoteName := fmt.Sprintf("tmp-pull-%d", pr.ID)
  885. if err = headGitRepo.AddRemote(tmpRemoteName, pr.BaseRepo.RepoPath(), false); err != nil {
  886. return fmt.Errorf("headGitRepo.AddRemote: %v", err)
  887. }
  888. // Make sure to remove the remote even if the push fails
  889. defer headGitRepo.RemoveRemote(tmpRemoteName)
  890. headFile := pr.GetGitRefName()
  891. // Remove head in case there is a conflict.
  892. file := path.Join(pr.BaseRepo.RepoPath(), headFile)
  893. _ = os.Remove(file)
  894. if err = git.Push(headRepoPath, git.PushOptions{
  895. Remote: tmpRemoteName,
  896. Branch: fmt.Sprintf("%s:%s", pr.HeadBranch, headFile),
  897. Force: true,
  898. }); err != nil {
  899. return fmt.Errorf("Push: %v", err)
  900. }
  901. return nil
  902. }
  903. // AddToTaskQueue adds itself to pull request test task queue.
  904. func (pr *PullRequest) AddToTaskQueue() {
  905. go pullRequestQueue.AddFunc(pr.ID, func() {
  906. pr.Status = PullRequestStatusChecking
  907. if err := pr.UpdateCols("status"); err != nil {
  908. log.Error(5, "AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
  909. }
  910. })
  911. }
  912. // PullRequestList defines a list of pull requests
  913. type PullRequestList []*PullRequest
  914. func (prs PullRequestList) loadAttributes(e Engine) error {
  915. if len(prs) == 0 {
  916. return nil
  917. }
  918. // Load issues.
  919. issueIDs := make([]int64, 0, len(prs))
  920. for i := range prs {
  921. issueIDs = append(issueIDs, prs[i].IssueID)
  922. }
  923. issues := make([]*Issue, 0, len(issueIDs))
  924. if err := e.
  925. Where("id > 0").
  926. In("id", issueIDs).
  927. Find(&issues); err != nil {
  928. return fmt.Errorf("find issues: %v", err)
  929. }
  930. set := make(map[int64]*Issue)
  931. for i := range issues {
  932. set[issues[i].ID] = issues[i]
  933. }
  934. for i := range prs {
  935. prs[i].Issue = set[prs[i].IssueID]
  936. }
  937. return nil
  938. }
  939. // LoadAttributes load all the prs attributes
  940. func (prs PullRequestList) LoadAttributes() error {
  941. return prs.loadAttributes(x)
  942. }
  943. func addHeadRepoTasks(prs []*PullRequest) {
  944. for _, pr := range prs {
  945. log.Trace("addHeadRepoTasks[%d]: composing new test task", pr.ID)
  946. if err := pr.UpdatePatch(); err != nil {
  947. log.Error(4, "UpdatePatch: %v", err)
  948. continue
  949. } else if err := pr.PushToBaseRepo(); err != nil {
  950. log.Error(4, "PushToBaseRepo: %v", err)
  951. continue
  952. }
  953. pr.AddToTaskQueue()
  954. }
  955. }
  956. // AddTestPullRequestTask adds new test tasks by given head/base repository and head/base branch,
  957. // and generate new patch for testing as needed.
  958. func AddTestPullRequestTask(doer *User, repoID int64, branch string, isSync bool) {
  959. log.Trace("AddTestPullRequestTask [head_repo_id: %d, head_branch: %s]: finding pull requests", repoID, branch)
  960. prs, err := GetUnmergedPullRequestsByHeadInfo(repoID, branch)
  961. if err != nil {
  962. log.Error(4, "Find pull requests [head_repo_id: %d, head_branch: %s]: %v", repoID, branch, err)
  963. return
  964. }
  965. if isSync {
  966. if err = PullRequestList(prs).LoadAttributes(); err != nil {
  967. log.Error(4, "PullRequestList.LoadAttributes: %v", err)
  968. }
  969. if err == nil {
  970. for _, pr := range prs {
  971. pr.Issue.PullRequest = pr
  972. if err = pr.Issue.LoadAttributes(); err != nil {
  973. log.Error(4, "LoadAttributes: %v", err)
  974. continue
  975. }
  976. if err = PrepareWebhooks(pr.Issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  977. Action: api.HookIssueSynchronized,
  978. Index: pr.Issue.Index,
  979. PullRequest: pr.Issue.PullRequest.APIFormat(),
  980. Repository: pr.Issue.Repo.APIFormat(AccessModeNone),
  981. Sender: doer.APIFormat(),
  982. }); err != nil {
  983. log.Error(4, "PrepareWebhooks [pull_id: %v]: %v", pr.ID, err)
  984. continue
  985. }
  986. go HookQueue.Add(pr.Issue.Repo.ID)
  987. }
  988. }
  989. }
  990. addHeadRepoTasks(prs)
  991. log.Trace("AddTestPullRequestTask [base_repo_id: %d, base_branch: %s]: finding pull requests", repoID, branch)
  992. prs, err = GetUnmergedPullRequestsByBaseInfo(repoID, branch)
  993. if err != nil {
  994. log.Error(4, "Find pull requests [base_repo_id: %d, base_branch: %s]: %v", repoID, branch, err)
  995. return
  996. }
  997. for _, pr := range prs {
  998. pr.AddToTaskQueue()
  999. }
  1000. }
  1001. // ChangeUsernameInPullRequests changes the name of head_user_name
  1002. func ChangeUsernameInPullRequests(oldUserName, newUserName string) error {
  1003. pr := PullRequest{
  1004. HeadUserName: strings.ToLower(newUserName),
  1005. }
  1006. _, err := x.
  1007. Cols("head_user_name").
  1008. Where("head_user_name = ?", strings.ToLower(oldUserName)).
  1009. Update(pr)
  1010. return err
  1011. }
  1012. // checkAndUpdateStatus checks if pull request is possible to leaving checking status,
  1013. // and set to be either conflict or mergeable.
  1014. func (pr *PullRequest) checkAndUpdateStatus() {
  1015. // Status is not changed to conflict means mergeable.
  1016. if pr.Status == PullRequestStatusChecking {
  1017. pr.Status = PullRequestStatusMergeable
  1018. }
  1019. // Make sure there is no waiting test to process before leaving the checking status.
  1020. if !pullRequestQueue.Exist(pr.ID) {
  1021. if err := pr.UpdateCols("status"); err != nil {
  1022. log.Error(4, "Update[%d]: %v", pr.ID, err)
  1023. }
  1024. }
  1025. }
  1026. // TestPullRequests checks and tests untested patches of pull requests.
  1027. // TODO: test more pull requests at same time.
  1028. func TestPullRequests() {
  1029. prs := make([]*PullRequest, 0, 10)
  1030. err := x.Where("status = ?", PullRequestStatusChecking).Find(&prs)
  1031. if err != nil {
  1032. log.Error(3, "Find Checking PRs", err)
  1033. return
  1034. }
  1035. var checkedPRs = make(map[int64]struct{})
  1036. // Update pull request status.
  1037. for _, pr := range prs {
  1038. checkedPRs[pr.ID] = struct{}{}
  1039. if err := pr.GetBaseRepo(); err != nil {
  1040. log.Error(3, "GetBaseRepo: %v", err)
  1041. continue
  1042. }
  1043. if pr.manuallyMerged() {
  1044. continue
  1045. }
  1046. if err := pr.testPatch(); err != nil {
  1047. log.Error(3, "testPatch: %v", err)
  1048. continue
  1049. }
  1050. pr.checkAndUpdateStatus()
  1051. }
  1052. // Start listening on new test requests.
  1053. for prID := range pullRequestQueue.Queue() {
  1054. log.Trace("TestPullRequests[%v]: processing test task", prID)
  1055. pullRequestQueue.Remove(prID)
  1056. id := com.StrTo(prID).MustInt64()
  1057. if _, ok := checkedPRs[id]; ok {
  1058. continue
  1059. }
  1060. pr, err := GetPullRequestByID(id)
  1061. if err != nil {
  1062. log.Error(4, "GetPullRequestByID[%s]: %v", prID, err)
  1063. continue
  1064. } else if pr.manuallyMerged() {
  1065. continue
  1066. } else if err = pr.testPatch(); err != nil {
  1067. log.Error(4, "testPatch[%d]: %v", pr.ID, err)
  1068. continue
  1069. }
  1070. pr.checkAndUpdateStatus()
  1071. }
  1072. }
  1073. // InitTestPullRequests runs the task to test all the checking status pull requests
  1074. func InitTestPullRequests() {
  1075. go TestPullRequests()
  1076. }