vue-i18n-automatic-translation 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,114 @@
1
+ # vue-i18n-automatic-translation
2
+
3
+ [中文文档](./README.zh-CN.md)
4
+
5
+ Scan Chinese copy in Vue / TS / JS source, wrap with `$t()` / `t()`, write locale JSON packs, and auto-translate. Configure scan paths via `vite.config` `i18nAuto`.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm i -D vue-i18n-automatic-translation
11
+ # peer: vite (used to load vite.config.ts)
12
+ npm i -D vite
13
+ ```
14
+
15
+ Or from a local path / git:
16
+
17
+ ```bash
18
+ npm i -D ../vue-i18n-automaticTranslation
19
+ # npm i -D git+https://github.com/your-org/vue-i18n-automaticTranslation.git
20
+ ```
21
+
22
+ ## Configure (`vite.config.ts`)
23
+
24
+ ```ts
25
+ import { defineConfig } from 'vite'
26
+
27
+ export default defineConfig({
28
+ // ...your existing vite options
29
+ i18nAuto: {
30
+ include: ['src/views', 'src/components'], // directories to scan
31
+ exclude: ['locales', 'assets', 'styles', 'node_modules', 'dist'],
32
+ localesDir: 'src/locales',
33
+ sourceLocale: 'zh-CN',
34
+ targetLocales: ['en-US', 'de-DE', 'ja-JP', 'ko-KR'],
35
+ replace: true, // wrap source with $t()/t()
36
+ translate: true, // online translate after extract
37
+ reportsDir: 'reports',
38
+ tImportFrom: '@/locales' // import path for plain .ts/.js `t`
39
+ }
40
+ })
41
+ ```
42
+
43
+ If `i18nAuto` is omitted, defaults scan `src` and use the built-in locale set (same as the original tenant toolkit).
44
+
45
+ ### Config fields
46
+
47
+ | Field | Default | Description |
48
+ |-------|---------|-------------|
49
+ | `include` | `['src']` | Paths to scan |
50
+ | `exclude` | `locales`, `assets`, `styles`, … | Directory names to skip |
51
+ | `localesDir` | `'src/locales'` | Locale JSON directory |
52
+ | `sourceLocale` | `'zh-CN'` | Source language |
53
+ | `targetLocales` | built-in set | Target languages |
54
+ | `replace` | `true` | Replace Chinese with `$t()` / `t()` |
55
+ | `translate` | `true` | Online translate after extract |
56
+ | `reportsDir` | `'reports'` | Report output directory |
57
+ | `tImportFrom` | `'@/locales'` | Import path when injecting `t` into plain `.ts` / `.js` |
58
+
59
+ ## Commands
60
+
61
+ Run inside the consumer project (directory with `vite.config` / `package.json`):
62
+
63
+ ```bash
64
+ # Scan include paths (or pass a path), extract Chinese, wrap $t, sync, translate
65
+ npx i18n-auto scan
66
+ npx i18n-auto scan src/views/workbench
67
+ npx i18n-auto scan --dry
68
+ npx i18n-auto scan --no-translate
69
+
70
+ # Only git-changed source files under include
71
+ npx i18n-auto changed
72
+ npx i18n-auto changed --staged
73
+ npx i18n-auto changed --no-translate
74
+ npx i18n-auto changed --fill-all
75
+
76
+ # Helpers
77
+ npx i18n-auto sync
78
+ npx i18n-auto inject-meta
79
+ npx i18n-auto fill-en --auto
80
+ npx i18n-auto fill-locales --check
81
+ npx i18n-auto offline-en
82
+ ```
83
+
84
+ ### package.json scripts (optional)
85
+
86
+ ```json
87
+ {
88
+ "scripts": {
89
+ "i18n:scan": "i18n-auto scan",
90
+ "i18n:changed": "i18n-auto changed"
91
+ }
92
+ }
93
+ ```
94
+
95
+ ## Behavior notes
96
+
97
+ - Comments (`<!-- -->` / `//` / `/* */`) are not replaced.
98
+ - Existing non-Chinese translations are never overwritten.
99
+ - Online translation uses Youdao demo + MyMemory (+ Google for English fallback). Free quotas may throttle; re-run to resume.
100
+ - Reports are written under `reports/` (`i18n-extract.json`, `i18n-changed-keys.json`, …).
101
+
102
+ ## Publish
103
+
104
+ ```bash
105
+ cd vue-i18n-automaticTranslation
106
+ npm login
107
+ npm publish
108
+ ```
109
+
110
+ Or push this folder as its own git repo and install via `git+https://...`.
111
+
112
+ ## License
113
+
114
+ MIT
@@ -0,0 +1,114 @@
1
+ # vue-i18n-automatic-translation
2
+
3
+ [English](./README.md)
4
+
5
+ 扫描 Vue / TS / JS 源码中的中文文案,自动包成 `$t()` / `t()`,写入语言包 JSON,并在线翻译。通过 `vite.config` 的 `i18nAuto` 配置扫描目录。
6
+
7
+ ## 安装
8
+
9
+ ```bash
10
+ npm i -D vue-i18n-automatic-translation
11
+ # peer:vite(用于加载 vite.config.ts)
12
+ npm i -D vite
13
+ ```
14
+
15
+ 或从本地路径 / git 安装:
16
+
17
+ ```bash
18
+ npm i -D ../vue-i18n-automaticTranslation
19
+ # npm i -D git+https://github.com/your-org/vue-i18n-automaticTranslation.git
20
+ ```
21
+
22
+ ## 配置(`vite.config.ts`)
23
+
24
+ ```ts
25
+ import { defineConfig } from 'vite'
26
+
27
+ export default defineConfig({
28
+ // ...原有 vite 配置
29
+ i18nAuto: {
30
+ include: ['src/views', 'src/components'], // 要扫描的目录
31
+ exclude: ['locales', 'assets', 'styles', 'node_modules', 'dist'],// 额外忽略目录
32
+ localesDir: 'src/locales', //语言包生成地址
33
+ sourceLocale: 'zh-CN', //源语言
34
+ targetLocales: ['en-US', 'de-DE', 'ja-JP', 'ko-KR'], //目标语言
35
+ replace: true, // 是否把源码中文替换成 $t()/t()
36
+ translate: true, // 抽取后是否在线翻译
37
+ reportsDir: 'reports', //日志
38
+ tImportFrom: '@/locales' // 普通 .ts/.js 注入 t 时的 import 路径
39
+ }
40
+ })
41
+ ```
42
+
43
+ 未配置 `i18nAuto` 时:默认扫描 `src`,语言列表与内置默认集一致。
44
+
45
+ ### 配置字段
46
+
47
+ | 字段 | 默认值 | 说明 |
48
+ |------|--------|------|
49
+ | `include` | `['src']` | 要扫描的路径 |
50
+ | `exclude` | `locales`、`assets`、`styles` 等 | 遍历时跳过的目录名 |
51
+ | `localesDir` | `'src/locales'` | 语言包目录 |
52
+ | `sourceLocale` | `'zh-CN'` | 源语言 |
53
+ | `targetLocales` | 内置语言集 | 目标语言 |
54
+ | `replace` | `true` | 是否替换为 `$t()` / `t()` |
55
+ | `translate` | `true` | 抽取后是否在线翻译 |
56
+ | `reportsDir` | `'reports'` | 报告输出目录 |
57
+ | `tImportFrom` | `'@/locales'` | 普通 `.ts` / `.js` 注入 `t` 的导入路径 |
58
+
59
+ ## 命令
60
+
61
+ 在消费方项目根目录执行(有 `vite.config` / `package.json` 的目录):
62
+
63
+ ```bash
64
+ # 按 include(或指定 path)扫描中文 → 写语言包 → 包 $t → 同步 → 翻译
65
+ npx i18n-auto scan
66
+ npx i18n-auto scan src/views/workbench
67
+ npx i18n-auto scan --dry
68
+ npx i18n-auto scan --no-translate
69
+
70
+ # 只处理 git 变更的源码文件(且落在 include 内)
71
+ npx i18n-auto changed
72
+ npx i18n-auto changed --staged
73
+ npx i18n-auto changed --no-translate
74
+ npx i18n-auto changed --fill-all
75
+
76
+ # 辅助命令
77
+ npx i18n-auto sync
78
+ npx i18n-auto inject-meta
79
+ npx i18n-auto fill-en --auto
80
+ npx i18n-auto fill-locales --check
81
+ npx i18n-auto offline-en
82
+ ```
83
+
84
+ ### package.json scripts(可选)
85
+
86
+ ```json
87
+ {
88
+ "scripts": {
89
+ "i18n:scan": "i18n-auto scan",
90
+ "i18n:changed": "i18n-auto changed"
91
+ }
92
+ }
93
+ ```
94
+
95
+ ## 行为说明
96
+
97
+ - 注释(`<!-- -->` / `//` / `/* */`)中的中文不会被替换。
98
+ - 已有非中文译文不会被覆盖。
99
+ - 在线翻译使用有道 demo + MyMemory(英文另有 Google 兜底)。免费配额可能限流,可重复执行续跑。
100
+ - 报告写入 `reports/`(如 `i18n-extract.json`、`i18n-changed-keys.json` 等)。
101
+
102
+ ## 发布
103
+
104
+ ```bash
105
+ cd vue-i18n-automaticTranslation
106
+ npm login
107
+ npm publish
108
+ ```
109
+
110
+ 或把本目录推成独立 git 仓库,通过 `git+https://...` 安装。
111
+
112
+ ## License
113
+
114
+ MIT
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import { runCli } from '../src/cli.mjs'
3
+
4
+ runCli(process.argv.slice(2)).catch((e) => {
5
+ console.error(`[i18n-auto] fatal: ${e?.message || e}`)
6
+ process.exit(1)
7
+ })
package/i18n-auto.d.ts ADDED
@@ -0,0 +1,30 @@
1
+ /** Augment Vite UserConfig with i18nAuto (optional helper for consumers). */
2
+
3
+ export interface I18nAutoConfig {
4
+ /** Directories/files to scan (relative to project root). Default: ['src'] */
5
+ include?: string[]
6
+ /** Directory names to skip while walking. */
7
+ exclude?: string[]
8
+ /** Locale JSON directory. Default: 'src/locales' */
9
+ localesDir?: string
10
+ /** Source language code. Default: 'zh-CN' */
11
+ sourceLocale?: string
12
+ /** Target locale codes (en-US, de-DE, ...). */
13
+ targetLocales?: string[]
14
+ /** Replace Chinese with $t()/t(). Default: true */
15
+ replace?: boolean
16
+ /** Run online translation after extract. Default: true */
17
+ translate?: boolean
18
+ /** Report output directory. Default: 'reports' */
19
+ reportsDir?: string
20
+ /** Import path when injecting `t` into plain .ts/.js. Default: '@/locales' */
21
+ tImportFrom?: string
22
+ }
23
+
24
+ declare module 'vite' {
25
+ interface UserConfig {
26
+ i18nAuto?: I18nAutoConfig
27
+ }
28
+ }
29
+
30
+ export {}
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "vue-i18n-automatic-translation",
3
+ "version": "1.0.0",
4
+ "description": "Scan Chinese text in Vue projects, wrap with $t(), and auto-translate locale JSON files. Configure via vite.config i18nAuto.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "bin": {
8
+ "i18n-auto": "./bin/i18n-auto.mjs"
9
+ },
10
+ "main": "./src/index.mjs",
11
+ "exports": {
12
+ ".": "./src/index.mjs"
13
+ },
14
+ "types": "./i18n-auto.d.ts",
15
+ "files": [
16
+ "bin",
17
+ "src",
18
+ "i18n-auto.d.ts",
19
+ "README.md",
20
+ "README.zh-CN.md"
21
+ ],
22
+ "engines": {
23
+ "node": ">=18"
24
+ },
25
+ "scripts": {
26
+ "i18n-auto": "node ./bin/i18n-auto.mjs"
27
+ },
28
+ "dependencies": {
29
+ "@vue/compiler-sfc": "^3.5.0",
30
+ "google-translate-api-x": "^10.7.3"
31
+ },
32
+ "peerDependencies": {
33
+ "vite": ">=4"
34
+ },
35
+ "peerDependenciesMeta": {
36
+ "vite": {
37
+ "optional": true
38
+ }
39
+ },
40
+ "keywords": [
41
+ "i18n",
42
+ "vue",
43
+ "vue-i18n",
44
+ "translation",
45
+ "chinese",
46
+ "vite"
47
+ ],
48
+ "repository": {
49
+ "type": "git",
50
+ "url": "git+https://github.com/FrontDeveloperApe/vue-i18n-automaticTranslation.git"
51
+ }
52
+ }
@@ -0,0 +1,364 @@
1
+ /**
2
+ * Git-changed files → extract → sync → scoped translate.
3
+ */
4
+
5
+ import { spawnSync } from 'child_process'
6
+ import fs from 'fs'
7
+ import path from 'path'
8
+ import { getContext } from './context.mjs'
9
+ import { runExtract } from './extract.mjs'
10
+ import { runSync } from './sync.mjs'
11
+ import { runOfflineEn } from './offline-en.mjs'
12
+ import { runTranslateEn } from './translate-en.mjs'
13
+ import { runTranslateLocales } from './translate-locales.mjs'
14
+
15
+ const SRC_RE = /\.(vue|ts|js|tsx|jsx)$/i
16
+
17
+ function parseArgs(argv) {
18
+ const opts = {
19
+ dry: false,
20
+ staged: false,
21
+ fillAll: false,
22
+ noTranslate: false,
23
+ onlineEn: false
24
+ }
25
+ for (const arg of argv) {
26
+ if (arg === '--dry') opts.dry = true
27
+ else if (arg === '--staged') opts.staged = true
28
+ else if (arg === '--fill-all' || arg === '--locales' || arg === '--translate') {
29
+ opts.fillAll = true
30
+ } else if (arg === '--no-translate') opts.noTranslate = true
31
+ else if (arg === '--online-en') opts.onlineEn = true
32
+ else if (arg === '--help' || arg === '-h') {
33
+ console.log(`Usage: i18n-auto changed [--dry] [--staged] [--no-translate] [--fill-all] [--online-en]
34
+ --dry scan only, no write
35
+ --staged only staged git changes
36
+ --no-translate skip online translate
37
+ --fill-all translate full locale backlog
38
+ --online-en force online for all pending English`)
39
+ process.exit(0)
40
+ }
41
+ }
42
+ return opts
43
+ }
44
+
45
+ function findGitRoot(start) {
46
+ let dir = path.resolve(start)
47
+ for (;;) {
48
+ if (fs.existsSync(path.join(dir, '.git'))) return dir
49
+ const parent = path.dirname(dir)
50
+ if (parent === dir) return start
51
+ dir = parent
52
+ }
53
+ }
54
+
55
+ function runGit(gitRoot, args) {
56
+ const r = spawnSync('git', args, {
57
+ cwd: gitRoot,
58
+ encoding: 'utf8',
59
+ shell: false
60
+ })
61
+ if (r.status !== 0) {
62
+ const err = (r.stderr || r.stdout || '').trim()
63
+ throw new Error(`git ${args.join(' ')} failed: ${err || `exit ${r.status}`}`)
64
+ }
65
+ return (r.stdout || '')
66
+ .split(/\r?\n/)
67
+ .map((s) => s.trim())
68
+ .filter(Boolean)
69
+ }
70
+
71
+ function runGitRaw(gitRoot, args) {
72
+ const r = spawnSync('git', args, {
73
+ cwd: gitRoot,
74
+ encoding: 'utf8',
75
+ shell: false
76
+ })
77
+ if (r.status !== 0) {
78
+ const err = (r.stderr || r.stdout || '').trim()
79
+ throw new Error(`git ${args.join(' ')} failed: ${err || `exit ${r.status}`}`)
80
+ }
81
+ return r.stdout || ''
82
+ }
83
+
84
+ function toProjectRel(repoRel, { root, gitRoot }) {
85
+ const norm = repoRel.replace(/\\/g, '/').replace(/^\.\//, '')
86
+ const abs = path.resolve(gitRoot, norm)
87
+ const rel = path.relative(root, abs).replace(/\\/g, '/')
88
+ if (!rel || rel.startsWith('..')) return null
89
+ return rel
90
+ }
91
+
92
+ function matchesInclude(rel, include) {
93
+ const n = rel.replace(/\\/g, '/')
94
+ return include.some((inc) => {
95
+ const i = inc.replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/$/, '')
96
+ return n === i || n.startsWith(i + '/')
97
+ })
98
+ }
99
+
100
+ function collectChangedFiles({ staged, root, gitRoot, include, localesDir }) {
101
+ const names = new Set()
102
+ for (const f of runGit(gitRoot, ['ls-files', '--others', '--exclude-standard'])) {
103
+ names.add(f)
104
+ }
105
+ if (staged) {
106
+ for (const f of runGit(gitRoot, ['diff', '--cached', '--name-only', '--diff-filter=ACMR'])) {
107
+ names.add(f)
108
+ }
109
+ } else {
110
+ for (const f of runGit(gitRoot, ['diff', '--name-only', '--diff-filter=ACMR'])) {
111
+ names.add(f)
112
+ }
113
+ for (const f of runGit(gitRoot, ['diff', '--cached', '--name-only', '--diff-filter=ACMR'])) {
114
+ names.add(f)
115
+ }
116
+ }
117
+
118
+ const localesRel = path.relative(root, localesDir).replace(/\\/g, '/')
119
+ const out = []
120
+ for (const repoRel of names) {
121
+ const rel = toProjectRel(repoRel, { root, gitRoot })
122
+ if (!rel) continue
123
+ if (!SRC_RE.test(rel)) continue
124
+ if (/\.d\.ts$/i.test(rel)) continue
125
+ if (localesRel && (rel === localesRel || rel.startsWith(localesRel + '/'))) continue
126
+ if (!matchesInclude(rel, include)) continue
127
+ const abs = path.join(root, rel)
128
+ if (!fs.existsSync(abs)) continue
129
+ out.push(rel)
130
+ }
131
+ return [...new Set(out)].sort()
132
+ }
133
+
134
+ function normalizeKey(raw) {
135
+ return String(raw || '')
136
+ .replace(/\s+/g, ' ')
137
+ .trim()
138
+ }
139
+
140
+ const CN_CHAR = /[\u4e00-\u9fff]/
141
+ const CN_TEXT =
142
+ /[\u4e00-\u9fff][\u4e00-\u9fff\w\s,。!?、:;""''()【】《》·…—\-~,.!?:;()[\]{}/%++=]*/g
143
+
144
+ function extractChineseKeysFromLine(line) {
145
+ const keys = new Set()
146
+ if (!line || !CN_CHAR.test(line)) return keys
147
+
148
+ const isHtmlKey = (text) =>
149
+ /<\/?[a-zA-Z]|\bbr\s*\/?>/i.test(text) || /^["']?>|<\/[a-zA-Z]/.test(text)
150
+
151
+ const isJunkKey = (text) =>
152
+ /console\.log|btnItem\.|function\s*\(|=>\s*\{|\.Format\(|\$\{|item\.label|row\.|innerHTML|domString/.test(
153
+ text
154
+ ) ||
155
+ /^(['"])[\s\S]*\1$/.test(text) ||
156
+ /^[,:)\]}]/.test(text) ||
157
+ /^[\u4e00-\u9fffA-Za-z0-9]+\[$/.test(text) ||
158
+ /^\]/.test(text) ||
159
+ /^米\]/.test(text) ||
160
+ /^0\s*\?/.test(text)
161
+
162
+ const wrappedRe = /(?:\$t|i18n\.t|\bt)\(\s*(['"])((?:\\.|(?!\1)[^\\])*)\1/g
163
+ let m
164
+ while ((m = wrappedRe.exec(line))) {
165
+ const text = normalizeKey(m[2].replace(/\\n/g, '\n').replace(/\\'/g, "'").replace(/\\"/g, '"'))
166
+ if (text && CN_CHAR.test(text) && text.length <= 80 && !isHtmlKey(text) && !isJunkKey(text))
167
+ keys.add(text)
168
+ }
169
+
170
+ const quoteRe = /(['"`])((?:\\.|(?!\1)[^\\])*)\1/g
171
+ while ((m = quoteRe.exec(line))) {
172
+ if (m[1] === '`' && m[2].includes('${')) continue
173
+ const text = normalizeKey(m[2].replace(/\\n/g, '\n').replace(/\\'/g, "'").replace(/\\"/g, '"'))
174
+ if (text && CN_CHAR.test(text) && text.length <= 80 && !isHtmlKey(text) && !isJunkKey(text))
175
+ keys.add(text)
176
+ }
177
+
178
+ const cleaned = line
179
+ .replace(/\{\{\s*\$t\([^)]+\)\s*\}\}/g, ' ')
180
+ .replace(/(?:\$t|i18n\.t|\bt)\([^)]*\)/g, ' ')
181
+ .replace(/<[^>]+>/g, ' ')
182
+ for (const hit of cleaned.match(CN_TEXT) || []) {
183
+ const text = normalizeKey(hit)
184
+ if (text && text.length <= 80 && !isHtmlKey(text) && !isJunkKey(text)) keys.add(text)
185
+ }
186
+
187
+ return keys
188
+ }
189
+
190
+ function collectKeysFromGitDiff(files, { staged, root, gitRoot }) {
191
+ const keys = new Set()
192
+ const untracked = new Set(runGit(gitRoot, ['ls-files', '--others', '--exclude-standard']))
193
+
194
+ for (const rel of files) {
195
+ const abs = path.join(root, rel)
196
+ const repoRel = path.relative(gitRoot, abs).replace(/\\/g, '/')
197
+ const isUntracked =
198
+ untracked.has(repoRel) ||
199
+ untracked.has(rel) ||
200
+ untracked.has(rel.replace(/\\/g, '/'))
201
+
202
+ if (isUntracked) {
203
+ if (!fs.existsSync(abs)) continue
204
+ for (const line of fs.readFileSync(abs, 'utf8').split(/\r?\n/)) {
205
+ for (const k of extractChineseKeysFromLine(line)) keys.add(k)
206
+ }
207
+ continue
208
+ }
209
+
210
+ const tryPaths = [repoRel, rel]
211
+ let diff = ''
212
+ for (const p of tryPaths) {
213
+ try {
214
+ diff = runGitRaw(
215
+ gitRoot,
216
+ staged ? ['diff', '--cached', '-U0', '--', p] : ['diff', 'HEAD', '-U0', '--', p]
217
+ )
218
+ if (diff) break
219
+ } catch {
220
+ /* try next */
221
+ }
222
+ }
223
+
224
+ for (const line of diff.split(/\r?\n/)) {
225
+ if (!line.startsWith('+') || line.startsWith('+++')) continue
226
+ for (const k of extractChineseKeysFromLine(line.slice(1))) keys.add(k)
227
+ }
228
+ }
229
+
230
+ return [...keys]
231
+ }
232
+
233
+ function writeChangedKeysFile(files, opts, extractReportPath, changedKeysPath) {
234
+ const { root, gitRoot } = opts
235
+ const keys = new Set()
236
+
237
+ for (const k of collectKeysFromGitDiff(files, opts)) keys.add(k)
238
+
239
+ if (fs.existsSync(extractReportPath)) {
240
+ try {
241
+ const report = JSON.parse(fs.readFileSync(extractReportPath, 'utf8') || '{}')
242
+ if (Array.isArray(report.added)) {
243
+ for (const t of report.added) {
244
+ const k = normalizeKey(t)
245
+ if (k) keys.add(k)
246
+ }
247
+ }
248
+ } catch {
249
+ console.warn('[i18n:changed] extract report invalid JSON, ignore')
250
+ }
251
+ }
252
+
253
+ const list = [...keys]
254
+ fs.mkdirSync(path.dirname(changedKeysPath), { recursive: true })
255
+ fs.writeFileSync(
256
+ changedKeysPath,
257
+ JSON.stringify(
258
+ {
259
+ at: new Date().toISOString(),
260
+ count: list.length,
261
+ texts: list,
262
+ files
263
+ },
264
+ null,
265
+ 2
266
+ ),
267
+ 'utf8'
268
+ )
269
+
270
+ console.log(
271
+ `[i18n:changed] scoped keys: ${list.length} -> ${path.relative(root, changedKeysPath)}`
272
+ )
273
+ if (list.length) {
274
+ for (const k of list.slice(0, 20)) console.log(` · ${k}`)
275
+ if (list.length > 20) console.log(` · … +${list.length - 20} more`)
276
+ }
277
+ return list
278
+ }
279
+
280
+ export async function runChanged(argv = []) {
281
+ const opts = parseArgs(argv)
282
+ const ctx = getContext()
283
+ const gitRoot = findGitRoot(ctx.root)
284
+ const extractReportPath = path.join(ctx.reportsDir, 'i18n-extract.json')
285
+ const changedKeysPath = path.join(ctx.reportsDir, 'i18n-changed-keys.json')
286
+
287
+ let files
288
+ try {
289
+ files = collectChangedFiles({
290
+ staged: opts.staged,
291
+ root: ctx.root,
292
+ gitRoot,
293
+ include: ctx.include,
294
+ localesDir: ctx.localesDir
295
+ })
296
+ } catch (e) {
297
+ console.error(`[i18n:changed] ${e.message}`)
298
+ process.exit(1)
299
+ }
300
+
301
+ if (!files.length) {
302
+ console.log('[i18n:changed] no changed source files in include paths')
303
+ console.log('[i18n:changed] tip: edit vue/ts files first, or use i18n-auto scan [path]')
304
+ return
305
+ }
306
+
307
+ console.log(`[i18n:changed] ${files.length} file(s):`)
308
+ for (const f of files) console.log(` - ${f}`)
309
+
310
+ const extractArgs = []
311
+ if (!opts.dry) extractArgs.push('--write')
312
+ if (ctx.replace === false) extractArgs.push('--no-replace')
313
+ for (const f of files) extractArgs.push(`--path=${f}`)
314
+
315
+ runExtract(extractArgs)
316
+
317
+ if (opts.dry) {
318
+ console.log('\n[i18n:changed] dry-run done (no sync/translate)')
319
+ return
320
+ }
321
+
322
+ const keys = writeChangedKeysFile(
323
+ files,
324
+ { staged: opts.staged, root: ctx.root, gitRoot },
325
+ extractReportPath,
326
+ changedKeysPath
327
+ )
328
+ const keysRel = path.relative(ctx.root, changedKeysPath).replace(/\\/g, '/')
329
+
330
+ runSync()
331
+
332
+ const shouldTranslate = !opts.noTranslate && ctx.translate !== false
333
+
334
+ if (opts.onlineEn) {
335
+ await runTranslateEn(['--auto', '--delay=500'])
336
+ } else {
337
+ runOfflineEn([])
338
+ if (shouldTranslate && keys.length) {
339
+ await runTranslateEn(['--auto', '--delay=300', `--keys-file=${keysRel}`])
340
+ }
341
+ }
342
+
343
+ if (opts.fillAll) {
344
+ await runTranslateLocales(['--all', '--delay=200', '--concurrency=2'])
345
+ } else if (shouldTranslate && keys.length) {
346
+ await runTranslateLocales([
347
+ '--all',
348
+ '--delay=200',
349
+ '--concurrency=2',
350
+ `--keys-file=${keysRel}`
351
+ ])
352
+ } else if (shouldTranslate && !keys.length) {
353
+ console.log('[i18n:changed] no Chinese keys in changed files, skip online translate')
354
+ }
355
+
356
+ console.log('\n[i18n:changed] done')
357
+ if (opts.noTranslate) {
358
+ console.log('[i18n:changed] tip: omit --no-translate to auto-translate scoped keys')
359
+ } else if (!opts.fillAll) {
360
+ console.log(
361
+ '[i18n:changed] tip: only translated keys from changed files; use --fill-all for full backlog'
362
+ )
363
+ }
364
+ }