standalone.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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 pkg = require('../package.json');
  19. const prepareReturnValue = require('./prepareReturnValue');
  20. const ALWAYS_IGNORED_GLOBS = ['**/node_modules/**'];
  21. const writeFileAtomic = require('write-file-atomic');
  22. /** @typedef {import('stylelint').LinterOptions} LinterOptions */
  23. /** @typedef {import('stylelint').LinterResult} LinterResult */
  24. /** @typedef {import('stylelint').LintResult} StylelintResult */
  25. /** @typedef {import('stylelint').Formatter} Formatter */
  26. /** @typedef {import('stylelint').FormatterType} FormatterType */
  27. /**
  28. *
  29. * @param {LinterOptions} options
  30. * @returns {Promise<LinterResult>}
  31. */
  32. async function standalone({
  33. allowEmptyInput = false,
  34. cache: useCache = false,
  35. cacheLocation,
  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. /** @type {FileCache} */
  59. let fileCache;
  60. const startTime = Date.now();
  61. const isValidCode = typeof code === 'string';
  62. if ((!files && !isValidCode) || (files && (code || isValidCode))) {
  63. return Promise.reject(
  64. new Error('You must pass stylelint a `files` glob or a `code` string, though not both'),
  65. );
  66. }
  67. // The ignorer will be used to filter file paths after the glob is checked,
  68. // before any files are actually read
  69. /** @type {import('ignore').Ignore} */
  70. let ignorer;
  71. try {
  72. ignorer = getFileIgnorer({ cwd, ignorePath, ignorePattern });
  73. } catch (error) {
  74. return Promise.reject(error);
  75. }
  76. /** @type {Formatter} */
  77. let formatterFunction;
  78. try {
  79. formatterFunction = getFormatterFunction(formatter);
  80. } catch (error) {
  81. return Promise.reject(error);
  82. }
  83. const stylelint = createStylelint({
  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 stylelint._lintSource({
  113. code,
  114. codeFilename: absoluteCodeFilename,
  115. });
  116. stylelintResult = await stylelint._createStylelintResult(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. const stylelintVersion = pkg.version;
  153. const hashOfConfig = hash(`${stylelintVersion}_${JSON.stringify(config || {})}`);
  154. fileCache = new FileCache(cacheLocation, cwd, hashOfConfig);
  155. } else {
  156. // No need to calculate hash here, we just want to delete cache file.
  157. fileCache = new FileCache(cacheLocation, cwd);
  158. // Remove cache file if cache option is disabled
  159. fileCache.destroy();
  160. }
  161. const effectiveGlobbyOptions = {
  162. cwd,
  163. ...(globbyOptions || {}),
  164. absolute: true,
  165. };
  166. const globCWD = effectiveGlobbyOptions.cwd;
  167. let filePaths = await globby(fileList, effectiveGlobbyOptions);
  168. // Record the length of filePaths before ignore operation
  169. // Prevent prompting "No files matching the pattern 'xx' were found." when .stylelintignore ignore all input files
  170. const filePathsLengthBeforeIgnore = filePaths.length;
  171. // The ignorer filter needs to check paths relative to cwd
  172. filePaths = filterFilePaths(
  173. ignorer,
  174. filePaths.map((p) => path.relative(globCWD, p)),
  175. );
  176. let stylelintResults;
  177. if (filePaths.length) {
  178. let absoluteFilePaths = filePaths.map((filePath) => {
  179. const absoluteFilepath = !path.isAbsolute(filePath)
  180. ? path.join(globCWD, filePath)
  181. : path.normalize(filePath);
  182. return absoluteFilepath;
  183. });
  184. if (useCache) {
  185. absoluteFilePaths = absoluteFilePaths.filter(fileCache.hasFileChanged.bind(fileCache));
  186. }
  187. const getStylelintResults = absoluteFilePaths.map(async (absoluteFilepath) => {
  188. debug(`Processing ${absoluteFilepath}`);
  189. try {
  190. const postcssResult = await stylelint._lintSource({
  191. filePath: absoluteFilepath,
  192. });
  193. if (postcssResult.stylelint.stylelintError && useCache) {
  194. debug(`${absoluteFilepath} contains linting errors and will not be cached.`);
  195. fileCache.removeEntry(absoluteFilepath);
  196. }
  197. /**
  198. * If we're fixing, save the file with changed code
  199. */
  200. if (
  201. postcssResult.root &&
  202. postcssResult.opts &&
  203. !postcssResult.stylelint.ignored &&
  204. fix &&
  205. !postcssResult.stylelint.disableWritingFix
  206. ) {
  207. const fixedCss = postcssResult.root.toString(postcssResult.opts.syntax);
  208. if (
  209. postcssResult.root &&
  210. postcssResult.root.source &&
  211. postcssResult.root.source.input.css !== fixedCss
  212. ) {
  213. await writeFileAtomic(absoluteFilepath, fixedCss);
  214. }
  215. }
  216. return stylelint._createStylelintResult(postcssResult, absoluteFilepath);
  217. } catch (error) {
  218. // On any error, we should not cache the lint result
  219. fileCache.removeEntry(absoluteFilepath);
  220. return handleError(stylelint, error, absoluteFilepath);
  221. }
  222. });
  223. stylelintResults = await Promise.all(getStylelintResults);
  224. } else if (allowEmptyInput) {
  225. stylelintResults = await Promise.all([]);
  226. } else if (filePathsLengthBeforeIgnore) {
  227. // All input files ignored
  228. stylelintResults = await Promise.reject(new AllFilesIgnoredError());
  229. } else {
  230. stylelintResults = await Promise.reject(new NoFilesFoundError(fileList));
  231. }
  232. if (useCache) {
  233. fileCache.reconcile();
  234. }
  235. const result = prepareReturnValue(stylelintResults, maxWarnings, formatterFunction, cwd);
  236. debug(`Linting complete in ${Date.now() - startTime}ms`);
  237. return result;
  238. }
  239. /**
  240. * @param {FormatterType | Formatter | undefined} selected
  241. * @returns {Formatter}
  242. */
  243. function getFormatterFunction(selected) {
  244. /** @type {Formatter} */
  245. let formatterFunction;
  246. if (typeof selected === 'string') {
  247. formatterFunction = formatters[selected];
  248. if (formatterFunction === undefined) {
  249. throw new Error(
  250. `You must use a valid formatter option: ${getFormatterOptionsText()} or a function`,
  251. );
  252. }
  253. } else if (typeof selected === 'function') {
  254. formatterFunction = selected;
  255. } else {
  256. formatterFunction = formatters.json;
  257. }
  258. return formatterFunction;
  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);