fix(cli): 在pnpm工作空间中的项目,保持package.json不受配置中的packages影响

This commit is contained in:
roymondchen 2025-08-27 16:48:51 +08:00
parent 9f350541bf
commit a10f9d230d

View File

@ -1,11 +1,35 @@
import fs from 'node:fs'; import fs from 'node:fs';
import path from 'node:path'; import path from 'node:path';
import process from 'node:process';
const windowsPathRegex = /^(?:[a-zA-Z]:|[\\/]{2}[^\\/]+[\\/]+[^\\/]+)?[\\/]$/;
export const isRootPath = (path: string) => {
if (typeof path !== 'string') {
throw new TypeError('Expected a string');
}
path = path.trim();
// While it's unclear how long a root path can be on Windows, it definitely cannot be longer than 100 characters.
if (path === '' || path.length > 100) {
return false;
}
return process.platform === 'win32' ? windowsPathRegex.test(path) : path === '/';
};
export const backupFile = (runtimeSource: string, file: string) => { export const backupFile = (runtimeSource: string, file: string) => {
if (isRootPath(runtimeSource)) {
return;
}
const filePath = path.join(runtimeSource, file); const filePath = path.join(runtimeSource, file);
if (fs.existsSync(filePath)) { if (fs.existsSync(filePath)) {
fs.copyFileSync(filePath, `${filePath}.bak`); fs.copyFileSync(filePath, `${filePath}.bak`);
} else {
backupFile(path.resolve(runtimeSource, '..'), file);
} }
}; };
@ -26,11 +50,17 @@ export const backupLock = (runtimeSource: string, npmType: string) => {
}; };
export const restoreFile = (runtimeSource: string, file: string) => { export const restoreFile = (runtimeSource: string, file: string) => {
if (isRootPath(runtimeSource)) {
return;
}
const filePath = path.join(runtimeSource, file); const filePath = path.join(runtimeSource, file);
if (fs.existsSync(filePath)) { if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath); fs.unlinkSync(filePath);
fs.renameSync(`${filePath}.bak`, filePath); fs.renameSync(`${filePath}.bak`, filePath);
} else {
restoreFile(path.resolve(runtimeSource, '..'), file);
} }
}; };