-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcore.js
More file actions
423 lines (371 loc) · 12.9 KB
/
Copy pathcore.js
File metadata and controls
423 lines (371 loc) · 12.9 KB
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
var gonzales = require('gonzales-pe');
var minimatch = require('minimatch');
var vow = require('vow');
var vfs = require('vow-fs');
/**
* @param {Array} predefinedOptions
* @constructor
* @name Comb
*/
var Comb = function(predefinedOptions) {
var _this = this;
// List of supported syntaxes:
var supportedSyntaxes = Array.prototype.slice.call(arguments, 1);
// List of file paths that should be excluded from processing:
var exclude;
// List of configured options with values:
var configuredOptions;
// List of handlers:
var handlers;
// Whether lint mode is on:
var lint;
// Whether verbose mode is on:
var verbose;
// Map of used options:
var options = {};
// List of option names in exact order they should be processed:
var optionsOrder = [];
var unmetOptions = {};
/**
* PRIVATE METHODS
*/
function usePredefinedOptions() {
if (!predefinedOptions) return;
predefinedOptions.forEach(function(option) {
_this.use(option);
});
}
/**
* @param {Object} option
*/
function updateOptionOrder(option) {
var name = option.name;
var runBefore = option.runBefore;
var runBeforeIndex;
options[name] = option;
if (runBefore) {
runBeforeIndex = optionsOrder.indexOf(runBefore);
if (runBeforeIndex > -1) {
optionsOrder.splice(runBeforeIndex, 0, name);
} else {
optionsOrder.push(name);
if (!unmetOptions[runBefore]) unmetOptions[runBefore] = [];
unmetOptions[runBefore].push(name);
}
} else {
optionsOrder.push(name);
}
var unmet = unmetOptions[name];
if (unmet) {
unmet.forEach(function(name) {
var i = optionsOrder.indexOf(name);
optionsOrder.splice(i, 1);
optionsOrder.splice( -1, 0, name);
});
}
}
/**
* Adds an option to list of configured options.
*
* @param {Object} option Option's object
* @param {Object} value Value that should be set for the option
* @returns {Object} Object with option's name, value and link to
* `process()` method
*/
function addHandler(option, value) {
value = option.setValue ?
option.setValue(value) :
setValue(option.accepts, value);
handlers.push(option);
configuredOptions[option.name] = value;
}
/**
* Processes value and checks if it is acceptable by the option.
*
* @param {Object} acceptableValues Map of value types that are acceptable
* by option. If `string` property is present, its value is a regular
* expression that is used to validate value passed to the function.
* @param {Object|undefined} value
* @returns {Boolean|String} Valid option's value
*/
function setValue(acceptableValues, value) {
if (!acceptableValues) throw new Error('Option\'s module must either' +
' implement `setValue()` method or provide `accepts` object' +
' with acceptable values.');
var valueType = typeof value;
var pattern = acceptableValues[valueType];
if (!pattern) throw new Error('The option does not accept values of type "' +
valueType + '".\nValue\'s type must be one the following: ' +
Object.keys(acceptableValues).join(', ') + '.');
switch (valueType) {
case 'boolean':
if (pattern.indexOf(value) < 0) throw new Error(' Value must be ' +
'one of the following: ' + pattern.join(', ') + '.');
return value;
case 'number':
if (value !== parseInt(value)) throw new Error('Value must be an integer.');
return new Array(value + 1).join(' ');
case 'string':
if (!value.match(pattern)) throw new Error('Value must match pattern ' +
pattern + '.');
return value;
default:
throw new Error('If you see this message and you are not' +
' a developer adding a new option, please open an issue here:' +
' https://github.com/csscomb/csscomb.js/issues/new' +
'\nFor option to accept values of type "' + valueType +
'" you need to implement custom `setValue()` method. See' +
' `lib/options/sort-order.js` for example.');
}
}
/**
* Checks if path is present in `exclude` list.
*
* @param {String} path
* @returns {Boolean} False if specified path is present in `exclude` list.
* Otherwise returns true.
*/
function shouldProcess(path) {
path = path.replace(/^\.\//, '');
for (var i = exclude.length; i--;) {
if (exclude[i].match(path)) return false;
}
return true;
}
/**
* Checks if specified path is not present in `exclude` list and it has one of
* acceptable extensions.
*
* @param {String} path
* @returns {Boolean} False if the path either has unacceptable extension or
* is present in `exclude` list. True if everything is ok.
*/
function shouldProcessFile(path) {
// Get file's extension:
var syntax = path.split('.').pop();
// Check if syntax is supported. If not, ignore the file:
if (supportedSyntaxes.indexOf(syntax) < 0) {
return false;
}
return shouldProcess(path);
}
/**
* Processes stylesheet tree node.
*
* @param {Array} tree Parsed tree
* @returns {Array} Modified tree
*/
function processTree(tree) {
var _handlers;
_handlers = handlers.filter(function(handler) {
var syntax = _this.getSyntax();
return handler.syntax.indexOf(syntax) > -1;
}).map(function(handler) {
return handler.process;
});
// We walk across complete tree for each handler,
// because we need strictly maintain order in which handlers work,
// despite fact that handlers work on different level of the tree.
_handlers.forEach(function(handler) {
processNode(['tree', tree], 0, handler);
});
return tree;
}
/**
* Processes tree node.
*
* @param {Array} node Tree node
* @param {Number} level Indent level
* @param {Object} handler Option's handler
*/
function processNode(node, level, handler) {
node.forEach(function(node) {
if (!Array.isArray(node)) return;
var nodeType = node.shift();
handler.call(_this, nodeType, node, level);
node.unshift(nodeType);
if (nodeType === 'atrulers' || nodeType === 'block') level++;
processNode(node, level, handler);
});
}
/**
* PUBLIC INSTANCE METHODS
* Methods that depend on certain instance variables, e.g. configuration:
* - use;
* - configure;
* - getOptionsOrder;
* - getValue;
* - getSyntax;
* - processPath;
* - processDirectory;
* - processFile;
* - processString;
*/
/**
*
* @param {Object} option
* @returns {Object} Comb's object
*/
this.use = function use(option) {
var name;
if (typeof option !== 'object') {
throw new Error('Can\'t use option because it is not an object');
}
name = option.name;
if (typeof name !== 'string' || !name) {
throw new Error('Can\'t use option because it has invalid name: ' +
name);
}
if (typeof option.accepts !== 'object' &&
typeof option.setValue !== 'function') {
throw new Error('Can\'t use option "' + name + '"');
}
if (typeof option.process !== 'function') {
throw new Error('Can\'t use option "' + name + '"');
}
updateOptionOrder(option);
return this;
};
/**
* Loads configuration from JSON.
* Activates and configures required options.
*
* @param {Object} config
* @returns {Object} Comb's object (that makes the method chainable).
*/
this.configure = function configure(config) {
handlers = [];
configuredOptions = {};
verbose = config.verbose;
lint = config.lint;
exclude = (config.exclude || []).map(function(pattern) {
return new minimatch.Minimatch(pattern);
});
optionsOrder.forEach(function(optionName) {
if (config[optionName] === undefined) return;
try {
addHandler(options[optionName], config[optionName]);
} catch (e) {
// Show warnings about illegal config values only in verbose mode:
if (verbose) {
console.warn('\nFailed to configure "%s" option:\n%s',
optionName, e.message);
}
}
});
return this;
};
this.getOptionsOrder = function getOptionsOrder() {
return optionsOrder.slice();
};
/**
* Gets option's value.
*
* @param {String} optionName
* @returns {String|Boolean|undefined}
*/
this.getValue = function getValue(optionName) {
return configuredOptions[optionName];
};
this.getSyntax = function getSyntax() {
return _this.syntax;
};
/**
* Processes directory or file.
*
* @param {String} path
* @returns {Promise}
*/
this.processPath = function processPath(path) {
path = path.replace(/\/$/, '');
return vfs.exists(path).then(function(exists) {
if (!exists) {
console.warn('Path ' + path + ' was not found.');
return;
}
return vfs.stat(path).then(function(stat) {
if (stat.isDirectory()) {
return _this.processDirectory(path);
} else {
return _this.processFile(path);
}
});
});
};
/**
* Processes directory recursively.
*
* @param {String} path
* @returns {Promise}
*/
this.processDirectory = function processDirectory(path) {
return vfs.listDir(path).then(function(filenames) {
return vow.all(filenames.map(function(filename) {
var fullname = path + '/' + filename;
return vfs.stat(fullname).then(function(stat) {
if (stat.isDirectory()) {
return shouldProcess(fullname) && _this.processDirectory(fullname);
} else {
return _this.processFile(fullname);
}
});
})).then(function(results) {
return [].concat.apply([], results);
});
});
};
/**
* Processes single file.
*
* @param {String} path
* @returns {Promise}
*/
this.processFile = function processFile(path) {
if (!shouldProcessFile(path)) return;
return vfs.read(path, 'utf8').then(function(data) {
var syntax = path.split('.').pop();
var processedData = _this.processString(data, { syntax: syntax, filename: path });
var isChanged = data !== processedData;
var tick = isChanged ? (lint ? '!' : '✓') : ' ';
var output = function() {
if (verbose) console.log(tick, path);
return isChanged ? 1 : 0;
};
if (!isChanged || lint) {
return output();
} else {
return vfs.write(path, processedData, 'utf8').then(output);
}
});
};
/**
* Processes a string.
*
* @param {String} text
* @param {{context: String, filename: String, syntax: String}} options
* @returns {String} Processed string
*/
this.processString = function processString(text, options) {
var syntax = options && options.syntax;
var filename = options && options.filename || '';
var context = options && options.context;
var tree;
if (!text || !_this.shouldProcessFile(filename)) return text;
// TODO: Parse different syntaxes
_this.syntax = syntax || 'css';
try {
tree = gonzales.srcToAST({ src: text, syntax: syntax, rule: context });
} catch (e) {
var version = require('../package.json').version;
var message = [filename,
e.message,
'CSScomb Core version: ' + version];
e.stack = e.message = message.join('\n');
throw e;
}
tree = processTree(tree);
return gonzales.astToSrc({ syntax: syntax, ast: tree });
};
usePredefinedOptions();
};
module.exports = Comb;