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

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