/
helpers.js
64 lines (56 loc) · 1.57 KB
/
helpers.js
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
const fs = require('fs');
const path = require('path');
const canSafelyOverwrite = (dir) =>
!fs.existsSync(dir) || fs.readdirSync(dir).length === 0;
const isValidPackageName = (projectName) =>
/^(?:@[a-z0-9-*~][a-z0-9-*._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/.test(
projectName
);
const toValidPackageName = (projectName) =>
projectName
.trim()
.toLowerCase()
.replace(/\s+/g, '-')
.replace(/^[._]/, '')
.replace(/[^a-z0-9-~]+/g, '-');
const emptyDir = (dir) => {
if (!fs.existsSync(dir)) {
return;
}
postOrderDirectoryTraverse(
dir,
(dir) => fs.rmdirSync(dir),
(file) => fs.unlinkSync(file)
);
};
function preOrderDirectoryTraverse(dir, dirCallback, fileCallback) {
for (const filename of fs.readdirSync(dir)) {
const fullpath = path.resolve(dir, filename);
if (fs.lstatSync(fullpath).isDirectory()) {
dirCallback(fullpath);
// in case the dirCallback removes the directory entirely
if (fs.existsSync(fullpath)) {
preOrderDirectoryTraverse(fullpath, dirCallback, fileCallback);
}
continue;
}
fileCallback(fullpath);
}
}
function postOrderDirectoryTraverse(dir, dirCallback, fileCallback) {
for (const filename of fs.readdirSync(dir)) {
const fullpath = path.resolve(dir, filename);
if (fs.lstatSync(fullpath).isDirectory()) {
postOrderDirectoryTraverse(fullpath, dirCallback, fileCallback);
dirCallback(fullpath);
continue;
}
fileCallback(fullpath);
}
}
module.exports = {
canSafelyOverwrite,
isValidPackageName,
toValidPackageName,
emptyDir,
};