-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathgenerator.js
1597 lines (1282 loc) · 49.3 KB
/
generator.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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
// Requires
var firebase = require('firebase');
var request = require('request');
var mkdirp = require('mkdirp');
var path = require('path');
var fs = require('fs');
var glob = require('glob');
var tinylr = require('tiny-lr');
var _ = require('lodash');
var wrench = require('wrench');
var utils = require('./utils.js');
var websocketServer = require('nodejs-websocket');
var Zip = require('adm-zip');
var slug = require('uslug');
var async = require('async');
var spawn = require('win-spawn');
var md5 = require('MD5');
var $ = require('cheerio');
var exec = require('child_process').exec;
require('colors');
// Template requires
// TODO: Abstract these later to make it simpler to change
var swig = require('swig');
swig.setDefaults({ loader: swig.loaders.fs(__dirname + '/..') });
var swigFunctions = require('./swig_functions').swigFunctions();
var swigFilters = require('./swig_filters');
var swigTags = require('./swig_tags');
swigFilters.init(swig);
swigTags.init(swig);
swig.setDefaults({ cache: false });
var wrap = function()
{
var args = Array.prototype.slice.call(arguments);
var last = args.pop();
last = 'debugger;' +
'var global = null;' +
'var console = null;' +
'var v8debug = null;' +
'var setTimeout = null;' +
'var setInterval = null;' +
'var setImmediate = null;' +
'var clearTimeout = null;' +
'var clearInterval = null;' +
'var clearImmediate = null;' +
'var root = null;' +
'var GLOBAL = null;' +
'var window = null;' +
'var process = null;' +
'var eval = null;' +
'var require = null;' +
'var __filename = null;' +
'var __dirname = null;' +
'var modules = null;' +
'var exports = null;' +
last;
args.push(last);
return Function.prototype.constructor.apply(this, args);
};
wrap.prototype = Function.prototype;
Function = wrap;
// Disable console log in various things
//console.log = function () {};
var cmsSocketPort = 6557;
/**
* Generator that handles various commands
* @param {Object} config Configuration options from .firebase.conf
* @param {Object} logger Object to use for logging, defaults to no-ops
*/
module.exports.generator = function (config, options, logger, fileParser) {
var self = this;
var firebaseUrl = config.get('webhook').firebase || 'webhook';
var liveReloadPort = config.get('connect')['wh-server'].options.livereload;
if(liveReloadPort !== 35730) {
cmsSocketPort = liveReloadPort + 1;
}
var websocket = null;
var strictMode = false;
var productionFlag = false;
this.versionString = null;
this.cachedData = null;
if(liveReloadPort === true)
{
liveReloadPort = 35729;
}
logger = logger || { ok: function() {}, error: function() {}, write: function() {}, writeln: function() {} };
// We dont error out here so init can still be run
if (firebaseUrl)
{
this.root = new firebase('https://' + firebaseUrl + '.firebaseio.com/');
} else {
this.root = null;
}
/**
* Used to get the bucket were using (combinaton of config and environment)
*/
var getBucket = function() {
return self.root.child('buckets/' + config.get('webhook').siteName + '/' + config.get('webhook').secretKey + '/dev');
};
/**
* Used to get the dns information about a site (used for certain swig functions)
*/
var getDnsChild = function() {
return self.root.child('management/sites/' + config.get('webhook').siteName + '/dns');
};
var getTypeData = function(type, callback) {
getBucket().child('contentType').child(type).once('value', function(data) {
callback(data.val());
});
}
/**
* Retrieves snapshot of data from Firebase
* @param {Function} callback Callback function to run after data is retrieved, is sent the snapshot
*/
var getData = function(callback) {
if(self.cachedData)
{
swigFunctions.setData(self.cachedData.data);
swigFunctions.setTypeInfo(self.cachedData.typeInfo);
swigFunctions.setSettings(self.cachedData.settings);
swigFilters.setSiteDns(self.cachedData.siteDns);
swigFilters.setFirebaseConf(config.get('webhook'));
swigFilters.setTypeInfo(self.cachedData.typeInfo);
callback(self.cachedData.data, self.cachedData.typeInfo);
return;
}
if(!self.root)
{
throw new Error('Missing firebase reference, may need to run init');
}
getBucket().once('value', function(data) {
data = data.val();
var typeInfo = {};
var settings = {};
if(!data || !data['contentType'])
{
typeInfo = {};
} else {
typeInfo = data['contentType'];
}
if(!data || !data.settings) {
settings = {};
} else {
settings = data.settings;
}
// Get the data portion of bucket, other things are not needed for templates
if(!data || !data.data) {
data = {};
} else {
data = data.data;
}
self.cachedData = {
data: data,
typeInfo: typeInfo,
settings: settings
};
// Sets the context for swig functions
swigFunctions.setData(data);
swigFunctions.setTypeInfo(typeInfo);
swigFunctions.setSettings(settings);
swigFilters.setTypeInfo(typeInfo);
getDnsChild().once('value', function(snap) {
var siteDns = snap.val() || config.get('webhook').siteName + '.webhook.org';
self.cachedData.siteDns = siteDns;
swigFilters.setSiteDns(siteDns);
swigFilters.setFirebaseConf(config.get('webhook'));
callback(data, typeInfo);
});
}, function(error) {
if(error.code === 'PERMISSION_DENIED') {
console.log('\n========================================================'.red);
console.log('# Permission denied #'.red);
console.log('========================================================'.red);
console.log('#'.red + ' You don\'t have permission to this site or your subscription expired.'.red);
console.log('# Visit '.red + 'https://billing.webhook.com/site/'.yellow + config.get('webhook').siteName.yellow + '/'.yellow + ' to manage your subscription.'.red);
console.log('# ---------------------------------------------------- #'.red)
process.exit(0);
} else {
throw new Error(error);
}
});
};
var searchEntryStream = null;
this.openSearchEntryStream = function(callback) {
if(config.get('webhook').noSearch === true) {
callback();
return;
}
if(!fs.existsSync('./.build/.wh/')) {
mkdirp.sync('./.build/.wh/');
}
searchEntryStream = fs.createWriteStream('./.build/.wh/searchjson.js');
searchEntryStream.write('var tipuesearch = {"pages": [\n');
callback();
};
this.closeSearchEntryStream = function(callback) {
if(config.get('webhook').noSearch === true || !searchEntryStream) {
callback();
return;
}
searchEntryStream.end(']}');
searchEntryStream.on('close', function() {
callback();
});
};
var writeSearchEntry = function(outFile, output) {
if(config.get('webhook').noSearch === true || !searchEntryStream) {
return;
}
var endUrl = outFile.replace('./.build', '');
if(path.extname(endUrl) !== '.html' || endUrl === '/404.html' || endUrl.indexOf('/_wh_previews') === 0) {
return;
}
endUrl = endUrl.replace('index.html', '');
var content = $.load(output);
var title = content('title').text();
var bodyObj = content('body');
if(bodyObj.attr('data-search-index') === "false") {
return;
}
var specialChild = bodyObj.find('[data-search-index="true"]');
if(specialChild.length > 0) {
bodyObj = specialChild.first();
}
bodyObj.find('script').remove();
bodyObj.find('iframe').remove();
bodyObj.find('object').remove();
bodyObj.find('[data-search-index="false"]').remove();
var body = bodyObj.text().trim();
var tags = "";
if(content('meta[name="keywords"]').length > 0) {
tags = content('meta[name="keywords"]').attr('content');
}
if(searchEntryStream) {
var searchObj = {
title: title,
text: body,
tags: tags,
loc: endUrl
};
searchEntryStream.write(JSON.stringify(searchObj) + ',\n');
searchObj = null;
}
title = '';
body = '';
};
/**
* Writes an instance of a template to the build directory
* @param {string} inFile Template to read
* @param {string} outFile Destination in build directory
* @param {Object} params The parameters to pass to the template
*/
var writeTemplate = function(inFile, outFile, params) {
params = params || {};
params['firebase_conf'] = config.get('webhook');
var originalOutFile = outFile;
// Merge functions in
params = utils.extend(params, swigFunctions.getFunctions());
params.cmsSocketPort = cmsSocketPort;
swigFunctions.init();
var outputUrl = outFile.replace('index.html', '').replace('./.build', '');
swigFunctions.setParams({ CURRENT_URL: outputUrl });
if(params.item) {
params.item = params._realGetItem(params.item._type, params.item._id, true);
}
params.production = productionFlag;
var output = '';
try {
output = swig.renderFile(inFile, params);
} catch (e) {
self.sendSockMessage(e.toString());
if(strictMode) {
throw e;
} else {
console.log('Error while rendering template: ' + inFile);
console.log(e.toString().red);
try {
output = swig.renderFile('./libs/debug500.html', { template: inFile, error: e.toString(), backtrace: e.stack.toString() })
} catch (e) {
return '';
}
}
}
mkdirp.sync(path.dirname(outFile));
fs.writeFileSync(outFile, output);
writeSearchEntry(outFile, output);
// Haha this crazy nonsense is to handle pagination, the swig function "paginate" makes
// shouldPaginate return true if there are more pages left, so we enter a while loop to
// generate each page of the pagination (todo one day, abstract this with above code into simple functions)
swigFunctions.increasePage();
while(swigFunctions.shouldPaginate())
{
outFile = originalOutFile.replace('/index.html', '/' + swigFunctions.pageUrl + swigFunctions.curPage + '/index.html');
outputUrl = outFile.replace('index.html', '').replace('./.build', '');
swigFunctions.setParams({ CURRENT_URL: outputUrl });
try {
var output = swig.renderFile(inFile, params);
} catch (e) {
self.sendSockMessage(e.toString());
if(strictMode) {
throw e;
} else {
console.log('Error while rendering template: ' + inFile);
console.log(e.toString().red);
try {
output = swig.renderFile('./libs/debug500.html', { template: inFile, error: e.toString(), backtrace: e.stack.toString() })
} catch (e) {
return '';
}
}
}
mkdirp.sync(path.dirname(outFile));
fs.writeFileSync(outFile, output);
writeSearchEntry(outFile, output);
swigFunctions.increasePage();
}
return outFile.replace('./.build', '');
};
/**
* Downloads a zip file from the requested url and extracts it into the main directory
* @param {string} zipUrl Url to zip file to download
* @param {Function} callback Callback, first parameter is error (true if error occured);
*/
var downloadRepo = function(zipUrl, callback) {
logger.ok('Downloading preset...');
// Keep track if the request fails to prevent the continuation of the install
var requestFailed = false;
// TODO: have this hit different templating repos
var repoRequest = request(zipUrl);
repoRequest
.on('response', function (response) {
// If we fail, set it as failing and remove zip file
if (response.statusCode !== 200) {
requestFailed = true;
fs.unlinkSync('.preset.zip');
callback(true);
}
})
.pipe(fs.createWriteStream('.preset.zip'))
.on('close', function () {
if (requestFailed) return;
// Unzip into temporary file
var zip = new Zip('.preset.zip');
var entries = zip.getEntries();
if(fs.existsSync('package.json')) {
fs.renameSync('package.json', 'old.package.json');
}
entries.forEach(function(entry) {
var newName = entry.entryName.split('/').slice(1).join('/');
entry.entryName = newName;
});
zip.extractAllTo('.', true);
if(fs.existsSync('old.package.json') && fs.existsSync('package.json')) {
var packageJson = JSON.parse(fs.readFileSync('package.json'));
var oldPackageJson = JSON.parse(fs.readFileSync('old.package.json'));
var depends = packageJson.dependencies;
var oldDepends = oldPackageJson.dependencies;
_.assign(depends, oldDepends);
packageJson.dependencies = depends;
fs.writeFileSync('package.json', JSON.stringify(packageJson, null, " "));
fs.unlinkSync('old.package.json');
} else if(fs.existsSync('old.package.json')) {
fs.renameSync('old.package.json', 'package.json');
}
fs.unlinkSync('.preset.zip');
callback();
});
};
var resetGenerator = function(callback) {
logger.ok('Resetting Generator...');
var zipUrl = 'http://dump.webhook.com/static/generate-repo.zip';
// Keep track if the request fails to prevent the continuation of the install
var requestFailed = false;
// TODO: have this hit different templating repos
var repoRequest = request(zipUrl);
repoRequest
.on('response', function (response) {
// If we fail, set it as failing and remove zip file
if (response.statusCode !== 200) {
requestFailed = true;
fs.unlinkSync('.reset.zip');
callback(true);
}
})
.pipe(fs.createWriteStream('.reset.zip'))
.on('close', function () {
if (requestFailed) return;
// Unzip into temporary file
var zip = new Zip('.reset.zip');
var entries = zip.getEntries();
removeDirectory('.pages-old', function() {
removeDirectory('.templates-old', function() {
removeDirectory('.static-old', function() {
try {
fs.renameSync('pages', '.pages-old');
} catch(error) {
fs.unlinkSync('.reset.zip');
callback(true);
return;
}
try {
fs.renameSync('templates', '.templates-old');
} catch(error) {
fs.renameSync('.pages-old', 'pages');
fs.unlinkSync('.reset.zip');
callback(true);
return;
}
try {
fs.renameSync('static', '.static-old');
} catch(error) {
fs.renameSync('.pages-old', 'pages');
fs.renameSync('.templates-old', 'templates');
fs.unlinkSync('.reset.zip');
callback(true);
return;
}
entries.forEach(function(entry) {
if(entry.entryName.indexOf('pages/') === 0
|| entry.entryName.indexOf('templates/') === 0
|| entry.entryName.indexOf('static/') === 0) {
zip.extractEntryTo(entry.entryName, '.', true, true);
}
});
removeDirectory('.pages-old', function() {
removeDirectory('.templates-old', function() {
removeDirectory('.static-old', function() {
fs.unlinkSync('.reset.zip');
self.init(config.get('webhook').siteName, config.get('webhook').secretKey, true, config.get('webhook').firebase, config.get('webhook').server, function() {
callback();
});
});
});
});
});
});
});
});
};
/**
* Extracts a local theme zip into the current generator directory
* @param zipUrl The location of the zip file on disk
* @param callback The callback to call with the data from the theme
*/
var extractPresetLocal = function(fileData, callback) {
fs.writeFileSync('.preset.zip', fileData, { encoding: 'base64' });
// Unzip into temporary file
var zip = new Zip('.preset.zip');
var entries = zip.getEntries();
if(fs.existsSync('package.json')) {
fs.renameSync('package.json', 'old.package.json');
}
entries.forEach(function(entry) {
var newName = entry.entryName.split('/').slice(1).join('/');
entry.entryName = newName;
});
zip.extractAllTo('.', true);
if(fs.existsSync('old.package.json') && fs.existsSync('package.json')) {
var packageJson = JSON.parse(fs.readFileSync('package.json'));
var oldPackageJson = JSON.parse(fs.readFileSync('old.package.json'));
var depends = packageJson.dependencies;
var oldDepends = oldPackageJson.dependencies;
_.assign(depends, oldDepends);
packageJson.dependencies = depends;
fs.writeFileSync('package.json', JSON.stringify(packageJson, null, " "));
fs.unlinkSync('old.package.json');
} else if(fs.existsSync('old.package.json')) {
fs.renameSync('old.package.json', 'package.json');
}
fs.unlinkSync('.preset.zip');
if(fs.existsSync('.preset-data.json')) {
var presetData = fileParser.readJSON('.preset-data.json');
fs.unlinkSync('.preset-data.json');
logger.ok('Done extracting.');
callback(presetData);
} else {
logger.ok('Done extracting.');
callback(null);
}
}
/**
* Downloads zip file and then sends the preset data for the theme to the CMS for installation
* @param {string} zipUrl Url to zip file to download
* @param {Function} callback Callback, first parameter is preset data to send to CMS
*/
var downloadPreset = function(zipUrl, callback) {
downloadRepo(zipUrl, function() {
if(fs.existsSync('.preset-data.json')) {
var presetData = fileParser.readJSON('.preset-data.json');
fs.unlinkSync('.preset-data.json');
logger.ok('Done downloading.');
callback(presetData);
} else {
logger.ok('Done downloading.');
callback(null);
}
});
};
/**
* Renders all templates in the /pages directory to the build directory
* @param {Function} done Callback passed either a true value to indicate its done, or an error
* @param {Function} cb Callback called after finished, passed list of files changed and done function
*/
this.renderPages = function (done, cb) {
logger.ok('Rendering Pages\n');
getData(function(data) {
glob('pages/**/*', function(err, files) {
files.forEach(function(file) {
if(fs.lstatSync(file).isDirectory()) {
return true;
}
var forceBuild = false;
var newFile = file.replace('pages', './.build');
var dir = path.dirname(newFile);
var filename = path.basename(newFile, path.extname(file));
var extension = path.extname(file);
if(extension === '.html' && filename !== 'index' && path.basename(newFile) !== '404.html' && file.indexOf('.raw.html') === -1 && extension !== 'tpl') {
dir = dir + '/' + filename;
filename = 'index';
}
if(filename.indexOf('.raw') !== -1 && filename.indexOf('.raw') === (filename.length - 4) && extension === '.html') {
filename = filename.slice(0, filename.length - 4);
}
if(extension === '.tpl') {
extension = filename.substr(filename.length - 5, filename.length - 1);
filename = filename.slice(0, filename.length - 5);
forceBuild = true;
}
newFile = dir + '/' + filename + extension;
if(forceBuild || extension === '.html' || extension === '.xml' || extension === '.rss' || extension === '.xhtml' || extension === '.atom' || extension === '.txt') {
writeTemplate(file, newFile);
} else {
mkdirp.sync(path.dirname(newFile));
fs.writeFileSync(newFile, fs.readFileSync(file));
}
});
if(fs.existsSync('./libs/.supported.js')) {
mkdirp.sync('./.build/.wh/_supported');
fs.writeFileSync('./.build/.wh/_supported/index.html', fs.readFileSync('./libs/.supported.js'));
}
logger.ok('Finished Rendering Pages\n');
if(cb) cb(done);
});
});
};
var generatedSlugs = {};
var generateSlug = function(value) {
if(!generatedSlugs[value._type]) {
generatedSlugs[value._type] = {};
}
if(value.slug) {
generatedSlugs[value._type][value.slug] = true;
return value.slug;
}
var tmpSlug = slug(value.name).toLowerCase();
var no = 2;
while(generatedSlugs[value._type][tmpSlug]) {
tmpSlug = slug(value.name).toLowerCase() + '_' + no;
no++;
}
generatedSlugs[value._type][tmpSlug] = true;
return tmpSlug;
}
/**
* Renders all templates in the /templates directory to the build directory
* @param {Function} done Callback passed either a true value to indicate its done, or an error
* @param {Function} cb Callback called after finished, passed list of files changed and done function
*/
this.renderTemplates = function(done, cb) {
logger.ok('Rendering Templates');
generatedSlugs = {};
getData(function(data, typeInfo) {
glob('templates/**/*.html', function(err, files) {
files.forEach(function(file) {
// We ignore partials, special directory to allow making of partial includes
if(path.extname(file) === '.html' && file.indexOf('templates/partials') !== 0)
{
if(path.dirname(file).split('/').length <= 1) {
return true;
}
// Here we try and abstract out the content type name from directory structure
var baseName = path.basename(file, '.html');
var newPath = path.dirname(file).replace('templates', './.build').split('/').slice(0,3).join('/');
var pathParts = path.dirname(file).split('/');
var objectName = pathParts[1];
var items = data[objectName];
var info = typeInfo[objectName];
var filePath = path.dirname(file);
var overrideFile = null;
if(!items) {
logger.error('Missing data for content type ' + objectName);
}
items = _.map(items, function(value, key) { value._id = key; value._type = objectName; return value });
var publishedItems = _.filter(items, function(item) {
if(!item.publish_date) {
return false;
}
var now = Date.now();
var pdate = Date.parse(item.publish_date);
if(pdate > now + (1 * 60 * 1000)) {
return false;
}
return true;
});
var baseNewPath = '';
// Find if this thing has a template control
var templateWidgetName = null;
if(typeInfo[objectName]) {
typeInfo[objectName].controls.forEach(function(control) {
if(control.controlType === 'layout') {
templateWidgetName = control.name;
}
});
}
var listPath = null;
if(typeInfo[objectName] && typeInfo[objectName].customUrls && typeInfo[objectName].customUrls.listUrl) {
var customPathParts = newPath.split('/');
if(typeInfo[objectName].customUrls.listUrl === '#') // Special remove syntax
{
listPath = customPathParts.join('/');
customPathParts.splice(2, 1);
} else {
customPathParts[2] = typeInfo[objectName].customUrls.listUrl;
}
newPath = customPathParts.join('/');
}
var origNewPath = newPath;
// TODO, DETECT IF FILE ALREADY EXISTS, IF IT DOES APPEND A NUMBER TO IT DUMMY
if(baseName === 'list')
{
newPath = newPath + '/index.html';
if(listPath) {
newPath = listPath + '/index.html';
}
writeTemplate(file, newPath);
} else if (baseName === 'individual') {
// Output should be path + id + '/index.html'
// Should pass in object as 'item'
baseNewPath = newPath;
var previewPath = baseNewPath.replace('./.build', './.build/_wh_previews');
// TODO: Check to make sure file does not exist yet, and then adjust slug if it does? (how to handle in swig functions)
for(var key in publishedItems)
{
var val = publishedItems[key];
if(templateWidgetName && val[templateWidgetName]) {
overrideFile = 'templates/' + objectName + '/layouts/' + val[templateWidgetName];
}
var addSlug = true;
if(val.slug) {
baseNewPath = './.build/' + val.slug + '/';
addSlug = false;
} else {
if(typeInfo[objectName] && typeInfo[objectName].customUrls && typeInfo[objectName].customUrls.individualUrl) {
baseNewPath = origNewPath + '/' + utils.parseCustomUrl(typeInfo[objectName].customUrls.individualUrl, val) + '/';
} else {
baseNewPath = origNewPath + '/';
}
}
var tmpSlug = '';
if(!val.slug) {
tmpSlug = generateSlug(val);
} else {
tmpSlug = val.slug;
}
if(addSlug) {
val.slug = baseNewPath.replace('./.build/', '') + tmpSlug;
newPath = baseNewPath + tmpSlug + '/index.html';
} else {
newPath = baseNewPath + 'index.html';
}
if(fs.existsSync(overrideFile)) {
writeTemplate(overrideFile, newPath, { item: val });
overrideFile = null;
} else {
writeTemplate(file, newPath, { item: val });
}
}
for(var key in items)
{
var val = items[key];
if(templateWidgetName && val[templateWidgetName]) {
overrideFile = 'templates/' + objectName + '/layouts/' + val[templateWidgetName];
}
newPath = previewPath + '/' + val.preview_url + '/index.html';
if(fs.existsSync(overrideFile)) {
writeTemplate(overrideFile, newPath, { item: val });
overrideFile = null;
} else {
writeTemplate(file, newPath, { item: val });
}
}
} else if(filePath.indexOf('templates/' + objectName + '/layouts') !== 0) { // Handle sub pages in here
baseNewPath = newPath;
var middlePathName = filePath.replace('templates/' + objectName, '') + '/' + baseName;
middlePathName = middlePathName.substring(1);
for(var key in publishedItems)
{
var val = publishedItems[key];
var addSlug = true;
if(val.slug) {
baseNewPath = './.build/' + val.slug + '/';
addSlug = false;
} else {
if(typeInfo[objectName] && typeInfo[objectName].customUrls && typeInfo[objectName].customUrls.individualUrl) {
baseNewPath = origNewPath + '/' + utils.parseCustomUrl(typeInfo[objectName].customUrls.individualUrl, val) + '/';
} else {
baseNewPath = origNewPath + '/';
}
}
var tmpSlug = '';
if(!val.slug) {
tmpSlug = generateSlug(val);
} else {
tmpSlug = val.slug;
}
if(addSlug) {
val.slug = baseNewPath.replace('./.build/', '') + tmpSlug;
newPath = baseNewPath + tmpSlug + '/' + middlePathName + '/index.html';
} else {
newPath = baseNewPath + middlePathName + '/index.html';
}
writeTemplate(file, newPath, { item: val });
}
}
}
});
logger.ok('Finished Rendering Templates');
if(cb) cb(done);
});
});
};
/**
* Copies the static directory into .build/static for asset generation
* @param {Function} callback Callback called after creation of directory is done
*/
this.copyStatic = function(callback) {
logger.ok('Copying static');
if(fs.existsSync('static')) {
mkdirp.sync('.build/static');
wrench.copyDirSyncRecursive('static', '.build/static', { forceDelete: true });
}
callback();
};
var removeDirectory = function(directory, callback) {
var isWin = /^win/.test(process.platform);
if(isWin) {
exec('rmdir /s /q ' + directory, function(err) {
if(err) {
if(fs.existsSync(directory)) {
wrench.rmdirSyncRecursive(directory);
}
}
callback();
});
} else {
if(fs.existsSync(directory)) {
wrench.rmdirSyncRecursive(directory);
}
callback();
}
}
self.staticHashs = false;
self.changedStaticFiles = [];
/**
* This creates a hash table of all the static files, used to send detailed information to livereload
* We only do this for static files for speed, for regular files a full reload usually is ok.
*/
var createStaticHashs = function() {
self.staticHashs = {};
self.changedStaticFiles = [];
if(fs.existsSync('.build/static')) {
var files = wrench.readdirSyncRecursive('.build/static');
files.forEach(function(file) {
var file = '.build/static/' + file;
if(!fs.lstatSync(file).isDirectory()) {
var hash = md5(fs.readFileSync(file));
self.staticHashs[file] = hash;
}
})
} else {
self.staticHashs = false;
self.changedStaticFiles = [];
}
};
/**
* Cleans the build directory
* @param {Function} done Callback passed either a true value to indicate its done, or an error
* @param {Function} cb Callback called after finished, passed list of files changed and done function
*/
this.cleanFiles = function(done, cb) {
logger.ok('Cleaning files');
removeDirectory('.build', function() {
if (cb) cb();
if (done) done(true);
});
};
var buildQueue = async.queue(function (task, callback) {
if(task.type === 'static') {
// For static builds we create a hash table to send correct livereload info
// We only do this for static files for speed, normal builds dont really matter
createStaticHashs();