-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
91 lines (75 loc) · 2.24 KB
/
index.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
const fs = require('fs');
let filesInDir = recursiveGetAllFiles('.');
filesInDir = filesInDir.filter((file) => {
return fs.statSync(file).isFile();
});
filesInDir.forEach((file) => {
fs.open(file, 'r+', (err, fileToRead) => {
if (err) {
console.log(`can't read file: ${file}`)
} else {
fs.readFile(fileToRead, { encoding: 'utf-8' }, (err, data) => {
if (err) {
console.log(`can't read file: ${file}`)
} else {
const regex = /{{inline [\', \"][^}]+[\', \"]}}/g;
let matches = regexMatchesInFile(data, regex);
matches.forEach((match) => {
let fileNameToInline = match.match(/[\', \"]([^}]+)[\', \"]/g);
fileNameToInline = fileNameToInline[0].replace(/[", ']/g, '');
let fileData = getInlinesFileData(fileNameToInline);
data = data.replace(match, fileData);
});
writeIntoFile(fileToRead, data, file);
}
});
}
});
});
function recursiveGetAllFiles(rootDir) {
let files = [];
files = getAllFilesInDirectory(rootDir, rootDir, rootDir);
return files;
}
function getAllFilesInDirectory(dir, rootDir, appendDir) {
let all = fs.readdirSync(dir) || [];
all.forEach((entity) => {
if (!entity.startsWith('.') && fs.statSync(`${dir}/${entity}`).isDirectory()) {
all.push(...getAllFilesInDirectory(`${dir}/${entity}`, rootDir, entity));
}
});
if (appendDir !== rootDir) {
all = all.map(entity => {
return `${appendDir}/${entity}`;
});
}
return all;
}
// gets all matches in a file for a regex
function regexMatchesInFile(data, regex) {
let matches = [], match;
do {
match = regex.exec(data);
if (Array.isArray(match)) {
matches = [...matches, match[0]];
}
} while (match);
return matches;
}
function getInlinesFileData(fileNameToInline) {
try {
let data = fs.readFileSync(fileNameToInline, 'utf-8');
return data;
} catch(error) {
return 'File Not Found';
console.log(error);
}
}
function writeIntoFile(file, data, fileName) {
fs.writeFile(file, data, { encoding: 'utf-8' }, (err, data) => {
if (err) {
console.log(`can't write to file: ${fileName}`)
}
console.log(`The file ${fileName} has been inlined!`);
});
}