"""Classify a directory as a plan unit, a reusable module, or unknown.""" from __future__ import annotations from enum import Enum from pathlib import Path import hcl2 class DirKind(str, Enum): PLAN_UNIT = "plan_unit" MODULE = "module" UNKNOWN = "unknown" def _has_backend_block(tf_path: Path) -> bool: try: with tf_path.open() as fh: parsed = hcl2.load(fh) except Exception: return False for block in parsed.get("terraform", []): if isinstance(block, dict) and "backend" in block: return True return False def classify_dir(repo_root: Path | str, rel_dir: str) -> DirKind: root = Path(repo_root) full = root / rel_dir if not full.is_dir(): raise FileNotFoundError(full) if (full / "terragrunt.hcl").is_file(): return DirKind.PLAN_UNIT tf_files = sorted(full.glob("*.tf")) + sorted(full.glob("*.tf.json")) if not tf_files: return DirKind.UNKNOWN for tf in tf_files: if tf.suffix == ".tf" and _has_backend_block(tf): return DirKind.PLAN_UNIT return DirKind.MODULE