Last active
June 14, 2024 14:43
-
-
Save AlexGeb/c8c0e567fe0f18be96817234eea5558c to your computer and use it in GitHub Desktop.
Change imports of pipe from 'fp-ts/function' to 'effect'
This file contains hidden or 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
| /* eslint-disable @typescript-eslint/no-non-null-assertion */ | |
| import { API, FileInfo, JSCodeshift } from 'jscodeshift'; | |
| const transform = (fileInfo: FileInfo, api: API) => { | |
| const j: JSCodeshift = api.jscodeshift; | |
| const root = j(fileInfo.source); | |
| const replaceFpTsFunctionImportByEffectImport = (name: string) => { | |
| const imports = root.find(j.ImportDeclaration); | |
| const getFpTsFunctionImport = (name: string) => | |
| imports.filter( | |
| path => | |
| path.node.source.value === 'fp-ts/function' && | |
| path.node.specifiers!.some( | |
| specifier => | |
| specifier.type === 'ImportSpecifier' && | |
| specifier.imported.name === name, | |
| ), | |
| ); | |
| const fpTsImport = getFpTsFunctionImport(name); | |
| const effectImport = imports.filter( | |
| path => | |
| path.node.source.value === 'effect' && path.node.importKind !== 'type', | |
| ); | |
| // If there's an import from 'fp-ts/function' for 'pipe', we need to replace or merge it | |
| if (fpTsImport.size() > 0) { | |
| // If there's already an import from 'effect', add 'pipe' to it | |
| if (effectImport.size() > 0) { | |
| // add pipe to first effect import | |
| effectImport | |
| .at(0) | |
| .get() | |
| .node.specifiers!.push(j.importSpecifier(j.identifier(name))); | |
| } else { | |
| // Otherwise, create a new import declaration for 'effect' with name | |
| const newEffectImport = j.importDeclaration( | |
| [j.importSpecifier(j.identifier(name))], | |
| j.literal('effect'), | |
| ); | |
| root.get().node.program.body.unshift(newEffectImport); | |
| } | |
| // Remove the 'pipe' import from 'fp-ts/function' | |
| fpTsImport.forEach(path => { | |
| path.node.specifiers = path.node.specifiers!.filter( | |
| specifier => | |
| !( | |
| specifier.type === 'ImportSpecifier' && | |
| specifier.imported.name === name | |
| ), | |
| ); | |
| if (path.node.specifiers.length === 0) { | |
| // Remove the entire import declaration if no specifiers are left | |
| j(path).remove(); | |
| } | |
| }); | |
| } | |
| }; | |
| ['pipe', 'identity', 'flow', 'unsafeCoerce'].forEach( | |
| replaceFpTsFunctionImportByEffectImport, | |
| ); | |
| return root.toSource(); | |
| }; | |
| export default transform; | |
| export const parser = 'tsx'; |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
jscodeshift -t ./transform.ts path/to/code