@yeepay/yeepay-cli
Version:
易宝前端脚手架
99 lines (87 loc) • 3.57 kB
JavaScript
import fs from 'fs';
import path from 'path';
import { $, cd } from 'zx';
export default class ChangeFile {
/**
* 修改 package.json 中的项目名称
* @param {string} projectPath - 项目路径
* @param {string} newProjectName - 新的项目名称
*/
async changePackageJson(newProjectName) {
try {
const packageJsonPath = path.join(process.cwd(), 'package.json');
// 读取 package.json 文件
const packageData = JSON.parse(await fs.promises.readFile(packageJsonPath, 'utf8'));
// 修改项目名称
packageData.name = newProjectName;
// 写入修改后的内容
await fs.promises.writeFile(
packageJsonPath,
JSON.stringify(packageData, null, 2),
'utf8'
);
} catch (error) {
throw new Error(`修改 package.json 失败: ${error.message}`);
}
}
/**
* 在 README.md 中添加项目负责人信息
*/
async addProjectOwner() {
try {
const readmePath = path.join(process.cwd(), 'README.md');
// 获取 git config 中的 user.name
const { stdout: userName } = await $`git config user.name`.quiet();
const ownerName = userName.trim();
// 读取 README.md 文件内容
let content = await fs.promises.readFile(readmePath, 'utf8');
// 将内容分割成行
const lines = content.split('\n');
// 检查是否存在"项目负责人:"
const hasOwnerLine = lines.some(line => line.includes('项目负责人:'));
if (!hasOwnerLine) {
// 如果不存在,在第二行插入
lines.splice(1, 0, `项目负责人:${ownerName}`);
} else {
// 如果存在,更新现有行
lines.forEach((line, index) => {
if (line.includes('项目负责人:')) {
lines[index] = `项目负责人:${ownerName}`;
}
});
}
// 写入更新后的内容
await fs.promises.writeFile(readmePath, lines.join('\n'), 'utf8');
} catch (error) {
throw new Error(`更新 README.md 失败: ${error.message}`);
}
}
async changeAllText(newProjectName, replaceText) {
const targetDir = process.cwd();
const walk = async (dir) => {
const files = fs.readdirSync(dir);
for (const file of files) {
const filePath = path.join(dir, file);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
if (['node_modules', '.git','README.md','package.json'].includes(file)) continue;
await walk(filePath);
} else {
// 只处理文本文件
let content;
try {
content = fs.readFileSync(filePath, 'utf8');
} catch (e) {
// 不是文本文件直接跳过
continue;
}
if (content.includes(replaceText)) {
const newContent = content.split(replaceText).join(newProjectName);
fs.writeFileSync(filePath, newContent, 'utf8');
}
}
}
};
await walk(targetDir);
}
}