|
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(); |
|
} |