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); } };