2020-01-02 15:13:47 -05:00
|
|
|
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
|
2019-04-06 21:01:23 -04:00
|
|
|
import { getFileInfoType } from "./utils.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.
|
2019-12-18 09:45:19 -05:00
|
|
|
* Requires the `--allow-read` and `--alow-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);
|
|
|
|
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-21 10:36:13 -05:00
|
|
|
if (err instanceof Deno.Err.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.
|
2019-12-18 09:45:19 -05:00
|
|
|
* Requires the `--allow-read` and `--alow-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);
|
|
|
|
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-21 10:36:13 -05:00
|
|
|
if (err instanceof Deno.Err.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
|
|
|
}
|
|
|
|
}
|