Skip to content

Commit

Permalink
fix: Escape RegExp characters in suffix.
Browse files Browse the repository at this point in the history
  • Loading branch information
cartant committed Nov 18, 2021
1 parent 797b2bb commit a23a69c
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
7 changes: 5 additions & 2 deletions source/rules/suffix-subjects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
getParserServices,
getTypeServices,
} from "eslint-etc";
import { ruleCreator } from "../utils";
import { escapeRegExp, ruleCreator } from "../utils";

const defaultOptions: readonly {
parameters?: boolean;
Expand Down Expand Up @@ -75,7 +75,10 @@ const rule = ruleCreator({
}

const { suffix = "Subject" } = config;
const suffixRegex = new RegExp(String.raw`${suffix}\$?$`, "i");
const suffixRegex = new RegExp(
String.raw`${escapeRegExp(suffix)}\$?$`,
"i"
);

function checkNode(nameNode: es.Node, typeNode?: es.Node) {
let tsNode = esTreeNodeToTSNodeMap.get(nameNode);
Expand Down
5 changes: 5 additions & 0 deletions source/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ export function createRegExpForWords(
return new RegExp(`(${joined})`, flags);
}

export function escapeRegExp(text: string): string {
// https://stackoverflow.com/a/3561711/6680611
return text.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&");
}

export const ruleCreator = ESLintUtils.RuleCreator(
(name) =>
`https://github.com/cartant/eslint-plugin-rxjs/tree/main/docs/rules/${name}.md`
Expand Down
13 changes: 13 additions & 0 deletions tests/rules/suffix-subjects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -591,6 +591,19 @@ ruleTester({ types: true }).run("suffix-subjects", rule, {
~~~~~~ [forbidden { "suffix": "Subject" }]
`
),
fromFixture(
stripIndent`
// BehaviorSubject with $$ suffix
// https://github.com/cartant/eslint-plugin-rxjs/issues/88
import { BehaviorSubject } from "rxjs";
const subject$ = new BehaviorSubject<number>(42);
~~~~~~~~ [forbidden { "suffix": "$$" }]
const someSubject$ = new BehaviorSubject<number>(54);
~~~~~~~~~~~~ [forbidden { "suffix": "$$" }]
`,
{ options: [{ suffix: "$$" }] }
),
fromFixture(
stripIndent`
// MySubject without suffix
Expand Down

0 comments on commit a23a69c

Please sign in to comment.