|
| 1 | +"""Command-line interface for the Codetracer Python recorder.""" |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +import argparse |
| 5 | +import json |
| 6 | +import runpy |
| 7 | +import sys |
| 8 | +from dataclasses import dataclass |
| 9 | +from importlib import metadata |
| 10 | +from pathlib import Path |
| 11 | +from typing import Iterable, Sequence |
| 12 | + |
| 13 | +from . import flush, start, stop |
| 14 | +from .formats import DEFAULT_FORMAT, SUPPORTED_FORMATS, normalize_format |
| 15 | + |
| 16 | + |
| 17 | +@dataclass(frozen=True) |
| 18 | +class RecorderCLIConfig: |
| 19 | + """Resolved CLI options for a recorder invocation.""" |
| 20 | + |
| 21 | + trace_dir: Path |
| 22 | + format: str |
| 23 | + activation_path: Path |
| 24 | + script: Path |
| 25 | + script_args: list[str] |
| 26 | + |
| 27 | + |
| 28 | +def _default_trace_dir() -> Path: |
| 29 | + return Path.cwd() / "trace-out" |
| 30 | + |
| 31 | + |
| 32 | +def _parse_args(argv: Sequence[str]) -> RecorderCLIConfig: |
| 33 | + parser = argparse.ArgumentParser( |
| 34 | + prog="codetracer_python_recorder", |
| 35 | + description=( |
| 36 | + "Record a trace for a Python script using the Codetracer runtime tracer. " |
| 37 | + "All script arguments must be provided after the script path or a '--' separator." |
| 38 | + ), |
| 39 | + allow_abbrev=False, |
| 40 | + ) |
| 41 | + parser.add_argument( |
| 42 | + "--trace-dir", |
| 43 | + type=Path, |
| 44 | + default=_default_trace_dir(), |
| 45 | + help=( |
| 46 | + "Directory where trace artefacts will be written " |
| 47 | + "(defaults to %(default)s relative to the current working directory)." |
| 48 | + ), |
| 49 | + ) |
| 50 | + parser.add_argument( |
| 51 | + "--format", |
| 52 | + default=DEFAULT_FORMAT, |
| 53 | + help=( |
| 54 | + "Trace serialisation format. Supported values: " |
| 55 | + + ", ".join(sorted(SUPPORTED_FORMATS)) |
| 56 | + + f". Defaults to {DEFAULT_FORMAT}." |
| 57 | + ), |
| 58 | + ) |
| 59 | + parser.add_argument( |
| 60 | + "--activation-path", |
| 61 | + type=Path, |
| 62 | + help=( |
| 63 | + "Optional path used to gate tracing. When provided, tracing begins once the " |
| 64 | + "interpreter enters this file. Defaults to the target script." |
| 65 | + ), |
| 66 | + ) |
| 67 | + |
| 68 | + known, remainder = parser.parse_known_args(argv) |
| 69 | + pending: list[str] = list(remainder) |
| 70 | + if not pending: |
| 71 | + parser.error("missing script to execute") |
| 72 | + |
| 73 | + if pending[0] == "--": |
| 74 | + pending.pop(0) |
| 75 | + if not pending: |
| 76 | + parser.error("missing script path after '--'") |
| 77 | + |
| 78 | + script_token = pending[0] |
| 79 | + script_path = Path(script_token).expanduser() |
| 80 | + if not script_path.exists(): |
| 81 | + parser.error(f"script '{script_path}' does not exist") |
| 82 | + script_path = script_path.resolve() |
| 83 | + |
| 84 | + script_args = pending[1:] |
| 85 | + if script_args and script_args[0] == "--": |
| 86 | + script_args = script_args[1:] |
| 87 | + |
| 88 | + trace_dir = Path(known.trace_dir).expanduser().resolve() |
| 89 | + fmt = normalize_format(known.format) |
| 90 | + if fmt not in SUPPORTED_FORMATS: |
| 91 | + parser.error( |
| 92 | + f"unsupported trace format '{known.format}'. Expected one of: " |
| 93 | + + ", ".join(sorted(SUPPORTED_FORMATS)) |
| 94 | + ) |
| 95 | + |
| 96 | + activation_path = ( |
| 97 | + Path(known.activation_path).expanduser().resolve() |
| 98 | + if known.activation_path |
| 99 | + else script_path |
| 100 | + ) |
| 101 | + |
| 102 | + return RecorderCLIConfig( |
| 103 | + trace_dir=trace_dir, |
| 104 | + format=fmt, |
| 105 | + activation_path=activation_path, |
| 106 | + script=script_path, |
| 107 | + script_args=script_args, |
| 108 | + ) |
| 109 | + |
| 110 | + |
| 111 | +def _resolve_package_version() -> str | None: |
| 112 | + try: |
| 113 | + return metadata.version("codetracer-python-recorder") |
| 114 | + except metadata.PackageNotFoundError: # pragma: no cover - dev checkout |
| 115 | + return None |
| 116 | + |
| 117 | + |
| 118 | +def _serialise_metadata( |
| 119 | + trace_dir: Path, |
| 120 | + *, |
| 121 | + script: Path, |
| 122 | +) -> None: |
| 123 | + """Augment trace metadata with recorder-specific information.""" |
| 124 | + metadata_path = trace_dir / "trace_metadata.json" |
| 125 | + try: |
| 126 | + raw = metadata_path.read_text(encoding="utf-8") |
| 127 | + except FileNotFoundError: |
| 128 | + return |
| 129 | + |
| 130 | + try: |
| 131 | + payload = json.loads(raw) if raw else {} |
| 132 | + except json.JSONDecodeError: |
| 133 | + return |
| 134 | + |
| 135 | + recorder_block = payload.setdefault( |
| 136 | + "recorder", |
| 137 | + { |
| 138 | + "name": "codetracer_python_recorder", |
| 139 | + }, |
| 140 | + ) |
| 141 | + if isinstance(recorder_block, dict): |
| 142 | + recorder_block.setdefault("name", "codetracer_python_recorder") |
| 143 | + recorder_block["target_script"] = str(script) |
| 144 | + version = _resolve_package_version() |
| 145 | + if version: |
| 146 | + recorder_block["version"] = version |
| 147 | + else: |
| 148 | + # Unexpected schema — bail out without mutating further. |
| 149 | + return |
| 150 | + |
| 151 | + metadata_path.write_text(json.dumps(payload), encoding="utf-8") |
| 152 | + |
| 153 | + |
| 154 | +def main(argv: Iterable[str] | None = None) -> int: |
| 155 | + """Entry point for ``python -m codetracer_python_recorder``.""" |
| 156 | + if argv is None: |
| 157 | + argv = sys.argv[1:] |
| 158 | + |
| 159 | + try: |
| 160 | + config = _parse_args(list(argv)) |
| 161 | + except SystemExit: |
| 162 | + # argparse already printed a helpful message; propagate exit code. |
| 163 | + raise |
| 164 | + except Exception as exc: # pragma: no cover - defensive guardrail |
| 165 | + sys.stderr.write(f"Failed to parse arguments: {exc}\n") |
| 166 | + return 2 |
| 167 | + |
| 168 | + trace_dir = config.trace_dir |
| 169 | + script_path = config.script |
| 170 | + script_args = config.script_args |
| 171 | + |
| 172 | + old_argv = sys.argv |
| 173 | + sys.argv = [str(script_path)] + script_args |
| 174 | + |
| 175 | + try: |
| 176 | + start( |
| 177 | + trace_dir, |
| 178 | + format=config.format, |
| 179 | + start_on_enter=config.activation_path, |
| 180 | + ) |
| 181 | + except Exception as exc: |
| 182 | + sys.stderr.write(f"Failed to start Codetracer session: {exc}\n") |
| 183 | + sys.argv = old_argv |
| 184 | + return 1 |
| 185 | + |
| 186 | + exit_code: int | None = None |
| 187 | + try: |
| 188 | + try: |
| 189 | + runpy.run_path(str(script_path), run_name="__main__") |
| 190 | + except SystemExit as exc: |
| 191 | + exit_code = exc.code if isinstance(exc.code, int) else 1 |
| 192 | + else: |
| 193 | + exit_code = 0 |
| 194 | + finally: |
| 195 | + try: |
| 196 | + flush() |
| 197 | + finally: |
| 198 | + stop() |
| 199 | + sys.argv = old_argv |
| 200 | + |
| 201 | + _serialise_metadata(trace_dir, script=script_path) |
| 202 | + |
| 203 | + return exit_code if exit_code is not None else 0 |
| 204 | + |
| 205 | + |
| 206 | +__all__ = ("main", "RecorderCLIConfig") |
0 commit comments