蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 Eclipse 工作空间编码首选项、GBK/UTF-8 编解码比对与三级编码继承离线核验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-charset.py
explore-charset.py120 行
"""Offline Eclipse workspace charset & encoding inheritance verifier for Ch03 (charset)."""
import json
import tempfile
from pathlib import Path

VERSION = "CPython 3.12.14 offline Eclipse charset/preferences verifier (desktop Eclipse SWT GUI absent)"


def check(name, summary, expected, actual):
    return {
        "name": name,
        "summary": summary,
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def parse_eclipse_prefs(text):
    result = {}
    for line in text.splitlines():
        line = line.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        k, v = line.split("=", 1)
        result[k.strip()] = v.strip()
    return result


def resolve_file_encoding(ws_prefs, proj_prefs, rel_path):
    file_key = f"encoding/{rel_path}"
    if file_key in proj_prefs:
        return proj_prefs[file_key]
    if "encoding/<project>" in proj_prefs:
        return proj_prefs["encoding/<project>"]
    return ws_prefs.get("encoding", "GBK")


def main():
    cases = []

    # Case 1: Workspace org.eclipse.core.resources.prefs UTF-8 persistence
    with tempfile.TemporaryDirectory() as tmp:
        prefs_file = (
            Path(tmp)
            / ".metadata"
            / ".plugins"
            / "org.eclipse.core.runtime"
            / ".settings"
            / "org.eclipse.core.resources.prefs"
        )
        prefs_file.parent.mkdir(parents=True, exist_ok=True)
        prefs_file.write_text(
            "eclipse.preferences.version=1\nencoding=UTF-8\n",
            encoding="utf-8",
        )
        parsed = parse_eclipse_prefs(prefs_file.read_text(encoding="utf-8"))
    cases.append(
        check(
            "workspace_resources_prefs_utf8",
            "Verify Workspace Text file encoding preference stored in org.eclipse.core.resources.prefs",
            {"eclipse.preferences.version": "1", "encoding": "UTF-8"},
            parsed,
        )
    )

    # Case 2: GBK vs UTF-8 encoding round-trip and mismatch detection
    sample = '// 中文注释:统一采用 UTF-8 编码\nString title = "蓝色天空网";\n'
    utf8_bytes = sample.encode("utf-8")
    gbk_bytes = sample.encode("gbk")
    utf8_roundtrip_ok = utf8_bytes.decode("utf-8") == sample
    mismatched_decoded = utf8_bytes.decode("gbk", errors="replace")
    mismatch_detected = mismatched_decoded != sample
    cases.append(
        check(
            "gbk_vs_utf8_roundtrip_check",
            "Verify clean UTF-8 round-trip for Chinese Java source vs mojibake on GBK/UTF-8 mismatch",
            {
                "utf8_roundtrip_ok": True,
                "gbk_utf8_bytes_differ": True,
                "mismatch_produces_corruption": True,
            },
            {
                "utf8_roundtrip_ok": utf8_roundtrip_ok,
                "gbk_utf8_bytes_differ": utf8_bytes != gbk_bytes,
                "mismatch_produces_corruption": mismatch_detected,
            },
        )
    )

    # Case 3: Eclipse encoding inheritance hierarchy (workspace -> project -> file)
    ws_prefs = {"encoding": "UTF-8"}
    proj_prefs = {
        "eclipse.preferences.version": "1",
        "encoding/<project>": "UTF-8",
        "encoding/src/legacy/ReportGbk.java": "GBK",
    }
    cases.append(
        check(
            "project_encoding_override_resolution",
            "Verify Eclipse file encoding resolution precedence across file, project, and workspace scopes",
            {
                "normal_java": "UTF-8",
                "legacy_override": "GBK",
                "fallback_workspace": "UTF-8",
            },
            {
                "normal_java": resolve_file_encoding(ws_prefs, proj_prefs, "src/app/Main.java"),
                "legacy_override": resolve_file_encoding(ws_prefs, proj_prefs, "src/legacy/ReportGbk.java"),
                "fallback_workspace": resolve_file_encoding(ws_prefs, {}, "src/app/Helper.java"),
            },
        )
    )

    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/eclipse-charset-lab/explore-charset.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-charset.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Eclipse

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2261.zip

下载课程关联工程包:Eclipse

课程关联工程包(登记关联35章) · 含当前章节或实例 · mbskycom202612a2259.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习