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

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