-
Notifications
You must be signed in to change notification settings - Fork 4
/
fs.ts
108 lines (92 loc) · 2.29 KB
/
fs.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import { constants } from "fs"
import { access, mkdir, readdir, stat } from "fs/promises"
import { vLog } from "./logging"
async function canAccessWithMode(path: string, mode: number) {
try {
await access(path, mode)
return true
} catch {
return false
}
}
export async function isWriteable(path: string) {
return canAccessWithMode(path, constants.W_OK)
}
export async function isReadable(path: string) {
return canAccessWithMode(path, constants.R_OK)
}
/**
* @returns True if readable, false otherwise
*/
export async function isAccessible(path: string) {
return canAccessWithMode(path, constants.F_OK)
}
export async function isDirectory(path: string) {
try {
const pathStat = await stat(path)
return pathStat.isDirectory()
} catch {
return false
}
}
export async function isFile(path: string) {
try {
const pathStat = await stat(path)
return pathStat.isFile()
} catch {
return false
}
}
const validFileSet = new Set([
".DS_Store",
".git",
".gitattributes",
".gitignore",
".gitlab-ci.yml",
".hg",
".hgcheck",
".hgignore",
".idea",
".npmignore",
".travis.yml",
"LICENSE",
"Thumbs.db",
"docs",
"mkdocs.yml",
"npm-debug.log",
"yarn-debug.log",
"yarn-error.log",
".pnpm-debug.log"
])
export async function isFolderEmpty(root: string) {
const conflicts = (await readdir(root, { withFileTypes: true }))
.filter((dirData) => !validFileSet.has(dirData.name))
// Support IntelliJ IDEA-based editors
.filter((dirData) => !/\.iml$/.test(dirData.name))
if (conflicts.length > 0) {
vLog(`Found conflicting contents in ${root}`)
const data = conflicts.reduce(
(result, dirent) =>
`${result}\n\t${dirent.name}${dirent.isDirectory() ? "/" : ""}`,
""
)
vLog(data)
return false
}
return true
}
export async function ensureWritableAndEmpty(dir: string) {
if (!(await isWriteable(dir))) {
vLog("Directory does not exist, creating...")
await mkdir(dir)
} else {
vLog("Directory exists, checking if it is empty...")
if (!(await isFolderEmpty(dir))) {
throw new Error(`Directory ${dir} is not empty.`)
}
vLog("Checking if directory is writable...")
if (!(await isWriteable(dir))) {
throw new Error(`Directory ${dir} is not accesible.`)
}
}
}