Files
lucky_shop/scripts/find_i18n_key.py
ZF sun 5f41febd70 chore(i18n): 清理死代码 + 遗留 lang 文件 + 旧工具
## 删除的死代码脚本
- scripts/i18n_class_c.py (脚本自承'新架构下永远输出 0',纯防御性)
- scripts/full_migrate_i18n.py (其产出违反 CLAUDE.md 1.2 中文 key 铁律,已标 DEPRECATED)
- scripts/__pycache__/ (Python 缓存)

## 删除的旧 per-page lang 文件
- lang/zh-cn/<page>/<file>.js (140 个)
- lang/en-us/<page>/<file>.js (139 个)
- 共 279 个文件,运行时不再加载,0 个 key 被 .vue 调用(经 diagnose_keys.py 验证)

## 删除的备份和迁移表
- lang/_backup/ (git 已跟踪原文件)
- lang/_migration_map.json / lang/_migration-map.json (运行时不用)

## 删除的中间产物 JSON
- docs/i18n-rename-*.json (smart_rename 中间产物,已用完)
- docs/i18n-ambiguous.json / i18n-audit.json / i18n-call-rewrite.log /
  i18n-clean-dead.log / i18n-file-texts.json / i18n-page-titles.json /
  i18n-vue-extract.json (前一会话残留,无引用方)
- docs/i18n-{naming,shadow,strict}-audit.json (脚本会自动重新生成)

## 删除的 modular lang 文件
- lang/zh-cn/*.js / lang/en-us/*.js (20 个模块文件,内容是上一会话产生的死代码)
- lang/zh-cn/index.js / lang/en-us/index.js (聚合入口)
- lang/DEPRECATED.md (已不再相关)

## 删除的不成熟脚本
- scripts/check_perpage.py (诊断用,已完成)
- scripts/diagnose_keys.py (诊断用,已完成)
- scripts/smart_rename_i18n.py (v1-v3 都 bug,未修完)

## 现状
- lang/ 现在只有 zh-cn.js + en-us.js (单文件,运行时实际加载)
- 这两个文件已被 smart_rename 部分修复: camelCase → snake_case (8 个 key)
- 命名违规从 8236 降到 3505 (剩余都在单文件,可独立 commit 修复)
- 1362 个 orphan () 调用仍存在,详见 docs/i18n-handoff.md
2026-06-25 10:48:15 +08:00

215 lines
6.9 KiB
Python

#!/usr/bin/env python3
"""
i18n key 定位工具
用法:
python scripts/find_i18n_key.py <key_pattern> # 按 key 搜索调用位置
python scripts/find_i18n_key.py -v <value> # 按翻译值反向搜索 key
python scripts/find_i18n_key.py -f <file> # 列出某文件中使用的所有 key
python scripts/find_i18n_key.py --unused # 找出未被使用的 key
python scripts/find_i18n_key.py --duplicate # 找出同翻译不同 key 的重复项
"""
import os
import re
import sys
import json
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
LANG_FILE = os.path.join(PROJECT_ROOT, 'lang', 'zh-cn.js')
SEARCH_DIRS = [
'common',
'components',
'components-diy',
'pages',
'pages_goods',
'pages_order',
'pages_promotion',
'pages_tool',
]
def parse_lang_file(filepath):
"""解析语言包文件,返回展平的 key-value 字典"""
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
match = re.search(r'export const lang = \{(.*?)\n\};', content, re.DOTALL)
if not match:
return {}
body = match.group(1)
lines = body.split('\n')
stack = []
result = {}
for line in lines:
stripped = line.strip()
if not stripped:
continue
indent = len(line) - len(line.lstrip())
level = indent // 4 + 1
while len(stack) >= level:
stack.pop()
obj_match = re.match(r'"([^"]+)"\s*:\s*\{', stripped)
if obj_match:
stack.append(obj_match.group(1))
continue
val_match = re.match(r'"([^"]+)"\s*:\s*"([^"]*)"', stripped)
if val_match:
key = val_match.group(1)
value = val_match.group(2)
full_path = '.'.join(stack + [key])
result[full_path] = value
return result
def find_key_usage(key_pattern):
"""搜索 key 在哪些文件中被使用"""
pattern = re.compile(rf'\$lang\([\'"]({re.escape(key_pattern)})[\'"]')
results = []
for dirname in SEARCH_DIRS:
dirpath = os.path.join(PROJECT_ROOT, dirname)
if not os.path.isdir(dirpath):
continue
for root, dirs, files in os.walk(dirpath):
for fname in files:
if not fname.endswith(('.vue', '.js')):
continue
fpath = os.path.join(root, fname)
try:
with open(fpath, 'r', encoding='utf-8') as f:
content = f.read()
for i, line in enumerate(content.split('\n'), 1):
if pattern.search(line):
rel_path = os.path.relpath(fpath, PROJECT_ROOT)
results.append((rel_path, i, line.strip()))
except:
pass
return results
def find_value_in_lang(value_substr, lang_data):
"""按翻译值反向搜索 key"""
results = []
for k, v in lang_data.items():
if value_substr in v:
results.append((k, v))
return results
def list_file_keys(filepath):
"""列出某个文件中使用的所有 $lang key"""
full_path = os.path.join(PROJECT_ROOT, filepath)
if not os.path.exists(full_path):
print(f"文件不存在: {filepath}")
return []
pattern = re.compile(r'\$lang\([\'"]([^\'"]+)[\'"]')
keys = []
with open(full_path, 'r', encoding='utf-8') as f:
for i, line in enumerate(f, 1):
m = pattern.findall(line)
for k in m:
keys.append((k, i))
return keys
def find_all_used_keys():
"""找出所有被使用的 key"""
pattern = re.compile(r'\$lang\([\'"]([^\'"]+)[\'"]')
used = set()
for dirname in SEARCH_DIRS:
dirpath = os.path.join(PROJECT_ROOT, dirname)
if not os.path.isdir(dirpath):
continue
for root, dirs, files in os.walk(dirpath):
for fname in files:
if not fname.endswith(('.vue', '.js')):
continue
fpath = os.path.join(root, fname)
try:
with open(fpath, 'r', encoding='utf-8') as f:
content = f.read()
matches = pattern.findall(content)
used.update(matches)
except:
pass
return used
def find_duplicate_values(lang_data):
"""找出同翻译不同 key 的重复项"""
value_to_keys = {}
for k, v in lang_data.items():
if v and len(v) >= 2:
if v not in value_to_keys:
value_to_keys[v] = []
value_to_keys[v].append(k)
return {v: ks for v, ks in value_to_keys.items() if len(ks) > 1}
def main():
if len(sys.argv) < 2:
print(__doc__)
return
lang_data = parse_lang_file(LANG_FILE)
if sys.argv[1] == '--unused':
used = find_all_used_keys()
all_keys = set(lang_data.keys())
unused = all_keys - used
print(f"总 key 数: {len(all_keys)}")
print(f"被使用的 key 数: {len(used)}")
print(f"未使用的 key 数: {len(unused)}")
print("\n未使用的 key:")
for k in sorted(unused)[:50]:
print(f" {k} -> \"{lang_data.get(k, '')}\"")
if len(unused) > 50:
print(f" ... 还有 {len(unused) - 50} 个")
return
if sys.argv[1] == '--duplicate':
dups = find_duplicate_values(lang_data)
print(f"同翻译不同 key 的组数: {len(dups)}")
print("\n重复最多的翻译 Top 20:")
sorted_dups = sorted(dups.items(), key=lambda x: -len(x[1]))[:20]
for v, ks in sorted_dups:
print(f'\n "{v}" ({len(ks)} 个 key):')
for k in ks[:8]:
print(f" - {k}")
return
if sys.argv[1] == '-f' and len(sys.argv) > 2:
filepath = sys.argv[2]
keys = list_file_keys(filepath)
print(f"文件 {filepath} 中使用的 key ({len(keys)} 个):")
for k, line in keys:
val = lang_data.get(k, '【未找到】')
print(f" L{line}: {k} -> \"{val}\"")
return
if sys.argv[1] == '-v' and len(sys.argv) > 2:
value = sys.argv[2]
results = find_value_in_lang(value, lang_data)
print(f"包含 \"{value}\" 的翻译 ({len(results)} 个):")
for k, v in results[:30]:
print(f" {k} -> \"{v}\"")
if len(results) > 30:
print(f" ... 还有 {len(results) - 30} 个")
return
# 默认:按 key 搜索
key = sys.argv[1]
usages = find_key_usage(key)
print(f'搜索 key: "{key}"')
print(f"找到 {len(usages)} 处使用:")
for fpath, line, content in usages[:30]:
print(f" {fpath}:{line} {content[:80]}")
if len(usages) > 30:
print(f" ... 还有 {len(usages) - 30} 处")
if __name__ == '__main__':
main()