Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

</div>

Expand Down
64 changes: 62 additions & 2 deletions docs/config/files.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ files:
- "config/*/url"
ignoredKeys:
- "internal/**"
- path: "legal/**"
locales: ["de-DE", "fr-FR"]
includeKeys:
- "ui/**"
- "messages/**"
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
4 changes: 3 additions & 1 deletion docs/config/structure.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
16 changes: 16 additions & 0 deletions src/__tests__/integration/android-xml.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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: `<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="secret">Secret old</string>
<string name="plain">Plain old</string>
</resources>
`,
});
});
});
136 changes: 135 additions & 1 deletion src/__tests__/integration/json.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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<string, unknown>) =>
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/
);
});
});
});
14 changes: 14 additions & 0 deletions src/__tests__/integration/markdown.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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.
`,
});
});
});
Loading
Loading