1 | const fs = require('fs');
|
2 | const md = require('./markdown-settings');
|
3 | const mdx = /(\.md$|\.markdown$)/
|
4 | const template = require('./document-template');
|
5 |
|
6 | function grayson(options){
|
7 | try {
|
8 | let directory = fs.readdirSync(options.input).filter(file => file.match(mdx));
|
9 | let navigation = directory.map(filename => filename.match(/index/ig) ? '/' : `/${filename.replace(/(md$|markdown$)/ig, 'html')}`);
|
10 | let result = directory
|
11 | .map(source => {
|
12 | source = fs.readFileSync(options.input + '/' + source).toString();
|
13 | return options.slides ? `:::slide\n${source}\n:::` : source;
|
14 | });
|
15 |
|
16 | if(options.output){
|
17 | switch(options.mode){
|
18 | case 'slides':
|
19 | fs.writeFileSync(`${options.output.replace(/\/$/, '')}/slides.html`, template({
|
20 | content: {
|
21 | nav: null,
|
22 | body: md.render(result.join(''))
|
23 | },
|
24 | metadata: options.metadata
|
25 | }));
|
26 | break;
|
27 | case 'blog':
|
28 | fs.writeFileSync(`${options.output}/index.html`, template({
|
29 | content: {
|
30 | nav: navigation,
|
31 | body: md.render(result.join(''))
|
32 | },
|
33 | metadata: options.metadata
|
34 | }))
|
35 | default:
|
36 | directory.forEach((file, i) => {
|
37 | let input = `${options.input.replace(/\/$/, '')}/${file}`;
|
38 | writeFile(Object.assign({}, options, {
|
39 | input,
|
40 | html: template({
|
41 | content: {
|
42 | body: md.render(result[i]),
|
43 | nav: navigation
|
44 | },
|
45 | metadata: options.metadata
|
46 | })
|
47 | }));
|
48 | });
|
49 | break;
|
50 | }
|
51 | }
|
52 |
|
53 | return result;
|
54 | } catch (err) {
|
55 | if(err.message.match(/not a directory/ig) && options.input.match(mdx)){
|
56 | if(options.output){
|
57 | return writeFile(Object.assign({}, options, {
|
58 | html: template({
|
59 | content: {
|
60 | body: md.render(fs.readFileSync(options.input).toString()),
|
61 | nav: null
|
62 | },
|
63 | metadata: options.metadata
|
64 | })
|
65 | }));
|
66 | }
|
67 |
|
68 | return template({
|
69 | content: {
|
70 | body: md.render(fs.readFileSync(options.input).toString()),
|
71 | nav: null
|
72 | },
|
73 | metadata: options.metadata
|
74 | });
|
75 | }
|
76 |
|
77 | throw err;
|
78 | }
|
79 | }
|
80 |
|
81 | function writeFile(options){
|
82 | if(!options.output || !fs.existsSync(options.output)){
|
83 | throw new Error('Invalid output directory');
|
84 | }
|
85 |
|
86 | let source = options.input.slice(options.input.lastIndexOf('/'));
|
87 | let filename = `${options.output.replace(/\/$/, '')}/${source.replace(/(md$|markdown$)/, 'html')}`;
|
88 |
|
89 | return fs.writeFileSync(filename, options.html);
|
90 | }
|
91 |
|
92 | module.exports = grayson;
|