-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
174 lines (154 loc) · 4.28 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
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
const fs = require('fs');
const minimist = require('minimist');
const path = require('path');
const request = require('request');
// map certain gist langs to prism langs
// additional mapping logic is in translateLanguage()
const languageMap = {
'batchfile': 'batch',
'c++': 'cpp',
'c#': 'csharp',
'f#': 'fsharp',
'html': 'markup',
'shell': 'bash',
'xml': 'markup'
};
// global vars the multiple functions use
let argv, fileContent, gists = [];
function init() {
argv = minimist(process.argv.slice(2), {
string: [
'input',
'user',
'pass',
'escape'
],
default: {
escape: 'htmlencode'
}
});
if (!argv.input) {
console.log('Input file not specified.');
} else if (!['htmlencode', 'script', 'comment', 'none'].includes(argv.escape)) {
console.log('Unrecognized value for escape.');
} else {
readInputFile();
processFileContent();
requestGists();
}
}
function readInputFile() {
try {
fileContent = fs.readFileSync(argv.input, 'utf8');
} catch (ex) {
console.log('Unable to read input file.');
console.log(ex.message);
}
}
function processFileContent() {
let regex = (/<script src="https:\/\/gist\.github\.com\/[^\/]+\/(\w+)\.js"><\/script>/gi);
let match;
while ((match = regex.exec(fileContent)) !== null) {
gists.push({
isProcessed: false,
scriptTag: match[0],
id: match[1],
language: '',
content: ''
});
}
console.log('Found ' + gists.length + ' gists.');
}
function requestGists() {
gists.forEach((gist, index) => {
let options = {
url: 'https://api.github.com/gists/' + gist.id,
headers: {
'User-Agent': 'gist-to-prismjs'
}
};
if (argv.user && argv.pass) {
options.auth = {
user: argv.user,
pass: argv.pass
};
}
// stagger requests, otherwise the API may return a 403 for abuse
setTimeout(() => {
console.log('Fetching gist ' + gist.id + '.');
request.get(options, requestGistCallback.bind(this, gist));
}, index * 25);
});
}
function requestGistCallback(gist, error, response, body) {
if (error) {
console.log('Unable to get content for gist ' + gist.id + '.');
console.log(error);
} else if (response.statusCode !== 200) {
console.log('Response status code ' + response.statusCode + ' received for gist ' + gist.id + '.');
console.log(body);
} else {
let json = JSON.parse(body);
// gists can have multiple files, but we assume the first here
let firstGistFile = Object.values(json.files)[0];
gist.language = firstGistFile.language;
gist.content = firstGistFile.content;
}
// mark this gist as processed and check if all are now processed
gist.isProcessed = true;
if (gists.every(gist => gist.isProcessed)) {
writeOutputFile();
}
}
function writeOutputFile() {
// replace each gist script tag in file content with a code block
gists.forEach(gist => {
let codeBlock = buildCodeBlock(gist);
fileContent = fileContent.replace(gist.scriptTag, codeBlock);
});
// output filename is just the input filename suffixed with "-output"
let inputPathObj = path.parse(argv.input);
let outputFile = path.join(inputPathObj.dir, inputPathObj.name + '-output' + inputPathObj.ext);
fs.writeFile(outputFile, fileContent, (err) => {
if (err) {
console.log('Unable to write output file.');
console.log(err);
} else {
console.log('Wrote ' + outputFile + '.');
}
});
}
function buildCodeBlock(gist) {
let prismLang = translateLanguage(gist.language);
let classAttr = prismLang ? ' class="language-' + prismLang + '"' : '';
if (argv.escape === 'script') {
return '<script type="text/plain"' + classAttr + '>' + gist.content + '</script>';
} else {
let content;
switch (argv.escape) {
case 'htmlencode':
content = gist.content.replace(/</g, '<').replace(/>/g, '>');
break;
case 'comment':
content = '<!--' + gist.content + '-->';
break;
case 'none':
content = gist.content;
break;
}
return '<pre><code' + classAttr + '>' + content + '</code></pre>';
}
}
function translateLanguage(gistLang) {
gistLang = (gistLang || '').toLowerCase();
if (!gistLang || gistLang === 'text') {
// a gist lang of null (can happen) or "Text" means no highlighting
return null;
} else {
// attempt to find mapped lang, otherwise use the lowercased lang as-is
let prismLang = languageMap[gistLang] || gistLang;
return prismLang;
}
}
// it's go time!
init();