prefer-read-only-props.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /**
  2. * @fileoverview Require component props to be typed as read-only.
  3. * @author Luke Zapart
  4. */
  5. 'use strict';
  6. const Components = require('../util/Components');
  7. const docsUrl = require('../util/docsUrl');
  8. function isFlowPropertyType(node) {
  9. return node.type === 'ObjectTypeProperty';
  10. }
  11. function isCovariant(node) {
  12. return (node.variance && (node.variance.kind === 'plus')) || (node.parent.parent.parent.id && (node.parent.parent.parent.id.name === '$ReadOnly'));
  13. }
  14. // ------------------------------------------------------------------------------
  15. // Rule Definition
  16. // ------------------------------------------------------------------------------
  17. module.exports = {
  18. meta: {
  19. docs: {
  20. description: 'Require read-only props.',
  21. category: 'Stylistic Issues',
  22. recommended: false,
  23. url: docsUrl('prefer-read-only-props')
  24. },
  25. fixable: 'code',
  26. messages: {
  27. readOnlyProp: 'Prop \'{{name}}\' should be read-only.'
  28. },
  29. schema: []
  30. },
  31. create: Components.detect((context, components) => ({
  32. 'Program:exit'() {
  33. const list = components.list();
  34. Object.keys(list).forEach((key) => {
  35. const component = list[key];
  36. if (!component.declaredPropTypes) {
  37. return;
  38. }
  39. Object.keys(component.declaredPropTypes).forEach((propName) => {
  40. const prop = component.declaredPropTypes[propName];
  41. if (!isFlowPropertyType(prop.node)) {
  42. return;
  43. }
  44. if (!isCovariant(prop.node)) {
  45. context.report({
  46. node: prop.node,
  47. messageId: 'readOnlyProp',
  48. data: {
  49. name: propName
  50. },
  51. fix: (fixer) => {
  52. if (!prop.node.variance) {
  53. // Insert covariance
  54. return fixer.insertTextBefore(prop.node, '+');
  55. }
  56. // Replace contravariance with covariance
  57. return fixer.replaceText(prop.node.variance, '+');
  58. }
  59. });
  60. }
  61. });
  62. });
  63. }
  64. }))
  65. };