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

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