-
Notifications
You must be signed in to change notification settings - Fork 2
/
osfilegen.js
119 lines (104 loc) · 3.58 KB
/
osfilegen.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
let fs = require("fs").promises;
let path = require("path");
const fileRegEx = /!/;
function replaceFile(filename, replacements) {
return new Promise((resolve) => {
let regExes = [];
for (const [searchFor, replaceTo] of Object.entries(replacements)) {
console.log(` replace ${searchFor} by ${replaceTo}`);
regExes.push({
regEx: new RegExp(searchFor, "gm"), // global and multiline
replaceTo: replaceTo
});
}
fs.readFile(filename, "utf8")
.then((contents) => {
regExes.forEach((entry) => {
contents = contents.replace(entry.regEx, entry.replaceTo);
});
resolve(contents);
})
.catch((err) => {
console.log(err);
});
});
}
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 === ".osfilegen.json") yield entry;
}
}
async function main() {
for await (const p of walk(".")) {
console.log(`handling ${p}`);
fs.readFile(p)
.then((data) => {
let dot = path.dirname(p);
let config = JSON.parse(data);
console.log(`dot ${dot}`);
for (const [directory, instructions] of Object.entries(config)) {
let targetDirectory = instructions.target.replace(
fileRegEx,
directory
);
delete instructions.target;
//console.log(`Looking at directory ${directory}`);
fs.mkdir(dot + "/" + targetDirectory, { recursive: true })
.then(() => {
for (const [file, replacements] of Object.entries(instructions)) {
let targetFile = replacements.target || file; // by default keep filename
delete replacements.target;
console.log(
` Looking at file ${directory}/${file} --> ${targetFile}`
);
let nFile = file.replace(fileRegEx, directory);
let nTargetFile = targetFile.replace(fileRegEx, directory);
replaceFile(dot + "/" + directory + "/" + nFile, replacements)
.then((content) => {
let lastIndex = targetFile.includes("/")
? nTargetFile.lastIndexOf("/")
: -1;
if (lastIndex >= 0) {
let ndir =
dot +
"/" +
targetDirectory +
"/" +
nTargetFile.slice(0, lastIndex);
fs.mkdir(ndir, { recursive: true }).then(() => {
fs.writeFile(
dot + "/" + targetDirectory + "/" + nTargetFile,
content,
(err) => {
if (err) throw err;
}
);
});
} else {
fs.writeFile(
dot + "/" + targetDirectory + "/" + nTargetFile,
content,
(err) => {
if (err) throw err;
}
);
}
})
.catch((error) => {
console.log(error);
});
}
})
.catch((err) => {
console.log(err);
});
}
})
.catch((err) => {
console.log(err);
});
}
}
main();