You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

pull.go 34 kB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106
  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. "fmt"
  7. "io/ioutil"
  8. "os"
  9. "path"
  10. "path/filepath"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "code.gitea.io/git"
  15. "code.gitea.io/gitea/modules/base"
  16. "code.gitea.io/gitea/modules/log"
  17. "code.gitea.io/gitea/modules/process"
  18. "code.gitea.io/gitea/modules/setting"
  19. "code.gitea.io/gitea/modules/sync"
  20. api "code.gitea.io/sdk/gitea"
  21. "github.com/Unknwon/com"
  22. "github.com/go-xorm/xorm"
  23. )
  24. var pullRequestQueue = sync.NewUniqueQueue(setting.Repository.PullRequestQueueLength)
  25. // PullRequestType defines pull request type
  26. type PullRequestType int
  27. // Enumerate all the pull request types
  28. const (
  29. PullRequestGitea PullRequestType = iota
  30. PullRequestGit
  31. )
  32. // PullRequestStatus defines pull request status
  33. type PullRequestStatus int
  34. // Enumerate all the pull request status
  35. const (
  36. PullRequestStatusConflict PullRequestStatus = iota
  37. PullRequestStatusChecking
  38. PullRequestStatusMergeable
  39. PullRequestStatusManuallyMerged
  40. )
  41. // PullRequest represents relation between pull request and repositories.
  42. type PullRequest struct {
  43. ID int64 `xorm:"pk autoincr"`
  44. Type PullRequestType
  45. Status PullRequestStatus
  46. IssueID int64 `xorm:"INDEX"`
  47. Issue *Issue `xorm:"-"`
  48. Index int64
  49. HeadRepoID int64 `xorm:"INDEX"`
  50. HeadRepo *Repository `xorm:"-"`
  51. BaseRepoID int64 `xorm:"INDEX"`
  52. BaseRepo *Repository `xorm:"-"`
  53. HeadUserName string
  54. HeadBranch string
  55. BaseBranch string
  56. MergeBase string `xorm:"VARCHAR(40)"`
  57. HasMerged bool `xorm:"INDEX"`
  58. MergedCommitID string `xorm:"VARCHAR(40)"`
  59. MergerID int64 `xorm:"INDEX"`
  60. Merger *User `xorm:"-"`
  61. Merged time.Time `xorm:"-"`
  62. MergedUnix int64 `xorm:"INDEX"`
  63. }
  64. // BeforeUpdate is invoked from XORM before updating an object of this type.
  65. func (pr *PullRequest) BeforeUpdate() {
  66. pr.MergedUnix = pr.Merged.Unix()
  67. }
  68. // AfterSet is invoked from XORM after setting the value of a field of this object.
  69. // Note: don't try to get Issue because will end up recursive querying.
  70. func (pr *PullRequest) AfterSet(colName string, _ xorm.Cell) {
  71. switch colName {
  72. case "merged_unix":
  73. if !pr.HasMerged {
  74. return
  75. }
  76. pr.Merged = time.Unix(pr.MergedUnix, 0).Local()
  77. }
  78. }
  79. // Note: don't try to get Issue because will end up recursive querying.
  80. func (pr *PullRequest) loadAttributes(e Engine) (err error) {
  81. if pr.HasMerged && pr.Merger == nil {
  82. pr.Merger, err = getUserByID(e, pr.MergerID)
  83. if IsErrUserNotExist(err) {
  84. pr.MergerID = -1
  85. pr.Merger = NewGhostUser()
  86. } else if err != nil {
  87. return fmt.Errorf("getUserByID [%d]: %v", pr.MergerID, err)
  88. }
  89. }
  90. return nil
  91. }
  92. // LoadAttributes loads pull request attributes from database
  93. func (pr *PullRequest) LoadAttributes() error {
  94. return pr.loadAttributes(x)
  95. }
  96. // LoadIssue loads issue information from database
  97. func (pr *PullRequest) LoadIssue() (err error) {
  98. return pr.loadIssue(x)
  99. }
  100. func (pr *PullRequest) loadIssue(e Engine) (err error) {
  101. if pr.Issue != nil {
  102. return nil
  103. }
  104. pr.Issue, err = getIssueByID(e, pr.IssueID)
  105. return err
  106. }
  107. // APIFormat assumes following fields have been assigned with valid values:
  108. // Required - Issue
  109. // Optional - Merger
  110. func (pr *PullRequest) APIFormat() *api.PullRequest {
  111. var (
  112. baseBranch *Branch
  113. headBranch *Branch
  114. baseCommit *git.Commit
  115. headCommit *git.Commit
  116. err error
  117. )
  118. apiIssue := pr.Issue.APIFormat()
  119. if pr.BaseRepo == nil {
  120. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  121. if err != nil {
  122. log.Error(log.ERROR, "GetRepositoryById[%d]: %v", pr.ID, err)
  123. return nil
  124. }
  125. }
  126. if pr.HeadRepo == nil {
  127. pr.HeadRepo, err = GetRepositoryByID(pr.HeadRepoID)
  128. if err != nil {
  129. log.Error(log.ERROR, "GetRepositoryById[%d]: %v", pr.ID, err)
  130. return nil
  131. }
  132. }
  133. if baseBranch, err = pr.BaseRepo.GetBranch(pr.BaseBranch); err != nil {
  134. return nil
  135. }
  136. if baseCommit, err = baseBranch.GetCommit(); err != nil {
  137. return nil
  138. }
  139. if headBranch, err = pr.HeadRepo.GetBranch(pr.HeadBranch); err != nil {
  140. return nil
  141. }
  142. if headCommit, err = headBranch.GetCommit(); err != nil {
  143. return nil
  144. }
  145. apiBaseBranchInfo := &api.PRBranchInfo{
  146. Name: pr.BaseBranch,
  147. Ref: pr.BaseBranch,
  148. Sha: baseCommit.ID.String(),
  149. RepoID: pr.BaseRepoID,
  150. Repository: pr.BaseRepo.APIFormat(AccessModeNone),
  151. }
  152. apiHeadBranchInfo := &api.PRBranchInfo{
  153. Name: pr.HeadBranch,
  154. Ref: pr.HeadBranch,
  155. Sha: headCommit.ID.String(),
  156. RepoID: pr.HeadRepoID,
  157. Repository: pr.HeadRepo.APIFormat(AccessModeNone),
  158. }
  159. apiPullRequest := &api.PullRequest{
  160. ID: pr.ID,
  161. Index: pr.Index,
  162. Poster: apiIssue.Poster,
  163. Title: apiIssue.Title,
  164. Body: apiIssue.Body,
  165. Labels: apiIssue.Labels,
  166. Milestone: apiIssue.Milestone,
  167. Assignee: apiIssue.Assignee,
  168. State: apiIssue.State,
  169. Comments: apiIssue.Comments,
  170. HTMLURL: pr.Issue.HTMLURL(),
  171. DiffURL: pr.Issue.DiffURL(),
  172. PatchURL: pr.Issue.PatchURL(),
  173. HasMerged: pr.HasMerged,
  174. Base: apiBaseBranchInfo,
  175. Head: apiHeadBranchInfo,
  176. MergeBase: pr.MergeBase,
  177. }
  178. if pr.Status != PullRequestStatusChecking {
  179. mergeable := pr.Status != PullRequestStatusConflict
  180. apiPullRequest.Mergeable = mergeable
  181. }
  182. if pr.HasMerged {
  183. apiPullRequest.Merged = &pr.Merged
  184. apiPullRequest.MergedCommitID = &pr.MergedCommitID
  185. apiPullRequest.MergedBy = pr.Merger.APIFormat()
  186. }
  187. return apiPullRequest
  188. }
  189. func (pr *PullRequest) getHeadRepo(e Engine) (err error) {
  190. pr.HeadRepo, err = getRepositoryByID(e, pr.HeadRepoID)
  191. if err != nil && !IsErrRepoNotExist(err) {
  192. return fmt.Errorf("getRepositoryByID(head): %v", err)
  193. }
  194. return nil
  195. }
  196. // GetHeadRepo loads the head repository
  197. func (pr *PullRequest) GetHeadRepo() error {
  198. return pr.getHeadRepo(x)
  199. }
  200. // GetBaseRepo loads the target repository
  201. func (pr *PullRequest) GetBaseRepo() (err error) {
  202. if pr.BaseRepo != nil {
  203. return nil
  204. }
  205. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  206. if err != nil {
  207. return fmt.Errorf("GetRepositoryByID(base): %v", err)
  208. }
  209. return nil
  210. }
  211. // IsChecking returns true if this pull request is still checking conflict.
  212. func (pr *PullRequest) IsChecking() bool {
  213. return pr.Status == PullRequestStatusChecking
  214. }
  215. // CanAutoMerge returns true if this pull request can be merged automatically.
  216. func (pr *PullRequest) CanAutoMerge() bool {
  217. return pr.Status == PullRequestStatusMergeable
  218. }
  219. // Merge merges pull request to base repository.
  220. // FIXME: add repoWorkingPull make sure two merges does not happen at same time.
  221. func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository) (err error) {
  222. if err = pr.GetHeadRepo(); err != nil {
  223. return fmt.Errorf("GetHeadRepo: %v", err)
  224. } else if err = pr.GetBaseRepo(); err != nil {
  225. return fmt.Errorf("GetBaseRepo: %v", err)
  226. }
  227. defer func() {
  228. go HookQueue.Add(pr.BaseRepo.ID)
  229. go AddTestPullRequestTask(doer, pr.BaseRepo.ID, pr.BaseBranch, false)
  230. }()
  231. headRepoPath := RepoPath(pr.HeadUserName, pr.HeadRepo.Name)
  232. headGitRepo, err := git.OpenRepository(headRepoPath)
  233. if err != nil {
  234. return fmt.Errorf("OpenRepository: %v", err)
  235. }
  236. // Clone base repo.
  237. tmpBasePath := path.Join(setting.AppDataPath, "tmp/repos", com.ToStr(time.Now().Nanosecond())+".git")
  238. if err := os.MkdirAll(path.Dir(tmpBasePath), os.ModePerm); err != nil {
  239. return fmt.Errorf("Failed to create dir %s: %v", tmpBasePath, err)
  240. }
  241. defer os.RemoveAll(path.Dir(tmpBasePath))
  242. var stderr string
  243. if _, stderr, err = process.GetManager().ExecTimeout(5*time.Minute,
  244. fmt.Sprintf("PullRequest.Merge (git clone): %s", tmpBasePath),
  245. "git", "clone", baseGitRepo.Path, tmpBasePath); err != nil {
  246. return fmt.Errorf("git clone: %s", stderr)
  247. }
  248. // Check out base branch.
  249. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  250. fmt.Sprintf("PullRequest.Merge (git checkout): %s", tmpBasePath),
  251. "git", "checkout", pr.BaseBranch); err != nil {
  252. return fmt.Errorf("git checkout: %s", stderr)
  253. }
  254. // Add head repo remote.
  255. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  256. fmt.Sprintf("PullRequest.Merge (git remote add): %s", tmpBasePath),
  257. "git", "remote", "add", "head_repo", headRepoPath); err != nil {
  258. return fmt.Errorf("git remote add [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  259. }
  260. // Merge commits.
  261. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  262. fmt.Sprintf("PullRequest.Merge (git fetch): %s", tmpBasePath),
  263. "git", "fetch", "head_repo"); err != nil {
  264. return fmt.Errorf("git fetch [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  265. }
  266. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  267. fmt.Sprintf("PullRequest.Merge (git merge --no-ff --no-commit): %s", tmpBasePath),
  268. "git", "merge", "--no-ff", "--no-commit", "head_repo/"+pr.HeadBranch); err != nil {
  269. return fmt.Errorf("git merge --no-ff --no-commit [%s]: %v - %s", tmpBasePath, err, stderr)
  270. }
  271. sig := doer.NewGitSig()
  272. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  273. fmt.Sprintf("PullRequest.Merge (git merge): %s", tmpBasePath),
  274. "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  275. "-m", fmt.Sprintf("Merge branch '%s' of %s/%s into %s", pr.HeadBranch, pr.HeadUserName, pr.HeadRepo.Name, pr.BaseBranch)); err != nil {
  276. return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, stderr)
  277. }
  278. // Push back to upstream.
  279. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  280. fmt.Sprintf("PullRequest.Merge (git push): %s", tmpBasePath),
  281. "git", "push", baseGitRepo.Path, pr.BaseBranch); err != nil {
  282. return fmt.Errorf("git push: %s", stderr)
  283. }
  284. pr.MergedCommitID, err = headGitRepo.GetBranchCommitID(pr.HeadBranch)
  285. if err != nil {
  286. return fmt.Errorf("GetBranchCommit: %v", err)
  287. }
  288. pr.Merged = time.Now()
  289. pr.Merger = doer
  290. pr.MergerID = doer.ID
  291. if err = pr.setMerged(); err != nil {
  292. log.Error(4, "setMerged [%d]: %v", pr.ID, err)
  293. }
  294. if err = MergePullRequestAction(doer, pr.Issue.Repo, pr.Issue); err != nil {
  295. log.Error(4, "MergePullRequestAction [%d]: %v", pr.ID, err)
  296. }
  297. // Reload pull request information.
  298. if err = pr.LoadAttributes(); err != nil {
  299. log.Error(4, "LoadAttributes: %v", err)
  300. return nil
  301. }
  302. if err = PrepareWebhooks(pr.Issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  303. Action: api.HookIssueClosed,
  304. Index: pr.Index,
  305. PullRequest: pr.APIFormat(),
  306. Repository: pr.Issue.Repo.APIFormat(AccessModeNone),
  307. Sender: doer.APIFormat(),
  308. }); err != nil {
  309. log.Error(4, "PrepareWebhooks: %v", err)
  310. return nil
  311. }
  312. l, err := headGitRepo.CommitsBetweenIDs(pr.MergedCommitID, pr.MergeBase)
  313. if err != nil {
  314. log.Error(4, "CommitsBetweenIDs: %v", err)
  315. return nil
  316. }
  317. // TODO: when squash commits, no need to append merge commit.
  318. // It is possible that head branch is not fully sync with base branch for merge commits,
  319. // so we need to get latest head commit and append merge commit manually
  320. // to avoid strange diff commits produced.
  321. mergeCommit, err := baseGitRepo.GetBranchCommit(pr.BaseBranch)
  322. if err != nil {
  323. log.Error(4, "GetBranchCommit: %v", err)
  324. return nil
  325. }
  326. l.PushFront(mergeCommit)
  327. p := &api.PushPayload{
  328. Ref: git.BranchPrefix + pr.BaseBranch,
  329. Before: pr.MergeBase,
  330. After: pr.MergedCommitID,
  331. CompareURL: setting.AppURL + pr.BaseRepo.ComposeCompareURL(pr.MergeBase, pr.MergedCommitID),
  332. Commits: ListToPushCommits(l).ToAPIPayloadCommits(pr.BaseRepo.HTMLURL()),
  333. Repo: pr.BaseRepo.APIFormat(AccessModeNone),
  334. Pusher: pr.HeadRepo.MustOwner().APIFormat(),
  335. Sender: doer.APIFormat(),
  336. }
  337. if err = PrepareWebhooks(pr.BaseRepo, HookEventPush, p); err != nil {
  338. return fmt.Errorf("PrepareWebhooks: %v", err)
  339. }
  340. return nil
  341. }
  342. // setMerged sets a pull request to merged and closes the corresponding issue
  343. func (pr *PullRequest) setMerged() (err error) {
  344. if pr.HasMerged {
  345. return fmt.Errorf("PullRequest[%d] already merged", pr.Index)
  346. }
  347. if pr.MergedCommitID == "" || pr.Merged.IsZero() || pr.Merger == nil {
  348. return fmt.Errorf("Unable to merge PullRequest[%d], some required fields are empty", pr.Index)
  349. }
  350. pr.HasMerged = true
  351. sess := x.NewSession()
  352. defer sessionRelease(sess)
  353. if err = sess.Begin(); err != nil {
  354. return err
  355. }
  356. if err = pr.loadIssue(sess); err != nil {
  357. return err
  358. }
  359. if err = pr.Issue.loadRepo(sess); err != nil {
  360. return err
  361. }
  362. if err = pr.Issue.Repo.getOwner(sess); err != nil {
  363. return err
  364. }
  365. if err = pr.Issue.changeStatus(sess, pr.Merger, pr.Issue.Repo, true); err != nil {
  366. return fmt.Errorf("Issue.changeStatus: %v", err)
  367. }
  368. if _, err = sess.Id(pr.ID).AllCols().Update(pr); err != nil {
  369. return fmt.Errorf("update pull request: %v", err)
  370. }
  371. if err = sess.Commit(); err != nil {
  372. return fmt.Errorf("Commit: %v", err)
  373. }
  374. return nil
  375. }
  376. // manuallyMerged checks if a pull request got manually merged
  377. // When a pull request got manually merged mark the pull request as merged
  378. func (pr *PullRequest) manuallyMerged() bool {
  379. commit, err := pr.getMergeCommit()
  380. if err != nil {
  381. log.Error(4, "PullRequest[%d].getMergeCommit: %v", pr.ID, err)
  382. return false
  383. }
  384. if commit != nil {
  385. pr.MergedCommitID = commit.ID.String()
  386. pr.Merged = commit.Author.When
  387. pr.Status = PullRequestStatusManuallyMerged
  388. merger, _ := GetUserByEmail(commit.Author.Email)
  389. // When the commit author is unknown set the BaseRepo owner as merger
  390. if merger == nil {
  391. if pr.BaseRepo.Owner == nil {
  392. if err = pr.BaseRepo.getOwner(x); err != nil {
  393. log.Error(4, "BaseRepo.getOwner[%d]: %v", pr.ID, err)
  394. return false
  395. }
  396. }
  397. merger = pr.BaseRepo.Owner
  398. }
  399. pr.Merger = merger
  400. pr.MergerID = merger.ID
  401. if err = pr.setMerged(); err != nil {
  402. log.Error(4, "PullRequest[%d].setMerged : %v", pr.ID, err)
  403. return false
  404. }
  405. 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())
  406. return true
  407. }
  408. return false
  409. }
  410. // getMergeCommit checks if a pull request got merged
  411. // Returns the git.Commit of the pull request if merged
  412. func (pr *PullRequest) getMergeCommit() (*git.Commit, error) {
  413. if pr.BaseRepo == nil {
  414. var err error
  415. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  416. if err != nil {
  417. return nil, fmt.Errorf("GetRepositoryByID: %v", err)
  418. }
  419. }
  420. indexTmpPath := filepath.Join(os.TempDir(), "gitea-"+pr.BaseRepo.Name+"-"+strconv.Itoa(time.Now().Nanosecond()))
  421. defer os.Remove(indexTmpPath)
  422. headFile := fmt.Sprintf("refs/pull/%d/head", pr.Index)
  423. // Check if a pull request is merged into BaseBranch
  424. _, stderr, err := process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("isMerged (git merge-base --is-ancestor): %d", pr.BaseRepo.ID),
  425. []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()},
  426. "git", "merge-base", "--is-ancestor", headFile, pr.BaseBranch)
  427. if err != nil {
  428. // Errors are signaled by a non-zero status that is not 1
  429. if err.Error() == "exit status 1" {
  430. return nil, nil
  431. }
  432. return nil, fmt.Errorf("git merge-base --is-ancestor: %v %v", stderr, err)
  433. }
  434. // We can ignore this error since we only get here when there's a valid commit in headFile
  435. commitID, _ := ioutil.ReadFile(pr.BaseRepo.RepoPath() + "/" + headFile)
  436. cmd := string(commitID)[:40] + ".." + pr.BaseBranch
  437. // Get the commit from BaseBranch where the pull request got merged
  438. mergeCommit, stderr, err := process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("isMerged (git rev-list --ancestry-path --merges --reverse): %d", pr.BaseRepo.ID),
  439. []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()},
  440. "git", "rev-list", "--ancestry-path", "--merges", "--reverse", cmd)
  441. if err != nil {
  442. return nil, fmt.Errorf("git rev-list --ancestry-path --merges --reverse: %v %v", stderr, err)
  443. }
  444. gitRepo, err := git.OpenRepository(pr.BaseRepo.RepoPath())
  445. if err != nil {
  446. return nil, fmt.Errorf("OpenRepository: %v", err)
  447. }
  448. commit, err := gitRepo.GetCommit(mergeCommit[:40])
  449. if err != nil {
  450. return nil, fmt.Errorf("GetCommit: %v", err)
  451. }
  452. return commit, nil
  453. }
  454. // patchConflicts is a list of conflict description from Git.
  455. var patchConflicts = []string{
  456. "patch does not apply",
  457. "already exists in working directory",
  458. "unrecognized input",
  459. "error:",
  460. }
  461. // testPatch checks if patch can be merged to base repository without conflict.
  462. func (pr *PullRequest) testPatch() (err error) {
  463. if pr.BaseRepo == nil {
  464. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  465. if err != nil {
  466. return fmt.Errorf("GetRepositoryByID: %v", err)
  467. }
  468. }
  469. patchPath, err := pr.BaseRepo.PatchPath(pr.Index)
  470. if err != nil {
  471. return fmt.Errorf("BaseRepo.PatchPath: %v", err)
  472. }
  473. // Fast fail if patch does not exist, this assumes data is corrupted.
  474. if !com.IsFile(patchPath) {
  475. log.Trace("PullRequest[%d].testPatch: ignored corrupted data", pr.ID)
  476. return nil
  477. }
  478. repoWorkingPool.CheckIn(com.ToStr(pr.BaseRepoID))
  479. defer repoWorkingPool.CheckOut(com.ToStr(pr.BaseRepoID))
  480. log.Trace("PullRequest[%d].testPatch (patchPath): %s", pr.ID, patchPath)
  481. pr.Status = PullRequestStatusChecking
  482. indexTmpPath := filepath.Join(os.TempDir(), "gitea-"+pr.BaseRepo.Name+"-"+strconv.Itoa(time.Now().Nanosecond()))
  483. defer os.Remove(indexTmpPath)
  484. var stderr string
  485. _, stderr, err = process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("testPatch (git read-tree): %d", pr.BaseRepo.ID),
  486. []string{"GIT_DIR=" + pr.BaseRepo.RepoPath(), "GIT_INDEX_FILE=" + indexTmpPath},
  487. "git", "read-tree", pr.BaseBranch)
  488. if err != nil {
  489. return fmt.Errorf("git read-tree --index-output=%s %s: %v - %s", indexTmpPath, pr.BaseBranch, err, stderr)
  490. }
  491. _, stderr, err = process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("testPatch (git apply --check): %d", pr.BaseRepo.ID),
  492. []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()},
  493. "git", "apply", "--check", "--cached", patchPath)
  494. if err != nil {
  495. for i := range patchConflicts {
  496. if strings.Contains(stderr, patchConflicts[i]) {
  497. log.Trace("PullRequest[%d].testPatch (apply): has conflict", pr.ID)
  498. fmt.Println(stderr)
  499. pr.Status = PullRequestStatusConflict
  500. return nil
  501. }
  502. }
  503. return fmt.Errorf("git apply --check: %v - %s", err, stderr)
  504. }
  505. return nil
  506. }
  507. // NewPullRequest creates new pull request with labels for repository.
  508. func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest, patch []byte) (err error) {
  509. sess := x.NewSession()
  510. defer sessionRelease(sess)
  511. if err = sess.Begin(); err != nil {
  512. return err
  513. }
  514. if err = newIssue(sess, pull.Poster, NewIssueOptions{
  515. Repo: repo,
  516. Issue: pull,
  517. LabelIDs: labelIDs,
  518. Attachments: uuids,
  519. IsPull: true,
  520. }); err != nil {
  521. return fmt.Errorf("newIssue: %v", err)
  522. }
  523. pr.Index = pull.Index
  524. if err = repo.SavePatch(pr.Index, patch); err != nil {
  525. return fmt.Errorf("SavePatch: %v", err)
  526. }
  527. pr.BaseRepo = repo
  528. if err = pr.testPatch(); err != nil {
  529. return fmt.Errorf("testPatch: %v", err)
  530. }
  531. // No conflict appears after test means mergeable.
  532. if pr.Status == PullRequestStatusChecking {
  533. pr.Status = PullRequestStatusMergeable
  534. }
  535. pr.IssueID = pull.ID
  536. if _, err = sess.Insert(pr); err != nil {
  537. return fmt.Errorf("insert pull repo: %v", err)
  538. }
  539. if err = sess.Commit(); err != nil {
  540. return fmt.Errorf("Commit: %v", err)
  541. }
  542. if err = NotifyWatchers(&Action{
  543. ActUserID: pull.Poster.ID,
  544. ActUserName: pull.Poster.Name,
  545. OpType: ActionCreatePullRequest,
  546. Content: fmt.Sprintf("%d|%s", pull.Index, pull.Title),
  547. RepoID: repo.ID,
  548. RepoUserName: repo.Owner.Name,
  549. RepoName: repo.Name,
  550. IsPrivate: repo.IsPrivate,
  551. }); err != nil {
  552. log.Error(4, "NotifyWatchers: %v", err)
  553. } else if err = pull.MailParticipants(); err != nil {
  554. log.Error(4, "MailParticipants: %v", err)
  555. }
  556. pr.Issue = pull
  557. pull.PullRequest = pr
  558. if err = PrepareWebhooks(repo, HookEventPullRequest, &api.PullRequestPayload{
  559. Action: api.HookIssueOpened,
  560. Index: pull.Index,
  561. PullRequest: pr.APIFormat(),
  562. Repository: repo.APIFormat(AccessModeNone),
  563. Sender: pull.Poster.APIFormat(),
  564. }); err != nil {
  565. log.Error(4, "PrepareWebhooks: %v", err)
  566. }
  567. go HookQueue.Add(repo.ID)
  568. return nil
  569. }
  570. // PullRequestsOptions holds the options for PRs
  571. type PullRequestsOptions struct {
  572. Page int
  573. State string
  574. SortType string
  575. Labels []string
  576. MilestoneID int64
  577. }
  578. func listPullRequestStatement(baseRepoID int64, opts *PullRequestsOptions) (*xorm.Session, error) {
  579. sess := x.Where("pull_request.base_repo_id=?", baseRepoID)
  580. sess.Join("INNER", "issue", "pull_request.issue_id = issue.id")
  581. switch opts.State {
  582. case "closed", "open":
  583. sess.And("issue.is_closed=?", opts.State == "closed")
  584. }
  585. sortIssuesSession(sess, opts.SortType)
  586. if labelIDs, err := base.StringsToInt64s(opts.Labels); err != nil {
  587. return nil, err
  588. } else if len(labelIDs) > 0 {
  589. sess.Join("INNER", "issue_label", "issue.id = issue_label.issue_id").
  590. In("issue_label.label_id", labelIDs)
  591. }
  592. if opts.MilestoneID > 0 {
  593. sess.And("issue.milestone_id=?", opts.MilestoneID)
  594. }
  595. return sess, nil
  596. }
  597. // PullRequests returns all pull requests for a base Repo by the given conditions
  598. func PullRequests(baseRepoID int64, opts *PullRequestsOptions) ([]*PullRequest, int64, error) {
  599. if opts.Page <= 0 {
  600. opts.Page = 1
  601. }
  602. countSession, err := listPullRequestStatement(baseRepoID, opts)
  603. if err != nil {
  604. log.Error(4, "listPullRequestStatement", err)
  605. return nil, 0, err
  606. }
  607. maxResults, err := countSession.Count(new(PullRequest))
  608. if err != nil {
  609. log.Error(4, "Count PRs", err)
  610. return nil, maxResults, err
  611. }
  612. prs := make([]*PullRequest, 0, ItemsPerPage)
  613. findSession, err := listPullRequestStatement(baseRepoID, opts)
  614. if err != nil {
  615. log.Error(4, "listPullRequestStatement", err)
  616. return nil, maxResults, err
  617. }
  618. findSession.Limit(ItemsPerPage, (opts.Page-1)*ItemsPerPage)
  619. return prs, maxResults, findSession.Find(&prs)
  620. }
  621. // GetUnmergedPullRequest returns a pull request that is open and has not been merged
  622. // by given head/base and repo/branch.
  623. func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string) (*PullRequest, error) {
  624. pr := new(PullRequest)
  625. has, err := x.
  626. Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  627. headRepoID, headBranch, baseRepoID, baseBranch, false, false).
  628. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  629. Get(pr)
  630. if err != nil {
  631. return nil, err
  632. } else if !has {
  633. return nil, ErrPullRequestNotExist{0, 0, headRepoID, baseRepoID, headBranch, baseBranch}
  634. }
  635. return pr, nil
  636. }
  637. // GetUnmergedPullRequestsByHeadInfo returns all pull requests that are open and has not been merged
  638. // by given head information (repo and branch).
  639. func GetUnmergedPullRequestsByHeadInfo(repoID int64, branch string) ([]*PullRequest, error) {
  640. prs := make([]*PullRequest, 0, 2)
  641. return prs, x.
  642. Where("head_repo_id = ? AND head_branch = ? AND has_merged = ? AND issue.is_closed = ?",
  643. repoID, branch, false, false).
  644. Join("INNER", "issue", "issue.id = pull_request.issue_id").
  645. Find(&prs)
  646. }
  647. // GetUnmergedPullRequestsByBaseInfo returns all pull requests that are open and has not been merged
  648. // by given base information (repo and branch).
  649. func GetUnmergedPullRequestsByBaseInfo(repoID int64, branch string) ([]*PullRequest, error) {
  650. prs := make([]*PullRequest, 0, 2)
  651. return prs, x.
  652. Where("base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  653. repoID, branch, false, false).
  654. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  655. Find(&prs)
  656. }
  657. // GetPullRequestByIndex returns a pull request by the given index
  658. func GetPullRequestByIndex(repoID int64, index int64) (*PullRequest, error) {
  659. pr := &PullRequest{
  660. BaseRepoID: repoID,
  661. Index: index,
  662. }
  663. has, err := x.Get(pr)
  664. if err != nil {
  665. return nil, err
  666. } else if !has {
  667. return nil, ErrPullRequestNotExist{0, 0, 0, repoID, "", ""}
  668. }
  669. if err = pr.LoadAttributes(); err != nil {
  670. return nil, err
  671. }
  672. if err = pr.LoadIssue(); err != nil {
  673. return nil, err
  674. }
  675. return pr, nil
  676. }
  677. func getPullRequestByID(e Engine, id int64) (*PullRequest, error) {
  678. pr := new(PullRequest)
  679. has, err := e.Id(id).Get(pr)
  680. if err != nil {
  681. return nil, err
  682. } else if !has {
  683. return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""}
  684. }
  685. return pr, pr.loadAttributes(e)
  686. }
  687. // GetPullRequestByID returns a pull request by given ID.
  688. func GetPullRequestByID(id int64) (*PullRequest, error) {
  689. return getPullRequestByID(x, id)
  690. }
  691. func getPullRequestByIssueID(e Engine, issueID int64) (*PullRequest, error) {
  692. pr := &PullRequest{
  693. IssueID: issueID,
  694. }
  695. has, err := e.Get(pr)
  696. if err != nil {
  697. return nil, err
  698. } else if !has {
  699. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  700. }
  701. return pr, pr.loadAttributes(e)
  702. }
  703. // GetPullRequestByIssueID returns pull request by given issue ID.
  704. func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) {
  705. return getPullRequestByIssueID(x, issueID)
  706. }
  707. // Update updates all fields of pull request.
  708. func (pr *PullRequest) Update() error {
  709. _, err := x.Id(pr.ID).AllCols().Update(pr)
  710. return err
  711. }
  712. // UpdateCols updates specific fields of pull request.
  713. func (pr *PullRequest) UpdateCols(cols ...string) error {
  714. _, err := x.Id(pr.ID).Cols(cols...).Update(pr)
  715. return err
  716. }
  717. // UpdatePatch generates and saves a new patch.
  718. func (pr *PullRequest) UpdatePatch() (err error) {
  719. if err = pr.GetHeadRepo(); err != nil {
  720. return fmt.Errorf("GetHeadRepo: %v", err)
  721. } else if pr.HeadRepo == nil {
  722. log.Trace("PullRequest[%d].UpdatePatch: ignored cruppted data", pr.ID)
  723. return nil
  724. }
  725. if err = pr.GetBaseRepo(); err != nil {
  726. return fmt.Errorf("GetBaseRepo: %v", err)
  727. }
  728. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  729. if err != nil {
  730. return fmt.Errorf("OpenRepository: %v", err)
  731. }
  732. // Add a temporary remote.
  733. tmpRemote := com.ToStr(time.Now().UnixNano())
  734. if err = headGitRepo.AddRemote(tmpRemote, RepoPath(pr.BaseRepo.MustOwner().Name, pr.BaseRepo.Name), true); err != nil {
  735. return fmt.Errorf("AddRemote: %v", err)
  736. }
  737. defer func() {
  738. headGitRepo.RemoveRemote(tmpRemote)
  739. }()
  740. remoteBranch := "remotes/" + tmpRemote + "/" + pr.BaseBranch
  741. pr.MergeBase, err = headGitRepo.GetMergeBase(remoteBranch, pr.HeadBranch)
  742. if err != nil {
  743. return fmt.Errorf("GetMergeBase: %v", err)
  744. } else if err = pr.Update(); err != nil {
  745. return fmt.Errorf("Update: %v", err)
  746. }
  747. patch, err := headGitRepo.GetPatch(pr.MergeBase, pr.HeadBranch)
  748. if err != nil {
  749. return fmt.Errorf("GetPatch: %v", err)
  750. }
  751. if err = pr.BaseRepo.SavePatch(pr.Index, patch); err != nil {
  752. return fmt.Errorf("BaseRepo.SavePatch: %v", err)
  753. }
  754. return nil
  755. }
  756. // PushToBaseRepo pushes commits from branches of head repository to
  757. // corresponding branches of base repository.
  758. // FIXME: Only push branches that are actually updates?
  759. func (pr *PullRequest) PushToBaseRepo() (err error) {
  760. log.Trace("PushToBaseRepo[%d]: pushing commits to base repo 'refs/pull/%d/head'", pr.BaseRepoID, pr.Index)
  761. headRepoPath := pr.HeadRepo.RepoPath()
  762. headGitRepo, err := git.OpenRepository(headRepoPath)
  763. if err != nil {
  764. return fmt.Errorf("OpenRepository: %v", err)
  765. }
  766. tmpRemoteName := fmt.Sprintf("tmp-pull-%d", pr.ID)
  767. if err = headGitRepo.AddRemote(tmpRemoteName, pr.BaseRepo.RepoPath(), false); err != nil {
  768. return fmt.Errorf("headGitRepo.AddRemote: %v", err)
  769. }
  770. // Make sure to remove the remote even if the push fails
  771. defer headGitRepo.RemoveRemote(tmpRemoteName)
  772. headFile := fmt.Sprintf("refs/pull/%d/head", pr.Index)
  773. // Remove head in case there is a conflict.
  774. file := path.Join(pr.BaseRepo.RepoPath(), headFile)
  775. _ = os.Remove(file)
  776. if err = git.Push(headRepoPath, tmpRemoteName, fmt.Sprintf("%s:%s", pr.HeadBranch, headFile)); err != nil {
  777. return fmt.Errorf("Push: %v", err)
  778. }
  779. return nil
  780. }
  781. // AddToTaskQueue adds itself to pull request test task queue.
  782. func (pr *PullRequest) AddToTaskQueue() {
  783. go pullRequestQueue.AddFunc(pr.ID, func() {
  784. pr.Status = PullRequestStatusChecking
  785. if err := pr.UpdateCols("status"); err != nil {
  786. log.Error(5, "AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
  787. }
  788. })
  789. }
  790. // PullRequestList defines a list of pull requests
  791. type PullRequestList []*PullRequest
  792. func (prs PullRequestList) loadAttributes(e Engine) error {
  793. if len(prs) == 0 {
  794. return nil
  795. }
  796. // Load issues.
  797. issueIDs := make([]int64, 0, len(prs))
  798. for i := range prs {
  799. issueIDs = append(issueIDs, prs[i].IssueID)
  800. }
  801. issues := make([]*Issue, 0, len(issueIDs))
  802. if err := e.
  803. Where("id > 0").
  804. In("id", issueIDs).
  805. Find(&issues); err != nil {
  806. return fmt.Errorf("find issues: %v", err)
  807. }
  808. set := make(map[int64]*Issue)
  809. for i := range issues {
  810. set[issues[i].ID] = issues[i]
  811. }
  812. for i := range prs {
  813. prs[i].Issue = set[prs[i].IssueID]
  814. }
  815. return nil
  816. }
  817. // LoadAttributes load all the prs attributes
  818. func (prs PullRequestList) LoadAttributes() error {
  819. return prs.loadAttributes(x)
  820. }
  821. func addHeadRepoTasks(prs []*PullRequest) {
  822. for _, pr := range prs {
  823. log.Trace("addHeadRepoTasks[%d]: composing new test task", pr.ID)
  824. if err := pr.UpdatePatch(); err != nil {
  825. log.Error(4, "UpdatePatch: %v", err)
  826. continue
  827. } else if err := pr.PushToBaseRepo(); err != nil {
  828. log.Error(4, "PushToBaseRepo: %v", err)
  829. continue
  830. }
  831. pr.AddToTaskQueue()
  832. }
  833. }
  834. // AddTestPullRequestTask adds new test tasks by given head/base repository and head/base branch,
  835. // and generate new patch for testing as needed.
  836. func AddTestPullRequestTask(doer *User, repoID int64, branch string, isSync bool) {
  837. log.Trace("AddTestPullRequestTask [head_repo_id: %d, head_branch: %s]: finding pull requests", repoID, branch)
  838. prs, err := GetUnmergedPullRequestsByHeadInfo(repoID, branch)
  839. if err != nil {
  840. log.Error(4, "Find pull requests [head_repo_id: %d, head_branch: %s]: %v", repoID, branch, err)
  841. return
  842. }
  843. if isSync {
  844. if err = PullRequestList(prs).LoadAttributes(); err != nil {
  845. log.Error(4, "PullRequestList.LoadAttributes: %v", err)
  846. }
  847. if err == nil {
  848. for _, pr := range prs {
  849. pr.Issue.PullRequest = pr
  850. if err = pr.Issue.LoadAttributes(); err != nil {
  851. log.Error(4, "LoadAttributes: %v", err)
  852. continue
  853. }
  854. if err = PrepareWebhooks(pr.Issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  855. Action: api.HookIssueSynchronized,
  856. Index: pr.Issue.Index,
  857. PullRequest: pr.Issue.PullRequest.APIFormat(),
  858. Repository: pr.Issue.Repo.APIFormat(AccessModeNone),
  859. Sender: doer.APIFormat(),
  860. }); err != nil {
  861. log.Error(4, "PrepareWebhooks [pull_id: %v]: %v", pr.ID, err)
  862. continue
  863. }
  864. go HookQueue.Add(pr.Issue.Repo.ID)
  865. }
  866. }
  867. }
  868. addHeadRepoTasks(prs)
  869. log.Trace("AddTestPullRequestTask [base_repo_id: %d, base_branch: %s]: finding pull requests", repoID, branch)
  870. prs, err = GetUnmergedPullRequestsByBaseInfo(repoID, branch)
  871. if err != nil {
  872. log.Error(4, "Find pull requests [base_repo_id: %d, base_branch: %s]: %v", repoID, branch, err)
  873. return
  874. }
  875. for _, pr := range prs {
  876. pr.AddToTaskQueue()
  877. }
  878. }
  879. // ChangeUsernameInPullRequests changes the name of head_user_name
  880. func ChangeUsernameInPullRequests(oldUserName, newUserName string) error {
  881. pr := PullRequest{
  882. HeadUserName: strings.ToLower(newUserName),
  883. }
  884. _, err := x.
  885. Cols("head_user_name").
  886. Where("head_user_name = ?", strings.ToLower(oldUserName)).
  887. Update(pr)
  888. return err
  889. }
  890. // checkAndUpdateStatus checks if pull request is possible to leaving checking status,
  891. // and set to be either conflict or mergeable.
  892. func (pr *PullRequest) checkAndUpdateStatus() {
  893. // Status is not changed to conflict means mergeable.
  894. if pr.Status == PullRequestStatusChecking {
  895. pr.Status = PullRequestStatusMergeable
  896. }
  897. // Make sure there is no waiting test to process before leaving the checking status.
  898. if !pullRequestQueue.Exist(pr.ID) {
  899. if err := pr.UpdateCols("status"); err != nil {
  900. log.Error(4, "Update[%d]: %v", pr.ID, err)
  901. }
  902. }
  903. }
  904. // TestPullRequests checks and tests untested patches of pull requests.
  905. // TODO: test more pull requests at same time.
  906. func TestPullRequests() {
  907. prs := make([]*PullRequest, 0, 10)
  908. x.Iterate(PullRequest{
  909. Status: PullRequestStatusChecking,
  910. },
  911. func(idx int, bean interface{}) error {
  912. pr := bean.(*PullRequest)
  913. if err := pr.GetBaseRepo(); err != nil {
  914. log.Error(3, "GetBaseRepo: %v", err)
  915. return nil
  916. }
  917. if pr.manuallyMerged() {
  918. return nil
  919. }
  920. if err := pr.testPatch(); err != nil {
  921. log.Error(3, "testPatch: %v", err)
  922. return nil
  923. }
  924. prs = append(prs, pr)
  925. return nil
  926. })
  927. // Update pull request status.
  928. for _, pr := range prs {
  929. pr.checkAndUpdateStatus()
  930. }
  931. // Start listening on new test requests.
  932. for prID := range pullRequestQueue.Queue() {
  933. log.Trace("TestPullRequests[%v]: processing test task", prID)
  934. pullRequestQueue.Remove(prID)
  935. pr, err := GetPullRequestByID(com.StrTo(prID).MustInt64())
  936. if err != nil {
  937. log.Error(4, "GetPullRequestByID[%s]: %v", prID, err)
  938. continue
  939. } else if pr.manuallyMerged() {
  940. continue
  941. } else if err = pr.testPatch(); err != nil {
  942. log.Error(4, "testPatch[%d]: %v", pr.ID, err)
  943. continue
  944. }
  945. pr.checkAndUpdateStatus()
  946. }
  947. }
  948. // InitTestPullRequests runs the task to test all the checking status pull requests
  949. func InitTestPullRequests() {
  950. go TestPullRequests()
  951. }