Skip to content

Commit

Permalink
Create reusable method for Regexp escaping members
Browse files Browse the repository at this point in the history
  • Loading branch information
oBusk committed May 30, 2024
1 parent 8e2a4d3 commit 6531735
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
3 changes: 2 additions & 1 deletion packages/knip/src/typescript/getImportsAndExports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import type {
UnresolvedImport,
} from '../types/serializable-map.js';
import { timerify } from '../util/Performance.js';
import { escapeRegexp } from '../util/escape-regexp.js';
import { isStartsLikePackageName, sanitizeSpecifier } from '../util/modules.js';
import { extname, isInNodeModules } from '../util/path.js';
import { shouldIgnore } from '../util/tag.js';
Expand Down Expand Up @@ -400,7 +401,7 @@ const getImportsAndExports = (
const setRefs = (item: SerializableExport | SerializableExportMember) => {
if (!item.symbol) return;
const symbols = new Set<ts.Symbol>();
for (const match of sourceFile.text.matchAll(new RegExp(item.identifier.replace(/[\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'))) {
for (const match of sourceFile.text.matchAll(new RegExp(escapeRegexp(item.identifier)))) {
const isDeclaration = match.index === item.pos || match.index === item.pos + 1; // off-by-one from `stripQuotes`
if (!isDeclaration) {
// @ts-expect-error ts.getTokenAtPosition is internal fn
Expand Down
8 changes: 8 additions & 0 deletions packages/knip/src/util/escape-regexp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/**
* Escapes a string to be used in a regular expression.
*
* Escapes all characters that have a special meaning in regular expressions.
*/
export function escapeRegexp(str: string): string {
return str.replace(/[\\^$*+?.()|[\]{}]/g, '\\$&');
}

0 comments on commit 6531735

Please sign in to comment.