GetFileDetail.js 2.8 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 } = req.query
  23. if ([uuid, session, id].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 log = await git.log({
  48. file: filePath,
  49. n: 1,
  50. format: {
  51. hash: '%H',
  52. abbrevHash: '%h',
  53. title: '%s',
  54. message: '%B',
  55. author_name: '%aN',
  56. email: '%aE',
  57. date: '%ad',
  58. }
  59. })
  60. if(this.isBinaryFile(path.join(r[0].path, filePath)))
  61. return res.json({
  62. ...BaseStdResponse.OK,
  63. type: 'binary',
  64. commit: log
  65. })
  66. const content = await git.show([`HEAD:${filePath}`])
  67. res.json({
  68. ...BaseStdResponse.OK,
  69. type: 'text',
  70. commit: log,
  71. content: btoa(encodeURI(content))
  72. })
  73. } catch (error) {
  74. this.logger.error('获取文件详情失败!' + error.stack)
  75. return res.json({
  76. ...BaseStdResponse.ERR,
  77. msg: '获取文件详情失败!'
  78. })
  79. }
  80. }
  81. }
  82. module.exports.GetFileDetail = GetFileDetail