Skip to content

Commit

Permalink
fix(eslint-plugin): [camelcase] handle optional member expr (#1204)
Browse files Browse the repository at this point in the history
  • Loading branch information
a-tarasyuk authored and bradzacher committed Nov 14, 2019
1 parent d8b07a7 commit 9c8203f
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 13 deletions.
42 changes: 29 additions & 13 deletions packages/eslint-plugin/src/rules/camelcase.ts
Expand Up @@ -72,23 +72,28 @@ export default util.createRule<Options, MessageIds>({
* @private
*/
function isTSPropertyType(node: TSESTree.Node): boolean {
if (!node.parent) {
return false;
}
if (TS_PROPERTY_TYPES.includes(node.parent.type)) {
if (TS_PROPERTY_TYPES.includes(node.type)) {
return true;
}

if (node.parent.type === AST_NODE_TYPES.AssignmentPattern) {
if (node.type === AST_NODE_TYPES.AssignmentPattern) {
return (
node.parent.parent !== undefined &&
TS_PROPERTY_TYPES.includes(node.parent.parent.type)
node.parent !== undefined &&
TS_PROPERTY_TYPES.includes(node.parent.type)
);
}

return false;
}

function report(node: TSESTree.Identifier): void {
context.report({
node,
messageId: 'notCamelCase',
data: { name: node.name },
});
}

return {
Identifier(node): void {
/*
Expand All @@ -103,13 +108,24 @@ export default util.createRule<Options, MessageIds>({
}

// Check TypeScript specific nodes
if (isTSPropertyType(node)) {
const parent = node.parent;
if (parent && isTSPropertyType(parent)) {
if (properties === 'always' && isUnderscored(name)) {
context.report({
node,
messageId: 'notCamelCase',
data: { name: node.name },
});
report(node);
}

return;
}

if (parent && parent.type === AST_NODE_TYPES.OptionalMemberExpression) {
// Report underscored object names
if (
properties === 'always' &&
parent.object.type === AST_NODE_TYPES.Identifier &&
parent.object.name === node.name &&
isUnderscored(name)
) {
report(node);
}

return;
Expand Down
44 changes: 44 additions & 0 deletions packages/eslint-plugin/tests/rules/camelcase.test.ts
Expand Up @@ -79,6 +79,22 @@ ruleTester.run('camelcase', rule, {
code: 'abstract class Foo { abstract bar: number = 0; }',
options: [{ properties: 'always' }],
},
{
code: 'const foo = foo?.baz;',
},
{
code: 'const foo = foo?.foo_bar?.foo_bar_baz;',
},
{
code: 'const foo = foo.bar?.foo_bar_baz;',
},
{
code: 'const foo = (foo?.bar?.baz)?.foo_bar_baz;',
},
{
code: 'const foo = foo_bar?.foo;',
options: [{ properties: 'never' }],
},
],

invalid: [
Expand Down Expand Up @@ -194,5 +210,33 @@ ruleTester.run('camelcase', rule, {
},
],
},
{
code: 'const foo = foo_bar?.foo;',
options: [{ properties: 'always' }],
errors: [
{
messageId: 'notCamelCase',
data: {
name: 'foo_bar',
},
line: 1,
column: 13,
},
],
},
{
code: 'const foo = (foo_test?.bar)?.baz;',
options: [{ properties: 'always' }],
errors: [
{
messageId: 'notCamelCase',
data: {
name: 'foo_test',
},
line: 1,
column: 14,
},
],
},
],
});

0 comments on commit 9c8203f

Please sign in to comment.