Skip to content

Commit

Permalink
feat: detect non-member expressions in n/no-sync (#127)
Browse files Browse the repository at this point in the history
  • Loading branch information
scagood committed Oct 11, 2023
1 parent 2d43f48 commit 6d02512
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 6 deletions.
29 changes: 23 additions & 6 deletions lib/rules/no-sync.js
Expand Up @@ -4,6 +4,24 @@
*/
"use strict"

const allowedAtRootLevelSelector = [
// fs.readFileSync()
":function MemberExpression > Identifier[name=/Sync$/]",
// readFileSync.call(null, 'path')
":function MemberExpression > Identifier[name=/Sync$/]",
// readFileSync()
":function :not(MemberExpression) > Identifier[name=/Sync$/]",
]

const disallowedAtRootLevelSelector = [
// fs.readFileSync()
"MemberExpression > Identifier[name=/Sync$/]",
// readFileSync.call(null, 'path')
"MemberExpression > Identifier[name=/Sync$/]",
// readFileSync()
":not(MemberExpression) > Identifier[name=/Sync$/]",
]

module.exports = {
meta: {
type: "suggestion",
Expand Down Expand Up @@ -32,18 +50,17 @@ module.exports = {
},

create(context) {
const selector =
context.options[0] && context.options[0].allowAtRootLevel
? ":function MemberExpression[property.name=/.*Sync$/]"
: "MemberExpression[property.name=/.*Sync$/]"
const selector = context.options[0]?.allowAtRootLevel
? allowedAtRootLevelSelector
: disallowedAtRootLevelSelector

return {
[selector](node) {
context.report({
node,
node: node.parent,
messageId: "noSync",
data: {
propertyName: node.property.name,
propertyName: node.name,
},
})
},
Expand Down
38 changes: 38 additions & 0 deletions tests/lib/rules/no-sync.js
Expand Up @@ -14,10 +14,18 @@ new RuleTester().run("no-sync", rule, {
code: "var foo = fs.fooSync;",
options: [{ allowAtRootLevel: true }],
},
{
code: "var foo = fooSync;",
options: [{ allowAtRootLevel: true }],
},
{
code: "if (true) {fs.fooSync();}",
options: [{ allowAtRootLevel: true }],
},
{
code: "if (true) {fooSync();}",
options: [{ allowAtRootLevel: true }],
},
],
invalid: [
{
Expand All @@ -30,6 +38,36 @@ new RuleTester().run("no-sync", rule, {
},
],
},
{
code: "var foo = fs.fooSync.apply();",
errors: [
{
messageId: "noSync",
data: { propertyName: "fooSync" },
type: "MemberExpression",
},
],
},
{
code: "var foo = fooSync();",
errors: [
{
messageId: "noSync",
data: { propertyName: "fooSync" },
type: "CallExpression",
},
],
},
{
code: "var foo = fooSync.apply();",
errors: [
{
messageId: "noSync",
data: { propertyName: "fooSync" },
type: "MemberExpression",
},
],
},
{
code: "var foo = fs.fooSync();",
options: [{ allowAtRootLevel: false }],
Expand Down

0 comments on commit 6d02512

Please sign in to comment.