normalizeRuleSettings.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. 'use strict';
  2. const _ = require('lodash');
  3. const rules = require('./rules');
  4. // Rule settings can take a number of forms, e.g.
  5. // a. "rule-name": null
  6. // b. "rule-name": [null, ...]
  7. // c. "rule-name": primaryOption
  8. // d. "rule-name": [primaryOption]
  9. // e. "rule-name": [primaryOption, secondaryOption]
  10. // Where primaryOption can be anything: primitive, Object, or Array.
  11. /**
  12. * This function normalizes all the possibilities into the
  13. * standard form: [primaryOption, secondaryOption]
  14. * Except in the cases with null, a & b, in which case
  15. * null is returned
  16. * @param {import('stylelint').StylelintConfigRuleSettings} rawSettings
  17. * @param {string} ruleName
  18. * @param {boolean} [primaryOptionArray] If primaryOptionArray is not provided, we try to get it from the, rules themselves, which will not work for plugins
  19. * @return {[any, Object] | Array<any | [any, Object]> | null}
  20. */
  21. module.exports = function (
  22. rawSettings,
  23. ruleName,
  24. // If primaryOptionArray is not provided, we try to get it from the
  25. // rules themselves, which will not work for plugins
  26. primaryOptionArray,
  27. ) {
  28. if (rawSettings === null) {
  29. return null;
  30. }
  31. if (!Array.isArray(rawSettings)) {
  32. return [rawSettings];
  33. }
  34. // Everything below is an array ...
  35. if (rawSettings[0] === null) {
  36. return null;
  37. }
  38. if (primaryOptionArray === undefined) {
  39. const rule = rules[ruleName];
  40. primaryOptionArray = _.get(rule, 'primaryOptionArray');
  41. }
  42. if (!primaryOptionArray) {
  43. return rawSettings;
  44. }
  45. // Everything below is a rule that CAN have an array for a primary option ...
  46. // (they might also have something else, e.g. rule-properties-order can
  47. // have the string "alphabetical")
  48. if (rawSettings.length === 1 && Array.isArray(rawSettings[0])) {
  49. return rawSettings;
  50. }
  51. if (
  52. rawSettings.length === 2 &&
  53. !_.isPlainObject(rawSettings[0]) &&
  54. _.isPlainObject(rawSettings[1])
  55. ) {
  56. return rawSettings;
  57. }
  58. return [rawSettings];
  59. };