-
Notifications
You must be signed in to change notification settings - Fork 2
/
cssgen.js
76 lines (63 loc) · 2.25 KB
/
cssgen.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
let fs = require("fs").promises;
let path = require("path");
const postcss = require("postcss");
const postcssCustomMedia = require("postcss-custom-media");
let sass = require("sass");
const fileRegEx = /!/;
function genFile(filename) {
return sass.compile(filename, {
style: "compressed",
loadPaths: ["./", "node_modules", "node_modules/@gouvfr/dsfr"]
});
}
async function* walk(dir) {
for await (const d of await fs.opendir(dir)) {
const entry = path.join(dir, d.name);
if (d.isDirectory()) yield* walk(entry);
else if (d.isFile() && d.name === ".cssgen.json") yield entry;
}
}
async function main() {
for await (const p of walk(".")) {
console.log(`handling ${p}`);
fs.readFile(p)
.then(async (data) => {
let dot = path.dirname(p);
let config = JSON.parse(data);
console.log(`dot ${dot}`);
for (const directory in config) {
console.log(`Looking at directory ${directory}`);
let hasStar = directory.endsWith("*");
let file = hasStar ? directory.slice(0, -1) : directory; // scss and css file will be name just like their containing folder
let fileInDirectory = directory.indexOf("/") >= 0;
const targetDir = fileInDirectory ? dot : dot + "/" + directory;
const targetFile = `${targetDir}/${file}.scss`;
let content = genFile(targetFile).css;
/* go through configured content replacements */
for (const replacement of config[directory]) {
let regexFrom = new RegExp(replacement.from, "gm");
content = content.replaceAll(regexFrom, replacement.to);
}
/* use postcss to remove custom media generated by VIC2 */
postcss([postcssCustomMedia()])
.process(content)
.then((pContent) => {
fs.writeFile(
fileInDirectory
? `${dot}/${file}${hasStar ? "" : ".gen"}.css`
: `${dot}/${directory}/${file}${hasStar ? "" : ".gen"}.css`,
pContent.css,
(err) => {
if (err) throw err;
}
);
});
}
})
.catch((err) => {
console.log(err);
process.exit(1);
});
}
}
main();