From acdd6c5c36162d5f9643c7f42202efc8508097b1 Mon Sep 17 00:00:00 2001 From: Stefano Caldarini Date: Fri, 13 Nov 2026 10:25:29 +0100 Subject: [PATCH 1/2] style: apply Prettier to files already failing format:check on main --- src/cli/cmd/glossary/glossary.ts | 44 +++++++++++++++++++---------- src/cli/cmd/memory/memory.ts | 48 +++++++++++++++++++------------- src/utils/error.ts | 1 - 3 files changed, 58 insertions(+), 35 deletions(-) diff --git a/src/cli/cmd/glossary/glossary.ts b/src/cli/cmd/glossary/glossary.ts index 17823be..7eb3617 100644 --- a/src/cli/cmd/glossary/glossary.ts +++ b/src/cli/cmd/glossary/glossary.ts @@ -37,7 +37,10 @@ glossaryCommand .helpOption('-h, --help', 'Show help') .action(async (name: string | undefined, _options: unknown, command: Command) => { ensureCredentials(); - await runSafely(() => createGlossary(name, isRunningInInteractiveMode(command)), 'glossary create'); + await runSafely( + () => createGlossary(name, isRunningInInteractiveMode(command)), + 'glossary create' + ); }); glossaryCommand @@ -52,7 +55,10 @@ glossaryCommand command: Command ) => { ensureCredentials(); - await runSafely(() => updateGlossary(id, name, isRunningInInteractiveMode(command)), 'glossary update'); + await runSafely( + () => updateGlossary(id, name, isRunningInInteractiveMode(command)), + 'glossary update' + ); } ); @@ -62,7 +68,10 @@ glossaryCommand .helpOption('-h, --help', 'Show help') .action(async (id: string | undefined, _options: unknown, command: Command) => { ensureCredentials(); - await runSafely(() => deleteGlossary(id, isRunningInInteractiveMode(command)), 'glossary delete'); + await runSafely( + () => deleteGlossary(id, isRunningInInteractiveMode(command)), + 'glossary delete' + ); }); glossaryCommand @@ -80,15 +89,16 @@ glossaryCommand command: Command ) => { ensureCredentials(); - await runSafely(() => - addEntry( - id, - sourceLang, - sourceTerm, - targetLang, - targetTerm, - isRunningInInteractiveMode(command) - ), + await runSafely( + () => + addEntry( + id, + sourceLang, + sourceTerm, + targetLang, + targetTerm, + isRunningInInteractiveMode(command) + ), 'glossary add-entry' ); } @@ -107,7 +117,10 @@ glossaryCommand command: Command ) => { ensureCredentials(); - await runSafely(() => deleteEntry(id, language, value, isRunningInInteractiveMode(command)), 'glossary delete-entry'); + await runSafely( + () => deleteEntry(id, language, value, isRunningInInteractiveMode(command)), + 'glossary delete-entry' + ); } ); @@ -123,7 +136,10 @@ glossaryCommand command: Command ) => { ensureCredentials(); - await runSafely(() => importCsv(id, file, isRunningInInteractiveMode(command)), 'glossary import-csv'); + await runSafely( + () => importCsv(id, file, isRunningInInteractiveMode(command)), + 'glossary import-csv' + ); } ); diff --git a/src/cli/cmd/memory/memory.ts b/src/cli/cmd/memory/memory.ts index eb07dec..248d6f2 100644 --- a/src/cli/cmd/memory/memory.ts +++ b/src/cli/cmd/memory/memory.ts @@ -52,7 +52,10 @@ memoryCommand command: Command ) => { ensureCredentials(); - await runSafely(() => updateMemory(id, name, isRunningInInteractiveMode(command)), 'memory update'); + await runSafely( + () => updateMemory(id, name, isRunningInInteractiveMode(command)), + 'memory update' + ); } ); @@ -80,15 +83,16 @@ memoryCommand command: Command ) => { ensureCredentials(); - await runSafely(() => - addTranslation( - id, - source, - target, - sentence, - translation, - isRunningInInteractiveMode(command) - ), + await runSafely( + () => + addTranslation( + id, + source, + target, + sentence, + translation, + isRunningInInteractiveMode(command) + ), 'memory add-translation' ); } @@ -109,15 +113,16 @@ memoryCommand command: Command ) => { ensureCredentials(); - await runSafely(() => - deleteTranslation( - id, - source, - target, - sentence, - translation, - isRunningInInteractiveMode(command) - ), + await runSafely( + () => + deleteTranslation( + id, + source, + target, + sentence, + translation, + isRunningInInteractiveMode(command) + ), 'memory delete-translation' ); } @@ -135,7 +140,10 @@ memoryCommand command: Command ) => { ensureCredentials(); - await runSafely(() => importTmx(id, file, isRunningInInteractiveMode(command)), 'memory import-tmx'); + await runSafely( + () => importTmx(id, file, isRunningInInteractiveMode(command)), + 'memory import-tmx' + ); } ); diff --git a/src/utils/error.ts b/src/utils/error.ts index 45aeb61..d330380 100644 --- a/src/utils/error.ts +++ b/src/utils/error.ts @@ -95,4 +95,3 @@ function displayError(message: string, spinner: OraSpinner): string { spinner.fail(message); return message; } - From 51b440419cfce6908202cc7e9ee2b8389a5eb1eb Mon Sep 17 00:00:00 2001 From: Stefano Caldarini Date: Fri, 13 Nov 2026 10:25:29 +0100 Subject: [PATCH 2/2] feat: ignore keys only for selected target locales (1.9.0) ignoredKeys entries can now be an object { path, locales } to ignore a key only for the listed target locales. Plain string entries keep applying to every target locale, and both forms can be mixed. - Schema: union of KeyPath and { path, locales }; a locale not in locales.target is a config error (catches typos such as de vs de-DE). Entries are not transformed, so commands that rewrite lara.yaml keep the user's syntax. - Engine: isIgnored() takes the target locale being processed. - Tests: schema tests, config round-trip, a 3-phase multi-locale scenario for all 10 formats, and JSON edge cases (mixed rules, source deletion, includeKeys, --target, invalid config). - Docs: per-language ignored keys section in docs/config/files.md. - Version bumped to 1.9.0 (package.json and README badge). --- README.md | 2 +- docs/config/files.md | 64 +++++++- docs/config/structure.md | 4 +- package.json | 2 +- .../android-xml.integration.test.ts | 16 ++ .../integration/json.integration.test.ts | 136 ++++++++++++++++- .../integration/markdown.integration.test.ts | 14 ++ .../integration/per-locale-ignore.helper.ts | 143 ++++++++++++++++++ .../integration/po.integration.test.ts | 20 +++ .../integration/ts.integration.test.ts | 19 +++ .../integration/txt.integration.test.ts | 13 ++ .../integration/vue.integration.test.ts | 19 +++ .../xcode-strings.integration.test.ts | 13 ++ .../xcode-stringsdict.integration.test.ts | 49 ++++++ .../xcode-xcstrings.integration.test.ts | 37 +++++ .../utils/config-ignored-keys.test.ts | 138 +++++++++++++++++ src/__tests__/utils/config-sync.test.ts | 13 ++ src/messages/messages.ts | 2 + src/modules/config/config.types.ts | 49 +++++- src/modules/translation/translation.engine.ts | 26 ++-- 20 files changed, 761 insertions(+), 18 deletions(-) create mode 100644 src/__tests__/integration/per-locale-ignore.helper.ts create mode 100644 src/__tests__/utils/config-ignored-keys.test.ts diff --git a/README.md b/README.md index 0fce74f..5340361 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ Lara Cli automates translation of your i18n files with a single command, preserv Supports multiple file formats including JSON, PO (gettext), TypeScript, Vue I18n single-file components, Markdown and MDX files, Android XML string resource files, Xcode localization files (.strings, .stringsdict, .xcstrings), and plain text (.txt) files. See [Supported Formats](docs/config/formats.md) for details. -[![Version](https://img.shields.io/badge/version-1.7.3-blue.svg)](https://github.com/translated/lara-cli) +[![Version](https://img.shields.io/badge/version-1.9.0-blue.svg)](https://github.com/translated/lara-cli) diff --git a/docs/config/files.md b/docs/config/files.md index 1e821ea..7f75b06 100644 --- a/docs/config/files.md +++ b/docs/config/files.md @@ -24,6 +24,8 @@ files: - "config/*/url" ignoredKeys: - "internal/**" + - path: "legal/**" + locales: ["de-DE", "fr-FR"] includeKeys: - "ui/**" - "messages/**" @@ -54,9 +56,9 @@ files: ### ignoredKeys -- **Type**: Array of strings (key patterns) +- **Type**: Array of key patterns, or of `{ path, locales }` objects - **Required**: No (defaults to empty array) -- **Description**: Identifies keys that should be left untouched in target files (not translated, not added, not removed) +- **Description**: Identifies keys that should be left untouched in target files (not translated, not added, not removed). A plain pattern applies to every target locale; the object form applies only to the listed target locales (see [Per-Language Ignored Keys](#per-language-ignored-keys)) - **Format**: Uses glob patterns for matching keys (e.g., `internal/**`, `**/debug`) ### includeKeys @@ -166,6 +168,64 @@ Target file (`es.json`) - if `debug` already existed: Note: The `debug` key is never translated or modified by Lara. If it already exists in the target, it is preserved as-is. If it does not exist, it is not added. +### Per-Language Ignored Keys + +To ignore a key only for some target locales, write the entry as an object with the key pattern in `path` and the target locales in `locales`. Plain string entries keep applying to every target locale, and both forms can be mixed in the same list. + +**Example:** + +Configuration (targets `it-IT`, `de-DE` and `fr-FR`): + +```yaml +locales: + source: en-US + target: [it-IT, de-DE, fr-FR] + +files: + json: + include: + - "src/i18n/[locale].json" + ignoredKeys: + - "**/debug" # every target locale + - path: "legal/**" # only de-DE and fr-FR + locales: [de-DE, fr-FR] +``` + +Source file (`en-US.json`): + +```json +{ + "title": "My Application", + "legal": { + "terms": "Terms of service" + } +} +``` + +Target file (`it-IT.json`): `legal/**` is translated as usual. + +```json +{ + "title": "La mia applicazione", + "legal": { + "terms": "Termini di servizio" + } +} +``` + +Target file (`de-DE.json`): `legal/**` behaves exactly like an ignored key. Here the key did not exist yet, so it is not added; an existing value (for example a legally reviewed text) would be preserved as-is, even when the source changes. + +```json +{ + "title": "Meine Anwendung" +} +``` + +Rules: + +- `locales` must be a non-empty list, and every locale in it must be listed in `locales.target`; otherwise the configuration is rejected (for example `files.json.ignoredKeys.1.locales: Locale "de" is not a target locale`). This catches typos such as `de` instead of `de-DE`, which would otherwise silently translate the key. +- When you narrow the run with `--target`, each rule still applies only to the locales it lists. + ### Include Keys Keys listed in `includeKeys` define a whitelist: only matching keys are translated. All non-matching keys behave as if they were ignored. When `includeKeys` is empty (the default), all keys are in scope. diff --git a/docs/config/structure.md b/docs/config/structure.md index 33129f0..cc7562a 100644 --- a/docs/config/structure.md +++ b/docs/config/structure.md @@ -71,7 +71,9 @@ files: - "**/id" - "config/*/url" ignoredKeys: - - "internal/**" + - "internal/**" # Ignored for every target locale + - path: "legal/**" # Ignored only for the listed target locales + locales: ["de-DE"] fileInstructions: - path: "src/i18n/[locale]/common.json" instruction: "Common UI elements" diff --git a/package.json b/package.json index 1ec0343..cdf49d3 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@translated/lara-cli", "type": "module", - "version": "1.8.0", + "version": "1.9.0", "description": "CLI tool for automated i18n file translation using Lara Translate", "repository": { "type": "git", diff --git a/src/__tests__/integration/android-xml.integration.test.ts b/src/__tests__/integration/android-xml.integration.test.ts index 7b37844..abee2af 100644 --- a/src/__tests__/integration/android-xml.integration.test.ts +++ b/src/__tests__/integration/android-xml.integration.test.ts @@ -7,6 +7,7 @@ import { fileURLToPath } from 'url'; import yaml from 'yaml'; import { executeCommand, mockTranslateBatchWithFallback } from './test-helpers.js'; +import { runPerLocaleIgnoreScenario } from './per-locale-ignore.helper.js'; import initCommand from '../../cli/cmd/init/init.js'; import translateCommand from '../../cli/cmd/translate/translate.js'; import { ConfigProvider } from '#modules/config/config.provider.js'; @@ -776,4 +777,19 @@ describe('Android XML Repository Integration Tests', () => { const [, , , batchOptions] = mockTranslateBatchWithFallback.mock.calls[0]!; expect((batchOptions as any).contentType).toBe('text/html'); }); + + it('should ignore a key only for the target locales listed in its ignoredKeys rule', async () => { + await runPerLocaleIgnoreScenario(testDir, { + fileType: 'xml', + paths: 'res/[locale]/strings.xml', + ignoredKey: 'secret', + file: (locale) => `res/${locale}/strings.xml`, + source: ` + + Secret old + Plain old + +`, + }); + }); }); diff --git a/src/__tests__/integration/json.integration.test.ts b/src/__tests__/integration/json.integration.test.ts index 630aeb1..cd389fb 100644 --- a/src/__tests__/integration/json.integration.test.ts +++ b/src/__tests__/integration/json.integration.test.ts @@ -6,7 +6,12 @@ import { fileURLToPath } from 'url'; import yaml from 'yaml'; -import { executeCommand } from './test-helpers.js'; +import { executeCommand, mockTranslateBatchWithFallback } from './test-helpers.js'; +import { + initProject, + patchConfig, + runPerLocaleIgnoreScenario, +} from './per-locale-ignore.helper.js'; import initCommand from '../../cli/cmd/init/init.js'; import translateCommand from '../../cli/cmd/translate/translate.js'; import { ConfigProvider } from '#modules/config/config.provider.js'; @@ -859,4 +864,133 @@ describe('JSON Repository Integration Tests', () => { // Not included → not added to new target expect(itContent.app?.name).toBeUndefined(); }); + + it('should ignore a key only for the target locales listed in its ignoredKeys rule', async () => { + await runPerLocaleIgnoreScenario(testDir, { + fileType: 'json', + paths: 'i18n/locales/[locale].json', + ignoredKey: 'secret', + file: (locale) => `i18n/locales/${locale}.json`, + source: `{ + "secret": "Secret old", + "plain": "Plain old" +} +`, + }); + }); + + describe('per-locale ignoredKeys', () => { + const localesDir = () => path.join(testDir, 'i18n', 'locales'); + const writeJson = async (locale: string, data: unknown) => { + await mkdir(localesDir(), { recursive: true }); + await writeFile(path.join(localesDir(), `${locale}.json`), JSON.stringify(data, null, 2)); + }; + const readJson = async (locale: string) => + JSON.parse(await readFile(path.join(localesDir(), `${locale}.json`), 'utf-8')); + const init = (targets: string) => initProject(targets, 'i18n/locales/[locale].json'); + const setFileConfig = (fields: Record) => + patchConfig(testDir, (config) => Object.assign(config.files.json, fields)); + + it('combines global and per-locale rules', async () => { + await writeJson('en', { + internal: { debug: 'Debug' }, + legal: { terms: 'Terms', privacy: 'Privacy' }, + promo: { banner: 'Sale' }, + title: 'Title', + }); + await init('it,fr,de'); + await setFileConfig({ + ignoredKeys: [ + 'internal/**', + { path: 'legal/**', locales: ['fr', 'de'] }, + { path: 'promo/*', locales: ['it'] }, + ], + }); + + await executeCommand(translateCommand, []); + + const it = await readJson('it'); + expect(it).toEqual({ + legal: { terms: '[it] Terms', privacy: '[it] Privacy' }, + title: '[it] Title', + }); + for (const locale of ['fr', 'de']) { + expect(await readJson(locale)).toEqual({ + promo: { banner: `[${locale}] Sale` }, + title: `[${locale}] Title`, + }); + } + }); + + it('does not call the API for locales where the key is ignored', async () => { + mockTranslateBatchWithFallback.mockClear(); + await writeJson('en', { secret: 'Secret', plain: 'Plain' }); + await init('it,fr'); + await setFileConfig({ ignoredKeys: [{ path: 'secret', locales: ['fr'] }] }); + + await executeCommand(translateCommand, []); + + const sentTo = (locale: string) => + mockTranslateBatchWithFallback.mock.calls + .filter((call) => call[2] === locale) + .flatMap((call) => call[0].map((block) => block.text)); + expect(sentTo('it').sort()).toEqual(['Plain', 'Secret']); + expect(sentTo('fr')).toEqual(['Plain']); + }); + + it('removes a source-deleted key only where it is not ignored', async () => { + await writeJson('en', { secret: 'Secret', plain: 'Plain' }); + await init('it,fr'); + await executeCommand(translateCommand, []); + expect((await readJson('fr')).secret).toBe('[fr] Secret'); + + await setFileConfig({ ignoredKeys: [{ path: 'secret', locales: ['fr'] }] }); + await writeJson('en', { plain: 'Plain' }); + await executeCommand(translateCommand, []); + + expect(await readJson('it')).toEqual({ plain: '[it] Plain' }); + expect(await readJson('fr')).toEqual({ secret: '[fr] Secret', plain: '[fr] Plain' }); + }); + + it('applies on top of includeKeys', async () => { + await writeJson('en', { ui: { title: 'Title', legal: 'Legal' }, other: 'Other' }); + await init('it,fr'); + await setFileConfig({ + includeKeys: ['ui/**'], + ignoredKeys: [{ path: 'ui/legal', locales: ['fr'] }], + }); + + await executeCommand(translateCommand, []); + + expect(await readJson('it')).toEqual({ ui: { title: '[it] Title', legal: '[it] Legal' } }); + expect(await readJson('fr')).toEqual({ ui: { title: '[fr] Title' } }); + }); + + it('honours the rule when the targets are narrowed with --target', async () => { + await writeJson('en', { secret: 'Secret', plain: 'Plain' }); + await init('it,fr'); + await setFileConfig({ ignoredKeys: [{ path: 'secret', locales: ['fr'] }] }); + + await executeCommand(translateCommand, ['--target', 'it']); + expect(await readJson('it')).toEqual({ secret: '[it] Secret', plain: '[it] Plain' }); + expect(existsSync(path.join(localesDir(), 'fr.json'))).toBe(false); + + await executeCommand(translateCommand, ['--target', 'fr', '--force']); + expect(await readJson('fr')).toEqual({ plain: '[fr] Plain' }); + }); + + it('rejects a rule naming a locale that is not a target', async () => { + await writeJson('en', { secret: 'Secret' }); + await init('it,fr'); + await setFileConfig({ ignoredKeys: ['internal/**', { path: 'secret', locales: ['es'] }] }); + + await expect(executeCommand(translateCommand, [])).rejects.toThrow(); + expect(existsSync(path.join(localesDir(), 'it.json'))).toBe(false); + + (ConfigProvider as any).instance = null; + expect(() => ConfigProvider.getInstance().getConfig()).toThrow( + /files\.json\.ignoredKeys\.1\.locales: Locale "es" is not a target locale/ + ); + }); + }); }); diff --git a/src/__tests__/integration/markdown.integration.test.ts b/src/__tests__/integration/markdown.integration.test.ts index 0e04bb3..d9095fe 100644 --- a/src/__tests__/integration/markdown.integration.test.ts +++ b/src/__tests__/integration/markdown.integration.test.ts @@ -7,6 +7,7 @@ import { fileURLToPath } from 'url'; import yaml from 'yaml'; import { executeCommand } from './test-helpers.js'; +import { runPerLocaleIgnoreScenario } from './per-locale-ignore.helper.js'; import initCommand from '../../cli/cmd/init/init.js'; import translateCommand from '../../cli/cmd/translate/translate.js'; import { ConfigProvider } from '#modules/config/config.provider.js'; @@ -900,4 +901,17 @@ Welcome to our documentation. // Non-included segment should be preserved expect(contentAfter).toContain('[it] Welcome to our documentation'); }); + + it('should ignore a key only for the target locales listed in its ignoredKeys rule', async () => { + await runPerLocaleIgnoreScenario(testDir, { + fileType: 'md', + paths: 'docs/[locale]/guide.md', + ignoredKey: 'segment_1', + file: (locale) => `docs/${locale}/guide.md`, + source: `# Plain old + +Secret old paragraph. +`, + }); + }); }); diff --git a/src/__tests__/integration/per-locale-ignore.helper.ts b/src/__tests__/integration/per-locale-ignore.helper.ts new file mode 100644 index 0000000..9804738 --- /dev/null +++ b/src/__tests__/integration/per-locale-ignore.helper.ts @@ -0,0 +1,143 @@ +import { expect } from 'vitest'; +import { mkdir, readFile, writeFile } from 'fs/promises'; +import path from 'path'; + +import yaml from 'yaml'; + +import { executeCommand } from './test-helpers.js'; +import initCommand from '../../cli/cmd/init/init.js'; +import translateCommand from '../../cli/cmd/translate/translate.js'; +import { ConfigProvider } from '#modules/config/config.provider.js'; + +/** + * Format adapter for {@link runPerLocaleIgnoreScenario}. The source holds two + * keys: the ignored one, whose value contains "Secret old", and a control one, + * whose value contains "Plain old". The scenario switches both to "new". + */ +export type PerLocaleIgnoreFormat = { + /** Key under `files` in lara.yaml (e.g. `json`, `xml`, `xcode-strings`). */ + fileType: string; + /** Value passed to `init --paths`. */ + paths: string; + /** Key pattern of the entry to ignore. */ + ignoredKey: string; + /** Path of a locale's file, relative to the project. Same for every locale in single-file formats. */ + file: (locale: string) => string; + /** Initial source content. */ + source: string; +}; + +/** Runs `init` non-interactively with the given targets and include path. */ +export async function initProject(targets: string, paths: string): Promise { + await executeCommand(initCommand, [ + '--non-interactive', + '--source', + 'en', + '--target', + targets, + '--paths', + paths, + ]); + (ConfigProvider as any).instance = null; +} + +/** Structurally edits lara.yaml, then reloads it. */ +export async function patchConfig(testDir: string, mutate: (config: any) => void): Promise { + const configPath = path.join(testDir, 'lara.yaml'); + const config = yaml.parse(await readFile(configPath, 'utf-8')); + mutate(config); + await writeFile(configPath, yaml.stringify(config)); + (ConfigProvider as any).instance = null; +} + +/** + * Replaces quote-delimited occurrences only, so `"Secret old"` in the source + * changes but `"[it] Secret old"` in a translation stored in the same file does not. + */ +function replaceQuoted(content: string, from: string, to: string): string { + const escaped = from.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const updated = content.replace(new RegExp(`(["'])${escaped}\\1`, 'g'), `$1${to}$1`); + if (updated === content) { + throw new Error(`replaceQuoted: no quoted "${from}" found`); + } + return updated; +} + +/** + * End-to-end scenario for `ignoredKeys: [{ path, locales }]` with several + * target locales: + * + * 1. No rule, targets it+fr: both locales get every key. + * 2. Rule for fr only, source values change: it is re-translated, fr keeps its + * old value for the ignored key while its other key is re-translated. + * 3. New target de added to the rule: de never receives the ignored key, + * it and fr are unaffected, and the source is still intact. + */ +export async function runPerLocaleIgnoreScenario( + testDir: string, + format: PerLocaleIgnoreFormat +): Promise { + const read = (locale: string) => readFile(path.join(testDir, format.file(locale)), 'utf-8'); + const sourcePath = path.join(testDir, format.file('en')); + // Single-file formats (i18n.ts, Vue, .xcstrings) store every locale in the source file. + const singleFile = format.file('en') === format.file('it'); + + await mkdir(path.dirname(sourcePath), { recursive: true }); + await writeFile(sourcePath, format.source); + await initProject('it,fr', format.paths); + + // Phase 1: no rule. + await executeCommand(translateCommand, []); + for (const locale of ['it', 'fr']) { + const content = await read(locale); + expect(content).toContain(`[${locale}] Secret old`); + expect(content).toContain(`[${locale}] Plain old`); + } + + // Phase 2: ignore the key for fr only, then change the source. + await patchConfig(testDir, (config) => { + config.files[format.fileType].ignoredKeys = [{ path: format.ignoredKey, locales: ['fr'] }]; + }); + const replace = singleFile + ? replaceQuoted + : (content: string, from: string, to: string) => content.replaceAll(from, to); + const current = await readFile(sourcePath, 'utf-8'); + await writeFile( + sourcePath, + replace(replace(current, 'Secret old', 'Secret new'), 'Plain old', 'Plain new') + ); + await executeCommand(translateCommand, []); + + const it2 = await read('it'); + expect(it2).toContain('[it] Secret new'); + expect(it2).toContain('[it] Plain new'); + expect(it2).not.toContain('[it] Secret old'); + + const fr2 = await read('fr'); + expect(fr2).toContain('[fr] Secret old'); + expect(fr2).not.toContain('[fr] Secret new'); + expect(fr2).toContain('[fr] Plain new'); + + // Phase 3: add de as a target, ignored too. + await patchConfig(testDir, (config) => { + config.locales.target = ['it', 'fr', 'de']; + config.files[format.fileType].ignoredKeys = [ + { path: format.ignoredKey, locales: ['fr', 'de'] }, + ]; + }); + await executeCommand(translateCommand, []); + + const de3 = await read('de'); + expect(de3).toContain('[de] Plain new'); + expect(de3).not.toContain('[de] Secret'); + + const fr3 = await read('fr'); + expect(fr3).toContain('[fr] Secret old'); + expect(fr3).not.toContain('[fr] Secret new'); + + const it3 = await read('it'); + expect(it3).toContain('[it] Secret new'); + + // The source must still hold the ignored key: an untranslated occurrence, not "[xx] Secret new". + expect(await read('en')).toMatch(/(? { + await runPerLocaleIgnoreScenario(testDir, { + fileType: 'po', + paths: 'locales/[locale]/messages.po', + ignoredKey: '*secret_msg*', + file: (locale) => `locales/${locale}/messages.po`, + source: `msgid "" +msgstr "" +"Content-Type: text/plain; charset=UTF-8\\n" + +msgid "secret_msg" +msgstr "Secret old" + +msgid "plain_msg" +msgstr "Plain old" +`, + }); + }); }); diff --git a/src/__tests__/integration/ts.integration.test.ts b/src/__tests__/integration/ts.integration.test.ts index de0a738..cfb9b98 100644 --- a/src/__tests__/integration/ts.integration.test.ts +++ b/src/__tests__/integration/ts.integration.test.ts @@ -11,6 +11,7 @@ import type { NodePath } from '@babel/traverse'; import yaml from 'yaml'; import { executeCommand } from './test-helpers.js'; +import { runPerLocaleIgnoreScenario } from './per-locale-ignore.helper.js'; import initCommand from '../../cli/cmd/init/init.js'; import translateCommand from '../../cli/cmd/translate/translate.js'; import { ConfigProvider } from '#modules/config/config.provider.js'; @@ -807,4 +808,22 @@ export default messages;` expect(contentAfter).toContain('[it] My App'); expect(contentAfter).toContain('[it] 1.0.0'); }); + + it('should ignore a key only for the target locales listed in its ignoredKeys rule', async () => { + await runPerLocaleIgnoreScenario(testDir, { + fileType: 'ts', + paths: 'src/i18n.ts', + ignoredKey: 'secret', + file: () => 'src/i18n.ts', + source: `const messages = { + en: { + secret: 'Secret old', + plain: 'Plain old', + }, +}; + +export default messages; +`, + }); + }); }); diff --git a/src/__tests__/integration/txt.integration.test.ts b/src/__tests__/integration/txt.integration.test.ts index 0cba186..623470f 100644 --- a/src/__tests__/integration/txt.integration.test.ts +++ b/src/__tests__/integration/txt.integration.test.ts @@ -7,6 +7,7 @@ import { fileURLToPath } from 'url'; import yaml from 'yaml'; import { executeCommand } from './test-helpers.js'; +import { runPerLocaleIgnoreScenario } from './per-locale-ignore.helper.js'; import initCommand from '../../cli/cmd/init/init.js'; import translateCommand from '../../cli/cmd/translate/translate.js'; import { ConfigProvider } from '#modules/config/config.provider.js'; @@ -492,4 +493,16 @@ describe('TXT Repository Integration Tests', () => { // Non-included line should be preserved expect(contentAfter).toContain('[it] Keep this'); }); + + it('should ignore a key only for the target locales listed in its ignoredKeys rule', async () => { + await runPerLocaleIgnoreScenario(testDir, { + fileType: 'txt', + paths: 'texts/[locale]/messages.txt', + ignoredKey: 'line_1', + file: (locale) => `texts/${locale}/messages.txt`, + source: `Plain old +Secret old +`, + }); + }); }); diff --git a/src/__tests__/integration/vue.integration.test.ts b/src/__tests__/integration/vue.integration.test.ts index 9db73fd..fd55383 100644 --- a/src/__tests__/integration/vue.integration.test.ts +++ b/src/__tests__/integration/vue.integration.test.ts @@ -7,6 +7,7 @@ import { fileURLToPath } from 'url'; import yaml from 'yaml'; import { executeCommand } from './test-helpers.js'; +import { runPerLocaleIgnoreScenario } from './per-locale-ignore.helper.js'; import initCommand from '../../cli/cmd/init/init.js'; import translateCommand from '../../cli/cmd/translate/translate.js'; import { ConfigProvider } from '#modules/config/config.provider.js'; @@ -809,4 +810,22 @@ describe('Vue Repository Integration Tests', () => { // Non-included key should be preserved expect(contentAfter).toContain('[it] Goodbye'); }); + + it('should ignore a key only for the target locales listed in its ignoredKeys rule', async () => { + await runPerLocaleIgnoreScenario(testDir, { + fileType: 'vue', + paths: 'src/components/*.vue', + ignoredKey: 'secret', + file: () => 'src/components/Hello.vue', + source: ` +{ + "en": { + "secret": "Secret old", + "plain": "Plain old" + } +} + +`, + }); + }); }); diff --git a/src/__tests__/integration/xcode-strings.integration.test.ts b/src/__tests__/integration/xcode-strings.integration.test.ts index 5964dab..afbb375 100644 --- a/src/__tests__/integration/xcode-strings.integration.test.ts +++ b/src/__tests__/integration/xcode-strings.integration.test.ts @@ -7,6 +7,7 @@ import { fileURLToPath } from 'url'; import yaml from 'yaml'; import { executeCommand } from './test-helpers.js'; +import { runPerLocaleIgnoreScenario } from './per-locale-ignore.helper.js'; import initCommand from '../../cli/cmd/init/init.js'; import translateCommand from '../../cli/cmd/translate/translate.js'; import { ConfigProvider } from '#modules/config/config.provider.js'; @@ -555,4 +556,16 @@ describe('Xcode .strings Repository Integration Tests', () => { expect(contentAfter).toContain('[it] Hello World'); expect(contentAfter).toContain('[it] Welcome to the app'); }); + + it('should ignore a key only for the target locales listed in its ignoredKeys rule', async () => { + await runPerLocaleIgnoreScenario(testDir, { + fileType: 'xcode-strings', + paths: '[locale].lproj/Localizable.strings', + ignoredKey: 'secret', + file: (locale) => `${locale}.lproj/Localizable.strings`, + source: `"secret" = "Secret old"; +"plain" = "Plain old"; +`, + }); + }); }); diff --git a/src/__tests__/integration/xcode-stringsdict.integration.test.ts b/src/__tests__/integration/xcode-stringsdict.integration.test.ts index 359c4dc..79ac370 100644 --- a/src/__tests__/integration/xcode-stringsdict.integration.test.ts +++ b/src/__tests__/integration/xcode-stringsdict.integration.test.ts @@ -7,6 +7,7 @@ import { fileURLToPath } from 'url'; import yaml from 'yaml'; import { executeCommand } from './test-helpers.js'; +import { runPerLocaleIgnoreScenario } from './per-locale-ignore.helper.js'; import initCommand from '../../cli/cmd/init/init.js'; import translateCommand from '../../cli/cmd/translate/translate.js'; import { ConfigProvider } from '#modules/config/config.provider.js'; @@ -1148,4 +1149,52 @@ describe('Xcode .stringsdict Repository Integration Tests', () => { expect(contentAfter).toContain('[it] %d item'); expect(contentAfter).toContain('[it] %d items'); }); + + it('should ignore a key only for the target locales listed in its ignoredKeys rule', async () => { + await runPerLocaleIgnoreScenario(testDir, { + fileType: 'xcode-stringsdict', + paths: '[locale].lproj/Localizable.stringsdict', + ignoredKey: 'secret_count/*', + file: (locale) => `${locale}.lproj/Localizable.stringsdict`, + source: ` + + + + secret_count + + NSStringLocalizedFormatKey + %#@items@ + items + + NSStringFormatSpecTypeKey + NSStringPluralRuleType + NSStringFormatValueTypeKey + d + one + Secret old one: %d + other + Secret old other: %d + + + plain_count + + NSStringLocalizedFormatKey + %#@items@ + items + + NSStringFormatSpecTypeKey + NSStringPluralRuleType + NSStringFormatValueTypeKey + d + one + Plain old one: %d + other + Plain old other: %d + + + + +`, + }); + }); }); diff --git a/src/__tests__/integration/xcode-xcstrings.integration.test.ts b/src/__tests__/integration/xcode-xcstrings.integration.test.ts index bba8a7c..97da62f 100644 --- a/src/__tests__/integration/xcode-xcstrings.integration.test.ts +++ b/src/__tests__/integration/xcode-xcstrings.integration.test.ts @@ -7,6 +7,7 @@ import { fileURLToPath } from 'url'; import yaml from 'yaml'; import { executeCommand } from './test-helpers.js'; +import { runPerLocaleIgnoreScenario } from './per-locale-ignore.helper.js'; import initCommand from '../../cli/cmd/init/init.js'; import translateCommand from '../../cli/cmd/translate/translate.js'; import { ConfigProvider } from '#modules/config/config.provider.js'; @@ -1004,4 +1005,40 @@ describe('Xcode .xcstrings Repository Integration Tests', () => { expect(consoleErrorSpy).toHaveBeenCalled(); consoleErrorSpy.mockRestore(); }); + + it('should ignore a key only for the target locales listed in its ignoredKeys rule', async () => { + await runPerLocaleIgnoreScenario(testDir, { + fileType: 'xcode-xcstrings', + paths: 'Localizable.xcstrings', + ignoredKey: 'secret_key', + file: () => 'Localizable.xcstrings', + source: `{ + "sourceLanguage": "en", + "version": "1.0", + "strings": { + "secret_key": { + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "Secret old" } } + } + }, + "plain_key": { + "localizations": { + "en": { "stringUnit": { "state": "translated", "value": "Plain old" } } + } + } + } +} +`, + }); + + const content = JSON.parse( + await readFile(path.join(testDir, 'Localizable.xcstrings'), 'utf-8') + ); + const secret = content.strings.secret_key.localizations; + expect(secret.en.stringUnit.value).toBe('Secret new'); + expect(secret.it.stringUnit.value).toBe('[it] Secret new'); + expect(secret.fr.stringUnit.value).toBe('[fr] Secret old'); + expect(secret.de).toBeUndefined(); + expect(content.strings.plain_key.localizations.de.stringUnit.value).toBe('[de] Plain new'); + }); }); diff --git a/src/__tests__/utils/config-ignored-keys.test.ts b/src/__tests__/utils/config-ignored-keys.test.ts new file mode 100644 index 0000000..d8781c9 --- /dev/null +++ b/src/__tests__/utils/config-ignored-keys.test.ts @@ -0,0 +1,138 @@ +import { describe, it, expect } from 'vitest'; + +import { Config } from '#modules/config/config.types.js'; + +/** + * Schema-level coverage for per-locale `ignoredKeys` entries. The behaviour + * they drive is covered end to end in the per-format integration tests. + */ +function buildConfig(ignoredKeys?: unknown[], target: string[] = ['it', 'fr', 'de']) { + return { + version: '1.0.0', + locales: { source: 'en', target }, + files: { + json: { include: ['src/i18n/[locale].json'], ignoredKeys }, + }, + }; +} + +describe('config schema: ignoredKeys', () => { + it('defaults to an empty list', () => { + const parsed = Config.parse(buildConfig()); + + expect(parsed.files.json?.ignoredKeys).toEqual([]); + }); + + it('still accepts plain string patterns', () => { + const parsed = Config.parse(buildConfig(['internal/**', '**/debug'])); + + expect(parsed.files.json?.ignoredKeys).toEqual(['internal/**', '**/debug']); + }); + + it('accepts the per-locale object form and keeps it as written', () => { + const parsed = Config.parse(buildConfig([{ path: 'legal/**', locales: ['fr', 'de'] }])); + + expect(parsed.files.json?.ignoredKeys).toEqual([{ path: 'legal/**', locales: ['fr', 'de'] }]); + }); + + it('accepts a mix of strings and objects, preserving order', () => { + const ignoredKeys = ['internal/**', { path: 'legal/**', locales: ['fr'] }, '**/debug']; + const parsed = Config.parse(buildConfig(ignoredKeys)); + + expect(parsed.files.json?.ignoredKeys).toEqual(ignoredKeys); + }); + + it('rejects an empty locales list', () => { + const result = Config.safeParse(buildConfig([{ path: 'legal/**', locales: [] }])); + + expect(result.success).toBe(false); + }); + + it('rejects an object without locales', () => { + const result = Config.safeParse(buildConfig([{ path: 'legal/**' }])); + + expect(result.success).toBe(false); + }); + + it('rejects an object without path', () => { + const result = Config.safeParse(buildConfig([{ locales: ['fr'] }])); + + expect(result.success).toBe(false); + }); + + it('applies KeyPath validation to the object path', () => { + const result = Config.safeParse(buildConfig([{ path: '/legal', locales: ['fr'] }])); + + expect(result.success).toBe(false); + }); + + it('rejects an unknown locale code', () => { + const result = Config.safeParse(buildConfig([{ path: 'legal/**', locales: ['xx-NOPE'] }])); + + expect(result.success).toBe(false); + }); + + it('rejects a valid locale that is not a target, pointing at the offending entry', () => { + const result = Config.safeParse( + buildConfig(['internal/**', { path: 'legal/**', locales: ['fr', 'es'] }]) + ); + + expect(result.success).toBe(false); + const issues = result.error?.issues ?? []; + expect(issues).toHaveLength(1); + expect(issues[0]?.path).toEqual(['files', 'json', 'ignoredKeys', 1, 'locales']); + expect(issues[0]?.message).toContain('"es"'); + expect(issues[0]?.message).toContain('locales.target'); + }); + + it('rejects the source locale', () => { + const result = Config.safeParse(buildConfig([{ path: 'legal/**', locales: ['en'] }])); + + expect(result.success).toBe(false); + expect(result.error?.issues[0]?.message).toContain('"en"'); + }); + + it('reports one issue per non-target locale across file types', () => { + const result = Config.safeParse({ + version: '1.0.0', + locales: { source: 'en', target: ['it'] }, + files: { + json: { + include: ['src/i18n/[locale].json'], + ignoredKeys: [{ path: 'a', locales: ['fr', 'de'] }], + }, + po: { + include: ['locales/[locale].po'], + ignoredKeys: [ + { path: 'b', locales: ['it'] }, + { path: 'c', locales: ['es'] }, + ], + }, + }, + }); + + expect(result.success).toBe(false); + const paths = (result.error?.issues ?? []).map((issue) => issue.path.join('.')); + expect(paths).toEqual([ + 'files.json.ignoredKeys.0.locales', + 'files.json.ignoredKeys.0.locales', + 'files.po.ignoredKeys.1.locales', + ]); + }); + + it('accepts per-locale rules on several file types when all locales are targets', () => { + const result = Config.safeParse({ + version: '1.0.0', + locales: { source: 'en', target: ['it', 'fr'] }, + files: { + json: { + include: ['src/i18n/[locale].json'], + ignoredKeys: [{ path: 'a', locales: ['fr'] }], + }, + po: { include: ['locales/[locale].po'], ignoredKeys: [{ path: 'b', locales: ['it'] }] }, + }, + }); + + expect(result.success).toBe(true); + }); +}); diff --git a/src/__tests__/utils/config-sync.test.ts b/src/__tests__/utils/config-sync.test.ts index 2f325dc..e06d930 100644 --- a/src/__tests__/utils/config-sync.test.ts +++ b/src/__tests__/utils/config-sync.test.ts @@ -108,6 +108,19 @@ describe('addIdToConfig', () => { expect(config.locales.target).toEqual(['it']); expect(config.files.json.include).toEqual(['src/i18n/[locale].json']); }); + + it('preserves per-locale ignoredKeys entries as written when rewriting the config', async () => { + const ignoredKeys = ['internal/**', { path: 'legal/**', locales: ['it'] }]; + await writeConfig({ + ...baseConfig, + files: { json: { ...baseConfig.files.json, ignoredKeys } }, + }); + + expect(addIdToConfig('memories', 'mem_1')).toBe(true); + + const config = await readConfig(); + expect(config.files.json.ignoredKeys).toEqual(ignoredKeys); + }); }); describe('removeIdFromConfig', () => { diff --git a/src/messages/messages.ts b/src/messages/messages.ts index 3fd2914..4d982a8 100644 --- a/src/messages/messages.ts +++ b/src/messages/messages.ts @@ -10,6 +10,8 @@ export const Messages = { 'No target locales specified. Please add target locales in config or use -t option.', configNotFound: 'Config file not found. Please run `lara-cli init` to create a config file.', invalidConfig: (issues: string) => `Invalid configuration file. Issues found:\n${issues}`, + ignoredKeyLocaleNotTarget: (locale: string) => + `Locale "${locale}" is not a target locale (add it to locales.target or remove it from this rule)`, noApiCredentials: 'No API credentials found. Please run `lara-cli init` to set the API credentials.', apiAuthFailed: (context: string) => diff --git a/src/modules/config/config.types.ts b/src/modules/config/config.types.ts index 2dcc469..83fea9d 100644 --- a/src/modules/config/config.types.ts +++ b/src/modules/config/config.types.ts @@ -9,6 +9,7 @@ import { } from '../common/common.types.js'; import { SEARCHABLE_EXTENSIONS, SUPPORTED_FILE_TYPES } from '../common/common.const.js'; import { getFileType, isRelative } from '#utils/path.js'; +import { Messages } from '#messages/messages.js'; export const DEFAULT_BATCH_SIZE = 50; @@ -72,6 +73,18 @@ const KeyPath = z message: 'Key path must contain at least one non-wildcard segment', }); +/** + * An `ignoredKeys` entry: a bare key pattern ignores the key for every target + * locale; the object form ignores it only for the listed target locales. + */ +const IgnoredKey = z.union([ + KeyPath, + z.object({ + path: KeyPath, + locales: z.array(LocalesEnum).min(1), + }), +]); + const Config = z .object({ version: z.string(), @@ -134,7 +147,7 @@ const Config = z ) .default([]), lockedKeys: z.array(KeyPath).default([]), - ignoredKeys: z.array(KeyPath).default([]), + ignoredKeys: z.array(IgnoredKey).default([]), includeKeys: z.array(KeyPath).default([]), }) ), @@ -163,10 +176,40 @@ const Config = z { message: 'File type must match the file extension', } - ); + ) + .superRefine((data, ctx) => { + // A per-locale rule naming a non-target locale would silently never apply + // (typically a typo such as `de` vs `de-DE`), so reject it up front. + const targets = new Set(data.locales.target); + for (const [fileType, fileConfig] of Object.entries(data.files)) { + fileConfig?.ignoredKeys.forEach((entry, index) => { + if (typeof entry === 'string') { + return; + } + for (const locale of entry.locales) { + if (!targets.has(locale)) { + ctx.addIssue({ + code: 'custom', + path: ['files', fileType, 'ignoredKeys', index, 'locales'], + message: Messages.errors.ignoredKeyLocaleNotTarget(locale), + }); + } + } + }); + } + }); type ConfigType = z.infer; type OrphanKeysMode = (typeof ORPHAN_KEYS_MODES)[number]; -export { IncludeFilePath as FilePath, KeyPath, Config, type ConfigType, type OrphanKeysMode }; +type IgnoredKeyType = z.infer; + +export { + IncludeFilePath as FilePath, + KeyPath, + Config, + type ConfigType, + type OrphanKeysMode, + type IgnoredKeyType, +}; diff --git a/src/modules/translation/translation.engine.ts b/src/modules/translation/translation.engine.ts index 62a014a..7a26c2b 100644 --- a/src/modules/translation/translation.engine.ts +++ b/src/modules/translation/translation.engine.ts @@ -13,7 +13,7 @@ import { TextBlock } from './translation.service.js'; import { Memory, TranslateOptions } from '@translated/lara'; import { Messages } from '#messages/messages.js'; import { ParserFactory } from '../../parsers/parser.factory.js'; -import { OrphanKeysMode } from '#modules/config/config.types.js'; +import { IgnoredKeyType, OrphanKeysMode } from '#modules/config/config.types.js'; export type TranslationEngineOptions = { sourceLocale: string; @@ -26,7 +26,7 @@ export type TranslationEngineOptions = { forceTranslation: boolean; lockedKeys: string[]; - ignoredKeys: string[]; + ignoredKeys: IgnoredKeyType[]; includeKeys: string[]; projectInstruction: string | undefined; @@ -73,7 +73,8 @@ export class TranslationEngine { private readonly forceTranslation: boolean; private readonly lockedPatterns: Matcher[]; - private readonly ignoredPatterns: Matcher[]; + // `locales` undefined = ignored for every target locale. + private readonly ignoredPatterns: Array<{ matcher: Matcher; locales?: Set }>; private readonly includePatterns: Matcher[]; private readonly projectInstruction: string | undefined; @@ -110,7 +111,11 @@ export class TranslationEngine { this.forceTranslation = options.forceTranslation; this.lockedPatterns = options.lockedKeys.map((pattern) => picomatch(pattern)); - this.ignoredPatterns = options.ignoredKeys.map((pattern) => picomatch(pattern)); + this.ignoredPatterns = options.ignoredKeys.map((entry) => + typeof entry === 'string' + ? { matcher: picomatch(entry) } + : { matcher: picomatch(entry.path), locales: new Set(entry.locales) } + ); this.includePatterns = options.includeKeys.map((pattern) => picomatch(pattern)); this.projectInstruction = options.projectInstruction; @@ -176,7 +181,7 @@ export class TranslationEngine { const target = this.parser.parse(targetContent, { targetLocale }); - const classified = this.classifyEntries(changelog, target); + const classified = this.classifyEntries(changelog, target, targetLocale); const { translations, failedTasks } = await this.executeTasks(classified, targetLocale); for (const task of failedTasks) { @@ -237,7 +242,8 @@ export class TranslationEngine { private classifyEntries( changelog: ReturnType['changelog'], - target: Record + target: Record, + targetLocale: string ): ClassifiedEntries { const ordered: Array<[string, OutputSlot]> = []; const solo: TranslateTask[] = []; @@ -249,7 +255,7 @@ export class TranslationEngine { const sourceValue = entry.value; const targetValue = target[key]; - if (!this.isIncluded(userKey) || this.isIgnored(userKey)) { + if (!this.isIncluded(userKey) || this.isIgnored(userKey, targetLocale)) { ordered.push([ key, targetValue !== undefined ? { kind: 'keep', value: targetValue } : { kind: 'omit' }, @@ -438,8 +444,10 @@ export class TranslationEngine { return key.replaceAll('\0', '/'); } - private isIgnored(userKey: string): boolean { - return this.ignoredPatterns.some((pattern) => pattern(userKey)); + private isIgnored(userKey: string, targetLocale: string): boolean { + return this.ignoredPatterns.some( + ({ matcher, locales }) => (!locales || locales.has(targetLocale)) && matcher(userKey) + ); } private isLocked(userKey: string): boolean {