2019-03-12 01:52:43 -04:00
|
|
|
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
|
2019-04-06 21:01:23 -04:00
|
|
|
import { getFileInfoType } from "./utils.ts";
|
2019-12-18 09:45:19 -05:00
|
|
|
const { lstat, lstatSync, mkdir, mkdirSync, ErrorKind } = Deno;
|
|
|
|
|
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) {
|
2019-12-18 09:45:19 -05:00
|
|
|
if (err instanceof Deno.DenoError && err.kind === ErrorKind.NotFound) {
|
|
|
|
// if dir not exists. then create it.
|
|
|
|
await mkdir(dir, true);
|
|
|
|
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) {
|
2019-12-18 09:45:19 -05:00
|
|
|
if (err instanceof Deno.DenoError && err.kind == ErrorKind.NotFound) {
|
|
|
|
// if dir not exists. then create it.
|
|
|
|
mkdirSync(dir, true);
|
|
|
|
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
|
|
|
}
|
|
|
|
}
|