addRuleToIndex.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. export const parser = 'flow';
  2. export default function transformer(file, api, options) {
  3. const j = api.jscodeshift;
  4. const s = j(file.source);
  5. const { ruleName, rulePath } = options || {};
  6. const nameSort = (a, b) => {
  7. const aName = a.key.type === 'Literal' ? a.key.value : a.key.name;
  8. const bName = b.key.type === 'Literal' ? b.key.value : b.key.name;
  9. if (aName < bName) {
  10. return -1;
  11. }
  12. if (bName < aName) {
  13. return 1;
  14. }
  15. return 0;
  16. };
  17. let changesMade = 0;
  18. const rulePathInSrc = `./${rulePath.match(/src\/(.*)\.js/)[1]}`;
  19. changesMade += s
  20. .find(j.Identifier, {
  21. name: 'rules',
  22. })
  23. .forEach((path, index) => {
  24. // Add rule path.
  25. if (index === 0) {
  26. path.parentPath.value.value.properties.unshift(j.property(
  27. 'init',
  28. j.literal(ruleName),
  29. j.callExpression(j.identifier('require'), [j.literal(rulePathInSrc)]),
  30. ));
  31. path.parentPath.value.value.properties.sort(nameSort);
  32. }
  33. // Set default reporting to error.
  34. if (index === 1) {
  35. path.parentPath.value.value.properties.unshift(j.property('init', j.literal(`jsx-a11y/${ruleName}`), j.literal('error')));
  36. path.parentPath.value.value.properties.sort(nameSort);
  37. }
  38. }).length;
  39. if (changesMade === 0) {
  40. return null;
  41. }
  42. return s.toSource({
  43. quote: 'single',
  44. trailingComma: true,
  45. });
  46. }