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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package models
  6. import (
  7. "bufio"
  8. "fmt"
  9. "io/ioutil"
  10. "os"
  11. "path"
  12. "path/filepath"
  13. "strconv"
  14. "strings"
  15. "time"
  16. "code.gitea.io/gitea/modules/git"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/process"
  19. "code.gitea.io/gitea/modules/setting"
  20. api "code.gitea.io/gitea/modules/structs"
  21. "code.gitea.io/gitea/modules/sync"
  22. "code.gitea.io/gitea/modules/timeutil"
  23. "github.com/unknwon/com"
  24. )
  25. var pullRequestQueue = sync.NewUniqueQueue(setting.Repository.PullRequestQueueLength)
  26. // PullRequestType defines pull request type
  27. type PullRequestType int
  28. // Enumerate all the pull request types
  29. const (
  30. PullRequestGitea PullRequestType = iota
  31. PullRequestGit
  32. )
  33. // PullRequestStatus defines pull request status
  34. type PullRequestStatus int
  35. // Enumerate all the pull request status
  36. const (
  37. PullRequestStatusConflict PullRequestStatus = iota
  38. PullRequestStatusChecking
  39. PullRequestStatusMergeable
  40. PullRequestStatusManuallyMerged
  41. )
  42. // PullRequest represents relation between pull request and repositories.
  43. type PullRequest struct {
  44. ID int64 `xorm:"pk autoincr"`
  45. Type PullRequestType
  46. Status PullRequestStatus
  47. ConflictedFiles []string `xorm:"TEXT JSON"`
  48. IssueID int64 `xorm:"INDEX"`
  49. Issue *Issue `xorm:"-"`
  50. Index int64
  51. HeadRepoID int64 `xorm:"INDEX"`
  52. HeadRepo *Repository `xorm:"-"`
  53. BaseRepoID int64 `xorm:"INDEX"`
  54. BaseRepo *Repository `xorm:"-"`
  55. HeadBranch string
  56. BaseBranch string
  57. ProtectedBranch *ProtectedBranch `xorm:"-"`
  58. MergeBase string `xorm:"VARCHAR(40)"`
  59. HasMerged bool `xorm:"INDEX"`
  60. MergedCommitID string `xorm:"VARCHAR(40)"`
  61. MergerID int64 `xorm:"INDEX"`
  62. Merger *User `xorm:"-"`
  63. MergedUnix timeutil.TimeStamp `xorm:"updated INDEX"`
  64. }
  65. // MustHeadUserName returns the HeadRepo's username if failed return blank
  66. func (pr *PullRequest) MustHeadUserName() string {
  67. if err := pr.LoadHeadRepo(); err != nil {
  68. log.Error("LoadHeadRepo: %v", err)
  69. return ""
  70. }
  71. return pr.HeadRepo.MustOwnerName()
  72. }
  73. // Note: don't try to get Issue because will end up recursive querying.
  74. func (pr *PullRequest) loadAttributes(e Engine) (err error) {
  75. if pr.HasMerged && pr.Merger == nil {
  76. pr.Merger, err = getUserByID(e, pr.MergerID)
  77. if IsErrUserNotExist(err) {
  78. pr.MergerID = -1
  79. pr.Merger = NewGhostUser()
  80. } else if err != nil {
  81. return fmt.Errorf("getUserByID [%d]: %v", pr.MergerID, err)
  82. }
  83. }
  84. return nil
  85. }
  86. // LoadAttributes loads pull request attributes from database
  87. func (pr *PullRequest) LoadAttributes() error {
  88. return pr.loadAttributes(x)
  89. }
  90. // LoadBaseRepo loads pull request base repository from database
  91. func (pr *PullRequest) LoadBaseRepo() error {
  92. if pr.BaseRepo == nil {
  93. if pr.HeadRepoID == pr.BaseRepoID && pr.HeadRepo != nil {
  94. pr.BaseRepo = pr.HeadRepo
  95. return nil
  96. }
  97. var repo Repository
  98. if has, err := x.ID(pr.BaseRepoID).Get(&repo); err != nil {
  99. return err
  100. } else if !has {
  101. return ErrRepoNotExist{ID: pr.BaseRepoID}
  102. }
  103. pr.BaseRepo = &repo
  104. }
  105. return nil
  106. }
  107. // LoadHeadRepo loads pull request head repository from database
  108. func (pr *PullRequest) LoadHeadRepo() error {
  109. if pr.HeadRepo == nil {
  110. if pr.HeadRepoID == pr.BaseRepoID && pr.BaseRepo != nil {
  111. pr.HeadRepo = pr.BaseRepo
  112. return nil
  113. }
  114. var repo Repository
  115. if has, err := x.ID(pr.HeadRepoID).Get(&repo); err != nil {
  116. return err
  117. } else if !has {
  118. return ErrRepoNotExist{ID: pr.BaseRepoID}
  119. }
  120. pr.HeadRepo = &repo
  121. }
  122. return nil
  123. }
  124. // LoadIssue loads issue information from database
  125. func (pr *PullRequest) LoadIssue() (err error) {
  126. return pr.loadIssue(x)
  127. }
  128. func (pr *PullRequest) loadIssue(e Engine) (err error) {
  129. if pr.Issue != nil {
  130. return nil
  131. }
  132. pr.Issue, err = getIssueByID(e, pr.IssueID)
  133. return err
  134. }
  135. // LoadProtectedBranch loads the protected branch of the base branch
  136. func (pr *PullRequest) LoadProtectedBranch() (err error) {
  137. if pr.BaseRepo == nil {
  138. if pr.BaseRepoID == 0 {
  139. return nil
  140. }
  141. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  142. if err != nil {
  143. return
  144. }
  145. }
  146. pr.ProtectedBranch, err = GetProtectedBranchBy(pr.BaseRepo.ID, pr.BaseBranch)
  147. return
  148. }
  149. // GetDefaultMergeMessage returns default message used when merging pull request
  150. func (pr *PullRequest) GetDefaultMergeMessage() string {
  151. if pr.HeadRepo == nil {
  152. var err error
  153. pr.HeadRepo, err = GetRepositoryByID(pr.HeadRepoID)
  154. if err != nil {
  155. log.Error("GetRepositoryById[%d]: %v", pr.HeadRepoID, err)
  156. return ""
  157. }
  158. }
  159. return fmt.Sprintf("Merge branch '%s' of %s/%s into %s", pr.HeadBranch, pr.MustHeadUserName(), pr.HeadRepo.Name, pr.BaseBranch)
  160. }
  161. // GetDefaultSquashMessage returns default message used when squash and merging pull request
  162. func (pr *PullRequest) GetDefaultSquashMessage() string {
  163. if err := pr.LoadIssue(); err != nil {
  164. log.Error("LoadIssue: %v", err)
  165. return ""
  166. }
  167. return fmt.Sprintf("%s (#%d)", pr.Issue.Title, pr.Issue.Index)
  168. }
  169. // GetGitRefName returns git ref for hidden pull request branch
  170. func (pr *PullRequest) GetGitRefName() string {
  171. return fmt.Sprintf("refs/pull/%d/head", pr.Index)
  172. }
  173. // APIFormat assumes following fields have been assigned with valid values:
  174. // Required - Issue
  175. // Optional - Merger
  176. func (pr *PullRequest) APIFormat() *api.PullRequest {
  177. return pr.apiFormat(x)
  178. }
  179. func (pr *PullRequest) apiFormat(e Engine) *api.PullRequest {
  180. var (
  181. baseBranch *git.Branch
  182. headBranch *git.Branch
  183. baseCommit *git.Commit
  184. headCommit *git.Commit
  185. err error
  186. )
  187. if err = pr.Issue.loadRepo(e); err != nil {
  188. log.Error("loadRepo[%d]: %v", pr.ID, err)
  189. return nil
  190. }
  191. apiIssue := pr.Issue.apiFormat(e)
  192. if pr.BaseRepo == nil {
  193. pr.BaseRepo, err = getRepositoryByID(e, pr.BaseRepoID)
  194. if err != nil {
  195. log.Error("GetRepositoryById[%d]: %v", pr.ID, err)
  196. return nil
  197. }
  198. }
  199. if pr.HeadRepo == nil {
  200. pr.HeadRepo, err = getRepositoryByID(e, pr.HeadRepoID)
  201. if err != nil {
  202. log.Error("GetRepositoryById[%d]: %v", pr.ID, err)
  203. return nil
  204. }
  205. }
  206. if err = pr.Issue.loadRepo(e); err != nil {
  207. log.Error("pr.Issue.loadRepo[%d]: %v", pr.ID, err)
  208. return nil
  209. }
  210. apiPullRequest := &api.PullRequest{
  211. ID: pr.ID,
  212. URL: pr.Issue.HTMLURL(),
  213. Index: pr.Index,
  214. Poster: apiIssue.Poster,
  215. Title: apiIssue.Title,
  216. Body: apiIssue.Body,
  217. Labels: apiIssue.Labels,
  218. Milestone: apiIssue.Milestone,
  219. Assignee: apiIssue.Assignee,
  220. Assignees: apiIssue.Assignees,
  221. State: apiIssue.State,
  222. Comments: apiIssue.Comments,
  223. HTMLURL: pr.Issue.HTMLURL(),
  224. DiffURL: pr.Issue.DiffURL(),
  225. PatchURL: pr.Issue.PatchURL(),
  226. HasMerged: pr.HasMerged,
  227. MergeBase: pr.MergeBase,
  228. Deadline: apiIssue.Deadline,
  229. Created: pr.Issue.CreatedUnix.AsTimePtr(),
  230. Updated: pr.Issue.UpdatedUnix.AsTimePtr(),
  231. }
  232. baseBranch, err = pr.BaseRepo.GetBranch(pr.BaseBranch)
  233. if err != nil {
  234. if git.IsErrBranchNotExist(err) {
  235. apiPullRequest.Base = nil
  236. } else {
  237. log.Error("GetBranch[%s]: %v", pr.BaseBranch, err)
  238. return nil
  239. }
  240. } else {
  241. apiBaseBranchInfo := &api.PRBranchInfo{
  242. Name: pr.BaseBranch,
  243. Ref: pr.BaseBranch,
  244. RepoID: pr.BaseRepoID,
  245. Repository: pr.BaseRepo.innerAPIFormat(e, AccessModeNone, false),
  246. }
  247. baseCommit, err = baseBranch.GetCommit()
  248. if err != nil {
  249. if git.IsErrNotExist(err) {
  250. apiBaseBranchInfo.Sha = ""
  251. } else {
  252. log.Error("GetCommit[%s]: %v", baseBranch.Name, err)
  253. return nil
  254. }
  255. } else {
  256. apiBaseBranchInfo.Sha = baseCommit.ID.String()
  257. }
  258. apiPullRequest.Base = apiBaseBranchInfo
  259. }
  260. headBranch, err = pr.HeadRepo.GetBranch(pr.HeadBranch)
  261. if err != nil {
  262. if git.IsErrBranchNotExist(err) {
  263. apiPullRequest.Head = nil
  264. } else {
  265. log.Error("GetBranch[%s]: %v", pr.HeadBranch, err)
  266. return nil
  267. }
  268. } else {
  269. apiHeadBranchInfo := &api.PRBranchInfo{
  270. Name: pr.HeadBranch,
  271. Ref: pr.HeadBranch,
  272. RepoID: pr.HeadRepoID,
  273. Repository: pr.HeadRepo.innerAPIFormat(e, AccessModeNone, false),
  274. }
  275. headCommit, err = headBranch.GetCommit()
  276. if err != nil {
  277. if git.IsErrNotExist(err) {
  278. apiHeadBranchInfo.Sha = ""
  279. } else {
  280. log.Error("GetCommit[%s]: %v", headBranch.Name, err)
  281. return nil
  282. }
  283. } else {
  284. apiHeadBranchInfo.Sha = headCommit.ID.String()
  285. }
  286. apiPullRequest.Head = apiHeadBranchInfo
  287. }
  288. if pr.Status != PullRequestStatusChecking {
  289. mergeable := pr.Status != PullRequestStatusConflict && !pr.IsWorkInProgress()
  290. apiPullRequest.Mergeable = mergeable
  291. }
  292. if pr.HasMerged {
  293. apiPullRequest.Merged = pr.MergedUnix.AsTimePtr()
  294. apiPullRequest.MergedCommitID = &pr.MergedCommitID
  295. apiPullRequest.MergedBy = pr.Merger.APIFormat()
  296. }
  297. return apiPullRequest
  298. }
  299. func (pr *PullRequest) getHeadRepo(e Engine) (err error) {
  300. pr.HeadRepo, err = getRepositoryByID(e, pr.HeadRepoID)
  301. if err != nil && !IsErrRepoNotExist(err) {
  302. return fmt.Errorf("getRepositoryByID(head): %v", err)
  303. }
  304. return nil
  305. }
  306. // GetHeadRepo loads the head repository
  307. func (pr *PullRequest) GetHeadRepo() error {
  308. return pr.getHeadRepo(x)
  309. }
  310. // GetBaseRepo loads the target repository
  311. func (pr *PullRequest) GetBaseRepo() (err error) {
  312. if pr.BaseRepo != nil {
  313. return nil
  314. }
  315. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  316. if err != nil {
  317. return fmt.Errorf("GetRepositoryByID(base): %v", err)
  318. }
  319. return nil
  320. }
  321. // IsChecking returns true if this pull request is still checking conflict.
  322. func (pr *PullRequest) IsChecking() bool {
  323. return pr.Status == PullRequestStatusChecking
  324. }
  325. // CanAutoMerge returns true if this pull request can be merged automatically.
  326. func (pr *PullRequest) CanAutoMerge() bool {
  327. return pr.Status == PullRequestStatusMergeable
  328. }
  329. // GetLastCommitStatus returns the last commit status for this pull request.
  330. func (pr *PullRequest) GetLastCommitStatus() (status *CommitStatus, err error) {
  331. if err = pr.GetHeadRepo(); err != nil {
  332. return nil, err
  333. }
  334. if pr.HeadRepo == nil {
  335. return nil, ErrPullRequestHeadRepoMissing{pr.ID, pr.HeadRepoID}
  336. }
  337. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  338. if err != nil {
  339. return nil, err
  340. }
  341. lastCommitID, err := headGitRepo.GetBranchCommitID(pr.HeadBranch)
  342. if err != nil {
  343. return nil, err
  344. }
  345. err = pr.LoadBaseRepo()
  346. if err != nil {
  347. return nil, err
  348. }
  349. statusList, err := GetLatestCommitStatus(pr.BaseRepo, lastCommitID, 0)
  350. if err != nil {
  351. return nil, err
  352. }
  353. return CalcCommitStatus(statusList), nil
  354. }
  355. // MergeStyle represents the approach to merge commits into base branch.
  356. type MergeStyle string
  357. const (
  358. // MergeStyleMerge create merge commit
  359. MergeStyleMerge MergeStyle = "merge"
  360. // MergeStyleRebase rebase before merging
  361. MergeStyleRebase MergeStyle = "rebase"
  362. // MergeStyleRebaseMerge rebase before merging with merge commit (--no-ff)
  363. MergeStyleRebaseMerge MergeStyle = "rebase-merge"
  364. // MergeStyleSquash squash commits into single commit before merging
  365. MergeStyleSquash MergeStyle = "squash"
  366. )
  367. // CheckUserAllowedToMerge checks whether the user is allowed to merge
  368. func (pr *PullRequest) CheckUserAllowedToMerge(doer *User) (err error) {
  369. if doer == nil {
  370. return ErrNotAllowedToMerge{
  371. "Not signed in",
  372. }
  373. }
  374. if pr.BaseRepo == nil {
  375. if err = pr.GetBaseRepo(); err != nil {
  376. return fmt.Errorf("GetBaseRepo: %v", err)
  377. }
  378. }
  379. if protected, err := pr.BaseRepo.IsProtectedBranchForMerging(pr, pr.BaseBranch, doer); err != nil {
  380. return fmt.Errorf("IsProtectedBranch: %v", err)
  381. } else if protected {
  382. return ErrNotAllowedToMerge{
  383. "The branch is protected",
  384. }
  385. }
  386. return nil
  387. }
  388. // SetMerged sets a pull request to merged and closes the corresponding issue
  389. func (pr *PullRequest) SetMerged() (err error) {
  390. if pr.HasMerged {
  391. return fmt.Errorf("PullRequest[%d] already merged", pr.Index)
  392. }
  393. if pr.MergedCommitID == "" || pr.MergedUnix == 0 || pr.Merger == nil {
  394. return fmt.Errorf("Unable to merge PullRequest[%d], some required fields are empty", pr.Index)
  395. }
  396. pr.HasMerged = true
  397. sess := x.NewSession()
  398. defer sess.Close()
  399. if err = sess.Begin(); err != nil {
  400. return err
  401. }
  402. if err = pr.loadIssue(sess); err != nil {
  403. return err
  404. }
  405. if err = pr.Issue.loadRepo(sess); err != nil {
  406. return err
  407. }
  408. if err = pr.Issue.Repo.getOwner(sess); err != nil {
  409. return err
  410. }
  411. if err = pr.Issue.changeStatus(sess, pr.Merger, true); err != nil {
  412. return fmt.Errorf("Issue.changeStatus: %v", err)
  413. }
  414. if _, err = sess.ID(pr.ID).Cols("has_merged, status, merged_commit_id, merger_id, merged_unix").Update(pr); err != nil {
  415. return fmt.Errorf("update pull request: %v", err)
  416. }
  417. if err = sess.Commit(); err != nil {
  418. return fmt.Errorf("Commit: %v", err)
  419. }
  420. return nil
  421. }
  422. // manuallyMerged checks if a pull request got manually merged
  423. // When a pull request got manually merged mark the pull request as merged
  424. func (pr *PullRequest) manuallyMerged() bool {
  425. commit, err := pr.getMergeCommit()
  426. if err != nil {
  427. log.Error("PullRequest[%d].getMergeCommit: %v", pr.ID, err)
  428. return false
  429. }
  430. if commit != nil {
  431. pr.MergedCommitID = commit.ID.String()
  432. pr.MergedUnix = timeutil.TimeStamp(commit.Author.When.Unix())
  433. pr.Status = PullRequestStatusManuallyMerged
  434. merger, _ := GetUserByEmail(commit.Author.Email)
  435. // When the commit author is unknown set the BaseRepo owner as merger
  436. if merger == nil {
  437. if pr.BaseRepo.Owner == nil {
  438. if err = pr.BaseRepo.getOwner(x); err != nil {
  439. log.Error("BaseRepo.getOwner[%d]: %v", pr.ID, err)
  440. return false
  441. }
  442. }
  443. merger = pr.BaseRepo.Owner
  444. }
  445. pr.Merger = merger
  446. pr.MergerID = merger.ID
  447. if err = pr.SetMerged(); err != nil {
  448. log.Error("PullRequest[%d].setMerged : %v", pr.ID, err)
  449. return false
  450. }
  451. 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())
  452. return true
  453. }
  454. return false
  455. }
  456. // getMergeCommit checks if a pull request got merged
  457. // Returns the git.Commit of the pull request if merged
  458. func (pr *PullRequest) getMergeCommit() (*git.Commit, error) {
  459. if pr.BaseRepo == nil {
  460. var err error
  461. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  462. if err != nil {
  463. return nil, fmt.Errorf("GetRepositoryByID: %v", err)
  464. }
  465. }
  466. indexTmpPath := filepath.Join(os.TempDir(), "gitea-"+pr.BaseRepo.Name+"-"+strconv.Itoa(time.Now().Nanosecond()))
  467. defer os.Remove(indexTmpPath)
  468. headFile := pr.GetGitRefName()
  469. // Check if a pull request is merged into BaseBranch
  470. _, stderr, err := process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("isMerged (git merge-base --is-ancestor): %d", pr.BaseRepo.ID),
  471. []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()},
  472. git.GitExecutable, "merge-base", "--is-ancestor", headFile, pr.BaseBranch)
  473. if err != nil {
  474. // Errors are signaled by a non-zero status that is not 1
  475. if strings.Contains(err.Error(), "exit status 1") {
  476. return nil, nil
  477. }
  478. return nil, fmt.Errorf("git merge-base --is-ancestor: %v %v", stderr, err)
  479. }
  480. commitIDBytes, err := ioutil.ReadFile(pr.BaseRepo.RepoPath() + "/" + headFile)
  481. if err != nil {
  482. return nil, fmt.Errorf("ReadFile(%s): %v", headFile, err)
  483. }
  484. commitID := string(commitIDBytes)
  485. if len(commitID) < 40 {
  486. return nil, fmt.Errorf(`ReadFile(%s): invalid commit-ID "%s"`, headFile, commitID)
  487. }
  488. cmd := commitID[:40] + ".." + pr.BaseBranch
  489. // Get the commit from BaseBranch where the pull request got merged
  490. mergeCommit, stderr, err := process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("isMerged (git rev-list --ancestry-path --merges --reverse): %d", pr.BaseRepo.ID),
  491. []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()},
  492. git.GitExecutable, "rev-list", "--ancestry-path", "--merges", "--reverse", cmd)
  493. if err != nil {
  494. return nil, fmt.Errorf("git rev-list --ancestry-path --merges --reverse: %v %v", stderr, err)
  495. } else if len(mergeCommit) < 40 {
  496. // PR was fast-forwarded, so just use last commit of PR
  497. mergeCommit = commitID[:40]
  498. }
  499. gitRepo, err := git.OpenRepository(pr.BaseRepo.RepoPath())
  500. if err != nil {
  501. return nil, fmt.Errorf("OpenRepository: %v", err)
  502. }
  503. commit, err := gitRepo.GetCommit(mergeCommit[:40])
  504. if err != nil {
  505. return nil, fmt.Errorf("GetCommit: %v", err)
  506. }
  507. return commit, nil
  508. }
  509. // patchConflicts is a list of conflict description from Git.
  510. var patchConflicts = []string{
  511. "patch does not apply",
  512. "already exists in working directory",
  513. "unrecognized input",
  514. "error:",
  515. }
  516. // testPatch checks if patch can be merged to base repository without conflict.
  517. func (pr *PullRequest) testPatch(e Engine) (err error) {
  518. if pr.BaseRepo == nil {
  519. pr.BaseRepo, err = getRepositoryByID(e, pr.BaseRepoID)
  520. if err != nil {
  521. return fmt.Errorf("GetRepositoryByID: %v", err)
  522. }
  523. }
  524. patchPath, err := pr.BaseRepo.patchPath(e, pr.Index)
  525. if err != nil {
  526. return fmt.Errorf("BaseRepo.PatchPath: %v", err)
  527. }
  528. // Fast fail if patch does not exist, this assumes data is corrupted.
  529. if !com.IsFile(patchPath) {
  530. log.Trace("PullRequest[%d].testPatch: ignored corrupted data", pr.ID)
  531. return nil
  532. }
  533. repoWorkingPool.CheckIn(com.ToStr(pr.BaseRepoID))
  534. defer repoWorkingPool.CheckOut(com.ToStr(pr.BaseRepoID))
  535. log.Trace("PullRequest[%d].testPatch (patchPath): %s", pr.ID, patchPath)
  536. pr.Status = PullRequestStatusChecking
  537. indexTmpPath := filepath.Join(os.TempDir(), "gitea-"+pr.BaseRepo.Name+"-"+strconv.Itoa(time.Now().Nanosecond()))
  538. defer os.Remove(indexTmpPath)
  539. var stderr string
  540. _, stderr, err = process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("testPatch (git read-tree): %d", pr.BaseRepo.ID),
  541. []string{"GIT_DIR=" + pr.BaseRepo.RepoPath(), "GIT_INDEX_FILE=" + indexTmpPath},
  542. git.GitExecutable, "read-tree", pr.BaseBranch)
  543. if err != nil {
  544. return fmt.Errorf("git read-tree --index-output=%s %s: %v - %s", indexTmpPath, pr.BaseBranch, err, stderr)
  545. }
  546. prUnit, err := pr.BaseRepo.getUnit(e, UnitTypePullRequests)
  547. if err != nil {
  548. return err
  549. }
  550. prConfig := prUnit.PullRequestsConfig()
  551. args := []string{"apply", "--check", "--cached"}
  552. if prConfig.IgnoreWhitespaceConflicts {
  553. args = append(args, "--ignore-whitespace")
  554. }
  555. args = append(args, patchPath)
  556. pr.ConflictedFiles = []string{}
  557. _, stderr, err = process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("testPatch (git apply --check): %d", pr.BaseRepo.ID),
  558. []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()},
  559. git.GitExecutable, args...)
  560. if err != nil {
  561. for i := range patchConflicts {
  562. if strings.Contains(stderr, patchConflicts[i]) {
  563. log.Trace("PullRequest[%d].testPatch (apply): has conflict: %s", pr.ID, stderr)
  564. const prefix = "error: patch failed:"
  565. pr.Status = PullRequestStatusConflict
  566. pr.ConflictedFiles = make([]string, 0, 5)
  567. scanner := bufio.NewScanner(strings.NewReader(stderr))
  568. for scanner.Scan() {
  569. line := scanner.Text()
  570. if strings.HasPrefix(line, prefix) {
  571. var found bool
  572. var filepath = strings.TrimSpace(strings.Split(line[len(prefix):], ":")[0])
  573. for _, f := range pr.ConflictedFiles {
  574. if f == filepath {
  575. found = true
  576. break
  577. }
  578. }
  579. if !found {
  580. pr.ConflictedFiles = append(pr.ConflictedFiles, filepath)
  581. }
  582. }
  583. // only list 10 conflicted files
  584. if len(pr.ConflictedFiles) >= 10 {
  585. break
  586. }
  587. }
  588. if len(pr.ConflictedFiles) > 0 {
  589. log.Trace("Found %d files conflicted: %v", len(pr.ConflictedFiles), pr.ConflictedFiles)
  590. }
  591. return nil
  592. }
  593. }
  594. return fmt.Errorf("git apply --check: %v - %s", err, stderr)
  595. }
  596. return nil
  597. }
  598. // NewPullRequest creates new pull request with labels for repository.
  599. func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest, patch []byte) (err error) {
  600. // Retry several times in case INSERT fails due to duplicate key for (repo_id, index); see #7887
  601. i := 0
  602. for {
  603. if err = newPullRequestAttempt(repo, pull, labelIDs, uuids, pr, patch); err == nil {
  604. return nil
  605. }
  606. if !IsErrNewIssueInsert(err) {
  607. return err
  608. }
  609. if i++; i == issueMaxDupIndexAttempts {
  610. break
  611. }
  612. log.Error("NewPullRequest: error attempting to insert the new issue; will retry. Original error: %v", err)
  613. }
  614. return fmt.Errorf("NewPullRequest: too many errors attempting to insert the new issue. Last error was: %v", err)
  615. }
  616. func newPullRequestAttempt(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest, patch []byte) (err error) {
  617. sess := x.NewSession()
  618. defer sess.Close()
  619. if err = sess.Begin(); err != nil {
  620. return err
  621. }
  622. if err = newIssue(sess, pull.Poster, NewIssueOptions{
  623. Repo: repo,
  624. Issue: pull,
  625. LabelIDs: labelIDs,
  626. Attachments: uuids,
  627. IsPull: true,
  628. }); err != nil {
  629. if IsErrUserDoesNotHaveAccessToRepo(err) || IsErrNewIssueInsert(err) {
  630. return err
  631. }
  632. return fmt.Errorf("newIssue: %v", err)
  633. }
  634. pr.Index = pull.Index
  635. pr.BaseRepo = repo
  636. pr.Status = PullRequestStatusChecking
  637. if len(patch) > 0 {
  638. if err = repo.savePatch(sess, pr.Index, patch); err != nil {
  639. return fmt.Errorf("SavePatch: %v", err)
  640. }
  641. if err = pr.testPatch(sess); err != nil {
  642. return fmt.Errorf("testPatch: %v", err)
  643. }
  644. }
  645. // No conflict appears after test means mergeable.
  646. if pr.Status == PullRequestStatusChecking {
  647. pr.Status = PullRequestStatusMergeable
  648. }
  649. pr.IssueID = pull.ID
  650. if _, err = sess.Insert(pr); err != nil {
  651. return fmt.Errorf("insert pull repo: %v", err)
  652. }
  653. if err = sess.Commit(); err != nil {
  654. return fmt.Errorf("Commit: %v", err)
  655. }
  656. return nil
  657. }
  658. // GetUnmergedPullRequest returns a pull request that is open and has not been merged
  659. // by given head/base and repo/branch.
  660. func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string) (*PullRequest, error) {
  661. pr := new(PullRequest)
  662. has, err := x.
  663. Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  664. headRepoID, headBranch, baseRepoID, baseBranch, false, false).
  665. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  666. Get(pr)
  667. if err != nil {
  668. return nil, err
  669. } else if !has {
  670. return nil, ErrPullRequestNotExist{0, 0, headRepoID, baseRepoID, headBranch, baseBranch}
  671. }
  672. return pr, nil
  673. }
  674. // GetLatestPullRequestByHeadInfo returns the latest pull request (regardless of its status)
  675. // by given head information (repo and branch).
  676. func GetLatestPullRequestByHeadInfo(repoID int64, branch string) (*PullRequest, error) {
  677. pr := new(PullRequest)
  678. has, err := x.
  679. Where("head_repo_id = ? AND head_branch = ?", repoID, branch).
  680. OrderBy("id DESC").
  681. Get(pr)
  682. if !has {
  683. return nil, err
  684. }
  685. return pr, err
  686. }
  687. // GetPullRequestByIndex returns a pull request by the given index
  688. func GetPullRequestByIndex(repoID int64, index int64) (*PullRequest, error) {
  689. pr := &PullRequest{
  690. BaseRepoID: repoID,
  691. Index: index,
  692. }
  693. has, err := x.Get(pr)
  694. if err != nil {
  695. return nil, err
  696. } else if !has {
  697. return nil, ErrPullRequestNotExist{0, 0, 0, repoID, "", ""}
  698. }
  699. if err = pr.LoadAttributes(); err != nil {
  700. return nil, err
  701. }
  702. if err = pr.LoadIssue(); err != nil {
  703. return nil, err
  704. }
  705. return pr, nil
  706. }
  707. func getPullRequestByID(e Engine, id int64) (*PullRequest, error) {
  708. pr := new(PullRequest)
  709. has, err := e.ID(id).Get(pr)
  710. if err != nil {
  711. return nil, err
  712. } else if !has {
  713. return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""}
  714. }
  715. return pr, pr.loadAttributes(e)
  716. }
  717. // GetPullRequestByID returns a pull request by given ID.
  718. func GetPullRequestByID(id int64) (*PullRequest, error) {
  719. return getPullRequestByID(x, id)
  720. }
  721. func getPullRequestByIssueID(e Engine, issueID int64) (*PullRequest, error) {
  722. pr := &PullRequest{
  723. IssueID: issueID,
  724. }
  725. has, err := e.Get(pr)
  726. if err != nil {
  727. return nil, err
  728. } else if !has {
  729. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  730. }
  731. return pr, pr.loadAttributes(e)
  732. }
  733. // GetPullRequestByIssueID returns pull request by given issue ID.
  734. func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) {
  735. return getPullRequestByIssueID(x, issueID)
  736. }
  737. // Update updates all fields of pull request.
  738. func (pr *PullRequest) Update() error {
  739. _, err := x.ID(pr.ID).AllCols().Update(pr)
  740. return err
  741. }
  742. // UpdateCols updates specific fields of pull request.
  743. func (pr *PullRequest) UpdateCols(cols ...string) error {
  744. _, err := x.ID(pr.ID).Cols(cols...).Update(pr)
  745. return err
  746. }
  747. // UpdatePatch generates and saves a new patch.
  748. func (pr *PullRequest) UpdatePatch() (err error) {
  749. if err = pr.GetHeadRepo(); err != nil {
  750. return fmt.Errorf("GetHeadRepo: %v", err)
  751. } else if pr.HeadRepo == nil {
  752. log.Trace("PullRequest[%d].UpdatePatch: ignored corrupted data", pr.ID)
  753. return nil
  754. }
  755. if err = pr.GetBaseRepo(); err != nil {
  756. return fmt.Errorf("GetBaseRepo: %v", err)
  757. }
  758. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  759. if err != nil {
  760. return fmt.Errorf("OpenRepository: %v", err)
  761. }
  762. // Add a temporary remote.
  763. tmpRemote := com.ToStr(time.Now().UnixNano())
  764. if err = headGitRepo.AddRemote(tmpRemote, RepoPath(pr.BaseRepo.MustOwner().Name, pr.BaseRepo.Name), true); err != nil {
  765. return fmt.Errorf("AddRemote: %v", err)
  766. }
  767. defer func() {
  768. if err := headGitRepo.RemoveRemote(tmpRemote); err != nil {
  769. log.Error("UpdatePatch: RemoveRemote: %s", err)
  770. }
  771. }()
  772. pr.MergeBase, _, err = headGitRepo.GetMergeBase(tmpRemote, pr.BaseBranch, pr.HeadBranch)
  773. if err != nil {
  774. return fmt.Errorf("GetMergeBase: %v", err)
  775. } else if err = pr.Update(); err != nil {
  776. return fmt.Errorf("Update: %v", err)
  777. }
  778. patch, err := headGitRepo.GetPatch(pr.MergeBase, pr.HeadBranch)
  779. if err != nil {
  780. return fmt.Errorf("GetPatch: %v", err)
  781. }
  782. if err = pr.BaseRepo.SavePatch(pr.Index, patch); err != nil {
  783. return fmt.Errorf("BaseRepo.SavePatch: %v", err)
  784. }
  785. return nil
  786. }
  787. // PushToBaseRepo pushes commits from branches of head repository to
  788. // corresponding branches of base repository.
  789. // FIXME: Only push branches that are actually updates?
  790. func (pr *PullRequest) PushToBaseRepo() (err error) {
  791. log.Trace("PushToBaseRepo[%d]: pushing commits to base repo '%s'", pr.BaseRepoID, pr.GetGitRefName())
  792. headRepoPath := pr.HeadRepo.RepoPath()
  793. headGitRepo, err := git.OpenRepository(headRepoPath)
  794. if err != nil {
  795. return fmt.Errorf("OpenRepository: %v", err)
  796. }
  797. tmpRemoteName := fmt.Sprintf("tmp-pull-%d", pr.ID)
  798. if err = headGitRepo.AddRemote(tmpRemoteName, pr.BaseRepo.RepoPath(), false); err != nil {
  799. return fmt.Errorf("headGitRepo.AddRemote: %v", err)
  800. }
  801. // Make sure to remove the remote even if the push fails
  802. defer func() {
  803. if err := headGitRepo.RemoveRemote(tmpRemoteName); err != nil {
  804. log.Error("PushToBaseRepo: RemoveRemote: %s", err)
  805. }
  806. }()
  807. headFile := pr.GetGitRefName()
  808. // Remove head in case there is a conflict.
  809. file := path.Join(pr.BaseRepo.RepoPath(), headFile)
  810. _ = os.Remove(file)
  811. if err = git.Push(headRepoPath, git.PushOptions{
  812. Remote: tmpRemoteName,
  813. Branch: fmt.Sprintf("%s:%s", pr.HeadBranch, headFile),
  814. Force: true,
  815. }); err != nil {
  816. return fmt.Errorf("Push: %v", err)
  817. }
  818. return nil
  819. }
  820. // AddToTaskQueue adds itself to pull request test task queue.
  821. func (pr *PullRequest) AddToTaskQueue() {
  822. go pullRequestQueue.AddFunc(pr.ID, func() {
  823. pr.Status = PullRequestStatusChecking
  824. if err := pr.UpdateCols("status"); err != nil {
  825. log.Error("AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
  826. }
  827. })
  828. }
  829. // checkAndUpdateStatus checks if pull request is possible to leaving checking status,
  830. // and set to be either conflict or mergeable.
  831. func (pr *PullRequest) checkAndUpdateStatus() {
  832. // Status is not changed to conflict means mergeable.
  833. if pr.Status == PullRequestStatusChecking {
  834. pr.Status = PullRequestStatusMergeable
  835. }
  836. // Make sure there is no waiting test to process before leaving the checking status.
  837. if !pullRequestQueue.Exist(pr.ID) {
  838. if err := pr.UpdateCols("status, conflicted_files"); err != nil {
  839. log.Error("Update[%d]: %v", pr.ID, err)
  840. }
  841. }
  842. }
  843. // IsWorkInProgress determine if the Pull Request is a Work In Progress by its title
  844. func (pr *PullRequest) IsWorkInProgress() bool {
  845. if err := pr.LoadIssue(); err != nil {
  846. log.Error("LoadIssue: %v", err)
  847. return false
  848. }
  849. for _, prefix := range setting.Repository.PullRequest.WorkInProgressPrefixes {
  850. if strings.HasPrefix(strings.ToUpper(pr.Issue.Title), prefix) {
  851. return true
  852. }
  853. }
  854. return false
  855. }
  856. // IsFilesConflicted determines if the Pull Request has changes conflicting with the target branch.
  857. func (pr *PullRequest) IsFilesConflicted() bool {
  858. return len(pr.ConflictedFiles) > 0
  859. }
  860. // GetWorkInProgressPrefix returns the prefix used to mark the pull request as a work in progress.
  861. // It returns an empty string when none were found
  862. func (pr *PullRequest) GetWorkInProgressPrefix() string {
  863. if err := pr.LoadIssue(); err != nil {
  864. log.Error("LoadIssue: %v", err)
  865. return ""
  866. }
  867. for _, prefix := range setting.Repository.PullRequest.WorkInProgressPrefixes {
  868. if strings.HasPrefix(strings.ToUpper(pr.Issue.Title), prefix) {
  869. return pr.Issue.Title[0:len(prefix)]
  870. }
  871. }
  872. return ""
  873. }