UNPKG

9.97 kBJavaScriptView Raw
1'use strict';
2
3const _ = require('lodash');
4const createStylelint = require('./createStylelint');
5const createStylelintResult = require('./createStylelintResult');
6const debug = require('debug')('stylelint:standalone');
7const FileCache = require('./utils/FileCache');
8const filterFilePaths = require('./utils/filterFilePaths');
9const formatters = require('./formatters');
10const fs = require('fs');
11const getFormatterOptionsText = require('./utils/getFormatterOptionsText');
12const globby = require('globby');
13const hash = require('./utils/hash');
14const invalidScopeDisables = require('./invalidScopeDisables');
15const needlessDisables = require('./needlessDisables');
16const NoFilesFoundError = require('./utils/noFilesFoundError');
17const path = require('path');
18const pkg = require('../package.json');
19const { default: ignore } = require('ignore');
20const DEFAULT_IGNORE_FILENAME = '.stylelintignore';
21const FILE_NOT_FOUND_ERROR_CODE = 'ENOENT';
22const ALWAYS_IGNORED_GLOBS = ['**/node_modules/**'];
23const writeFileAtomic = require('write-file-atomic');
24
25/** @typedef {import('stylelint').StylelintStandaloneOptions} StylelintOptions */
26/** @typedef {import('stylelint').StylelintStandaloneReturnValue} StylelintStandaloneReturnValue */
27/** @typedef {import('stylelint').StylelintResult} StylelintResult */
28
29/**
30 * @param {StylelintOptions} options
31 * @returns {Promise<StylelintStandaloneReturnValue>}
32 */
33module.exports = function(options) {
34 const cacheLocation = options.cacheLocation;
35 const code = options.code;
36 const codeFilename = options.codeFilename;
37 const config = options.config;
38 const configBasedir = options.configBasedir;
39 const configFile = options.configFile;
40 const configOverrides = options.configOverrides;
41 const customSyntax = options.customSyntax;
42 const globbyOptions = options.globbyOptions;
43 const files = options.files;
44 const fix = options.fix;
45 const formatter = options.formatter;
46 const ignoreDisables = options.ignoreDisables;
47 const reportNeedlessDisables = options.reportNeedlessDisables;
48 const reportInvalidScopeDisables = options.reportInvalidScopeDisables;
49 const maxWarnings = options.maxWarnings;
50 const syntax = options.syntax;
51 const allowEmptyInput = options.allowEmptyInput || false;
52 const useCache = options.cache || false;
53 /** @type {FileCache} */
54 let fileCache;
55 const startTime = Date.now();
56
57 // The ignorer will be used to filter file paths after the glob is checked,
58 // before any files are actually read
59 const ignoreFilePath = options.ignorePath || DEFAULT_IGNORE_FILENAME;
60 const absoluteIgnoreFilePath = path.isAbsolute(ignoreFilePath)
61 ? ignoreFilePath
62 : path.resolve(process.cwd(), ignoreFilePath);
63 let ignoreText = '';
64
65 try {
66 ignoreText = fs.readFileSync(absoluteIgnoreFilePath, 'utf8');
67 } catch (readError) {
68 if (readError.code !== FILE_NOT_FOUND_ERROR_CODE) throw readError;
69 }
70
71 /**
72 * TODO TYPES
73 * @type {any}
74 */
75 const ignorePattern = options.ignorePattern || [];
76 const ignorer = ignore()
77 .add(ignoreText)
78 .add(ignorePattern);
79
80 const isValidCode = typeof code === 'string';
81
82 if ((!files && !isValidCode) || (files && (code || isValidCode))) {
83 throw new Error('You must pass stylelint a `files` glob or a `code` string, though not both');
84 }
85
86 /** @type {Function} */
87 let formatterFunction;
88
89 if (typeof formatter === 'string') {
90 formatterFunction = formatters[formatter];
91
92 if (formatterFunction === undefined) {
93 return Promise.reject(
94 new Error(
95 `You must use a valid formatter option: ${getFormatterOptionsText()} or a function`,
96 ),
97 );
98 }
99 } else if (typeof formatter === 'function') {
100 formatterFunction = formatter;
101 } else {
102 formatterFunction = formatters.json;
103 }
104
105 const stylelint = createStylelint({
106 config,
107 configFile,
108 configBasedir,
109 configOverrides,
110 ignoreDisables,
111 ignorePath: ignoreFilePath,
112 reportNeedlessDisables,
113 reportInvalidScopeDisables,
114 syntax,
115 customSyntax,
116 fix,
117 });
118
119 if (!files) {
120 const absoluteCodeFilename =
121 codeFilename !== undefined && !path.isAbsolute(codeFilename)
122 ? path.join(process.cwd(), codeFilename)
123 : codeFilename;
124
125 // if file is ignored, return nothing
126 if (
127 absoluteCodeFilename &&
128 !filterFilePaths(ignorer, [path.relative(process.cwd(), absoluteCodeFilename)]).length
129 ) {
130 return Promise.resolve(prepareReturnValue([]));
131 }
132
133 return stylelint
134 ._lintSource({
135 code,
136 codeFilename: absoluteCodeFilename,
137 })
138 .then((postcssResult) => {
139 // Check for file existence
140 return new Promise((resolve, reject) => {
141 if (!absoluteCodeFilename) {
142 reject();
143
144 return;
145 }
146
147 fs.stat(absoluteCodeFilename, (err) => {
148 if (err) {
149 reject();
150 } else {
151 resolve();
152 }
153 });
154 })
155 .then(() => {
156 return stylelint._createStylelintResult(postcssResult, absoluteCodeFilename);
157 })
158 .catch(() => {
159 return stylelint._createStylelintResult(postcssResult);
160 });
161 })
162 .catch(_.partial(handleError, stylelint))
163 .then((stylelintResult) => {
164 const postcssResult = stylelintResult._postcssResult;
165 const returnValue = prepareReturnValue([stylelintResult]);
166
167 if (options.fix && postcssResult && !postcssResult.stylelint.ignored) {
168 // If we're fixing, the output should be the fixed code
169 returnValue.output = postcssResult.root.toString(postcssResult.opts.syntax);
170 }
171
172 return returnValue;
173 });
174 }
175
176 let fileList = files;
177
178 if (typeof fileList === 'string') {
179 fileList = [fileList];
180 }
181
182 if (!options.disableDefaultIgnores) {
183 fileList = fileList.concat(ALWAYS_IGNORED_GLOBS.map((glob) => `!${glob}`));
184 }
185
186 if (useCache) {
187 const stylelintVersion = pkg.version;
188 const hashOfConfig = hash(`${stylelintVersion}_${JSON.stringify(config || {})}`);
189
190 fileCache = new FileCache(cacheLocation, hashOfConfig);
191 } else {
192 // No need to calculate hash here, we just want to delete cache file.
193 fileCache = new FileCache(cacheLocation);
194 // Remove cache file if cache option is disabled
195 fileCache.destroy();
196 }
197
198 return globby(fileList, globbyOptions)
199 .then((filePaths) => {
200 // The ignorer filter needs to check paths relative to cwd
201 filePaths = filterFilePaths(
202 ignorer,
203 filePaths.map((p) => path.relative(process.cwd(), p)),
204 );
205
206 if (!filePaths.length) {
207 if (!allowEmptyInput) {
208 throw new NoFilesFoundError(fileList);
209 }
210
211 return Promise.all([]);
212 }
213
214 const cwd = _.get(globbyOptions, 'cwd', process.cwd());
215 let absoluteFilePaths = filePaths.map((filePath) => {
216 const absoluteFilepath = !path.isAbsolute(filePath)
217 ? path.join(cwd, filePath)
218 : path.normalize(filePath);
219
220 return absoluteFilepath;
221 });
222
223 if (useCache) {
224 absoluteFilePaths = absoluteFilePaths.filter(fileCache.hasFileChanged.bind(fileCache));
225 }
226
227 const getStylelintResults = absoluteFilePaths.map((absoluteFilepath) => {
228 debug(`Processing ${absoluteFilepath}`);
229
230 return stylelint
231 ._lintSource({
232 filePath: absoluteFilepath,
233 })
234 .then((postcssResult) => {
235 if (postcssResult.stylelint.stylelintError && useCache) {
236 debug(`${absoluteFilepath} contains linting errors and will not be cached.`);
237 fileCache.removeEntry(absoluteFilepath);
238 }
239
240 /**
241 * If we're fixing, save the file with changed code
242 * @type {Promise<Error | void>}
243 */
244 let fixFile = Promise.resolve();
245
246 if (
247 postcssResult.root &&
248 postcssResult.opts &&
249 !postcssResult.stylelint.ignored &&
250 options.fix
251 ) {
252 // @ts-ignore TODO TYPES toString accepts 0 arguments
253 const fixedCss = postcssResult.root.toString(postcssResult.opts.syntax);
254
255 if (
256 postcssResult.root &&
257 postcssResult.root.source &&
258 // @ts-ignore TODO TYPES css is unknown property
259 postcssResult.root.source.input.css !== fixedCss
260 ) {
261 fixFile = writeFileAtomic(absoluteFilepath, fixedCss);
262 }
263 }
264
265 return fixFile.then(() =>
266 stylelint._createStylelintResult(postcssResult, absoluteFilepath),
267 );
268 })
269 .catch((error) => {
270 // On any error, we should not cache the lint result
271 fileCache.removeEntry(absoluteFilepath);
272
273 return handleError(stylelint, error, absoluteFilepath);
274 });
275 });
276
277 return Promise.all(getStylelintResults);
278 })
279 .then((stylelintResults) => {
280 if (useCache) {
281 fileCache.reconcile();
282 }
283
284 return prepareReturnValue(stylelintResults);
285 });
286
287 /**
288 * @param {StylelintResult[]} stylelintResults
289 * @returns {StylelintStandaloneReturnValue}
290 */
291 function prepareReturnValue(stylelintResults) {
292 const errored = stylelintResults.some(
293 (result) => result.errored || result.parseErrors.length > 0,
294 );
295
296 /** @type {StylelintStandaloneReturnValue} */
297 const returnValue = {
298 errored,
299 results: [],
300 output: '',
301 };
302
303 if (reportNeedlessDisables) {
304 returnValue.needlessDisables = needlessDisables(stylelintResults);
305 }
306
307 if (reportInvalidScopeDisables) {
308 returnValue.invalidScopeDisables = invalidScopeDisables(
309 stylelintResults,
310 stylelint._options.config,
311 );
312 }
313
314 if (maxWarnings !== undefined) {
315 const foundWarnings = stylelintResults.reduce((count, file) => {
316 return count + file.warnings.length;
317 }, 0);
318
319 if (foundWarnings > maxWarnings) {
320 returnValue.maxWarningsExceeded = { maxWarnings, foundWarnings };
321 }
322 }
323
324 returnValue.output = formatterFunction(stylelintResults, returnValue);
325 returnValue.results = stylelintResults;
326
327 debug(`Linting complete in ${Date.now() - startTime}ms`);
328
329 return returnValue;
330 }
331};
332
333/**
334 * @param {import('stylelint').StylelintInternalApi} stylelint
335 * @param {any} error
336 * @param {string} [filePath]
337 * @return {Promise<StylelintResult>}
338 */
339function handleError(stylelint, error, filePath = undefined) {
340 if (error.name === 'CssSyntaxError') {
341 return createStylelintResult(stylelint, undefined, filePath, error);
342 }
343
344 throw error;
345}