-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcli.js
executable file
·118 lines (91 loc) · 2.12 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
108
109
110
111
112
113
114
115
116
117
118
#!/usr/bin/env node
"use strict";
const fs = require("fs");
const vm = require("vm");
const razorleaf = require("./");
const DirectoryLoader = require("./directory-loader");
const showUsage = () => {
console.error("Usage: razorleaf [-d|--data <expression>] [<template file>]");
};
const readToEnd = (textStream, callback) => {
let text = "";
textStream.on("data", part => {
text += part;
});
textStream.on("end", () => {
callback(null, text);
});
textStream.on("error", callback);
};
const evalExpression = js => {
let isExpression;
try {
/* eslint-disable no-new */
new Function("'use strict'; (" + js + "\n)");
new Function("'use strict'; void " + js);
/* eslint-enable no-new */
isExpression = true;
} catch (error) {
isExpression = false;
}
return vm.runInNewContext(
isExpression ?
"(" + js + "\n)" :
js
);
};
const firstIndex = (a, b) =>
a === -1 ? b :
b === -1 ? a :
a < b ? a : b;
const mainWithOptions = (options, args) => {
args = args.slice();
if (args[0] === "-h" || args[0] === "--help") {
showUsage();
return;
}
const separator = args.indexOf("--");
if (separator !== -1) {
args.splice(separator, 1);
}
const d = firstIndex(args.indexOf("-d"), args.indexOf("--data"));
let dataExpression = null;
if (d !== -1 && (separator === -1 || d < separator)) {
if (d + 1 === args.length) {
showUsage();
process.exit(1);
return;
}
dataExpression = args[d + 1];
args.splice(d, 2);
}
if (args.length > 1) {
showUsage();
process.exit(1);
return;
}
const data = dataExpression ? evalExpression(dataExpression) : null;
const read = (error, templateSource) => {
if (error) {
throw error;
}
const loader = new DirectoryLoader(".", options);
const template = razorleaf.compile(templateSource, loader.options);
process.stdout.write(template(data));
};
if (args.length === 0 || args[0] === "-") {
readToEnd(process.stdin, read);
} else {
fs.readFile(args[0], "utf-8", read);
}
};
const main = args => {
mainWithOptions(undefined, args);
};
module.exports = {
main,
mainWithOptions,
};
if (module === require.main) {
main(process.argv.slice(2));
}