Created
August 22, 2023 06:57
-
-
Save hi-ogawa/cc0702969d341567edf0f0fff35e4924 to your computer and use it in GitHub Desktop.
intl-extract.ts by jscodeshift
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
/* eslint-disable no-console */ | |
import type { API, FileInfo } from "jscodeshift"; | |
import * as recast from "recast"; | |
export default function transformer(file: FileInfo, api: API): string | undefined { | |
const j = api.jscodeshift; | |
const $j = j(file.source); | |
const result: { | |
location: string; | |
code: string; | |
descriptor: Record<string, string>; | |
}[] = []; | |
// intl.formatMessage(...) | |
for (const p of $j.find(j.CallExpression).paths()) { | |
const node = p.value; | |
const code = recast.print(node).code.trim(); | |
const location = `${file.path}:${node.loc?.start.line}:${node.loc?.start.column}`; | |
if ( | |
j.MemberExpression.check(node.callee) && | |
j.Identifier.check(node.callee.object) && | |
node.callee.object.name === "intl" && | |
j.Identifier.check(node.callee.property) && | |
node.callee.property.name === "formatMessage" | |
) { | |
const arg = node.arguments[0]; | |
const descriptor: Record<string, string> = {}; | |
if (j.ObjectExpression.check(arg)) { | |
for (const prop of arg.properties) { | |
if ( | |
j.ObjectProperty.check(prop) && | |
j.Identifier.check(prop.key) && | |
j.StringLiteral.check(prop.value) | |
) { | |
descriptor[prop.key.name] = prop.value.value; | |
} | |
} | |
} | |
result.push({ | |
location, | |
code, | |
descriptor | |
}); | |
} | |
} | |
// <FormattedMessage ... > | |
for (const p of $j.find(j.JSXOpeningElement).paths()) { | |
const node = p.value; | |
const code = recast.print(node).code.trim(); | |
const location = `${file.path}:${node.loc?.start.line}:${node.loc?.start.column}`; | |
if (j.JSXIdentifier.check(node.name) && node.name.name === "FormattedMessage") { | |
const descriptor: Record<string, string> = {}; | |
for (const attr of node.attributes ?? []) { | |
if ( | |
j.JSXAttribute.check(attr) && | |
j.JSXIdentifier.check(attr.name) && | |
j.StringLiteral.check(attr.value) | |
) { | |
descriptor[attr.name.name] = attr.value.value; | |
} | |
} | |
result.push({ | |
location, | |
code, | |
descriptor | |
}); | |
} | |
} | |
return; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment