cli.mjs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  1. import { isAbsolute, join, resolve } from 'node:path';
  2. import { EOL } from 'node:os';
  3. import { existsSync } from 'node:fs';
  4. import process from 'node:process';
  5. import picocolors from 'picocolors';
  6. const { dim, red } = picocolors;
  7. import meow from 'meow';
  8. import { isBoolean, isNumber, isObject, isPlainObject, isString } from './utils/validateTypes.mjs';
  9. import checkInvalidCLIOptions from './utils/checkInvalidCLIOptions.mjs';
  10. import dynamicImport from './utils/dynamicImport.mjs';
  11. import printConfig from './printConfig.mjs';
  12. import resolveSilent from './utils/resolveSilent.mjs';
  13. import standalone from './standalone.mjs';
  14. import writeOutputFile from './writeOutputFile.mjs';
  15. import {
  16. DEFAULT_CACHE_LOCATION,
  17. DEFAULT_FIX_MODE,
  18. DEFAULT_FORMATTER,
  19. DEFAULT_IGNORE_FILENAME,
  20. DEFAULT_SUPPRESSION_FILENAME,
  21. EXIT_CODE_FATAL_ERROR,
  22. EXIT_CODE_INVALID_USAGE,
  23. EXIT_CODE_LINT_PROBLEM,
  24. EXIT_CODE_SUCCESS,
  25. } from './constants.mjs';
  26. import normalizeFixMode from './utils/normalizeFixMode.mjs';
  27. const helpText = `
  28. Usage: stylelint [input] [options]
  29. Input: Files(s), glob(s), or nothing to use stdin.
  30. If an input argument is wrapped in quotation marks, it will be passed to
  31. globby for cross-platform glob support. "node_modules" are always ignored.
  32. You can also pass no input and use stdin, instead.
  33. Options:
  34. --config, -c <path_or_module>
  35. A path to a specific configuration file (JSON, YAML, CommonJS, or ES module),
  36. or a module name in "node_modules" that points to one. If no argument is
  37. provided, Stylelint will search for configuration files in the following
  38. places, in this order:
  39. - a "stylelint" property in "package.json"
  40. - a ".stylelintrc" file
  41. - a ".stylelintrc.{cjs,mjs,js,json,yaml,yml}" file
  42. - a "stylelint.config.{cjs,mjs,js}" file
  43. The search will begin in the working directory and move up the directory
  44. tree until a configuration file is found.
  45. --config-basedir <path>
  46. An absolute path to the directory that relative paths defining "extends",
  47. "plugins", and "customSyntax" are *relative to*. Only necessary if these
  48. values are relative paths.
  49. --print-config
  50. Print the configuration for the given input file path. Globs are unsupported.
  51. --ignore-path, -i <path>
  52. A path to a file containing patterns that describe files to ignore. The
  53. path can be absolute or relative to "process.cwd()". You can repeat the
  54. option to provide multiple paths. By default, Stylelint looks for
  55. "${DEFAULT_IGNORE_FILENAME}" in "process.cwd()". Multiple can be set.
  56. --ignore-pattern, --ip <pattern>
  57. A pattern of files to ignore (in addition to those in "${DEFAULT_IGNORE_FILENAME}").
  58. Multiple can be set.
  59. --fix [<mode>]
  60. Automatically fix problems of certain rules. The modes are as follows:
  61. lax attempting to fix as much as possible even with syntax errors (default)
  62. strict only fixing when there are no syntax errors
  63. --compute-edit-info, --cei
  64. Compute edit information for fixable problems.
  65. --custom-syntax <name_or_path>
  66. A module name or path to a JS file exporting a PostCSS-compatible syntax.
  67. --stdin
  68. Accept stdin input even if it is empty.
  69. --stdin-filename <name>
  70. A filename to assign stdin input.
  71. --ignore-disables, --id
  72. Ignore "stylelint-disable" comments.
  73. --disable-default-ignores, --di
  74. Allow linting of "node_modules".
  75. --[no-]cache
  76. Store the info about processed files in order to only operate on the
  77. changed ones the next time you run Stylelint. By default, the cache is
  78. stored in "${DEFAULT_CACHE_LOCATION}". To adjust this, use "--cache-location".
  79. Cache is disabled by default.
  80. --cache-location <path>
  81. A path to a file or directory to be used for the cache location. If a
  82. directory is specified, a cache file will be created inside the specified
  83. folder, with a name derived from a hash of the current working directory.
  84. If the directory for the cache does not exist, make sure you add a trailing "/"
  85. on *nix systems or "\\" on Windows. Otherwise the path will be assumed to
  86. be a file.
  87. --cache-strategy <strategy>
  88. A strategy for the cache to use for detecting changed files. Either one of:
  89. metadata by metadata of a file (default)
  90. content by content of a file
  91. The "content" strategy can be useful in cases where the modification time
  92. of your files changes even if their contents have not. For example, this can
  93. happen during git operations like "git clone" because git does not track file
  94. modification time.
  95. --formatter, -f <formatter>
  96. An output formatter. The variants are as follows:
  97. string human-readable strings (default)
  98. compact similar to ESLint's compact formatter
  99. github workflow commands for GitHub Actions (DEPRECATED)
  100. json JSON format
  101. tap TAP format
  102. unix C compiler-like format
  103. verbose extend "string" to include a file list and a tally
  104. --custom-formatter <path_or_module>
  105. A path to a JS file or module name exporting a custom formatting function.
  106. --quiet, -q
  107. Only register problems for rules with an "error"-level severity (ignore
  108. "warning"-level).
  109. --quiet-deprecation-warnings
  110. Ignore deprecations warnings.
  111. --[no-]color
  112. Force enabling/disabling of color.
  113. --[no-]validate
  114. Force enable/disable the validation of the rules' options.
  115. --report-needless-disables, --rd
  116. Also report errors for "stylelint-disable" comments that are not blocking
  117. a lint warning. The process will exit with code ${EXIT_CODE_LINT_PROBLEM} if needless disables are found.
  118. --report-invalid-scope-disables, --risd
  119. Report "stylelint-disable" comments that used for rules that don't exist
  120. within the configuration object. The process will exit with code ${EXIT_CODE_LINT_PROBLEM} if invalid
  121. scope disables are found.
  122. --report-descriptionless-disables, --rdd
  123. Report "stylelint-disable" comments without a description. The process will
  124. exit with code ${EXIT_CODE_LINT_PROBLEM} if descriptionless disables are found.
  125. --max-warnings, --mw <number>
  126. The number of warnings above which the process will exit with code ${EXIT_CODE_LINT_PROBLEM}.
  127. Useful when setting "defaultSeverity" to "warning" and expecting the process
  128. to fail on warnings (e.g. CI build).
  129. --output-file, -o <path>
  130. A file path to write a report.
  131. --allow-empty-input, --aei
  132. When a glob pattern matches no files, the process will exit without throwing an error.
  133. --suppress [<rule>]
  134. Suppress problems and record them in a file. If no rule is specified,
  135. all problems are suppressed. Otherwise, only problems with the given
  136. rules are suppressed, e.g., "--suppress rule1 --suppress rule2".
  137. See also "--suppress-location".
  138. --suppress-location <path>
  139. A path to a file or directory to be used for the suppressions file location. If a
  140. directory is specified, a suppressions file will be created inside the specified
  141. folder, with the name "${DEFAULT_SUPPRESSION_FILENAME}".
  142. --globby-options, --go <json>
  143. Options in JSON format passed to globby.
  144. --version, -v
  145. Show the version.
  146. --help, -h
  147. Show the help.
  148. `;
  149. const flags = {
  150. allowEmptyInput: {
  151. aliases: ['aei'],
  152. type: 'boolean',
  153. },
  154. cache: {
  155. type: 'boolean',
  156. },
  157. cacheLocation: {
  158. type: 'string',
  159. },
  160. cacheStrategy: {
  161. type: 'string',
  162. },
  163. color: {
  164. type: 'boolean',
  165. },
  166. computeEditInfo: {
  167. shortFlag: 'cei',
  168. type: 'boolean',
  169. default: false,
  170. },
  171. config: {
  172. shortFlag: 'c',
  173. type: 'string',
  174. },
  175. configBasedir: {
  176. type: 'string',
  177. },
  178. customFormatter: {
  179. type: 'string',
  180. },
  181. customSyntax: {
  182. type: 'string',
  183. },
  184. disableDefaultIgnores: {
  185. aliases: ['di'],
  186. type: 'boolean',
  187. },
  188. fix: {
  189. type: 'string',
  190. },
  191. formatter: {
  192. shortFlag: 'f',
  193. type: 'string',
  194. },
  195. globbyOptions: {
  196. aliases: ['go'],
  197. type: 'string',
  198. },
  199. help: {
  200. shortFlag: 'h',
  201. type: 'boolean',
  202. },
  203. ignoreDisables: {
  204. aliases: ['id'],
  205. type: 'boolean',
  206. },
  207. ignorePath: {
  208. shortFlag: 'i',
  209. type: 'string',
  210. isMultiple: true,
  211. },
  212. ignorePattern: {
  213. aliases: ['ip'],
  214. type: 'string',
  215. isMultiple: true,
  216. },
  217. maxWarnings: {
  218. aliases: ['mw'],
  219. type: 'number',
  220. },
  221. outputFile: {
  222. shortFlag: 'o',
  223. type: 'string',
  224. },
  225. printConfig: {
  226. type: 'boolean',
  227. },
  228. quiet: {
  229. shortFlag: 'q',
  230. type: 'boolean',
  231. },
  232. quietDeprecationWarnings: {
  233. type: 'boolean',
  234. },
  235. reportDescriptionlessDisables: {
  236. aliases: ['rdd'],
  237. type: 'boolean',
  238. },
  239. reportInvalidScopeDisables: {
  240. aliases: ['risd'],
  241. type: 'boolean',
  242. },
  243. reportNeedlessDisables: {
  244. aliases: ['rd'],
  245. type: 'boolean',
  246. },
  247. reportUnscopedDisables: {
  248. aliases: ['rud'],
  249. type: 'boolean',
  250. },
  251. stdin: {
  252. type: 'boolean',
  253. },
  254. stdinFilename: {
  255. type: 'string',
  256. },
  257. suppress: {
  258. type: 'string',
  259. isMultiple: true,
  260. },
  261. suppressLocation: {
  262. type: 'string',
  263. },
  264. validate: {
  265. type: 'boolean',
  266. default: true,
  267. },
  268. version: {
  269. shortFlag: 'v',
  270. type: 'boolean',
  271. },
  272. };
  273. /**
  274. * @param {string[]} argv
  275. * @returns {Promise<void>}
  276. */
  277. export default async function main(argv) {
  278. const cli = buildCLI(argv);
  279. const invalidOptionsMessage = checkInvalidCLIOptions(flags, cli.flags);
  280. if (invalidOptionsMessage) {
  281. process.stderr.write(invalidOptionsMessage);
  282. process.exitCode = EXIT_CODE_INVALID_USAGE;
  283. return;
  284. }
  285. const {
  286. // Sort alphabetically
  287. allowEmptyInput,
  288. cache,
  289. cacheLocation,
  290. cacheStrategy,
  291. computeEditInfo,
  292. config: configFile,
  293. configBasedir,
  294. customFormatter,
  295. customSyntax,
  296. disableDefaultIgnores,
  297. formatter: formatterInput,
  298. fix,
  299. globbyOptions,
  300. help,
  301. ignoreDisables,
  302. ignorePath,
  303. ignorePattern,
  304. maxWarnings,
  305. outputFile,
  306. printConfig: printConfigFlag,
  307. quiet,
  308. quietDeprecationWarnings,
  309. reportDescriptionlessDisables,
  310. reportInvalidScopeDisables,
  311. reportNeedlessDisables,
  312. reportUnscopedDisables,
  313. stdin,
  314. stdinFilename,
  315. suppress,
  316. suppressLocation,
  317. validate,
  318. version,
  319. } = cli.flags;
  320. const showHelp = () => cli.showHelp(EXIT_CODE_SUCCESS);
  321. if (help) {
  322. showHelp();
  323. return;
  324. }
  325. if (version) {
  326. cli.showVersion();
  327. return;
  328. }
  329. let formatter = undefined;
  330. if (isString(customFormatter)) {
  331. formatter = await importCustomFormatter(customFormatter);
  332. } else if (isString(formatterInput)) {
  333. formatter = /** @type {import('stylelint').FormatterType} */ (formatterInput);
  334. }
  335. /** @type {import('stylelint').LinterOptions} */
  336. const options = {
  337. formatter,
  338. _defaultFormatter: DEFAULT_FORMATTER,
  339. };
  340. if (isBoolean(quiet)) {
  341. options.quiet = quiet;
  342. }
  343. if (isBoolean(quietDeprecationWarnings)) {
  344. options.quietDeprecationWarnings = quietDeprecationWarnings;
  345. }
  346. if (isString(customSyntax)) {
  347. options.customSyntax = customSyntax;
  348. }
  349. const cwd = process.cwd();
  350. if (isString(configFile)) {
  351. // Should check these possibilities:
  352. // a. name of a node_module
  353. // b. absolute path
  354. // c. relative path relative to `process.cwd()`.
  355. // If none of the above work, we'll try a relative path starting
  356. // in `process.cwd()`.
  357. options.configFile = resolveSilent(cwd, configFile) || join(cwd, configFile);
  358. }
  359. if (isString(configBasedir)) {
  360. options.configBasedir = isAbsolute(configBasedir) ? configBasedir : resolve(cwd, configBasedir);
  361. }
  362. if (isString(globbyOptions)) {
  363. try {
  364. options.globbyOptions = await parseGlobbyOptions(globbyOptions);
  365. } catch (error) {
  366. if (typeof error === 'string') {
  367. process.stderr.write(`${error}${EOL}`);
  368. process.exitCode = EXIT_CODE_INVALID_USAGE;
  369. return;
  370. }
  371. throw error;
  372. }
  373. }
  374. if (isString(stdinFilename)) {
  375. options.codeFilename = stdinFilename;
  376. }
  377. if (Array.isArray(ignorePath)) {
  378. options.ignorePath = ignorePath;
  379. }
  380. if (Array.isArray(ignorePattern)) {
  381. options.ignorePattern = ignorePattern;
  382. }
  383. if (isBoolean(ignoreDisables)) {
  384. options.ignoreDisables = ignoreDisables;
  385. }
  386. if (isBoolean(disableDefaultIgnores)) {
  387. options.disableDefaultIgnores = disableDefaultIgnores;
  388. }
  389. if (isBoolean(cache)) {
  390. options.cache = cache;
  391. }
  392. if (isString(cacheLocation)) {
  393. options.cacheLocation = cacheLocation;
  394. }
  395. if (isString(cacheStrategy)) {
  396. options.cacheStrategy = cacheStrategy;
  397. }
  398. if (isString(fix)) {
  399. options.fix = normalizeFixMode(fix);
  400. // If the fix argument is unknown, consider it as an input path.
  401. // TODO: `false` is for backward compatibility. We can remove it in the next major (17.0.0).
  402. if (options.fix === undefined && fix !== 'false') {
  403. options.fix = DEFAULT_FIX_MODE;
  404. cli.input.push(fix);
  405. }
  406. }
  407. if (isBoolean(validate)) {
  408. options.validate = validate;
  409. }
  410. if (isBoolean(reportNeedlessDisables)) {
  411. options.reportNeedlessDisables = reportNeedlessDisables;
  412. }
  413. if (isBoolean(reportInvalidScopeDisables)) {
  414. options.reportInvalidScopeDisables = reportInvalidScopeDisables;
  415. }
  416. if (isBoolean(reportDescriptionlessDisables)) {
  417. options.reportDescriptionlessDisables = reportDescriptionlessDisables;
  418. }
  419. if (isBoolean(reportUnscopedDisables)) {
  420. options.reportUnscopedDisables = reportUnscopedDisables;
  421. }
  422. if (isNumber(maxWarnings)) {
  423. options.maxWarnings = maxWarnings;
  424. }
  425. if (isBoolean(allowEmptyInput)) {
  426. options.allowEmptyInput = allowEmptyInput;
  427. }
  428. if (isBoolean(computeEditInfo)) {
  429. options.computeEditInfo = computeEditInfo;
  430. }
  431. // Handle suppress logic - detect both --suppress (all) and --suppress=rule cases
  432. const hasPlainSuppress = argv.includes('--suppress');
  433. const hasRuleSuppress = Array.isArray(suppress) && suppress.length > 0;
  434. if (hasPlainSuppress) {
  435. options.suppressAll = true;
  436. }
  437. if (hasRuleSuppress) {
  438. options.suppressRule = suppress;
  439. }
  440. if (isString(suppressLocation)) {
  441. options.suppressLocation = suppressLocation;
  442. }
  443. if (options.suppressAll && options.suppressRule) {
  444. process.stderr.write(
  445. `${red('Error: The --suppress and --suppress=<rule> options cannot be used together.')}${EOL}`,
  446. );
  447. process.exitCode = EXIT_CODE_INVALID_USAGE;
  448. return;
  449. }
  450. // Add input/code into options
  451. if (cli.input.length > 0) {
  452. options.files = cli.input;
  453. } else {
  454. options.code = await getStdin();
  455. }
  456. const hasStdin = stdin || isString(options.code);
  457. if (hasStdin && (options.suppressAll || options.suppressRule)) {
  458. process.stderr.write(
  459. `${red(
  460. 'Error: The --suppress and --suppress=<rule> options cannot be used with piped-in code.',
  461. )}${EOL}`,
  462. );
  463. process.exitCode = EXIT_CODE_INVALID_USAGE;
  464. return;
  465. }
  466. if (printConfigFlag) {
  467. await printConfig(options)
  468. .then((config) => {
  469. process.stdout.write(JSON.stringify(config, null, 2));
  470. })
  471. .catch(handleError);
  472. return;
  473. }
  474. if (!options.files && !isString(options.code) && !stdin) {
  475. showHelp();
  476. return;
  477. }
  478. return standalone(options)
  479. .then(({ report, code, errored, maxWarningsExceeded }) => {
  480. if (!report && !code) {
  481. return;
  482. }
  483. if (code) {
  484. process.stdout.write(code);
  485. }
  486. if (report) {
  487. process.stderr.write(report);
  488. }
  489. if (isString(outputFile)) {
  490. writeOutputFile(report, outputFile).catch(handleError);
  491. }
  492. if (errored) {
  493. process.exitCode = EXIT_CODE_LINT_PROBLEM;
  494. } else if (isNumber(maxWarnings) && maxWarningsExceeded) {
  495. const foundWarnings = maxWarningsExceeded.foundWarnings;
  496. process.stderr.write(
  497. `${EOL}${red(`Max warnings exceeded: `)}${foundWarnings} found. ${dim(
  498. `${maxWarnings} allowed${EOL}${EOL}`,
  499. )}`,
  500. );
  501. process.exitCode = EXIT_CODE_LINT_PROBLEM;
  502. }
  503. })
  504. .catch(handleError);
  505. }
  506. /**
  507. * @param {unknown} err
  508. * @returns {void}
  509. */
  510. function handleError(err) {
  511. if (!isObject(err)) {
  512. throw err;
  513. }
  514. if ('stack' in err && isString(err.stack)) {
  515. process.stderr.write(err.stack + EOL);
  516. }
  517. const exitCode = 'code' in err && isNumber(err.code) ? err.code : EXIT_CODE_FATAL_ERROR;
  518. process.exitCode = exitCode;
  519. }
  520. /**
  521. * @param {string} value
  522. * @returns {Promise<Record<string, unknown>>}
  523. */
  524. function parseGlobbyOptions(value) {
  525. const errorMessage = () =>
  526. `Invalid option ${red('"--globby-options"')}.` +
  527. ` The value ${red(`"${value}"`)} is not valid JSON object.`;
  528. let options;
  529. try {
  530. options = JSON.parse(value);
  531. } catch {
  532. return Promise.reject(errorMessage());
  533. }
  534. if (isPlainObject(options)) {
  535. return Promise.resolve(options);
  536. }
  537. return Promise.reject(errorMessage());
  538. }
  539. /**
  540. * @returns {Promise<string | undefined>}
  541. */
  542. async function getStdin() {
  543. const { stdin } = process;
  544. if (stdin.isTTY) {
  545. return undefined;
  546. }
  547. const chunks = [];
  548. for await (const chunk of stdin) {
  549. chunks.push(chunk);
  550. }
  551. return Buffer.concat(chunks).toString();
  552. }
  553. /**
  554. * @param {string} fileOrModulePath
  555. * @returns {Promise<import('stylelint').Formatter>}
  556. */
  557. function importCustomFormatter(fileOrModulePath) {
  558. let modulePath = fileOrModulePath;
  559. if (existsSync(modulePath)) {
  560. modulePath = resolve(modulePath); // to absolute path
  561. }
  562. return dynamicImport(modulePath).then((m) => m.default);
  563. }
  564. /**
  565. * @param {string[]} argv
  566. */
  567. export function buildCLI(argv) {
  568. return meow(helpText, {
  569. autoHelp: false,
  570. autoVersion: false,
  571. argv,
  572. // NOTE: `meow()` infers flag types when passing a flag object with inline.
  573. // However, `checkInvalidCLIOptions()` also needs this flag object.
  574. // So, unfortunately, the return value type inference by `meow()` is unavailable here.
  575. //
  576. // @ts-expect-error -- TS2322: Type '{ allowEmptyInput: {...} }' is not assignable to type 'AnyFlags'.
  577. flags,
  578. // NOTE: We must enable `allowUnknownFlags` because meow exits with `2` if `allowUnknownFlags` is disabled.
  579. // Instead, we use our different exit code with `checkInvalidCLIOptions()`.
  580. // See also https://github.com/sindresorhus/meow/blob/v12.0.1/source/validate.js#L75
  581. allowUnknownFlags: true,
  582. // NOTE: If CLI flags are unspecified (e.g., `--cache` nor `--no-cache`), we want to fall back to config properties (e.g., `cache`).
  583. booleanDefault: undefined,
  584. importMeta: import.meta,
  585. });
  586. }