-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
86 lines (74 loc) · 2.32 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
const fs = require('fs');
function printUsageAndExit() {
console.error("Usage: <input_snippet> <output_directory>");
console.error("input_snippet can be either a file or a directory");
process.exit(1)
}
function xmlEscape(string) {
return string.replace(/([&"<>\n'])/g, (str, item) => {
const map = {
'>': '>',
'<': '<',
"'": ''',
'"': '"',
'&': '&',
"\n": ' '
};
return map[item];
});
}
function mapContext(string) {
const map = {
'html': "HTML",
'typescript': "TypeScript"
};
return map[string] || string;
}
function convertSnippet(snippet, context) {
let vars = {};
let body = snippet.body.join("\n");
body = body.replace(/\\t/, '');
let replacement = (str, name, value) => {
name = name === "0" ? "END" : name;
name = name.replace("-", "_");
vars[name] = value;
return "$" + name + "$";
};
body = body.replace(/\$([_a-zA-Z0-9\-]+)/g, replacement);
body = body.replace(/\${([_a-zA-Z0-9\-]+(?:\s*:\s*([_a-zA-Z][_a-zA-Z0-9]*))?)}/g, replacement);
let templateText = `
<template name="${xmlEscape(snippet.prefix)}" value="${xmlEscape(body)}" description="${xmlEscape(snippet.description)}" toReformat="true" toShortenFQNames="true">`;
for (const variable of Object.keys(vars).sort()) {
if (variable === "END") continue;
templateText += `
<variable name="${variable}" expression="" defaultValue=""${vars[variable] || variable}"" alwaysStopAt="true" />`;
}
templateText += `
<context>
<option name="${mapContext(context)}" value="true" />
</context>
</template>`;
templateText += "";
return templateText;
}
function convertFile(input, file, output) {
console.log(`converting ${file}`);
const snippets = JSON.parse(fs.readFileSync(`${input}/${file}`));
let templateSetText = `<templateSet group="${input}">`;
for (const name of Object.keys(snippets).sort()) {
const snippet = snippets[name];
templateSetText += convertSnippet(snippet, file.substr(0, file.indexOf('.')));
}
templateSetText += "\n</templateSet>";
console.log(templateSetText);
}
const input = process.argv[2];
const output = process.argv[3];
if (!input || !output) {
printUsageAndExit()
}
fs.readdir(input, (err, files) => {
files.forEach(file => {
convertFile(input, file, output)
});
});