-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
282 lines (245 loc) · 7.39 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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
#!/usr/bin/env node
const fs = require('fs-extra');
const marked = require('marked');
const initialConfig = require('./initialConfig.json');
/**
* TODO:
* - add a msgo new command. It will drop a new md file in the current folder with the initial info filled out
* - update the readme to actually describe how you use the tool
* - open the index.html file after build
* - include a msgo github link at the bottom of the page
* - include the author blurb
* - Similar to the header / footer html. Allow an html snippet named author.html
* - add the ability for the user to add a header.html file
* - organize the blog links into their subfolders (i.e. indented <li> elements)
* - add publish date to the index page
* - give the headers some color
* - better styling on the index page links. Possibly with a title
*/
switch (process.argv[2]) {
case 'b':
case 'build':
build();
break;
case 'i':
case 'init':
init();
break;
case '--help':
console.log('\nMSGO - markdown static site generator\n');
console.log('Usage: msgo [OPTION]\n');
console.log('b, build Compile the build directory.');
console.log('i, init Initialize config + file structure.');
console.log('--help Display a list of available commands.');
break;
default:
console.log('Not a valid argument.');
console.log('Type msgo --help for a list of valid commands.');
break;
}
// Initialize the file structure (if not already in place);
async function init() {
const pwd = await fs.readdir('./');
if (!pwd.includes('msgo.json')) {
await fs.writeFile('msgo.json', JSON.stringify(initialConfig));
console.log('Created msgo.json');
}
if (!pwd.includes('src')) {
const sample = await fs.readFile(__dirname + '/sample');
await fs.mkdir('src/sample', { recursive: true });
await fs.writeFile('src/sample/index.md', sample);
console.log('Created sample app');
}
}
async function generateHTML({ config, file, footer, links, subDir }) {
console.log(`Building ${subDir || ''}/${file}...`);
// Take first part of file name for html name (this will be the url)
const [fileName, ext] = file.split('.');
const path = subDir ? `${subDir}/${fileName}` : `${fileName}`;
if (ext !== 'md') {
// Copy assets into src
return fs.copySync(`./src/${path}.${ext}`, `./build/${file}`, {
overwrite: true,
});
}
const data = await fs.readFile(`./src/${path}.md`, 'utf8');
// Break out metadata at deliminator
const [meta, markdown] = data.split('@@@');
// Convert Meta tags to object
const metaObj = meta.split(/\n/).reduce((acc, el) => {
if (el.length) {
const [key, value] = el.split('=');
acc[key] = value.trim();
}
return acc;
}, {});
metaObj.siteName = config.name;
metaObj.url = `${path}.html`;
// Store metaObj for each blog
// Used to generate index & sitemap
links.push(metaObj);
// Read Markdown and generate HTML
const html = parseHTML({ markdown, footer, metaObj, subDir });
// Create sub directory
if (subDir) await fs.mkdir(`./build/${subDir}`);
// Write HTML to file
await fs.writeFile(`./build/${path}.html`, html);
}
// Compile source folder to HTML
async function build() {
// Check for config file before building
const pwd = await fs.readdir('./');
if (!pwd.includes('msgo.json')) {
console.error(
'Error: Missing config file.\nRun msgo -init before building.'
);
return;
}
// Delete existing build directory
if (pwd.includes('build')) {
await fs.rmdir('./build', { recursive: true, force: true });
}
// Create build directory
await fs.mkdir('./build');
await fs.mkdir('./build/assets');
// Copy assets into src
fs.copySync(__dirname + '/src/assets', './build/assets', {
overwrite: true,
});
// Read config from msgo.json
const config = JSON.parse(await fs.readFile('./msgo.json'));
const links = [];
const src = await fs.readdir('./src');
let footer = '';
if (src.includes('footer.html')) {
footer = await fs.readFile('./src/footer.html');
}
for (const file of src) {
if (fs.lstatSync(`./src/${file}`).isDirectory()) {
// Read files from nested directory
const subDirFiles = await fs.readdir(`./src/${file}`);
for (const child of subDirFiles) {
await generateHTML({
config,
file: child,
footer,
links,
subDir: file,
});
}
} else {
// Create html for root file
await generateHTML({ config, file, footer, links });
}
}
await generateSiteMap({ config, links });
const indexPage = await generateIndexPage({ config, footer, links });
await fs.writeFile('./build/index.html', indexPage);
console.log('Complete!');
}
function parseHTML({ markdown, metaObj, footer, subDir }) {
// Generte meta tags and HTML
const metaTags = generateMetaTags(metaObj);
const parsed = marked.parse(markdown);
const syleLink = subDir ? '../assets/style.css' : './assets/style.css';
return `
<!DOCTYPE html>
<html lang="en">
${metaTags}
<link rel="stylesheet" href=${syleLink}>
<title>${metaObj.title}</title>
</head>
<body>
<article>
${parsed}
</article>
<footer>
${footer}
</footer>
</body>
</html>
`;
}
async function generateIndexPage({ config, footer, links }) {
// Push links to index page
const blogList = links.map((metaObj) => {
return `<li><a href="./${metaObj.url}">${metaObj.title}</a> - ${metaObj.description}</li>`;
});
const meta = generateMetaTags({
description: config.description,
image: config.baseUrl + '/' + config.image,
siteName: config.name,
title: config.name,
url: config.baseUrl,
});
return `
<!DOCTYPE html>
<html lang="en">
<link rel="stylesheet" href="./assets/style.css">
${meta}
<title>${config.name}</title>
</head>
<body>
<article>
<ul>${blogList.join('')}</ul>
</article>
<footer>
${footer}
</footer>
</body>
</html>
`;
}
async function generateSiteMap({ config, links }) {
const [today] = new Date().toISOString().split('T');
// Push articles to sitemap
sitemap = links.map((metaObj) => {
return `
<url>
<loc>${config.baseUrl}/${metaObj.url || ''}</loc>
<lastmod>${metaObj.date || today}</lastmod>
</url>
`;
});
// Include index page in sitemap
sitemap.unshift(`
<url>
<loc>${config.baseUrl}</loc>
<lastmod>${today}</lastmod>
</url>
`);
// Write sitemap.xml to file
await fs.writeFile(
`./build/sitemap.xml`,
[
'<?xml version="1.0" encoding="UTF-8"?>',
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',
...sitemap,
'</urlset>',
].join('')
);
}
function generateMetaTags({ description, image, siteName, title, url }) {
// Create meta tags for social links
return `
<!-- Base meta tags -->
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="${description || ''}" />
<meta name="language" content="english" />
<meta name="title" content="${title || ''}" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- OpenGraph -->
<meta property="og:description" content="${description || ''}" />
<meta property="og:image" content="${image}" />
<meta property="og:site_name" content="${siteName || ''}" />
<meta property="og:title" content="${title || ''}" />
<meta property="og:type" content="article" />
<meta property="og:url" content="${url || ''}" />
<!-- Twitter -->
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:description" content="${description || ''}" />
<meta name="twitter:image" content="${image || ''}" />
<meta name="twitter:title" content="${title || ''}" />
`;
}