直接上代码
nodejs
import * as path from 'path';
import * as fs from 'fs-extra';
import { execSync } from 'child_process';
const getNewVersion = (version) => {
let [major, minor, patch] = version.split('.');
if (+patch >= 100) {
minor = +minor + 1;
patch = 0;
} else {
patch = +patch + 1;
}
if (+minor >= 100) {
major = +major + 1;
minor = 0;
}
return `${major}.${minor}.${patch}`;
};
// 修改.npmrc文件,使用户通过token值登录npm,绕过使用密码登录
const modifyNpmRc = (token) => {
// TODO: npmrcUrl需要更改为服务器对应的地址
const npmrcUrl = 'C:\\Users\\90962\\.npmrc';
const originNpmRc = fs.readFileSync(npmrcUrl, 'utf8');
const newNpmRc = originNpmRc.replace(/\/\/registry\.npmjs\.org\/:_authToken=.*?(\n|$)/g, '').replace(/\n$/, '');
fs.outputFileSync(npmrcUrl, `${newNpmRc}\n//registry.npmjs.org/:_authToken=${token}\n`);
};
// token需要用户先在对应包所属的npm创建并填写,保存在数据库中
// token获取地址: https://www.npmjs.com/settings/{username}/tokens
const autoPublish = async (content, {
gitUrl = 'https://gitee.com/loma18/test-horse-npm-publish.git',
token = 'npm_U34BF6z42iN0TbaWYBQB2NPoUmvxxxxxxxxx',
} = {}) => {
console.log('自动发布中...');
const cwd = process.cwd();
const targetName = gitUrl.match(/.+\/(.*)\.git/)[1];
const targetDir = path.join(cwd, targetName); // 目标目录
if (fs.existsSync(targetDir)) {
await fs.remove(targetDir);
console.log('2');
}
console.log('代码下载开始...');
execSync(`git clone ${gitUrl}`, { cwd: './' });
console.log('代码下载结束');
// 要改的文件
console.log('代码修改中...');
let newVersion = 'version:';
// 修改版本号
const pkgStr = fs.readFileSync(`${targetDir}/package.json`, 'utf8').replace(/(?<="version":\s?")(.*)?(?=")/, (...rest) => {
const [, curVersion] = rest;
newVersion = getNewVersion(curVersion);
return newVersion;
});
fs.outputFileSync(`${targetDir}/package.json`, pkgStr, 'utf8');
fs.outputFileSync(`${targetDir}/index.js`, content, 'utf8');
console.log(`代码修改成功-version:${newVersion}`);
const config = { cwd: targetDir };
// git提交修改
console.log('git提交中...');
execSync('git init', config);
execSync('git add .', config);
execSync('git commit -m change-index', config);
execSync('git push -u origin master', config);
console.log('git提交成功');
// npm发版
console.log('自动发布中...');
modifyNpmRc(token);
execSync('npm publish --registry=https://registry.npmjs.org/', { cwd: targetDir });
console.log('自动发布成功');
// 移除已下载文件
console.log('清除已下载文件...');
fs.remove(targetDir);
console.log('清除已下载文件结束');
};
export {
autoPublish,
};
注:以上代码需在nodejs环境下执行
总体流程 就是:
1、前端将要改的数据传到后端nodejs中
2、后端拉取git代码到本地,并用前端数据覆盖修改对应的文件
3、git提交保存修改的文件
4、npm发布
其中这里有个小坑,就是npm一般登录是用密码的,需要有交互式命令控制台,为了完全自动化发布,需要用到npm提供的token方式。在https://www.npmjs.com/settings/{username}/tokens中获取(需登录),username就是你的用户名。将token保存到.npmrc文件中,形如:
//registry.npmjs.org/:_authToken=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