2021-01-11 12:13:41 -05:00
|
|
|
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
|
2020-05-09 08:34:47 -04:00
|
|
|
import { getFileInfoType } from "./_util.ts";
|
2019-12-18 09:45:19 -05:00
|
|
|
|
2019-03-12 01:52:43 -04:00
|
|
|
/**
|
2019-03-14 10:24:54 -04:00
|
|
|
* Ensures that the directory exists.
|
|
|
|
* If the directory structure does not exist, it is created. Like mkdir -p.
|
2020-05-16 05:36:11 -04:00
|
|
|
* Requires the `--allow-read` and `--allow-write` flag.
|
2019-03-12 01:52:43 -04:00
|
|
|
*/
|
|
|
|
export async function ensureDir(dir: string): Promise<void> {
|
|
|
|
try {
|
2020-06-12 15:23:38 -04:00
|
|
|
const fileInfo = await Deno.lstat(dir);
|
2020-04-16 01:40:30 -04:00
|
|
|
if (!fileInfo.isDirectory) {
|
2019-04-06 21:01:23 -04:00
|
|
|
throw new Error(
|
2020-07-14 15:24:17 -04:00
|
|
|
`Ensure path exists, expected 'dir', got '${
|
|
|
|
getFileInfoType(fileInfo)
|
|
|
|
}'`,
|
2019-04-06 21:01:23 -04:00
|
|
|
);
|
|
|
|
}
|
|
|
|
} catch (err) {
|
2020-02-24 15:48:35 -05:00
|
|
|
if (err instanceof Deno.errors.NotFound) {
|
2019-12-18 09:45:19 -05:00
|
|
|
// if dir not exists. then create it.
|
2020-06-12 15:23:38 -04:00
|
|
|
await Deno.mkdir(dir, { recursive: true });
|
2019-12-18 09:45:19 -05:00
|
|
|
return;
|
2019-04-06 21:01:23 -04:00
|
|
|
}
|
2019-12-18 09:45:19 -05:00
|
|
|
throw err;
|
2019-03-12 01:52:43 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2019-03-14 10:24:54 -04:00
|
|
|
* Ensures that the directory exists.
|
|
|
|
* If the directory structure does not exist, it is created. Like mkdir -p.
|
2020-05-16 05:36:11 -04:00
|
|
|
* Requires the `--allow-read` and `--allow-write` flag.
|
2019-03-12 01:52:43 -04:00
|
|
|
*/
|
|
|
|
export function ensureDirSync(dir: string): void {
|
|
|
|
try {
|
2020-06-12 15:23:38 -04:00
|
|
|
const fileInfo = Deno.lstatSync(dir);
|
2020-04-16 01:40:30 -04:00
|
|
|
if (!fileInfo.isDirectory) {
|
2019-04-06 21:01:23 -04:00
|
|
|
throw new Error(
|
2020-07-14 15:24:17 -04:00
|
|
|
`Ensure path exists, expected 'dir', got '${
|
|
|
|
getFileInfoType(fileInfo)
|
|
|
|
}'`,
|
2019-04-06 21:01:23 -04:00
|
|
|
);
|
|
|
|
}
|
|
|
|
} catch (err) {
|
2020-02-24 15:48:35 -05:00
|
|
|
if (err instanceof Deno.errors.NotFound) {
|
2019-12-18 09:45:19 -05:00
|
|
|
// if dir not exists. then create it.
|
2020-06-12 15:23:38 -04:00
|
|
|
Deno.mkdirSync(dir, { recursive: true });
|
2019-12-18 09:45:19 -05:00
|
|
|
return;
|
2019-04-06 21:01:23 -04:00
|
|
|
}
|
2019-12-18 09:45:19 -05:00
|
|
|
throw err;
|
2019-03-12 01:52:43 -04:00
|
|
|
}
|
|
|
|
}
|