Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:bug: Correct kernel localized format arguments https://github.com/siyuan-note/siyuan/issues/19430

Daniel241d16d3304a
diff --git a/.github/workflows/i18n.yml b/.github/workflows/i18n.yml
new file mode 100644
index 0000000000..cc9e1e851d
--- /dev/null
+++ b/.github/workflows/i18n.yml
@@ -0,0 +1,22 @@
+name: Language validation
+
+on:
+ pull_request:
+ push:
+ branches: [dev, master]
+
+permissions:
+ contents: read
+
+jobs:
+ languages:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v6
+ - uses: actions/setup-python@v6
+ with:
+ python-version: '3.x'
+ - name: Test language validation
+ run: python -m unittest discover -s scripts -p "test_check_lang_keys.py"
+ - name: Check language keys and kernel placeholders
+ run: python scripts/check-lang-keys.py
diff --git a/AGENTS.md b/AGENTS.md
index 7dcafed7d2..ec91df91d9 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -44,7 +44,8 @@ SiYuan repository guide. Module path `github.com/siyuan-note/siyuan`, license AG
- Domains: `ld246.com` only in `zh-CN.json`; use `liuyun.io` in all other languages
- In `zh-TW` localization and the Traditional Chinese user guide, consistently translate the content-model term Block as `區塊`, including compounds (e.g. `子區塊`, `程式碼區塊`, `區塊 ID`); never abbreviate it as `塊`, and count blocks with `個區塊`
- Translate Block Reference as `區塊引用` and Blockquote as `引述區塊`; preserve non-content-block terms such as `分塊` (data chunks) and `覈取方塊` (Checkbox)
- - After modifying i18n files, run `python scripts/check-lang-keys.py` to verify key completeness across all language files
+ - Preserve each `_kernel` message's Go format argument positions and verbs from `en.json`; when translation requires a different order, use explicit argument indexes such as `%[4]s` and `%[3]d`. Preserve `%%` for literal percent signs
+ - After modifying i18n files, run `python scripts/check-lang-keys.py` to verify key completeness and kernel format argument compatibility across all language files
2. **Cross-platform scripting:**
- Do not assume the current shell is Bash, zsh, or PowerShell. Confirm the shell before using shell-specific syntax; otherwise avoid constructs such as `&&`, heredocs, and `/dev/null`
- For simple sequences, use separate command calls and set the command working directory instead of chaining `cd` with another command
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index 2fbc36bbf8..f3864865d9 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -2618,7 +2618,7 @@
"207": "‫جارٍ استبدال المسار [%d/%d]‬",
"208": "جارٍ رفع قائمة الفهرس...",
"209": "جارٍ رفع فهرس التحقق...",
- "210": "جارٍ التحقق من البيانات السحابية",
+ "210": "جارٍ التحقق من البيانات السحابية %v/%v",
"211": "اكتمل التحقق من البيانات السحابية",
"212": "هناك بعض العيوب في الإصدار الحالي لمزامنة البيانات السحابية، يرجى الترقية إلى أحدث إصدار. آسف على الإزعاج",
"213": "فشل التحقق السحابي، الرجاء محاولة الترقية إلى أحدث إصدار وتسجيل الدخول مرة أخرى في [الإعدادات - الحساب والمزامنة - الحساب] قبل المزامنة",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 2b0ce8f4f5..f6b1889c1e 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -2497,8 +2497,8 @@
"86": "कृपया [सेटिंग्स - प्रमाणीकरण - स्क्रीन लॉक पासवर्ड] कॉन्फ़िगर करें",
"87": "इस स्थान पर नहीं ले जा सकते",
"88": "[%d] डेटा फ़ाइलों का पार्सिंग पूर्ण, शेष प्रसंस्करण [%d]",
- "89": "[%d/%d] ब्लॉक-स्तरीय तत्वों [%s] के [%d] डेटा इंडेक्स बनाए",
- "90": "[%d/%d] ब्लॉक-स्तरीय तत्वों [%s] के [%d] खोज इंडेक्स बनाए",
+ "89": "[%[1]d/%[2]d] ब्लॉक-स्तरीय तत्वों [%[4]s] के [%[3]d] डेटा इंडेक्स बनाए",
+ "90": "[%[1]d/%[2]d] ब्लॉक-स्तरीय तत्वों [%[4]s] के [%[3]d] खोज इंडेक्स बनाए",
"91": "असंदर्भित एसेट की सफाई पूर्ण। [%d] फ़ाइलें हटाई गईं, कुल [%s] डिस्क स्थान खाली किया गया",
"92": "दस्तावेज़ पार्स कर रहा है [%s]",
"93": "[%d/%d] दस्तावेज़ [%s] से संबंधित इंडेक्स साफ़ किया",
@@ -2642,7 +2642,7 @@
"231": "क्लाउड स्टोरेज में असंदर्भित डेटा ऑब्जेक्ट हटा रहा है...",
"232": "क्लाउड डेटा स्टोरेज साफ कर दिया गया है। [%d] स्नैपशॉट और [%d] डेटा ऑब्जेक्ट हटाए गए, और कुल [%s] डिस्क स्थान खाली किया गया",
"233": "उपयोगकर्ता गाइड बंद कर रहा है...",
- "234": "[%d/%d] दस्तावेज़ [%s] के [%d] पठनीय पथ अपडेट किए",
+ "234": "[%[1]d/%[2]d] दस्तावेज़ [%[4]s] के [%[3]d] पठनीय पथ अपडेट किए",
"235": "[%d/%d] बाज़ार पैकेज अपडेट कर रहा है...",
"236": "[%d/%d] बाज़ार पैकेज [%s] अपडेट कर रहा है...",
"237": "बाज़ार पैकेज अपडेट पूर्ण: %d सफल, %d विफल, %d अपडेट की आवश्यकताओं को पूरा नहीं करते",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 19ad14a7b3..33b50ce5c3 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -2497,8 +2497,8 @@
"86": "[설정 - 인증 - 화면 잠금 비밀번호]를 구성하세요",
"87": "이 위치로 이동할 수 없습니다",
"88": "[%d]개 데이터 파일 파싱 완료, 남은 처리 [%d]",
- "89": "[%d/%d] 블록 레벨 요소 [%s]의 데이터 인덱스 [%d]개 생성됨",
- "90": "[%d/%d] 블록 레벨 요소 [%s]의 검색 인덱스 [%d]개 생성됨",
+ "89": "[%[1]d/%[2]d] 블록 레벨 요소 [%[4]s]의 데이터 인덱스 [%[3]d]개 생성됨",
+ "90": "[%[1]d/%[2]d] 블록 레벨 요소 [%[4]s]의 검색 인덱스 [%[3]d]개 생성됨",
"91": "참조되지 않은 에셋 정리가 완료되었습니다. [%d]개 파일이 삭제되어 총 [%s]의 디스크 공간이 확보되었습니다",
"92": "문서 [%s] 파싱 중",
"93": "[%d/%d] 문서 [%s] 관련 인덱스 정리됨",
@@ -2642,7 +2642,7 @@
"231": "클라우드 저장소 미참조 데이터 객체 삭제 중...",
"232": "클라우드 데이터 저장소가 정리되었습니다. [%d]개의 스냅샷과 [%d]개의 데이터 객체가 삭제되었으며 총 [%s]의 디스크 공간이 확보되었습니다",
"233": "사용자 가이드 닫는 중...",
- "234": "문서 [%s]의 읽을 수 있는 경로 [%d]개 업데이트됨 [%d/%d]",
+ "234": "문서 [%[4]s]의 읽을 수 있는 경로 [%[3]d]개 업데이트됨 [%[1]d/%[2]d]",
"235": "[%d/%d] 마켓플레이스 패키지 업데이트 중...",
"236": "[%d/%d] 마켓플레이스 패키지 [%s] 업데이트 중...",
"237": "마켓플레이스 패키지 업데이트 완료: %d개 성공, %d개 실패, %d개는 업데이트 요구 사항을 충족하지 않음",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index 0b950c4741..1bfc7e5e04 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -2497,8 +2497,8 @@
"86": "Lütfen [Ayarlar - Kimlik Doğrulama - Erişim yetkilendirme kodu] kısmını yapılandır",
"87": "Bu konuma taşınamaz",
"88": "[%d] veri dosyası çözümlendi, [%d] kaldı",
- "89": "[%d/%d] [%s] blok düzeyinde veri indeksleri oluşturuldu [%d]",
- "90": "[%d/%d] [%s] blok düzeyinde arama indeksleri oluşturuldu [%d]",
+ "89": "[%[1]d/%[2]d] [%[4]s] blok düzeyinde veri indeksleri oluşturuldu [%[3]d]",
+ "90": "[%[1]d/%[2]d] [%[4]s] blok düzeyinde arama indeksleri oluşturuldu [%[3]d]",
"91": "Referanssız varlıklar temizlendi. [%d] dosya silindi, toplamda [%s] disk alanı boşaltıldı",
"92": "Belge çözümleniyor [%s]",
"93": "[%d/%d] [%s] belgesiyle ilgili dizin temizlendi",
@@ -2642,7 +2642,7 @@
"231": "Bulut depolamada kullanılmayan veri nesneleri siliniyor...",
"232": "Bulut veri depolama temizlendi. [%d] anlık görüntü ve [%d] veri nesnesi silindi, toplamda [%s] disk alanı boşaltıldı",
"233": "Kullanıcı rehberi kapatılıyor...",
- "234": "[%d/%d] [%s] belgesinin okunabilir yolları güncellendi [%d]",
+ "234": "[%[1]d/%[2]d] [%[4]s] belgesinin okunabilir yolları güncellendi [%[3]d]",
"235": "[%d/%d] pazar paketi güncelleniyor...",
"236": "[%d/%d] pazar paketi [%s] güncelleniyor...",
"237": "Pazar paketi güncellemeleri tamamlandı: %d güncellendi, %d başarısız oldu, %d güncelleme gereksinimlerini karşılamıyor",
diff --git a/scripts/check-lang-keys.py b/scripts/check-lang-keys.py
index 6f4eefb7a5..80ac77c59f 100644
--- a/scripts/check-lang-keys.py
+++ b/scripts/check-lang-keys.py
@@ -8,6 +8,8 @@ and finds:
- Duplicate keys: keys that appear multiple times in the same file
using statistical methods.
+同时以 en.json 为基准,校验内核消息的 Go 格式参数索引和动词。
+
Usage:
python scripts/check-lang-keys.py
python scripts/check-lang-keys.py -d app/appearance/langs
@@ -18,8 +20,8 @@ Options:
-h, --help Show help message and exit
Exit codes:
- 0 All language files have complete keys
- 1 Some language files have missing or extra keys
+ 0 All language files have complete keys and compatible kernel placeholders
+ 1 Language files have key, format, or loading errors
"""
import json
@@ -198,6 +200,71 @@ def load_lang_file(file_path):
return None, None, [], {}
+def format_arguments(message):
+ """按 Go fmt 的参数索引解析动词,保留每个参数的使用次数和用途。"""
+ arguments = Counter()
+ next_arg = 1
+ pos = 0
+ while pos < len(message):
+ if message[pos] != "%":
+ pos += 1
+ continue
+ start = pos
+ pos += 1
+ while pos < len(message) and message[pos] in "+-# 0":
+ pos += 1
+ # 索引可指定宽度、精度或值;每次消费参数后,后续隐式参数从下一位开始。
+ while pos < len(message):
+ char = message[pos]
+ if char == "[":
+ match = re.match(r"\[([1-9][0-9]*)\]", message[pos:])
+ if not match:
+ raise ValueError(f"Invalid argument index at offset {pos}")
+ next_arg = int(match.group(1))
+ pos += len(match.group(0))
+ elif char == "*":
+ arguments[(next_arg, "*")] += 1
+ next_arg += 1
+ pos += 1
+ elif char in "0123456789.":
+ pos += 1
+ else:
+ break
+ if pos == len(message) or message[pos] not in "vTtbcdoOxXUeEfFgGspq%":
+ raise ValueError(f"Invalid format directive at offset {start}")
+ verb = message[pos]
+ pos += 1
+ if verb != "%":
+ arguments[(next_arg, verb)] += 1
+ next_arg += 1
+ return arguments
+
+
+def check_kernel_placeholders(lang_data):
+ """以英文数字键为基准,检查所有内核消息的参数及格式动词。"""
+ reference = lang_data.get("en.json", {}).get("_kernel")
+ if not isinstance(reference, dict):
+ print("Error: en.json must contain a _kernel object")
+ return False
+ valid = True
+ for name, data in lang_data.items():
+ kernel = data.get("_kernel", {})
+ for key, message in reference.items():
+ if not key.isdecimal():
+ continue
+ try:
+ expected = format_arguments(message)
+ actual = format_arguments(kernel[key])
+ if actual == expected:
+ continue
+ detail = f"expected {dict(expected)}, got {dict(actual)}"
+ except (KeyError, TypeError, ValueError) as error:
+ detail = str(error)
+ print(f"Error: {name} _kernel.{key}: {detail}")
+ valid = False
+ return valid
+
+
def check_lang_keys(langs_dir):
"""Check if language file keys are complete.
@@ -219,14 +286,18 @@ def check_lang_keys(langs_dir):
# Load all language files
lang_keys = {}
+ lang_data = {}
+ load_failed = False
duplicate_keys_by_file = {}
key_order_by_file = {}
for lang_file in sorted(langs_path.glob("*.json")):
keys, data, duplicates, key_order = load_lang_file(lang_file)
if keys is None:
+ load_failed = True
continue
lang_keys[lang_file.name] = keys
+ lang_data[lang_file.name] = data
if duplicates:
duplicate_keys_by_file[lang_file.name] = duplicates
key_order_by_file[lang_file.name] = key_order
@@ -266,7 +337,7 @@ def check_lang_keys(langs_dir):
print(f"Unexpected keys: {len(unexpected_keys)}\n")
# Check keys for each file
- all_complete = True
+ all_complete = check_kernel_placeholders(lang_data) and not load_failed
file_issues = {} # {lang_name: {'missing': set, 'extra': set, 'duplicates': list}}
for lang_name, keys in lang_keys.items():
@@ -284,8 +355,10 @@ def check_lang_keys(langs_dir):
# Output results
if all_complete and not file_issues:
- print("All language files have complete keys!")
+ print("All language files have complete keys and compatible kernel placeholders!")
return True
+ if not file_issues:
+ return False
# Report issues grouped by file
print("Issues found:")
diff --git a/scripts/test_check_lang_keys.py b/scripts/test_check_lang_keys.py
new file mode 100644
index 0000000000..7d3c99360b
--- /dev/null
+++ b/scripts/test_check_lang_keys.py
@@ -0,0 +1,62 @@
+import importlib.util
+import json
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import unittest
+
+
+SCRIPT = Path(__file__).with_name("check-lang-keys.py")
+SPEC = importlib.util.spec_from_file_location("check_lang_keys", SCRIPT)
+checker = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(checker)
+
+
+class KernelPlaceholdersTest(unittest.TestCase):
+ def test_argument_order(self):
+ baseline = checker.format_arguments("%d %d %d %s")
+ for message in ("%d %d %s %d", "%s %d %d %d"):
+ self.assertNotEqual(baseline, checker.format_arguments(message))
+ for message in ("%[1]d %[2]d %[4]s %[3]d", "%[4]s %[3]d %[1]d %d"):
+ self.assertEqual(baseline, checker.format_arguments(message))
+
+ def test_verbs_and_escaping(self):
+ self.assertEqual({}, checker.format_arguments("100%%"))
+ for verb in "vTtbcdoOxXUeEfFgGspq":
+ self.assertEqual({(1, verb): 1}, checker.format_arguments("%" + verb))
+ self.assertEqual({(1, "f"): 1}, checker.format_arguments("%08.2f"))
+ self.assertNotEqual(checker.format_arguments("%v %v"), checker.format_arguments(""))
+ self.assertNotEqual(checker.format_arguments("%s"), checker.format_arguments("%[1]s %[1]s"))
+
+ def test_dynamic_width_precision(self):
+ self.assertEqual(
+ checker.format_arguments("%*.*f"),
+ checker.format_arguments("%[1]*.[2]*[3]f"),
+ )
+
+ def test_invalid_directives(self):
+ for message in ("%", "%[0]s", "%[x]s", "%[2", "%z"):
+ with self.subTest(message=message), self.assertRaises(ValueError):
+ checker.format_arguments(message)
+
+ def test_repository_translations(self):
+ directory = SCRIPT.parent.parent / "app/appearance/langs"
+ data = {path.name: json.loads(path.read_text(encoding="utf-8"))
+ for path in directory.glob("*.json")}
+ self.assertTrue(checker.check_kernel_placeholders(data))
+
+ def test_cli_rejects_drift(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ for name, message in (("en", "%v %v"), ("test", "missing")):
+ (root / (name + ".json")).write_text(
+ json.dumps({"_kernel": {"210": message}}), encoding="utf-8")
+ result = subprocess.run([sys.executable, str(SCRIPT), "--dir", directory],
+ capture_output=True, text=True)
+ self.assertEqual(1, result.returncode)
+ self.assertIn("test.json _kernel.210", result.stdout)
+
+
+if __name__ == "__main__":
+ unittest.main()