Dever v0.0.2

This commit is contained in:
Codex committed 2026-11-27 06:03:56 +00:00
commit e6e175ebcf
816 files changed
+120349

No files matched your search

+301
View File
@@ -0,0 +1,301 @@
#!/usr/bin/env python3
"""在 Debian 13 开发容器内组装 Linux x86_64 完整离线开发包。"""
import argparse
import hashlib
import json
import os
from pathlib import Path
import shutil
import subprocess
import tomllib
SOURCE = Path(__file__).resolve().parents[1]
TRIPLE = "x86_64-unknown-linux-gnu"
PACKAGES = (
"gcc-14-x86-64-linux-gnu", "cpp-14-x86-64-linux-gnu", "libgcc-14-dev",
"libc6-dev", "linux-libc-dev", "binutils-x86-64-linux-gnu", "libc6", "libgcc-s1",
)
def native_input(path):
"""只保留原生 C 构建所需工具;Rust LTO 使用包内 LLVM,不需要 GCC LTO。"""
name = str(path)
if name.startswith("/usr/include/"):
return True
if path.parent == Path("/usr/bin"):
return path.name in {
"x86_64-linux-gnu-gcc-14", "x86_64-linux-gnu-as",
"x86_64-linux-gnu-ld", "x86_64-linux-gnu-ar", "x86_64-linux-gnu-ranlib",
}
if name.startswith("/usr/libexec/gcc/"):
return path.name in {"cc1", "collect2", "liblto_plugin.so", "lto-wrapper"}
if name.startswith("/usr/lib/gcc/"):
return "/include/" in name or path.name in {
"libgcc.a", "libgcc_eh.a", "libgcc_s.so", "crtbegin.o", "crtbeginS.o",
"crtbeginT.o", "crtend.o", "crtendS.o",
"liblto_plugin.so",
}
return path.parent in {Path("/usr/lib/x86_64-linux-gnu"), Path("/usr/lib64")}
def output(*arguments, **options):
return subprocess.check_output(arguments, text=True, **options).strip()
def digest(path):
with path.open("rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest()
def copy(source, destination):
"""只解引用作者明确选定的工具文件,不复制 Cargo home 或用户配置。"""
if source.is_dir():
shutil.copytree(source, destination, dirs_exist_ok=True)
else:
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source, destination)
destination.chmod(0o755 if os.access(source, os.X_OK) else 0o644)
def script(path, body):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text('#!/bin/sh\nset -eu\ntools=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)\n' + body)
path.chmod(0o755)
def native_tools(tools):
"""保留 Debian 工具的相对安装布局;glibc 只进链接 sysroot,不覆盖宿主加载器。"""
base = {str(Path(path).resolve()) for path in output("dpkg-query", "-L", "libc6").splitlines()}
packages = set(PACKAGES)
executables = []
for package in PACKAGES:
for name in output("dpkg-query", "-L", package).splitlines():
path = Path(name)
if not path.is_file() or not native_input(path):
continue
copy(path, tools / "native" / path.relative_to("/"))
# Debian 的链接脚本使用 /lib;发行包展开 usrmerge 别名,不改写官方库文件。
if package == "libc6":
copy(path, tools / "native" / path.relative_to("/usr"))
if os.access(path, os.X_OK):
with path.open("rb") as stream:
if stream.read(4) == b"\x7fELF":
executables.append(path)
for name in ("as", "ld", "ar"):
copy(Path(f"/usr/bin/x86_64-linux-gnu-{name}"), tools / "native/usr/bin" / name)
libraries = set()
for executable in executables:
listing = subprocess.run(["ldd", str(executable)], text=True, capture_output=True)
if listing.returncode and "not a dynamic executable" not in listing.stderr + listing.stdout:
raise RuntimeError(f"ldd {executable}: {listing.stderr}{listing.stdout}")
for line in listing.stdout.splitlines():
if "=> not found" in line:
raise RuntimeError(line)
fields = line.split()
if "=>" in fields and fields[2].startswith("/"):
library = Path(fields[2])
if str(library.resolve()) not in base:
libraries.add(library)
for library in sorted(libraries):
copy(library, tools / "lib" / library.name)
owner = output("dpkg-query", "-S", str(library.resolve())).splitlines()[0].split(": ", 1)[0]
packages.add(owner)
copy(Path("/usr/lib/x86_64-linux-gnu/libgcc_s.so.1"), tools / "lib/libgcc_s.so.1")
packages.add("libgcc-s1")
for package in sorted(packages):
name = package.split(":", 1)[0]
copy(Path("/usr/share/doc") / name / "copyright", tools / "licenses" / name / "copyright")
copy(Path("/usr/share/common-licenses"), tools / "licenses/common")
(tools / "native-packages.txt").write_text(output("dpkg-query", "-W", *sorted(packages)) + "\n")
script(tools / "bin/cc", '''export LD_LIBRARY_PATH="$tools/lib"
exec "$tools/native/usr/bin/x86_64-linux-gnu-gcc-14" \\
--sysroot="$tools/native" \\
-B"$tools/native/usr/lib/gcc/x86_64-linux-gnu/14/" \\
-B"$tools/native/usr/libexec/gcc/x86_64-linux-gnu/14/" \\
-B"$tools/native/usr/bin/" \\
-B"$tools/native/usr/lib/x86_64-linux-gnu/" "$@"
''')
def rust_tools(tools, version, vendor):
rust = Path(output("rustc", f"+{version}", "--print", "sysroot"))
if f"host: {TRIPLE}" not in output("rustc", f"+{version}", "-vV"):
raise RuntimeError(f"this package requires the official {TRIPLE} toolchain")
for name in ("cargo", "rustc"):
copy(rust / "bin" / name, tools / "rust/bin" / name)
for library in (rust / "lib").glob("*.so*"):
if not library.is_symlink():
copy(library, tools / "rust/lib" / library.name)
for name in ("lib", "bin"):
copy(rust / "lib/rustlib" / TRIPLE / name, tools / "rust/lib/rustlib" / TRIPLE / name)
# 只裁剪已链接的工具;标准库 rlib/rmeta 中的符号、类型元数据与位码仍用于编译。
binaries = [*(tools / "rust/bin").iterdir(), *(tools / "rust/lib").glob("*.so*")]
binaries.extend(path for path in (tools / "rust/lib/rustlib" / TRIPLE / "bin").rglob("*")
if path.is_file())
for binary in binaries:
# 官方 .so 目录也含链接脚本,按原样保留,只处理 ELF 文件。
with binary.open("rb") as stream:
if stream.read(4) == b"\x7fELF":
subprocess.run(["strip", "--strip-unneeded", str(binary)], check=True)
copy(rust / "share/doc/rust", tools / "licenses/rust")
if vendor:
copy(vendor, tools / "vendor")
else:
subprocess.run([
"cargo", f"+{version}", "vendor", "--locked", "--offline", "--versioned-dirs",
str(tools / "vendor"),
], cwd=SOURCE / "rust", check=True)
config = tools / ".cargo/config.toml"
config.parent.mkdir()
config.write_text('''[source.crates-io]
replace-with = "vendored-sources"
[source.vendored-sources]
directory = "vendor"
''')
script(tools / "bin/cargo", '''export CARGO_HOME="$tools/.cargo"
export RUSTC="$tools/rust/bin/rustc"
export CC="$tools/bin/cc"
export AR="$tools/native/usr/bin/x86_64-linux-gnu-ar"
export CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER="$CC"
export CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER="$tools/bin/aarch64-linux-gnu-gcc"
export CC_aarch64_unknown_linux_gnu="$tools/bin/aarch64-linux-gnu-gcc"
export AR_aarch64_unknown_linux_gnu="$tools/cross/usr/bin/aarch64-linux-gnu-ar"
export LD_LIBRARY_PATH="$tools/cross/usr/lib/x86_64-linux-gnu:$tools/lib"
export PATH="$tools/native/usr/bin:/usr/bin:/bin"
exec "$tools/rust/bin/cargo" --config "$tools/.cargo/config.toml" "$@"
''')
script(tools / "bin/rustc", '''export LD_LIBRARY_PATH="$tools/lib"
exec "$tools/rust/bin/rustc" "$@"
''')
def prepare(compiler, work):
work.mkdir()
bundle = work / "dever"
bundle.mkdir()
for name in ("rust/Cargo.toml", "rust/Cargo.lock", "rust/src", "lib",
"skills/dever/SKILL.md", "GETTING_STARTED.md", "LANGUAGE.md",
"DOCUMENTATION.md", "sdk/README.md",
"test/rust/native/combinations.dever"):
copy(SOURCE / name, bundle / name)
for language in ("python", "javascript", "go", "c"):
for path in sorted((SOURCE / "sdk" / language).iterdir()):
if path.is_file():
copy(path, bundle / path.relative_to(SOURCE))
copy(compiler, bundle / "bin/dever-core")
script(bundle / "bin/dever", '''export DEVER_ROOT="$tools"
exec "$tools/bin/dever-core" "$@"
''')
return bundle
def aarch64_tools(tools, native, standard):
"""复用已准备的 Debian 交叉工具与官方目标标准库,不带旧 Dever 运行库。"""
copy(standard, tools / "rust/lib/rustlib/aarch64-unknown-linux-gnu")
for name in ("usr/aarch64-linux-gnu", "usr/lib/gcc-cross/aarch64-linux-gnu",
"usr/libexec/gcc-cross/aarch64-linux-gnu", "usr/lib/x86_64-linux-gnu"):
# libcc1 是 GDB 的表达式求值插件;包内 Rust/C 构建不包含调试器。
shutil.copytree(native / name, tools / "cross" / name,
ignore=shutil.ignore_patterns("libcc1.so"))
for name in ("gcc-14", "as", "ld", "ar", "ranlib"):
copy(native / "usr/bin" / f"aarch64-linux-gnu-{name}",
tools / "cross/usr/bin" / f"aarch64-linux-gnu-{name}")
for path in (native / "usr/share/doc").iterdir():
if any(name in path.name for name in ("aarch64", "arm64", "cross-base")):
copy(path / "copyright", tools / "licenses/cross" / path.name / "copyright")
script(tools / "bin/aarch64-linux-gnu-gcc", '''export LD_LIBRARY_PATH="$tools/cross/usr/lib/x86_64-linux-gnu:$tools/lib"
exec "$tools/cross/usr/bin/aarch64-linux-gnu-gcc-14" \\
--sysroot="$tools/cross" \\
-B"$tools/cross/usr/lib/gcc-cross/aarch64-linux-gnu/14/" \\
-B"$tools/cross/usr/libexec/gcc-cross/aarch64-linux-gnu/14/" \\
-B"$tools/cross/usr/bin/" "$@"
''')
def record(bundle, compiler):
files = []
for path in sorted(bundle.rglob("*")):
if path.is_symlink():
raise RuntimeError(f"release contains a symlink: {path}")
if path.is_file():
files.append({"path": path.relative_to(bundle).as_posix(),
"bytes": path.stat().st_size, "sha256": digest(path),
"executable": os.access(path, os.X_OK)})
version = tomllib.loads((bundle / "rust/Cargo.toml").read_text())["package"]["version"]
if output(str(compiler), "--version") != f"dever {version}":
raise RuntimeError("compiler version differs from release sources")
manifest = {"format": "dever-development-1", "version": version, "target": TRIPLE,
"rust": "1.95.0", "compiler_sha256": digest(compiler), "files": files}
(bundle / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
return manifest
def external_tools(home, bundle):
"""只选独立准备目录中的工具和下载缓存;不带日志、配置或编译缓存。"""
home = home.resolve(strict=True)
selected = ["tools/go", "tools/node", "tools/uv", "tools/python", "tools/patchelf",
"go/modules", "npm/_cacache", "uv/archive-v0", "uv/wheels-v5",
"uv/simple-v18", "uv/sdists-v9"]
for name in selected:
source = home / name
if not source.is_dir():
raise RuntimeError(f"external distribution input is not prepared: {name}")
for path in source.rglob("*"):
if path.is_symlink() and not path.resolve(strict=True).is_relative_to(home):
raise RuntimeError(f"external cache link escapes its prepared directory: {path}")
copy(source, bundle / "external" / name)
script(bundle / "bin/dever", '''export DEVER_ROOT="$tools"
export DEVER_HOME="${DEVER_HOME:-$tools/external}"
exec "$tools/bin/dever-core" "$@"
''')
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--compiler", required=True, type=Path)
parser.add_argument("--work", required=True, type=Path, help="new staging directory")
parser.add_argument("--output", required=True, type=Path, help="new .tar.xz or .tar.gz archive")
parser.add_argument("--external-home", type=Path, help="isolated prepared DEVER_HOME to include official tools and dependency download caches")
parser.add_argument("--aarch64-native", type=Path, help="prepared Debian 13 cross-GCC root; paired with --aarch64-std")
parser.add_argument("--aarch64-std", type=Path, help="official Rust 1.95 rustlib/aarch64-unknown-linux-gnu directory")
args = parser.parse_args()
if bool(args.aarch64_native) != bool(args.aarch64_std):
parser.error("--aarch64-native and --aarch64-std must be provided together")
system = Path("/etc/os-release").read_text()
if 'ID=debian\n' not in system or 'VERSION_ID="13"' not in system:
parser.error("prepare this package in the Debian 13 development container")
args.compiler = args.compiler.resolve(strict=True)
args.work = args.work.absolute()
args.output = args.output.absolute()
if not args.output.name.endswith((".tar.xz", ".tar.gz")):
parser.error("output must end in .tar.xz or .tar.gz")
checksum = Path(str(args.output) + ".sha256")
if args.output.exists() or checksum.exists():
parser.error("output archive and checksum must not exist")
bundle = prepare(args.compiler, args.work)
tools = bundle / "toolchain"
tools.mkdir()
native_tools(tools)
rust_tools(tools, "1.95.0", None)
if args.aarch64_native:
aarch64_tools(tools, args.aarch64_native.resolve(strict=True), args.aarch64_std.resolve(strict=True))
if args.external_home:
external_tools(args.external_home, bundle)
copy(SOURCE / "build/README.md", bundle / "DEVELOPMENT.md")
manifest = record(bundle, args.compiler)
args.output.parent.mkdir(parents=True, exist_ok=True)
compressor = "xz -3 -T4" if args.output.suffix == ".xz" else "gzip -6"
with args.output.open("xb") as stream:
subprocess.run(["tar", "-C", str(args.work), "-I", compressor, "-cf", "-", "dever"],
stdout=stream, check=True)
with checksum.open("x") as stream:
stream.write(f"{digest(args.output)} {args.output.name}\n")
print(json.dumps({"archive": str(args.output), "bytes": args.output.stat().st_size,
"files": len(manifest["files"]), "compiler_sha256": digest(args.compiler)}))
if __name__ == "__main__":
main()