| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088 |
- #!/usr/bin/env python3
- """Create a complete CPLD analysis handoff from configured source roots."""
- from __future__ import annotations
- import json
- import hashlib
- import argparse
- import concurrent.futures
- import os
- import re
- import shutil
- import stat
- import subprocess
- import sys
- import tempfile
- import uuid
- import zipfile
- from datetime import datetime, timezone
- from pathlib import Path
- from typing import NamedTuple
- ROOT = Path(__file__).resolve().parent
- TOOLS = ROOT / "tools"
- if str(TOOLS) not in sys.path:
- sys.path.insert(0, str(TOOLS))
- import package_agent_handoff as handoff # noqa: E402
- PackagingError = handoff.PackagingError
- CONFIG_SCHEMA = "cpld-agent-analysis-sources-v1"
- DEFAULT_CONFIG = ROOT / "config" / "agent_analysis_handoff_sources.json"
- DEFAULT_OUTPUT_DIR = Path.home() / "Downloads" / "CPLD-agent-analysis"
- CATEGORY_ORDER = {
- "core": 0,
- "hardware": 1,
- "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."""
- from __future__ import annotations
- import argparse
- import hashlib
- import json
- import shutil
- import sys
- import zipfile
- from pathlib import Path, PurePosixPath
- def safe_output_path(root: Path, relative: str) -> Path:
- portable = PurePosixPath(relative)
- if portable.is_absolute() or not portable.parts or any(part in {"", ".", ".."} for part in portable.parts):
- raise RuntimeError(f"unsafe output path: {relative}")
- target = (root / Path(*portable.parts)).resolve(strict=False)
- try:
- target.relative_to(root.resolve(strict=False))
- except ValueError as exc:
- raise RuntimeError(f"output path escapes target directory: {relative}") from exc
- return target
- def sha256_path(path: Path) -> str:
- digest = hashlib.sha256()
- with path.open("rb") as handle:
- for chunk in iter(lambda: handle.read(1024 * 1024), b""):
- digest.update(chunk)
- return digest.hexdigest()
- def main() -> int:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--package-dir", type=Path, default=Path(__file__).resolve().parent)
- parser.add_argument("--output-dir", type=Path, default=Path("reassembled"))
- args = parser.parse_args()
- package_dir = args.package_dir.resolve(strict=True)
- output_dir = args.output_dir.resolve(strict=False)
- index = json.loads((package_dir / "HANDOFF-INDEX.json").read_text(encoding="utf-8"))
- output_dir.mkdir(parents=True, exist_ok=True)
- for item in index.get("large_files", []):
- target = safe_output_path(output_dir, item["path"])
- target.parent.mkdir(parents=True, exist_ok=True)
- temporary = target.with_name(target.name + ".partial")
- temporary.unlink(missing_ok=True)
- total = 0
- with temporary.open("xb") as destination:
- for chunk in sorted(item["chunks"], key=lambda value: value["number"]):
- volume = package_dir / chunk["volume"]
- with zipfile.ZipFile(volume, "r") as archive:
- with archive.open(chunk["archive_path"], "r") as source:
- digest = hashlib.sha256()
- chunk_bytes = 0
- while True:
- payload = source.read(1024 * 1024)
- if not payload:
- break
- destination.write(payload)
- digest.update(payload)
- chunk_bytes += len(payload)
- if chunk_bytes != chunk["size"] or digest.hexdigest() != chunk["sha256"]:
- raise RuntimeError(f"chunk verification failed: {chunk['archive_path']}")
- total += chunk_bytes
- if total != item["size"] or sha256_path(temporary) != item["sha256"]:
- temporary.unlink(missing_ok=True)
- raise RuntimeError(f"reassembled file verification failed: {item['path']}")
- temporary.replace(target)
- print(f"reassembled: {target}")
- return 0
- if __name__ == "__main__":
- try:
- raise SystemExit(main())
- except (OSError, RuntimeError, KeyError, ValueError, json.JSONDecodeError, zipfile.BadZipFile) as exc:
- print(f"error: {exc}", file=sys.stderr)
- raise SystemExit(1)
- '''
- class ExternalSource(NamedTuple):
- id: str
- category: str
- kind: str
- path_candidates: tuple[Path, ...]
- archive_policy: str
- class HandoffConfig(NamedTuple):
- max_zip_bytes: int
- target_zip_bytes: int
- external_sources: tuple[ExternalSource, ...]
- extra_exclusions: tuple[dict[str, str], ...]
- class ResolvedSource(NamedTuple):
- id: str
- category: str
- kind: str
- path: Path
- archive_policy: str
- class PackageItem(NamedTuple):
- candidate: handoff.Candidate
- category: str
- source_id: str
- original_path: str
- 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, ...]
- excluded: tuple[dict[str, str], ...]
- 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):
- items: tuple[PackageItem, ...]
- excluded: tuple[dict[str, str], ...]
- 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:
- if any("include" in item.casefold() for item in unknown):
- raise PackagingError(f"positive include rules are forbidden in {label}: {unknown}")
- raise PackagingError(f"unsupported fields in {label}: {unknown}")
- def _expand_path(value: str, *, repo_root: Path, user_profile: Path) -> Path:
- tokens = {
- "repo_root": str(repo_root),
- "user_profile": str(user_profile),
- "codex_temp": str(user_profile / "CodexTemp"),
- }
- try:
- expanded = value.format_map(tokens)
- except (KeyError, ValueError) as exc:
- raise PackagingError(f"unsupported path token in external source: {value}") from exc
- return Path(expanded).expanduser()
- def load_config(
- path: Path,
- *,
- repo_root: Path = ROOT,
- user_profile: Path | None = None,
- ) -> HandoffConfig:
- try:
- payload = json.loads(path.read_text(encoding="utf-8-sig"))
- except (OSError, UnicodeError, json.JSONDecodeError) as exc:
- raise PackagingError(f"unable to read analysis source config: {path}") from exc
- if not isinstance(payload, dict):
- raise PackagingError("analysis source config must be a JSON object")
- _require_keys(
- payload,
- {
- "schema",
- "max_zip_bytes",
- "target_zip_bytes",
- "external_sources",
- "extra_exclusions",
- },
- "config",
- )
- if payload.get("schema") != CONFIG_SCHEMA:
- raise PackagingError(f"unsupported analysis source config schema: {payload.get('schema')}")
- max_zip_bytes = payload.get("max_zip_bytes")
- target_zip_bytes = payload.get("target_zip_bytes")
- if not isinstance(max_zip_bytes, int) or max_zip_bytes <= 0:
- raise PackagingError("max_zip_bytes must be a positive integer")
- if not isinstance(target_zip_bytes, int) or not 0 < target_zip_bytes < max_zip_bytes:
- raise PackagingError("target_zip_bytes must be positive and smaller than max_zip_bytes")
- raw_sources = payload.get("external_sources")
- if not isinstance(raw_sources, list):
- raise PackagingError("external_sources must be an array")
- profile = user_profile or Path.home()
- sources: list[ExternalSource] = []
- seen_ids: set[str] = set()
- for index, raw_source in enumerate(raw_sources):
- if not isinstance(raw_source, dict):
- raise PackagingError(f"external_sources[{index}] must be an object")
- _require_keys(
- raw_source,
- {"id", "category", "kind", "path_candidates", "archive_policy"},
- f"external_sources[{index}]",
- )
- source_id = raw_source.get("id")
- category = raw_source.get("category")
- kind = raw_source.get("kind")
- archive_policy = raw_source.get("archive_policy")
- raw_paths = raw_source.get("path_candidates")
- if not isinstance(source_id, str) or not source_id or source_id in seen_ids:
- raise PackagingError(f"external source id is missing or duplicated: {source_id}")
- if not isinstance(category, str) or not category:
- raise PackagingError(f"external source category is invalid: {source_id}")
- if kind not in {"directory", "file", "git_worktree"}:
- raise PackagingError(f"external source kind is invalid: {source_id}")
- if archive_policy not in {"inspect", "copy"}:
- raise PackagingError(f"external archive policy is invalid: {source_id}")
- if not isinstance(raw_paths, list) or not raw_paths or not all(isinstance(item, str) for item in raw_paths):
- raise PackagingError(f"external source path_candidates are invalid: {source_id}")
- seen_ids.add(source_id)
- sources.append(
- ExternalSource(
- id=source_id,
- category=category,
- kind=kind,
- path_candidates=tuple(
- _expand_path(item, repo_root=repo_root, user_profile=profile)
- for item in raw_paths
- ),
- archive_policy=archive_policy,
- )
- )
- raw_exclusions = payload.get("extra_exclusions")
- if not isinstance(raw_exclusions, list) or not all(isinstance(item, dict) for item in raw_exclusions):
- raise PackagingError("extra_exclusions must be an array of objects")
- exclusions: list[dict[str, str]] = []
- for index, raw_exclusion in enumerate(raw_exclusions):
- _require_keys(raw_exclusion, {"path", "reason"}, f"extra_exclusions[{index}]")
- exclusion_path = raw_exclusion.get("path")
- reason = raw_exclusion.get("reason")
- if not isinstance(exclusion_path, str) or not exclusion_path or "\\" in exclusion_path:
- raise PackagingError(f"extra exclusion path is invalid: {index}")
- if not isinstance(reason, str) or not reason.strip():
- raise PackagingError(f"extra exclusion reason is invalid: {index}")
- normalized_path = handoff.normalize_relative(exclusion_path.strip("/").split("/"))
- exclusions.append({"path": normalized_path, "reason": reason.strip()})
- return HandoffConfig(
- max_zip_bytes=max_zip_bytes,
- target_zip_bytes=target_zip_bytes,
- external_sources=tuple(sources),
- extra_exclusions=tuple(exclusions),
- )
- def analysis_exclusion_reason(
- relative: str,
- *,
- is_dir: bool,
- context: handoff.ScanContext,
- extra_exclusions: tuple[dict[str, str], ...] = (),
- ) -> str | None:
- 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:
- return secret_reason
- for item in extra_exclusions:
- 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"
- 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",
- ".mypy_cache": "mypy_cache",
- ".ruff_cache": "ruff_cache",
- ".tox": "tox_environment",
- ".nox": "nox_environment",
- ".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 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
- def scan_analysis_root(
- root: Path,
- *,
- extra_exclusions: tuple[dict[str, str], ...] = (),
- ) -> tuple[list[handoff.Candidate], list[dict[str, str]], handoff.ScanContext]:
- def resolve(relative: str, *, is_dir: bool, context: handoff.ScanContext) -> str | None:
- return analysis_exclusion_reason(
- relative,
- is_dir=is_dir,
- context=context,
- extra_exclusions=extra_exclusions,
- )
- return handoff.scan_tree(root, exclusion_resolver=resolve)
- def resolve_external_sources(
- sources: tuple[ExternalSource, ...],
- ) -> tuple[list[ResolvedSource], list[dict[str, str]]]:
- resolved: list[ResolvedSource] = []
- warnings: list[dict[str, str]] = []
- for source in sources:
- selected: Path | None = None
- for candidate in source.path_candidates:
- if source.kind == "file" and candidate.is_file():
- selected = candidate.resolve(strict=True)
- break
- if source.kind in {"directory", "git_worktree"} and candidate.is_dir():
- selected = candidate.resolve(strict=True)
- break
- if selected is None:
- warnings.append(
- {
- "code": "missing_external_source",
- "source_id": source.id,
- "message": "no configured path candidate is available",
- }
- )
- continue
- resolved.append(
- ResolvedSource(
- id=source.id,
- category=source.category,
- kind=source.kind,
- path=selected,
- archive_policy=source.archive_policy,
- )
- )
- return resolved, warnings
- def _candidate_from_path(path: Path, relative: str) -> handoff.Candidate:
- try:
- file_stat = os.lstat(path)
- except OSError as exc:
- raise PackagingError(f"unable to inspect generated analysis input: {relative}") from exc
- if not stat.S_ISREG(file_stat.st_mode) or handoff.stat_is_reparse_point(file_stat):
- raise PackagingError(f"analysis input is not a regular file: {relative}")
- return handoff.Candidate(
- absolute=path,
- relative=handoff.normalize_relative(relative.split("/")),
- size=file_stat.st_size,
- mtime_ns=file_stat.st_mtime_ns,
- device=int(file_stat.st_dev),
- inode=int(file_stat.st_ino),
- mode=int(file_stat.st_mode),
- )
- def make_package_item(
- path: Path,
- *,
- relative: str,
- category: str,
- source_id: str,
- scan_archive: bool = True,
- ) -> PackageItem:
- return PackageItem(
- candidate=_candidate_from_path(path, relative),
- category=category,
- source_id=source_id,
- original_path=path.name,
- scan_archive=scan_archive,
- )
- def _rebase_candidate(candidate: handoff.Candidate, prefix: str) -> handoff.Candidate:
- return handoff.Candidate(
- absolute=candidate.absolute,
- relative=handoff.normalize_relative([*prefix.split("/"), *candidate.relative.split("/")]),
- size=candidate.size,
- mtime_ns=candidate.mtime_ns,
- device=candidate.device,
- inode=candidate.inode,
- mode=candidate.mode,
- )
- def _rebase_exclusions(excluded: list[dict[str, str]], prefix: str) -> list[dict[str, str]]:
- return [
- {
- "path": handoff.normalize_relative([*prefix.split("/"), *item["path"].split("/")]),
- "rule": item["rule"],
- }
- for item in excluded
- ]
- def _collect_directory_items(
- *,
- root: Path,
- source_id: str,
- category: str,
- prefix: str,
- extra_exclusions: tuple[dict[str, str], ...],
- ) -> tuple[list[PackageItem], list[dict[str, str]]]:
- candidates, excluded, _ = scan_analysis_root(root, extra_exclusions=extra_exclusions)
- items = [
- PackageItem(
- candidate=_rebase_candidate(candidate, prefix),
- category=category,
- source_id=source_id,
- original_path=candidate.relative,
- scan_archive=True,
- )
- for candidate in candidates
- ]
- return items, _rebase_exclusions(excluded, prefix)
- def _run_git(command: list[str], *, cwd: Path, timeout: int = 300) -> str:
- try:
- completed = subprocess.run(
- command,
- cwd=cwd,
- stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT,
- text=True,
- encoding="utf-8",
- errors="replace",
- timeout=timeout,
- check=False,
- )
- except (OSError, subprocess.TimeoutExpired) as exc:
- raise PackagingError(f"unable to run Git for {cwd.name}") from exc
- if completed.returncode != 0:
- detail = completed.stdout.strip().splitlines()
- suffix = f": {detail[-1]}" if detail else ""
- raise PackagingError(f"Git command failed for {cwd.name}{suffix}")
- return completed.stdout
- def _create_git_bundle(
- *,
- root: Path,
- source_id: str,
- temp_root: Path,
- ) -> tuple[PackageItem, dict[str, object]]:
- git = shutil.which("git")
- if not git:
- raise PackagingError("Git is required to create complete analysis history bundles")
- bundle_dir = temp_root / "git-bundles"
- bundle_dir.mkdir(parents=True, exist_ok=True)
- bundle_path = bundle_dir / f"{source_id}.bundle"
- _run_git([git, "bundle", "create", str(bundle_path), "--all"], cwd=root)
- verify_output = _run_git([git, "bundle", "verify", str(bundle_path)], cwd=root)
- head = _run_git([git, "rev-parse", "HEAD"], cwd=root).strip()
- branch = _run_git([git, "branch", "--show-current"], cwd=root).strip() or None
- status = _run_git(
- [
- git,
- "--no-optional-locks",
- "-c",
- "core.fsmonitor=false",
- "-c",
- "core.untrackedCache=false",
- "status",
- "--short",
- "--branch",
- "--untracked-files=all",
- ],
- cwd=root,
- )
- ref_lines = [line for line in verify_output.splitlines() if " refs/" in line or line.rstrip().endswith(" HEAD")]
- candidate = _candidate_from_path(bundle_path, f"git-history/{source_id}.bundle")
- item = PackageItem(
- candidate=candidate,
- category="core",
- source_id=source_id,
- original_path=".git",
- scan_archive=False,
- )
- metadata = {
- "source_id": source_id,
- "branch": branch,
- "head": head,
- "working_tree_clean": not any(
- line and not line.startswith("##") for line in status.splitlines()
- ),
- "status": "pass",
- "bundle_path": candidate.relative,
- "bundle_ref_count": len(ref_lines),
- "bundle_verify": "pass",
- }
- return item, metadata
- 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)
- items: list[PackageItem] = []
- excluded: list[dict[str, str]] = []
- 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,
- source_id="workspace-current",
- category="core",
- prefix="workspace-current",
- extra_exclusions=config.extra_exclusions,
- )
- 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",
- "category": "core",
- "kind": "git_worktree",
- "path": str(root),
- "status": "pass",
- }
- )
- 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)
- for source in resolved_sources:
- prefix = f"external/{source.id}"
- if source.kind == "file":
- candidate = _candidate_from_path(source.path, f"{prefix}/{source.path.name}")
- items.append(
- PackageItem(
- candidate=candidate,
- category=source.category,
- source_id=source.id,
- original_path=source.path.name,
- scan_archive=source.archive_policy == "inspect",
- )
- )
- else:
- source_items, source_excluded = _collect_directory_items(
- root=source.path,
- source_id=source.id,
- category=source.category,
- prefix=prefix,
- extra_exclusions=config.extra_exclusions,
- )
- 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,
- "category": source.category,
- "kind": source.kind,
- "path": str(source.path),
- "status": "pass",
- }
- )
- if source.kind == "git_worktree":
- external_bundle, external_git = _create_git_bundle(
- root=source.path,
- source_id=source.id,
- temp_root=temp_root,
- )
- items.append(external_bundle)
- git_metadata.append(external_git)
- items.sort(key=lambda item: handoff.windows_collision_key(item.candidate.relative))
- excluded.sort(key=lambda item: handoff.windows_collision_key(item["path"]))
- return AnalysisCollection(
- status="pass_with_warnings" if warnings else "pass",
- items=tuple(items),
- excluded=tuple(excluded),
- warnings=tuple(warnings),
- sources=tuple(sources),
- git=tuple(git_metadata),
- source_snapshots=tuple(source_snapshots),
- )
- def find_7z() -> Path | None:
- discovered = shutil.which("7z") or shutil.which("7zz")
- candidates = [
- Path(discovered) if discovered else None,
- Path(r"C:\Program Files\7-Zip\7z.exe"),
- Path(r"C:\Program Files (x86)\7-Zip\7z.exe"),
- ]
- for candidate in candidates:
- if candidate is not None and candidate.is_file():
- return candidate.resolve(strict=True)
- 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(
- [str(seven_zip), *arguments],
- cwd=cwd,
- stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT,
- text=True,
- encoding="utf-8",
- errors="replace",
- timeout=300,
- check=False,
- )
- except (OSError, subprocess.TimeoutExpired) as exc:
- raise PackagingError("unable to run 7-Zip for archive inspection") from exc
- if completed.returncode != 0:
- detail = completed.stdout.strip().splitlines()
- suffix = f": {detail[-1]}" if detail else ""
- raise PackagingError(f"7-Zip archive inspection failed{suffix}")
- 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] = {}
- members: list[dict[str, str]] = []
- for raw_line in payload.splitlines():
- line = raw_line.rstrip("\r\n")
- if line.strip() == "----------":
- in_members = True
- current = {}
- continue
- if not in_members:
- continue
- if not line.strip():
- if current:
- members.append(current)
- current = {}
- continue
- key, separator, value = line.partition(" = ")
- if separator:
- current[key.strip()] = value.strip()
- if current:
- members.append(current)
- for member in members:
- raw_path = member.get("Path", "")
- normalized = raw_path.replace("\\", "/")
- if not normalized or normalized.startswith("/") or re.match(r"^[A-Za-z]:", normalized):
- raise PackagingError(f"unsafe archive member path in {archive_label}")
- handoff.normalize_relative(normalized.split("/"))
- if member.get("Encrypted") not in {None, "", "-"}:
- raise PackagingError(f"encrypted archive member is unsupported in {archive_label}")
- if member.get("Symbolic Link") or member.get("Hard Link"):
- raise PackagingError(f"archive link member is unsupported in {archive_label}")
- if member.get("Alternate Stream") not in {None, "", "-"}:
- raise PackagingError(f"archive alternate stream is unsupported in {archive_label}")
- if member.get("Split Before") not in {None, "", "-"} or member.get("Split After") not in {
- None,
- "",
- "-",
- }:
- raise PackagingError(f"split archive member is unsupported in {archive_label}")
- return members
- def _inspect_and_extract_unsupported_archive(
- item: PackageItem,
- *,
- temp_root: Path,
- seven_zip: Path,
- extra_exclusions: tuple[dict[str, str], ...],
- ) -> tuple[list[PackageItem], list[dict[str, str]], bool]:
- listing = _run_7z(
- seven_zip,
- ["l", "-slt", "-sccUTF-8", str(item.candidate.absolute)],
- cwd=item.candidate.absolute.parent,
- )
- members = _parse_7z_members(listing, item.candidate.relative)
- file_members = [
- member
- for member in members
- if member.get("Folder") != "+" and "D" not in member.get("Attributes", "")
- ]
- expected_bytes = sum(int(member.get("Size") or "0") for member in file_members)
- token = hashlib.sha256(item.candidate.relative.encode("utf-8")).hexdigest()[:16]
- extract_root = temp_root / "expanded-archives" / token
- extract_root.mkdir(parents=True, exist_ok=False)
- _run_7z(
- seven_zip,
- ["x", "-y", "-aoa", "-sccUTF-8", f"-o{extract_root}", str(item.candidate.absolute)],
- cwd=item.candidate.absolute.parent,
- )
- actual_files = [path for path in extract_root.rglob("*") if path.is_file()]
- actual_bytes = sum(path.stat().st_size for path in actual_files)
- if len(actual_files) != len(file_members) or actual_bytes != expected_bytes:
- raise PackagingError(
- f"archive extraction inventory mismatch: {item.candidate.relative} "
- f"(files {len(actual_files)}/{len(file_members)}, bytes {actual_bytes}/{expected_bytes})"
- )
- expanded_candidates, expanded_excluded, _ = scan_analysis_root(
- extract_root,
- extra_exclusions=extra_exclusions,
- )
- handoff.audit_candidates(expanded_candidates)
- expanded_prefix = f"{item.candidate.relative}.expanded"
- expanded_items = [
- PackageItem(
- candidate=_rebase_candidate(candidate, expanded_prefix),
- category=item.category,
- source_id=item.source_id,
- original_path=f"{item.original_path}!/{candidate.relative}",
- scan_archive=True,
- )
- for candidate in expanded_candidates
- ]
- rebased_excluded = _rebase_exclusions(expanded_excluded, expanded_prefix)
- sensitive_rules = {
- "credential_or_license_file",
- "credential_configuration_file",
- "private_key_file",
- "secret_environment_file",
- "cloud_credential_file",
- "container_registry_credential_file",
- }
- contains_sensitive = any(entry["rule"] in sensitive_rules for entry in expanded_excluded)
- return expanded_items, rebased_excluded, contains_sensitive
- def _inspect_and_extract_zip_archive(
- item: PackageItem,
- *,
- temp_root: Path,
- extra_exclusions: tuple[dict[str, str], ...],
- ) -> tuple[list[PackageItem], list[dict[str, str]], bool]:
- archive_label = item.candidate.relative
- try:
- with zipfile.ZipFile(item.candidate.absolute, "r") as archive:
- file_members: list[zipfile.ZipInfo] = []
- expected_bytes = 0
- for info in archive.infolist():
- normalized = info.filename.replace("\\", "/")
- if (
- not normalized
- or normalized.startswith("/")
- or re.match(r"^[A-Za-z]:", normalized)
- ):
- raise PackagingError(
- f"unsafe archive member path in {archive_label}"
- )
- handoff.normalize_relative(normalized.split("/"))
- if info.flag_bits & 0x1:
- raise PackagingError(
- f"encrypted archive member is unsupported in {archive_label}"
- )
- member_mode = (info.external_attr >> 16) & 0xFFFF
- member_type = stat.S_IFMT(member_mode)
- if info.is_dir():
- if (
- info.file_size != 0
- or info.compress_size != 0
- or member_type not in {0, stat.S_IFDIR}
- ):
- raise PackagingError(
- f"unsafe archive member type in {archive_label}"
- )
- continue
- if member_type not in {0, stat.S_IFREG}:
- raise PackagingError(
- f"unsafe archive member type in {archive_label}"
- )
- file_members.append(info)
- expected_bytes += info.file_size
- except (OSError, zipfile.BadZipFile) as exc:
- raise PackagingError(
- f"unable to inspect source archive: {archive_label}"
- ) from exc
- token = hashlib.sha256(archive_label.encode("utf-8")).hexdigest()[:16]
- extract_root = temp_root / "expanded-archives" / token
- extract_root.mkdir(parents=True, exist_ok=False)
- actual_files: list[Path] = []
- actual_bytes = 0
- try:
- with zipfile.ZipFile(item.candidate.absolute, "r") as archive:
- for info in file_members:
- parts = info.filename.replace("\\", "/").split("/")
- target_path = extract_root / Path(*parts)
- target_path.parent.mkdir(parents=True, exist_ok=True)
- with archive.open(info, "r") as source, target_path.open("wb") as destination:
- shutil.copyfileobj(source, destination, length=1024 * 1024)
- actual_files.append(target_path)
- actual_bytes += target_path.stat().st_size
- except (OSError, zipfile.BadZipFile) as exc:
- raise PackagingError(
- f"unable to extract source archive: {archive_label}"
- ) from exc
- if len(actual_files) != len(file_members) or actual_bytes != expected_bytes:
- raise PackagingError(
- f"archive extraction inventory mismatch: {archive_label} "
- f"(files {len(actual_files)}/{len(file_members)}, bytes {actual_bytes}/{expected_bytes})"
- )
- expanded_candidates, expanded_excluded, _ = scan_analysis_root(
- extract_root,
- extra_exclusions=extra_exclusions,
- )
- handoff.audit_candidates(expanded_candidates)
- expanded_prefix = f"{archive_label}.expanded"
- expanded_items = [
- PackageItem(
- candidate=_rebase_candidate(candidate, expanded_prefix),
- category=item.category,
- source_id=item.source_id,
- original_path=f"{item.original_path}!/{candidate.relative}",
- scan_archive=True,
- )
- for candidate in expanded_candidates
- ]
- rebased_excluded = _rebase_exclusions(expanded_excluded, expanded_prefix)
- sensitive_rules = {
- "credential_or_license_file",
- "credential_configuration_file",
- "private_key_file",
- "secret_environment_file",
- "cloud_credential_file",
- "container_registry_credential_file",
- }
- contains_sensitive = any(entry["rule"] in sensitive_rules for entry in expanded_excluded)
- return expanded_items, rebased_excluded, contains_sensitive
- def prepare_unsupported_archives(
- items: tuple[PackageItem, ...],
- *,
- temp_root: Path,
- seven_zip: Path | None,
- extra_exclusions: tuple[dict[str, str], ...],
- ) -> ArchivePreparation:
- prepared: list[PackageItem] = []
- excluded: list[dict[str, str]] = []
- warnings: list[dict[str, str]] = []
- temp_root.mkdir(parents=True, exist_ok=True)
- for item in items:
- archive_kind = handoff.archive_kind(item.candidate.relative)
- if archive_kind is None:
- prepared.append(item)
- continue
- if archive_kind == "zip":
- expanded_items, expanded_excluded, contains_sensitive = _inspect_and_extract_zip_archive(
- item,
- temp_root=temp_root,
- extra_exclusions=extra_exclusions,
- )
- elif seven_zip is None:
- if _is_reference_item(item):
- warnings.append(
- {
- "code": "unsupported_archive_without_7zip",
- "source_id": item.source_id,
- "path": item.candidate.relative,
- "message": "7-Zip is unavailable; unsupported archive kept unexpanded",
- }
- )
- prepared.append(item._replace(scan_archive=False))
- continue
- if item.candidate.absolute.is_file():
- raise PackagingError(
- "7-Zip is required to inspect unsupported source archives"
- )
- prepared.append(item._replace(scan_archive=False))
- continue
- else:
- expanded_items, expanded_excluded, contains_sensitive = _inspect_and_extract_unsupported_archive(
- item,
- temp_root=temp_root,
- seven_zip=seven_zip,
- extra_exclusions=extra_exclusions,
- )
- has_filtered_members = bool(expanded_excluded)
- if has_filtered_members:
- prepared.extend(expanded_items)
- excluded.extend(expanded_excluded)
- if contains_sensitive:
- excluded.append(
- {
- "path": item.candidate.relative,
- "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=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(
- items=tuple(prepared),
- excluded=tuple(excluded),
- warnings=tuple(warnings),
- )
- def _utc_now() -> str:
- return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
- def _validate_package_name(package_name: str) -> None:
- try:
- collision_key = handoff.windows_collision_key(package_name)
- except PackagingError as exc:
- raise PackagingError("package name is not a portable Windows file name") from exc
- if (
- not handoff.SAFE_PACKAGE_NAME.fullmatch(package_name)
- or package_name in {".", ".."}
- or not collision_key
- ):
- raise PackagingError("package name is not a portable Windows file name")
- def _item_sort_key(item: PackageItem) -> tuple[int, str, str]:
- return (
- CATEGORY_ORDER.get(item.category, len(CATEGORY_ORDER)),
- item.category.casefold(),
- handoff.windows_collision_key(item.candidate.relative),
- )
- 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]]:
- sorted_items = sorted(items, key=_item_sort_key)
- collision_paths: dict[str, str] = {}
- for item in sorted_items:
- key = handoff.windows_collision_key(item.candidate.relative)
- previous = collision_paths.get(key)
- if previous is not None:
- raise PackagingError(
- f"analysis inputs contain a Windows path collision: {previous} and {item.candidate.relative}"
- )
- collision_paths[key] = item.candidate.relative
- 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(
- archive: zipfile.ZipFile,
- item: PackageItem,
- ) -> dict[str, object]:
- candidate = item.candidate
- digest = hashlib.sha256()
- total = 0
- secret_tail = b""
- entry_name = f"CPLD/{candidate.relative}"
- try:
- with archive.open(handoff.zip_info(entry_name, candidate.mode), "w", force_zip64=True) as target:
- with handoff.open_candidate(candidate) as source:
- for chunk in iter(lambda: source.read(1024 * 1024), b""):
- secret_tail = handoff.scan_secret_markers(
- chunk,
- secret_tail,
- candidate.relative,
- )
- target.write(chunk)
- digest.update(chunk)
- total += len(chunk)
- except OSError as exc:
- raise PackagingError(f"unable to package {candidate.relative}: {exc}") from exc
- if total != candidate.size:
- raise PackagingError(f"source size changed during packaging: {candidate.relative}")
- return {"path": candidate.relative, "size": total, "sha256": digest.hexdigest()}
- def _write_package_item(
- archive: zipfile.ZipFile,
- item: PackageItem,
- ) -> dict[str, object]:
- if item.scan_archive:
- return handoff.write_candidate(archive, item.candidate)
- 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,
- package_name: str,
- number: int,
- count: int,
- items: list[PackageItem],
- inventory_by_path: dict[str, dict[str, object]],
- ) -> dict[str, object]:
- categories = sorted({item.category for item in items})
- entries = [inventory_by_path[item.candidate.relative] for item in items]
- return {
- "schema": "cpld-agent-analysis-volume-v1",
- "run_id": run_id,
- "package_name": package_name,
- "volume_number": number,
- "volume_count": count,
- "categories": categories,
- "file_count": len(entries),
- "uncompressed_bytes": sum(int(entry["size"]) for entry in entries),
- "files": entries,
- }
- def _write_volume(
- path: Path,
- *,
- run_id: str,
- package_name: str,
- number: int,
- count: int,
- items: list[PackageItem],
- inventory_by_path: dict[str, dict[str, object]],
- ) -> dict[str, object]:
- manifest = _volume_manifest(
- run_id=run_id,
- package_name=package_name,
- number=number,
- count=count,
- items=items,
- inventory_by_path=inventory_by_path,
- )
- manifest_name = "CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json"
- manifest_payload = handoff.json_bytes(manifest)
- written_inventory: list[dict[str, object]] = []
- try:
- with zipfile.ZipFile(
- path, "w", compression=zipfile.ZIP_DEFLATED, allowZip64=True
- ) as archive:
- for item in sorted(items, key=_item_sort_key):
- expected = inventory_by_path[item.candidate.relative]
- if item.scan_archive:
- actual = handoff.write_candidate(archive, item.candidate)
- else:
- actual = _write_unscanned_candidate(archive, item)
- 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)
- with archive.open(
- handoff.zip_info(manifest_name), "w", force_zip64=True
- ) as target:
- target.write(manifest_payload)
- except (OSError, zipfile.BadZipFile) as exc:
- raise PackagingError(f"unable to create ZIP volume: {exc}") from exc
- 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},
- )
- return {
- "file": path.name,
- "volume_number": number,
- "volume_count": count,
- "categories": manifest["categories"],
- "file_count": len(items),
- "uncompressed_bytes": manifest["uncompressed_bytes"],
- "compressed_bytes": path.stat().st_size,
- "sha256": handoff.sha256_file(path),
- }
- def _estimated_item_bytes(item: PackageItem) -> int:
- return item.candidate.size + 512 + (len(item.candidate.relative.encode("utf-8")) * 2)
- def _partition_items(
- items: tuple[PackageItem, ...],
- *,
- target_zip_bytes: int,
- ) -> list[list[PackageItem]]:
- base_overhead = min(64_000, max(1_024, target_zip_bytes // 20))
- groups: list[list[PackageItem]] = []
- current: list[PackageItem] = []
- current_category: str | None = None
- estimated_bytes = base_overhead
- for item in sorted(items, key=_item_sort_key):
- item_estimate = _estimated_item_bytes(item)
- if current and (
- item.category != current_category
- or estimated_bytes + item_estimate > target_zip_bytes
- ):
- groups.append(current)
- current = []
- estimated_bytes = base_overhead
- if not current:
- current_category = item.category
- current.append(item)
- estimated_bytes += item_estimate
- if current:
- groups.append(current)
- return groups
- def _split_oversized_groups(
- staging: Path,
- *,
- run_id: str,
- package_name: str,
- groups: list[list[PackageItem]],
- inventory_by_path: dict[str, dict[str, object]],
- target_zip_bytes: int,
- max_zip_bytes: int,
- ) -> list[list[PackageItem]]:
- pending = list(groups)
- accepted: list[list[PackageItem]] = []
- probe_number = 0
- while pending:
- group = pending.pop(0)
- probe_number += 1
- probe = staging / f".volume-probe-{probe_number:04d}.zip"
- try:
- _write_volume(
- probe,
- run_id=run_id,
- package_name=package_name,
- number=1,
- count=1,
- items=group,
- inventory_by_path=inventory_by_path,
- )
- size = probe.stat().st_size
- finally:
- probe.unlink(missing_ok=True)
- if size < max_zip_bytes and (size <= target_zip_bytes or len(group) == 1):
- accepted.append(group)
- continue
- if len(group) == 1:
- raise PackagingError(
- f"single analysis file requires chunking before ZIP creation: {group[0].candidate.relative}"
- )
- middle = len(group) // 2
- pending[0:0] = [group[:middle], group[middle:]]
- return accepted
- def _prepare_large_file_chunks(
- staging: Path,
- *,
- run_id: str,
- package_name: str,
- items: tuple[PackageItem, ...],
- inventory_by_path: dict[str, dict[str, object]],
- target_zip_bytes: int,
- max_zip_bytes: int,
- ) -> tuple[tuple[PackageItem, ...], list[dict[str, object]], Path | None]:
- packaged_items: list[PackageItem] = []
- large_files: list[dict[str, object]] = []
- chunk_root: Path | None = None
- probe_number = 0
- chunk_payload_bytes = max(1, (target_zip_bytes * 3) // 4)
- for item in sorted(items, key=_item_sort_key):
- must_probe = _estimated_item_bytes(item) > target_zip_bytes
- if must_probe:
- probe_number += 1
- probe = staging / f".large-file-probe-{probe_number:04d}.zip"
- try:
- _write_volume(
- probe,
- run_id=run_id,
- package_name=package_name,
- number=1,
- count=1,
- items=[item],
- inventory_by_path=inventory_by_path,
- )
- probe_size = probe.stat().st_size
- finally:
- probe.unlink(missing_ok=True)
- if probe_size <= target_zip_bytes and probe_size < max_zip_bytes:
- packaged_items.append(item)
- continue
- else:
- packaged_items.append(item)
- continue
- if chunk_root is None:
- chunk_root = staging / ".large-file-chunks"
- chunk_root.mkdir()
- original = inventory_by_path[item.candidate.relative]
- file_id = hashlib.sha256(item.candidate.relative.encode("utf-8")).hexdigest()[:16]
- file_chunk_root = chunk_root / file_id
- file_chunk_root.mkdir()
- file_name = Path(item.candidate.relative).name
- chunks: list[dict[str, object]] = []
- original_digest = hashlib.sha256()
- original_bytes = 0
- secret_tail = b""
- with handoff.open_candidate(item.candidate) as source:
- number = 0
- while True:
- payload = source.read(chunk_payload_bytes)
- if not payload:
- break
- number += 1
- secret_tail = handoff.scan_secret_markers(
- payload,
- secret_tail,
- item.candidate.relative,
- )
- original_digest.update(payload)
- original_bytes += len(payload)
- chunk_name = f"{file_name}.part{number:04d}"
- chunk_path = file_chunk_root / chunk_name
- with chunk_path.open("xb") as handle:
- handle.write(payload)
- chunk_relative = f"HANDOFF-LARGE-FILES/{file_id}/{chunk_name}"
- chunk_item = make_package_item(
- chunk_path,
- relative=chunk_relative,
- category=item.category,
- source_id=item.source_id,
- scan_archive=False,
- )
- packaged_items.append(chunk_item)
- chunks.append(
- {
- "number": number,
- "path": chunk_relative,
- "archive_path": f"CPLD/{chunk_relative}",
- "size": len(payload),
- "sha256": hashlib.sha256(payload).hexdigest(),
- }
- )
- if original_bytes != original["size"] or original_digest.hexdigest() != original["sha256"]:
- raise PackagingError(f"source changed while splitting large file: {item.candidate.relative}")
- if len(chunks) < 2:
- raise PackagingError(f"large file split did not produce multiple chunks: {item.candidate.relative}")
- large_files.append(
- {
- "path": item.candidate.relative,
- "category": item.category,
- "source_id": item.source_id,
- "original_path": item.original_path,
- "size": original["size"],
- "sha256": original["sha256"],
- "chunks": chunks,
- }
- )
- return tuple(packaged_items), large_files, chunk_root
- def _assert_items_unchanged(
- items: tuple[PackageItem, ...],
- inventory_by_path: dict[str, dict[str, object]],
- ) -> None:
- for item in items:
- current = handoff.hash_candidate(item.candidate)
- expected = inventory_by_path[item.candidate.relative]
- if current["size"] != expected["size"] or current["sha256"] != expected["sha256"]:
- 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"
- f"本目录包含 {volume_count} 个互相独立的普通 ZIP。请先核对 `SHA256SUMS.txt`,"
- "再把所有 ZIP 解压到同一个目录。\n\n"
- "`HANDOFF-INDEX.json` 记录每个原始文件的来源、目标卷、大小和 SHA-256。\n"
- )
- def _publish_directory_atomically(staging: Path, final: Path, *, force: bool) -> None:
- backup: Path | None = None
- backup_created = False
- new_directory_published = False
- if os.path.lexists(final):
- if not force:
- raise PackagingError(f"package output already exists: {final}")
- file_stat = os.lstat(final)
- if not stat.S_ISDIR(file_stat.st_mode) or handoff.stat_is_reparse_point(file_stat):
- raise PackagingError(f"existing package output is not a regular directory: {final}")
- backup = final.with_name(f".{final.name}.{uuid.uuid4().hex}.backup")
- try:
- if backup is not None:
- os.replace(final, backup)
- backup_created = True
- os.replace(staging, final)
- new_directory_published = True
- except BaseException as exc:
- if new_directory_published and os.path.lexists(final):
- try:
- shutil.rmtree(final)
- except OSError:
- pass
- if backup_created and backup is not None and os.path.lexists(backup):
- try:
- os.replace(backup, final)
- except OSError as rollback_exc:
- raise PackagingError(
- f"package publication failed and rollback was incomplete: {rollback_exc}"
- ) from exc
- if isinstance(exc, PackagingError):
- raise
- raise PackagingError(f"unable to publish package directory atomically: {exc}") from exc
- if backup is not None:
- shutil.rmtree(backup)
- def create_analysis_package(
- *,
- collection: AnalysisCollection,
- output_root: Path,
- package_name: str,
- max_zip_bytes: int,
- target_zip_bytes: int,
- force: bool,
- ) -> dict[str, object]:
- _validate_package_name(package_name)
- if max_zip_bytes <= 0 or not 0 < target_zip_bytes < max_zip_bytes:
- raise PackagingError("ZIP size limits are invalid")
- if not collection.items:
- raise PackagingError("analysis package has no included files")
- output_root = output_root.expanduser().resolve(strict=False)
- output_root.mkdir(parents=True, exist_ok=True)
- final_dir = output_root / package_name
- if os.path.lexists(final_dir) and not force:
- raise PackagingError(f"package output already exists: {final_dir}")
- run_id = uuid.uuid4().hex
- staging = Path(tempfile.mkdtemp(prefix=f".{package_name}.{run_id}.", dir=output_root))
- try:
- inventory = _audit_package_items(collection.items)
- inventory_by_path = {str(item["path"]): item for item in inventory}
- package_items = collection.items
- package_inventory = inventory
- package_inventory_by_path = inventory_by_path
- large_files: list[dict[str, object]] = []
- chunk_root: Path | None = None
- single_path = staging / f"{package_name}.zip"
- single_info = _write_volume(
- single_path,
- run_id=run_id,
- package_name=package_name,
- number=1,
- count=1,
- items=list(sorted(collection.items, key=_item_sort_key)),
- inventory_by_path=inventory_by_path,
- )
- if single_path.stat().st_size < max_zip_bytes:
- volume_infos = [single_info]
- groups = [list(sorted(collection.items, key=_item_sort_key))]
- else:
- single_path.unlink()
- package_items, large_files, chunk_root = _prepare_large_file_chunks(
- staging,
- run_id=run_id,
- package_name=package_name,
- items=collection.items,
- inventory_by_path=inventory_by_path,
- target_zip_bytes=target_zip_bytes,
- max_zip_bytes=max_zip_bytes,
- )
- package_inventory = _audit_package_items(package_items)
- package_inventory_by_path = {
- str(item["path"]): item for item in package_inventory
- }
- initial_groups = _partition_items(
- package_items,
- target_zip_bytes=target_zip_bytes,
- )
- groups = _split_oversized_groups(
- staging,
- run_id=run_id,
- package_name=package_name,
- groups=initial_groups,
- inventory_by_path=package_inventory_by_path,
- target_zip_bytes=target_zip_bytes,
- max_zip_bytes=max_zip_bytes,
- )
- volume_infos = []
- count = len(groups)
- for number, group in enumerate(groups, start=1):
- category = group[0].category if len({item.category for item in group}) == 1 else "mixed"
- safe_category = re.sub(r"[^a-z0-9]+", "-", category.casefold()).strip("-") or "data"
- volume_path = staging / f"{package_name}.part{number:03d}-{safe_category}.zip"
- volume_info = _write_volume(
- volume_path,
- run_id=run_id,
- package_name=package_name,
- number=number,
- count=count,
- items=group,
- inventory_by_path=package_inventory_by_path,
- )
- if volume_path.stat().st_size >= max_zip_bytes:
- raise PackagingError(f"ZIP volume exceeds strict size limit: {volume_path.name}")
- volume_infos.append(volume_info)
- volume_by_path: dict[str, str] = {}
- for volume_info, group in zip(volume_infos, groups, strict=True):
- for item in group:
- volume_by_path[item.candidate.relative] = str(volume_info["file"])
- large_paths = {str(item["path"]) for item in large_files}
- indexed_files = [
- {**item, "volume": volume_by_path[str(item["path"])]}
- for item in inventory
- if str(item["path"]) not in large_paths
- ]
- for large_file in large_files:
- for chunk in large_file["chunks"]:
- chunk["volume"] = volume_by_path[str(chunk["path"])]
- index = {
- "schema": "cpld-agent-analysis-index-v1",
- "run_id": run_id,
- "created_at_utc": _utc_now(),
- "package_name": package_name,
- "status": collection.status,
- "max_zip_bytes": max_zip_bytes,
- "target_zip_bytes": target_zip_bytes,
- "sources": list(collection.sources),
- "git": list(collection.git),
- "warnings": list(collection.warnings),
- "excluded": list(collection.excluded),
- "volumes": volume_infos,
- "files": indexed_files,
- "large_files": large_files,
- }
- if large_files:
- (staging / "reassemble_large_files.py").write_text(
- REASSEMBLER_SCRIPT,
- 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}")
- _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)
- except BaseException:
- if os.path.lexists(staging):
- shutil.rmtree(staging, ignore_errors=True)
- raise
- return {
- "status": collection.status,
- "mode": "package",
- "run_id": run_id,
- "output_dir": str(final_dir),
- "volumes": volume_infos,
- "included_file_count": len(inventory),
- "included_bytes": sum(int(item["size"]) for item in inventory),
- "excluded_entry_count": len(collection.excluded),
- "warning_count": len(collection.warnings),
- }
- 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,
- ) -> AnalysisCollection:
- warnings = (*collection.warnings, *preparation.warnings)
- excluded = sorted(
- (*collection.excluded, *preparation.excluded),
- key=lambda item: handoff.windows_collision_key(item["path"]),
- )
- return AnalysisCollection(
- status="pass_with_warnings" if warnings else "pass",
- items=preparation.items,
- excluded=tuple(excluded),
- warnings=tuple(warnings),
- sources=collection.sources,
- git=collection.git,
- source_snapshots=collection.source_snapshots,
- )
- def explain_analysis_path(
- path: Path,
- *,
- repo_root: Path,
- config: HandoffConfig,
- ) -> dict[str, object]:
- root = repo_root.resolve(strict=True)
- requested = path if path.is_absolute() else root / path
- target = requested.expanduser().resolve(strict=False)
- resolved_sources, warnings = resolve_external_sources(config.external_sources)
- source_roots: list[tuple[str, str, Path, Path | None]] = [
- ("workspace-current", "core", root, None)
- ]
- for source in resolved_sources:
- if source.kind == "file":
- source_roots.append((source.id, source.category, source.path.parent, source.path))
- else:
- source_roots.append((source.id, source.category, source.path, None))
- matches: list[tuple[int, str, str, Path, Path | None]] = []
- for source_id, category, source_root, exact_file in source_roots:
- if exact_file is not None and target != exact_file:
- continue
- try:
- target.relative_to(source_root)
- except ValueError:
- continue
- matches.append((len(source_root.parts), source_id, category, source_root, exact_file))
- if not matches:
- raise PackagingError("path is outside the current repository and configured external sources")
- _, source_id, category, source_root, exact_file = max(matches, key=lambda item: item[0])
- relative = exact_file.name if exact_file is not None else target.relative_to(source_root).as_posix()
- if not relative:
- relative = "."
- is_dir = target.is_dir()
- context = handoff.load_scan_context(source_root)
- reason = analysis_exclusion_reason(
- relative,
- is_dir=is_dir,
- context=context,
- extra_exclusions=config.extra_exclusions,
- )
- archive_relative = (
- f"workspace-current/{relative}"
- if source_id == "workspace-current"
- else f"external/{source_id}/{relative}"
- )
- return {
- "status": "pass_with_warnings" if warnings else "pass",
- "mode": "explain",
- "path": str(target),
- "exists": target.exists(),
- "source_id": source_id,
- "category": category,
- "source_relative_path": relative,
- "archive_path": f"CPLD/{archive_relative}",
- "decision": "exclude" if reason else "include",
- "reason": reason,
- "content_scan": "not_run",
- "warnings": warnings,
- }
- def audit_analysis_collection(collection: AnalysisCollection) -> dict[str, object]:
- inventory = _audit_package_items(collection.items)
- inventory_by_path = {str(item["path"]): item for item in inventory}
- _assert_items_unchanged(collection.items, inventory_by_path)
- return {
- "status": collection.status,
- "mode": "audit_only",
- "included_file_count": len(inventory),
- "included_bytes": sum(int(item["size"]) for item in inventory),
- "excluded_entry_count": len(collection.excluded),
- "warning_count": len(collection.warnings),
- "warnings": list(collection.warnings),
- "sources": list(collection.sources),
- "git": list(collection.git),
- }
- def _validate_output_root(
- output_root: Path,
- *,
- repo_root: Path,
- config: HandoffConfig,
- ) -> Path:
- output = output_root.expanduser().resolve(strict=False)
- source_paths = [repo_root.resolve(strict=True)]
- resolved_sources, _ = resolve_external_sources(config.external_sources)
- source_paths.extend(source.path if source.kind != "file" else source.path.parent for source in resolved_sources)
- for source_path in source_paths:
- try:
- output.relative_to(source_path)
- except ValueError:
- continue
- raise PackagingError(f"output directory must be outside every packaged source root: {source_path}")
- return output
- def build_parser() -> argparse.ArgumentParser:
- parser = argparse.ArgumentParser(description=__doc__)
- 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
- def main(argv: list[str] | None = None) -> int:
- args = build_parser().parse_args(argv)
- 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=source_root)
- if args.explain is not None:
- payload = explain_analysis_path(args.explain, repo_root=source_root, config=config)
- else:
- seven_zip = find_7z()
- _validate_package_name(package_name)
- 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=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=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:
- 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
- print(json.dumps(payload, ensure_ascii=False, indent=2))
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|