cli.js 14 KB

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