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 24 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
Squashed commit of the following: commit 0afcb843d7ffd596991c4885cab768273a6eb42c Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 17:13:29 2016 -0600 Removed Upload stats as the upload table is just a temporary table commit 7ecd73ff5535612d79d471409173ee7f1fcfa157 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 08:42:41 2016 -0600 Fix for CodeMirror mode commit c29b9ab531e2e7af0fb5db24dc17e51027dd1174 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 08:03:33 2016 -0600 Made tabbing in editor use spaces commit 23af384c53206a8a40e11e45bf49d7a149c4adcd Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:56:46 2016 -0600 Fix for data-url commit cfb8a97591cb6fc0a92e49563b7b764c524db0e9 Merge: 7fc8a89 991ce42 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:42:53 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go public/js/gogs.js commit 7fc8a89cb495478225b02d613e647f99a1489634 Merge: fd3d86c c03d040 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:40:00 2016 -0600 Merge branch 'feature-create-and-edit-repo-file' of github.com:richmahn/gogs into feature-create-and-edit-repo-file commit fd3d86ca6bbc02cfda566a504ffd6b03db4f75ef Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:39:44 2016 -0600 Code cleanup commit c03d0401c1049eeeccc32ab1f9c3303c130be5ee Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 29 15:38:23 2016 -0600 Code cleanup commit 98e1206ccf9f9a4503c020e3a7830cf9f861dfae Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 18:36:01 2016 -0600 Code cleanup and fixes commit c2895dc742f25f8412879c9fa15e18f27f42f194 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 18:24:04 2016 -0600 Fixes per Unknwon's requests commit 6aa7e46b21ad4c96e562daa2eac26a8fb408f8ef Merge: 889e9fa ad7ea88 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 17:13:43 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go modules/setting/setting.go commit 889e9faf1bd8559a4979c8f46005d488c1a234d4 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:09:18 2016 -0600 Fix in gogs.js commit 47603edf223f147b114be65f3bd27bc1e88827a5 Merge: bb57912 cf85e9e Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:07:36 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go public/js/gogs.js commit bb5791255867a71c11a77b639db050ad09c597a4 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:02:18 2016 -0600 Update for using CodeMirror mode addon commit d10d128c51039be19e2af9c66c63db66a9f2ec6d Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Tue Jul 19 16:12:57 2016 -0600 Update for Edit commit 34a34982025144e3225e389f7849eb6273c1d576 Merge: fa1b752 1c7dcdd Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Tue Jul 19 11:52:02 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go commit fa1b752be29cd455c5184ddac2ffe80b3489763e Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 15 18:35:42 2016 -0600 Feature for editing, creating, uploading and deleting files
9 years ago
10 years ago
10 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  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. "os"
  8. "path"
  9. "strings"
  10. "time"
  11. "github.com/Unknwon/com"
  12. "github.com/go-xorm/xorm"
  13. "github.com/gogits/git-module"
  14. api "github.com/gogits/go-gogs-client"
  15. "github.com/gogits/gogs/modules/log"
  16. "github.com/gogits/gogs/modules/process"
  17. "github.com/gogits/gogs/modules/setting"
  18. )
  19. type PullRequestType int
  20. const (
  21. PULL_REQUEST_GOGS PullRequestType = iota
  22. PLLL_ERQUEST_GIT
  23. )
  24. type PullRequestStatus int
  25. const (
  26. PULL_REQUEST_STATUS_CONFLICT PullRequestStatus = iota
  27. PULL_REQUEST_STATUS_CHECKING
  28. PULL_REQUEST_STATUS_MERGEABLE
  29. )
  30. // PullRequest represents relation between pull request and repositories.
  31. type PullRequest struct {
  32. ID int64 `xorm:"pk autoincr"`
  33. Type PullRequestType
  34. Status PullRequestStatus
  35. IssueID int64 `xorm:"INDEX"`
  36. Issue *Issue `xorm:"-"`
  37. Index int64
  38. HeadRepoID int64
  39. HeadRepo *Repository `xorm:"-"`
  40. BaseRepoID int64
  41. BaseRepo *Repository `xorm:"-"`
  42. HeadUserName string
  43. HeadBranch string
  44. BaseBranch string
  45. MergeBase string `xorm:"VARCHAR(40)"`
  46. HasMerged bool
  47. MergedCommitID string `xorm:"VARCHAR(40)"`
  48. MergerID int64
  49. Merger *User `xorm:"-"`
  50. Merged time.Time `xorm:"-"`
  51. MergedUnix int64
  52. }
  53. func (pr *PullRequest) BeforeUpdate() {
  54. pr.MergedUnix = pr.Merged.Unix()
  55. }
  56. // Note: don't try to get Issue because will end up recursive querying.
  57. func (pr *PullRequest) AfterSet(colName string, _ xorm.Cell) {
  58. switch colName {
  59. case "merged_unix":
  60. if !pr.HasMerged {
  61. return
  62. }
  63. pr.Merged = time.Unix(pr.MergedUnix, 0).Local()
  64. }
  65. }
  66. // Note: don't try to get Issue because will end up recursive querying.
  67. func (pr *PullRequest) loadAttributes(e Engine) (err error) {
  68. if pr.HasMerged && pr.Merger == nil {
  69. pr.Merger, err = getUserByID(e, pr.MergerID)
  70. if IsErrUserNotExist(err) {
  71. pr.MergerID = -1
  72. pr.Merger = NewGhostUser()
  73. } else if err != nil {
  74. return fmt.Errorf("getUserByID [%d]: %v", pr.MergerID, err)
  75. }
  76. }
  77. return nil
  78. }
  79. func (pr *PullRequest) LoadAttributes() error {
  80. return pr.loadAttributes(x)
  81. }
  82. func (pr *PullRequest) LoadIssue() (err error) {
  83. pr.Issue, err = GetIssueByID(pr.IssueID)
  84. return err
  85. }
  86. // This method assumes following fields have been assigned with valid values:
  87. // Required - Issue
  88. // Optional - Merger
  89. func (pr *PullRequest) APIFormat() *api.PullRequest {
  90. apiIssue := pr.Issue.APIFormat()
  91. apiPullRequest := &api.PullRequest{
  92. ID: pr.ID,
  93. Index: pr.Index,
  94. State: apiIssue.State,
  95. Title: apiIssue.Title,
  96. Body: apiIssue.Body,
  97. User: apiIssue.User,
  98. Labels: apiIssue.Labels,
  99. Milestone: apiIssue.Milestone,
  100. Assignee: apiIssue.Assignee,
  101. Comments: apiIssue.Comments,
  102. HasMerged: pr.HasMerged,
  103. }
  104. if pr.Status != PULL_REQUEST_STATUS_CHECKING {
  105. mergeable := pr.Status != PULL_REQUEST_STATUS_CONFLICT
  106. apiPullRequest.Mergeable = &mergeable
  107. }
  108. if pr.HasMerged {
  109. apiPullRequest.Merged = &pr.Merged
  110. apiPullRequest.MergedCommitID = &pr.MergedCommitID
  111. apiPullRequest.MergedBy = pr.Merger.APIFormat()
  112. }
  113. return apiPullRequest
  114. }
  115. func (pr *PullRequest) getHeadRepo(e Engine) (err error) {
  116. pr.HeadRepo, err = getRepositoryByID(e, pr.HeadRepoID)
  117. if err != nil && !IsErrRepoNotExist(err) {
  118. return fmt.Errorf("getRepositoryByID(head): %v", err)
  119. }
  120. return nil
  121. }
  122. func (pr *PullRequest) GetHeadRepo() error {
  123. return pr.getHeadRepo(x)
  124. }
  125. func (pr *PullRequest) GetBaseRepo() (err error) {
  126. if pr.BaseRepo != nil {
  127. return nil
  128. }
  129. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  130. if err != nil {
  131. return fmt.Errorf("GetRepositoryByID(base): %v", err)
  132. }
  133. return nil
  134. }
  135. // IsChecking returns true if this pull request is still checking conflict.
  136. func (pr *PullRequest) IsChecking() bool {
  137. return pr.Status == PULL_REQUEST_STATUS_CHECKING
  138. }
  139. // CanAutoMerge returns true if this pull request can be merged automatically.
  140. func (pr *PullRequest) CanAutoMerge() bool {
  141. return pr.Status == PULL_REQUEST_STATUS_MERGEABLE
  142. }
  143. // Merge merges pull request to base repository.
  144. // FIXME: add repoWorkingPull make sure two merges does not happen at same time.
  145. func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository) (err error) {
  146. if err = pr.GetHeadRepo(); err != nil {
  147. return fmt.Errorf("GetHeadRepo: %v", err)
  148. } else if err = pr.GetBaseRepo(); err != nil {
  149. return fmt.Errorf("GetBaseRepo: %v", err)
  150. }
  151. defer func() {
  152. go HookQueue.Add(pr.BaseRepo.ID)
  153. go AddTestPullRequestTask(doer, pr.BaseRepo.ID, pr.BaseBranch, false)
  154. }()
  155. sess := x.NewSession()
  156. defer sessionRelease(sess)
  157. if err = sess.Begin(); err != nil {
  158. return err
  159. }
  160. if err = pr.Issue.changeStatus(sess, doer, pr.Issue.Repo, true); err != nil {
  161. return fmt.Errorf("Issue.changeStatus: %v", err)
  162. }
  163. headRepoPath := RepoPath(pr.HeadUserName, pr.HeadRepo.Name)
  164. headGitRepo, err := git.OpenRepository(headRepoPath)
  165. if err != nil {
  166. return fmt.Errorf("OpenRepository: %v", err)
  167. }
  168. // Clone base repo.
  169. tmpBasePath := path.Join(setting.AppDataPath, "tmp/repos", com.ToStr(time.Now().Nanosecond())+".git")
  170. os.MkdirAll(path.Dir(tmpBasePath), os.ModePerm)
  171. defer os.RemoveAll(path.Dir(tmpBasePath))
  172. var stderr string
  173. if _, stderr, err = process.ExecTimeout(5*time.Minute,
  174. fmt.Sprintf("PullRequest.Merge (git clone): %s", tmpBasePath),
  175. "git", "clone", baseGitRepo.Path, tmpBasePath); err != nil {
  176. return fmt.Errorf("git clone: %s", stderr)
  177. }
  178. // Check out base branch.
  179. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  180. fmt.Sprintf("PullRequest.Merge (git checkout): %s", tmpBasePath),
  181. "git", "checkout", pr.BaseBranch); err != nil {
  182. return fmt.Errorf("git checkout: %s", stderr)
  183. }
  184. // Add head repo remote.
  185. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  186. fmt.Sprintf("PullRequest.Merge (git remote add): %s", tmpBasePath),
  187. "git", "remote", "add", "head_repo", headRepoPath); err != nil {
  188. return fmt.Errorf("git remote add [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  189. }
  190. // Merge commits.
  191. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  192. fmt.Sprintf("PullRequest.Merge (git fetch): %s", tmpBasePath),
  193. "git", "fetch", "head_repo"); err != nil {
  194. return fmt.Errorf("git fetch [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  195. }
  196. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  197. fmt.Sprintf("PullRequest.Merge (git merge --no-ff --no-commit): %s", tmpBasePath),
  198. "git", "merge", "--no-ff", "--no-commit", "head_repo/"+pr.HeadBranch); err != nil {
  199. return fmt.Errorf("git merge --no-ff --no-commit [%s]: %v - %s", tmpBasePath, err, stderr)
  200. }
  201. sig := doer.NewGitSig()
  202. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  203. fmt.Sprintf("PullRequest.Merge (git merge): %s", tmpBasePath),
  204. "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  205. "-m", fmt.Sprintf("Merge branch '%s' of %s/%s into %s", pr.HeadBranch, pr.HeadUserName, pr.HeadRepo.Name, pr.BaseBranch)); err != nil {
  206. return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, stderr)
  207. }
  208. // Push back to upstream.
  209. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  210. fmt.Sprintf("PullRequest.Merge (git push): %s", tmpBasePath),
  211. "git", "push", baseGitRepo.Path, pr.BaseBranch); err != nil {
  212. return fmt.Errorf("git push: %s", stderr)
  213. }
  214. pr.MergedCommitID, err = headGitRepo.GetBranchCommitID(pr.HeadBranch)
  215. if err != nil {
  216. return fmt.Errorf("GetBranchCommit: %v", err)
  217. }
  218. pr.HasMerged = true
  219. pr.Merged = time.Now()
  220. pr.MergerID = doer.ID
  221. if _, err = sess.Id(pr.ID).AllCols().Update(pr); err != nil {
  222. return fmt.Errorf("update pull request: %v", err)
  223. }
  224. if err = sess.Commit(); err != nil {
  225. return fmt.Errorf("Commit: %v", err)
  226. }
  227. if err = MergePullRequestAction(doer, pr.Issue.Repo, pr.Issue); err != nil {
  228. log.Error(4, "MergePullRequestAction [%d]: %v", pr.ID, err)
  229. }
  230. // Reload pull request information.
  231. if err = pr.LoadAttributes(); err != nil {
  232. log.Error(4, "LoadAttributes: %v", err)
  233. return nil
  234. }
  235. if err = PrepareWebhooks(pr.Issue.Repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{
  236. Action: api.HOOK_ISSUE_CLOSED,
  237. Index: pr.Index,
  238. PullRequest: pr.APIFormat(),
  239. Repository: pr.Issue.Repo.APIFormat(nil),
  240. Sender: doer.APIFormat(),
  241. }); err != nil {
  242. log.Error(4, "PrepareWebhooks: %v", err)
  243. return nil
  244. }
  245. l, err := headGitRepo.CommitsBetweenIDs(pr.MergedCommitID, pr.MergeBase)
  246. if err != nil {
  247. log.Error(4, "CommitsBetweenIDs: %v", err)
  248. return nil
  249. }
  250. // TODO: when squash commits, no need to append merge commit.
  251. // It is possible that head branch is not fully sync with base branch for merge commits,
  252. // so we need to get latest head commit and append merge commit manully
  253. // to avoid strange diff commits produced.
  254. mergeCommit, err := baseGitRepo.GetBranchCommit(pr.BaseBranch)
  255. if err != nil {
  256. log.Error(4, "GetBranchCommit: %v", err)
  257. return nil
  258. }
  259. l.PushFront(mergeCommit)
  260. p := &api.PushPayload{
  261. Ref: git.BRANCH_PREFIX + pr.BaseBranch,
  262. Before: pr.MergeBase,
  263. After: pr.MergedCommitID,
  264. CompareURL: setting.AppUrl + pr.BaseRepo.ComposeCompareURL(pr.MergeBase, pr.MergedCommitID),
  265. Commits: ListToPushCommits(l).ToApiPayloadCommits(pr.BaseRepo.FullLink()),
  266. Repo: pr.BaseRepo.APIFormat(nil),
  267. Pusher: pr.HeadRepo.MustOwner().APIFormat(),
  268. Sender: doer.APIFormat(),
  269. }
  270. if err = PrepareWebhooks(pr.BaseRepo, HOOK_EVENT_PUSH, p); err != nil {
  271. return fmt.Errorf("PrepareWebhooks: %v", err)
  272. }
  273. return nil
  274. }
  275. // patchConflicts is a list of conflit description from Git.
  276. var patchConflicts = []string{
  277. "patch does not apply",
  278. "already exists in working directory",
  279. "unrecognized input",
  280. "error:",
  281. }
  282. // testPatch checks if patch can be merged to base repository without conflit.
  283. // FIXME: make a mechanism to clean up stable local copies.
  284. func (pr *PullRequest) testPatch() (err error) {
  285. if pr.BaseRepo == nil {
  286. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  287. if err != nil {
  288. return fmt.Errorf("GetRepositoryByID: %v", err)
  289. }
  290. }
  291. patchPath, err := pr.BaseRepo.PatchPath(pr.Index)
  292. if err != nil {
  293. return fmt.Errorf("BaseRepo.PatchPath: %v", err)
  294. }
  295. // Fast fail if patch does not exist, this assumes data is cruppted.
  296. if !com.IsFile(patchPath) {
  297. log.Trace("PullRequest[%d].testPatch: ignored cruppted data", pr.ID)
  298. return nil
  299. }
  300. log.Trace("PullRequest[%d].testPatch (patchPath): %s", pr.ID, patchPath)
  301. if err := pr.BaseRepo.UpdateLocalCopy(pr.BaseRepo.DefaultBranch); err != nil {
  302. return fmt.Errorf("UpdateLocalCopy: %v", err)
  303. }
  304. // Checkout base branch.
  305. _, stderr, err := process.ExecDir(-1, pr.BaseRepo.LocalCopyPath(),
  306. fmt.Sprintf("PullRequest.Merge (git checkout): %v", pr.BaseRepo.ID),
  307. "git", "checkout", pr.BaseBranch)
  308. if err != nil {
  309. return fmt.Errorf("git checkout: %s", stderr)
  310. }
  311. pr.Status = PULL_REQUEST_STATUS_CHECKING
  312. _, stderr, err = process.ExecDir(-1, pr.BaseRepo.LocalCopyPath(),
  313. fmt.Sprintf("testPatch (git apply --check): %d", pr.BaseRepo.ID),
  314. "git", "apply", "--check", patchPath)
  315. if err != nil {
  316. for i := range patchConflicts {
  317. if strings.Contains(stderr, patchConflicts[i]) {
  318. log.Trace("PullRequest[%d].testPatch (apply): has conflit", pr.ID)
  319. fmt.Println(stderr)
  320. pr.Status = PULL_REQUEST_STATUS_CONFLICT
  321. return nil
  322. }
  323. }
  324. return fmt.Errorf("git apply --check: %v - %s", err, stderr)
  325. }
  326. return nil
  327. }
  328. // NewPullRequest creates new pull request with labels for repository.
  329. func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest, patch []byte) (err error) {
  330. sess := x.NewSession()
  331. defer sessionRelease(sess)
  332. if err = sess.Begin(); err != nil {
  333. return err
  334. }
  335. if err = newIssue(sess, repo, pull, labelIDs, uuids, true); err != nil {
  336. return fmt.Errorf("newIssue: %v", err)
  337. }
  338. pr.Index = pull.Index
  339. if err = repo.SavePatch(pr.Index, patch); err != nil {
  340. return fmt.Errorf("SavePatch: %v", err)
  341. }
  342. pr.BaseRepo = repo
  343. if err = pr.testPatch(); err != nil {
  344. return fmt.Errorf("testPatch: %v", err)
  345. }
  346. // No conflict appears after test means mergeable.
  347. if pr.Status == PULL_REQUEST_STATUS_CHECKING {
  348. pr.Status = PULL_REQUEST_STATUS_MERGEABLE
  349. }
  350. pr.IssueID = pull.ID
  351. if _, err = sess.Insert(pr); err != nil {
  352. return fmt.Errorf("insert pull repo: %v", err)
  353. }
  354. if err = sess.Commit(); err != nil {
  355. return fmt.Errorf("Commit: %v", err)
  356. }
  357. if err = NotifyWatchers(&Action{
  358. ActUserID: pull.Poster.ID,
  359. ActUserName: pull.Poster.Name,
  360. ActEmail: pull.Poster.Email,
  361. OpType: ACTION_CREATE_PULL_REQUEST,
  362. Content: fmt.Sprintf("%d|%s", pull.Index, pull.Title),
  363. RepoID: repo.ID,
  364. RepoUserName: repo.Owner.Name,
  365. RepoName: repo.Name,
  366. IsPrivate: repo.IsPrivate,
  367. }); err != nil {
  368. log.Error(4, "NotifyWatchers: %v", err)
  369. } else if err = pull.MailParticipants(); err != nil {
  370. log.Error(4, "MailParticipants: %v", err)
  371. }
  372. pr.Issue = pull
  373. pull.PullRequest = pr
  374. if err = PrepareWebhooks(repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{
  375. Action: api.HOOK_ISSUE_OPENED,
  376. Index: pull.Index,
  377. PullRequest: pr.APIFormat(),
  378. Repository: repo.APIFormat(nil),
  379. Sender: pull.Poster.APIFormat(),
  380. }); err != nil {
  381. log.Error(4, "PrepareWebhooks: %v", err)
  382. }
  383. go HookQueue.Add(repo.ID)
  384. return nil
  385. }
  386. // GetUnmergedPullRequest returnss a pull request that is open and has not been merged
  387. // by given head/base and repo/branch.
  388. func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string) (*PullRequest, error) {
  389. pr := new(PullRequest)
  390. has, err := x.Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  391. headRepoID, headBranch, baseRepoID, baseBranch, false, false).
  392. Join("INNER", "issue", "issue.id=pull_request.issue_id").Get(pr)
  393. if err != nil {
  394. return nil, err
  395. } else if !has {
  396. return nil, ErrPullRequestNotExist{0, 0, headRepoID, baseRepoID, headBranch, baseBranch}
  397. }
  398. return pr, nil
  399. }
  400. // GetUnmergedPullRequestsByHeadInfo returnss all pull requests that are open and has not been merged
  401. // by given head information (repo and branch).
  402. func GetUnmergedPullRequestsByHeadInfo(repoID int64, branch string) ([]*PullRequest, error) {
  403. prs := make([]*PullRequest, 0, 2)
  404. return prs, x.Where("head_repo_id = ? AND head_branch = ? AND has_merged = ? AND issue.is_closed = ?",
  405. repoID, branch, false, false).
  406. Join("INNER", "issue", "issue.id = pull_request.issue_id").Find(&prs)
  407. }
  408. // GetUnmergedPullRequestsByBaseInfo returnss all pull requests that are open and has not been merged
  409. // by given base information (repo and branch).
  410. func GetUnmergedPullRequestsByBaseInfo(repoID int64, branch string) ([]*PullRequest, error) {
  411. prs := make([]*PullRequest, 0, 2)
  412. return prs, x.Where("base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  413. repoID, branch, false, false).
  414. Join("INNER", "issue", "issue.id=pull_request.issue_id").Find(&prs)
  415. }
  416. func getPullRequestByID(e Engine, id int64) (*PullRequest, error) {
  417. pr := new(PullRequest)
  418. has, err := e.Id(id).Get(pr)
  419. if err != nil {
  420. return nil, err
  421. } else if !has {
  422. return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""}
  423. }
  424. return pr, pr.loadAttributes(e)
  425. }
  426. // GetPullRequestByID returns a pull request by given ID.
  427. func GetPullRequestByID(id int64) (*PullRequest, error) {
  428. return getPullRequestByID(x, id)
  429. }
  430. func getPullRequestByIssueID(e Engine, issueID int64) (*PullRequest, error) {
  431. pr := &PullRequest{
  432. IssueID: issueID,
  433. }
  434. has, err := e.Get(pr)
  435. if err != nil {
  436. return nil, err
  437. } else if !has {
  438. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  439. }
  440. return pr, pr.loadAttributes(e)
  441. }
  442. // GetPullRequestByIssueID returns pull request by given issue ID.
  443. func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) {
  444. return getPullRequestByIssueID(x, issueID)
  445. }
  446. // Update updates all fields of pull request.
  447. func (pr *PullRequest) Update() error {
  448. _, err := x.Id(pr.ID).AllCols().Update(pr)
  449. return err
  450. }
  451. // Update updates specific fields of pull request.
  452. func (pr *PullRequest) UpdateCols(cols ...string) error {
  453. _, err := x.Id(pr.ID).Cols(cols...).Update(pr)
  454. return err
  455. }
  456. var PullRequestQueue = NewUniqueQueue(setting.Repository.PullRequestQueueLength)
  457. // UpdatePatch generates and saves a new patch.
  458. func (pr *PullRequest) UpdatePatch() (err error) {
  459. if err = pr.GetHeadRepo(); err != nil {
  460. return fmt.Errorf("GetHeadRepo: %v", err)
  461. } else if pr.HeadRepo == nil {
  462. log.Trace("PullRequest[%d].UpdatePatch: ignored cruppted data", pr.ID)
  463. return nil
  464. }
  465. if err = pr.GetBaseRepo(); err != nil {
  466. return fmt.Errorf("GetBaseRepo: %v", err)
  467. }
  468. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  469. if err != nil {
  470. return fmt.Errorf("OpenRepository: %v", err)
  471. }
  472. // Add a temporary remote.
  473. tmpRemote := com.ToStr(time.Now().UnixNano())
  474. if err = headGitRepo.AddRemote(tmpRemote, RepoPath(pr.BaseRepo.MustOwner().Name, pr.BaseRepo.Name), true); err != nil {
  475. return fmt.Errorf("AddRemote: %v", err)
  476. }
  477. defer func() {
  478. headGitRepo.RemoveRemote(tmpRemote)
  479. }()
  480. remoteBranch := "remotes/" + tmpRemote + "/" + pr.BaseBranch
  481. pr.MergeBase, err = headGitRepo.GetMergeBase(remoteBranch, pr.HeadBranch)
  482. if err != nil {
  483. return fmt.Errorf("GetMergeBase: %v", err)
  484. } else if err = pr.Update(); err != nil {
  485. return fmt.Errorf("Update: %v", err)
  486. }
  487. patch, err := headGitRepo.GetPatch(pr.MergeBase, pr.HeadBranch)
  488. if err != nil {
  489. return fmt.Errorf("GetPatch: %v", err)
  490. }
  491. if err = pr.BaseRepo.SavePatch(pr.Index, patch); err != nil {
  492. return fmt.Errorf("BaseRepo.SavePatch: %v", err)
  493. }
  494. return nil
  495. }
  496. // PushToBaseRepo pushes commits from branches of head repository to
  497. // corresponding branches of base repository.
  498. // FIXME: Only push branches that are actually updates?
  499. func (pr *PullRequest) PushToBaseRepo() (err error) {
  500. log.Trace("PushToBaseRepo[%d]: pushing commits to base repo 'refs/pull/%d/head'", pr.BaseRepoID, pr.Index)
  501. headRepoPath := pr.HeadRepo.RepoPath()
  502. headGitRepo, err := git.OpenRepository(headRepoPath)
  503. if err != nil {
  504. return fmt.Errorf("OpenRepository: %v", err)
  505. }
  506. tmpRemoteName := fmt.Sprintf("tmp-pull-%d", pr.ID)
  507. if err = headGitRepo.AddRemote(tmpRemoteName, pr.BaseRepo.RepoPath(), false); err != nil {
  508. return fmt.Errorf("headGitRepo.AddRemote: %v", err)
  509. }
  510. // Make sure to remove the remote even if the push fails
  511. defer headGitRepo.RemoveRemote(tmpRemoteName)
  512. headFile := fmt.Sprintf("refs/pull/%d/head", pr.Index)
  513. // Remove head in case there is a conflict.
  514. os.Remove(path.Join(pr.BaseRepo.RepoPath(), headFile))
  515. if err = git.Push(headRepoPath, tmpRemoteName, fmt.Sprintf("%s:%s", pr.HeadBranch, headFile)); err != nil {
  516. return fmt.Errorf("Push: %v", err)
  517. }
  518. return nil
  519. }
  520. // AddToTaskQueue adds itself to pull request test task queue.
  521. func (pr *PullRequest) AddToTaskQueue() {
  522. go PullRequestQueue.AddFunc(pr.ID, func() {
  523. pr.Status = PULL_REQUEST_STATUS_CHECKING
  524. if err := pr.UpdateCols("status"); err != nil {
  525. log.Error(5, "AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
  526. }
  527. })
  528. }
  529. type PullRequestList []*PullRequest
  530. func (prs PullRequestList) loadAttributes(e Engine) error {
  531. if len(prs) == 0 {
  532. return nil
  533. }
  534. // Load issues.
  535. issueIDs := make([]int64, 0, len(prs))
  536. for i := range prs {
  537. issueIDs = append(issueIDs, prs[i].IssueID)
  538. }
  539. issues := make([]*Issue, 0, len(issueIDs))
  540. if err := e.Where("id > 0").In("id", issueIDs).Find(&issues); err != nil {
  541. return fmt.Errorf("find issues: %v", err)
  542. }
  543. set := make(map[int64]*Issue)
  544. for i := range issues {
  545. set[issues[i].ID] = issues[i]
  546. }
  547. for i := range prs {
  548. prs[i].Issue = set[prs[i].IssueID]
  549. }
  550. return nil
  551. }
  552. func (prs PullRequestList) LoadAttributes() error {
  553. return prs.loadAttributes(x)
  554. }
  555. func addHeadRepoTasks(prs []*PullRequest) {
  556. for _, pr := range prs {
  557. log.Trace("addHeadRepoTasks[%d]: composing new test task", pr.ID)
  558. if err := pr.UpdatePatch(); err != nil {
  559. log.Error(4, "UpdatePatch: %v", err)
  560. continue
  561. } else if err := pr.PushToBaseRepo(); err != nil {
  562. log.Error(4, "PushToBaseRepo: %v", err)
  563. continue
  564. }
  565. pr.AddToTaskQueue()
  566. }
  567. }
  568. // AddTestPullRequestTask adds new test tasks by given head/base repository and head/base branch,
  569. // and generate new patch for testing as needed.
  570. func AddTestPullRequestTask(doer *User, repoID int64, branch string, isSync bool) {
  571. log.Trace("AddTestPullRequestTask [head_repo_id: %d, head_branch: %s]: finding pull requests", repoID, branch)
  572. prs, err := GetUnmergedPullRequestsByHeadInfo(repoID, branch)
  573. if err != nil {
  574. log.Error(4, "Find pull requests [head_repo_id: %d, head_branch: %s]: %v", repoID, branch, err)
  575. return
  576. }
  577. if isSync {
  578. if err = PullRequestList(prs).LoadAttributes(); err != nil {
  579. log.Error(4, "PullRequestList.LoadAttributes: %v", err)
  580. }
  581. if err == nil {
  582. for _, pr := range prs {
  583. pr.Issue.PullRequest = pr
  584. if err = pr.Issue.LoadAttributes(); err != nil {
  585. log.Error(4, "LoadAttributes: %v", err)
  586. continue
  587. }
  588. if err = PrepareWebhooks(pr.Issue.Repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{
  589. Action: api.HOOK_ISSUE_SYNCHRONIZED,
  590. Index: pr.Issue.Index,
  591. PullRequest: pr.Issue.PullRequest.APIFormat(),
  592. Repository: pr.Issue.Repo.APIFormat(nil),
  593. Sender: doer.APIFormat(),
  594. }); err != nil {
  595. log.Error(4, "PrepareWebhooks [pull_id: %v]: %v", pr.ID, err)
  596. continue
  597. }
  598. go HookQueue.Add(pr.Issue.Repo.ID)
  599. }
  600. }
  601. }
  602. addHeadRepoTasks(prs)
  603. log.Trace("AddTestPullRequestTask [base_repo_id: %d, base_branch: %s]: finding pull requests", repoID, branch)
  604. prs, err = GetUnmergedPullRequestsByBaseInfo(repoID, branch)
  605. if err != nil {
  606. log.Error(4, "Find pull requests [base_repo_id: %d, base_branch: %s]: %v", repoID, branch, err)
  607. return
  608. }
  609. for _, pr := range prs {
  610. pr.AddToTaskQueue()
  611. }
  612. }
  613. func ChangeUsernameInPullRequests(oldUserName, newUserName string) error {
  614. pr := PullRequest{
  615. HeadUserName: strings.ToLower(newUserName),
  616. }
  617. _, err := x.Cols("head_user_name").Where("head_user_name = ?", strings.ToLower(oldUserName)).Update(pr)
  618. return err
  619. }
  620. // checkAndUpdateStatus checks if pull request is possible to levaing checking status,
  621. // and set to be either conflict or mergeable.
  622. func (pr *PullRequest) checkAndUpdateStatus() {
  623. // Status is not changed to conflict means mergeable.
  624. if pr.Status == PULL_REQUEST_STATUS_CHECKING {
  625. pr.Status = PULL_REQUEST_STATUS_MERGEABLE
  626. }
  627. // Make sure there is no waiting test to process before levaing the checking status.
  628. if !PullRequestQueue.Exist(pr.ID) {
  629. if err := pr.UpdateCols("status"); err != nil {
  630. log.Error(4, "Update[%d]: %v", pr.ID, err)
  631. }
  632. }
  633. }
  634. // TestPullRequests checks and tests untested patches of pull requests.
  635. // TODO: test more pull requests at same time.
  636. func TestPullRequests() {
  637. prs := make([]*PullRequest, 0, 10)
  638. x.Iterate(PullRequest{
  639. Status: PULL_REQUEST_STATUS_CHECKING,
  640. },
  641. func(idx int, bean interface{}) error {
  642. pr := bean.(*PullRequest)
  643. if err := pr.GetBaseRepo(); err != nil {
  644. log.Error(3, "GetBaseRepo: %v", err)
  645. return nil
  646. }
  647. if err := pr.testPatch(); err != nil {
  648. log.Error(3, "testPatch: %v", err)
  649. return nil
  650. }
  651. prs = append(prs, pr)
  652. return nil
  653. })
  654. // Update pull request status.
  655. for _, pr := range prs {
  656. pr.checkAndUpdateStatus()
  657. }
  658. // Start listening on new test requests.
  659. for prID := range PullRequestQueue.Queue() {
  660. log.Trace("TestPullRequests[%v]: processing test task", prID)
  661. PullRequestQueue.Remove(prID)
  662. pr, err := GetPullRequestByID(com.StrTo(prID).MustInt64())
  663. if err != nil {
  664. log.Error(4, "GetPullRequestByID[%d]: %v", prID, err)
  665. continue
  666. } else if err = pr.testPatch(); err != nil {
  667. log.Error(4, "testPatch[%d]: %v", pr.ID, err)
  668. continue
  669. }
  670. pr.checkAndUpdateStatus()
  671. }
  672. }
  673. func InitTestPullRequests() {
  674. go TestPullRequests()
  675. }