exclusion_packager.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. #!/usr/bin/env python3
  2. """Deterministic exclusion-based packaging engine for Prod2U canonical packaging.
  3. Enforces:
  4. - Candidates = Included ∪ Excluded (strictly disjoint partition)
  5. - Every excluded file records path, type, reason, and size
  6. - Unknown files default to included or explicit alert (never silently dropped)
  7. - DEFLATE level 9
  8. """
  9. from __future__ import annotations
  10. import fnmatch
  11. import hashlib
  12. import json
  13. from pathlib import Path, PurePosixPath
  14. from typing import Callable, Iterable
  15. def sha256_bytes(data: bytes) -> str:
  16. return hashlib.sha256(data).hexdigest()
  17. def sha256_file(path: Path) -> str:
  18. h = hashlib.sha256()
  19. with path.open("rb") as f:
  20. for chunk in iter(lambda: f.read(1024 * 1024), b""):
  21. h.update(chunk)
  22. return h.hexdigest()
  23. def scan_candidate_universe(
  24. root: Path,
  25. extra_files: dict[str, Path] | None = None,
  26. ) -> dict[str, dict]:
  27. """Scan all candidate files in the workspace (excluding .git internal database).
  28. Returns a dict mapping relative POSIX path to metadata:
  29. {"path": rel, "size": size, "abs_path": Path}
  30. """
  31. root = Path(root).resolve()
  32. universe: dict[str, dict] = {}
  33. for p in sorted(root.rglob("*")):
  34. if p.is_file():
  35. parts = p.relative_to(root).parts
  36. # Exclude git internal database from candidate scan
  37. if any(part == ".git" for part in parts):
  38. continue
  39. rel = p.relative_to(root).as_posix()
  40. universe[rel] = {
  41. "path": rel,
  42. "size": p.stat().st_size,
  43. "abs_path": p,
  44. }
  45. if extra_files:
  46. for rel_name, abs_path in sorted(extra_files.items()):
  47. if abs_path.is_file():
  48. universe[rel_name] = {
  49. "path": rel_name,
  50. "size": abs_path.stat().st_size,
  51. "abs_path": abs_path,
  52. }
  53. return universe
  54. def classify_files(
  55. universe: dict[str, dict],
  56. rules: list[tuple[Callable[[str, dict], bool], str, str]],
  57. force_include: set[str] | None = None,
  58. ) -> tuple[dict[str, dict], list[dict]]:
  59. """Partition candidate universe into included files and excluded records.
  60. Each rule is a tuple: (predicate_fn, type_str, reason_str).
  61. Unknown files not matching any rule default to INCLUDED.
  62. """
  63. force_include = force_include or set()
  64. included: dict[str, dict] = {}
  65. exclusions: list[dict] = []
  66. for rel_path, item in sorted(universe.items()):
  67. if rel_path in force_include:
  68. included[rel_path] = item
  69. continue
  70. matched = False
  71. for predicate, type_str, reason_str in rules:
  72. if predicate(rel_path, item):
  73. exclusions.append({
  74. "path": rel_path,
  75. "type": type_str,
  76. "reason": reason_str,
  77. "size": item["size"],
  78. })
  79. matched = True
  80. break
  81. if not matched:
  82. # Unknown files default to included (never silently dropped)
  83. included[rel_path] = item
  84. verify_partition(universe, included, exclusions)
  85. return included, exclusions
  86. def verify_partition(
  87. universe: dict[str, dict],
  88. included: dict[str, dict],
  89. exclusions: list[dict],
  90. ) -> None:
  91. """Mechanically verify that Candidates = Included ∪ Excluded and Included ∩ Excluded = ∅."""
  92. universe_set = set(universe.keys())
  93. included_set = set(included.keys())
  94. excluded_set = {x["path"] for x in exclusions}
  95. overlap = included_set.intersection(excluded_set)
  96. if overlap:
  97. sample = sorted(overlap)[:5]
  98. raise ValueError(f"EXCLUSION_INCLUSION_OVERLAP: files present in both: {sample}")
  99. union = included_set.union(excluded_set)
  100. if union != universe_set:
  101. missing = universe_set - union
  102. extra = union - universe_set
  103. raise ValueError(f"EXCLUSION_PARTITION_MISMATCH: missing={sorted(missing)[:5]}, extra={sorted(extra)[:5]}")
  104. if len(included) + len(exclusions) != len(universe):
  105. raise ValueError("EXCLUSION_COUNT_MISMATCH")
  106. def create_exclusions_payload(
  107. universe: dict[str, dict],
  108. included: dict[str, dict],
  109. exclusions: list[dict],
  110. scope: str,
  111. ) -> dict:
  112. """Create EXCLUSIONS.json payload adhering to prod2u-package-exclusions-v2."""
  113. return {
  114. "schema": "prod2u-package-exclusions-v2",
  115. "scope": scope,
  116. "total_candidates": len(universe),
  117. "included_count": len(included),
  118. "excluded_count": len(exclusions),
  119. "exclusions": sorted(exclusions, key=lambda x: x["path"]),
  120. }
  121. def make_prefix_matcher(prefix: str) -> Callable[[str, dict], bool]:
  122. prefix = prefix.rstrip("/") + "/"
  123. return lambda rel, _item: rel.startswith(prefix)
  124. def make_pattern_matcher(pattern: str) -> Callable[[str, dict], bool]:
  125. return lambda rel, _item: fnmatch.fnmatch(rel, pattern) or fnmatch.fnmatch(PurePosixPath(rel).name, pattern)
  126. def get_standard_system_exclusion_rules() -> list[tuple[Callable[[str, dict], bool], str, str]]:
  127. """Common rules for caches, temporary outputs, editor state, and raw reference stores."""
  128. rules: list[tuple[Callable[[str, dict], bool], str, str]] = [
  129. # Python and pytest caches
  130. (lambda r, _: "__pycache__" in PurePosixPath(r).parts or r.endswith((".pyc", ".pyo")), "cache", "Python compiled bytecode"),
  131. (lambda r, _: ".pytest_cache" in PurePosixPath(r).parts, "cache", "pytest temporary runtime cache"),
  132. # Dist directory
  133. (make_prefix_matcher("dist"), "build-artifact", "Pre-existing built package archive in dist/"),
  134. # Editor / IDE metadata
  135. (lambda r, _: any(part in (".codebuddy", ".omo", ".vscode", ".idea") for part in PurePosixPath(r).parts) or r.endswith((".swp", "*~")), "editor-cache", "Local IDE or editor runtime state"),
  136. # Transient root logs
  137. (lambda r, _: PurePosixPath(r).parent == PurePosixPath(".") and (r.startswith("td_") and r.endswith((".log", ".logw"))), "tool-log", "Transient toolchain execution log in repo root"),
  138. # Heavy external reference assets
  139. (make_prefix_matcher("reference/original/board"), "raw-reference", "Binary PCB board database files stored in external reference repository"),
  140. (make_prefix_matcher("reference/original/schematics"), "raw-reference", "Raw schematic PDFs stored in external reference repository"),
  141. (make_prefix_matcher("reference/original/local_archives"), "raw-reference", "Raw local archive dump stored in external reference repository"),
  142. ]
  143. return rules
  144. def get_6400_v2_exclusion_rules(kind: str) -> list[tuple[Callable[[str, dict], bool], str, str]]:
  145. """Exclusion rules for 6400-v2 product packaging."""
  146. rules = get_standard_system_exclusion_rules()
  147. # Exclude other product (MRDIMM) files from 6400-v2 packages
  148. rules.extend([
  149. (lambda r, _: "identification" in PurePosixPath(r).parts or "identification" in PurePosixPath(r).name, "historical", "Retired 6400-identification profile artifact"),
  150. (lambda r, _: "sim-debug" in PurePosixPath(r).parts or "sim-debug" in PurePosixPath(r).name, "historical", "Retired 6400-sim-debug profile artifact"),
  151. (make_prefix_matcher("products/mrdimm-chamber"), "other-product", "MRDIMM chamber project definition"),
  152. (make_prefix_matcher("projects/mrdimm-chamber"), "other-product", "MRDIMM chamber project docs/specs"),
  153. (lambda r, _: "mrdimm" in PurePosixPath(r).name and not r.startswith("tests/unit/test_mrdimm_"), "other-product", "MRDIMM-specific tool or artifact"),
  154. (make_prefix_matcher("td/bitgen/prod2u_mrdimm"), "other-product", "MRDIMM bitgen tcl"),
  155. (make_prefix_matcher("td/phy/prod2u_mrdimm"), "other-product", "MRDIMM phy tcl"),
  156. (make_prefix_matcher("td/syn/prod2u_mrdimm"), "other-product", "MRDIMM syn tcl"),
  157. (make_prefix_matcher("constraints/prod2u_mrdimm"), "other-product", "MRDIMM constraints"),
  158. (make_prefix_matcher("generated/mrdimm"), "other-product", "MRDIMM generated contracts"),
  159. # Retired / superseded legacy directories
  160. (make_prefix_matcher("src/legacy"), "historical", "Retired legacy CPLD implementations"),
  161. (make_prefix_matcher("docs/historical"), "historical", "Superseded historical documentation"),
  162. ])
  163. if kind in ("firmware", "delivery"):
  164. # Firmware/Delivery release package excludes developer test suites, scripts, and documentation
  165. rules.extend([
  166. (make_prefix_matcher("tests"), "source-test", "Automated test suites excluded from binary firmware release"),
  167. (make_prefix_matcher("tools"), "source-tool", "Engineering tools excluded from binary firmware release"),
  168. (make_prefix_matcher("docs"), "documentation", "Developer documentation excluded from binary firmware release"),
  169. (make_prefix_matcher("containers"), "container", "Container environment recipes excluded from binary firmware release"),
  170. (make_prefix_matcher("reference"), "reference", "Reference files excluded from binary firmware release"),
  171. (lambda r, _: r in ("pyproject.toml", "RECOVERY_STATE.md", "TASK_PLAN.json", "RESULTS.json", ".gitattributes", ".gitignore"), "metadata", "Repo build metadata excluded from firmware release"),
  172. ])
  173. return rules