From ca990561d4adf45fcd9a64ada1d9f8ac574192d0 Mon Sep 17 00:00:00 2001 From: Tushar Singh Date: Sun, 14 May 2023 12:00:22 +0530 Subject: [PATCH] mkdirP: don't throw errors if windows drive exists --- packages/io/__tests__/io.test.ts | 19 +++++++++++++++++++ packages/io/src/io.ts | 12 +++++++++++- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/packages/io/__tests__/io.test.ts b/packages/io/__tests__/io.test.ts index c05be13f..82a3d402 100644 --- a/packages/io/__tests__/io.test.ts +++ b/packages/io/__tests__/io.test.ts @@ -864,6 +864,25 @@ describe('mkdirP', () => { (await fs.lstat(path.join(realDirPath, 'sub_dir'))).isDirectory() ).toBe(true) }) + + if (ioUtil.IS_WINDOWS) { + it('show error only if Windows drive does not exist', async () => { + let errMsg: string + const driveRoot = path.parse(getTestTemp()).root + // Assuming 'A:\' is not a common Windows drive lets us test for a non-existing drive + for (const testPath of [driveRoot, 'A:\\']) { + if (await ioUtil.exists(testPath)) { + await io.mkdirP(testPath) + } else { + errMsg = `Drive '${testPath}' does not exist.` + await expect(io.mkdirP(testPath)).rejects.toHaveProperty( + 'message', + errMsg + ) + } + } + }) + } }) describe('which', () => { diff --git a/packages/io/src/io.ts b/packages/io/src/io.ts index bbd8efd3..4b5a6ba5 100644 --- a/packages/io/src/io.ts +++ b/packages/io/src/io.ts @@ -141,7 +141,17 @@ export async function rmRF(inputPath: string): Promise { */ export async function mkdirP(fsPath: string): Promise { ok(fsPath, 'a path argument must be provided') - await ioUtil.mkdir(fsPath, {recursive: true}) + // mkdirP would throw EPERM error if `fsPath` is a Windows drive root dir, e.g. 'C:\' + // even when it exists. This aligns with node's fs.mkdir impl. However, mkdirP shouldn't + // throw errors if `fsPath` exists regardless of the underlying platform. + // In this case, we will only check if drive exists and throw an error if it doesn't. + if (ioUtil.IS_WINDOWS && path.parse(fsPath).root === fsPath) { + if (!(await ioUtil.exists(fsPath))) { + throw new Error(`Drive '${fsPath}' does not exist.`) + } + } else { + await ioUtil.mkdir(fsPath, {recursive: true}) + } } /**