cli.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. 'use strict';
  2. const { EOL } = require('os');
  3. const meow = require('meow');
  4. const path = require('path');
  5. const { red, dim } = require('picocolors');
  6. const { isPlainObject } = require('./utils/validateTypes');
  7. const checkInvalidCLIOptions = require('./utils/checkInvalidCLIOptions');
  8. const getFormatterOptionsText = require('./utils/getFormatterOptionsText');
  9. const getStdin = require('./utils/getStdin');
  10. const printConfig = require('./printConfig');
  11. const resolveFrom = require('resolve-from');
  12. const standalone = require('./standalone');
  13. const writeOutputFile = require('./writeOutputFile');
  14. const resolveCustomFormatter = require('./resolveCustomFormatter');
  15. const EXIT_CODE_ERROR = 2;
  16. /**
  17. * @typedef {object} CLIFlags
  18. * @property {boolean} [cache]
  19. * @property {string} [cacheLocation]
  20. * @property {string} [cacheStrategy]
  21. * @property {string | false} config
  22. * @property {string} [configBasedir]
  23. * @property {string} [customSyntax]
  24. * @property {string} [printConfig]
  25. * @property {string} [color]
  26. * @property {string} [customFormatter]
  27. * @property {boolean} [disableDefaultIgnores]
  28. * @property {boolean} [fix]
  29. * @property {string} [formatter="string"]
  30. * @property {string} [help]
  31. * @property {boolean} [ignoreDisables]
  32. * @property {string[]} [ignorePath]
  33. * @property {string[]} [ignorePattern]
  34. * @property {string} [noColor]
  35. * @property {string} [outputFile]
  36. * @property {boolean} [stdin]
  37. * @property {string} [stdinFilename]
  38. * @property {boolean} [reportNeedlessDisables]
  39. * @property {boolean} [reportInvalidScopeDisables]
  40. * @property {boolean} [reportDescriptionlessDisables]
  41. * @property {number} [maxWarnings]
  42. * @property {boolean} quiet
  43. * @property {boolean} quietDeprecationWarnings
  44. * @property {string} [version]
  45. * @property {boolean} [allowEmptyInput]
  46. * @property {string} [globbyOptions]
  47. */
  48. /**
  49. * @typedef {object} CLIOptions
  50. * @property {any} input
  51. * @property {any} help
  52. * @property {any} pkg
  53. * @property {Function} showHelp
  54. * @property {Function} showVersion
  55. * @property {CLIFlags} flags
  56. */
  57. /**
  58. * @typedef {object} OptionBaseType
  59. * @property {any} formatter
  60. * @property {boolean} [cache]
  61. * @property {string} [configFile]
  62. * @property {string} [cacheLocation]
  63. * @property {string} [cacheStrategy]
  64. * @property {string} [customSyntax]
  65. * @property {string} [codeFilename]
  66. * @property {string} [configBasedir]
  67. * @property {boolean} [quiet]
  68. * @property {boolean} [quietDeprecationWarnings]
  69. * @property {any} [printConfig]
  70. * @property {boolean} [fix]
  71. * @property {Record<string, unknown>} [globbyOptions]
  72. * @property {boolean} [ignoreDisables]
  73. * @property {any} [ignorePath]
  74. * @property {string} [outputFile]
  75. * @property {boolean} [reportNeedlessDisables]
  76. * @property {boolean} [reportInvalidScopeDisables]
  77. * @property {boolean} [reportDescriptionlessDisables]
  78. * @property {boolean} [disableDefaultIgnores]
  79. * @property {number} [maxWarnings]
  80. * @property {string[]} [ignorePattern]
  81. * @property {boolean} [allowEmptyInput]
  82. * @property {string} [files]
  83. * @property {string} [code]
  84. */
  85. const meowOptions = {
  86. autoHelp: false,
  87. autoVersion: false,
  88. help: `
  89. Usage: stylelint [input] [options]
  90. Input: Files(s), glob(s), or nothing to use stdin.
  91. If an input argument is wrapped in quotation marks, it will be passed to
  92. globby for cross-platform glob support. node_modules are always ignored.
  93. You can also pass no input and use stdin, instead.
  94. Options:
  95. --config, -c
  96. Path to a specific configuration file (JSON, YAML, or CommonJS), or the
  97. name of a module in node_modules that points to one. If no --config
  98. argument is provided, stylelint will search for configuration files in
  99. the following places, in this order:
  100. - a stylelint property in package.json
  101. - a .stylelintrc file (with or without filename extension:
  102. .json, .yaml, .yml, and .js are available)
  103. - a stylelint.config.js file exporting a JS object
  104. The search will begin in the working directory and move up the directory
  105. tree until a configuration file is found.
  106. --config-basedir
  107. An absolute path to the directory that relative paths defining "extends",
  108. "plugins", and "customSyntax" are *relative to*. Only necessary if these
  109. values are relative paths.
  110. --print-config
  111. Print the configuration for the given path.
  112. --ignore-path, -i
  113. Path to a file containing patterns that describe files to ignore. The
  114. path can be absolute or relative to process.cwd(). You can repeat the
  115. option to provide multiple paths. By default, Stylelint looks for
  116. .stylelintignore in process.cwd().
  117. --ignore-pattern, --ip
  118. Pattern of files to ignore (in addition to those in .stylelintignore)
  119. --fix
  120. Automatically fix problems of certain rules.
  121. --custom-syntax
  122. Module name or path to a JS file exporting a PostCSS-compatible syntax.
  123. --stdin
  124. Accept stdin input even if it is empty.
  125. --stdin-filename
  126. A filename to assign stdin input.
  127. --ignore-disables, --id
  128. Ignore stylelint-disable comments.
  129. --disable-default-ignores, --di
  130. Allow linting of node_modules.
  131. --cache [default: false]
  132. Store the info about processed files in order to only operate on the
  133. changed ones the next time you run stylelint. By default, the cache
  134. is stored in "./.stylelintcache". To adjust this, use --cache-location.
  135. --cache-location [default: '.stylelintcache']
  136. Path to a file or directory to be used for the cache location.
  137. Default is "./.stylelintcache". If a directory is specified, a cache
  138. file will be created inside the specified folder, with a name derived
  139. from a hash of the current working directory.
  140. If the directory for the cache does not exist, make sure you add a trailing "/"
  141. on *nix systems or "\\" on Windows. Otherwise the path will be assumed to be a file.
  142. --cache-strategy [default: "metadata"]
  143. Strategy for the cache to use for detecting changed files. Can be either
  144. "metadata" or "content".
  145. The "content" strategy can be useful in cases where the modification time of
  146. your files changes even if their contents have not. For example, this can happen
  147. during git operations like "git clone" because git does not track file modification
  148. time.
  149. --formatter, -f [default: "string"]
  150. The output formatter: ${getFormatterOptionsText({ useOr: true })}.
  151. --custom-formatter
  152. Path to a JS file exporting a custom formatting function.
  153. The file can either be a filesystem path, a module name, or a file to load from a dependency.
  154. --quiet, -q
  155. Only register problems for rules with an "error"-level severity (ignore
  156. "warning"-level).
  157. --quiet-deprecation-warnings
  158. Ignore deprecations warnings.
  159. --color
  160. --no-color
  161. Force enabling/disabling of color.
  162. --report-needless-disables, --rd
  163. Also report errors for stylelint-disable comments that are not blocking a lint warning.
  164. The process will exit with code ${EXIT_CODE_ERROR} if needless disables are found.
  165. --report-invalid-scope-disables, --risd
  166. Report stylelint-disable comments that used for rules that don't exist within the configuration object.
  167. The process will exit with code ${EXIT_CODE_ERROR} if invalid scope disables are found.
  168. --report-descriptionless-disables, --rdd
  169. Report stylelint-disable comments without a description.
  170. The process will exit with code ${EXIT_CODE_ERROR} if descriptionless disables are found.
  171. --max-warnings, --mw
  172. Number of warnings above which the process will exit with code ${EXIT_CODE_ERROR}.
  173. Useful when setting "defaultSeverity" to "warning" and expecting the
  174. process to fail on warnings (e.g. CI build).
  175. --output-file, -o
  176. Path of file to write report.
  177. --version, -v
  178. Show the currently installed version of stylelint.
  179. --allow-empty-input, --aei
  180. When glob pattern matches no files, the process will exit without throwing an error.
  181. --globby-options, --go
  182. Options in JSON format passed to globby.
  183. `,
  184. flags: {
  185. allowEmptyInput: {
  186. alias: 'aei',
  187. type: 'boolean',
  188. },
  189. cache: {
  190. type: 'boolean',
  191. },
  192. cacheLocation: {
  193. type: 'string',
  194. },
  195. cacheStrategy: {
  196. type: 'string',
  197. },
  198. color: {
  199. type: 'boolean',
  200. },
  201. config: {
  202. alias: 'c',
  203. type: 'string',
  204. },
  205. configBasedir: {
  206. type: 'string',
  207. },
  208. customFormatter: {
  209. type: 'string',
  210. },
  211. customSyntax: {
  212. type: 'string',
  213. },
  214. disableDefaultIgnores: {
  215. alias: 'di',
  216. type: 'boolean',
  217. },
  218. fix: {
  219. type: 'boolean',
  220. },
  221. formatter: {
  222. alias: 'f',
  223. default: 'string',
  224. type: 'string',
  225. },
  226. help: {
  227. alias: 'h',
  228. type: 'boolean',
  229. },
  230. ignoreDisables: {
  231. alias: 'id',
  232. type: 'boolean',
  233. },
  234. ignorePath: {
  235. alias: 'i',
  236. type: 'string',
  237. isMultiple: true,
  238. },
  239. ignorePattern: {
  240. alias: 'ip',
  241. type: 'string',
  242. isMultiple: true,
  243. },
  244. maxWarnings: {
  245. alias: 'mw',
  246. type: 'number',
  247. },
  248. outputFile: {
  249. alias: 'o',
  250. type: 'string',
  251. },
  252. printConfig: {
  253. type: 'boolean',
  254. },
  255. quiet: {
  256. alias: 'q',
  257. type: 'boolean',
  258. },
  259. quietDeprecationWarnings: {
  260. type: 'boolean',
  261. },
  262. reportDescriptionlessDisables: {
  263. alias: 'rdd',
  264. type: 'boolean',
  265. },
  266. reportInvalidScopeDisables: {
  267. alias: 'risd',
  268. type: 'boolean',
  269. },
  270. reportNeedlessDisables: {
  271. alias: 'rd',
  272. type: 'boolean',
  273. },
  274. stdin: {
  275. type: 'boolean',
  276. },
  277. stdinFilename: {
  278. type: 'string',
  279. },
  280. version: {
  281. alias: 'v',
  282. type: 'boolean',
  283. },
  284. globbyOptions: {
  285. alias: 'go',
  286. type: 'string',
  287. },
  288. },
  289. };
  290. /**
  291. * @param {string[]} argv
  292. * @returns {Promise<any>}
  293. */
  294. module.exports = async (argv) => {
  295. const cli = buildCLI(argv);
  296. const invalidOptionsMessage = checkInvalidCLIOptions(meowOptions.flags, cli.flags);
  297. if (invalidOptionsMessage) {
  298. process.stderr.write(invalidOptionsMessage);
  299. process.exit(EXIT_CODE_ERROR); // eslint-disable-line no-process-exit
  300. }
  301. let formatter = cli.flags.formatter;
  302. if (cli.flags.customFormatter) {
  303. const customFormatter = resolveCustomFormatter(cli.flags.customFormatter);
  304. formatter = require(customFormatter);
  305. }
  306. /** @type {OptionBaseType} */
  307. const optionsBase = {
  308. formatter,
  309. };
  310. if (cli.flags.quiet) {
  311. optionsBase.quiet = cli.flags.quiet;
  312. }
  313. if (cli.flags.quietDeprecationWarnings) {
  314. optionsBase.quietDeprecationWarnings = cli.flags.quietDeprecationWarnings;
  315. }
  316. if (cli.flags.customSyntax) {
  317. optionsBase.customSyntax = cli.flags.customSyntax;
  318. }
  319. if (cli.flags.config) {
  320. // Should check these possibilities:
  321. // a. name of a node_module
  322. // b. absolute path
  323. // c. relative path relative to `process.cwd()`.
  324. // If none of the above work, we'll try a relative path starting
  325. // in `process.cwd()`.
  326. optionsBase.configFile =
  327. resolveFrom.silent(process.cwd(), cli.flags.config) ||
  328. path.join(process.cwd(), cli.flags.config);
  329. }
  330. if (cli.flags.configBasedir) {
  331. optionsBase.configBasedir = path.isAbsolute(cli.flags.configBasedir)
  332. ? cli.flags.configBasedir
  333. : path.resolve(process.cwd(), cli.flags.configBasedir);
  334. }
  335. if (cli.flags.globbyOptions) {
  336. try {
  337. optionsBase.globbyOptions = await parseGlobbyOptions(cli.flags.globbyOptions);
  338. } catch (error) {
  339. if (typeof error === 'string') {
  340. process.stderr.write(`${error}${EOL}`);
  341. process.exitCode = EXIT_CODE_ERROR;
  342. return;
  343. }
  344. throw error;
  345. }
  346. }
  347. if (cli.flags.stdinFilename) {
  348. optionsBase.codeFilename = cli.flags.stdinFilename;
  349. }
  350. if (cli.flags.ignorePath) {
  351. optionsBase.ignorePath = cli.flags.ignorePath;
  352. }
  353. if (cli.flags.ignorePattern) {
  354. optionsBase.ignorePattern = cli.flags.ignorePattern;
  355. }
  356. if (cli.flags.ignoreDisables) {
  357. optionsBase.ignoreDisables = cli.flags.ignoreDisables;
  358. }
  359. if (cli.flags.disableDefaultIgnores) {
  360. optionsBase.disableDefaultIgnores = cli.flags.disableDefaultIgnores;
  361. }
  362. if (cli.flags.cache) {
  363. optionsBase.cache = true;
  364. }
  365. if (cli.flags.cacheLocation) {
  366. optionsBase.cacheLocation = cli.flags.cacheLocation;
  367. }
  368. if (cli.flags.cacheStrategy) {
  369. optionsBase.cacheStrategy = cli.flags.cacheStrategy;
  370. }
  371. if (cli.flags.fix) {
  372. optionsBase.fix = cli.flags.fix;
  373. }
  374. if (cli.flags.outputFile) {
  375. optionsBase.outputFile = cli.flags.outputFile;
  376. }
  377. const reportNeedlessDisables = cli.flags.reportNeedlessDisables;
  378. const reportInvalidScopeDisables = cli.flags.reportInvalidScopeDisables;
  379. const reportDescriptionlessDisables = cli.flags.reportDescriptionlessDisables;
  380. if (reportNeedlessDisables) {
  381. optionsBase.reportNeedlessDisables = reportNeedlessDisables;
  382. }
  383. if (reportInvalidScopeDisables) {
  384. optionsBase.reportInvalidScopeDisables = reportInvalidScopeDisables;
  385. }
  386. if (reportDescriptionlessDisables) {
  387. optionsBase.reportDescriptionlessDisables = reportDescriptionlessDisables;
  388. }
  389. const maxWarnings = cli.flags.maxWarnings;
  390. if (maxWarnings !== undefined) {
  391. optionsBase.maxWarnings = maxWarnings;
  392. }
  393. if (cli.flags.help) {
  394. cli.showHelp(0);
  395. return;
  396. }
  397. if (cli.flags.version) {
  398. cli.showVersion();
  399. return;
  400. }
  401. if (cli.flags.allowEmptyInput) {
  402. optionsBase.allowEmptyInput = cli.flags.allowEmptyInput;
  403. }
  404. // Add input/code into options
  405. /** @type {OptionBaseType} */
  406. const options = cli.input.length
  407. ? {
  408. ...optionsBase,
  409. files: /** @type {string} */ (cli.input),
  410. }
  411. : await getStdin().then((stdin) => {
  412. return {
  413. ...optionsBase,
  414. code: stdin,
  415. };
  416. });
  417. if (cli.flags.printConfig) {
  418. return printConfig(options)
  419. .then((config) => {
  420. process.stdout.write(JSON.stringify(config, null, ' '));
  421. })
  422. .catch(handleError);
  423. }
  424. if (!options.files && !options.code && !cli.flags.stdin) {
  425. cli.showHelp(0);
  426. return;
  427. }
  428. return standalone(options)
  429. .then((linted) => {
  430. if (!linted.output) {
  431. return;
  432. }
  433. process.stdout.write(linted.output);
  434. if (options.outputFile) {
  435. writeOutputFile(linted.output, options.outputFile).catch(handleError);
  436. }
  437. if (linted.errored) {
  438. process.exitCode = EXIT_CODE_ERROR;
  439. } else if (maxWarnings !== undefined && linted.maxWarningsExceeded) {
  440. const foundWarnings = linted.maxWarningsExceeded.foundWarnings;
  441. process.stderr.write(
  442. `${EOL}${red(`Max warnings exceeded: `)}${foundWarnings} found. ${dim(
  443. `${maxWarnings} allowed${EOL}${EOL}`,
  444. )}`,
  445. );
  446. process.exitCode = EXIT_CODE_ERROR;
  447. }
  448. })
  449. .catch(handleError);
  450. };
  451. /**
  452. * @param {{ stack: any, code: any }} err
  453. * @returns {void}
  454. */
  455. function handleError(err) {
  456. process.stderr.write(err.stack + EOL);
  457. const exitCode = typeof err.code === 'number' ? err.code : 1;
  458. process.exitCode = exitCode;
  459. }
  460. /**
  461. * @param {string} value
  462. * @returns {Promise<Record<string, unknown>>}
  463. */
  464. function parseGlobbyOptions(value) {
  465. const errorMessage = () =>
  466. `Invalid option ${red('"--globby-options"')}.` +
  467. ` The value ${red(`"${value}"`)} is not valid JSON object.`;
  468. let options;
  469. try {
  470. options = JSON.parse(value);
  471. } catch (_) {
  472. return Promise.reject(errorMessage());
  473. }
  474. if (isPlainObject(options)) {
  475. return Promise.resolve(options);
  476. }
  477. return Promise.reject(errorMessage());
  478. }
  479. /**
  480. * @param {string[]} argv
  481. * @returns {CLIOptions}
  482. */
  483. function buildCLI(argv) {
  484. // @ts-expect-error -- TS2322: Type 'Result<AnyFlags>' is not assignable to type 'CLIOptions'.
  485. return meow({ ...meowOptions, argv });
  486. }
  487. module.exports.buildCLI = buildCLI;