From d45431d2468ec4234290c90e08174ef1a494d9fa Mon Sep 17 00:00:00 2001 From: Bryan Pan Date: Mon, 19 Jul 2021 18:55:35 -0700 Subject: [PATCH] fix: add force to rm script in create-astro (#729) * fix: add force to rm script in create-astro * add changeset * edit overwrite prompt * rm cannot remove '.' or '..' -- creating a helper function to empty the directory * delete symlinks * comments --- .changeset/odd-cameras-wave.md | 5 +++++ packages/create-astro/src/index.ts | 23 ++++++++++++++++++++--- 2 files changed, 25 insertions(+), 3 deletions(-) create mode 100644 .changeset/odd-cameras-wave.md diff --git a/.changeset/odd-cameras-wave.md b/.changeset/odd-cameras-wave.md new file mode 100644 index 000000000..2eb675b42 --- /dev/null +++ b/.changeset/odd-cameras-wave.md @@ -0,0 +1,5 @@ +--- +'create-astro': patch +--- + +create-astro does not fail when removing subdirectories diff --git a/packages/create-astro/src/index.ts b/packages/create-astro/src/index.ts index c072399a6..20a3176a8 100644 --- a/packages/create-astro/src/index.ts +++ b/packages/create-astro/src/index.ts @@ -20,6 +20,24 @@ export function mkdirp(dir: string) { } } +/** + * Delete all files, subdirectories, and symlinks in a given + * directory. + * + * @param dir the directory to empty + * @returns a promise for emptying a given directory + */ +export async function emptyDir(dir: string) { + const items = await fs.promises.readdir(dir); + return Promise.all(items.map(async (item) => { + const itemPath = path.join(dir, item); + const stat = await fs.promises.stat(itemPath); + return stat.isDirectory() + ? fs.promises.rm(itemPath, { recursive: true, force: true }) // To remove directories + : fs.promises.unlink(itemPath); // Remove files and symlinks + })); +} + const { version } = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf-8')); const POSTPROCESS_FILES = ['package.json', 'astro.config.mjs', 'CHANGELOG.md']; // some files need processing after copying. @@ -37,15 +55,14 @@ export async function main() { const response = await prompts({ type: 'confirm', name: 'forceOverwrite', - message: 'Directory not empty. Continue?', + message: `Directory not empty. Delete ${cwd} to continue?`, initial: false, }); if (!response.forceOverwrite) { process.exit(1); } - await fs.promises.rm(cwd, { recursive: true }); - mkdirp(cwd); + await emptyDir(cwd); } } else { mkdirp(cwd);