2020-01-02 15:13:47 -05:00
|
|
|
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
|
2020-05-09 08:34:47 -04:00
|
|
|
import { getFileInfoType } from "./_util.ts";
|
2020-02-21 10:36:13 -05:00
|
|
|
const { lstat, lstatSync, mkdir, mkdirSync } = Deno;
|
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 {
|
2019-12-18 09:45:19 -05:00
|
|
|
const fileInfo = await lstat(dir);
|
2020-04-16 01:40:30 -04:00
|
|
|
if (!fileInfo.isDirectory) {
|
2019-04-06 21:01:23 -04:00
|
|
|
throw new Error(
|
2019-12-18 09:45:19 -05: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-01-07 14:14:33 -05:00
|
|
|
await 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 {
|
2019-12-18 09:45:19 -05:00
|
|
|
const fileInfo = lstatSync(dir);
|
2020-04-16 01:40:30 -04:00
|
|
|
if (!fileInfo.isDirectory) {
|
2019-04-06 21:01:23 -04:00
|
|
|
throw new Error(
|
2019-12-18 09:45:19 -05: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-01-07 14:14:33 -05:00
|
|
|
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
|
|
|
}
|
|
|
|
}
|