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

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