-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
93 lines (78 loc) · 2.04 KB
/
utils.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
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
const fs = require('fs');
const escapeStringRegexp = require('escape-string-regexp');
const SHEBANG_REGEX = /#!(.*) (.*)\n/;
const existsFile = (path) => {
return fs.existsSync(path);
};
const readFile = (path) => {
return fs.readFileSync(path, 'utf8');
};
const writeFile = (path, content) => {
fs.writeFileSync(path, content);
};
const hasShebang = (content) => {
return SHEBANG_REGEX.test(content);
};
const getShebang = (content) => {
return SHEBANG_REGEX.exec(content)[0].replace(/\n/g, '');
};
const buildShebangLine = (interpreter) => {
return `#!/usr/bin/env ${interpreter}`;
};
const rewriteShebang = (path) => {
if (existsFile(path)) {
const content = readFile(path);
if (hasShebang(content)) {
const shebang = getShebang(content);
const re = new RegExp(escapeStringRegexp(shebang), 'gi');
writeFile(path, `${shebang}\n${content.replace(re, '')}`);
}
}
};
const writeShebang = (path, interpreter) => {
if (existsFile(path)) {
const content = readFile(path);
if (!hasShebang(content)) {
const shebang = buildShebangLine(interpreter);
writeFile(path, `${shebang}\n${content}`);
}
}
};
const newBundle = (name, path) => ({
name,
path,
});
const getBundles = (bundle) => {
const { name: path, assets, childBundles } = bundle;
const bundles = [];
if (childBundles && childBundles.size) {
childBundles.forEach(({ name: path, assets, type }) => {
if (assets && assets.size && type !== 'map') {
assets.forEach(({ name }) => {
if (!bundles.find((b) => b.name === name)) {
bundles.push(newBundle(name, path));
}
});
}
});
}
if (path && assets) {
if (assets && assets.size) {
assets.forEach(({ name, type }) => {
if (!bundles.find((b) => b.name === name) && type !== 'map') {
bundles.push(newBundle(name, path));
}
});
}
}
return bundles;
};
module.exports = {
existsFile,
readFile,
hasShebang,
buildShebangLine,
rewriteShebang,
writeShebang,
getBundles,
};