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

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