|
| 1 | +"""``apm deps why <pkg>`` -- explain why a package is installed. |
| 2 | +
|
| 3 | +Inverts the lockfile dependency graph from a target package back to one or |
| 4 | +more direct dependencies that pulled it in. The lockfile is the source of |
| 5 | +truth -- no remote calls. |
| 6 | +
|
| 7 | +Output formats: |
| 8 | +
|
| 9 | +* Default: a plain-text indented tree (ASCII ``+--``), one chain per |
| 10 | + direct dependency that transitively required the target. Rich is |
| 11 | + intentionally not used here -- a list of N short root-to-leaf chains |
| 12 | + is not a single tree, and ``rich.tree`` would imply a hierarchy that |
| 13 | + does not exist. |
| 14 | +* ``--json``: a machine-readable JSON document on stdout. |
| 15 | +
|
| 16 | +Exit codes: |
| 17 | +
|
| 18 | +* ``0`` -- target found and explained. |
| 19 | +* ``1`` -- package not installed or query ambiguous. |
| 20 | +* ``2`` -- no lockfile / project misconfiguration. |
| 21 | +""" |
| 22 | + |
| 23 | +from __future__ import annotations |
| 24 | + |
| 25 | +import json |
| 26 | +import sys |
| 27 | + |
| 28 | +import click |
| 29 | + |
| 30 | +from ...core.command_logger import CommandLogger |
| 31 | +from ...core.scope import InstallScope, get_apm_dir |
| 32 | +from ...deps.lockfile import LockFile, get_lockfile_path, migrate_lockfile_if_needed |
| 33 | +from ...deps.why_walker import ( |
| 34 | + AmbiguousPackageError, |
| 35 | + PackageNotInstalledError, |
| 36 | + WhyEdge, |
| 37 | + WhyResult, |
| 38 | + compute_why, |
| 39 | + resolve_package_query, |
| 40 | +) |
| 41 | +from ...utils.console import set_console_stderr |
| 42 | + |
| 43 | +# Exit codes |
| 44 | +_EXIT_OK = 0 |
| 45 | +_EXIT_NOT_FOUND = 1 |
| 46 | +_EXIT_NO_LOCKFILE = 2 |
| 47 | + |
| 48 | + |
| 49 | +# --------------------------------------------------------------------------- |
| 50 | +# Formatting helpers |
| 51 | +# --------------------------------------------------------------------------- |
| 52 | + |
| 53 | + |
| 54 | +def _format_dep_label(dep) -> str: |
| 55 | + """Render ``repo_url@version`` for the human output header.""" |
| 56 | + version = ( |
| 57 | + dep.version |
| 58 | + or (dep.resolved_commit[:7] if dep.resolved_commit else None) |
| 59 | + or dep.resolved_ref |
| 60 | + or "unknown" |
| 61 | + ) |
| 62 | + return f"{dep.repo_url}@{version}" |
| 63 | + |
| 64 | + |
| 65 | +def _edge_annotation(edge: WhyEdge, is_root: bool) -> str: |
| 66 | + """Render the bracketed annotation for a single chain edge. |
| 67 | +
|
| 68 | + Mirrors the design-pack convention: |
| 69 | + * Root edge (direct dep): ``[constraint: ^1.2.0, declared in apm.yml]`` |
| 70 | + or ``[declared in apm.yml]`` when constraint is unknown. |
| 71 | + * Inner edges: ``[constraint: ^1.4.0]`` or empty. |
| 72 | + """ |
| 73 | + parts: list[str] = [] |
| 74 | + if edge.constraint: |
| 75 | + parts.append(f"constraint: {edge.constraint}") |
| 76 | + if is_root: |
| 77 | + parts.append("declared in apm.yml") |
| 78 | + if not parts: |
| 79 | + return "" |
| 80 | + return f" [{', '.join(parts)}]" |
| 81 | + |
| 82 | + |
| 83 | +def _render_human(result: WhyResult) -> str: |
| 84 | + """Render the human-readable explanation as a single string.""" |
| 85 | + target = result.target |
| 86 | + header_kind = "direct dependency" if result.is_direct else "transitive" |
| 87 | + lines: list[str] = [f"[i] {_format_dep_label(target)} ({header_kind})", ""] |
| 88 | + |
| 89 | + if result.is_direct: |
| 90 | + # Single trivial chain. |
| 91 | + edge = result.paths[0].chain[0] |
| 92 | + annotation = _edge_annotation(edge, is_root=True) |
| 93 | + lines.append(f" {target.repo_url}{annotation}") |
| 94 | + return "\n".join(lines) |
| 95 | + |
| 96 | + for path in result.paths: |
| 97 | + for idx, edge in enumerate(path.chain): |
| 98 | + # Root is determined by the absence of a recorded parent, NOT by |
| 99 | + # position in the chain: compute_why() may emit truncated chains |
| 100 | + # (missing parent in lockfile, cycle break, depth-cap hit) where |
| 101 | + # the first element is NOT a real root. See PR #1495 review. |
| 102 | + is_root = edge.parent_key is None |
| 103 | + annotation = _edge_annotation(edge, is_root=is_root) |
| 104 | + prefix = " " if idx == 0 else (" " + " " * (idx - 1) + "+-- ") |
| 105 | + lines.append(f"{prefix}{edge.child_key}{annotation}") |
| 106 | + lines.append("") # blank line between chains |
| 107 | + # Caller uses click.echo() which appends its own newline; do not add one |
| 108 | + # here or we emit a trailing blank line. |
| 109 | + return "\n".join(lines).rstrip() |
| 110 | + |
| 111 | + |
| 112 | +def _render_json(result: WhyResult) -> str: |
| 113 | + """Render the JSON explanation.""" |
| 114 | + target = result.target |
| 115 | + payload = { |
| 116 | + "package": { |
| 117 | + "repo_url": target.repo_url, |
| 118 | + "version": target.version or target.resolved_ref or target.resolved_commit, |
| 119 | + "source": target.source or "git", |
| 120 | + "is_direct": result.is_direct, |
| 121 | + }, |
| 122 | + "paths": [ |
| 123 | + { |
| 124 | + "chain": [ |
| 125 | + { |
| 126 | + "repo_url": edge.child_key, |
| 127 | + "constraint": edge.constraint, |
| 128 | + # Directness is recorded by the walker as a missing |
| 129 | + # parent_key, not by position: a corrupt or |
| 130 | + # depth-capped chain may not start at a true root. |
| 131 | + "is_direct": edge.parent_key is None, |
| 132 | + } |
| 133 | + for edge in path.chain |
| 134 | + ] |
| 135 | + } |
| 136 | + for path in result.paths |
| 137 | + ], |
| 138 | + } |
| 139 | + return json.dumps(payload, indent=2, sort_keys=True) |
| 140 | + |
| 141 | + |
| 142 | +# --------------------------------------------------------------------------- |
| 143 | +# Lockfile loading |
| 144 | +# --------------------------------------------------------------------------- |
| 145 | + |
| 146 | + |
| 147 | +def _load_lockfile(apm_dir, logger: CommandLogger) -> LockFile | None: |
| 148 | + """Load the lockfile for *apm_dir*; emit an error and return ``None`` |
| 149 | + when missing or unreadable. Callers translate that into exit code 2. |
| 150 | + """ |
| 151 | + migrate_lockfile_if_needed(apm_dir) |
| 152 | + lockfile_path = get_lockfile_path(apm_dir) |
| 153 | + if not lockfile_path.exists(): |
| 154 | + logger.error("no apm.lock.yaml found in this project.") |
| 155 | + logger.info("Hint: run 'apm install' first.") |
| 156 | + return None |
| 157 | + lockfile = LockFile.read(lockfile_path) |
| 158 | + if lockfile is None: |
| 159 | + logger.error(f"could not read lockfile at {lockfile_path}") |
| 160 | + return None |
| 161 | + return lockfile |
| 162 | + |
| 163 | + |
| 164 | +# --------------------------------------------------------------------------- |
| 165 | +# CLI entry point |
| 166 | +# --------------------------------------------------------------------------- |
| 167 | + |
| 168 | + |
| 169 | +_HELP = ( |
| 170 | + "Explain why a package is installed by walking the lockfile back to " |
| 171 | + "one or more direct dependencies that pulled it in.\n\n" |
| 172 | + "Examples:\n" |
| 173 | + " apm deps why shared-utils\n" |
| 174 | + " apm deps why acme-org/shared-utils --json\n" |
| 175 | + " apm deps why shared-utils --global" |
| 176 | +) |
| 177 | + |
| 178 | + |
| 179 | +@click.command(name="why", help=_HELP) |
| 180 | +@click.argument("package", required=True) |
| 181 | +@click.option( |
| 182 | + "--global", |
| 183 | + "-g", |
| 184 | + "global_", |
| 185 | + is_flag=True, |
| 186 | + default=False, |
| 187 | + help="Resolve against the user-scope lockfile (~/.apm/apm.lock.yaml).", |
| 188 | +) |
| 189 | +@click.option( |
| 190 | + "--json", |
| 191 | + "as_json", |
| 192 | + is_flag=True, |
| 193 | + default=False, |
| 194 | + help="Emit machine-readable JSON to stdout.", |
| 195 | +) |
| 196 | +def why(package: str, global_: bool, as_json: bool) -> None: |
| 197 | + """Entry point for ``apm deps why <pkg>``.""" |
| 198 | + # Stream discipline: under --json, route ALL human-facing output to |
| 199 | + # stderr so that downstream tools (jq, scripts) can consume stdout |
| 200 | + # as a clean JSON document. Mirrors the convention established by |
| 201 | + # `apm pack --json` (commands/pack.py) and by npm / yarn / cargo. |
| 202 | + if as_json: |
| 203 | + set_console_stderr(True) |
| 204 | + |
| 205 | + logger = CommandLogger("deps-why") |
| 206 | + scope = InstallScope.USER if global_ else InstallScope.PROJECT |
| 207 | + apm_dir = get_apm_dir(scope) |
| 208 | + |
| 209 | + lockfile = _load_lockfile(apm_dir, logger) |
| 210 | + if lockfile is None: |
| 211 | + if as_json: |
| 212 | + click.echo(json.dumps({"error": "no_lockfile"}), err=True) |
| 213 | + sys.exit(_EXIT_NO_LOCKFILE) |
| 214 | + |
| 215 | + try: |
| 216 | + target = resolve_package_query(lockfile, package) |
| 217 | + except AmbiguousPackageError as exc: |
| 218 | + if as_json: |
| 219 | + click.echo( |
| 220 | + json.dumps({"error": "ambiguous", "query": exc.query, "matches": exc.matches}), |
| 221 | + err=True, |
| 222 | + ) |
| 223 | + else: |
| 224 | + logger.error(f"'{exc.query}' matches multiple packages:") |
| 225 | + for match in exc.matches: |
| 226 | + click.echo(f" - {match}", err=True) |
| 227 | + logger.info("Hint: use the full owner/repo form.") |
| 228 | + sys.exit(_EXIT_NOT_FOUND) |
| 229 | + except PackageNotInstalledError as exc: |
| 230 | + if as_json: |
| 231 | + click.echo( |
| 232 | + json.dumps({"error": "not_installed", "query": exc.query}), |
| 233 | + err=True, |
| 234 | + ) |
| 235 | + else: |
| 236 | + logger.error(f"'{exc.query}' is not installed (not in apm.lock.yaml).") |
| 237 | + logger.info("Hint: run 'apm deps list' to see installed packages.") |
| 238 | + sys.exit(_EXIT_NOT_FOUND) |
| 239 | + |
| 240 | + result = compute_why(lockfile, target) |
| 241 | + |
| 242 | + if as_json: |
| 243 | + click.echo(_render_json(result)) |
| 244 | + else: |
| 245 | + click.echo(_render_human(result)) |
| 246 | + |
| 247 | + sys.exit(_EXIT_OK) |
0 commit comments