2020-01-02 15:13:47 -05:00
|
|
|
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
|
2019-12-18 05:12:36 -05:00
|
|
|
import { join } from "../path/mod.ts";
|
2020-04-29 16:39:37 -04:00
|
|
|
const { readDir, readDirSync, mkdir, mkdirSync, remove, removeSync } = Deno;
|
2019-03-11 14:19:52 -04:00
|
|
|
/**
|
|
|
|
* 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.
|
2020-05-16 14:36:13 -04:00
|
|
|
* Requires the `--allow-read` and `--allow-write` flag.
|
2019-03-11 14:19:52 -04:00
|
|
|
*/
|
|
|
|
export async function emptyDir(dir: string): Promise<void> {
|
|
|
|
try {
|
2020-04-16 01:40:30 -04:00
|
|
|
const items = [];
|
2020-04-29 16:39:37 -04:00
|
|
|
for await (const dirEntry of readDir(dir)) {
|
2020-04-16 01:40:30 -04:00
|
|
|
items.push(dirEntry);
|
|
|
|
}
|
2019-12-18 05:12:36 -05:00
|
|
|
|
|
|
|
while (items.length) {
|
|
|
|
const item = items.shift();
|
|
|
|
if (item && item.name) {
|
|
|
|
const filepath = join(dir, item.name);
|
|
|
|
await remove(filepath, { recursive: true });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} catch (err) {
|
2020-02-24 15:48:35 -05:00
|
|
|
if (!(err instanceof Deno.errors.NotFound)) {
|
2019-12-18 05:12:36 -05:00
|
|
|
throw err;
|
2019-03-11 14:19:52 -04:00
|
|
|
}
|
2019-12-18 05:12:36 -05:00
|
|
|
|
|
|
|
// if not exist. then create it
|
2020-01-07 14:14:33 -05:00
|
|
|
await mkdir(dir, { recursive: true });
|
2019-03-11 14:19:52 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* 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.
|
2020-05-16 14:36:13 -04:00
|
|
|
* Requires the `--allow-read` and `--allow-write` flag.
|
2019-03-11 14:19:52 -04:00
|
|
|
*/
|
|
|
|
export function emptyDirSync(dir: string): void {
|
|
|
|
try {
|
2020-04-29 16:39:37 -04:00
|
|
|
const items = [...readDirSync(dir)];
|
2019-12-18 05:12:36 -05:00
|
|
|
|
2020-05-17 13:24:39 -04:00
|
|
|
// If the directory exists, remove all entries inside it.
|
2019-12-18 05:12:36 -05:00
|
|
|
while (items.length) {
|
|
|
|
const item = items.shift();
|
|
|
|
if (item && item.name) {
|
|
|
|
const filepath = join(dir, item.name);
|
|
|
|
removeSync(filepath, { recursive: true });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} catch (err) {
|
2020-02-24 15:48:35 -05:00
|
|
|
if (!(err instanceof Deno.errors.NotFound)) {
|
2019-12-18 05:12:36 -05:00
|
|
|
throw err;
|
|
|
|
}
|
2019-03-11 14:19:52 -04:00
|
|
|
// if not exist. then create it
|
2020-01-07 14:14:33 -05:00
|
|
|
mkdirSync(dir, { recursive: true });
|
2019-03-11 14:19:52 -04:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|