-
Notifications
You must be signed in to change notification settings - Fork 19
/
mdown.js
97 lines (72 loc) · 2.55 KB
/
mdown.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
var _fs = require('fs'),
_path = require('path'),
_glob = require('glob'),
_minimatch = require('minimatch'),
_wrench = require('wrench'),
_showdown = require('github-flavored-markdown');
var DEFAULT_ENCODING = 'utf-8';
exports.batchProcess = function(opts){
opts.encoding = opts.encoding || DEFAULT_ENCODING;
_glob(opts.input, null, function(er, files){
if (opts.exclude) {
files = filterFiles(files, opts.exclude);
}
files.forEach(function(filePath){
var content = exports.toHTML(_fs.readFileSync(filePath, opts.encoding), opts);
if (opts.output) {
outputToFile(filePath, content, opts);
} else {
console.log(content);
}
});
});
};
function filterFiles(files, exclude) {
var excludes = exclude.split(',');
return files.filter(function(filePath){
return ! excludes.some(function(glob){
return _minimatch(filePath, glob);
});
});
}
function outputToFile(filePath, content, opts){
var inputDir = opts.input.replace(/^([^\*]*).*/, '$1'),
rPathReplace = new RegExp('^'+ inputDir +'(.+)'),
distPath = filePath.replace(rPathReplace, function(str, p1){
return _path.join(opts.output, p1).replace(/\.[^\.]+$/, '.html');
}),
distFolder = _path.dirname(distPath);
if (distFolder) {
_wrench.mkdirSyncRecursive(distFolder);
}
_fs.writeFileSync(distPath, content, opts.encoding);
}
exports.toHTML = function(content, opts){
var header, footer;
if (opts) {
header = opts.header? _fs.readFileSync(opts.header, opts.encoding) : '';
footer = opts.footer? _fs.readFileSync(opts.footer, opts.encoding) : '';
}
content = normalizeLineBreaks(content);
content = convertCodeBlocks(content);
return concat([header, _showdown.parse(content), footer]);
};
function concat(arr){
return arr.filter(function(val){
return !!val;
}).join('\n');
}
//borrowed from amd-utils (http://millermedeiros.github.com/amd-utils)
//author: Miller Medeiros
function normalizeLineBreaks(str, lineEnd) {
lineEnd = lineEnd || '\n';
return str
.replace(/\r\n/g, lineEnd) // DOS
.replace(/\r/g, lineEnd) // Mac
.replace(/\n/g, lineEnd); // Unix
}
// showdown have issues with the gh-style code blocks
var _rCodeBlocks = /^```\s*(\w+)\s*$([\s\S]*?)^```$/gm;
function convertCodeBlocks(mdown){
return mdown.replace(_rCodeBlocks, '<pre><code>$2</code></pre>');
}