-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.js
107 lines (79 loc) · 2.77 KB
/
cli.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
#!/usr/bin/env node
const process = require('process');
const fs = require('fs');
const path = require('path');
const CWD = process.cwd();
const CONFIG_FILENAME = 'siskin.config.js';
const CONFIG_PATH = path.join(CWD, CONFIG_FILENAME);
const [, , templateName, ...variables] = process.argv;
let transformations = [];
const readConfigFile = () => {
return new Promise((resolve, reject) => {
if (!fs.existsSync(CONFIG_PATH)) reject(`No ${CONFIG_FILENAME} file found in current working directory`);
const config = require(CONFIG_PATH);
resolve(config);
});
};
const execConfigFile = (data) => {
return new Promise((resolve, reject) => {
const template = data.templates.find((t) => t.name === templateName);
transformations = template.transformations;
if (!template) reject(`No template ${templateName} found.`);
const promises = [];
template.files.forEach((file) => {
const promise = new Promise((innerResolve) => {
const fromFile = path.join(CWD, file.from);
const fileName = path.basename(fromFile);
const fileNameReplaced = replaceVariables(fileName);
const toFilePath = path.join(CWD, file.to);
const toFilePathReplaced = replaceVariables(toFilePath);
const toFile = path.join(toFilePathReplaced, fileNameReplaced);
fs.mkdirSync(toFilePathReplaced, { recursive: true });
fs.copyFileSync(fromFile, toFile);
fs.readFile(toFile, (err, data) => {
if (err) reject(err.message);
const newFileContent = replaceVariables(data);
fs.writeFile(toFile, newFileContent, () => {
innerResolve();
});
});
});
promises.push(promise);
});
Promise.all(promises).then(() => resolve());
});
};
const replaceVariables = (string) => {
let s = String(string);
const localTransformations = transformations;
variables.forEach((variable, index) => {
let v = variable;
if (localTransformations && localTransformations[index]) {
v = localTransformations[index](variables);
delete localTransformations[index];
}
s = s.replace(new RegExp(`\\$__${index}__\\$`, 'gm'), v);
});
Object.entries(localTransformations).forEach(([key, transformation]) => {
s = s.replace(new RegExp(`\\$__${key}__\\$`, 'gm'), transformation(variables));
});
return s;
};
const checkArgs = () => {
return new Promise((resolve, reject) => {
if (!templateName) reject('Please provide a template name.');
resolve();
});
};
const run = () => {
checkArgs()
.then(() => readConfigFile())
.then((config) => execConfigFile(config))
.then(() => console.log('Templating finished !'))
.catch((err) => {
console.log(err);
process.stderr.write(err.toString());
return 0;
});
};
run();