From a10f9d230d93064c28ff82f2c3aba2679f8fe495 Mon Sep 17 00:00:00 2001 From: roymondchen Date: Wed, 27 Aug 2025 16:48:51 +0800 Subject: [PATCH] =?UTF-8?q?fix(cli):=20=E5=9C=A8pnpm=E5=B7=A5=E4=BD=9C?= =?UTF-8?q?=E7=A9=BA=E9=97=B4=E4=B8=AD=E7=9A=84=E9=A1=B9=E7=9B=AE=EF=BC=8C?= =?UTF-8?q?=E4=BF=9D=E6=8C=81package.json=E4=B8=8D=E5=8F=97=E9=85=8D?= =?UTF-8?q?=E7=BD=AE=E4=B8=AD=E7=9A=84packages=E5=BD=B1=E5=93=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/cli/src/utils/backupPackageFile.ts | 30 +++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/packages/cli/src/utils/backupPackageFile.ts b/packages/cli/src/utils/backupPackageFile.ts index 9655ddf9..1fce781d 100644 --- a/packages/cli/src/utils/backupPackageFile.ts +++ b/packages/cli/src/utils/backupPackageFile.ts @@ -1,11 +1,35 @@ import fs from 'node:fs'; 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) => { + if (isRootPath(runtimeSource)) { + return; + } + const filePath = path.join(runtimeSource, file); if (fs.existsSync(filePath)) { 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) => { + if (isRootPath(runtimeSource)) { + return; + } + const filePath = path.join(runtimeSource, file); if (fs.existsSync(filePath)) { fs.unlinkSync(filePath); fs.renameSync(`${filePath}.bak`, filePath); + } else { + restoreFile(path.resolve(runtimeSource, '..'), file); } };