ChangeBranch.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. const API = require("../../lib/API")
  2. const AccessControl = require("../../lib/AccessControl")
  3. const { BaseStdResponse } = require("../../BaseStdResponse")
  4. const db = require("../../plugin/DataBase/db")
  5. const redis = require('../../plugin/DataBase/Redis')
  6. const simpleGit = require('simple-git')
  7. class ChangeBranch extends API {
  8. constructor() {
  9. super()
  10. this.setMethod("GET")
  11. this.setPath("/GitActions/ChangeBranch")
  12. }
  13. async onRequest(req, res) {
  14. let { uuid, session, id, branch } = req.query
  15. if ([uuid, session, id, branch ].some(value => value === '' || value === null || value === undefined))
  16. return res.json({
  17. ...BaseStdResponse.MISSING_PARAMETER
  18. })
  19. // 检查 session
  20. if (!await AccessControl.checkSession(uuid, session))
  21. return res.status(401).json({
  22. ...BaseStdResponse.ACCESS_DENIED
  23. })
  24. let sql = 'SELECT state, path, url FROM repos WHERE create_user = ? AND id = ?'
  25. let r = await db.query(sql, [uuid, id])
  26. if (!r || r.length === 0)
  27. return res.json({
  28. ...BaseStdResponse.ERR,
  29. msg: '未找到仓库'
  30. })
  31. if (r[0].state !== 1 || !r[0].path)
  32. return res.json({
  33. ...BaseStdResponse.ERR,
  34. msg: '仓库未成功克隆!'
  35. })
  36. try {
  37. const redisKey = [`gitLogs:${r[0].path}`,`contributors:${r[0].path}`,`codeStats:${r[0].path}`]
  38. await redis.del(redisKey)
  39. const git = simpleGit()
  40. await git.cwd(r[0].path)
  41. const branches = await git.branch()
  42. const remoteBranch = 'remotes/origin/' + branch
  43. if(!branches.all.includes(branch) && !branches.all.includes(remoteBranch))
  44. return res.json({
  45. ...BaseStdResponse.ERR,
  46. msg: '分支不存在!'
  47. })
  48. await git.checkout(branch)
  49. res.json({
  50. ...BaseStdResponse.OK
  51. })
  52. } catch (error) {
  53. this.logger.error('切换仓库分支失败!' + error.stack)
  54. return res.json({
  55. ...BaseStdResponse.ERR,
  56. msg: '切换仓库分支失败!'
  57. })
  58. }
  59. }
  60. }
  61. module.exports.ChangeBranch = ChangeBranch