Skip to content

Commit

Permalink
[New] add prefer-exact-props rule
Browse files Browse the repository at this point in the history
  • Loading branch information
jomasti authored and ljharb committed Nov 18, 2017
1 parent f233eb7 commit 675dfae
Show file tree
Hide file tree
Showing 7 changed files with 832 additions and 8 deletions.
4 changes: 3 additions & 1 deletion README.md
Expand Up @@ -53,7 +53,9 @@ You should also specify settings that will be shared across all the plugin rules
// The names of any function used to wrap propTypes, e.g. `forbidExtraProps`. If this isn't set, any propTypes wrapped in a function will be skipped.
"forbidExtraProps",
{"property": "freeze", "object": "Object"},
{"property": "myFavoriteWrapper"}
{"property": "myFavoriteWrapper"},
// for rules that check exact prop wrappers
{"property": "forbidExtraProps", "exact": true}
],
"componentWrapperFunctions": [
// The name of any function used to wrap components, e.g. Mobx `observer` function. If this isn't set, components wrapped by these functions will be skipped.
Expand Down
140 changes: 140 additions & 0 deletions docs/rules/prefer-exact-props.md
@@ -0,0 +1,140 @@
# Prefer exact proptype definitions (react/prefer-exact-props)

Recommends options to ensure only exact prop definitions are used when writing components. This recommends solutions for PropTypes or for Flow types.

In React, you can define prop types for components using propTypes. Such an example is below:

```jsx
class Foo extends React.Component {
render() {
return <p>{this.props.bar}</p>;
}
}

Foo.propTypes = {
bar: PropTypes.string
};
```

The problem with this is that the consumer of the component could still pass in extra props. There could even be a typo for expected props. In order to prevent those situations, one could use the npm package [prop-types-exact](https://www.npmjs.com/package/prop-types-exact) to warn when unexpected props are passed to the component.

One can also define props for a component using Flow types. Such an example is below:

```jsx
class Foo extends React.Component {
props: {
bar: string
}

render() {
return <p>{this.props.bar}</p>;
}
}
```

In this case, one could instead enforce only the exact props being used by using exact type objects, like below:

```jsx
class Foo extends React.Component {
props: {|
bar: string
}|

render() {
return <p>{this.props.bar}</p>;
}
}
```

See the [Flow docs](https://flow.org/en/docs/types/objects/#toc-exact-object-types) on exact object types for more information.

## Rule Details

This rule will only produce errors for prop types when combined with the appropriate entries in `propWrapperFunctions`. For example:

```json
{
"settings": {
"propWrapperFunctions": [
{"property": "exact", "exact": true}
]
}
}
```

The following patterns are considered warnings:

```jsx
class Component extends React.Component {
render() {
return <div />;
}
}
Component.propTypes = {
foo: PropTypes.string
};
```

```jsx
class Component extends React.Component {
static propTypes = {
foo: PropTypes.string
}
render() {
return <div />;
}
}
```

```jsx
class Component extends React.Component {
props: {
foo: string
}
render() {
return <div />;
}
}
```

```jsx
function Component(props: { foo: string }) {
return <div />;
}
```

```jsx
type Props = {
foo: string
}
function Component(props: Props) {
return <div />;
}
```

The following patterns are **not** considered warnings:

```jsx
type Props = {|
foo: string
|}
function Component(props: Props) {
return <div />;
}
```

```jsx
import exact from 'prop-types-exact';
class Component extends React.Component {
render() {
return <div />;
}
}
Component.propTypes = exact({
foo: PropTypes.string
});
```

## When Not To Use It

If you aren't concerned about extra props being passed to a component or potential spelling errors for existing props aren't a common nuisance, then you can leave this rule off.
1 change: 1 addition & 0 deletions index.js
Expand Up @@ -81,6 +81,7 @@ const allRules = {
'no-unused-state': require('./lib/rules/no-unused-state'),
'no-will-update-set-state': require('./lib/rules/no-will-update-set-state'),
'prefer-es6-class': require('./lib/rules/prefer-es6-class'),
'prefer-exact-props': require('./lib/rules/prefer-exact-props'),
'prefer-read-only-props': require('./lib/rules/prefer-read-only-props'),
'prefer-stateless-function': require('./lib/rules/prefer-stateless-function'),
'prop-types': require('./lib/rules/prop-types'),
Expand Down
159 changes: 159 additions & 0 deletions lib/rules/prefer-exact-props.js
@@ -0,0 +1,159 @@
/**
* @fileoverview Prefer exact proptype definitions
*/

'use strict';

const Components = require('../util/Components');
const docsUrl = require('../util/docsUrl');
const propsUtil = require('../util/props');
const propWrapperUtil = require('../util/propWrapper');
const variableUtil = require('../util/variable');

const PROP_TYPES_MESSAGE = 'Component propTypes should be exact by using {{exactPropWrappers}}.';
const FLOW_MESSAGE = 'Component flow props should be set with exact objects.';

// -----------------------------------------------------------------------------
// Rule Definition
// -----------------------------------------------------------------------------

module.exports = {
meta: {
docs: {
description: 'Prefer exact proptype definitions',
category: 'Possible Errors',
recommended: false,
url: docsUrl('prefer-exact-props')
},
schema: []
},

create: Components.detect((context, components, utils) => {
const typeAliases = {};
const exactWrappers = propWrapperUtil.getExactPropWrapperFunctions(context);
const sourceCode = context.getSourceCode();

function getPropTypesErrorMessage() {
const formattedWrappers = propWrapperUtil.formatPropWrapperFunctions(exactWrappers);
const message = exactWrappers.size > 1 ? `one of ${formattedWrappers}` : formattedWrappers;
return {exactPropWrappers: message};
}

function isNonExactObjectTypeAnnotation(node) {
return (
node
&& node.type === 'ObjectTypeAnnotation'
&& node.properties.length > 0
&& !node.exact
);
}

function hasNonExactObjectTypeAnnotation(node) {
const typeAnnotation = node.typeAnnotation;
return (
typeAnnotation
&& typeAnnotation.typeAnnotation
&& isNonExactObjectTypeAnnotation(typeAnnotation.typeAnnotation)
);
}

function hasGenericTypeAnnotation(node) {
const typeAnnotation = node.typeAnnotation;
return (
typeAnnotation
&& typeAnnotation.typeAnnotation
&& typeAnnotation.typeAnnotation.type === 'GenericTypeAnnotation'
);
}

function isNonEmptyObjectExpression(node) {
return (
node
&& node.type === 'ObjectExpression'
&& node.properties.length > 0
);
}

function isNonExactPropWrapperFunction(node) {
return (
node
&& node.type === 'CallExpression'
&& !propWrapperUtil.isExactPropWrapperFunction(context, sourceCode.getText(node.callee))
);
}

function reportPropTypesError(node) {
context.report({
node,
message: PROP_TYPES_MESSAGE,
data: getPropTypesErrorMessage()
});
}

function reportFlowError(node) {
context.report({
node,
message: FLOW_MESSAGE
});
}

return {
TypeAlias(node) {
// working around an issue with eslint@3 and babel-eslint not finding the TypeAlias in scope
typeAliases[node.id.name] = node;
},

ClassProperty(node) {
if (!propsUtil.isPropTypesDeclaration(node)) {
return;
}

if (hasNonExactObjectTypeAnnotation(node)) {
reportFlowError(node);
} else if (exactWrappers.size > 0 && isNonEmptyObjectExpression(node.value)) {
reportPropTypesError(node);
} else if (exactWrappers.size > 0 && isNonExactPropWrapperFunction(node.value)) {
reportPropTypesError(node);
}
},

Identifier(node) {
if (!utils.getParentStatelessComponent(node)) {
return;
}

if (hasNonExactObjectTypeAnnotation(node)) {
reportFlowError(node);
} else if (hasGenericTypeAnnotation(node)) {
const identifier = node.typeAnnotation.typeAnnotation.id.name;
const typeAlias = typeAliases[identifier];
const propsDefinition = typeAlias ? typeAlias.right : null;
if (isNonExactObjectTypeAnnotation(propsDefinition)) {
reportFlowError(node);
}
}
},

MemberExpression(node) {
if (!propsUtil.isPropTypesDeclaration(node) || exactWrappers.size === 0) {
return;
}

const right = node.parent.right;
if (isNonEmptyObjectExpression(right)) {
reportPropTypesError(node);
} else if (isNonExactPropWrapperFunction(right)) {
reportPropTypesError(node);
} else if (right.type === 'Identifier') {
const identifier = right.name;
const propsDefinition = variableUtil.findVariableByName(context, identifier);
if (isNonEmptyObjectExpression(propsDefinition)) {
reportPropTypesError(node);
} else if (isNonExactPropWrapperFunction(propsDefinition)) {
reportPropTypesError(node);
}
}
}
};
})
};
42 changes: 36 additions & 6 deletions lib/util/propWrapper.js
Expand Up @@ -4,6 +4,16 @@

'use strict';

function searchPropWrapperFunctions(name, propWrapperFunctions) {
const splitName = name.split('.');
return Array.from(propWrapperFunctions).some((func) => {
if (splitName.length === 2 && func.object === splitName[0] && func.property === splitName[1]) {
return true;
}
return name === func || func.property === name;
});
}

function getPropWrapperFunctions(context) {
return new Set(context.settings.propWrapperFunctions || []);
}
Expand All @@ -13,16 +23,36 @@ function isPropWrapperFunction(context, name) {
return false;
}
const propWrapperFunctions = getPropWrapperFunctions(context);
const splitName = name.split('.');
return Array.from(propWrapperFunctions).some((func) => {
if (splitName.length === 2 && func.object === splitName[0] && func.property === splitName[1]) {
return true;
return searchPropWrapperFunctions(name, propWrapperFunctions);
}

function getExactPropWrapperFunctions(context) {
const propWrapperFunctions = getPropWrapperFunctions(context);
const exactPropWrappers = Array.from(propWrapperFunctions).filter((func) => func.exact === true);
return new Set(exactPropWrappers);
}

function isExactPropWrapperFunction(context, name) {
const exactPropWrappers = getExactPropWrapperFunctions(context);
return searchPropWrapperFunctions(name, exactPropWrappers);
}

function formatPropWrapperFunctions(propWrapperFunctions) {
return Array.from(propWrapperFunctions, (func) => {
if (func.object && func.property) {
return `'${func.object}.${func.property}'`;
}
return name === func || func.property === name;
});
if (func.property) {
return `'${func.property}'`;
}
return `'${func}'`;
}).join(', ');
}

module.exports = {
formatPropWrapperFunctions,
getExactPropWrapperFunctions,
getPropWrapperFunctions,
isExactPropWrapperFunction,
isPropWrapperFunction
};

0 comments on commit 675dfae

Please sign in to comment.