Skip to content

Commit 55d673c

Browse files
cli: os g prints one hint when the project declares other locales (#39432)
<!-- claude-projects-attribution: {"github_login":"os-elon-musk"} --> _Requested by **Elon** · [project thread](https://claude.ai/code/project/chan_01WedDzV26nniwxv7jC88B9D?thread=cmsg_01WedDzV26nniwxv7jC88B9DMmPgXVVfb8MdCS5amdMX6N)_ Fixes #39324 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:开发者在声明了多种语言的项目里用生成命令新建对象、视图等之后,会多看到一行提示:标签只写了源语言,请运行翻译检查命令,并说明翻译写在哪里;单语言项目看不到这行。 - 为什么做:落实"模板携带全部平台语言、生成器只写源语言"的裁决,让开发者知道其他语言还没翻译,而不是悄悄留下缺口。 - 出错会怎样:最坏情况是提示该出现时没出现或多出现一行,不会写入或改动任何文件;改动可直接撤回。 - 要你做什么:无。 ## What changes - New module `packages/cli/src/utils/generate-locale-hint.ts`: `declaredOtherLocales(config)` reads the loaded stack the way `os i18n check` reads it (`normalizeStackInput` then `authoringRuleUnionStack`; source locale through `resolveSourceLocale`, i.e. `sourceLocale`, else `defaultLocale`, else `en`; declared locales through `withGatedDefaultLocale` over `supportedLocales`) and answers the declared locales minus the source. `reportGenerateLocaleHint(config)` prints one `printInfo` line when that set is non-empty, nothing otherwise. - `packages/cli/src/commands/generate.ts` (4,664 lines, so the new concern lives in the sibling module): one import and one call, as the last statement of `runMetadataGeneration`, i.e. only after a successful write. A `--dry-run`, every refusal and the reach-refusal rollback return or exit before it. - The line (with all 11 platform locales declared, source `en`): ``Labels written in the source locale (en) only; this project also declares zh-Hans, zh-Hant, es and 7 more. Run `os i18n check` to list what is untranslated, and add translations to the stack's `translations` bundles (`os i18n extract` scaffolds them).`` - No translation stub is written (the card's ruling: coverage counts any string as translated). - Changeset `.changeset/39324-generate-locale-hint.md`, patch on `@objectstack/cli`. ## Tests New `packages/cli/test/generate-locale-hint-39324.test.ts` (unit tier, in-process `Generate.run` in a sandbox project under this package's `node_modules`): - all 11 `PLATFORM_LOCALE_TAGS` declared: exactly one hint line naming `en`, `zh-Hans, zh-Hant, es and 7 more`, `os i18n check` and `translations`; the tree afterwards is exactly the config, `src/objects/index.ts` and `src/objects/note.object.ts` (no stub), and the scaffold carries `label: 'Note'`; - `supportedLocales: ['en']`: no line; no `i18n` block: no line; `--dry-run`: nothing written and no line; - reader cases: `supportedLocales` minus `defaultLocale`; `sourceLocale` outranks `defaultLocale` and a differing users' `defaultLocale` counts as declared; source-only stacks and no config answer nothing. <details><summary>Readings at a4c7b5b</summary> - `vitest run test/generate-locale-hint-39324.test.ts`: `Tests 8 passed (8)`, VERDICT command-exit 0. - Ablation (`scripts/ablation-replace.mjs`, call line in `generate.ts` deleted, mutation landed blob 11b7cfb to ea314788, restored to HEAD): `Tests 1 failed | 7 passed (8)`, the failing case is the every-locale one. - `vitest run --project unit` over the generate-related unit files (`commands.test.ts` included; the spawning ones are integration tier): `Test Files 14 passed (14)`, `Tests 368 passed (368)`. - `pnpm --filter @objectstack/cli typecheck`: exit 0 (`check:test-typecheck: OK`). - Full `packages/cli` unit tier: NOT MEASURED, reason: did not finish inside the 570 s foreground window on the shared box; Test Core runs it. </details> ## Acceptance notes - "Declared" means `i18n.supportedLocales` (plus the gated users' `defaultLocale`). A project with translation bundles but no `i18n` block gets no line, although `os i18n check` would gate the bundle locales there; the card scopes the hint to declared locales. - Locales are compared as written, as `os i18n check` compares them; a project declaring `zh-CN` sees `zh-CN` named. - `os g` has no `--json` mode, so the line goes to stdout with the command's other output. ## Verification First read: `packages/cli/src/utils/generate-locale-hint.ts` (`declaredOtherLocales`), then the one-call hunk at the end of `runMetadataGeneration` in `generate.ts`. Two-minute check: in a project whose `objectstack.config.ts` declares `i18n: { defaultLocale: 'en', supportedLocales: ['en', 'zh-Hans'] }`, run `os g object note`; expect the usual Created lines and one info line ending in "this project also declares zh-Hans. Run `os i18n check` ...". With `supportedLocales: ['en']`, no such line. --- _Generated by [Claude Code](https://claude.ai/code/session_016WV4czHUJLmdQAqm4fdDs9)_ <!-- signed: repo:objectstack@os-elon-musk · os-elon-musk · session_016WV4czHUJLmdQAqm4fdDs9 --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 1324973 commit 55d673c

4 files changed

Lines changed: 264 additions & 0 deletions

File tree

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
'@objectstack/cli': patch
3+
---
4+
5+
feat(cli): `os g` prints one hint when the project declares locales other than its source locale
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
Who sees it: a developer running `os g <kind>` in a project whose `i18n` block declares more languages than the source language (the blank template and the Starter declare every platform locale).
11+
12+
- After a successful write, `os g` prints one line: the scaffold's labels were written in the source locale only, run `os i18n check` to list what is untranslated, and translations go in the stack's `translations` bundles (`os i18n extract` scaffolds them).
13+
- The declared locales are read the way `os i18n check` reads them: `i18n.supportedLocales`, plus the users' `i18n.defaultLocale` on a stack that also declares `i18n.sourceLocale`, minus the source locale (`sourceLocale`, else `defaultLocale`, else `en`).
14+
- A single-locale project, a project with no `i18n` block, a `--dry-run` and a refused generation print no such line.
15+
- No translation stub is written: coverage counts any string in a bundle as translated, so a stub would hide the gap.

‎packages/cli/src/commands/generate.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ import { normalizeDatasetTerm } from '@objectstack/spec/ui';
6161
import { printHeader, printSuccess, printError, printInfo, printStep, printWarning, createTimer, isReportedError, CLI_ALIAS } from '../utils/format.js';
6262
import { metadataFileName } from '../utils/metadata-file-name.js';
6363
import { namespacedItemName, readProjectNamespace, type ProjectNamespace } from '../utils/project-namespace.js';
64+
import { reportGenerateLocaleHint } from '../utils/generate-locale-hint.js';
6465
import { findEmissionParseFailures } from '../utils/emitted-source-parses.js';
6566
import { findBarrelAliasRefusal } from '../utils/importable-binding.js';
6667
import {
@@ -2334,6 +2335,7 @@ async function runMetadataGeneration(
23342335
if (generator.navEntry) {
23352336
reportNavEntry(generator.navEntry(name, namespace), type, project.kind === 'loaded' ? project.config : undefined);
23362337
}
2338+
reportGenerateLocaleHint(project.kind === 'loaded' ? project.config : undefined);
23372339
}
23382340

23392341
/**
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* The one line `os g` prints, after a successful write, in a project that
5+
* declares locales other than its source locale.
6+
*
7+
* ## The ruling it follows
8+
*
9+
* The blank template and the Starter ship every platform locale
10+
* (`PLATFORM_LOCALE_TAGS`); generators write the source language only; and
11+
* translation completeness is `os i18n check`'s report, not a warning in
12+
* default `os lint`. So a scaffold's label is written once, in the source
13+
* locale, and the author is told so in one line that names the command that
14+
* lists the gaps and where translations go.
15+
*
16+
* ⛔ No translation stubs are ever written: coverage counts any string in a
17+
* bundle as translated, so a stub copied from the source label would read as
18+
* 100% and hide the very gap this line points at.
19+
*
20+
* ## Which locales count as "other"
21+
*
22+
* The locales the stack DECLARES — `i18n.supportedLocales`, plus the users'
23+
* `i18n.defaultLocale` on a stack that also declares `i18n.sourceLocale`
24+
* (`withGatedDefaultLocale`) — minus the source locale
25+
* (`resolveSourceLocale`: `sourceLocale`, else `defaultLocale`, else `'en'`).
26+
* These are the readers `os i18n check` and `os i18n extract` use, so the line
27+
* never names a locale those commands would not gate. Locales are compared as
28+
* written, the way those commands compare them. A stack that declares no
29+
* other locale gets no line at all.
30+
*/
31+
32+
import { normalizeStackInput } from '@objectstack/spec';
33+
import { CLI_ALIAS, printInfo } from './format.js';
34+
import { resolveSourceLocale, withGatedDefaultLocale } from './i18n-coverage.js';
35+
import { authoringRuleUnionStack } from './stack-collections.js';
36+
37+
/** How many other locales the line names before it says "and N more". */
38+
const NAMED_LOCALES = 3;
39+
40+
/** The source locale and the declared locales other than it. */
41+
export interface DeclaredOtherLocales {
42+
source: string;
43+
others: string[];
44+
}
45+
46+
/**
47+
* The locales a loaded stack declares besides its source locale, or
48+
* `undefined` when it declares none (or there is no loaded stack).
49+
* Pure: it prints nothing.
50+
*/
51+
export function declaredOtherLocales(config: unknown): DeclaredOtherLocales | undefined {
52+
if (!config || typeof config !== 'object') return undefined;
53+
// Read the way `os i18n check` reads the stack, so the two cannot disagree.
54+
const stack = authoringRuleUnionStack(normalizeStackInput(config as Record<string, unknown>)) as {
55+
i18n?: { supportedLocales?: unknown };
56+
};
57+
const i18n = stack.i18n;
58+
if (!i18n || typeof i18n !== 'object') return undefined;
59+
const supported = Array.isArray(i18n.supportedLocales)
60+
? i18n.supportedLocales.filter((l): l is string => typeof l === 'string' && l.length > 0)
61+
: [];
62+
const declared = withGatedDefaultLocale(supported, i18n) ?? [];
63+
const source = resolveSourceLocale(i18n);
64+
const others = Array.from(new Set(declared)).filter((locale) => locale !== source);
65+
return others.length > 0 ? { source, others } : undefined;
66+
}
67+
68+
/** The hint's text, uncoloured. */
69+
export function generateLocaleHintLine({ source, others }: DeclaredOtherLocales): string {
70+
const named = others.slice(0, NAMED_LOCALES).join(', ');
71+
const rest = others.length - NAMED_LOCALES;
72+
const list = rest > 0 ? `${named} and ${rest} more` : named;
73+
return (
74+
`Labels written in the source locale (${source}) only; this project also declares ${list}. ` +
75+
`Run \`${CLI_ALIAS} i18n check\` to list what is untranslated, and add translations to the stack's ` +
76+
`\`translations\` bundles (\`${CLI_ALIAS} i18n extract\` scaffolds them).`
77+
);
78+
}
79+
80+
/**
81+
* Print the hint once, after `os g` wrote a scaffold, when the loaded stack
82+
* declares locales other than its source locale; print nothing otherwise.
83+
*/
84+
export function reportGenerateLocaleHint(config: unknown): void {
85+
const declared = declaredOtherLocales(config);
86+
if (declared) printInfo(generateLocaleHintLine(declared));
87+
}
Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* PIN — `os g` in a project that declares locales other than its source
5+
* locale prints ONE line after a successful write: the label was written in
6+
* the source locale only, run `os i18n check`, and where translations go.
7+
*
8+
* The maintainer's ruling: the blank template and the Starter ship every
9+
* platform locale; generators write the source language only; completeness is
10+
* `os i18n check`'s report. ⛔ No translation stub is written, because
11+
* coverage counts any string in a bundle as translated.
12+
*
13+
* Halves:
14+
* 1. The command, in-process (`Generate.run` in a sandbox project under this
15+
* package's `node_modules`, so the config's `@objectstack/spec` import
16+
* resolves to the workspace copy): one line with every platform locale
17+
* declared and no translation file written; no line in a single-locale
18+
* project; no line on `--dry-run`, which writes nothing.
19+
* 2. The reader: which declared locales count as "other" — the same readers
20+
* `os i18n check` uses (`sourceLocale` outranks `defaultLocale`, and the
21+
* users' `defaultLocale` is gated on a stack declaring `sourceLocale`).
22+
*/
23+
24+
import { afterAll, afterEach, describe, expect, it, vi } from 'vitest';
25+
import fs from 'node:fs';
26+
import path from 'node:path';
27+
import { fileURLToPath } from 'node:url';
28+
import { PLATFORM_LOCALE_TAGS } from '@objectstack/spec/system';
29+
import Generate from '../src/commands/generate';
30+
import { declaredOtherLocales, generateLocaleHintLine } from '../src/utils/generate-locale-hint.js';
31+
32+
const HERE = path.dirname(fileURLToPath(import.meta.url));
33+
const CLI_ROOT = path.resolve(HERE, '..');
34+
const TMP_ROOT = fs.mkdtempSync(path.join(HERE, '..', 'node_modules', '.generate-locale-hint-'));
35+
const ORIGINAL_CWD = process.cwd();
36+
37+
afterEach(() => {
38+
process.chdir(ORIGINAL_CWD);
39+
});
40+
41+
afterAll(() => {
42+
fs.rmSync(TMP_ROOT, { recursive: true, force: true });
43+
});
44+
45+
/** A project whose config declares `i18n` as given (nothing when omitted). */
46+
function project(i18n?: Record<string, unknown>): string {
47+
const root = fs.mkdtempSync(path.join(TMP_ROOT, 'project-'));
48+
const i18nLine = i18n ? ` i18n: ${JSON.stringify(i18n)},\n` : '';
49+
fs.writeFileSync(
50+
path.join(root, 'objectstack.config.ts'),
51+
`import { defineStack } from '@objectstack/spec';
52+
53+
export default defineStack({
54+
manifest: {
55+
id: 'com.example.locale-hint',
56+
namespace: 'locale_hint',
57+
version: '0.1.0',
58+
type: 'app',
59+
name: 'Locale Hint',
60+
},
61+
${i18nLine}});
62+
`,
63+
);
64+
return root;
65+
}
66+
67+
/** Every file under `root`, relative, sorted. */
68+
function tree(root: string): string[] {
69+
const out: string[] = [];
70+
const walk = (dir: string): void => {
71+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
72+
const full = path.join(dir, entry.name);
73+
if (entry.isDirectory()) walk(full);
74+
else out.push(path.relative(root, full));
75+
}
76+
};
77+
walk(root);
78+
return out.sort();
79+
}
80+
81+
/** Run `os g …` in `cwd`, in-process, and answer its stdout lines, uncoloured. */
82+
async function generate(cwd: string, argv: string[]): Promise<string[]> {
83+
const lines: string[] = [];
84+
const logSpy = vi.spyOn(console, 'log').mockImplementation((...args: unknown[]) => {
85+
lines.push(args.map(String).join(' '));
86+
});
87+
process.chdir(cwd);
88+
try {
89+
await Generate.run(argv, { root: CLI_ROOT });
90+
} finally {
91+
logSpy.mockRestore();
92+
process.chdir(ORIGINAL_CWD);
93+
}
94+
// eslint-disable-next-line no-control-regex
95+
return lines.join('\n').replace(/\u001b\[[0-9;]*m/g, '').split('\n');
96+
}
97+
98+
const hintLines = (lines: string[]): string[] => lines.filter((l) => l.includes('i18n check'));
99+
100+
describe('os g: one hint when the project declares other locales', () => {
101+
it('every platform locale declared: one line naming the source and `os i18n check`, and no stub written', async () => {
102+
const root = project({ defaultLocale: 'en', supportedLocales: [...PLATFORM_LOCALE_TAGS] });
103+
const lines = await generate(root, ['object', 'note']);
104+
105+
const hints = hintLines(lines);
106+
expect(hints).toHaveLength(1);
107+
expect(hints[0]).toContain('source locale (en) only');
108+
expect(hints[0]).toContain('zh-Hans, zh-Hant, es and 7 more');
109+
expect(hints[0]).toContain('`os i18n check`');
110+
expect(hints[0]).toContain('`translations`');
111+
112+
// The scaffold and its barrel, and nothing else: no translation stub.
113+
expect(tree(root)).toEqual(['objectstack.config.ts', 'src/objects/index.ts', 'src/objects/note.object.ts']);
114+
const scaffold = fs.readFileSync(path.join(root, 'src/objects/note.object.ts'), 'utf8');
115+
expect(scaffold).toContain("label: 'Note'");
116+
}, 60_000); // the first in-process run pays the config loader's cold start
117+
118+
it('a single-locale project: no line', async () => {
119+
const root = project({ defaultLocale: 'en', supportedLocales: ['en'] });
120+
const lines = await generate(root, ['object', 'note']);
121+
expect(fs.existsSync(path.join(root, 'src/objects/note.object.ts'))).toBe(true);
122+
expect(hintLines(lines)).toEqual([]);
123+
});
124+
125+
it('a project with no i18n block: no line', async () => {
126+
const root = project();
127+
const lines = await generate(root, ['object', 'note']);
128+
expect(fs.existsSync(path.join(root, 'src/objects/note.object.ts'))).toBe(true);
129+
expect(hintLines(lines)).toEqual([]);
130+
});
131+
132+
it('--dry-run writes nothing, so it says nothing about a written label', async () => {
133+
const root = project({ defaultLocale: 'en', supportedLocales: [...PLATFORM_LOCALE_TAGS] });
134+
const lines = await generate(root, ['object', 'note', '--dry-run']);
135+
expect(tree(root)).toEqual(['objectstack.config.ts']);
136+
expect(hintLines(lines)).toEqual([]);
137+
});
138+
});
139+
140+
describe('which declared locales are "other than the source"', () => {
141+
it('supportedLocales minus defaultLocale when no sourceLocale is declared', () => {
142+
expect(declaredOtherLocales({ i18n: { defaultLocale: 'en', supportedLocales: ['en', 'zh-Hans'] } }))
143+
.toEqual({ source: 'en', others: ['zh-Hans'] });
144+
});
145+
146+
it('sourceLocale outranks defaultLocale, and the users\' defaultLocale counts as declared', () => {
147+
expect(declaredOtherLocales({ i18n: { sourceLocale: 'en', defaultLocale: 'zh-Hans', supportedLocales: ['en'] } }))
148+
.toEqual({ source: 'en', others: ['zh-Hans'] });
149+
});
150+
151+
it('a stack whose only declared locale is the source answers nothing', () => {
152+
expect(declaredOtherLocales({ i18n: { defaultLocale: 'ja', supportedLocales: ['ja'] } })).toBeUndefined();
153+
expect(declaredOtherLocales({})).toBeUndefined();
154+
expect(declaredOtherLocales(undefined)).toBeUndefined();
155+
});
156+
157+
it('names up to three locales, then counts the rest', () => {
158+
expect(generateLocaleHintLine({ source: 'en', others: ['de', 'fr'] })).toContain('also declares de, fr.');
159+
});
160+
});

0 commit comments

Comments
 (0)