configurationComment.mjs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { assertString, isString } from './validateTypes.mjs';
  2. import { isComment } from './typeGuards.mjs';
  3. export const DISABLE_COMMAND = '-disable';
  4. export const DISABLE_LINE_COMMAND = '-disable-line';
  5. export const DISABLE_NEXT_LINE_COMMAND = '-disable-next-line';
  6. export 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. export const DEFAULT_CONFIGURATION_COMMENT = 'stylelint';
  14. /**
  15. * Extract a command from a given comment.
  16. *
  17. * @param {string} commentText
  18. * @param {string} [configurationComment]
  19. * @returns {string}
  20. */
  21. export function extractConfigurationComment(
  22. commentText,
  23. configurationComment = DEFAULT_CONFIGURATION_COMMENT,
  24. ) {
  25. if (!commentText) return commentText;
  26. const [command] = commentText.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 {string | import('postcss').Node} textOrNode
  34. * @param {string} [configurationComment]
  35. * @returns {boolean}
  36. */
  37. export function isConfigurationComment(
  38. textOrNode,
  39. configurationComment = DEFAULT_CONFIGURATION_COMMENT,
  40. ) {
  41. const commentText = isString(textOrNode)
  42. ? textOrNode
  43. : isComment(textOrNode)
  44. ? textOrNode.text
  45. : undefined;
  46. if (!commentText) return false;
  47. const command = extractConfigurationComment(commentText, configurationComment);
  48. return command !== undefined && ALL_COMMANDS.has(command);
  49. }
  50. /**
  51. * Get full stylelint command
  52. *
  53. * @param {string} command
  54. * @param {string} [configurationComment]
  55. * @returns {string}
  56. */
  57. export function getConfigurationComment(
  58. command,
  59. configurationComment = DEFAULT_CONFIGURATION_COMMENT,
  60. ) {
  61. return `${configurationComment}${command}`;
  62. }