standalone.js 8.4 KB

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