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