UNPKG

2.77 kBJavaScriptView Raw
1/*
2 * grunt
3 * http://gruntjs.com/
4 *
5 * Copyright (c) 2012 "Cowboy" Ben Alman
6 * Licensed under the MIT license.
7 * https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT
8 */
9
10module.exports = function(grunt) {
11
12 // ==========================================================================
13 // HELPERS
14 // ==========================================================================
15
16 // Get a config property. Most useful as a directive like <config:foo.bar>.
17 grunt.registerHelper('config', grunt.config);
18
19 // Read a JSON file. Most useful as a directive like <json:package.json>.
20 var jsons = {};
21 grunt.registerHelper('json', function(filepath) {
22 // Don't re-fetch if being called as a directive and JSON is already cached.
23 if (!this.directive || !(filepath in jsons)) {
24 jsons[filepath] = grunt.file.readJSON(filepath);
25 }
26 return jsons[filepath];
27 });
28
29 // Return the given source coude with any leading banner comment stripped.
30 grunt.registerHelper('strip_banner', function(src, options) {
31 if (!options) { options = {}; }
32 var m = [];
33 if (options.line) {
34 // Strip // ... leading banners.
35 m.push('(?:.*\\/\\/.*\\n)*\\s*');
36 }
37 if (options.block) {
38 // Strips all /* ... */ block comment banners.
39 m.push('\\/\\*[\\s\\S]*?\\*\\/');
40 } else {
41 // Strips only /* ... */ block comment banners, excluding /*! ... */.
42 m.push('\\/\\*[^!][\\s\\S]*?\\*\\/');
43 }
44 var re = new RegExp('^\\s*(?:' + m.join('|') + ')\\s*', '');
45 return src.replace(re, '');
46 });
47
48 // Get a source file's contents with any leading banner comment stripped. If
49 // used as a directive, get options from the flags object.
50 grunt.registerHelper('file_strip_banner', function(filepath, opts) {
51 var src = grunt.file.read(filepath);
52 return grunt.helper('strip_banner', src, this.directive ? this.flags : opts);
53 });
54
55 // Process a file as a template.
56 grunt.registerHelper('file_template', function(filepath) {
57 var src = grunt.file.read(filepath);
58 return grunt.template.process(src);
59 });
60
61 // Generate banner from template.
62 grunt.registerHelper('banner', function(prop) {
63 if (!prop) { prop = 'meta.banner'; }
64 var banner;
65 var tmpl = grunt.config(prop);
66 if (tmpl) {
67 // Now, log.
68 grunt.verbose.write('Generating banner...');
69 try {
70 // Compile and run template, using config object as the data source.
71 banner = grunt.template.process(tmpl) + grunt.utils.linefeed;
72 grunt.verbose.ok();
73 } catch(e) {
74 banner = '';
75 grunt.verbose.error();
76 grunt.warn(e, 11);
77 }
78 } else {
79 grunt.warn('No "' + prop + '" banner template defined.', 11);
80 banner = '';
81 }
82 return banner;
83 });
84
85};