UNPKG

3.01 kBJavaScriptView Raw
1'use strict';
2
3var fs = require('fs');
4var os = require('os');
5var path = require('path');
6var utils = require('./utils');
7
8/**
9 * Register the plugin.
10 *
11 * ```js
12 * // in your generator
13 * this.use(require('generate-collections'));
14 *
15 * // or, to customize options
16 * var collections = require('generate-collections');
17 * this.use(collections.create([options]));
18 * ```
19 * @api public
20 */
21
22function collections(config) {
23 config = config || {};
24
25 return function plugin(app, base) {
26 if (!utils.isValid(app, 'generate-collections')) return;
27 app.define('home', path.resolve.bind(path, os.homedir()));
28
29 /**
30 * Options
31 */
32
33 app.option(config);
34
35 // add default view collections
36 if (!app.files) app.create('files', { viewType: 'renderable'});
37 if (!app.includes) app.create('includes', { viewType: 'partial' });
38 if (!app.layouts) app.create('layouts', { viewType: 'layout' });
39
40 // generator-specific collections
41 if (app.isGenerator && !app.templates) {
42 app.create('templates', { viewType: 'renderable' });
43 }
44
45 /**
46 * Middleware for collections created by this generator
47 */
48
49 app.preLayout(/./, function(view, next) {
50 if (utils.falsey(view.layout) && !view.isType('partial')) {
51 // use the empty layout created above, to ensure that all
52 // pre-and post-layout middleware are still triggered
53 view.layout = app.resolveLayout(view);
54 if (utils.falsey(view.layout)) {
55 view.layout = 'empty';
56 }
57 next();
58 return;
59 }
60
61 if (view.isType('partial')) {
62 view.options.layout = null;
63 view.data.layout = null;
64 view.layout = null;
65 if (typeof view.partialLayout === 'string') {
66 view.layout = view.partialLayout;
67 }
68 }
69 next();
70 });
71
72 // remove or rename template prefixes before writing files to the file system
73 var regex = app.options.templatePathRegex || /./;
74 app.templates.preWrite(regex, utils.renameFile(app));
75 app.templates.onLoad(regex, function(view, next) {
76 var userDefined = app.home('templates', view.basename);
77 if (utils.exists(userDefined)) {
78 view.contents = fs.readFileSync(userDefined);
79 }
80 utils.stripPrefixes(view);
81 utils.parser.parse(view, next);
82 });
83
84 // "noop" layout
85 app.layout('empty', {content: '{% body %}'});
86
87 // create collections defined on the options
88 if (utils.isObject(app.options.create)) {
89 for (var key in app.options.create) {
90 if (!app[key]) {
91 app.create(key, app.options.create[key]);
92 } else {
93 app[key].option(app.options.create[key]);
94 }
95 }
96 }
97
98 // pass the plugin to sub-generators
99 return plugin;
100 };
101}
102
103/**
104 * Expose `plugin` function so that verb-collections
105 * can be run as a global generator
106 */
107
108module.exports = collections();
109
110/**
111 * Expose `collection` function so that options can be passed
112 */
113
114module.exports.create = collections;