const API = require("../../lib/API") const AccessControl = require("../../lib/AccessControl") const { BaseStdResponse } = require("../../BaseStdResponse") const db = require("../../plugin/DataBase/db") const path = require('path') const { isBinaryFileSync } = require('isbinaryfile') const simpleGit = require('simple-git') class GetFileDetail extends API { constructor() { super() this.setMethod("GET") this.setPath("/Repos/GetFileDetail") } isBinaryFile(filePath) { try { return isBinaryFileSync(filePath) } catch (err) { return false } } async onRequest(req, res) { let { uuid, session, id, filePath, hash } = req.query if ([uuid, session, id, filePath].some(value => value === '' || value === null || value === undefined)) return res.json({ ...BaseStdResponse.MISSING_PARAMETER }) // 检查 session if (!await AccessControl.checkSession(uuid, session)) return res.status(401).json({ ...BaseStdResponse.ACCESS_DENIED }) let sql = 'SELECT name, logo, create_time, update_time, state, path, url FROM repos WHERE create_user = ? AND id = ?' let r = await db.query(sql, [uuid, id]) if (!r || r.length === 0) return res.json({ ...BaseStdResponse.ERR, msg: '未找到仓库' }) if (r[0].state !== 1 || !r[0].path) return res.json({ ...BaseStdResponse.ERR, msg: '仓库未成功克隆!' }) try { const git = simpleGit() await git.cwd(r[0].path) const targetHash = hash || 'HEAD' const log = await git.log({ file: filePath, n: 1, format: { hash: '%H', abbrevHash: '%h', title: '%s', message: '%B', author_name: '%aN', email: '%aE', date: '%ad' } }) if (this.isBinaryFile(path.join(r[0].path, filePath))) return res.json({ ...BaseStdResponse.OK, type: 'binary', commit: log }) const content = await git.show([`${targetHash}:${filePath}`]) res.json({ ...BaseStdResponse.OK, type: 'text', commit: log, content: btoa(encodeURI(content)) }) } catch (error) { this.logger.error('获取文件详情失败!' + error.stack) return res.json({ ...BaseStdResponse.ERR, msg: '获取文件详情失败!' }) } } } module.exports.GetFileDetail = GetFileDetail