-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
chore: add utility getRequireVarDeclarators
- Loading branch information
Showing
2 changed files
with
42 additions
and
40 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
37 changes: 37 additions & 0 deletions
37
src/transforms/v2-to-v3/modules/requireModule/getRequireVarDeclarators.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
import { CallExpression, Collection, JSCodeshift, Literal, VariableDeclarator } from "jscodeshift"; | ||
import { PACKAGE_NAME } from "../../config"; | ||
|
||
export const getRequireVarDeclarators = ( | ||
j: JSCodeshift, | ||
source: Collection<unknown>, | ||
path?: string | ||
): Collection<VariableDeclarator> => | ||
source | ||
.find(j.VariableDeclarator, { | ||
init: { | ||
type: "CallExpression", | ||
callee: { type: "Identifier", name: "require" }, | ||
}, | ||
}) | ||
.filter((varDeclarator) => { | ||
const declaratorInit = varDeclarator.value.init; | ||
if (!declaratorInit || declaratorInit.type !== "CallExpression") { | ||
return false; | ||
} | ||
|
||
const callExpression = declaratorInit as CallExpression; | ||
if (callExpression.arguments.length !== 1) { | ||
return false; | ||
} | ||
|
||
const { value: sourceValue } = callExpression.arguments[0] as Literal; | ||
if (typeof sourceValue !== "string") { | ||
return false; | ||
} | ||
|
||
if (path) { | ||
return sourceValue === path; | ||
} | ||
|
||
return sourceValue.startsWith(PACKAGE_NAME); | ||
}); |