|
|
@@ -6,6 +6,7 @@ from __future__ import annotations
|
|
|
import json
|
|
|
import hashlib
|
|
|
import argparse
|
|
|
+import concurrent.futures
|
|
|
import os
|
|
|
import re
|
|
|
import shutil
|
|
|
@@ -38,6 +39,23 @@ CATEGORY_ORDER = {
|
|
|
"td-docs": 2,
|
|
|
"evidence": 3,
|
|
|
}
|
|
|
+GENERATED_BINARY_SUFFIXES = {
|
|
|
+ ".bit",
|
|
|
+ ".bid",
|
|
|
+ ".data",
|
|
|
+ ".db",
|
|
|
+ ".timing",
|
|
|
+ ".rpt",
|
|
|
+ ".area",
|
|
|
+ ".qor",
|
|
|
+ ".vvp",
|
|
|
+}
|
|
|
+TRANSIENT_SUFFIXES = {".pyc", ".pyo", ".tmp", ".partial", ".part", ".swp", ".swo"}
|
|
|
+ARCHIVE_SUFFIXES = {".zip", ".rar", ".7z"}
|
|
|
+RUNTIME_EVIDENCE_SUFFIXES = {".log", ".logw", ".vcd", ".fst", ".lxt", ".gtkw", ".raw", ".bin"}
|
|
|
+BOARD_DESIGN_SUFFIXES = {".brd", ".sch", ".kicad_pcb", ".kicad_sch", ".kicad_pro", ".kicad_prl", ".dsn"}
|
|
|
+IMAGE_SUFFIXES = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff", ".webp", ".svg"}
|
|
|
+STRAY_FILENAMES = {"-", "a.out"}
|
|
|
REASSEMBLER_SCRIPT = '''#!/usr/bin/env python3
|
|
|
"""Reassemble files that were split across analysis ZIP volumes."""
|
|
|
|
|
|
@@ -152,6 +170,14 @@ class PackageItem(NamedTuple):
|
|
|
scan_archive: bool
|
|
|
|
|
|
|
|
|
+class SourceSnapshot(NamedTuple):
|
|
|
+ source_id: str
|
|
|
+ root: Path
|
|
|
+ extra_exclusions: tuple[dict[str, str], ...]
|
|
|
+ candidates: tuple[tuple[object, ...], ...]
|
|
|
+ excluded: tuple[tuple[str, str], ...]
|
|
|
+
|
|
|
+
|
|
|
class AnalysisCollection(NamedTuple):
|
|
|
status: str
|
|
|
items: tuple[PackageItem, ...]
|
|
|
@@ -159,6 +185,75 @@ class AnalysisCollection(NamedTuple):
|
|
|
warnings: tuple[dict[str, str], ...]
|
|
|
sources: tuple[dict[str, object], ...]
|
|
|
git: tuple[dict[str, object], ...]
|
|
|
+ source_snapshots: tuple[SourceSnapshot, ...] = ()
|
|
|
+
|
|
|
+
|
|
|
+def _is_reference_path(item: PackageItem) -> bool:
|
|
|
+ parts = item.candidate.relative.casefold().split("/")
|
|
|
+ for index, part in enumerate(parts):
|
|
|
+ if part == "reference":
|
|
|
+ next_part = parts[index + 1] if index + 1 < len(parts) else ""
|
|
|
+ if next_part == "historical":
|
|
|
+ return False
|
|
|
+ return True
|
|
|
+ return False
|
|
|
+
|
|
|
+
|
|
|
+def _is_reference_item(item: PackageItem) -> bool:
|
|
|
+ return item.category == "td-docs" or _is_reference_path(item)
|
|
|
+
|
|
|
+
|
|
|
+def _split_collection_by_reference(
|
|
|
+ collection: AnalysisCollection,
|
|
|
+) -> tuple[AnalysisCollection, AnalysisCollection]:
|
|
|
+ core_items: list[PackageItem] = []
|
|
|
+ reference_items: list[PackageItem] = []
|
|
|
+ for item in collection.items:
|
|
|
+ if _is_reference_item(item):
|
|
|
+ if item.category == "core" and _is_reference_path(item):
|
|
|
+ item = item._replace(category="reference")
|
|
|
+ reference_items.append(item)
|
|
|
+ else:
|
|
|
+ core_items.append(item)
|
|
|
+ reference_items_tuple = tuple(reference_items)
|
|
|
+ core_items_tuple = tuple(core_items)
|
|
|
+ reference_source_ids = {item.source_id for item in reference_items_tuple}
|
|
|
+ core_source_ids = {item.source_id for item in core_items_tuple}
|
|
|
+
|
|
|
+ def _filter_sources(
|
|
|
+ sources: tuple[dict[str, object], ...], source_ids: set[str]
|
|
|
+ ) -> tuple[dict[str, object], ...]:
|
|
|
+ return tuple(s for s in sources if s.get("id") in source_ids)
|
|
|
+
|
|
|
+ def _filter_git(
|
|
|
+ git: tuple[dict[str, object], ...], source_ids: set[str]
|
|
|
+ ) -> tuple[dict[str, object], ...]:
|
|
|
+ return tuple(g for g in git if g.get("source_id") in source_ids)
|
|
|
+
|
|
|
+ def _filter_snapshots(
|
|
|
+ snapshots: tuple[SourceSnapshot, ...], source_ids: set[str]
|
|
|
+ ) -> tuple[SourceSnapshot, ...]:
|
|
|
+ return tuple(ss for ss in snapshots if ss.source_id in source_ids)
|
|
|
+
|
|
|
+ core_collection = AnalysisCollection(
|
|
|
+ status=collection.status,
|
|
|
+ items=core_items_tuple,
|
|
|
+ excluded=collection.excluded,
|
|
|
+ warnings=collection.warnings,
|
|
|
+ sources=_filter_sources(collection.sources, core_source_ids),
|
|
|
+ git=_filter_git(collection.git, core_source_ids),
|
|
|
+ source_snapshots=_filter_snapshots(collection.source_snapshots, core_source_ids),
|
|
|
+ )
|
|
|
+ reference_collection = AnalysisCollection(
|
|
|
+ status=collection.status,
|
|
|
+ items=reference_items_tuple,
|
|
|
+ excluded=collection.excluded,
|
|
|
+ warnings=collection.warnings,
|
|
|
+ sources=_filter_sources(collection.sources, reference_source_ids),
|
|
|
+ git=_filter_git(collection.git, reference_source_ids),
|
|
|
+ source_snapshots=_filter_snapshots(collection.source_snapshots, reference_source_ids),
|
|
|
+ )
|
|
|
+ return core_collection, reference_collection
|
|
|
|
|
|
|
|
|
class ArchivePreparation(NamedTuple):
|
|
|
@@ -167,6 +262,35 @@ class ArchivePreparation(NamedTuple):
|
|
|
warnings: tuple[dict[str, str], ...]
|
|
|
|
|
|
|
|
|
+def _source_snapshot(
|
|
|
+ root: Path,
|
|
|
+ *,
|
|
|
+ source_id: str,
|
|
|
+ extra_exclusions: tuple[dict[str, str], ...],
|
|
|
+) -> SourceSnapshot:
|
|
|
+ candidates, excluded, _ = scan_analysis_root(
|
|
|
+ root,
|
|
|
+ extra_exclusions=extra_exclusions,
|
|
|
+ )
|
|
|
+ return SourceSnapshot(
|
|
|
+ source_id=source_id,
|
|
|
+ root=root.resolve(strict=True),
|
|
|
+ extra_exclusions=extra_exclusions,
|
|
|
+ candidates=tuple(
|
|
|
+ (
|
|
|
+ candidate.relative,
|
|
|
+ candidate.size,
|
|
|
+ candidate.mtime_ns,
|
|
|
+ candidate.device,
|
|
|
+ candidate.inode,
|
|
|
+ candidate.mode,
|
|
|
+ )
|
|
|
+ for candidate in candidates
|
|
|
+ ),
|
|
|
+ excluded=tuple((item["path"], item["rule"]) for item in excluded),
|
|
|
+ )
|
|
|
+
|
|
|
+
|
|
|
def _require_keys(payload: dict[str, object], allowed: set[str], label: str) -> None:
|
|
|
unknown = sorted(set(payload) - allowed)
|
|
|
if unknown:
|
|
|
@@ -293,6 +417,7 @@ def analysis_exclusion_reason(
|
|
|
del context
|
|
|
lower = relative.casefold()
|
|
|
parts = lower.split("/")
|
|
|
+ raw_parts = relative.split("/")
|
|
|
name = parts[-1]
|
|
|
secret_reason = handoff.secret_path_reason(relative, is_dir=is_dir)
|
|
|
if secret_reason:
|
|
|
@@ -301,17 +426,62 @@ def analysis_exclusion_reason(
|
|
|
prefix = str(item.get("path", "")).casefold().strip("/")
|
|
|
if prefix and handoff.is_under(lower, prefix):
|
|
|
return str(item.get("reason") or "configured_analysis_exclusion")
|
|
|
+ explicit_roots = {
|
|
|
+ ".git": "raw_git_metadata",
|
|
|
+ ".codegraph": "declared_external_reparse_alias",
|
|
|
+ ".codex": "codex_session_runtime",
|
|
|
+ ".hypothesis": "hypothesis_cache",
|
|
|
+ ".ruff_cache": "ruff_cache",
|
|
|
+ ".pytest_cache": "pytest_cache",
|
|
|
+ "dist": "generated_delivery_output",
|
|
|
+ "log": "runtime_log_directory",
|
|
|
+ "runs": "run_state_directory",
|
|
|
+ "td/build": "td_build_output",
|
|
|
+ "reference/historical": "reference_historical_material",
|
|
|
+ "reference/original/legacy_rtl": "reference_legacy_rtl",
|
|
|
+ "receipts/local": "local_runtime_receipt",
|
|
|
+ "tools/board-viewer/generated": "generated_board_viewer_output",
|
|
|
+ "anlogic_cd": "vendor_installer_payload",
|
|
|
+ }
|
|
|
+ for prefix, reason in explicit_roots.items():
|
|
|
+ if handoff.is_under(lower, prefix):
|
|
|
+ return reason
|
|
|
+
|
|
|
+ if handoff.is_under(lower, "tmp/edge-headless-profile"):
|
|
|
+ return "browser_runtime_profile"
|
|
|
+ if handoff.is_under(lower, "tmp/rtl_sim"):
|
|
|
+ return "compiled_rtl_simulation"
|
|
|
+ if handoff.is_under(lower, "tmp/toolchain_probe"):
|
|
|
+ return "toolchain_probe_runtime"
|
|
|
+ if handoff.is_under(lower, "tmp/td"):
|
|
|
+ return "td_runtime_snapshot"
|
|
|
+ if handoff.is_under(lower, "tmp/refactor"):
|
|
|
+ return "compiled_refactor_probe"
|
|
|
+ if any(component.endswith("_Runs") for component in raw_parts):
|
|
|
+ return "generated_run_directory"
|
|
|
+ if re.match(r"^tmp/pytest-[^/]+$", lower):
|
|
|
+ return "temporary_tool_runtime"
|
|
|
+ if handoff.is_under(lower, "tmp"):
|
|
|
+ return "temporary_workspace_directory"
|
|
|
+
|
|
|
+ if handoff.is_under(lower, "td/project/log"):
|
|
|
+ return "td_gui_runtime_log"
|
|
|
+ if handoff.is_under(lower, "td/project") and len(parts) >= 3 and parts[2].endswith("_runs"):
|
|
|
+ return "td_gui_runtime_run"
|
|
|
+ if lower in {
|
|
|
+ "td/project/.lock.f",
|
|
|
+ "td/project/.recent_user_depot.ini",
|
|
|
+ }:
|
|
|
+ return "td_gui_runtime_state"
|
|
|
+
|
|
|
if handoff.is_under(lower, ".git"):
|
|
|
return "raw_git_metadata"
|
|
|
if handoff.is_under(lower, ".omo"):
|
|
|
return "agent_session_runtime"
|
|
|
- if lower == ".codex" or handoff.is_under(lower, ".codex/reports"):
|
|
|
- return None
|
|
|
- if handoff.is_under(lower, ".codex"):
|
|
|
- return "codex_session_runtime"
|
|
|
- if handoff.is_under(lower, "tmp") and len(parts) >= 2 and parts[1].startswith("sysinternals-handle-"):
|
|
|
- return "external_tool_cache"
|
|
|
cache_components = {
|
|
|
+ ".git": "raw_git_metadata",
|
|
|
+ ".codegraph": "declared_external_reparse_alias",
|
|
|
+ ".codex": "codex_session_runtime",
|
|
|
"__pycache__": "python_bytecode_cache",
|
|
|
".pytest_cache": "pytest_cache",
|
|
|
".hypothesis": "hypothesis_cache",
|
|
|
@@ -322,16 +492,37 @@ def analysis_exclusion_reason(
|
|
|
".venv": "virtual_environment",
|
|
|
"venv": "virtual_environment",
|
|
|
"htmlcov": "coverage_report",
|
|
|
+ "build": "build_output",
|
|
|
+ "runs": "run_state_directory",
|
|
|
}
|
|
|
for component in parts:
|
|
|
if component in cache_components:
|
|
|
return cache_components[component]
|
|
|
+ if component == "dist":
|
|
|
+ return "generated_delivery_output"
|
|
|
+
|
|
|
if not is_dir:
|
|
|
suffix = Path(name).suffix.casefold()
|
|
|
- if suffix in {".pyc", ".pyo"}:
|
|
|
- return "python_bytecode"
|
|
|
- if suffix in {".tmp", ".partial", ".part", ".swp", ".swo"} or name.endswith("~"):
|
|
|
- return "atomic_or_editor_temporary_file"
|
|
|
+ if suffix in GENERATED_BINARY_SUFFIXES:
|
|
|
+ return "generated_binary_artifact"
|
|
|
+ if suffix in ARCHIVE_SUFFIXES:
|
|
|
+ return "archive_file_not_source"
|
|
|
+ if suffix in RUNTIME_EVIDENCE_SUFFIXES:
|
|
|
+ return "runtime_evidence_or_waveform"
|
|
|
+ if suffix in BOARD_DESIGN_SUFFIXES:
|
|
|
+ if "reference" in parts:
|
|
|
+ return None
|
|
|
+ return "board_design_file"
|
|
|
+ if suffix in IMAGE_SUFFIXES:
|
|
|
+ if "reference" in parts:
|
|
|
+ return None
|
|
|
+ return "image_file"
|
|
|
+ if name in STRAY_FILENAMES:
|
|
|
+ return "stray_or_temporary_file"
|
|
|
+ if suffix in TRANSIENT_SUFFIXES or name.endswith("~"):
|
|
|
+ return "temporary_file"
|
|
|
+ if suffix == ".dmp" or name.startswith("minidump-"):
|
|
|
+ return "crash_dump"
|
|
|
if name in {".ds_store", "thumbs.db", "desktop.ini"}:
|
|
|
return "os_metadata_cache"
|
|
|
return None
|
|
|
@@ -549,6 +740,7 @@ def collect_analysis_inputs(
|
|
|
repo_root: Path,
|
|
|
config: HandoffConfig,
|
|
|
temp_root: Path,
|
|
|
+ include_git_bundle: bool = True,
|
|
|
) -> AnalysisCollection:
|
|
|
root = repo_root.resolve(strict=True)
|
|
|
temp_root.mkdir(parents=True, exist_ok=True)
|
|
|
@@ -557,6 +749,7 @@ def collect_analysis_inputs(
|
|
|
warnings: list[dict[str, str]] = []
|
|
|
sources: list[dict[str, object]] = []
|
|
|
git_metadata: list[dict[str, object]] = []
|
|
|
+ source_snapshots: list[SourceSnapshot] = []
|
|
|
|
|
|
root_items, root_excluded = _collect_directory_items(
|
|
|
root=root,
|
|
|
@@ -567,6 +760,13 @@ def collect_analysis_inputs(
|
|
|
)
|
|
|
items.extend(root_items)
|
|
|
excluded.extend(root_excluded)
|
|
|
+ source_snapshots.append(
|
|
|
+ _source_snapshot(
|
|
|
+ root,
|
|
|
+ source_id="workspace-current",
|
|
|
+ extra_exclusions=config.extra_exclusions,
|
|
|
+ )
|
|
|
+ )
|
|
|
sources.append(
|
|
|
{
|
|
|
"id": "workspace-current",
|
|
|
@@ -576,13 +776,14 @@ def collect_analysis_inputs(
|
|
|
"status": "pass",
|
|
|
}
|
|
|
)
|
|
|
- bundle_item, bundle_metadata = _create_git_bundle(
|
|
|
- root=root,
|
|
|
- source_id="workspace-current",
|
|
|
- temp_root=temp_root,
|
|
|
- )
|
|
|
- items.append(bundle_item)
|
|
|
- git_metadata.append(bundle_metadata)
|
|
|
+ if include_git_bundle:
|
|
|
+ bundle_item, bundle_metadata = _create_git_bundle(
|
|
|
+ root=root,
|
|
|
+ source_id="workspace-current",
|
|
|
+ temp_root=temp_root,
|
|
|
+ )
|
|
|
+ items.append(bundle_item)
|
|
|
+ git_metadata.append(bundle_metadata)
|
|
|
|
|
|
resolved_sources, source_warnings = resolve_external_sources(config.external_sources)
|
|
|
warnings.extend(source_warnings)
|
|
|
@@ -609,6 +810,13 @@ def collect_analysis_inputs(
|
|
|
)
|
|
|
items.extend(source_items)
|
|
|
excluded.extend(source_excluded)
|
|
|
+ source_snapshots.append(
|
|
|
+ _source_snapshot(
|
|
|
+ source.path,
|
|
|
+ source_id=source.id,
|
|
|
+ extra_exclusions=config.extra_exclusions,
|
|
|
+ )
|
|
|
+ )
|
|
|
sources.append(
|
|
|
{
|
|
|
"id": source.id,
|
|
|
@@ -636,6 +844,7 @@ def collect_analysis_inputs(
|
|
|
warnings=tuple(warnings),
|
|
|
sources=tuple(sources),
|
|
|
git=tuple(git_metadata),
|
|
|
+ source_snapshots=tuple(source_snapshots),
|
|
|
)
|
|
|
|
|
|
|
|
|
@@ -652,6 +861,21 @@ def find_7z() -> Path | None:
|
|
|
return None
|
|
|
|
|
|
|
|
|
+def build_7zip_create_command(archive_path: Path, staging_root: Path) -> list[str]:
|
|
|
+ del staging_root
|
|
|
+ return [
|
|
|
+ "a",
|
|
|
+ "-tzip",
|
|
|
+ "-mm=Deflate",
|
|
|
+ "-mx=9",
|
|
|
+ "-mmt",
|
|
|
+ "-y",
|
|
|
+ "-r",
|
|
|
+ str(archive_path),
|
|
|
+ "CPLD\\*",
|
|
|
+ ]
|
|
|
+
|
|
|
+
|
|
|
def _run_7z(seven_zip: Path, arguments: list[str], *, cwd: Path) -> str:
|
|
|
try:
|
|
|
completed = subprocess.run(
|
|
|
@@ -674,6 +898,19 @@ def _run_7z(seven_zip: Path, arguments: list[str], *, cwd: Path) -> str:
|
|
|
return completed.stdout
|
|
|
|
|
|
|
|
|
+def _rename_archive_entries(
|
|
|
+ seven_zip: Path,
|
|
|
+ archive_path: Path,
|
|
|
+ renames: list[tuple[str, str]],
|
|
|
+) -> None:
|
|
|
+ for offset in range(0, len(renames), 64):
|
|
|
+ batch = renames[offset : offset + 64]
|
|
|
+ arguments = ["rn", "-y", str(archive_path)]
|
|
|
+ for old_name, new_name in batch:
|
|
|
+ arguments.extend((old_name, new_name))
|
|
|
+ _run_7z(seven_zip, arguments, cwd=archive_path.parent)
|
|
|
+
|
|
|
+
|
|
|
def _parse_7z_members(payload: str, archive_label: str) -> list[dict[str, str]]:
|
|
|
in_members = False
|
|
|
current: dict[str, str] = {}
|
|
|
@@ -792,32 +1029,22 @@ def prepare_unsupported_archives(
|
|
|
warnings: list[dict[str, str]] = []
|
|
|
temp_root.mkdir(parents=True, exist_ok=True)
|
|
|
for item in items:
|
|
|
- if handoff.archive_kind(item.candidate.relative) != "unsupported":
|
|
|
+ archive_kind = handoff.archive_kind(item.candidate.relative)
|
|
|
+ if archive_kind is None:
|
|
|
prepared.append(item)
|
|
|
continue
|
|
|
if seven_zip is None:
|
|
|
- excluded.append(
|
|
|
- {
|
|
|
- "path": item.candidate.relative,
|
|
|
- "rule": "unsupported_archive_without_7zip",
|
|
|
- }
|
|
|
- )
|
|
|
- warnings.append(
|
|
|
- {
|
|
|
- "code": "missing_7zip",
|
|
|
- "source_id": item.source_id,
|
|
|
- "message": f"unsupported archive was skipped: {item.candidate.relative}",
|
|
|
- }
|
|
|
- )
|
|
|
- continue
|
|
|
+ raise PackagingError("7-Zip is required to inspect source archives")
|
|
|
expanded_items, expanded_excluded, contains_sensitive = _inspect_and_extract_unsupported_archive(
|
|
|
item,
|
|
|
temp_root=temp_root,
|
|
|
seven_zip=seven_zip,
|
|
|
extra_exclusions=extra_exclusions,
|
|
|
)
|
|
|
- prepared.extend(expanded_items)
|
|
|
- excluded.extend(expanded_excluded)
|
|
|
+ has_filtered_members = bool(expanded_excluded)
|
|
|
+ if has_filtered_members:
|
|
|
+ prepared.extend(expanded_items)
|
|
|
+ excluded.extend(expanded_excluded)
|
|
|
if contains_sensitive:
|
|
|
excluded.append(
|
|
|
{
|
|
|
@@ -825,8 +1052,15 @@ def prepare_unsupported_archives(
|
|
|
"rule": "unsupported_archive_contains_sensitive_content",
|
|
|
}
|
|
|
)
|
|
|
+ elif has_filtered_members:
|
|
|
+ excluded.append(
|
|
|
+ {
|
|
|
+ "path": item.candidate.relative,
|
|
|
+ "rule": "archive_contains_excluded_members",
|
|
|
+ }
|
|
|
+ )
|
|
|
else:
|
|
|
- prepared.append(item._replace(scan_archive=False))
|
|
|
+ prepared.append(item._replace(scan_archive=archive_kind != "unsupported"))
|
|
|
prepared.sort(key=lambda item: handoff.windows_collision_key(item.candidate.relative))
|
|
|
excluded.sort(key=lambda item: handoff.windows_collision_key(item["path"]))
|
|
|
return ArchivePreparation(
|
|
|
@@ -861,10 +1095,24 @@ def _item_sort_key(item: PackageItem) -> tuple[int, str, str]:
|
|
|
)
|
|
|
|
|
|
|
|
|
+def _audit_one_item(item: PackageItem) -> dict[str, object]:
|
|
|
+ if item.scan_archive:
|
|
|
+ file_inventory = handoff.stream_candidate(item.candidate)
|
|
|
+ else:
|
|
|
+ file_inventory = handoff.hash_candidate(item.candidate)
|
|
|
+ return {
|
|
|
+ **file_inventory,
|
|
|
+ "archive_path": f"CPLD/{item.candidate.relative}",
|
|
|
+ "category": item.category,
|
|
|
+ "source_id": item.source_id,
|
|
|
+ "original_path": item.original_path,
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
def _audit_package_items(items: tuple[PackageItem, ...]) -> list[dict[str, object]]:
|
|
|
- inventory: list[dict[str, object]] = []
|
|
|
+ sorted_items = sorted(items, key=_item_sort_key)
|
|
|
collision_paths: dict[str, str] = {}
|
|
|
- for item in sorted(items, key=_item_sort_key):
|
|
|
+ for item in sorted_items:
|
|
|
key = handoff.windows_collision_key(item.candidate.relative)
|
|
|
previous = collision_paths.get(key)
|
|
|
if previous is not None:
|
|
|
@@ -872,20 +1120,9 @@ def _audit_package_items(items: tuple[PackageItem, ...]) -> list[dict[str, objec
|
|
|
f"analysis inputs contain a Windows path collision: {previous} and {item.candidate.relative}"
|
|
|
)
|
|
|
collision_paths[key] = item.candidate.relative
|
|
|
- if item.scan_archive:
|
|
|
- file_inventory = handoff.stream_candidate(item.candidate)
|
|
|
- else:
|
|
|
- file_inventory = handoff.hash_candidate(item.candidate)
|
|
|
- inventory.append(
|
|
|
- {
|
|
|
- **file_inventory,
|
|
|
- "archive_path": f"CPLD/{item.candidate.relative}",
|
|
|
- "category": item.category,
|
|
|
- "source_id": item.source_id,
|
|
|
- "original_path": item.original_path,
|
|
|
- }
|
|
|
- )
|
|
|
- return inventory
|
|
|
+ max_workers = os.cpu_count() or 1
|
|
|
+ with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
|
|
|
+ return list(executor.map(_audit_one_item, sorted_items))
|
|
|
|
|
|
|
|
|
def _write_unscanned_candidate(
|
|
|
@@ -925,6 +1162,41 @@ def _write_package_item(
|
|
|
return _write_unscanned_candidate(archive, item)
|
|
|
|
|
|
|
|
|
+def _stage_package_item(
|
|
|
+ staging_root: Path,
|
|
|
+ item: PackageItem,
|
|
|
+ staging_name: str,
|
|
|
+) -> dict[str, object]:
|
|
|
+ target = staging_root / "CPLD" / staging_name
|
|
|
+ target.parent.mkdir(parents=True, exist_ok=True)
|
|
|
+ if item.scan_archive:
|
|
|
+ try:
|
|
|
+ with target.open("wb") as destination:
|
|
|
+ return handoff.stream_candidate(item.candidate, target=destination)
|
|
|
+ except OSError as exc:
|
|
|
+ raise PackagingError(f"unable to stage {item.candidate.relative}: {exc}") from exc
|
|
|
+
|
|
|
+ digest = hashlib.sha256()
|
|
|
+ total = 0
|
|
|
+ secret_tail = b""
|
|
|
+ try:
|
|
|
+ with handoff.open_candidate(item.candidate) as source, target.open("wb") as destination:
|
|
|
+ for chunk in iter(lambda: source.read(1024 * 1024), b""):
|
|
|
+ secret_tail = handoff.scan_secret_markers(
|
|
|
+ chunk,
|
|
|
+ secret_tail,
|
|
|
+ item.candidate.relative,
|
|
|
+ )
|
|
|
+ destination.write(chunk)
|
|
|
+ digest.update(chunk)
|
|
|
+ total += len(chunk)
|
|
|
+ except OSError as exc:
|
|
|
+ raise PackagingError(f"unable to stage {item.candidate.relative}: {exc}") from exc
|
|
|
+ if total != item.candidate.size:
|
|
|
+ raise PackagingError(f"source size changed during staging: {item.candidate.relative}")
|
|
|
+ return {"path": item.candidate.relative, "size": total, "sha256": digest.hexdigest()}
|
|
|
+
|
|
|
+
|
|
|
def _volume_manifest(
|
|
|
*,
|
|
|
run_id: str,
|
|
|
@@ -969,31 +1241,57 @@ def _write_volume(
|
|
|
)
|
|
|
manifest_name = "CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json"
|
|
|
manifest_payload = handoff.json_bytes(manifest)
|
|
|
+ seven_zip = find_7z()
|
|
|
+ if seven_zip is None:
|
|
|
+ raise PackagingError("7-Zip is required to create the analysis ZIP")
|
|
|
+ stage_path = Path(tempfile.mkdtemp(prefix=f".{path.stem}.", dir=path.parent))
|
|
|
written_inventory: list[dict[str, object]] = []
|
|
|
- with zipfile.ZipFile(
|
|
|
- path,
|
|
|
- "x",
|
|
|
- compression=zipfile.ZIP_DEFLATED,
|
|
|
- compresslevel=6,
|
|
|
- allowZip64=True,
|
|
|
- strict_timestamps=False,
|
|
|
- ) as archive:
|
|
|
- for item in items:
|
|
|
- actual = _write_package_item(archive, item)
|
|
|
+ archive_renames: list[tuple[str, str]] = []
|
|
|
+ try:
|
|
|
+ staging_args = [(item_number, item) for item_number, item in enumerate(items)]
|
|
|
+
|
|
|
+ def _stage_one(args: tuple[int, PackageItem]) -> tuple[int, dict[str, object]]:
|
|
|
+ item_number, item = args
|
|
|
+ staging_name = f"candidate-{item_number:08d}"
|
|
|
+ return item_number, _stage_package_item(stage_path, item, staging_name)
|
|
|
+
|
|
|
+ max_workers = os.cpu_count() or 1
|
|
|
+ with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
|
|
|
+ staged = list(executor.map(_stage_one, staging_args))
|
|
|
+
|
|
|
+ for item_number, actual in staged:
|
|
|
+ item = items[item_number]
|
|
|
expected = inventory_by_path[item.candidate.relative]
|
|
|
if actual["size"] != expected["size"] or actual["sha256"] != expected["sha256"]:
|
|
|
raise PackagingError(f"source changed while writing ZIP: {item.candidate.relative}")
|
|
|
written_inventory.append(actual)
|
|
|
- handoff.write_bytes_entry(archive, manifest_name, manifest_payload)
|
|
|
-
|
|
|
- expected_names = {f"CPLD/{item.candidate.relative}" for item in items}
|
|
|
- expected_names.add(manifest_name)
|
|
|
- handoff.verify_archive(
|
|
|
- path,
|
|
|
- expected_names=expected_names,
|
|
|
- inventory=written_inventory,
|
|
|
- expected_payloads={manifest_name: manifest_payload},
|
|
|
- )
|
|
|
+ archive_renames.append(
|
|
|
+ (
|
|
|
+ f"CPLD/candidate-{item_number:08d}",
|
|
|
+ f"CPLD/{item.candidate.relative}",
|
|
|
+ )
|
|
|
+ )
|
|
|
+ manifest_staging_path = stage_path / "CPLD" / "metadata-manifest"
|
|
|
+ manifest_staging_path.parent.mkdir(parents=True, exist_ok=True)
|
|
|
+ manifest_staging_path.write_bytes(manifest_payload)
|
|
|
+ archive_renames.append(("CPLD/metadata-manifest", manifest_name))
|
|
|
+ _run_7z(
|
|
|
+ seven_zip,
|
|
|
+ build_7zip_create_command(path, stage_path),
|
|
|
+ cwd=stage_path,
|
|
|
+ )
|
|
|
+ _rename_archive_entries(seven_zip, path, archive_renames)
|
|
|
+
|
|
|
+ expected_names = {f"CPLD/{item.candidate.relative}" for item in items}
|
|
|
+ expected_names.add(manifest_name)
|
|
|
+ handoff.verify_archive(
|
|
|
+ path,
|
|
|
+ expected_names=expected_names,
|
|
|
+ inventory=written_inventory,
|
|
|
+ expected_payloads={manifest_name: manifest_payload},
|
|
|
+ )
|
|
|
+ finally:
|
|
|
+ shutil.rmtree(stage_path, ignore_errors=True)
|
|
|
return {
|
|
|
"file": path.name,
|
|
|
"volume_number": number,
|
|
|
@@ -1197,6 +1495,20 @@ def _assert_items_unchanged(
|
|
|
raise PackagingError(f"source changed during analysis packaging: {item.candidate.relative}")
|
|
|
|
|
|
|
|
|
+def _assert_source_trees_unchanged(collection: AnalysisCollection) -> None:
|
|
|
+ for snapshot in collection.source_snapshots:
|
|
|
+ current = _source_snapshot(
|
|
|
+ snapshot.root,
|
|
|
+ source_id=snapshot.source_id,
|
|
|
+ extra_exclusions=snapshot.extra_exclusions,
|
|
|
+ )
|
|
|
+ if (
|
|
|
+ current.candidates != snapshot.candidates
|
|
|
+ or current.excluded != snapshot.excluded
|
|
|
+ ):
|
|
|
+ raise PackagingError("source tree changed during analysis packaging: retry from a stable workspace snapshot")
|
|
|
+
|
|
|
+
|
|
|
def _start_here_text(package_name: str, volume_count: int) -> str:
|
|
|
return (
|
|
|
f"# {package_name} 分析交付包\n\n"
|
|
|
@@ -1388,6 +1700,7 @@ def create_analysis_package(
|
|
|
if handoff.sha256_file(volume_path) != info["sha256"]:
|
|
|
raise PackagingError(f"ZIP volume hash changed after verification: {volume_path.name}")
|
|
|
_assert_items_unchanged(collection.items, inventory_by_path)
|
|
|
+ _assert_source_trees_unchanged(collection)
|
|
|
if chunk_root is not None:
|
|
|
shutil.rmtree(chunk_root)
|
|
|
_publish_directory_atomically(staging, final_dir, force=force)
|
|
|
@@ -1408,6 +1721,66 @@ def create_analysis_package(
|
|
|
}
|
|
|
|
|
|
|
|
|
+def _reference_fingerprint(inventory: list[dict[str, object]]) -> str:
|
|
|
+ digest = hashlib.sha256()
|
|
|
+ for item in sorted(inventory, key=lambda row: str(row["path"])):
|
|
|
+ path = str(item["path"])
|
|
|
+ size = str(item["size"])
|
|
|
+ sha = str(item["sha256"])
|
|
|
+ digest.update(f"{path}|{size}|{sha}\n".encode("utf-8"))
|
|
|
+ return digest.hexdigest()
|
|
|
+
|
|
|
+
|
|
|
+def _create_reference_package_with_cache(
|
|
|
+ *,
|
|
|
+ collection: AnalysisCollection,
|
|
|
+ output_root: Path,
|
|
|
+ package_name: str,
|
|
|
+ max_zip_bytes: int,
|
|
|
+ target_zip_bytes: int,
|
|
|
+ force: bool,
|
|
|
+) -> dict[str, object]:
|
|
|
+ reference_package_name = f"{package_name}-reference"
|
|
|
+ reference_dir = output_root / reference_package_name
|
|
|
+ fingerprint_path = reference_dir / "REFERENCE-FINGERPRINT"
|
|
|
+
|
|
|
+ inventory = _audit_package_items(collection.items)
|
|
|
+ fingerprint = _reference_fingerprint(inventory)
|
|
|
+
|
|
|
+ if not force and fingerprint_path.exists():
|
|
|
+ previous = fingerprint_path.read_text(encoding="ascii").strip()
|
|
|
+ if previous == fingerprint:
|
|
|
+ index_path = reference_dir / "HANDOFF-INDEX.json"
|
|
|
+ if index_path.exists():
|
|
|
+ index = json.loads(index_path.read_text(encoding="utf-8"))
|
|
|
+ return {
|
|
|
+ "status": collection.status,
|
|
|
+ "mode": "reference_cached",
|
|
|
+ "package_name": reference_package_name,
|
|
|
+ "output_dir": str(reference_dir),
|
|
|
+ "volumes": index.get("volumes", []),
|
|
|
+ "included_file_count": len(inventory),
|
|
|
+ "included_bytes": sum(int(item["size"]) for item in inventory),
|
|
|
+ "fingerprint": fingerprint,
|
|
|
+ "skipped": True,
|
|
|
+ }
|
|
|
+
|
|
|
+ payload = create_analysis_package(
|
|
|
+ collection=collection,
|
|
|
+ output_root=output_root,
|
|
|
+ package_name=reference_package_name,
|
|
|
+ max_zip_bytes=max_zip_bytes,
|
|
|
+ target_zip_bytes=target_zip_bytes,
|
|
|
+ force=force,
|
|
|
+ )
|
|
|
+ reference_dir = Path(payload["output_dir"])
|
|
|
+ fingerprint_path = reference_dir / "REFERENCE-FINGERPRINT"
|
|
|
+ fingerprint_path.write_text(fingerprint + "\n", encoding="ascii")
|
|
|
+ payload["fingerprint"] = fingerprint
|
|
|
+ payload["skipped"] = False
|
|
|
+ return payload
|
|
|
+
|
|
|
+
|
|
|
def merge_archive_preparation(
|
|
|
collection: AnalysisCollection,
|
|
|
preparation: ArchivePreparation,
|
|
|
@@ -1424,6 +1797,7 @@ def merge_archive_preparation(
|
|
|
warnings=tuple(warnings),
|
|
|
sources=collection.sources,
|
|
|
git=collection.git,
|
|
|
+ source_snapshots=collection.source_snapshots,
|
|
|
)
|
|
|
|
|
|
|
|
|
@@ -1530,9 +1904,11 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
parser.add_argument("--audit-only", action="store_true", help="scan and verify inputs without creating ZIP files")
|
|
|
parser.add_argument("--explain", type=Path, metavar="PATH", help="explain whether one path is included or excluded")
|
|
|
parser.add_argument("--config", type=Path, default=DEFAULT_CONFIG, help="source and exclusion configuration JSON")
|
|
|
+ parser.add_argument("--source-root", type=Path, default=ROOT, help="root directory to package as the primary source")
|
|
|
parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUTPUT_DIR, help="parent directory for the package directory")
|
|
|
parser.add_argument("--package-name", help="portable package directory and ZIP base name")
|
|
|
parser.add_argument("--force-overwrite", action="store_true", help="atomically replace an existing package directory")
|
|
|
+ parser.add_argument("--no-git-bundle", action="store_true", help="omit the git history bundle from the package")
|
|
|
return parser
|
|
|
|
|
|
|
|
|
@@ -1541,38 +1917,59 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
package_name = args.package_name or datetime.now(timezone.utc).strftime(
|
|
|
"cpld-agent-analysis-%Y%m%dT%H%M%SZ"
|
|
|
)
|
|
|
+ source_root = args.source_root.expanduser().resolve(strict=True)
|
|
|
try:
|
|
|
- config = load_config(args.config, repo_root=ROOT)
|
|
|
+ config = load_config(args.config, repo_root=source_root)
|
|
|
if args.explain is not None:
|
|
|
- payload = explain_analysis_path(args.explain, repo_root=ROOT, config=config)
|
|
|
+ payload = explain_analysis_path(args.explain, repo_root=source_root, config=config)
|
|
|
else:
|
|
|
+ seven_zip = find_7z()
|
|
|
+ if seven_zip is None:
|
|
|
+ raise PackagingError("7-Zip is required for analysis packaging and archive inspection")
|
|
|
_validate_package_name(package_name)
|
|
|
- output_root = _validate_output_root(args.output_dir, repo_root=ROOT, config=config)
|
|
|
+ output_root = _validate_output_root(args.output_dir, repo_root=source_root, config=config)
|
|
|
with tempfile.TemporaryDirectory(prefix="ca-") as temporary:
|
|
|
temp_root = Path(temporary)
|
|
|
collection = collect_analysis_inputs(
|
|
|
- repo_root=ROOT,
|
|
|
+ repo_root=source_root,
|
|
|
config=config,
|
|
|
temp_root=temp_root / "inputs",
|
|
|
+ include_git_bundle=not args.no_git_bundle,
|
|
|
)
|
|
|
preparation = prepare_unsupported_archives(
|
|
|
collection.items,
|
|
|
temp_root=temp_root / "archives",
|
|
|
- seven_zip=find_7z(),
|
|
|
+ seven_zip=seven_zip,
|
|
|
extra_exclusions=config.extra_exclusions,
|
|
|
)
|
|
|
prepared_collection = merge_archive_preparation(collection, preparation)
|
|
|
if args.audit_only:
|
|
|
payload = audit_analysis_collection(prepared_collection)
|
|
|
else:
|
|
|
- payload = create_analysis_package(
|
|
|
- collection=prepared_collection,
|
|
|
- output_root=output_root,
|
|
|
- package_name=package_name,
|
|
|
- max_zip_bytes=config.max_zip_bytes,
|
|
|
- target_zip_bytes=config.target_zip_bytes,
|
|
|
- force=args.force_overwrite,
|
|
|
+ core_collection, reference_collection = _split_collection_by_reference(
|
|
|
+ prepared_collection
|
|
|
)
|
|
|
+ if not core_collection.items and not reference_collection.items:
|
|
|
+ raise PackagingError("analysis package has no included files")
|
|
|
+ payload: dict[str, object] = {}
|
|
|
+ if core_collection.items:
|
|
|
+ payload["core"] = create_analysis_package(
|
|
|
+ collection=core_collection,
|
|
|
+ output_root=output_root,
|
|
|
+ package_name=package_name,
|
|
|
+ max_zip_bytes=config.max_zip_bytes,
|
|
|
+ target_zip_bytes=config.target_zip_bytes,
|
|
|
+ force=args.force_overwrite,
|
|
|
+ )
|
|
|
+ if reference_collection.items:
|
|
|
+ payload["reference"] = _create_reference_package_with_cache(
|
|
|
+ collection=reference_collection,
|
|
|
+ output_root=output_root,
|
|
|
+ package_name=package_name,
|
|
|
+ max_zip_bytes=config.max_zip_bytes,
|
|
|
+ target_zip_bytes=config.target_zip_bytes,
|
|
|
+ force=args.force_overwrite,
|
|
|
+ )
|
|
|
except (PackagingError, OSError, ValueError) as exc:
|
|
|
print(f"error: {exc}", file=sys.stderr)
|
|
|
return 1
|