cli.js 15 KB

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