UNPKG

2.66 kBJavaScriptView Raw
1'use strict';
2
3var utils = require('../utils');
4
5// internal
6var reEscComments = /\\#/g;
7// note that '^^' is used in place of escaped comments
8var reUnescapeComments = /\^\^/g;
9var reComments = /#.*$/;
10var reEscapeChars = /[.|\-[\]()\\]/g;
11var reAsterisk = /\*/g;
12
13module.exports = add;
14
15/**
16 * Converts file patterns or regular expressions to nodemon
17 * compatible RegExp matching rules. Note: the `rules` argument
18 * object is modified to include the new rule and new RegExp
19 *
20 * ### Example:
21 *
22 * var rules = { watch: [], ignore: [] };
23 * add(rules, 'watch', '*.js');
24 * add(rules, 'ignore', '/public/');
25 * add(rules, 'watch', ':(\d)*\.js'); // note: string based regexp
26 * add(rules, 'watch', /\d*\.js/);
27 *
28 * @param {Object} rules containing `watch` and `ignore`. Also updated during
29 * execution
30 * @param {String} which must be either "watch" or "ignore"
31 * @param {String|RegExp} the actual rule.
32 */
33function add(rules, which, rule) {
34 if (!{ ignore: 1, watch: 1}[which]) {
35 throw new Error('rules/index.js#add requires "ignore" or "watch" as the ' +
36 'first argument');
37 }
38
39 if (Array.isArray(rule)) {
40 rule.forEach(function (rule) {
41 add(rules, which, rule);
42 });
43 return;
44 }
45
46 // support the rule being a RegExp, but reformat it to
47 // the custom :<regexp> format that we're working with.
48 if (rule instanceof RegExp) {
49 // rule = ':' + rule.toString().replace(/^\/(.*?)\/$/g, '$1');
50 utils.log.error('RegExp format no longer supported, but globs are.');
51 return;
52 }
53
54 // remove comments and trim lines
55 // this mess of replace methods is escaping "\#" to allow for emacs temp files
56
57 // first up strip comments and remove blank head or tails
58 rule = (rule || '').replace(reEscComments, '^^')
59 .replace(reComments, '')
60 .replace(reUnescapeComments, '#').trim();
61
62 var regexp = false;
63
64 if (typeof rule === 'string' && rule.substring(0, 1) === ':') {
65 rule = rule.substring(1);
66 utils.log.error('RegExp no longer supported: ' + rule);
67 regexp = true;
68 } else if (rule.length === 0) {
69 // blank line (or it was a comment)
70 return;
71 }
72
73 if (regexp) {
74 // rules[which].push(rule);
75 } else {
76 // rule = rule.replace(reEscapeChars, '\\$&')
77 // .replace(reAsterisk, '.*');
78
79 rules[which].push(rule);
80 // compile a regexp of all the rules for this ignore or watch
81 var re = rules[which].map(function (rule) {
82 return rule.replace(reEscapeChars, '\\$&')
83 .replace(reAsterisk, '.*');
84 }).join('|');
85
86 // used for the directory matching
87 rules[which].re = new RegExp(re);
88 }
89}