forked from csscomb/csscomb.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcsscomb.js
More file actions
314 lines (277 loc) · 8.61 KB
/
csscomb.js
File metadata and controls
314 lines (277 loc) · 8.61 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
'use strict';
let gonzales = require('gonzales-pe');
let fs = require('fs');
let Comb = require('./core');
let format = require('./format');
let path = require('path');
/**
* @param {String|Object} config
* @constructor
* @name CSScomb
*/
let CSScomb = function(config) {
let comb = new Comb();
// Add plugins.
fs.readdirSync(__dirname + '/options').map(function(option) {
return require('./options/' + option);
}).forEach(function(option) {
comb.use(option);
});
// If config was passed, configure:
if (typeof config === 'string') {
config = CSScomb.getConfig(config);
}
if (typeof config === 'object') {
comb.configure(config);
}
// Chaining.
return comb;
};
/**
* STATIC METHODS
* Methods that can be called without creating an instance:
* - detectInFile;
* - detectInString;
* - getConfig;
* - getCustomConfig;
* - getCustomConfigPath;
* For example: `CSScomb.getConfig('zen')`
*/
/**
* Detects the options in the given file
*
* @param {String} file Path to the stylesheet
* @param {Array} options List of options to detect
* @returns {Object} Detected options
*/
CSScomb.detectInFile = function detectInFile(file, options) {
var stylesheet = fs.readFileSync(file, 'utf8');
return CSScomb.detectInString(stylesheet, options);
};
/**
* Detects the options in the given string
*
* @param {String} text Stylesheet
* @param {Array} options List of options to detect
* @returns {Object} Detected options
*/
CSScomb.detectInString = function detectInString(text, options) {
var result;
var handlers = [];
if (!text) return text;
var optionNames = fs.readdirSync(__dirname + '/options');
optionNames.forEach(function(option) {
option = option.slice(0, -3);
if (options && options.indexOf(option) < 0) return;
try {
handlers.push(getHandler(option));
} catch (e) {
let message = `\nFailed to load "${option}" option:\n${e.message}`;
console.warn(message);
}
});
var tree = cssToAST(text);
var detectedOptions = detectInTree(tree, handlers);
result = getDetectedOptions(detectedOptions, handlers);
// Handle conflicting options with spaces around braces:
var blockIndent = result['block-indent'];
var spaceAfterOpeningBrace = result['space-after-opening-brace'];
if (typeof blockIndent === 'string' &&
spaceAfterOpeningBrace &&
spaceAfterOpeningBrace.indexOf('\n') > -1) {
result['space-after-opening-brace'] = '\n';
}
return result;
};
/**
* Gets one of configuration files from configs' directory.
*
* @param {String} name Config's name, e.g. 'yandex'
* @returns {Object} Configuration object
*/
CSScomb.getConfig = function getConfig(name) {
const DEFAULT_CONFIG_NAME = 'csscomb';
name = name || DEFAULT_CONFIG_NAME;
if (typeof name !== 'string') {
throw new Error('Config name must be a string.');
}
let CONFIG_DIR_PATH = '../config';
let dir = `${__dirname}/${CONFIG_DIR_PATH}`;
let availableConfigsNames = fs.readdirSync(dir)
.map(function(configFileName) {
return configFileName.split('.')[0]; // Strip file extension(s)
});
if (availableConfigsNames.indexOf(name) < 0) {
let configsNamesAsString = availableConfigsNames
.map(function(configName) {
return '\'' + configName + '\'';
})
.join(', ');
let message = `"${name}" is not a valid config name. Try one
of the following: ${configsNamesAsString}.`;
throw new Error(format(message));
}
return require(CONFIG_DIR_PATH + '/' + name + '.json');
};
/**
* Gets configuration from provided config path or looks for it in common
* places.
*
* @param {String} [configPath]
* @returns {Object|null}
*/
CSScomb.getCustomConfig = function getCustomConfig(configPath) {
var config;
configPath = configPath || CSScomb.getCustomConfigPath();
try {
config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
} catch (e) {
config = null;
}
return config;
};
/**
* Looks for a config file: recursively from current (process) directory
* up to $HOME dir
* If no custom config file is found, return `null`.
*
* @param {String} [configPath]
* @returns {String | null}
*/
CSScomb.getCustomConfigPath = function getCustomConfigPath(configPath) {
var HOME = process.env.HOME ||
process.env.HOMEPATH ||
process.env.USERPROFILE;
configPath = configPath || path.join(process.cwd(), '.csscomb.json');
// If we've finally found a config, return its path:
if (fs.existsSync(configPath)) return fs.realpathSync(configPath);
// If we are in HOME dir already and yet no config file, return a default
// one from our package.
// If project is located not under HOME, compare to root instead.
// Since there appears to be no good way to get root path in
// Windows, assume that if current dir has no parent dir, we're in
// root.
var dirname = path.dirname(configPath);
var parentDirname = path.dirname(dirname);
if (dirname === HOME || dirname === parentDirname) return null;
// If there is no config in this directory, go one level up and look for
// a config there:
configPath = path.join(parentDirname, '.csscomb.json');
return CSScomb.getCustomConfigPath(configPath);
};
/**
* Converts CSS string to AST.
*
* @param {String} text CSS string
* @param {String} [syntax] Syntax name (e.g., `scss`)
* @param {String} [filename]
* @returns {Array} AST
*/
function cssToAST(text, syntax, filename) {
var string = JSON.stringify;
var fileInfo = filename ? ' at ' + filename : '';
var tree;
try {
tree = gonzales.parse(text, {syntax: syntax});
} catch (e) {
throw new Error('Parsing error' + fileInfo + ': ' + e.message);
}
// TODO: When can tree be undefined? <tg>
if (typeof tree === 'undefined') {
let message = `Undefined tree ${fileInfo}: ${string(text)} =>
${string(tree)}`;
throw new Error(format(message));
}
return tree;
}
/**
* Processes tree and detects options.
*
* @param {Array} tree
* @param {Array} handlers List of options that we should look for
* @returns {Object} Map with detected options and all variants of possible
* values
*/
function detectInTree(tree, handlers) {
var detectedOptions = {};
// 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) {
detectedOptions[handler.name] = handler.detect(tree);
});
return detectedOptions;
}
/**
* Gets the detected options.
*
* @param {Object} detected
* @param {Array} handlers
* @returns {Object}
*/
function getDetectedOptions(detected, handlers) {
var options = {};
Object.keys(detected).forEach(function(option) {
// List of all the detected variants from the stylesheet
// for the given option:
var values = detected[option];
var i;
if (!values.length) {
// If there are no values for the option, check if there is
// a default one:
for (i = handlers.length; i--;) {
if (handlers[i].name === option &&
handlers[i].detectDefault !== undefined) {
options[option] = handlers[i].detectDefault;
break;
}
}
} else if (values.length === 1) {
options[option] = values[0];
} else {
// If there are more than one value for the option, find
// the most popular one; `variants` would be populated
// with the popularity for different values.
var variants = {};
var bestGuess = null;
var maximum = 0;
for (i = values.length; i--;) {
var currentValue = values[i];
// Count the current value:
if (variants[currentValue]) {
variants[currentValue]++;
} else {
variants[currentValue] = 1;
}
// If the current variant is the most popular one, treat
// it as the best guess:
if (variants[currentValue] >= maximum) {
maximum = variants[currentValue];
bestGuess = currentValue;
}
}
if (bestGuess !== null) {
options[option] = bestGuess;
}
}
});
return options;
}
/**
* Gets option's data needed for detection
*
* @param {String} optionName
* @returns {Object} Object with option's name, link to `detect()` method
* and default value for the case when nothing can be detected
*/
function getHandler(optionName) {
var option = require('./options/' + optionName);
if (!option.detect)
throw new Error('Option does not have `detect()` method.');
return {
name: option.name,
detect: option.detect,
detectDefault: option.detectDefault
};
}
module.exports = CSScomb;