1 | import { stat, statSync } from "fs"
|
2 |
|
3 | export const assertFolder = async (path) => {
|
4 | const filesystemEntry = await pathToFilesystemEntry(path)
|
5 |
|
6 | if (!filesystemEntry) {
|
7 | throw new Error(`folder not found on filesystem.
|
8 | path: ${path}`)
|
9 | }
|
10 |
|
11 | const { type } = filesystemEntry
|
12 | if (type !== "folder") {
|
13 | throw new Error(`folder expected but found something else on filesystem.
|
14 | path: ${path}
|
15 | found: ${type}`)
|
16 | }
|
17 | }
|
18 |
|
19 | export const assertFile = async (path) => {
|
20 | const filesystemEntry = await pathToFilesystemEntry(path)
|
21 |
|
22 | if (!filesystemEntry) {
|
23 | throw new Error(`file not found on filesystem.
|
24 | path: ${path}`)
|
25 | }
|
26 |
|
27 | const { type } = filesystemEntry
|
28 | if (type !== "file") {
|
29 | throw new Error(`file expected but found something else on filesystem.
|
30 | path: ${path}
|
31 | found: ${type}`)
|
32 | }
|
33 | }
|
34 |
|
35 | export const assertFileSync = (path) => {
|
36 | let stats
|
37 |
|
38 | try {
|
39 | stats = statSync(path)
|
40 | } catch (e) {
|
41 | if (e.code === "ENOENT") {
|
42 | throw new Error(`file not found on filesystem.
|
43 | path: ${path}`)
|
44 | }
|
45 | throw e
|
46 | }
|
47 |
|
48 | const entry = statsToEntry(stats)
|
49 | if (entry !== "file") {
|
50 | throw new Error(`file expected but found something else on filesystem.
|
51 | path: ${path}
|
52 | found: ${entry}`)
|
53 | }
|
54 | }
|
55 |
|
56 | const pathToFilesystemEntry = (path) =>
|
57 | new Promise((resolve, reject) => {
|
58 | stat(path, (error, stats) => {
|
59 | if (error) {
|
60 | if (error.code === "ENOENT") resolve(null)
|
61 | else reject(error)
|
62 | } else {
|
63 | resolve({
|
64 | type: statsToEntry(stats),
|
65 | stats,
|
66 | })
|
67 | }
|
68 | })
|
69 | })
|
70 |
|
71 | const statsToEntry = (stats) => {
|
72 | if (stats.isFile()) {
|
73 | return "file"
|
74 | }
|
75 | if (stats.isDirectory()) {
|
76 | return "folder"
|
77 | }
|
78 | return "other"
|
79 | }
|