Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

pull.go 33KB

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