configurationComment.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. 'use strict';
  2. const { assertString } = require('./validateTypes');
  3. const DISABLE_COMMAND = '-disable';
  4. const DISABLE_LINE_COMMAND = '-disable-line';
  5. const DISABLE_NEXT_LINE_COMMAND = '-disable-next-line';
  6. const ENABLE_COMMAND = '-enable';
  7. const ALL_COMMANDS = new Set([
  8. DISABLE_COMMAND,
  9. DISABLE_LINE_COMMAND,
  10. DISABLE_NEXT_LINE_COMMAND,
  11. ENABLE_COMMAND,
  12. ]);
  13. const DEFAULT_CONFIGURATION_COMMENT = 'stylelint';
  14. /** @typedef {import('postcss').Comment} Comment */
  15. /**
  16. * Extract a command from a given comment.
  17. *
  18. * @param {Comment} comment
  19. * @param {string} [configurationComment]
  20. * @returns {string}
  21. */
  22. function extractConfigurationComment(
  23. comment,
  24. configurationComment = DEFAULT_CONFIGURATION_COMMENT,
  25. ) {
  26. const [command] = comment.text.split(/\s/, 1);
  27. assertString(command);
  28. return command.replace(configurationComment, '');
  29. }
  30. /**
  31. * Tests if the given comment is a Stylelint command.
  32. *
  33. * @param {Comment} comment
  34. * @param {string} [configurationComment]
  35. * @returns {boolean}
  36. */
  37. function isConfigurationComment(comment, configurationComment = DEFAULT_CONFIGURATION_COMMENT) {
  38. const command = extractConfigurationComment(comment, configurationComment);
  39. return command !== undefined && ALL_COMMANDS.has(command);
  40. }
  41. /**
  42. * Get full stylelint command
  43. *
  44. * @param {string} command
  45. * @param {string} [configurationComment]
  46. * @returns {string}
  47. */
  48. function getConfigurationComment(command, configurationComment = DEFAULT_CONFIGURATION_COMMENT) {
  49. return `${configurationComment}${command}`;
  50. }
  51. module.exports = {
  52. DEFAULT_CONFIGURATION_COMMENT,
  53. DISABLE_COMMAND,
  54. DISABLE_LINE_COMMAND,
  55. DISABLE_NEXT_LINE_COMMAND,
  56. ENABLE_COMMAND,
  57. extractConfigurationComment,
  58. getConfigurationComment,
  59. isConfigurationComment,
  60. };