|
|
@@ -791,6 +791,11 @@ def collect_analysis_inputs(
|
|
|
) -> AnalysisCollection:
|
|
|
root = repo_root.resolve(strict=True)
|
|
|
temp_root.mkdir(parents=True, exist_ok=True)
|
|
|
+ if profile == "full" and not include_git_bundle:
|
|
|
+ raise PackagingError(
|
|
|
+ "full inclusion-first packages require a git bundle so replay can restore "
|
|
|
+ "commit-to-commit source closure comparison"
|
|
|
+ )
|
|
|
items: list[PackageItem] = []
|
|
|
excluded: list[dict[str, str]] = []
|
|
|
warnings: list[dict[str, str]] = []
|
|
|
@@ -1398,41 +1403,73 @@ def replay_analysis_package(package_dir: Path, *, extract_root: Path) -> dict[st
|
|
|
raise PackagingError(f"replay extract root already exists: {extract_root}")
|
|
|
index_path = package_dir / "HANDOFF-INDEX.json"
|
|
|
sums_path = package_dir / "SHA256SUMS.txt"
|
|
|
+ exclusions_path = package_dir / "EXCLUSIONS.txt"
|
|
|
if not index_path.is_file() or not sums_path.is_file():
|
|
|
raise PackagingError("package directory is missing HANDOFF-INDEX.json or SHA256SUMS.txt")
|
|
|
index = json.loads(index_path.read_text(encoding="utf-8"))
|
|
|
extract_root.mkdir(parents=True, exist_ok=False)
|
|
|
+ zip_extract_root = extract_root / "from-zip"
|
|
|
+ tar_extract_root = extract_root / "from-tar-zst"
|
|
|
+ zip_extract_root.mkdir(parents=True, exist_ok=True)
|
|
|
verified_volumes: list[dict[str, object]] = []
|
|
|
+ verified_sidecars: list[dict[str, object]] = []
|
|
|
+ tar_zst_name: str | None = None
|
|
|
for line in sums_path.read_text(encoding="ascii").splitlines():
|
|
|
line = line.strip()
|
|
|
- if not line:
|
|
|
+ if not line or line.startswith("#"):
|
|
|
continue
|
|
|
digest, _, name = line.partition(" ")
|
|
|
if not digest or not name:
|
|
|
raise PackagingError(f"invalid SHA256SUMS line: {line}")
|
|
|
- volume_path = package_dir / name
|
|
|
- actual = handoff.sha256_file(volume_path)
|
|
|
+ member_path = package_dir / name
|
|
|
+ actual = handoff.sha256_file(member_path)
|
|
|
if actual != digest:
|
|
|
raise PackagingError(f"SHA256SUMS mismatch for {name}")
|
|
|
- with zipfile.ZipFile(volume_path, "r", allowZip64=True) as archive:
|
|
|
- archive.extractall(extract_root)
|
|
|
- verified_volumes.append({"file": name, "sha256": actual})
|
|
|
+ lower = name.casefold()
|
|
|
+ if lower.endswith(".zip"):
|
|
|
+ with zipfile.ZipFile(member_path, "r", allowZip64=True) as archive:
|
|
|
+ archive.extractall(zip_extract_root)
|
|
|
+ verified_volumes.append({"file": name, "sha256": actual})
|
|
|
+ elif lower.endswith(".tar.zst"):
|
|
|
+ tar_zst_name = name
|
|
|
+ tar_extract_root.mkdir(parents=True, exist_ok=True)
|
|
|
+ completed = subprocess.run(
|
|
|
+ ["tar", "--zstd", "-xf", str(member_path), "-C", str(tar_extract_root)],
|
|
|
+ stdout=subprocess.PIPE,
|
|
|
+ stderr=subprocess.PIPE,
|
|
|
+ check=False,
|
|
|
+ )
|
|
|
+ if completed.returncode != 0:
|
|
|
+ raise PackagingError(
|
|
|
+ f"unable to extract tar.zst during replay: {name}: "
|
|
|
+ f"{completed.stderr.decode('utf-8', errors='replace').strip()}"
|
|
|
+ )
|
|
|
+ verified_sidecars.append({"file": name, "sha256": actual, "kind": "tar_zst"})
|
|
|
+ else:
|
|
|
+ verified_sidecars.append({"file": name, "sha256": actual, "kind": "sidecar"})
|
|
|
checked_files = 0
|
|
|
for item in index.get("files", []):
|
|
|
relative = str(item["path"])
|
|
|
- target = extract_root / "CPLD" / Path(*relative.split("/"))
|
|
|
+ target = zip_extract_root / "CPLD" / Path(*relative.split("/"))
|
|
|
if not target.is_file():
|
|
|
raise PackagingError(f"replay missing extracted file: {relative}")
|
|
|
digest = handoff.sha256_file(target)
|
|
|
if digest != item["sha256"] or target.stat().st_size != int(item["size"]):
|
|
|
raise PackagingError(f"replay hash mismatch for {relative}")
|
|
|
+ if tar_zst_name is not None:
|
|
|
+ # tar.zst is created from ZIP extract roots, so the same CPLD tree must round-trip.
|
|
|
+ tar_target = tar_extract_root / "CPLD" / Path(*relative.split("/"))
|
|
|
+ if not tar_target.is_file():
|
|
|
+ raise PackagingError(f"tar.zst replay missing extracted file: {relative}")
|
|
|
+ if handoff.sha256_file(tar_target) != digest:
|
|
|
+ raise PackagingError(f"tar.zst replay hash mismatch for {relative}")
|
|
|
checked_files += 1
|
|
|
for record in index.get("content_dedup", []):
|
|
|
- physical = extract_root / "CPLD" / Path(*str(record["physical_path"]).split("/"))
|
|
|
+ physical = zip_extract_root / "CPLD" / Path(*str(record["physical_path"]).split("/"))
|
|
|
if not physical.is_file():
|
|
|
raise PackagingError(f"replay missing dedup physical file: {record['physical_path']}")
|
|
|
for alias in record.get("logical_paths", []):
|
|
|
- alias_path = extract_root / "CPLD" / Path(*str(alias).split("/"))
|
|
|
+ alias_path = zip_extract_root / "CPLD" / Path(*str(alias).split("/"))
|
|
|
if alias_path.exists():
|
|
|
raise PackagingError(f"replay found duplicated physical alias path: {alias}")
|
|
|
return {
|
|
|
@@ -1441,6 +1478,9 @@ def replay_analysis_package(package_dir: Path, *, extract_root: Path) -> dict[st
|
|
|
"package_dir": str(package_dir),
|
|
|
"extract_root": str(extract_root),
|
|
|
"volumes": verified_volumes,
|
|
|
+ "sidecars": verified_sidecars,
|
|
|
+ "exclusions_present": exclusions_path.is_file(),
|
|
|
+ "tar_zst": tar_zst_name,
|
|
|
"checked_files": checked_files,
|
|
|
"content_dedup_groups": len(index.get("content_dedup", [])),
|
|
|
"derived_evidence_count": len(index.get("derived_evidence", [])),
|
|
|
@@ -1852,12 +1892,146 @@ def _assert_source_trees_unchanged(collection: AnalysisCollection, *, profile: s
|
|
|
def _start_here_text(package_name: str, volume_count: int) -> str:
|
|
|
return (
|
|
|
f"# {package_name} 分析交付包\n\n"
|
|
|
- f"本目录包含 {volume_count} 个互相独立的普通 ZIP。请先核对 `SHA256SUMS.txt`,"
|
|
|
- "再把所有 ZIP 解压到同一个目录。\n\n"
|
|
|
+ f"本目录包含 {volume_count} 个互相独立的普通 ZIP,以及可选的 `.tar.zst` 同源归档。"
|
|
|
+ "请先核对 `SHA256SUMS.txt`,再把所有 ZIP 解压到同一个目录;"
|
|
|
+ "也可用 `tar --zstd -xf <package>.tar.zst` 还原。\n\n"
|
|
|
"`HANDOFF-INDEX.json` 记录每个原始文件的来源、目标卷、大小和 SHA-256,"
|
|
|
+ "`EXCLUSIONS.txt` 列出排除路径与规则,"
|
|
|
"以及 `excluded`(排除原因)、`derived_evidence`(由原始 BRD 派生的 board-viewer JSON/SVG,"
|
|
|
"不是 RTL/TD source closure)和 `content_dedup`(相同大文件只保留一份物理副本时的逻辑归属)。\n"
|
|
|
+ "完整 full 包必须包含 `git-history/*.bundle`,以便在干净提取后用 commit-to-commit "
|
|
|
+ "恢复 source closure 比对。\n"
|
|
|
+ )
|
|
|
+
|
|
|
+
|
|
|
+def write_exclusions_text(excluded: list[dict[str, object]]) -> str:
|
|
|
+ """Render a portable EXCLUSIONS.txt for the package sidecar layout."""
|
|
|
+ lines = [
|
|
|
+ "# path<TAB>rule",
|
|
|
+ "# Inclusion-first package: only versioned recursive exclusions are listed.",
|
|
|
+ ]
|
|
|
+ for item in sorted(excluded, key=lambda row: handoff.windows_collision_key(str(row.get("path", "")))):
|
|
|
+ path = str(item.get("path", ""))
|
|
|
+ rule = str(item.get("rule", item.get("reason", "excluded")))
|
|
|
+ lines.append(f"{path}\t{rule}")
|
|
|
+ return "\n".join(lines) + "\n"
|
|
|
+
|
|
|
+
|
|
|
+def create_tar_zst_archive(source_dir: Path, archive_path: Path) -> str:
|
|
|
+ """Create a deterministic-enough tar.zst of source_dir contents; return SHA-256."""
|
|
|
+ source_dir = source_dir.resolve(strict=True)
|
|
|
+ archive_path = archive_path.resolve(strict=False)
|
|
|
+ if archive_path.exists():
|
|
|
+ archive_path.unlink()
|
|
|
+ zstd = shutil.which("zstd")
|
|
|
+ if zstd is None:
|
|
|
+ raise PackagingError("zstd is required to create .tar.zst package archives")
|
|
|
+ # Prefer GNU tar --zstd when available; fall back to compress-program.
|
|
|
+ command = [
|
|
|
+ "tar",
|
|
|
+ "--zstd",
|
|
|
+ "-cf",
|
|
|
+ str(archive_path),
|
|
|
+ "--sort=name",
|
|
|
+ "--mtime=UTC 1980-01-01",
|
|
|
+ "--owner=0",
|
|
|
+ "--group=0",
|
|
|
+ "--numeric-owner",
|
|
|
+ "-C",
|
|
|
+ str(source_dir),
|
|
|
+ ".",
|
|
|
+ ]
|
|
|
+ completed = subprocess.run(
|
|
|
+ command,
|
|
|
+ stdout=subprocess.PIPE,
|
|
|
+ stderr=subprocess.PIPE,
|
|
|
+ check=False,
|
|
|
+ )
|
|
|
+ if completed.returncode != 0:
|
|
|
+ # Older tar without --zstd / --sort: use compress-program path.
|
|
|
+ fallback = [
|
|
|
+ "tar",
|
|
|
+ "-cf",
|
|
|
+ str(archive_path),
|
|
|
+ "-I",
|
|
|
+ zstd,
|
|
|
+ "-C",
|
|
|
+ str(source_dir),
|
|
|
+ ".",
|
|
|
+ ]
|
|
|
+ completed = subprocess.run(
|
|
|
+ fallback,
|
|
|
+ stdout=subprocess.PIPE,
|
|
|
+ stderr=subprocess.PIPE,
|
|
|
+ check=False,
|
|
|
+ )
|
|
|
+ if completed.returncode != 0:
|
|
|
+ detail = completed.stderr.decode("utf-8", errors="replace").strip()
|
|
|
+ raise PackagingError(f"unable to create tar.zst archive: {detail or 'tar failed'}")
|
|
|
+ return handoff.sha256_file(archive_path)
|
|
|
+
|
|
|
+
|
|
|
+def write_package_layout_sidecars(
|
|
|
+ staging: Path,
|
|
|
+ *,
|
|
|
+ index: dict[str, object],
|
|
|
+ excluded: list[dict[str, object]],
|
|
|
+ package_name: str,
|
|
|
+ include_tar_zst: bool = True,
|
|
|
+) -> list[dict[str, object]]:
|
|
|
+ """Write index/checksums/exclusions and optional tar.zst; return checksum rows."""
|
|
|
+ staging.mkdir(parents=True, exist_ok=True)
|
|
|
+ (staging / "HANDOFF-INDEX.json").write_bytes(handoff.json_bytes(index))
|
|
|
+ (staging / "EXCLUSIONS.txt").write_text(
|
|
|
+ write_exclusions_text(excluded),
|
|
|
+ encoding="utf-8",
|
|
|
+ newline="\n",
|
|
|
+ )
|
|
|
+ (staging / "START-HERE.zh-CN.md").write_text(
|
|
|
+ _start_here_text(package_name, len(index.get("volumes", []))),
|
|
|
+ encoding="utf-8",
|
|
|
+ newline="\n",
|
|
|
+ )
|
|
|
+
|
|
|
+ checksum_rows: list[dict[str, object]] = []
|
|
|
+ for info in index.get("volumes", []):
|
|
|
+ name = str(info["file"])
|
|
|
+ checksum_rows.append({"file": name, "sha256": str(info["sha256"])})
|
|
|
+
|
|
|
+ if include_tar_zst:
|
|
|
+ # Stage CPLD tree from ZIP volumes into a temporary extract for tar.zst.
|
|
|
+ extract_root = staging / ".tar-zst-staging"
|
|
|
+ if extract_root.exists():
|
|
|
+ shutil.rmtree(extract_root)
|
|
|
+ extract_root.mkdir(parents=True, exist_ok=True)
|
|
|
+ for info in index.get("volumes", []):
|
|
|
+ volume_path = staging / str(info["file"])
|
|
|
+ with zipfile.ZipFile(volume_path, "r", allowZip64=True) as archive:
|
|
|
+ archive.extractall(extract_root)
|
|
|
+ tar_name = f"{package_name}.tar.zst"
|
|
|
+ tar_path = staging / tar_name
|
|
|
+ tar_sha = create_tar_zst_archive(extract_root, tar_path)
|
|
|
+ shutil.rmtree(extract_root)
|
|
|
+ checksum_rows.append({"file": tar_name, "sha256": tar_sha})
|
|
|
+ index["formats"] = {
|
|
|
+ "zip_volumes": [str(info["file"]) for info in index.get("volumes", [])],
|
|
|
+ "tar_zst": tar_name,
|
|
|
+ "tar_zst_sha256": tar_sha,
|
|
|
+ }
|
|
|
+ (staging / "HANDOFF-INDEX.json").write_bytes(handoff.json_bytes(index))
|
|
|
+
|
|
|
+ for sidecar in ("HANDOFF-INDEX.json", "EXCLUSIONS.txt", "START-HERE.zh-CN.md"):
|
|
|
+ checksum_rows.append(
|
|
|
+ {"file": sidecar, "sha256": handoff.sha256_file(staging / sidecar)}
|
|
|
+ )
|
|
|
+
|
|
|
+ checksum_lines = [f"{row['sha256']} {row['file']}" for row in checksum_rows]
|
|
|
+ (staging / "SHA256SUMS.txt").write_text(
|
|
|
+ "\n".join(checksum_lines) + "\n",
|
|
|
+ encoding="ascii",
|
|
|
+ newline="\n",
|
|
|
)
|
|
|
+ return checksum_rows
|
|
|
|
|
|
|
|
|
def _publish_directory_atomically(staging: Path, final: Path, *, force: bool) -> None:
|
|
|
@@ -2039,25 +2213,19 @@ def create_analysis_package(
|
|
|
encoding="utf-8",
|
|
|
newline="\n",
|
|
|
)
|
|
|
- (staging / "HANDOFF-INDEX.json").write_bytes(handoff.json_bytes(index))
|
|
|
- (staging / "START-HERE.zh-CN.md").write_text(
|
|
|
- _start_here_text(package_name, len(volume_infos)),
|
|
|
- encoding="utf-8",
|
|
|
- newline="\n",
|
|
|
- )
|
|
|
- checksum_lines = [f"{info['sha256']} {info['file']}" for info in volume_infos]
|
|
|
- (staging / "SHA256SUMS.txt").write_text(
|
|
|
- "\n".join(checksum_lines) + "\n",
|
|
|
- encoding="ascii",
|
|
|
- newline="\n",
|
|
|
- )
|
|
|
-
|
|
|
for info in volume_infos:
|
|
|
volume_path = staging / str(info["file"])
|
|
|
if volume_path.stat().st_size >= max_zip_bytes:
|
|
|
raise PackagingError(f"ZIP volume exceeds strict size limit: {volume_path.name}")
|
|
|
if handoff.sha256_file(volume_path) != info["sha256"]:
|
|
|
raise PackagingError(f"ZIP volume hash changed after verification: {volume_path.name}")
|
|
|
+ checksum_rows = write_package_layout_sidecars(
|
|
|
+ staging,
|
|
|
+ index=index,
|
|
|
+ excluded=package_excluded,
|
|
|
+ package_name=package_name,
|
|
|
+ include_tar_zst=True,
|
|
|
+ )
|
|
|
full_inventory_by_path = {str(item["path"]): item for item in full_inventory}
|
|
|
_assert_items_unchanged(collection.items, full_inventory_by_path)
|
|
|
_assert_source_trees_unchanged(collection, profile=profile)
|
|
|
@@ -2068,6 +2236,10 @@ def create_analysis_package(
|
|
|
if os.path.lexists(staging):
|
|
|
shutil.rmtree(staging, ignore_errors=True)
|
|
|
raise
|
|
|
+ formats = {}
|
|
|
+ index_path = final_dir / "HANDOFF-INDEX.json"
|
|
|
+ if index_path.is_file():
|
|
|
+ formats = json.loads(index_path.read_text(encoding="utf-8")).get("formats", {})
|
|
|
return {
|
|
|
"status": collection.status,
|
|
|
"mode": "package",
|
|
|
@@ -2076,6 +2248,8 @@ def create_analysis_package(
|
|
|
"run_id": run_id,
|
|
|
"output_dir": str(final_dir),
|
|
|
"volumes": volume_infos,
|
|
|
+ "formats": formats,
|
|
|
+ "checksum_entries": len(checksum_rows),
|
|
|
"included_file_count": len(inventory),
|
|
|
"included_bytes": sum(int(item["size"]) for item in inventory),
|
|
|
"excluded_entry_count": len(package_excluded),
|