本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1256 lines
35KB

  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package models
  6. import (
  7. "bufio"
  8. "fmt"
  9. "io/ioutil"
  10. "os"
  11. "path"
  12. "path/filepath"
  13. "strconv"
  14. "strings"
  15. "time"
  16. "code.gitea.io/gitea/modules/base"
  17. "code.gitea.io/gitea/modules/git"
  18. "code.gitea.io/gitea/modules/log"
  19. "code.gitea.io/gitea/modules/process"
  20. "code.gitea.io/gitea/modules/setting"
  21. api "code.gitea.io/gitea/modules/structs"
  22. "code.gitea.io/gitea/modules/sync"
  23. "code.gitea.io/gitea/modules/timeutil"
  24. "github.com/unknwon/com"
  25. "xorm.io/xorm"
  26. )
  27. var pullRequestQueue = sync.NewUniqueQueue(setting.Repository.PullRequestQueueLength)
  28. // PullRequestType defines pull request type
  29. type PullRequestType int
  30. // Enumerate all the pull request types
  31. const (
  32. PullRequestGitea PullRequestType = iota
  33. PullRequestGit
  34. )
  35. // PullRequestStatus defines pull request status
  36. type PullRequestStatus int
  37. // Enumerate all the pull request status
  38. const (
  39. PullRequestStatusConflict PullRequestStatus = iota
  40. PullRequestStatusChecking
  41. PullRequestStatusMergeable
  42. PullRequestStatusManuallyMerged
  43. )
  44. // PullRequest represents relation between pull request and repositories.
  45. type PullRequest struct {
  46. ID int64 `xorm:"pk autoincr"`
  47. Type PullRequestType
  48. Status PullRequestStatus
  49. ConflictedFiles []string `xorm:"TEXT JSON"`
  50. IssueID int64 `xorm:"INDEX"`
  51. Issue *Issue `xorm:"-"`
  52. Index int64
  53. HeadRepoID int64 `xorm:"INDEX"`
  54. HeadRepo *Repository `xorm:"-"`
  55. BaseRepoID int64 `xorm:"INDEX"`
  56. BaseRepo *Repository `xorm:"-"`
  57. HeadBranch string
  58. BaseBranch string
  59. ProtectedBranch *ProtectedBranch `xorm:"-"`
  60. MergeBase string `xorm:"VARCHAR(40)"`
  61. HasMerged bool `xorm:"INDEX"`
  62. MergedCommitID string `xorm:"VARCHAR(40)"`
  63. MergerID int64 `xorm:"INDEX"`
  64. Merger *User `xorm:"-"`
  65. MergedUnix timeutil.TimeStamp `xorm:"updated INDEX"`
  66. }
  67. // MustHeadUserName returns the HeadRepo's username if failed return blank
  68. func (pr *PullRequest) MustHeadUserName() string {
  69. if err := pr.LoadHeadRepo(); err != nil {
  70. log.Error("LoadHeadRepo: %v", err)
  71. return ""
  72. }
  73. return pr.HeadRepo.MustOwnerName()
  74. }
  75. // Note: don't try to get Issue because will end up recursive querying.
  76. func (pr *PullRequest) loadAttributes(e Engine) (err error) {
  77. if pr.HasMerged && pr.Merger == nil {
  78. pr.Merger, err = getUserByID(e, pr.MergerID)
  79. if IsErrUserNotExist(err) {
  80. pr.MergerID = -1
  81. pr.Merger = NewGhostUser()
  82. } else if err != nil {
  83. return fmt.Errorf("getUserByID [%d]: %v", pr.MergerID, err)
  84. }
  85. }
  86. return nil
  87. }
  88. // LoadAttributes loads pull request attributes from database
  89. func (pr *PullRequest) LoadAttributes() error {
  90. return pr.loadAttributes(x)
  91. }
  92. // LoadBaseRepo loads pull request base repository from database
  93. func (pr *PullRequest) LoadBaseRepo() error {
  94. if pr.BaseRepo == nil {
  95. if pr.HeadRepoID == pr.BaseRepoID && pr.HeadRepo != nil {
  96. pr.BaseRepo = pr.HeadRepo
  97. return nil
  98. }
  99. var repo Repository
  100. if has, err := x.ID(pr.BaseRepoID).Get(&repo); err != nil {
  101. return err
  102. } else if !has {
  103. return ErrRepoNotExist{ID: pr.BaseRepoID}
  104. }
  105. pr.BaseRepo = &repo
  106. }
  107. return nil
  108. }
  109. // LoadHeadRepo loads pull request head repository from database
  110. func (pr *PullRequest) LoadHeadRepo() error {
  111. if pr.HeadRepo == nil {
  112. if pr.HeadRepoID == pr.BaseRepoID && pr.BaseRepo != nil {
  113. pr.HeadRepo = pr.BaseRepo
  114. return nil
  115. }
  116. var repo Repository
  117. if has, err := x.ID(pr.HeadRepoID).Get(&repo); err != nil {
  118. return err
  119. } else if !has {
  120. return ErrRepoNotExist{ID: pr.BaseRepoID}
  121. }
  122. pr.HeadRepo = &repo
  123. }
  124. return nil
  125. }
  126. // LoadIssue loads issue information from database
  127. func (pr *PullRequest) LoadIssue() (err error) {
  128. return pr.loadIssue(x)
  129. }
  130. func (pr *PullRequest) loadIssue(e Engine) (err error) {
  131. if pr.Issue != nil {
  132. return nil
  133. }
  134. pr.Issue, err = getIssueByID(e, pr.IssueID)
  135. return err
  136. }
  137. // LoadProtectedBranch loads the protected branch of the base branch
  138. func (pr *PullRequest) LoadProtectedBranch() (err error) {
  139. if pr.BaseRepo == nil {
  140. if pr.BaseRepoID == 0 {
  141. return nil
  142. }
  143. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  144. if err != nil {
  145. return
  146. }
  147. }
  148. pr.ProtectedBranch, err = GetProtectedBranchBy(pr.BaseRepo.ID, pr.BaseBranch)
  149. return
  150. }
  151. // GetDefaultMergeMessage returns default message used when merging pull request
  152. func (pr *PullRequest) GetDefaultMergeMessage() string {
  153. if pr.HeadRepo == nil {
  154. var err error
  155. pr.HeadRepo, err = GetRepositoryByID(pr.HeadRepoID)
  156. if err != nil {
  157. log.Error("GetRepositoryById[%d]: %v", pr.HeadRepoID, err)
  158. return ""
  159. }
  160. }
  161. return fmt.Sprintf("Merge branch '%s' of %s/%s into %s", pr.HeadBranch, pr.MustHeadUserName(), pr.HeadRepo.Name, pr.BaseBranch)
  162. }
  163. // GetDefaultSquashMessage returns default message used when squash and merging pull request
  164. func (pr *PullRequest) GetDefaultSquashMessage() string {
  165. if err := pr.LoadIssue(); err != nil {
  166. log.Error("LoadIssue: %v", err)
  167. return ""
  168. }
  169. return fmt.Sprintf("%s (#%d)", pr.Issue.Title, pr.Issue.Index)
  170. }
  171. // GetGitRefName returns git ref for hidden pull request branch
  172. func (pr *PullRequest) GetGitRefName() string {
  173. return fmt.Sprintf("refs/pull/%d/head", pr.Index)
  174. }
  175. // APIFormat assumes following fields have been assigned with valid values:
  176. // Required - Issue
  177. // Optional - Merger
  178. func (pr *PullRequest) APIFormat() *api.PullRequest {
  179. return pr.apiFormat(x)
  180. }
  181. func (pr *PullRequest) apiFormat(e Engine) *api.PullRequest {
  182. var (
  183. baseBranch *git.Branch
  184. headBranch *git.Branch
  185. baseCommit *git.Commit
  186. headCommit *git.Commit
  187. err error
  188. )
  189. if err = pr.Issue.loadRepo(e); err != nil {
  190. log.Error("loadRepo[%d]: %v", pr.ID, err)
  191. return nil
  192. }
  193. apiIssue := pr.Issue.apiFormat(e)
  194. if pr.BaseRepo == nil {
  195. pr.BaseRepo, err = getRepositoryByID(e, pr.BaseRepoID)
  196. if err != nil {
  197. log.Error("GetRepositoryById[%d]: %v", pr.ID, err)
  198. return nil
  199. }
  200. }
  201. if pr.HeadRepo == nil {
  202. pr.HeadRepo, err = getRepositoryByID(e, pr.HeadRepoID)
  203. if err != nil {
  204. log.Error("GetRepositoryById[%d]: %v", pr.ID, err)
  205. return nil
  206. }
  207. }
  208. if err = pr.Issue.loadRepo(e); err != nil {
  209. log.Error("pr.Issue.loadRepo[%d]: %v", pr.ID, err)
  210. return nil
  211. }
  212. apiPullRequest := &api.PullRequest{
  213. ID: pr.ID,
  214. URL: pr.Issue.HTMLURL(),
  215. Index: pr.Index,
  216. Poster: apiIssue.Poster,
  217. Title: apiIssue.Title,
  218. Body: apiIssue.Body,
  219. Labels: apiIssue.Labels,
  220. Milestone: apiIssue.Milestone,
  221. Assignee: apiIssue.Assignee,
  222. Assignees: apiIssue.Assignees,
  223. State: apiIssue.State,
  224. Comments: apiIssue.Comments,
  225. HTMLURL: pr.Issue.HTMLURL(),
  226. DiffURL: pr.Issue.DiffURL(),
  227. PatchURL: pr.Issue.PatchURL(),
  228. HasMerged: pr.HasMerged,
  229. MergeBase: pr.MergeBase,
  230. Deadline: apiIssue.Deadline,
  231. Created: pr.Issue.CreatedUnix.AsTimePtr(),
  232. Updated: pr.Issue.UpdatedUnix.AsTimePtr(),
  233. }
  234. baseBranch, err = pr.BaseRepo.GetBranch(pr.BaseBranch)
  235. if err != nil {
  236. if git.IsErrBranchNotExist(err) {
  237. apiPullRequest.Base = nil
  238. } else {
  239. log.Error("GetBranch[%s]: %v", pr.BaseBranch, err)
  240. return nil
  241. }
  242. } else {
  243. apiBaseBranchInfo := &api.PRBranchInfo{
  244. Name: pr.BaseBranch,
  245. Ref: pr.BaseBranch,
  246. RepoID: pr.BaseRepoID,
  247. Repository: pr.BaseRepo.innerAPIFormat(e, AccessModeNone, false),
  248. }
  249. baseCommit, err = baseBranch.GetCommit()
  250. if err != nil {
  251. if git.IsErrNotExist(err) {
  252. apiBaseBranchInfo.Sha = ""
  253. } else {
  254. log.Error("GetCommit[%s]: %v", baseBranch.Name, err)
  255. return nil
  256. }
  257. } else {
  258. apiBaseBranchInfo.Sha = baseCommit.ID.String()
  259. }
  260. apiPullRequest.Base = apiBaseBranchInfo
  261. }
  262. headBranch, err = pr.HeadRepo.GetBranch(pr.HeadBranch)
  263. if err != nil {
  264. if git.IsErrBranchNotExist(err) {
  265. apiPullRequest.Head = nil
  266. } else {
  267. log.Error("GetBranch[%s]: %v", pr.HeadBranch, err)
  268. return nil
  269. }
  270. } else {
  271. apiHeadBranchInfo := &api.PRBranchInfo{
  272. Name: pr.HeadBranch,
  273. Ref: pr.HeadBranch,
  274. RepoID: pr.HeadRepoID,
  275. Repository: pr.HeadRepo.innerAPIFormat(e, AccessModeNone, false),
  276. }
  277. headCommit, err = headBranch.GetCommit()
  278. if err != nil {
  279. if git.IsErrNotExist(err) {
  280. apiHeadBranchInfo.Sha = ""
  281. } else {
  282. log.Error("GetCommit[%s]: %v", headBranch.Name, err)
  283. return nil
  284. }
  285. } else {
  286. apiHeadBranchInfo.Sha = headCommit.ID.String()
  287. }
  288. apiPullRequest.Head = apiHeadBranchInfo
  289. }
  290. if pr.Status != PullRequestStatusChecking {
  291. mergeable := pr.Status != PullRequestStatusConflict && !pr.IsWorkInProgress()
  292. apiPullRequest.Mergeable = mergeable
  293. }
  294. if pr.HasMerged {
  295. apiPullRequest.Merged = pr.MergedUnix.AsTimePtr()
  296. apiPullRequest.MergedCommitID = &pr.MergedCommitID
  297. apiPullRequest.MergedBy = pr.Merger.APIFormat()
  298. }
  299. return apiPullRequest
  300. }
  301. func (pr *PullRequest) getHeadRepo(e Engine) (err error) {
  302. pr.HeadRepo, err = getRepositoryByID(e, pr.HeadRepoID)
  303. if err != nil && !IsErrRepoNotExist(err) {
  304. return fmt.Errorf("getRepositoryByID(head): %v", err)
  305. }
  306. return nil
  307. }
  308. // GetHeadRepo loads the head repository
  309. func (pr *PullRequest) GetHeadRepo() error {
  310. return pr.getHeadRepo(x)
  311. }
  312. // GetBaseRepo loads the target repository
  313. func (pr *PullRequest) GetBaseRepo() (err error) {
  314. if pr.BaseRepo != nil {
  315. return nil
  316. }
  317. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  318. if err != nil {
  319. return fmt.Errorf("GetRepositoryByID(base): %v", err)
  320. }
  321. return nil
  322. }
  323. // IsChecking returns true if this pull request is still checking conflict.
  324. func (pr *PullRequest) IsChecking() bool {
  325. return pr.Status == PullRequestStatusChecking
  326. }
  327. // CanAutoMerge returns true if this pull request can be merged automatically.
  328. func (pr *PullRequest) CanAutoMerge() bool {
  329. return pr.Status == PullRequestStatusMergeable
  330. }
  331. // GetLastCommitStatus returns the last commit status for this pull request.
  332. func (pr *PullRequest) GetLastCommitStatus() (status *CommitStatus, err error) {
  333. if err = pr.GetHeadRepo(); err != nil {
  334. return nil, err
  335. }
  336. if pr.HeadRepo == nil {
  337. return nil, ErrPullRequestHeadRepoMissing{pr.ID, pr.HeadRepoID}
  338. }
  339. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  340. if err != nil {
  341. return nil, err
  342. }
  343. lastCommitID, err := headGitRepo.GetBranchCommitID(pr.HeadBranch)
  344. if err != nil {
  345. return nil, err
  346. }
  347. err = pr.LoadBaseRepo()
  348. if err != nil {
  349. return nil, err
  350. }
  351. statusList, err := GetLatestCommitStatus(pr.BaseRepo, lastCommitID, 0)
  352. if err != nil {
  353. return nil, err
  354. }
  355. return CalcCommitStatus(statusList), nil
  356. }
  357. // MergeStyle represents the approach to merge commits into base branch.
  358. type MergeStyle string
  359. const (
  360. // MergeStyleMerge create merge commit
  361. MergeStyleMerge MergeStyle = "merge"
  362. // MergeStyleRebase rebase before merging
  363. MergeStyleRebase MergeStyle = "rebase"
  364. // MergeStyleRebaseMerge rebase before merging with merge commit (--no-ff)
  365. MergeStyleRebaseMerge MergeStyle = "rebase-merge"
  366. // MergeStyleSquash squash commits into single commit before merging
  367. MergeStyleSquash MergeStyle = "squash"
  368. )
  369. // CheckUserAllowedToMerge checks whether the user is allowed to merge
  370. func (pr *PullRequest) CheckUserAllowedToMerge(doer *User) (err error) {
  371. if doer == nil {
  372. return ErrNotAllowedToMerge{
  373. "Not signed in",
  374. }
  375. }
  376. if pr.BaseRepo == nil {
  377. if err = pr.GetBaseRepo(); err != nil {
  378. return fmt.Errorf("GetBaseRepo: %v", err)
  379. }
  380. }
  381. if protected, err := pr.BaseRepo.IsProtectedBranchForMerging(pr, pr.BaseBranch, doer); err != nil {
  382. return fmt.Errorf("IsProtectedBranch: %v", err)
  383. } else if protected {
  384. return ErrNotAllowedToMerge{
  385. "The branch is protected",
  386. }
  387. }
  388. return nil
  389. }
  390. // SetMerged sets a pull request to merged and closes the corresponding issue
  391. func (pr *PullRequest) SetMerged() (err error) {
  392. if pr.HasMerged {
  393. return fmt.Errorf("PullRequest[%d] already merged", pr.Index)
  394. }
  395. if pr.MergedCommitID == "" || pr.MergedUnix == 0 || pr.Merger == nil {
  396. return fmt.Errorf("Unable to merge PullRequest[%d], some required fields are empty", pr.Index)
  397. }
  398. pr.HasMerged = true
  399. sess := x.NewSession()
  400. defer sess.Close()
  401. if err = sess.Begin(); err != nil {
  402. return err
  403. }
  404. if err = pr.loadIssue(sess); err != nil {
  405. return err
  406. }
  407. if err = pr.Issue.loadRepo(sess); err != nil {
  408. return err
  409. }
  410. if err = pr.Issue.Repo.getOwner(sess); err != nil {
  411. return err
  412. }
  413. if err = pr.GetHeadRepo(); err != nil {
  414. return err
  415. }
  416. if err = pr.GetBaseRepo(); err != nil {
  417. return err
  418. }
  419. if err = pr.HeadRepo.GetOwner(); err != nil {
  420. return err
  421. }
  422. if err = pr.Issue.changeStatus(sess, pr.Merger, true); err != nil {
  423. return fmt.Errorf("Issue.changeStatus: %v", err)
  424. }
  425. if _, err = sess.ID(pr.ID).Cols("has_merged, status, merged_commit_id, merger_id, merged_unix").Update(pr); err != nil {
  426. return fmt.Errorf("update pull request: %v", err)
  427. }
  428. var FromID = pr.BaseRepo.OwnerName
  429. var Why = "奖励"+pr.BaseRepo.Name+ "项目的贡献"
  430. var ToID = pr.HeadRepo.Owner.Name
  431. var Qty = int(pr.BaseRepo.NextPoint)
  432. if FromID != ToID {
  433. if _, err = sess.Insert(&Transfer{FromID: FromID, ToID: ToID, Why: Why, Qty: Qty}); err != nil {
  434. return fmt.Errorf("Transfer", err)
  435. }
  436. if _, err = sess.Exec("UPDATE `user` SET point = point + ? WHERE name = ?", Qty, ToID); err != nil {
  437. return fmt.Errorf("Add Point", err)
  438. }
  439. if _, err = sess.Exec("UPDATE `user` SET point = point - ? WHERE name = ?", Qty, FromID); err != nil {
  440. return fmt.Errorf("Subtract Point", err)
  441. }
  442. if _, err = sess.Exec("UPDATE `repository` SET point = point - ? WHERE id = ?", Qty, pr.BaseRepo.ID); err != nil {
  443. return err
  444. }
  445. if _, err = sess.Exec("UPDATE `repository` SET next_point = point * percent * 0.01 WHERE id = ?", pr.BaseRepo.ID); err != nil {
  446. return err
  447. }
  448. }
  449. if err = sess.Commit(); err != nil {
  450. return fmt.Errorf("Commit: %v", err)
  451. }
  452. return nil
  453. }
  454. // manuallyMerged checks if a pull request got manually merged
  455. // When a pull request got manually merged mark the pull request as merged
  456. func (pr *PullRequest) manuallyMerged() bool {
  457. commit, err := pr.getMergeCommit()
  458. if err != nil {
  459. log.Error("PullRequest[%d].getMergeCommit: %v", pr.ID, err)
  460. return false
  461. }
  462. if commit != nil {
  463. pr.MergedCommitID = commit.ID.String()
  464. pr.MergedUnix = timeutil.TimeStamp(commit.Author.When.Unix())
  465. pr.Status = PullRequestStatusManuallyMerged
  466. merger, _ := GetUserByEmail(commit.Author.Email)
  467. // When the commit author is unknown set the BaseRepo owner as merger
  468. if merger == nil {
  469. if pr.BaseRepo.Owner == nil {
  470. if err = pr.BaseRepo.getOwner(x); err != nil {
  471. log.Error("BaseRepo.getOwner[%d]: %v", pr.ID, err)
  472. return false
  473. }
  474. }
  475. merger = pr.BaseRepo.Owner
  476. }
  477. pr.Merger = merger
  478. pr.MergerID = merger.ID
  479. // if err = pr.SetMerged(); err != nil {
  480. // log.Error("PullRequest[%d].setMerged : %v", pr.ID, err)
  481. // return false
  482. // }
  483. 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())
  484. return true
  485. }
  486. return false
  487. }
  488. // getMergeCommit checks if a pull request got merged
  489. // Returns the git.Commit of the pull request if merged
  490. func (pr *PullRequest) getMergeCommit() (*git.Commit, error) {
  491. if pr.BaseRepo == nil {
  492. var err error
  493. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  494. if err != nil {
  495. return nil, fmt.Errorf("GetRepositoryByID: %v", err)
  496. }
  497. }
  498. indexTmpPath := filepath.Join(os.TempDir(), "gitea-"+pr.BaseRepo.Name+"-"+strconv.Itoa(time.Now().Nanosecond()))
  499. defer os.Remove(indexTmpPath)
  500. headFile := pr.GetGitRefName()
  501. // Check if a pull request is merged into BaseBranch
  502. _, stderr, err := process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("isMerged (git merge-base --is-ancestor): %d", pr.BaseRepo.ID),
  503. []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()},
  504. git.GitExecutable, "merge-base", "--is-ancestor", headFile, pr.BaseBranch)
  505. if err != nil {
  506. // Errors are signaled by a non-zero status that is not 1
  507. if strings.Contains(err.Error(), "exit status 1") {
  508. return nil, nil
  509. }
  510. return nil, fmt.Errorf("git merge-base --is-ancestor: %v %v", stderr, err)
  511. }
  512. commitIDBytes, err := ioutil.ReadFile(pr.BaseRepo.RepoPath() + "/" + headFile)
  513. if err != nil {
  514. return nil, fmt.Errorf("ReadFile(%s): %v", headFile, err)
  515. }
  516. commitID := string(commitIDBytes)
  517. if len(commitID) < 40 {
  518. return nil, fmt.Errorf(`ReadFile(%s): invalid commit-ID "%s"`, headFile, commitID)
  519. }
  520. cmd := commitID[:40] + ".." + pr.BaseBranch
  521. // Get the commit from BaseBranch where the pull request got merged
  522. mergeCommit, stderr, err := process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("isMerged (git rev-list --ancestry-path --merges --reverse): %d", pr.BaseRepo.ID),
  523. []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()},
  524. git.GitExecutable, "rev-list", "--ancestry-path", "--merges", "--reverse", cmd)
  525. if err != nil {
  526. return nil, fmt.Errorf("git rev-list --ancestry-path --merges --reverse: %v %v", stderr, err)
  527. } else if len(mergeCommit) < 40 {
  528. // PR was fast-forwarded, so just use last commit of PR
  529. mergeCommit = commitID[:40]
  530. }
  531. gitRepo, err := git.OpenRepository(pr.BaseRepo.RepoPath())
  532. if err != nil {
  533. return nil, fmt.Errorf("OpenRepository: %v", err)
  534. }
  535. commit, err := gitRepo.GetCommit(mergeCommit[:40])
  536. if err != nil {
  537. return nil, fmt.Errorf("GetCommit: %v", err)
  538. }
  539. return commit, nil
  540. }
  541. // patchConflicts is a list of conflict description from Git.
  542. var patchConflicts = []string{
  543. "patch does not apply",
  544. "already exists in working directory",
  545. "unrecognized input",
  546. "error:",
  547. }
  548. // testPatch checks if patch can be merged to base repository without conflict.
  549. func (pr *PullRequest) testPatch(e Engine) (err error) {
  550. if pr.BaseRepo == nil {
  551. pr.BaseRepo, err = getRepositoryByID(e, pr.BaseRepoID)
  552. if err != nil {
  553. return fmt.Errorf("GetRepositoryByID: %v", err)
  554. }
  555. }
  556. patchPath, err := pr.BaseRepo.patchPath(e, pr.Index)
  557. if err != nil {
  558. return fmt.Errorf("BaseRepo.PatchPath: %v", err)
  559. }
  560. // Fast fail if patch does not exist, this assumes data is corrupted.
  561. if !com.IsFile(patchPath) {
  562. log.Trace("PullRequest[%d].testPatch: ignored corrupted data", pr.ID)
  563. return nil
  564. }
  565. repoWorkingPool.CheckIn(com.ToStr(pr.BaseRepoID))
  566. defer repoWorkingPool.CheckOut(com.ToStr(pr.BaseRepoID))
  567. log.Trace("PullRequest[%d].testPatch (patchPath): %s", pr.ID, patchPath)
  568. pr.Status = PullRequestStatusChecking
  569. indexTmpPath := filepath.Join(os.TempDir(), "gitea-"+pr.BaseRepo.Name+"-"+strconv.Itoa(time.Now().Nanosecond()))
  570. defer os.Remove(indexTmpPath)
  571. var stderr string
  572. _, stderr, err = process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("testPatch (git read-tree): %d", pr.BaseRepo.ID),
  573. []string{"GIT_DIR=" + pr.BaseRepo.RepoPath(), "GIT_INDEX_FILE=" + indexTmpPath},
  574. git.GitExecutable, "read-tree", pr.BaseBranch)
  575. if err != nil {
  576. return fmt.Errorf("git read-tree --index-output=%s %s: %v - %s", indexTmpPath, pr.BaseBranch, err, stderr)
  577. }
  578. prUnit, err := pr.BaseRepo.getUnit(e, UnitTypePullRequests)
  579. if err != nil {
  580. return err
  581. }
  582. prConfig := prUnit.PullRequestsConfig()
  583. args := []string{"apply", "--check", "--cached"}
  584. if prConfig.IgnoreWhitespaceConflicts {
  585. args = append(args, "--ignore-whitespace")
  586. }
  587. args = append(args, patchPath)
  588. pr.ConflictedFiles = []string{}
  589. _, stderr, err = process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("testPatch (git apply --check): %d", pr.BaseRepo.ID),
  590. []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()},
  591. git.GitExecutable, args...)
  592. if err != nil {
  593. for i := range patchConflicts {
  594. if strings.Contains(stderr, patchConflicts[i]) {
  595. log.Trace("PullRequest[%d].testPatch (apply): has conflict: %s", pr.ID, stderr)
  596. const prefix = "error: patch failed:"
  597. pr.Status = PullRequestStatusConflict
  598. pr.ConflictedFiles = make([]string, 0, 5)
  599. scanner := bufio.NewScanner(strings.NewReader(stderr))
  600. for scanner.Scan() {
  601. line := scanner.Text()
  602. if strings.HasPrefix(line, prefix) {
  603. var found bool
  604. var filepath = strings.TrimSpace(strings.Split(line[len(prefix):], ":")[0])
  605. for _, f := range pr.ConflictedFiles {
  606. if f == filepath {
  607. found = true
  608. break
  609. }
  610. }
  611. if !found {
  612. pr.ConflictedFiles = append(pr.ConflictedFiles, filepath)
  613. }
  614. }
  615. // only list 10 conflicted files
  616. if len(pr.ConflictedFiles) >= 10 {
  617. break
  618. }
  619. }
  620. if len(pr.ConflictedFiles) > 0 {
  621. log.Trace("Found %d files conflicted: %v", len(pr.ConflictedFiles), pr.ConflictedFiles)
  622. }
  623. return nil
  624. }
  625. }
  626. return fmt.Errorf("git apply --check: %v - %s", err, stderr)
  627. }
  628. return nil
  629. }
  630. // NewPullRequest creates new pull request with labels for repository.
  631. func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest, patch []byte) (err error) {
  632. // Retry several times in case INSERT fails due to duplicate key for (repo_id, index); see #7887
  633. i := 0
  634. for {
  635. if err = newPullRequestAttempt(repo, pull, labelIDs, uuids, pr, patch); err == nil {
  636. return nil
  637. }
  638. if !IsErrNewIssueInsert(err) {
  639. return err
  640. }
  641. if i++; i == issueMaxDupIndexAttempts {
  642. break
  643. }
  644. log.Error("NewPullRequest: error attempting to insert the new issue; will retry. Original error: %v", err)
  645. }
  646. return fmt.Errorf("NewPullRequest: too many errors attempting to insert the new issue. Last error was: %v", err)
  647. }
  648. func newPullRequestAttempt(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest, patch []byte) (err error) {
  649. sess := x.NewSession()
  650. defer sess.Close()
  651. if err = sess.Begin(); err != nil {
  652. return err
  653. }
  654. if err = newIssue(sess, pull.Poster, NewIssueOptions{
  655. Repo: repo,
  656. Issue: pull,
  657. LabelIDs: labelIDs,
  658. Attachments: uuids,
  659. IsPull: true,
  660. }); err != nil {
  661. if IsErrUserDoesNotHaveAccessToRepo(err) || IsErrNewIssueInsert(err) {
  662. return err
  663. }
  664. return fmt.Errorf("newIssue: %v", err)
  665. }
  666. pr.Index = pull.Index
  667. pr.BaseRepo = repo
  668. pr.Status = PullRequestStatusChecking
  669. if len(patch) > 0 {
  670. if err = repo.savePatch(sess, pr.Index, patch); err != nil {
  671. return fmt.Errorf("SavePatch: %v", err)
  672. }
  673. if err = pr.testPatch(sess); err != nil {
  674. return fmt.Errorf("testPatch: %v", err)
  675. }
  676. }
  677. // No conflict appears after test means mergeable.
  678. if pr.Status == PullRequestStatusChecking {
  679. pr.Status = PullRequestStatusMergeable
  680. }
  681. pr.IssueID = pull.ID
  682. if _, err = sess.Insert(pr); err != nil {
  683. return fmt.Errorf("insert pull repo: %v", err)
  684. }
  685. if err = sess.Commit(); err != nil {
  686. return fmt.Errorf("Commit: %v", err)
  687. }
  688. return nil
  689. }
  690. // PullRequestsOptions holds the options for PRs
  691. type PullRequestsOptions struct {
  692. Page int
  693. State string
  694. SortType string
  695. Labels []string
  696. MilestoneID int64
  697. }
  698. func listPullRequestStatement(baseRepoID int64, opts *PullRequestsOptions) (*xorm.Session, error) {
  699. sess := x.Where("pull_request.base_repo_id=?", baseRepoID)
  700. sess.Join("INNER", "issue", "pull_request.issue_id = issue.id")
  701. switch opts.State {
  702. case "closed", "open":
  703. sess.And("issue.is_closed=?", opts.State == "closed")
  704. }
  705. if labelIDs, err := base.StringsToInt64s(opts.Labels); err != nil {
  706. return nil, err
  707. } else if len(labelIDs) > 0 {
  708. sess.Join("INNER", "issue_label", "issue.id = issue_label.issue_id").
  709. In("issue_label.label_id", labelIDs)
  710. }
  711. if opts.MilestoneID > 0 {
  712. sess.And("issue.milestone_id=?", opts.MilestoneID)
  713. }
  714. return sess, nil
  715. }
  716. // PullRequests returns all pull requests for a base Repo by the given conditions
  717. func PullRequests(baseRepoID int64, opts *PullRequestsOptions) ([]*PullRequest, int64, error) {
  718. if opts.Page <= 0 {
  719. opts.Page = 1
  720. }
  721. countSession, err := listPullRequestStatement(baseRepoID, opts)
  722. if err != nil {
  723. log.Error("listPullRequestStatement: %v", err)
  724. return nil, 0, err
  725. }
  726. maxResults, err := countSession.Count(new(PullRequest))
  727. if err != nil {
  728. log.Error("Count PRs: %v", err)
  729. return nil, maxResults, err
  730. }
  731. prs := make([]*PullRequest, 0, ItemsPerPage)
  732. findSession, err := listPullRequestStatement(baseRepoID, opts)
  733. sortIssuesSession(findSession, opts.SortType)
  734. if err != nil {
  735. log.Error("listPullRequestStatement: %v", err)
  736. return nil, maxResults, err
  737. }
  738. findSession.Limit(ItemsPerPage, (opts.Page-1)*ItemsPerPage)
  739. return prs, maxResults, findSession.Find(&prs)
  740. }
  741. // GetUnmergedPullRequest returns a pull request that is open and has not been merged
  742. // by given head/base and repo/branch.
  743. func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string) (*PullRequest, error) {
  744. pr := new(PullRequest)
  745. has, err := x.
  746. Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  747. headRepoID, headBranch, baseRepoID, baseBranch, false, false).
  748. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  749. Get(pr)
  750. if err != nil {
  751. return nil, err
  752. } else if !has {
  753. return nil, ErrPullRequestNotExist{0, 0, headRepoID, baseRepoID, headBranch, baseBranch}
  754. }
  755. return pr, nil
  756. }
  757. // GetUnmergedPullRequestsByHeadInfo returns all pull requests that are open and has not been merged
  758. // by given head information (repo and branch).
  759. func GetUnmergedPullRequestsByHeadInfo(repoID int64, branch string) ([]*PullRequest, error) {
  760. prs := make([]*PullRequest, 0, 2)
  761. return prs, x.
  762. Where("head_repo_id = ? AND head_branch = ? AND has_merged = ? AND issue.is_closed = ?",
  763. repoID, branch, false, false).
  764. Join("INNER", "issue", "issue.id = pull_request.issue_id").
  765. Find(&prs)
  766. }
  767. // GetLatestPullRequestByHeadInfo returns the latest pull request (regardless of its status)
  768. // by given head information (repo and branch).
  769. func GetLatestPullRequestByHeadInfo(repoID int64, branch string) (*PullRequest, error) {
  770. pr := new(PullRequest)
  771. has, err := x.
  772. Where("head_repo_id = ? AND head_branch = ?", repoID, branch).
  773. OrderBy("id DESC").
  774. Get(pr)
  775. if !has {
  776. return nil, err
  777. }
  778. return pr, err
  779. }
  780. // GetUnmergedPullRequestsByBaseInfo returns all pull requests that are open and has not been merged
  781. // by given base information (repo and branch).
  782. func GetUnmergedPullRequestsByBaseInfo(repoID int64, branch string) ([]*PullRequest, error) {
  783. prs := make([]*PullRequest, 0, 2)
  784. return prs, x.
  785. Where("base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  786. repoID, branch, false, false).
  787. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  788. Find(&prs)
  789. }
  790. // GetPullRequestByIndex returns a pull request by the given index
  791. func GetPullRequestByIndex(repoID int64, index int64) (*PullRequest, error) {
  792. pr := &PullRequest{
  793. BaseRepoID: repoID,
  794. Index: index,
  795. }
  796. has, err := x.Get(pr)
  797. if err != nil {
  798. return nil, err
  799. } else if !has {
  800. return nil, ErrPullRequestNotExist{0, 0, 0, repoID, "", ""}
  801. }
  802. if err = pr.LoadAttributes(); err != nil {
  803. return nil, err
  804. }
  805. if err = pr.LoadIssue(); err != nil {
  806. return nil, err
  807. }
  808. return pr, nil
  809. }
  810. func getPullRequestByID(e Engine, id int64) (*PullRequest, error) {
  811. pr := new(PullRequest)
  812. has, err := e.ID(id).Get(pr)
  813. if err != nil {
  814. return nil, err
  815. } else if !has {
  816. return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""}
  817. }
  818. return pr, pr.loadAttributes(e)
  819. }
  820. // GetPullRequestByID returns a pull request by given ID.
  821. func GetPullRequestByID(id int64) (*PullRequest, error) {
  822. return getPullRequestByID(x, id)
  823. }
  824. func getPullRequestByIssueID(e Engine, issueID int64) (*PullRequest, error) {
  825. pr := &PullRequest{
  826. IssueID: issueID,
  827. }
  828. has, err := e.Get(pr)
  829. if err != nil {
  830. return nil, err
  831. } else if !has {
  832. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  833. }
  834. return pr, pr.loadAttributes(e)
  835. }
  836. // GetPullRequestByIssueID returns pull request by given issue ID.
  837. func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) {
  838. return getPullRequestByIssueID(x, issueID)
  839. }
  840. // Update updates all fields of pull request.
  841. func (pr *PullRequest) Update() error {
  842. _, err := x.ID(pr.ID).AllCols().Update(pr)
  843. return err
  844. }
  845. // UpdateCols updates specific fields of pull request.
  846. func (pr *PullRequest) UpdateCols(cols ...string) error {
  847. _, err := x.ID(pr.ID).Cols(cols...).Update(pr)
  848. return err
  849. }
  850. // UpdatePatch generates and saves a new patch.
  851. func (pr *PullRequest) UpdatePatch() (err error) {
  852. if err = pr.GetHeadRepo(); err != nil {
  853. return fmt.Errorf("GetHeadRepo: %v", err)
  854. } else if pr.HeadRepo == nil {
  855. log.Trace("PullRequest[%d].UpdatePatch: ignored corrupted data", pr.ID)
  856. return nil
  857. }
  858. if err = pr.GetBaseRepo(); err != nil {
  859. return fmt.Errorf("GetBaseRepo: %v", err)
  860. }
  861. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  862. if err != nil {
  863. return fmt.Errorf("OpenRepository: %v", err)
  864. }
  865. // Add a temporary remote.
  866. tmpRemote := com.ToStr(time.Now().UnixNano())
  867. if err = headGitRepo.AddRemote(tmpRemote, RepoPath(pr.BaseRepo.MustOwner().Name, pr.BaseRepo.Name), true); err != nil {
  868. return fmt.Errorf("AddRemote: %v", err)
  869. }
  870. defer func() {
  871. if err := headGitRepo.RemoveRemote(tmpRemote); err != nil {
  872. log.Error("UpdatePatch: RemoveRemote: %s", err)
  873. }
  874. }()
  875. pr.MergeBase, _, err = headGitRepo.GetMergeBase(tmpRemote, pr.BaseBranch, pr.HeadBranch)
  876. if err != nil {
  877. return fmt.Errorf("GetMergeBase: %v", err)
  878. } else if err = pr.Update(); err != nil {
  879. return fmt.Errorf("Update: %v", err)
  880. }
  881. patch, err := headGitRepo.GetPatch(pr.MergeBase, pr.HeadBranch)
  882. if err != nil {
  883. return fmt.Errorf("GetPatch: %v", err)
  884. }
  885. if err = pr.BaseRepo.SavePatch(pr.Index, patch); err != nil {
  886. return fmt.Errorf("BaseRepo.SavePatch: %v", err)
  887. }
  888. return nil
  889. }
  890. // PushToBaseRepo pushes commits from branches of head repository to
  891. // corresponding branches of base repository.
  892. // FIXME: Only push branches that are actually updates?
  893. func (pr *PullRequest) PushToBaseRepo() (err error) {
  894. log.Trace("PushToBaseRepo[%d]: pushing commits to base repo '%s'", pr.BaseRepoID, pr.GetGitRefName())
  895. headRepoPath := pr.HeadRepo.RepoPath()
  896. headGitRepo, err := git.OpenRepository(headRepoPath)
  897. if err != nil {
  898. return fmt.Errorf("OpenRepository: %v", err)
  899. }
  900. tmpRemoteName := fmt.Sprintf("tmp-pull-%d", pr.ID)
  901. if err = headGitRepo.AddRemote(tmpRemoteName, pr.BaseRepo.RepoPath(), false); err != nil {
  902. return fmt.Errorf("headGitRepo.AddRemote: %v", err)
  903. }
  904. // Make sure to remove the remote even if the push fails
  905. defer func() {
  906. if err := headGitRepo.RemoveRemote(tmpRemoteName); err != nil {
  907. log.Error("PushToBaseRepo: RemoveRemote: %s", err)
  908. }
  909. }()
  910. headFile := pr.GetGitRefName()
  911. // Remove head in case there is a conflict.
  912. file := path.Join(pr.BaseRepo.RepoPath(), headFile)
  913. _ = os.Remove(file)
  914. if err = git.Push(headRepoPath, git.PushOptions{
  915. Remote: tmpRemoteName,
  916. Branch: fmt.Sprintf("%s:%s", pr.HeadBranch, headFile),
  917. Force: true,
  918. }); err != nil {
  919. return fmt.Errorf("Push: %v", err)
  920. }
  921. return nil
  922. }
  923. // AddToTaskQueue adds itself to pull request test task queue.
  924. func (pr *PullRequest) AddToTaskQueue() {
  925. go pullRequestQueue.AddFunc(pr.ID, func() {
  926. pr.Status = PullRequestStatusChecking
  927. if err := pr.UpdateCols("status"); err != nil {
  928. log.Error("AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
  929. }
  930. })
  931. }
  932. // PullRequestList defines a list of pull requests
  933. type PullRequestList []*PullRequest
  934. func (prs PullRequestList) loadAttributes(e Engine) error {
  935. if len(prs) == 0 {
  936. return nil
  937. }
  938. // Load issues.
  939. issueIDs := prs.getIssueIDs()
  940. issues := make([]*Issue, 0, len(issueIDs))
  941. if err := e.
  942. Where("id > 0").
  943. In("id", issueIDs).
  944. Find(&issues); err != nil {
  945. return fmt.Errorf("find issues: %v", err)
  946. }
  947. set := make(map[int64]*Issue)
  948. for i := range issues {
  949. set[issues[i].ID] = issues[i]
  950. }
  951. for i := range prs {
  952. prs[i].Issue = set[prs[i].IssueID]
  953. }
  954. return nil
  955. }
  956. func (prs PullRequestList) getIssueIDs() []int64 {
  957. issueIDs := make([]int64, 0, len(prs))
  958. for i := range prs {
  959. issueIDs = append(issueIDs, prs[i].IssueID)
  960. }
  961. return issueIDs
  962. }
  963. // LoadAttributes load all the prs attributes
  964. func (prs PullRequestList) LoadAttributes() error {
  965. return prs.loadAttributes(x)
  966. }
  967. func (prs PullRequestList) invalidateCodeComments(e Engine, doer *User, repo *git.Repository, branch string) error {
  968. if len(prs) == 0 {
  969. return nil
  970. }
  971. issueIDs := prs.getIssueIDs()
  972. var codeComments []*Comment
  973. if err := e.
  974. Where("type = ? and invalidated = ?", CommentTypeCode, false).
  975. In("issue_id", issueIDs).
  976. Find(&codeComments); err != nil {
  977. return fmt.Errorf("find code comments: %v", err)
  978. }
  979. for _, comment := range codeComments {
  980. if err := comment.CheckInvalidation(repo, doer, branch); err != nil {
  981. return err
  982. }
  983. }
  984. return nil
  985. }
  986. // InvalidateCodeComments will lookup the prs for code comments which got invalidated by change
  987. func (prs PullRequestList) InvalidateCodeComments(doer *User, repo *git.Repository, branch string) error {
  988. return prs.invalidateCodeComments(x, doer, repo, branch)
  989. }
  990. // checkAndUpdateStatus checks if pull request is possible to leaving checking status,
  991. // and set to be either conflict or mergeable.
  992. func (pr *PullRequest) checkAndUpdateStatus() {
  993. // Status is not changed to conflict means mergeable.
  994. if pr.Status == PullRequestStatusChecking {
  995. pr.Status = PullRequestStatusMergeable
  996. }
  997. // Make sure there is no waiting test to process before leaving the checking status.
  998. if !pullRequestQueue.Exist(pr.ID) {
  999. if err := pr.UpdateCols("status, conflicted_files"); err != nil {
  1000. log.Error("Update[%d]: %v", pr.ID, err)
  1001. }
  1002. }
  1003. }
  1004. // IsWorkInProgress determine if the Pull Request is a Work In Progress by its title
  1005. func (pr *PullRequest) IsWorkInProgress() bool {
  1006. if err := pr.LoadIssue(); err != nil {
  1007. log.Error("LoadIssue: %v", err)
  1008. return false
  1009. }
  1010. for _, prefix := range setting.Repository.PullRequest.WorkInProgressPrefixes {
  1011. if strings.HasPrefix(strings.ToUpper(pr.Issue.Title), prefix) {
  1012. return true
  1013. }
  1014. }
  1015. return false
  1016. }
  1017. // IsFilesConflicted determines if the Pull Request has changes conflicting with the target branch.
  1018. func (pr *PullRequest) IsFilesConflicted() bool {
  1019. return len(pr.ConflictedFiles) > 0
  1020. }
  1021. // GetWorkInProgressPrefix returns the prefix used to mark the pull request as a work in progress.
  1022. // It returns an empty string when none were found
  1023. func (pr *PullRequest) GetWorkInProgressPrefix() string {
  1024. if err := pr.LoadIssue(); err != nil {
  1025. log.Error("LoadIssue: %v", err)
  1026. return ""
  1027. }
  1028. for _, prefix := range setting.Repository.PullRequest.WorkInProgressPrefixes {
  1029. if strings.HasPrefix(strings.ToUpper(pr.Issue.Title), prefix) {
  1030. return pr.Issue.Title[0:len(prefix)]
  1031. }
  1032. }
  1033. return ""
  1034. }
  1035. // TestPullRequests checks and tests untested patches of pull requests.
  1036. // TODO: test more pull requests at same time.
  1037. func TestPullRequests() {
  1038. prs := make([]*PullRequest, 0, 10)
  1039. err := x.Where("status = ?", PullRequestStatusChecking).Find(&prs)
  1040. if err != nil {
  1041. log.Error("Find Checking PRs: %v", err)
  1042. return
  1043. }
  1044. var checkedPRs = make(map[int64]struct{})
  1045. // Update pull request status.
  1046. for _, pr := range prs {
  1047. checkedPRs[pr.ID] = struct{}{}
  1048. if err := pr.GetBaseRepo(); err != nil {
  1049. log.Error("GetBaseRepo: %v", err)
  1050. continue
  1051. }
  1052. if pr.manuallyMerged() {
  1053. continue
  1054. }
  1055. if err := pr.testPatch(x); err != nil {
  1056. log.Error("testPatch: %v", err)
  1057. continue
  1058. }
  1059. pr.checkAndUpdateStatus()
  1060. }
  1061. // Start listening on new test requests.
  1062. for prID := range pullRequestQueue.Queue() {
  1063. log.Trace("TestPullRequests[%v]: processing test task", prID)
  1064. pullRequestQueue.Remove(prID)
  1065. id := com.StrTo(prID).MustInt64()
  1066. if _, ok := checkedPRs[id]; ok {
  1067. continue
  1068. }
  1069. pr, err := GetPullRequestByID(id)
  1070. if err != nil {
  1071. log.Error("GetPullRequestByID[%s]: %v", prID, err)
  1072. continue
  1073. } else if pr.manuallyMerged() {
  1074. continue
  1075. } else if err = pr.testPatch(x); err != nil {
  1076. log.Error("testPatch[%d]: %v", pr.ID, err)
  1077. continue
  1078. }
  1079. pr.checkAndUpdateStatus()
  1080. }
  1081. }
  1082. // InitTestPullRequests runs the task to test all the checking status pull requests
  1083. func InitTestPullRequests() {
  1084. go TestPullRequests()
  1085. }
上海开阖软件有限公司 沪ICP备12045867号-1