UNPKG

2.32 kBJavaScriptView Raw
1/*
2 * grunt
3 * https://github.com/cowboy/grunt
4 *
5 * Copyright (c) 2012 "Cowboy" Ben Alman
6 * Licensed under the MIT license.
7 * http://benalman.com/about/license/
8 */
9
10var spawn = require('child_process').spawn;
11
12// ============================================================================
13// HELPERS
14// ============================================================================
15
16// Get a config property. Most useful as a directive like <config:foo.bar>.
17task.registerHelper('config', config);
18
19// Read a JSON file. Most useful as a directive like <json:package.json>.
20task.registerHelper('json', file.readJson.bind(file));
21
22// Spawn a child process, capturing its stdout and stderr.
23task.registerHelper('child_process', function(opts, done) {
24 var child = spawn(opts.cmd, opts.args, opts.opts);
25 var results = [];
26 var errors = [];
27 child.stdout.on('data', results.push.bind(results));
28 child.stderr.on('data', errors.push.bind(errors));
29 child.on('exit', function(code) {
30 if (code === 0) {
31 done(null, results.join('').replace(/\s+$/, ''), code);
32 } else if ('fallback' in opts) {
33 done(null, opts.fallback, code);
34 } else {
35 done(code, errors.join('').replace(/\s+$/, ''), code);
36 }
37 });
38});
39
40// Return the given source coude with any leading banner comment stripped.
41task.registerHelper('strip_banner', template.stripBanner);
42
43// Get a source file's contents with any leading banner comment stripped.
44task.registerHelper('file_strip_banner', function(filepath) {
45 return template.stripBanner(file.read(filepath));
46});
47
48// Generate banner from template.
49task.registerHelper('banner', function(prop) {
50 if (!prop) { prop = 'meta.banner'; }
51 var banner, obj;
52 var tmpl = config(prop);
53 if (tmpl) {
54 // Read config object first, to ensure that verbose-mode JSON reading via
55 // <json> directive doesn't interrupt logging.
56 obj = config();
57 // Now, log.
58 verbose.write('Generating banner...');
59 try {
60 // Compile and run template, passing in config object as the data source.
61 banner = template.process(tmpl, obj) + '\n';
62 verbose.ok();
63 } catch(e) {
64 banner = '';
65 verbose.error();
66 fail.warn(e, 11);
67 }
68 } else {
69 fail.warn('No "' + prop + '" banner template defined.', 11);
70 banner = '';
71 }
72 return banner;
73});