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