在一个长期维护的项目中,为了更好排查之前已上线或使用的版本的问题,我们可以在浏览器控制台中打印出git信息,如:git号、git提交时间、打包时间等,也可以生成一个git信息文件,方便后续排查问题。
上代码
const execSync = require('child_process').execSync;
const fs = require('fs');
const path = require('path');
// 读取package.json文件
const data = fs.readFileSync(path.resolve(__dirname, './package.json'));
const packageData = JSON.parse(data);
// 获取git信息的相关命令
const COMMITHASH_COMMAND = 'rev-parse HEAD'; // 获取git完整提交哈希值
const VERSION_COMMAND = 'describe --always'; // 获取git前8位提交哈希值
const BRANCH_COMMAND = 'rev-parse --abbrev-ref HEAD'; // 获取分支名
const NEW_COMMIT_MESSAGE = 'log -1 --pretty=%B'; // 获取提交信息
const COMMIT_TIME = 'show -s --format=%cd'; // 获取提交时间
try {
console.log('正在生成版本及git提交信息...');
const d = new Date();
const commitId = execSync(`git ${COMMITHASH_COMMAND}`).toString().trim();
const branch = execSync(`git ${BRANCH_COMMAND}`).toString().trim();
const release = execSync(`git ${VERSION_COMMAND}`).toString().trim();
// const commitMessage = execSync(`git ${NEW_COMMIT_MESSAGE}`).toString().trim();
const commitTime = execSync(`git ${COMMIT_TIME}`).toString().trim();
const commitDate = new Date(commitTime);
const gitCommitInfo = {
COMMIT_ID: commitId,
Branch: branch,
// Release: release,
// CommitMessage: commitMessage,
CommitTime: commitDate ? getTimeStr(commitDate) : commitTime,
PackingTime: getTimeStr(d),
Version: packageData.version,
}
const versionStr = `
COMMIT_ID: ${commitId}
Branch: ${branch}
Release: ${release}
CommitTime: ${commitDate ? getTimeStr(commitDate) : commitTime}
PackingTime: ${getTimeStr(d)}
Version: ${packageData.version}
`;
fs.writeFileSync(path.resolve(__dirname, `./public/VERSION`), versionStr);
console.log('版本及git提交信息生成完成!耗时:' + (new Date().getTime() - d.getTime()) + 'ms');
} catch (e) {
throw new Error(e);
}
function getTimeStr(date) {
let month = date.getMonth() + 1;
let day = date.getDate();
let hours = date.getHours();
let minutes = date.getMinutes();
let seconds = date.getSeconds();
month = month < 10 ? ('0' + month) : month;
day = day < 10 ? ('0' + day) : day;
hours = hours < 10 ? ('0' + hours) : hours;
minutes = minutes < 10 ? ('0' + minutes) : minutes;
seconds = seconds < 10 ? ('0' + seconds) : seconds;
let time = `${date.getFullYear()}/${month}/${day} ${hours}:${minutes}:${seconds}`;
return time;
}
输出的VERSION文件内容如下
COMMIT_ID: a1f2d95008aa46e718487ef9b69bcca2255a9e13
Branch: develop_liyn_v3
Release: a1f2d950
CommitTime: 2024/12/26 14:08:19
PackingTime: 2024/12/27 09:02:14
Version: 0.2.1
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。