UNPKG

2.85 kBJavaScriptView Raw
1var _ = require('lodash'),
2 async = require ('async'),
3 dateformat = require('dateformat'),
4 Engine = require('./engine'),
5 ncp = require('ncp'),
6 p = require('path'),
7 watchtree = require('watch-tree-maintained'),
8 wrench = require('wrench');
9
10/**
11 * class AE86
12 */
13function AE86(opts) {
14 opts = opts || {};
15 this.outDir = opts.outDir || 'out';
16}
17
18/**
19 * Create example AE86 project files in current directory.
20 *
21 * @param {Function} cb: standard cb(err, result) callback
22 */
23AE86.prototype.init = function (cb) {
24 ncp.ncp(p.join(__dirname, '../examples'), '.', cb);
25};
26
27/**
28 * Generate website based on the templates and params.
29 *
30 * @param {Function} cb: standard cb(err, result) callback
31 */
32AE86.prototype.generate = function (cb) {
33
34 var self = this;
35
36 function _static(cb) {
37 // copy static files as-is
38 ncp.ncp('static', self.outDir, cb);
39 }
40
41 function _pages(cb) {
42
43 function _params() {
44 // initialise userland params
45 var params = require(p.join(process.cwd(), 'params')).params;
46 // add website info
47 params.sitemap = params.sitemap || {};
48 params.__genId = dateformat('yyyymmddHHMMss');
49 return params;
50 }
51
52 var engine = new Engine(),
53 tasks = {};
54
55 ['partials', 'layouts', 'pages'].forEach(function (dir) {
56 tasks[dir] = function (cb) {
57 engine.compile(dir, cb);
58 };
59 });
60
61 async.parallel(tasks, function (err, results) {
62 engine.merge(self.outDir, results, _params(), cb);
63 });
64 }
65
66 async.parallel([_static, _pages], cb);
67};
68
69/**
70 * Watch for any file changes in AE86 project files.
71 * A change means the project website will automatically be regenerated.
72 */
73AE86.prototype.watch = function () {
74 const SAMPLE_RATE = 5;
75
76 var self = this;
77
78 function _listener() {
79 // remove cached params.js module so the regeneration will pick up a fresh (possibly modified) params.js
80 delete require.cache[p.join(process.cwd(), 'params.js')];
81 // no callback because the process shouldn't exit
82 self.generate();
83 }
84
85 function _watch(file) {
86 var watcher = watchtree.watchTree(file, {
87 ignore: '\\.swp',
88 'sample-rate': SAMPLE_RATE
89 });
90 watcher.on('fileCreated', function(path, stats) {
91 console.log('%s was created', file);
92 _listener();
93 });
94 watcher.on('fileModified', function(path, stats) {
95 console.log('%s was modified', file);
96 _listener();
97 });
98 watcher.on('fileDeleted', function(path) {
99 console.log('%s was deleted', file);
100 self.clean();
101 _listener();
102 });
103 }
104
105 ['static', 'partials', 'layouts', 'pages', 'params.js'].forEach(_watch);
106};
107
108/**
109 * Remove the generated website.
110 *
111 * @param {Function} cb: standard cb(err, result) callback
112 */
113AE86.prototype.clean = function (cb) {
114 wrench.rmdirRecursive(this.outDir, cb);
115};
116
117module.exports = AE86;