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 40KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340
  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 && !pr.IsWorkInProgress()
  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 := prs.getIssueIDs()
  931. issues := make([]*Issue, 0, len(issueIDs))
  932. if err := e.
  933. Where("id > 0").
  934. In("id", issueIDs).
  935. Find(&issues); err != nil {
  936. return fmt.Errorf("find issues: %v", err)
  937. }
  938. set := make(map[int64]*Issue)
  939. for i := range issues {
  940. set[issues[i].ID] = issues[i]
  941. }
  942. for i := range prs {
  943. prs[i].Issue = set[prs[i].IssueID]
  944. }
  945. return nil
  946. }
  947. func (prs PullRequestList) getIssueIDs() []int64 {
  948. issueIDs := make([]int64, 0, len(prs))
  949. for i := range prs {
  950. issueIDs = append(issueIDs, prs[i].IssueID)
  951. }
  952. return issueIDs
  953. }
  954. // LoadAttributes load all the prs attributes
  955. func (prs PullRequestList) LoadAttributes() error {
  956. return prs.loadAttributes(x)
  957. }
  958. func (prs PullRequestList) invalidateCodeComments(e Engine, doer *User, repo *git.Repository, branch string) error {
  959. if len(prs) == 0 {
  960. return nil
  961. }
  962. issueIDs := prs.getIssueIDs()
  963. var codeComments []*Comment
  964. if err := e.
  965. Where("type = ? and invalidated = ?", CommentTypeCode, false).
  966. In("issue_id", issueIDs).
  967. Find(&codeComments); err != nil {
  968. return fmt.Errorf("find code comments: %v", err)
  969. }
  970. for _, comment := range codeComments {
  971. if err := comment.CheckInvalidation(repo, doer, branch); err != nil {
  972. return err
  973. }
  974. }
  975. return nil
  976. }
  977. // InvalidateCodeComments will lookup the prs for code comments which got invalidated by change
  978. func (prs PullRequestList) InvalidateCodeComments(doer *User, repo *git.Repository, branch string) error {
  979. return prs.invalidateCodeComments(x, doer, repo, branch)
  980. }
  981. func addHeadRepoTasks(prs []*PullRequest) {
  982. for _, pr := range prs {
  983. log.Trace("addHeadRepoTasks[%d]: composing new test task", pr.ID)
  984. if err := pr.UpdatePatch(); err != nil {
  985. log.Error(4, "UpdatePatch: %v", err)
  986. continue
  987. } else if err := pr.PushToBaseRepo(); err != nil {
  988. log.Error(4, "PushToBaseRepo: %v", err)
  989. continue
  990. }
  991. pr.AddToTaskQueue()
  992. }
  993. }
  994. // AddTestPullRequestTask adds new test tasks by given head/base repository and head/base branch,
  995. // and generate new patch for testing as needed.
  996. func AddTestPullRequestTask(doer *User, repoID int64, branch string, isSync bool) {
  997. log.Trace("AddTestPullRequestTask [head_repo_id: %d, head_branch: %s]: finding pull requests", repoID, branch)
  998. prs, err := GetUnmergedPullRequestsByHeadInfo(repoID, branch)
  999. if err != nil {
  1000. log.Error(4, "Find pull requests [head_repo_id: %d, head_branch: %s]: %v", repoID, branch, err)
  1001. return
  1002. }
  1003. if isSync {
  1004. requests := PullRequestList(prs)
  1005. if err = requests.LoadAttributes(); err != nil {
  1006. log.Error(4, "PullRequestList.LoadAttributes: %v", err)
  1007. }
  1008. if invalidationErr := checkForInvalidation(requests, repoID, doer, branch); invalidationErr != nil {
  1009. log.Error(4, "checkForInvalidation: %v", invalidationErr)
  1010. }
  1011. if err == nil {
  1012. for _, pr := range prs {
  1013. pr.Issue.PullRequest = pr
  1014. if err = pr.Issue.LoadAttributes(); err != nil {
  1015. log.Error(4, "LoadAttributes: %v", err)
  1016. continue
  1017. }
  1018. if err = PrepareWebhooks(pr.Issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  1019. Action: api.HookIssueSynchronized,
  1020. Index: pr.Issue.Index,
  1021. PullRequest: pr.Issue.PullRequest.APIFormat(),
  1022. Repository: pr.Issue.Repo.APIFormat(AccessModeNone),
  1023. Sender: doer.APIFormat(),
  1024. }); err != nil {
  1025. log.Error(4, "PrepareWebhooks [pull_id: %v]: %v", pr.ID, err)
  1026. continue
  1027. }
  1028. go HookQueue.Add(pr.Issue.Repo.ID)
  1029. }
  1030. }
  1031. }
  1032. addHeadRepoTasks(prs)
  1033. log.Trace("AddTestPullRequestTask [base_repo_id: %d, base_branch: %s]: finding pull requests", repoID, branch)
  1034. prs, err = GetUnmergedPullRequestsByBaseInfo(repoID, branch)
  1035. if err != nil {
  1036. log.Error(4, "Find pull requests [base_repo_id: %d, base_branch: %s]: %v", repoID, branch, err)
  1037. return
  1038. }
  1039. for _, pr := range prs {
  1040. pr.AddToTaskQueue()
  1041. }
  1042. }
  1043. func checkForInvalidation(requests PullRequestList, repoID int64, doer *User, branch string) error {
  1044. repo, err := GetRepositoryByID(repoID)
  1045. if err != nil {
  1046. return fmt.Errorf("GetRepositoryByID: %v", err)
  1047. }
  1048. gitRepo, err := git.OpenRepository(repo.RepoPath())
  1049. if err != nil {
  1050. return fmt.Errorf("git.OpenRepository: %v", err)
  1051. }
  1052. go func() {
  1053. err := requests.InvalidateCodeComments(doer, gitRepo, branch)
  1054. if err != nil {
  1055. log.Error(4, "PullRequestList.InvalidateCodeComments: %v", err)
  1056. }
  1057. }()
  1058. return nil
  1059. }
  1060. // ChangeUsernameInPullRequests changes the name of head_user_name
  1061. func ChangeUsernameInPullRequests(oldUserName, newUserName string) error {
  1062. pr := PullRequest{
  1063. HeadUserName: strings.ToLower(newUserName),
  1064. }
  1065. _, err := x.
  1066. Cols("head_user_name").
  1067. Where("head_user_name = ?", strings.ToLower(oldUserName)).
  1068. Update(pr)
  1069. return err
  1070. }
  1071. // checkAndUpdateStatus checks if pull request is possible to leaving checking status,
  1072. // and set to be either conflict or mergeable.
  1073. func (pr *PullRequest) checkAndUpdateStatus() {
  1074. // Status is not changed to conflict means mergeable.
  1075. if pr.Status == PullRequestStatusChecking {
  1076. pr.Status = PullRequestStatusMergeable
  1077. }
  1078. // Make sure there is no waiting test to process before leaving the checking status.
  1079. if !pullRequestQueue.Exist(pr.ID) {
  1080. if err := pr.UpdateCols("status"); err != nil {
  1081. log.Error(4, "Update[%d]: %v", pr.ID, err)
  1082. }
  1083. }
  1084. }
  1085. // IsWorkInProgress determine if the Pull Request is a Work In Progress by its title
  1086. func (pr *PullRequest) IsWorkInProgress() bool {
  1087. if err := pr.LoadIssue(); err != nil {
  1088. log.Error(4, "LoadIssue: %v", err)
  1089. return false
  1090. }
  1091. for _, prefix := range setting.Repository.PullRequest.WorkInProgressPrefixes {
  1092. if strings.HasPrefix(strings.ToUpper(pr.Issue.Title), prefix) {
  1093. return true
  1094. }
  1095. }
  1096. return false
  1097. }
  1098. // GetWorkInProgressPrefix returns the prefix used to mark the pull request as a work in progress.
  1099. // It returns an empty string when none were found
  1100. func (pr *PullRequest) GetWorkInProgressPrefix() string {
  1101. if err := pr.LoadIssue(); err != nil {
  1102. log.Error(4, "LoadIssue: %v", err)
  1103. return ""
  1104. }
  1105. for _, prefix := range setting.Repository.PullRequest.WorkInProgressPrefixes {
  1106. if strings.HasPrefix(strings.ToUpper(pr.Issue.Title), prefix) {
  1107. return pr.Issue.Title[0:len(prefix)]
  1108. }
  1109. }
  1110. return ""
  1111. }
  1112. // TestPullRequests checks and tests untested patches of pull requests.
  1113. // TODO: test more pull requests at same time.
  1114. func TestPullRequests() {
  1115. prs := make([]*PullRequest, 0, 10)
  1116. err := x.Where("status = ?", PullRequestStatusChecking).Find(&prs)
  1117. if err != nil {
  1118. log.Error(3, "Find Checking PRs", err)
  1119. return
  1120. }
  1121. var checkedPRs = make(map[int64]struct{})
  1122. // Update pull request status.
  1123. for _, pr := range prs {
  1124. checkedPRs[pr.ID] = struct{}{}
  1125. if err := pr.GetBaseRepo(); err != nil {
  1126. log.Error(3, "GetBaseRepo: %v", err)
  1127. continue
  1128. }
  1129. if pr.manuallyMerged() {
  1130. continue
  1131. }
  1132. if err := pr.testPatch(); err != nil {
  1133. log.Error(3, "testPatch: %v", err)
  1134. continue
  1135. }
  1136. pr.checkAndUpdateStatus()
  1137. }
  1138. // Start listening on new test requests.
  1139. for prID := range pullRequestQueue.Queue() {
  1140. log.Trace("TestPullRequests[%v]: processing test task", prID)
  1141. pullRequestQueue.Remove(prID)
  1142. id := com.StrTo(prID).MustInt64()
  1143. if _, ok := checkedPRs[id]; ok {
  1144. continue
  1145. }
  1146. pr, err := GetPullRequestByID(id)
  1147. if err != nil {
  1148. log.Error(4, "GetPullRequestByID[%s]: %v", prID, err)
  1149. continue
  1150. } else if pr.manuallyMerged() {
  1151. continue
  1152. } else if err = pr.testPatch(); err != nil {
  1153. log.Error(4, "testPatch[%d]: %v", pr.ID, err)
  1154. continue
  1155. }
  1156. pr.checkAndUpdateStatus()
  1157. }
  1158. }
  1159. // InitTestPullRequests runs the task to test all the checking status pull requests
  1160. func InitTestPullRequests() {
  1161. go TestPullRequests()
  1162. }