-
Notifications
You must be signed in to change notification settings - Fork 32
/
md2code.js
63 lines (55 loc) · 1.87 KB
/
md2code.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
'use strict';
var fs = require('fs');
var spawnSync = require('child_process').spawnSync;
var _ = require('lodash');
var lines =
fs.readFileSync('README.md', 'utf8').trim().split('\n').map(s => s + '\n');
var fencepos =
lines.map((s, i) => [s, i]).filter(([s, i]) => s.indexOf('```') === 0);
var seen = new Set([]);
var replacement = [];
var fnames = [];
_.chunk(fencepos, 2).forEach(([[_, i], [__, j]]) => {
var language = lines[i].match(/```([^\s]+)/);
language = language ? language[1] : language;
var fname = null;
if (lines[i + 1].indexOf('# export') === 0) {
fname = lines[i + 1].match(/# export ([^\s]+)/)[1];
fnames.push(fname);
}
var contentStart = i + 1 + (fname === null ? 0 : 1);
var contents = lines.slice(contentStart, j).join('');
if (language === 'py' || language === 'python') {
contents =
spawnSync('yapf', [], {input: contents, encoding: 'utf8'}).stdout;
replacement.push({start: i, end: j, contentStart, contents});
}
if (fname) {
if (seen.has(fname)) {
fs.appendFileSync(fname, contents);
} else {
if (language === 'py' || language === 'python') {
fs.writeFileSync(
fname, '# -*- coding: utf-8 -*-\n\n'); // I need emoji!
fs.appendFileSync(fname, contents);
} else {
fs.writeFileSync(fname, contents);
}
seen.add(fname);
}
}
});
for (var ri = replacement.length - 1; ri >= 0; ri--) {
var r = replacement[ri];
for (var k = r.contentStart + 1; k < r.end; k++) {
lines[k] = '';
}
lines[r.contentStart] = r.contents;
}
fs.writeFileSync('README.md', lines.join(''))
// run a final Yapf on the final files. Ensures newlines between functions, etc.
for (let fname of fnames) {
let contents = fs.readFileSync(fname, 'utf8');
contents = spawnSync('yapf', [], {input: contents, encoding: 'utf8'}).stdout;
fs.writeFileSync(fname, contents);
}