GetFileDetail.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 simpleGit = require('simple-git')
  6. class GetFileDetail extends API {
  7. constructor() {
  8. super()
  9. this.setMethod("GET")
  10. this.setPath("/Repos/GetFileDetail")
  11. }
  12. async onRequest(req, res) {
  13. let { uuid, session, id, filePath } = req.query
  14. if ([uuid, session, id].some(value => value === '' || value === null || value === undefined))
  15. return res.json({
  16. ...BaseStdResponse.MISSING_PARAMETER
  17. })
  18. // 检查 session
  19. if (!await AccessControl.checkSession(uuid, session))
  20. return res.status(401).json({
  21. ...BaseStdResponse.ACCESS_DENIED
  22. })
  23. let sql = 'SELECT name, logo, create_time, update_time, state, path, url FROM repos WHERE create_user = ? AND id = ?'
  24. let r = await db.query(sql, [uuid, id])
  25. if (!r || r.length === 0)
  26. return res.json({
  27. ...BaseStdResponse.ERR,
  28. msg: '未找到仓库'
  29. })
  30. if (r[0].state !== 1 || !r[0].path)
  31. return res.json({
  32. ...BaseStdResponse.ERR,
  33. msg: '仓库未成功克隆!'
  34. })
  35. try {
  36. const git = simpleGit()
  37. await git.cwd(r[0].path)
  38. const log = await git.log({
  39. file: filePath,
  40. n: 1,
  41. format: {
  42. hash: '%H',
  43. abbrevHash: '%h',
  44. title: '%s',
  45. message: '%B',
  46. author_name: '%aN',
  47. email: '%aE',
  48. date: '%ad',
  49. }
  50. })
  51. const content = await git.show([`HEAD:${filePath}`])
  52. res.json({
  53. ...BaseStdResponse.OK,
  54. commit: log,
  55. content: btoa(encodeURI(content))
  56. })
  57. } catch (error) {
  58. this.logger.error('获取文件详情失败!' + error.stack)
  59. return res.json({
  60. ...BaseStdResponse.ERR,
  61. msg: '获取文件详情失败!'
  62. })
  63. }
  64. }
  65. }
  66. module.exports.GetFileDetail = GetFileDetail