diff --git a/src/features/clean.ts b/src/features/clean.ts index 5ab936b03..b9e92e494 100644 --- a/src/features/clean.ts +++ b/src/features/clean.ts @@ -63,7 +63,7 @@ export function resolveClean( clean = [] } - if (clean.some((item) => path.resolve(item) === cwd)) { + if (clean.some((item) => path.resolve(cwd, item) === cwd)) { throw new Error( 'Cannot clean the current working directory. Please specify a different path to clean option.', ) diff --git a/tests/clean.test.ts b/tests/clean.test.ts index 2b25cf6b8..eceeb9b0f 100644 --- a/tests/clean.test.ts +++ b/tests/clean.test.ts @@ -159,6 +159,50 @@ describe('clean', () => { ).rejects.toThrow('Cannot clean the current working directory') }) + test('should not clean a custom cwd', async (context) => { + const files = { + 'pkg/index.ts': 'export const hello = "world"', + } + + // `cwd` points at a package directory, as it does in workspace mode, while + // the process stays in the test directory. + await expect( + testBuild({ + context, + files, + options: (cwd) => ({ + cwd: path.join(cwd, 'pkg'), + clean: ['.'], + }), + }), + ).rejects.toThrow('Cannot clean the current working directory') + }) + + test('should resolve clean patterns against a custom cwd', async (context) => { + const files = { + 'pkg/index.ts': 'export const hello = "world"', + 'pkg/pkg/old-file.js': 'old content', + } + + const testDir = getTestDir(context.task) + + await testBuild({ + context, + files, + options: (cwd) => ({ + cwd: path.join(cwd, 'pkg'), + clean: ['pkg'], + }), + snapshot: false, + }) + + // `pkg` is relative to the custom cwd, so it means `pkg/pkg`, not the cwd + const staleExists = await fsExists( + path.join(testDir, 'pkg', 'pkg', 'old-file.js'), + ) + expect(staleExists).toBe(false) + }) + test('should clean nested directories', async (context) => { const files = { 'index.ts': 'export const hello = "world"',