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

运行 Eclipse JAR 导出模式对比、META-INF/MANIFEST.MF 生成与 ZIP 归档完整性离线核验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-create-jar-files.py
explore-create-jar-files.py163 行
"""Offline Eclipse JAR Export wizard, MANIFEST.MF & zipfile integrity verifier for Ch17 (create-jar-files)."""
import json
import tempfile
import zipfile
from pathlib import Path

VERSION = "CPython 3.12.14 offline Eclipse JAR-export/manifest 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 build_manifest(main_class=None, created_by="Eclipse JAR Export Verifier"):
    lines = [
        "Manifest-Version: 1.0",
        f"Created-By: {created_by}",
    ]
    if main_class:
        lines.append(f"Main-Class: {main_class}")
    return "\r\n".join(lines) + "\r\n"


def parse_manifest(text):
    headers = {}
    for line in text.splitlines():
        if ":" in line:
            k, v = line.split(":", 1)
            headers[k.strip()] = v.strip()
    return headers


def export_jar(proj_dir, jar_path, include_sources=False, main_class=None):
    manifest_text = build_manifest(main_class=main_class)
    with zipfile.ZipFile(jar_path, "w", compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr("META-INF/MANIFEST.MF", manifest_text.encode("utf-8"))
        bin_dir = proj_dir / "bin"
        for p in sorted(bin_dir.rglob("*.class")):
            zf.write(p, p.relative_to(bin_dir).as_posix())
        if include_sources:
            src_dir = proj_dir / "src"
            for p in sorted(src_dir.rglob("*")):
                if p.is_file():
                    zf.write(p, p.relative_to(src_dir).as_posix())


def main():
    cases = []

    with tempfile.TemporaryDirectory() as tmp:
        proj = Path(tmp) / "OrderApp"
        (proj / "bin" / "com" / "mbsky" / "demo").mkdir(parents=True)
        (proj / "src" / "com" / "mbsky" / "demo").mkdir(parents=True)
        # Minimal Java class file magic header bytes (0xCAFEBABE) for offline archive verification
        (proj / "bin" / "com" / "mbsky" / "demo" / "App.class").write_bytes(b"\xca\xfe\xba\xbe\x00\x00\x00\x34")
        (proj / "src" / "com" / "mbsky" / "demo" / "App.java").write_text(
            "package com.mbsky.demo;\npublic class App { public static void main(String[] a) {} }\n",
            encoding="utf-8",
        )
        (proj / "src" / "app.properties").write_text("version=1.0\n", encoding="utf-8")

        jar_default = Path(tmp) / "order-default.jar"
        jar_with_src = Path(tmp) / "order-with-src.jar"
        export_jar(proj, jar_default, include_sources=False, main_class="com.mbsky.demo.App")
        export_jar(proj, jar_with_src, include_sources=True, main_class="com.mbsky.demo.App")

        # Case 1: Default export (.class only) vs Export Java source files and resources
        with zipfile.ZipFile(jar_default, "r") as z1, zipfile.ZipFile(jar_with_src, "r") as z2:
            names_default = sorted(z1.namelist())
            names_with_src = sorted(z2.namelist())
            manifest_raw = z1.read("META-INF/MANIFEST.MF").decode("utf-8")
            crc_ok = z1.testzip() is None and z2.testzip() is None
            class_magic_ok = z1.read("com/mbsky/demo/App.class").startswith(b"\xca\xfe\xba\xbe")

    cases.append(
        check(
            "jar_export_class_only_vs_with_sources",
            "Verify default JAR export includes compiled .class only while checking source option adds .java and resources",
            {
                "default_entries": ["META-INF/MANIFEST.MF", "com/mbsky/demo/App.class"],
                "with_sources_entries": [
                    "META-INF/MANIFEST.MF",
                    "app.properties",
                    "com/mbsky/demo/App.class",
                    "com/mbsky/demo/App.java",
                ],
            },
            {
                "default_entries": names_default,
                "with_sources_entries": names_with_src,
            },
        )
    )

    # Case 2: MANIFEST.MF generation, trailing CRLF requirement, and Main-Class parsing
    parsed_mf = parse_manifest(manifest_raw)
    cases.append(
        check(
            "manifest_mf_generation_and_main_class",
            "Verify META-INF/MANIFEST.MF contains Manifest-Version, Main-Class, and trailing newline",
            {
                "manifest_version": "1.0",
                "main_class": "com.mbsky.demo.App",
                "ends_with_newline": True,
            },
            {
                "manifest_version": parsed_mf["Manifest-Version"],
                "main_class": parsed_mf["Main-Class"],
                "ends_with_newline": manifest_raw.endswith("\r\n"),
            },
        )
    )

    # Case 3: Runnable JAR integrity verification (ZIP CRC + Main-Class maps to existing .class entry)
    expected_entry = parsed_mf["Main-Class"].replace(".", "/") + ".class"
    cases.append(
        check(
            "runnable_jar_integrity_verification",
            "Verify JAR passes ZIP CRC integrity check and Main-Class resolves to a valid .class entry",
            {
                "zip_crc_ok": True,
                "main_class_entry_present": True,
                "class_magic_cafebabe": True,
            },
            {
                "zip_crc_ok": crc_ok,
                "main_class_entry_present": expected_entry in names_default,
                "class_magic_cafebabe": class_magic_ok,
            },
        )
    )

    # Case 4: File > Export filter for 'JAR' and destination filename check
    export_wizards = ["Java / JAR file", "Java / Runnable JAR file", "Java / Javadoc", "General / Archive File"]
    jar_matches = [w for w in export_wizards if "jar" in w.lower()]
    dest_ok = "dist/order-app.jar".endswith(".jar")
    cases.append(
        check(
            "export_wizard_filter_and_path_validation",
            "Verify File > Export filtering for 'JAR' distinguishes JAR file vs Runnable JAR file and validates .jar target",
            {
                "jar_matches": ["Java / JAR file", "Java / Runnable JAR file"],
                "valid_jar_destination": True,
            },
            {
                "jar_matches": jar_matches,
                "valid_jar_destination": dest_ok,
            },
        )
    )

    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-create-jar-files-lab/explore-create-jar-files.py

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

下载课程关联工程包:Eclipse

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

下载课程关联工程包:Eclipse

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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