Skip to content

Instantly share code, notes, and snippets.

@evanpurkhiser
Created August 13, 2024 05:24
Show Gist options
  • Save evanpurkhiser/3a837892f6a035b516ff2a44e0e5e91b to your computer and use it in GitHub Desktop.
Save evanpurkhiser/3a837892f6a035b516ff2a44e0e5e91b to your computer and use it in GitHub Desktop.
import type { API, FileInfo, JSXElement } from "jscodeshift";
export default function transformer(file: FileInfo, api: API) {
const j = api.jscodeshift;
function locateButtonToTransform(identifier: JSXElement) {
return !!(
identifier.openingElement.name?.type === "JSXIdentifier" &&
identifier.openingElement.name.name === "Button" &&
identifier.openingElement.attributes?.some(
(attr) =>
attr.type === "JSXAttribute" &&
attr.name.type === "JSXIdentifier" &&
attr.name.name === "href",
)
);
}
const ast = j(file.source);
const oldButtons = ast.find(j.JSXElement, locateButtonToTransform);
if (oldButtons.length === 0) {
return;
}
// Rename Button to LinkButton
oldButtons.forEach((path) => {
if (path.node.openingElement.name.type === "JSXIdentifier") {
path.node.openingElement.name.name = "LinkButton";
}
if (path.node.closingElement?.name.type === "JSXIdentifier") {
path.node.closingElement.name.name = "LinkButton";
}
});
// Look if there are still usages of Button so we keep that import
const hasMoreButton = ast.findJSXElements("Button").length > 0;
ast
.find(j.ImportDeclaration)
.filter(
(path) =>
path.node.source.type === "StringLiteral" &&
path.node.source.value === "sentry/components/button" &&
path.node.importKind === "value",
)
.forEach((path) => {
if (path.node.specifiers) {
// Filter out the old Button import if we don't need it
const specifiers = hasMoreButton
? path.node.specifiers
: path.node.specifiers.filter(
(node) =>
!(
node.type === "ImportSpecifier" &&
["Button", "LinkButton"].includes(node.imported.name)
),
);
console.log(specifiers);
path.node.specifiers = [
...specifiers,
j.importSpecifier(j.identifier("LinkButton")),
];
}
});
return ast.toSource();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment