GetFileDetail.js 2.9 KB

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