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.

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