From bb24fb74ffe0bb35649e0adbb1473458c8abf71f Mon Sep 17 00:00:00 2001 From: Axetroy Date: Wed, 18 Dec 2019 18:12:36 +0800 Subject: fix permission errors are swallowed by fs.emptyDir (#3501) --- std/fs/empty_dir.ts | 65 ++++++++++++++++++++++++++++++++++------------------- 1 file changed, 42 insertions(+), 23 deletions(-) (limited to 'std/fs/empty_dir.ts') diff --git a/std/fs/empty_dir.ts b/std/fs/empty_dir.ts index 81bc45839..ded02b7e4 100644 --- a/std/fs/empty_dir.ts +++ b/std/fs/empty_dir.ts @@ -1,25 +1,39 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. +import { join } from "../path/mod.ts"; +const { + readDir, + readDirSync, + mkdir, + mkdirSync, + remove, + removeSync, + ErrorKind +} = Deno; /** * Ensures that a directory is empty. * Deletes directory contents if the directory is not empty. * If the directory does not exist, it is created. * The directory itself is not deleted. + * Requires the `--allow-read` and `--alow-write` flag. */ export async function emptyDir(dir: string): Promise { - let items: Deno.FileInfo[] = []; try { - items = await Deno.readDir(dir); - } catch { - // if not exist. then create it - await Deno.mkdir(dir, true); - return; - } - while (items.length) { - const item = items.shift(); - if (item && item.name) { - const fn = dir + "/" + item.name; - await Deno.remove(fn, { recursive: true }); + const items = await readDir(dir); + + while (items.length) { + const item = items.shift(); + if (item && item.name) { + const filepath = join(dir, item.name); + await remove(filepath, { recursive: true }); + } + } + } catch (err) { + if ((err as Deno.DenoError).kind !== ErrorKind.NotFound) { + throw err; } + + // if not exist. then create it + await mkdir(dir, true); } } @@ -28,21 +42,26 @@ export async function emptyDir(dir: string): Promise { * Deletes directory contents if the directory is not empty. * If the directory does not exist, it is created. * The directory itself is not deleted. + * Requires the `--allow-read` and `--alow-write` flag. */ export function emptyDirSync(dir: string): void { - let items: Deno.FileInfo[] = []; try { - items = Deno.readDirSync(dir); - } catch { + const items = readDirSync(dir); + + // if directory already exist. then remove it's child item. + while (items.length) { + const item = items.shift(); + if (item && item.name) { + const filepath = join(dir, item.name); + removeSync(filepath, { recursive: true }); + } + } + } catch (err) { + if ((err as Deno.DenoError).kind !== ErrorKind.NotFound) { + throw err; + } // if not exist. then create it - Deno.mkdirSync(dir, true); + mkdirSync(dir, true); return; } - while (items.length) { - const item = items.shift(); - if (item && item.name) { - const fn = dir + "/" + item.name; - Deno.removeSync(fn, { recursive: true }); - } - } } -- cgit v1.2.3