Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New rule: no-duplicate-dependent-keys #104

Merged
merged 8 commits into from
Aug 7, 2017
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions docs/rules/no-duplicate-dependent-keys.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Disallow repeating dependent keys (`no-duplicate-dependent-keys`)

## Rule Details

This rule makes it easy to spot repeating dependent keys in computed properties.

Examples of **incorrect** code for this rule:

```js
computed('foo.bar', 'foo.baz', 'foo.qux', 'foo.bar', function() {
//...
})
// or using brace expansions
computed('foo.{bar,baz,qux}', 'foo.bar', function() {
//...
})
```

Examples of **correct** code for this rule:

```js
computed('foo.bar', 'foo.baz', 'foo.qux', function() {
//...
})
// or using brace expansions
computed('foo.{bar,baz,qux}', 'bar.foo', function() {
//...
})
```
30 changes: 30 additions & 0 deletions lib/rules/no-duplicate-dependent-keys.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
'use strict';

const utils = require('../utils/utils');

const MESSAGE = 'Dependent keys should not be repeated';
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

module.exports = {
meta: {
docs: {
description: 'Disallow repeating dependent keys',
category: 'General',
recommended: true
Copy link
Member

@michalsnik michalsnik Aug 7, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please make it not recommended, so we can do a minor release first. I didn't catch this earlier

},
fixable: null,
message: MESSAGE,
},

create(context) {
return {
CallExpression(node) {
if (utils.hasDuplicateDependentKeys(node)) {
context.report(node, MESSAGE);
}
}
};
}
};
64 changes: 64 additions & 0 deletions lib/utils/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,13 @@ module.exports = {
parseCallee,
parseArgs,
findUnorderedProperty,
parseDependentKeys,
unwrapBraceExpressions,
hasDuplicateDependentKeys,
};

const ember = require('./ember');

/**
* Find nodes of given name
*
Expand Down Expand Up @@ -270,3 +275,62 @@ function findUnorderedProperty(arr) {

return null;
}

/**
* Checks whether a computed property has duplicate dependent keys.
*
* @param {CallExpression} callExp Given call expression
* @return {Boolean} Flag whether dependent keys present.
*/
function hasDuplicateDependentKeys(callExp) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function should be in ember.js util. We want these utils to be independent from ember-related stuff.

if (!ember.isComputedProp(callExp)) return false;

const dependentKeys = parseDependentKeys(callExp);
const uniqueKeys = dependentKeys
.filter((val, index, self) => self.indexOf(val) === index);
return uniqueKeys.length !== dependentKeys.length;
}

/**
* Parses dependent keys from call expression and returns them in an array.
*
* It also unwraps the expressions, so that `model.{foo,bar}` becomes `model.foo, model.bar`.
*
* @param {CallExpression} callExp CallExpression to examine
* @return {Array} Array of unwrapped dependent keys
*/
function parseDependentKeys(callExp) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This too

const isMemberExpCallExp = callExp.arguments.length === 0 && callExp.callee.object;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd add comment above why do we check this. I was confused at first and then I saw a case with .volatile in tests.

You should also check it rather like so:

!callExp.arguments.length &&
isMemberExpression(callExp.callee) &&
isCallExpression(callExp.callee.object)

const args = isMemberExpCallExp ? callExp.callee.object.arguments : callExp.arguments;

const dependentKeys = args
.filter(arg => isLiteral(arg))
.map(literal => literal.value);
return unwrapBraceExpressions(dependentKeys);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add empty line before return

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good point, we should probably configure it in the project's eslint I think

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yup, feel free to add it :)

}

/**
* Unwraps brace expressions.
*
* @param {Array} dependentKeys array of strings containing unprocessed dependent keys.
* @return {Array} Array of unwrapped dependent keys
*/
function unwrapBraceExpressions(dependentKeys) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And perhaps this

const braceExpressionRegexp = /\.{.+}/g;

const unwrappedExpressions = dependentKeys.map((key) => {
if (!braceExpressionRegexp.test(key)) return key;

const parts = key.split('.');
const prefix = parts[0];
const properties = parts[1]
.replace('{', '')
.replace('}', '')
.split(',');

return properties.map(property => `${prefix}.${property}`);
});

return unwrappedExpressions
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if you have dependent key like: lorem.ipsum.{dolor,sit}? I think this function will return:

[
  'lorem.ipsum'
]

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good point!

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

on the other hand, this will not work in Ember, as only one level of nesting is supported, WDYT @michalsnik?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This works actually @jbandura, only multi-level braces nesting is not allowed. See:
https://ember-twiddle.com/57f5af38632a6770fcae0c0904c07e08?openFiles=controllers.application.js%2C

.reduce((acc, cur) => acc.concat(cur), []);
}
70 changes: 70 additions & 0 deletions tests/lib/rules/no-duplicate-dependent-keys.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
'use strict';

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const rule = require('../../../lib/rules/no-duplicate-dependent-keys');
const RuleTester = require('eslint').RuleTester;


//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------

const ruleTester = new RuleTester();
const parserOptions = { ecmaVersion: 6, sourceType: 'module' };
ruleTester.run('no-duplicate-dependent-keys', rule, {
valid: [
{
code: `
{
foo: computed('model.foo', 'model.bar', 'model.baz', function() {})
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should test more cases, those with @each and [] too. People tend to create really crazy dependent keys and we need to make sure we support all of those weird cases, so I recommend to enlarge the test suite for this rule significantly :) WDYT?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

makes sense, will do 👍

}
`,
parserOptions,
},
{
code: `
{
foo: computed('model.{foo,bar}', 'model.qux', function() {})
}
`,
parserOptions,
},
{
code: `
{
foo: Ember.computed('model.{foo,bar}', 'model.qux', function() {
}).volatile()
}
`,
parserOptions,
}
],

invalid: [
{
code: `
{
foo: computed('model.foo', 'model.bar', 'model.baz', 'model.foo', function() {})
}
`,
parserOptions,
errors: [{
message: rule.meta.message,
}]
},
{
code: `
{
foo: computed('model.{foo,bar}', 'model.bar', function() {})
}
`,
parserOptions,
errors: [{
message: rule.meta.message,
}]
}
]
});
83 changes: 83 additions & 0 deletions tests/lib/utils/utils-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -186,3 +186,86 @@ describe('parseArgs', () => {
expect(parsedArgs).toEqual(['asd', 'qwe', 'zxc']);
});
});

describe('parseDependentKeys', () => {
it('should parse dependent keys from callexpression', () => {
const node = parse("computed('model.{foo,bar}', 'model.bar')");
expect(utils.parseDependentKeys(node)).toEqual([
'model.foo', 'model.bar', 'model.bar',
]);
});

it('should work when no dependent keys present', () => {
const node = parse('computed(function() {})');
expect(utils.parseDependentKeys(node)).toEqual([]);
});

it('should handle dependent keys and function arguments', () => {
const node = parse("computed('model.{foo,bar}', 'model.bar', function() {})");
expect(utils.parseDependentKeys(node)).toEqual([
'model.foo', 'model.bar', 'model.bar',
]);
});

it('should handle dependent keys and function arguments in MemberExpression', () => {
const node = parse(`
computed('model.{foo,bar}', 'model.bar', function() {
}).volatile();
`);
expect(utils.parseDependentKeys(node)).toEqual([
'model.foo', 'model.bar', 'model.bar',
]);
});
});

describe('unwrapBraceExpressions', () => {
it('should unwrap simple dependent keys', () => {
expect(utils.unwrapBraceExpressions([
'model.foo', 'model.bar'
])).toEqual(['model.foo', 'model.bar']);
});

it('should unwrap dependent keys with braces', () => {
expect(utils.unwrapBraceExpressions([
'model.{foo,bar}', 'model.bar'
])).toEqual(['model.foo', 'model.bar', 'model.bar']);
});

it('should unwrap more complex dependent keys', () => {
expect(utils.unwrapBraceExpressions([
'model.{foo,bar}', 'model.bar', 'data.{foo,baz,qux}'
])).toEqual([
'model.foo', 'model.bar', 'model.bar', 'data.foo', 'data.baz', 'data.qux',
]);
});
});

describe('hasDuplicateDependentKeys', () => {
it('reports duplicate dependent keys in computed calls', () => {
let node = parse("computed('model.{foo,bar}', 'model.bar')");
expect(utils.hasDuplicateDependentKeys(node)).toBeTruthy();
node = parse("Ember.computed('model.{foo,bar}', 'model.bar')");
expect(utils.hasDuplicateDependentKeys(node)).toBeTruthy();
});

it('ignores not repeated dependentKeys', () => {
let node = parse("computed('model.{foo,bar}', 'model.qux')");
expect(utils.hasDuplicateDependentKeys(node)).not.toBeTruthy();
node = parse("Ember.computed('model.{foo,bar}', 'model.qux')");
expect(utils.hasDuplicateDependentKeys(node)).not.toBeTruthy();
node = parse("computed('model.{foo,bar}', 'model.qux').volatile()");
expect(utils.hasDuplicateDependentKeys(node)).not.toBeTruthy();
});

it('ignores non-computed calls', () => {
const node = parse("foo('model.{foo,bar}', 'model.bar')");
expect(utils.hasDuplicateDependentKeys(node)).not.toBeTruthy();
});

it('reports duplicate dependent keys in computed calls with MemberExp', () => {
let node = parse("Ember.computed('model.{foo,bar}', 'model.bar').volatile()");
expect(utils.hasDuplicateDependentKeys(node)).toBeTruthy();
node = parse("computed('model.{foo,bar}', 'model.bar').volatile()");
expect(utils.hasDuplicateDependentKeys(node)).toBeTruthy();
});
});