-
Notifications
You must be signed in to change notification settings - Fork 0
/
ossg.js
504 lines (439 loc) · 10.9 KB
/
ossg.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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
const fs = require('fs');
const path = require('path');
let settings = {};
function main()
{
let args = getArguments();
if (args.length < 1)
{
printHelp();
}
else
{
if (args[0] == '-h' || args[0] == '-help' || args[0] == '--help')
{
printHelp();
}
else if (args[0] == '-V' || args[0] == '-version' || args[0] == '--version')
{
printVersion();
}
else if (args[0] == '-g')
{
generateSettings(args[1]);
}
else
{
let file = readFile(args[0]);
if (file != null)
{
parseSettings(file);
parsePages();
// create page output folder if it doesn't exist.
if (!pathExists(settings.output_path + '/' + settings.output_pages_path))
{
createFolder(settings.output_path + '/' + settings.output_pages_path);
}
for (let index in settings.pages)
{
let page = settings.pages[index];
let template = getTemplate(page.template);
let html = generateHTML(template, page);
// insert each page into the 'default' template.
let defaultTemplate = getTemplate(settings.default);
let defaultPage = page;
defaultPage.content = html;
let finalHtml = generateHTML(defaultTemplate, defaultPage);
writeFile(settings.output_path + '/' + settings.output_pages_path + '/' + page.name + '.html', finalHtml);
}
let index = getIndex();
let indexHtml = generateHTML(index);
writeFile(settings.output_path + '/index.html', indexHtml);
// copy resources
copyFolderRecursive(
settings.input_path + '/' + settings.resources,
settings.output_path + '/' + settings.resources
);
}
}
}
}
//
// Get the command line arguments.
//
function getArguments()
{
return process.argv.slice(2);
}
//
// Read in a utf8-encoded file.
//
function readFile(path)
{
let data = '';
try
{
data = fs.readFileSync(path, 'utf8');
return data;
}
catch (err)
{
if (err.errno == -2)
{
//@@TODO: throw a proper error.
throw "File not found: " + path;
}
else
{
console.log(err);
}
}
}
//
// Write out a utf8-encoded file.
//
function writeFile(path, data)
{
fs.writeFileSync(path, data);
}
//
// Get the names of files in a folder
//
function getFilenames(path)
{
try {
return fs.readdirSync(path);
}
catch (err) {
if (err.errno == -2)
{
//@@TODO: throw a proper error.
throw "Path not found: " + path;
}
else
{
console.log(err);
}
}
}
//
// Check whether a path exists.
//
function pathExists(path)
{
return fs.existsSync(path);
}
//
// Create folder.
//
function createFolder(path)
{
fs.mkdirSync(path);
}
function isFolder(path)
{
return fs.lstatSync(path).isDirectory();
}
//
// Copy a file.
//
function copyFile(source, target)
{
let targetFile = target;
// if target is a directory a new file with the same name will be created
if (pathExists(target))
{
if (isFolder(target))
{
targetFile = path.join(target, path.basename(source));
}
}
writeFile(targetFile, readFile(source));
}
//
// Recursively copy files and folders from source to target.
//
function copyFolderRecursive(source, target)
{
let files = [];
// check if folder needs to be created
if (!pathExists(target))
{
createFolder(target);
}
// copy
if (isFolder(source))
{
files = fs.readdirSync(source);
files.forEach(function (file) {
let curSource = path.join(source, file);
let curTarget = path.join(target, path.relative(source, curSource));
if (isFolder(curSource))
{
copyFolderRecursive(curSource, curTarget);
}
else
{
copyFile(curSource, target);
}
});
}
}
//
// Generate a settings JSON file.
//
function generateSettings(name)
{
let json = {};
json.input_path = "";
json.output_path = "";
json.input_pages_path = "";
json.output_pages_path = "";
json.resources = "";
json.templates = [{name: "default", path:""}];
json.title = "";
json.default = "default";
let str = JSON.stringify(json, null, 4);
if (name == null)
{
writeFile("./settings.json", str);
}
else
{
writeFile("./" + name, str);
}
}
//
// Parse the settings JSON file.
//
function parseSettings(data)
{
let json = JSON.parse(data);
const properties = {
// paths
input_path: ".",
output_path: ".",
input_pages_path: "pages",
output_pages_path: "pages",
resources: "resources",
templates: [
// name:
// path:
],
// site settings
base_url: "/",
title: null,
default: "default",
// optimization options
client_markdown: true,
};
for (property in json)
{
settings[property] = json[property];
}
for (property in properties)
{
if (settings[property] == null)
{
settings[property] = properties[property];
}
}
}
//
// Parse the pages.
// Return page objects, which have metadata properties and a content property.
//
function parsePages()
{
let filenames = getFilenames(settings.input_path + '/' + settings.input_pages_path);
let pages = [];
let pageObjs = [];
for (file in filenames)
{
pages.push(readFile(settings.input_path + '/' + settings.input_pages_path + '/' + filenames[file]));
}
for (index in pages)
{
let page = pages[index];
let pageObj = {};
pageObj.name = filenames[index];
//@@TODO: transform page contents
// extract the metadata from the front of the file
let pos = 0;
let cur = page.charAt(pos);
let metadata;
function advance()
{
pos++;
cur = page.charAt(pos);
}
while (cur != null && cur != '')
{
if (cur == '-')
{
if (page.charAt(pos + 1) == '-' &&
page.charAt(pos + 2) == '-')
{
pos++;
cur = page.charAt(pos);
metadata = '';
while (cur != '-' ||
page.charAt(pos + 1) != '-' ||
page.charAt(pos + 2) != '-')
{
metadata += cur;
advance();
}
// move past the '---'
advance();
advance();
advance();
advance();
// chop off the metadata
page = page.slice(pos);
page = page.trimLeft();
// trim the front:
metadata = metadata.slice(2);
if (metadata.charAt(0) == '\n' || metadata.charAt(0) == '\r')
{
metadata = metadata.slice(1);
}
break;
}
}
else if (cur != '\n' && cur != ' ' && cur != '\t' && cur != '\r')
{
//@@TODO: Emit a better error (and stop program?)
console.log("no valid YAML, page " + index);
break;
}
advance();
}
let dataObj = {};
if (metadata)
{
dataObj = parseMetadata(metadata);
}
// defaults
const properties = {
name: pageObj.name,
title: null,
template: null,
// ...
};
// copy the dataObj properties into the pageObj.
for (property in dataObj)
{
pageObj[property] = dataObj[property];
}
for (property in properties)
{
if (pageObj[property] == null)
{
pageObj[property] = properties[property];
}
}
pageObj.content = page;
pageObj.path = '/' + settings.output_pages_path + '/' + pageObj.name + '.html';
pageObjs.push(pageObj);
}
settings.pages = pageObjs;
}
//
// Parse YAML metadata.
//
function parseMetadata(metadata)
{
let lines = metadata.split('\n');
let dataObj = {};
for (i in lines)
{
let line = lines[i];
line = line.trim();
if (line == '') continue; // skip blank lines
let separator = line.indexOf(':');
let k = line.slice(0, separator);
let v = line.substr(separator + 1);
k = k.trim();
v = v.trim();
dataObj[k] = v;
}
return dataObj;
}
//
// Get template information by name.
//
function getTemplate(name)
{
let template = settings.templates.find(function (e) {
return e.name == name;
});
if (template != null)
{
template.html = readFile(settings.input_path + '/' + template.path);
}
else
{
//@@TODO: throw error and exit if template not found.
throw 'No template called "' + name + '" found.';
}
return template;
}
//
// Get index template.
//
function getIndex()
{
return {
name: "index",
path: settings.input_path + "/index.html",
html: readFile(settings.input_path + '/index.html')
};
}
//
// Get page information by name.
//
function getPage(name)
{
let page = settings.pages.find(function (e) {
return e.name == name;
});
if (page != null)
{
return page;
}
else
{
//@@TODO: throw error and exit if page not found.
throw 'No page called ' + name + ' found.';
}
}
//
// Generate HTML.
// A basic templating engine.
//
function generateHTML(template, page)
{
site = settings; // alias global settings.
let html = template.html;
let output = '';
//@@TODO: throw proper error.
if (html.length == 0) throw "Template " + template.name + " has no content.";
// include a page
function include(name)
{
return getPage(name).content;
}
output = eval('`' + html + '`');
return output;
}
function printHelp()
{
console.log("Usage: node ossg.js [-g | -V | -h] [file]");
console.log("Oscar's static site generator. Compile templates & pages into a website.");
}
function printVersion()
{
console.log("OSSG: v0.0.1");
}
main();