import process from 'process' import child_process from 'child_process' import fs from 'fs' import path from 'path' import axios from 'axios' import { fileURLToPath } from 'url' import compressing from 'compressing' import packageJson from '../package.json' const __filename = fileURLToPath(import.meta.url) const __dirname = path.dirname(__filename) function parseTime(time, format = 'yyyy-MM-dd hh:mm:ss') { const date = time instanceof Date ? time : new Date(time) const o = { 'M+': date.getMonth() + 1, // 月份 'd+': date.getDate(), // 日 'h+': date.getHours(), // 小时 'm+': date.getMinutes(), // 分 's+': date.getSeconds(), // 秒 'q+': Math.floor((date.getMonth() + 3) / 3), // 季度 S: date.getMilliseconds() // 毫秒 } if (/(y+)/.test(format)) { format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)) } for (const k in o) { if (new RegExp('(' + k + ')').test(format)) { format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)) } } return format } let hash function getHash() { if (!hash) { try { hash = child_process.execSync('git rev-parse HEAD').slice(0, 6) } catch (e) { console.log('------------------读取版本Hash失败---------------') console.warn(e) hash = '000000' } } return hash } let branchName function getBranchName() { if (!branchName) { try { branchName = child_process.execSync('git symbolic-ref --short -q HEAD') branchName = branchName.subarray(0, branchName.length - 1) } catch (e) { console.log('------------------读取分支名称失败---------------') console.warn(e) branchName = 'UNKNOW' } } return branchName } function openFolderBySystem(folderPath) { try { if (process.platform === 'win32') { child_process.spawn('cmd', ['/c', 'start', '', folderPath], { detached: true, stdio: 'ignore' }) return } if (process.platform === 'darwin') { child_process.spawn('open', [folderPath], { detached: true, stdio: 'ignore' }) return } child_process.spawn('xdg-open', [folderPath], { detached: true, stdio: 'ignore' }) } catch (e) { console.log('------------------打开输出目录失败---------------') console.warn(e) } } function getVersion(date, mode) { return `${parseTime(date, 'yyyy-MM-dd hh:mm:ss')} branch:${getBranchName()} ${getHash()} mode:${mode}` } export default function codeVersion() { const virtualModuleId = 'virtual:version' const resolvedVirtualModuleId = '\0' + virtualModuleId const date = new Date() let config return { name: 'vite-plugin-code-version', apply(_config, { command }) { config = { ..._config, command } return true }, resolveId(id) { if (id === virtualModuleId) { return resolvedVirtualModuleId } }, load(id) { if (id === resolvedVirtualModuleId) { return `export default "${config.command === 'serve' ? 'dev' : getVersion(date, config.mode)}"` } }, async writeBundle() { if (config.command === 'build') { const projectPath = path.join(__dirname, '../') const distPath = projectPath + 'dist' let versionJson = { artifactId: packageJson.name, version: packageJson.version, appId: packageJson.appId, codeId: packageJson.codeId, codeVersion: getVersion(date, config.mode) } if (packageJson.increApi) { // 获取版本信息 try { console.log('------------------正在写入升级记录---------------') const res = await axios.default({ url: packageJson.increApi + '?appId=' + packageJson.appId + '&codeId=' + packageJson.codeId, method: 'get', timeout: 5000 }) const { code, data } = res.data if (code === 0 && data) { versionJson = { ...versionJson, artifactId: packageJson.name, upgradeId: data.upgradeId, version: data.version, releaseTime: data.releaseTime, fromCommit: data.fromCommit, untilCommit: data.untilCommit, newFeatures: data.newFeatures, repair: data.repair, other: data.other, operId: data.operId, operName: data.operName } console.log('------------------写入升级记录成功---------------') } } catch (e) { console.log(e.message) console.log('------------------提交升级记录到远端失败---------------') } } fs.mkdirSync(distPath + '/increpack-config') fs.writeFileSync(distPath + '/increpack-config/version.json', JSON.stringify(versionJson), 'utf8') // eslint-disable-next-line no-undef const increName = `${process.env.VITE_PROJECT_NAME}-${config.mode}-${parseTime(date, 'yyyy-MM-dd')}-${getBranchName()}-${getHash()}.zip` // 打包压缩 // eslint-disable-next-line no-undef if (process.env.VITE_COMPRESS_DIST !== '0') { const tempFile = projectPath + '/' + increName await compressing.zip .compressDir(distPath, tempFile, { ignoreBase: true }) .then(() => { // 剪切回dist目录下 fs.renameSync(tempFile, distPath + '/' + increName) console.log('------------------打包成功------------------') console.log(increName) }) .catch((err) => { console.error(err) }) } openFolderBySystem(distPath) } } } }