Repository navigation
chore(i18n): sweep dead locale keys (AST-gated) #2263
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
887e40c
chore(i18n): delete dead webview locale keys
myk1yt 2128f5e
chore(i18n): delete dead src locale keys
myk1yt ee68131
fix(webview): resolve the command exit-status tooltip key
myk1yt e4556da
test(webview): render the exited tooltip instead of only the catalog
myk1yt 692513d
chore(i18n): delete orphaned core marketplace filter keys
myk1yt b1ea428
Merge remote-tracking branch 'origin/main' into chore/i18n-dead-key-s…
8609c1a
chore(i18n): add i18n key lint rule and interpolation check
edelauna 998dda9
Merge remote-tracking branch 'origin/main' into chore/i18n-dead-key-s…
edelauna 3fa169d
fix(i18n): fix lint test and review findings
edelauna 49c001f
fix(i18n): harden interpolation checker
edelauna 109a224
fix(i18n): address interpolation checker review findings
edelauna File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| // i18next splits a namespace from a key on ":" only. t("chat.foo") has no namespace, so it looks in the | ||
| // default namespace, misses, and shows the raw key to the user. Built-in no-restricted-syntax only. | ||
| import { readdirSync } from "node:fs" | ||
| import { basename } from "node:path" | ||
|
|
||
| /** | ||
| * @param {URL | string} enLocalesDir The `en` locale directory. Each JSON file name is a namespace. | ||
| */ | ||
| export function createI18nDotKeyConfig(enLocalesDir) { | ||
| const namespaces = readdirSync(enLocalesDir) | ||
| .filter((file) => file.endsWith(".json")) | ||
| .map((file) => basename(file, ".json")) | ||
| const dotKey = `/^(${namespaces.join("|")})\\./` | ||
| const message = "Write the key as 'namespace:path'. A dot after the namespace is not a namespace separator." | ||
|
|
||
| return { | ||
| files: ["**/*.ts", "**/*.tsx"], | ||
| ignores: ["**/__tests__/**", "**/*.test.ts", "**/*.test.tsx", "**/*.spec.ts", "**/*.spec.tsx"], | ||
| rules: { | ||
| "no-restricted-syntax": [ | ||
| "error", | ||
| ...i18nDotKeySelectors(dotKey).map((selector) => ({ selector, message })), | ||
| ], | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| /** The selectors alone, for a file set that already sets no-restricted-syntax. */ | ||
| export function getI18nDotKeySelectors(config) { | ||
| return config.rules["no-restricted-syntax"].slice(1) | ||
| } | ||
|
|
||
| function i18nDotKeySelectors(dotKey) { | ||
| const call = "CallExpression:matches([callee.name='t'], [callee.property.name='t'])" | ||
| return [`${call}[arguments.0.value=${dotKey}]`, `${call}[arguments.0.quasis.0.value.cooked=${dotKey}]`] | ||
| } |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| import assert from "node:assert/strict" | ||
| import { describe, it } from "node:test" | ||
| import { URL } from "node:url" | ||
|
|
||
| import { Linter } from "eslint" | ||
| import typescriptEslint from "typescript-eslint" | ||
|
|
||
| import { createI18nDotKeyConfig } from "./i18n-keys.js" | ||
|
|
||
| const linter = new Linter({ configType: "flat" }) | ||
| const config = [ | ||
| { files: ["**/*.ts", "**/*.tsx"], languageOptions: { parser: typescriptEslint.parser } }, | ||
| createI18nDotKeyConfig(new URL("../../webview-ui/src/i18n/locales/en", import.meta.url)), | ||
| ] | ||
|
|
||
| const lint = (code, filename = "components/example.tsx") => | ||
| linter.verify(code, config, { filename }).map((message) => message.message) | ||
|
|
||
| describe("i18n dot-form keys", () => { | ||
| for (const code of [ | ||
| 't("chat.commandExecution.exitStatus", { exitCode })', | ||
| 'i18next.t("settings.autoApprove.title")', | ||
| "t(`chat.errors.${name}`)", | ||
| "t(`chat\\u002ecommandExecution.exitStatus`)", | ||
| ]) { | ||
| it(`flags: ${code}`, () => { | ||
| assert.equal(lint(code).length, 1) | ||
| }) | ||
| } | ||
|
|
||
| for (const code of [ | ||
| 't("chat:commandExecution.exitStatus", { exitCode })', | ||
| 't("unknownNamespace.key")', | ||
| "t(`chat:errors.${name}`)", | ||
| ]) { | ||
| it(`allows: ${code}`, () => { | ||
| assert.deepEqual(lint(code), []) | ||
| }) | ||
| } | ||
|
|
||
| it("does not apply to spec files", () => { | ||
| assert.deepEqual(lint('t("chat.key")', "components/__tests__/example.spec.tsx"), []) | ||
| }) | ||
| }) |
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,118 @@ | ||
| /** | ||
| * Finds t("ns:key", { ... }) calls that do not pass a variable the English string needs. | ||
| * Example: the string has {{exitCode}} but the call passes { exitStatus }. | ||
| * | ||
| * Usage: node scripts/check-i18n-interpolation.js | ||
| * | ||
| * Only calls with a string-literal key and an object-literal second argument are checked. | ||
| * A spread in the object skips the call. | ||
| */ | ||
|
|
||
| const path = require("path") | ||
| const fs = require("fs") | ||
| const { execFileSync } = require("child_process") | ||
| const ts = require("typescript") | ||
|
|
||
| const ROOT = path.join(__dirname, "..") | ||
| const PACKAGES = ["src", "webview-ui/src"] | ||
|
|
||
| const files = execFileSync( | ||
| "git", | ||
| ["ls-files", "-z", "--", ...PACKAGES.map((p) => `${p}/**/*.ts`), ...PACKAGES.map((p) => `${p}/**/*.tsx`)], | ||
| { | ||
| cwd: ROOT, | ||
| encoding: "utf8", | ||
| }, | ||
| ) | ||
| .split("\0") | ||
| .filter((f) => f && !/(\/__tests__\/|\.(spec|test)\.tsx?$)/.test(f)) | ||
|
|
||
| const resources = {} | ||
| function getResource(pkg, ns) { | ||
| // A namespace is a locale file name. Reject anything that could leave the locale directory. | ||
| if (!/^[\w.-]+$/.test(ns)) return undefined | ||
| const id = `${pkg}:${ns}` | ||
| if (!(id in resources)) { | ||
| const file = path.join(ROOT, pkg === "src" ? "src" : "webview-ui/src", "i18n/locales/en", `${ns}.json`) | ||
| resources[id] = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, "utf8")) : undefined | ||
| } | ||
| return resources[id] | ||
| } | ||
|
|
||
| function lookup(resource, keyPath) { | ||
| let node = resource | ||
| for (const part of keyPath.split(".")) { | ||
| if (node === null || typeof node !== "object" || !(part in node)) return undefined | ||
| node = node[part] | ||
| } | ||
| return node | ||
| } | ||
|
|
||
| // "Exited with {{exitCode}}" and "{{- name}}" and "{{n, number}}" -> exitCode, name, n | ||
| function placeholders(value) { | ||
| return [...value.matchAll(/\{\{-?\s*([\w$]+)[^}]*\}\}/g)].map((m) => m[1]) | ||
| } | ||
|
|
||
| const problems = [] | ||
|
|
||
| for (const rel of files) { | ||
| const pkg = rel.startsWith("src/") ? "src" : "webview-ui" | ||
| const source = fs.readFileSync(path.join(ROOT, rel), "utf8") | ||
| const sf = ts.createSourceFile( | ||
| rel, | ||
| source, | ||
| ts.ScriptTarget.Latest, | ||
| true, | ||
| rel.endsWith("x") ? ts.ScriptKind.TSX : ts.ScriptKind.TS, | ||
| ) | ||
|
|
||
| const visit = (node) => { | ||
| if (ts.isCallExpression(node)) { | ||
| const callee = node.expression | ||
| const isT = | ||
| (ts.isIdentifier(callee) && callee.text === "t") || | ||
| (ts.isPropertyAccessExpression(callee) && callee.name.text === "t") | ||
| const [keyArg, optionsArg] = node.arguments | ||
| if ( | ||
| isT && | ||
| keyArg && | ||
| ts.isStringLiteralLike(keyArg) && | ||
| keyArg.text.includes(":") && | ||
| optionsArg && | ||
| ts.isObjectLiteralExpression(optionsArg) && | ||
| !optionsArg.properties.some(ts.isSpreadAssignment) | ||
| ) { | ||
| // i18next splits on the first ":" and joins the rest with "." | ||
| const [ns, ...rest] = keyArg.text.split(":") | ||
| const keyPath = rest.join(".") | ||
| const resource = getResource(pkg, ns) | ||
| if (resource) { | ||
| const passed = new Set( | ||
| optionsArg.properties.map( | ||
| (p) => p.name && (ts.isIdentifier(p.name) || ts.isStringLiteral(p.name)) && p.name.text, | ||
| ), | ||
| ) | ||
| // A plural key lives under key_one, key_other, and so on. | ||
| const values = [keyPath, `${keyPath}_zero`, `${keyPath}_one`, `${keyPath}_other`] | ||
| .map((k) => lookup(resource, k)) | ||
| .filter((v) => typeof v === "string") | ||
| const missing = new Set(values.flatMap(placeholders).filter((name) => !passed.has(name))) | ||
| if (missing.size > 0) { | ||
| const { line } = sf.getLineAndCharacterOfPosition(node.getStart()) | ||
| problems.push( | ||
| `${rel}:${line + 1} t("${keyArg.text}") does not pass: ${[...missing].join(", ")}`, | ||
| ) | ||
| } | ||
| } | ||
| } | ||
| } | ||
| ts.forEachChild(node, visit) | ||
| } | ||
| visit(sf) | ||
| } | ||
|
|
||
| if (problems.length > 0) { | ||
| console.error(`Found ${problems.length} t() call(s) missing an interpolation variable:\n${problems.join("\n")}`) | ||
| process.exit(1) | ||
| } | ||
| console.log(`OK: checked ${files.length} files, no missing interpolation variables.`) | ||
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
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.