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

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108
  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 && len(mergeCommit) != 40 {
  442. err = fmt.Errorf("unexpected length of output (got:%d bytes) '%s'", len(mergeCommit), mergeCommit)
  443. }
  444. if err != nil {
  445. return nil, fmt.Errorf("git rev-list --ancestry-path --merges --reverse: %v %v", stderr, err)
  446. }
  447. gitRepo, err := git.OpenRepository(pr.BaseRepo.RepoPath())
  448. if err != nil {
  449. return nil, fmt.Errorf("OpenRepository: %v", err)
  450. }
  451. commit, err := gitRepo.GetCommit(mergeCommit[:40])
  452. if err != nil {
  453. return nil, fmt.Errorf("GetCommit: %v", err)
  454. }
  455. return commit, nil
  456. }
  457. // patchConflicts is a list of conflict description from Git.
  458. var patchConflicts = []string{
  459. "patch does not apply",
  460. "already exists in working directory",
  461. "unrecognized input",
  462. "error:",
  463. }
  464. // testPatch checks if patch can be merged to base repository without conflict.
  465. func (pr *PullRequest) testPatch() (err error) {
  466. if pr.BaseRepo == nil {
  467. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  468. if err != nil {
  469. return fmt.Errorf("GetRepositoryByID: %v", err)
  470. }
  471. }
  472. patchPath, err := pr.BaseRepo.PatchPath(pr.Index)
  473. if err != nil {
  474. return fmt.Errorf("BaseRepo.PatchPath: %v", err)
  475. }
  476. // Fast fail if patch does not exist, this assumes data is corrupted.
  477. if !com.IsFile(patchPath) {
  478. log.Trace("PullRequest[%d].testPatch: ignored corrupted data", pr.ID)
  479. return nil
  480. }
  481. repoWorkingPool.CheckIn(com.ToStr(pr.BaseRepoID))
  482. defer repoWorkingPool.CheckOut(com.ToStr(pr.BaseRepoID))
  483. log.Trace("PullRequest[%d].testPatch (patchPath): %s", pr.ID, patchPath)
  484. pr.Status = PullRequestStatusChecking
  485. indexTmpPath := filepath.Join(os.TempDir(), "gitea-"+pr.BaseRepo.Name+"-"+strconv.Itoa(time.Now().Nanosecond()))
  486. defer os.Remove(indexTmpPath)
  487. var stderr string
  488. _, stderr, err = process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("testPatch (git read-tree): %d", pr.BaseRepo.ID),
  489. []string{"GIT_DIR=" + pr.BaseRepo.RepoPath(), "GIT_INDEX_FILE=" + indexTmpPath},
  490. "git", "read-tree", pr.BaseBranch)
  491. if err != nil {
  492. return fmt.Errorf("git read-tree --index-output=%s %s: %v - %s", indexTmpPath, pr.BaseBranch, err, stderr)
  493. }
  494. _, stderr, err = process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("testPatch (git apply --check): %d", pr.BaseRepo.ID),
  495. []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()},
  496. "git", "apply", "--check", "--cached", patchPath)
  497. if err != nil {
  498. for i := range patchConflicts {
  499. if strings.Contains(stderr, patchConflicts[i]) {
  500. log.Trace("PullRequest[%d].testPatch (apply): has conflict", pr.ID)
  501. fmt.Println(stderr)
  502. pr.Status = PullRequestStatusConflict
  503. return nil
  504. }
  505. }
  506. return fmt.Errorf("git apply --check: %v - %s", err, stderr)
  507. }
  508. return nil
  509. }
  510. // NewPullRequest creates new pull request with labels for repository.
  511. func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest, patch []byte) (err error) {
  512. sess := x.NewSession()
  513. defer sessionRelease(sess)
  514. if err = sess.Begin(); err != nil {
  515. return err
  516. }
  517. if err = newIssue(sess, pull.Poster, NewIssueOptions{
  518. Repo: repo,
  519. Issue: pull,
  520. LabelIDs: labelIDs,
  521. Attachments: uuids,
  522. IsPull: true,
  523. }); err != nil {
  524. return fmt.Errorf("newIssue: %v", err)
  525. }
  526. pr.Index = pull.Index
  527. if err = repo.SavePatch(pr.Index, patch); err != nil {
  528. return fmt.Errorf("SavePatch: %v", err)
  529. }
  530. pr.BaseRepo = repo
  531. if err = pr.testPatch(); err != nil {
  532. return fmt.Errorf("testPatch: %v", err)
  533. }
  534. // No conflict appears after test means mergeable.
  535. if pr.Status == PullRequestStatusChecking {
  536. pr.Status = PullRequestStatusMergeable
  537. }
  538. pr.IssueID = pull.ID
  539. if _, err = sess.Insert(pr); err != nil {
  540. return fmt.Errorf("insert pull repo: %v", err)
  541. }
  542. if err = sess.Commit(); err != nil {
  543. return fmt.Errorf("Commit: %v", err)
  544. }
  545. if err = NotifyWatchers(&Action{
  546. ActUserID: pull.Poster.ID,
  547. ActUserName: pull.Poster.Name,
  548. OpType: ActionCreatePullRequest,
  549. Content: fmt.Sprintf("%d|%s", pull.Index, pull.Title),
  550. RepoID: repo.ID,
  551. RepoUserName: repo.Owner.Name,
  552. RepoName: repo.Name,
  553. IsPrivate: repo.IsPrivate,
  554. }); err != nil {
  555. log.Error(4, "NotifyWatchers: %v", err)
  556. } else if err = pull.MailParticipants(); err != nil {
  557. log.Error(4, "MailParticipants: %v", err)
  558. }
  559. pr.Issue = pull
  560. pull.PullRequest = pr
  561. if err = PrepareWebhooks(repo, HookEventPullRequest, &api.PullRequestPayload{
  562. Action: api.HookIssueOpened,
  563. Index: pull.Index,
  564. PullRequest: pr.APIFormat(),
  565. Repository: repo.APIFormat(AccessModeNone),
  566. Sender: pull.Poster.APIFormat(),
  567. }); err != nil {
  568. log.Error(4, "PrepareWebhooks: %v", err)
  569. }
  570. go HookQueue.Add(repo.ID)
  571. return nil
  572. }
  573. // PullRequestsOptions holds the options for PRs
  574. type PullRequestsOptions struct {
  575. Page int
  576. State string
  577. SortType string
  578. Labels []string
  579. MilestoneID int64
  580. }
  581. func listPullRequestStatement(baseRepoID int64, opts *PullRequestsOptions) (*xorm.Session, error) {
  582. sess := x.Where("pull_request.base_repo_id=?", baseRepoID)
  583. sess.Join("INNER", "issue", "pull_request.issue_id = issue.id")
  584. switch opts.State {
  585. case "closed", "open":
  586. sess.And("issue.is_closed=?", opts.State == "closed")
  587. }
  588. sortIssuesSession(sess, opts.SortType)
  589. if labelIDs, err := base.StringsToInt64s(opts.Labels); err != nil {
  590. return nil, err
  591. } else if len(labelIDs) > 0 {
  592. sess.Join("INNER", "issue_label", "issue.id = issue_label.issue_id").
  593. In("issue_label.label_id", labelIDs)
  594. }
  595. if opts.MilestoneID > 0 {
  596. sess.And("issue.milestone_id=?", opts.MilestoneID)
  597. }
  598. return sess, nil
  599. }
  600. // PullRequests returns all pull requests for a base Repo by the given conditions
  601. func PullRequests(baseRepoID int64, opts *PullRequestsOptions) ([]*PullRequest, int64, error) {
  602. if opts.Page <= 0 {
  603. opts.Page = 1
  604. }
  605. countSession, err := listPullRequestStatement(baseRepoID, opts)
  606. if err != nil {
  607. log.Error(4, "listPullRequestStatement", err)
  608. return nil, 0, err
  609. }
  610. maxResults, err := countSession.Count(new(PullRequest))
  611. if err != nil {
  612. log.Error(4, "Count PRs", err)
  613. return nil, maxResults, err
  614. }
  615. prs := make([]*PullRequest, 0, ItemsPerPage)
  616. findSession, err := listPullRequestStatement(baseRepoID, opts)
  617. if err != nil {
  618. log.Error(4, "listPullRequestStatement", err)
  619. return nil, maxResults, err
  620. }
  621. findSession.Limit(ItemsPerPage, (opts.Page-1)*ItemsPerPage)
  622. return prs, maxResults, findSession.Find(&prs)
  623. }
  624. // GetUnmergedPullRequest returns a pull request that is open and has not been merged
  625. // by given head/base and repo/branch.
  626. func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string) (*PullRequest, error) {
  627. pr := new(PullRequest)
  628. has, err := x.
  629. Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  630. headRepoID, headBranch, baseRepoID, baseBranch, false, false).
  631. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  632. Get(pr)
  633. if err != nil {
  634. return nil, err
  635. } else if !has {
  636. return nil, ErrPullRequestNotExist{0, 0, headRepoID, baseRepoID, headBranch, baseBranch}
  637. }
  638. return pr, nil
  639. }
  640. // GetUnmergedPullRequestsByHeadInfo returns all pull requests that are open and has not been merged
  641. // by given head information (repo and branch).
  642. func GetUnmergedPullRequestsByHeadInfo(repoID int64, branch string) ([]*PullRequest, error) {
  643. prs := make([]*PullRequest, 0, 2)
  644. return prs, x.
  645. Where("head_repo_id = ? AND head_branch = ? AND has_merged = ? AND issue.is_closed = ?",
  646. repoID, branch, false, false).
  647. Join("INNER", "issue", "issue.id = pull_request.issue_id").
  648. Find(&prs)
  649. }
  650. // GetUnmergedPullRequestsByBaseInfo returns all pull requests that are open and has not been merged
  651. // by given base information (repo and branch).
  652. func GetUnmergedPullRequestsByBaseInfo(repoID int64, branch string) ([]*PullRequest, error) {
  653. prs := make([]*PullRequest, 0, 2)
  654. return prs, x.
  655. Where("base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  656. repoID, branch, false, false).
  657. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  658. Find(&prs)
  659. }
  660. // GetPullRequestByIndex returns a pull request by the given index
  661. func GetPullRequestByIndex(repoID int64, index int64) (*PullRequest, error) {
  662. pr := &PullRequest{
  663. BaseRepoID: repoID,
  664. Index: index,
  665. }
  666. has, err := x.Get(pr)
  667. if err != nil {
  668. return nil, err
  669. } else if !has {
  670. return nil, ErrPullRequestNotExist{0, 0, 0, repoID, "", ""}
  671. }
  672. if err = pr.LoadAttributes(); err != nil {
  673. return nil, err
  674. }
  675. if err = pr.LoadIssue(); err != nil {
  676. return nil, err
  677. }
  678. return pr, nil
  679. }
  680. func getPullRequestByID(e Engine, id int64) (*PullRequest, error) {
  681. pr := new(PullRequest)
  682. has, err := e.Id(id).Get(pr)
  683. if err != nil {
  684. return nil, err
  685. } else if !has {
  686. return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""}
  687. }
  688. return pr, pr.loadAttributes(e)
  689. }
  690. // GetPullRequestByID returns a pull request by given ID.
  691. func GetPullRequestByID(id int64) (*PullRequest, error) {
  692. return getPullRequestByID(x, id)
  693. }
  694. func getPullRequestByIssueID(e Engine, issueID int64) (*PullRequest, error) {
  695. pr := &PullRequest{
  696. IssueID: issueID,
  697. }
  698. has, err := e.Get(pr)
  699. if err != nil {
  700. return nil, err
  701. } else if !has {
  702. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  703. }
  704. return pr, pr.loadAttributes(e)
  705. }
  706. // GetPullRequestByIssueID returns pull request by given issue ID.
  707. func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) {
  708. return getPullRequestByIssueID(x, issueID)
  709. }
  710. // Update updates all fields of pull request.
  711. func (pr *PullRequest) Update() error {
  712. _, err := x.Id(pr.ID).AllCols().Update(pr)
  713. return err
  714. }
  715. // UpdateCols updates specific fields of pull request.
  716. func (pr *PullRequest) UpdateCols(cols ...string) error {
  717. _, err := x.Id(pr.ID).Cols(cols...).Update(pr)
  718. return err
  719. }
  720. // UpdatePatch generates and saves a new patch.
  721. func (pr *PullRequest) UpdatePatch() (err error) {
  722. if err = pr.GetHeadRepo(); err != nil {
  723. return fmt.Errorf("GetHeadRepo: %v", err)
  724. } else if pr.HeadRepo == nil {
  725. log.Trace("PullRequest[%d].UpdatePatch: ignored cruppted data", pr.ID)
  726. return nil
  727. }
  728. if err = pr.GetBaseRepo(); err != nil {
  729. return fmt.Errorf("GetBaseRepo: %v", err)
  730. }
  731. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  732. if err != nil {
  733. return fmt.Errorf("OpenRepository: %v", err)
  734. }
  735. // Add a temporary remote.
  736. tmpRemote := com.ToStr(time.Now().UnixNano())
  737. if err = headGitRepo.AddRemote(tmpRemote, RepoPath(pr.BaseRepo.MustOwner().Name, pr.BaseRepo.Name), true); err != nil {
  738. return fmt.Errorf("AddRemote: %v", err)
  739. }
  740. defer func() {
  741. headGitRepo.RemoveRemote(tmpRemote)
  742. }()
  743. remoteBranch := "remotes/" + tmpRemote + "/" + pr.BaseBranch
  744. pr.MergeBase, err = headGitRepo.GetMergeBase(remoteBranch, pr.HeadBranch)
  745. if err != nil {
  746. return fmt.Errorf("GetMergeBase: %v", err)
  747. } else if err = pr.Update(); err != nil {
  748. return fmt.Errorf("Update: %v", err)
  749. }
  750. patch, err := headGitRepo.GetPatch(pr.MergeBase, pr.HeadBranch)
  751. if err != nil {
  752. return fmt.Errorf("GetPatch: %v", err)
  753. }
  754. if err = pr.BaseRepo.SavePatch(pr.Index, patch); err != nil {
  755. return fmt.Errorf("BaseRepo.SavePatch: %v", err)
  756. }
  757. return nil
  758. }
  759. // PushToBaseRepo pushes commits from branches of head repository to
  760. // corresponding branches of base repository.
  761. // FIXME: Only push branches that are actually updates?
  762. func (pr *PullRequest) PushToBaseRepo() (err error) {
  763. log.Trace("PushToBaseRepo[%d]: pushing commits to base repo 'refs/pull/%d/head'", pr.BaseRepoID, pr.Index)
  764. headRepoPath := pr.HeadRepo.RepoPath()
  765. headGitRepo, err := git.OpenRepository(headRepoPath)
  766. if err != nil {
  767. return fmt.Errorf("OpenRepository: %v", err)
  768. }
  769. tmpRemoteName := fmt.Sprintf("tmp-pull-%d", pr.ID)
  770. if err = headGitRepo.AddRemote(tmpRemoteName, pr.BaseRepo.RepoPath(), false); err != nil {
  771. return fmt.Errorf("headGitRepo.AddRemote: %v", err)
  772. }
  773. // Make sure to remove the remote even if the push fails
  774. defer headGitRepo.RemoveRemote(tmpRemoteName)
  775. headFile := fmt.Sprintf("refs/pull/%d/head", pr.Index)
  776. // Remove head in case there is a conflict.
  777. file := path.Join(pr.BaseRepo.RepoPath(), headFile)
  778. _ = os.Remove(file)
  779. if err = git.Push(headRepoPath, tmpRemoteName, fmt.Sprintf("%s:%s", pr.HeadBranch, headFile)); err != nil {
  780. return fmt.Errorf("Push: %v", err)
  781. }
  782. return nil
  783. }
  784. // AddToTaskQueue adds itself to pull request test task queue.
  785. func (pr *PullRequest) AddToTaskQueue() {
  786. go pullRequestQueue.AddFunc(pr.ID, func() {
  787. pr.Status = PullRequestStatusChecking
  788. if err := pr.UpdateCols("status"); err != nil {
  789. log.Error(5, "AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
  790. }
  791. })
  792. }
  793. // PullRequestList defines a list of pull requests
  794. type PullRequestList []*PullRequest
  795. func (prs PullRequestList) loadAttributes(e Engine) error {
  796. if len(prs) == 0 {
  797. return nil
  798. }
  799. // Load issues.
  800. issueIDs := make([]int64, 0, len(prs))
  801. for i := range prs {
  802. issueIDs = append(issueIDs, prs[i].IssueID)
  803. }
  804. issues := make([]*Issue, 0, len(issueIDs))
  805. if err := e.
  806. Where("id > 0").
  807. In("id", issueIDs).
  808. Find(&issues); err != nil {
  809. return fmt.Errorf("find issues: %v", err)
  810. }
  811. set := make(map[int64]*Issue)
  812. for i := range issues {
  813. set[issues[i].ID] = issues[i]
  814. }
  815. for i := range prs {
  816. prs[i].Issue = set[prs[i].IssueID]
  817. }
  818. return nil
  819. }
  820. // LoadAttributes load all the prs attributes
  821. func (prs PullRequestList) LoadAttributes() error {
  822. return prs.loadAttributes(x)
  823. }
  824. func addHeadRepoTasks(prs []*PullRequest) {
  825. for _, pr := range prs {
  826. log.Trace("addHeadRepoTasks[%d]: composing new test task", pr.ID)
  827. if err := pr.UpdatePatch(); err != nil {
  828. log.Error(4, "UpdatePatch: %v", err)
  829. continue
  830. } else if err := pr.PushToBaseRepo(); err != nil {
  831. log.Error(4, "PushToBaseRepo: %v", err)
  832. continue
  833. }
  834. pr.AddToTaskQueue()
  835. }
  836. }
  837. // AddTestPullRequestTask adds new test tasks by given head/base repository and head/base branch,
  838. // and generate new patch for testing as needed.
  839. func AddTestPullRequestTask(doer *User, repoID int64, branch string, isSync bool) {
  840. log.Trace("AddTestPullRequestTask [head_repo_id: %d, head_branch: %s]: finding pull requests", repoID, branch)
  841. prs, err := GetUnmergedPullRequestsByHeadInfo(repoID, branch)
  842. if err != nil {
  843. log.Error(4, "Find pull requests [head_repo_id: %d, head_branch: %s]: %v", repoID, branch, err)
  844. return
  845. }
  846. if isSync {
  847. if err = PullRequestList(prs).LoadAttributes(); err != nil {
  848. log.Error(4, "PullRequestList.LoadAttributes: %v", err)
  849. }
  850. if err == nil {
  851. for _, pr := range prs {
  852. pr.Issue.PullRequest = pr
  853. if err = pr.Issue.LoadAttributes(); err != nil {
  854. log.Error(4, "LoadAttributes: %v", err)
  855. continue
  856. }
  857. if err = PrepareWebhooks(pr.Issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  858. Action: api.HookIssueSynchronized,
  859. Index: pr.Issue.Index,
  860. PullRequest: pr.Issue.PullRequest.APIFormat(),
  861. Repository: pr.Issue.Repo.APIFormat(AccessModeNone),
  862. Sender: doer.APIFormat(),
  863. }); err != nil {
  864. log.Error(4, "PrepareWebhooks [pull_id: %v]: %v", pr.ID, err)
  865. continue
  866. }
  867. go HookQueue.Add(pr.Issue.Repo.ID)
  868. }
  869. }
  870. }
  871. addHeadRepoTasks(prs)
  872. log.Trace("AddTestPullRequestTask [base_repo_id: %d, base_branch: %s]: finding pull requests", repoID, branch)
  873. prs, err = GetUnmergedPullRequestsByBaseInfo(repoID, branch)
  874. if err != nil {
  875. log.Error(4, "Find pull requests [base_repo_id: %d, base_branch: %s]: %v", repoID, branch, err)
  876. return
  877. }
  878. for _, pr := range prs {
  879. pr.AddToTaskQueue()
  880. }
  881. }
  882. // ChangeUsernameInPullRequests changes the name of head_user_name
  883. func ChangeUsernameInPullRequests(oldUserName, newUserName string) error {
  884. pr := PullRequest{
  885. HeadUserName: strings.ToLower(newUserName),
  886. }
  887. _, err := x.
  888. Cols("head_user_name").
  889. Where("head_user_name = ?", strings.ToLower(oldUserName)).
  890. Update(pr)
  891. return err
  892. }
  893. // checkAndUpdateStatus checks if pull request is possible to leaving checking status,
  894. // and set to be either conflict or mergeable.
  895. func (pr *PullRequest) checkAndUpdateStatus() {
  896. // Status is not changed to conflict means mergeable.
  897. if pr.Status == PullRequestStatusChecking {
  898. pr.Status = PullRequestStatusMergeable
  899. }
  900. // Make sure there is no waiting test to process before leaving the checking status.
  901. if !pullRequestQueue.Exist(pr.ID) {
  902. if err := pr.UpdateCols("status"); err != nil {
  903. log.Error(4, "Update[%d]: %v", pr.ID, err)
  904. }
  905. }
  906. }
  907. // TestPullRequests checks and tests untested patches of pull requests.
  908. // TODO: test more pull requests at same time.
  909. func TestPullRequests() {
  910. prs := make([]*PullRequest, 0, 10)
  911. x.Iterate(PullRequest{
  912. Status: PullRequestStatusChecking,
  913. },
  914. func(idx int, bean interface{}) error {
  915. pr := bean.(*PullRequest)
  916. if err := pr.GetBaseRepo(); err != nil {
  917. log.Error(3, "GetBaseRepo: %v", err)
  918. return nil
  919. }
  920. if pr.manuallyMerged() {
  921. return nil
  922. }
  923. if err := pr.testPatch(); err != nil {
  924. log.Error(3, "testPatch: %v", err)
  925. return nil
  926. }
  927. prs = append(prs, pr)
  928. return nil
  929. })
  930. // Update pull request status.
  931. for _, pr := range prs {
  932. pr.checkAndUpdateStatus()
  933. }
  934. // Start listening on new test requests.
  935. for prID := range pullRequestQueue.Queue() {
  936. log.Trace("TestPullRequests[%v]: processing test task", prID)
  937. pullRequestQueue.Remove(prID)
  938. pr, err := GetPullRequestByID(com.StrTo(prID).MustInt64())
  939. if err != nil {
  940. log.Error(4, "GetPullRequestByID[%s]: %v", prID, err)
  941. continue
  942. } else if pr.manuallyMerged() {
  943. continue
  944. } else if err = pr.testPatch(); err != nil {
  945. log.Error(4, "testPatch[%d]: %v", pr.ID, err)
  946. continue
  947. }
  948. pr.checkAndUpdateStatus()
  949. }
  950. }
  951. // InitTestPullRequests runs the task to test all the checking status pull requests
  952. func InitTestPullRequests() {
  953. go TestPullRequests()
  954. }