standalone.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. 'use strict';
  2. const debug = require('debug')('stylelint:standalone');
  3. const fastGlob = require('fast-glob');
  4. const fs = require('fs');
  5. const globby = require('globby');
  6. const normalizePath = require('normalize-path');
  7. const path = require('path');
  8. const createStylelint = require('./createStylelint');
  9. const createStylelintResult = require('./createStylelintResult');
  10. const FileCache = require('./utils/FileCache');
  11. const filterFilePaths = require('./utils/filterFilePaths');
  12. const formatters = require('./formatters');
  13. const getFileIgnorer = require('./utils/getFileIgnorer');
  14. const getFormatterOptionsText = require('./utils/getFormatterOptionsText');
  15. const hash = require('./utils/hash');
  16. const NoFilesFoundError = require('./utils/noFilesFoundError');
  17. const AllFilesIgnoredError = require('./utils/allFilesIgnoredError');
  18. const { assert } = require('./utils/validateTypes');
  19. const pkg = require('../package.json');
  20. const prepareReturnValue = require('./prepareReturnValue');
  21. const ALWAYS_IGNORED_GLOBS = ['**/node_modules/**'];
  22. const writeFileAtomic = require('write-file-atomic');
  23. /** @typedef {import('stylelint').LinterOptions} LinterOptions */
  24. /** @typedef {import('stylelint').LinterResult} LinterResult */
  25. /** @typedef {import('stylelint').LintResult} StylelintResult */
  26. /** @typedef {import('stylelint').Formatter} Formatter */
  27. /** @typedef {import('stylelint').FormatterType} FormatterType */
  28. /**
  29. *
  30. * @param {LinterOptions} options
  31. * @returns {Promise<LinterResult>}
  32. */
  33. async function standalone({
  34. allowEmptyInput = false,
  35. cache: useCache = false,
  36. cacheLocation,
  37. code,
  38. codeFilename,
  39. config,
  40. configBasedir,
  41. configFile,
  42. customSyntax,
  43. cwd = process.cwd(),
  44. disableDefaultIgnores,
  45. files,
  46. fix,
  47. formatter,
  48. globbyOptions,
  49. ignoreDisables,
  50. ignorePath,
  51. ignorePattern,
  52. maxWarnings,
  53. quiet,
  54. reportDescriptionlessDisables,
  55. reportInvalidScopeDisables,
  56. reportNeedlessDisables,
  57. syntax,
  58. }) {
  59. /** @type {FileCache} */
  60. let fileCache;
  61. const startTime = Date.now();
  62. const isValidCode = typeof code === 'string';
  63. if ((!files && !isValidCode) || (files && (code || isValidCode))) {
  64. return Promise.reject(
  65. new Error('You must pass stylelint a `files` glob or a `code` string, though not both'),
  66. );
  67. }
  68. // The ignorer will be used to filter file paths after the glob is checked,
  69. // before any files are actually read
  70. /** @type {import('ignore').Ignore} */
  71. let ignorer;
  72. try {
  73. ignorer = getFileIgnorer({ cwd, ignorePath, ignorePattern });
  74. } catch (error) {
  75. return Promise.reject(error);
  76. }
  77. /** @type {Formatter} */
  78. let formatterFunction;
  79. try {
  80. formatterFunction = getFormatterFunction(formatter);
  81. } catch (error) {
  82. return Promise.reject(error);
  83. }
  84. const stylelint = createStylelint({
  85. config,
  86. configFile,
  87. configBasedir,
  88. cwd,
  89. ignoreDisables,
  90. ignorePath,
  91. reportNeedlessDisables,
  92. reportInvalidScopeDisables,
  93. reportDescriptionlessDisables,
  94. syntax,
  95. customSyntax,
  96. fix,
  97. quiet,
  98. });
  99. if (!files) {
  100. const absoluteCodeFilename =
  101. codeFilename !== undefined && !path.isAbsolute(codeFilename)
  102. ? path.join(cwd, codeFilename)
  103. : codeFilename;
  104. // if file is ignored, return nothing
  105. if (
  106. absoluteCodeFilename &&
  107. !filterFilePaths(ignorer, [path.relative(cwd, absoluteCodeFilename)]).length
  108. ) {
  109. return prepareReturnValue([], maxWarnings, formatterFunction, cwd);
  110. }
  111. let stylelintResult;
  112. try {
  113. const postcssResult = await stylelint._lintSource({
  114. code,
  115. codeFilename: absoluteCodeFilename,
  116. });
  117. stylelintResult = await stylelint._createStylelintResult(postcssResult, absoluteCodeFilename);
  118. } catch (error) {
  119. stylelintResult = await handleError(stylelint, error);
  120. }
  121. const postcssResult = stylelintResult._postcssResult;
  122. const returnValue = prepareReturnValue([stylelintResult], maxWarnings, formatterFunction, cwd);
  123. if (
  124. fix &&
  125. postcssResult &&
  126. !postcssResult.stylelint.ignored &&
  127. !postcssResult.stylelint.ruleDisableFix
  128. ) {
  129. returnValue.output =
  130. !postcssResult.stylelint.disableWritingFix && postcssResult.opts
  131. ? // If we're fixing, the output should be the fixed code
  132. postcssResult.root.toString(postcssResult.opts.syntax)
  133. : // If the writing of the fix is disabled, the input code is returned as-is
  134. code;
  135. }
  136. return returnValue;
  137. }
  138. let fileList = [files].flat().map((entry) => {
  139. const globCWD = (globbyOptions && globbyOptions.cwd) || cwd;
  140. const absolutePath = !path.isAbsolute(entry)
  141. ? path.join(globCWD, entry)
  142. : path.normalize(entry);
  143. if (fs.existsSync(absolutePath)) {
  144. // This path points to a file. Return an escaped path to avoid globbing
  145. return fastGlob.escapePath(normalizePath(entry));
  146. }
  147. return entry;
  148. });
  149. if (!disableDefaultIgnores) {
  150. fileList = fileList.concat(ALWAYS_IGNORED_GLOBS.map((glob) => `!${glob}`));
  151. }
  152. if (useCache) {
  153. const stylelintVersion = pkg.version;
  154. const hashOfConfig = hash(`${stylelintVersion}_${JSON.stringify(config || {})}`);
  155. fileCache = new FileCache(cacheLocation, cwd, hashOfConfig);
  156. } else {
  157. // No need to calculate hash here, we just want to delete cache file.
  158. fileCache = new FileCache(cacheLocation, cwd);
  159. // Remove cache file if cache option is disabled
  160. fileCache.destroy();
  161. }
  162. const effectiveGlobbyOptions = {
  163. cwd,
  164. ...(globbyOptions || {}),
  165. absolute: true,
  166. };
  167. const globCWD = effectiveGlobbyOptions.cwd;
  168. let filePaths = await globby(fileList, effectiveGlobbyOptions);
  169. // Record the length of filePaths before ignore operation
  170. // Prevent prompting "No files matching the pattern 'xx' were found." when .stylelintignore ignore all input files
  171. const filePathsLengthBeforeIgnore = filePaths.length;
  172. // The ignorer filter needs to check paths relative to cwd
  173. filePaths = filterFilePaths(
  174. ignorer,
  175. filePaths.map((p) => path.relative(globCWD, p)),
  176. );
  177. let stylelintResults;
  178. if (filePaths.length) {
  179. let absoluteFilePaths = filePaths.map((filePath) => {
  180. const absoluteFilepath = !path.isAbsolute(filePath)
  181. ? path.join(globCWD, filePath)
  182. : path.normalize(filePath);
  183. return absoluteFilepath;
  184. });
  185. if (useCache) {
  186. absoluteFilePaths = absoluteFilePaths.filter(fileCache.hasFileChanged.bind(fileCache));
  187. }
  188. const getStylelintResults = absoluteFilePaths.map(async (absoluteFilepath) => {
  189. debug(`Processing ${absoluteFilepath}`);
  190. try {
  191. const postcssResult = await stylelint._lintSource({
  192. filePath: absoluteFilepath,
  193. });
  194. if (postcssResult.stylelint.stylelintError && useCache) {
  195. debug(`${absoluteFilepath} contains linting errors and will not be cached.`);
  196. fileCache.removeEntry(absoluteFilepath);
  197. }
  198. /**
  199. * If we're fixing, save the file with changed code
  200. */
  201. if (
  202. postcssResult.root &&
  203. postcssResult.opts &&
  204. !postcssResult.stylelint.ignored &&
  205. fix &&
  206. !postcssResult.stylelint.disableWritingFix
  207. ) {
  208. const fixedCss = postcssResult.root.toString(postcssResult.opts.syntax);
  209. if (
  210. postcssResult.root &&
  211. postcssResult.root.source &&
  212. postcssResult.root.source.input.css !== fixedCss
  213. ) {
  214. await writeFileAtomic(absoluteFilepath, fixedCss);
  215. }
  216. }
  217. return stylelint._createStylelintResult(postcssResult, absoluteFilepath);
  218. } catch (error) {
  219. // On any error, we should not cache the lint result
  220. fileCache.removeEntry(absoluteFilepath);
  221. return handleError(stylelint, error, absoluteFilepath);
  222. }
  223. });
  224. stylelintResults = await Promise.all(getStylelintResults);
  225. } else if (allowEmptyInput) {
  226. stylelintResults = await Promise.all([]);
  227. } else if (filePathsLengthBeforeIgnore) {
  228. // All input files ignored
  229. stylelintResults = await Promise.reject(new AllFilesIgnoredError());
  230. } else {
  231. stylelintResults = await Promise.reject(new NoFilesFoundError(fileList));
  232. }
  233. if (useCache) {
  234. fileCache.reconcile();
  235. }
  236. const result = prepareReturnValue(stylelintResults, maxWarnings, formatterFunction, cwd);
  237. debug(`Linting complete in ${Date.now() - startTime}ms`);
  238. return result;
  239. }
  240. /**
  241. * @param {FormatterType | Formatter | undefined} selected
  242. * @returns {Formatter}
  243. */
  244. function getFormatterFunction(selected) {
  245. if (typeof selected === 'string') {
  246. const formatterFunction = formatters[selected];
  247. if (formatterFunction === undefined) {
  248. throw new Error(
  249. `You must use a valid formatter option: ${getFormatterOptionsText()} or a function`,
  250. );
  251. }
  252. return formatterFunction;
  253. }
  254. if (typeof selected === 'function') {
  255. return selected;
  256. }
  257. assert(formatters.json);
  258. return formatters.json;
  259. }
  260. /**
  261. * @param {import('stylelint').InternalApi} stylelint
  262. * @param {any} error
  263. * @param {string} [filePath]
  264. * @return {Promise<StylelintResult>}
  265. */
  266. function handleError(stylelint, error, filePath = undefined) {
  267. if (error.name === 'CssSyntaxError') {
  268. return createStylelintResult(stylelint, undefined, filePath, error);
  269. }
  270. throw error;
  271. }
  272. module.exports = /** @type {typeof import('stylelint').lint} */ (standalone);