diffctx 2.0.0rc0__cp311-abi3-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
diffctx/__init__.py ADDED
@@ -0,0 +1,91 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+ from ._app import run
8
+ from ._native import build_diff_context
9
+ from .ignore import get_ignore_specs, get_whitelist_spec
10
+ from .tree import TreeBuildContext, build_tree
11
+ from .version import __version__
12
+ from .writer import tree_to_string
13
+
14
+ logging.getLogger("diffctx").addHandler(logging.NullHandler())
15
+
16
+ __all__ = [
17
+ "__version__",
18
+ "build_diff_context",
19
+ "map_directory",
20
+ "run",
21
+ "to_json",
22
+ "to_markdown",
23
+ "to_text",
24
+ "to_yaml",
25
+ ]
26
+
27
+
28
+ def _root_display_name(user_path: str | Path, resolved: Path) -> str:
29
+ original_name = Path(user_path).name
30
+ if original_name:
31
+ return original_name
32
+ return str(resolved)
33
+
34
+
35
+ def _resolve_path_if_exists(path: str | Path | None, label: str) -> Path | None:
36
+ if path is None:
37
+ return None
38
+ resolved = Path(path).resolve()
39
+ if not resolved.is_file():
40
+ raise FileNotFoundError(f"{label} '{path}' does not exist")
41
+ return resolved
42
+
43
+
44
+ def map_directory(
45
+ path: str | Path,
46
+ *,
47
+ max_depth: int | None = None,
48
+ no_content: bool = False,
49
+ max_file_bytes: int | None = None,
50
+ ignore_file: str | Path | None = None,
51
+ no_default_ignores: bool = False,
52
+ whitelist_file: str | Path | None = None,
53
+ ) -> dict[str, Any]:
54
+ root_dir = Path(path).resolve()
55
+ if not root_dir.is_dir():
56
+ raise ValueError(f"'{path}' is not a directory")
57
+
58
+ ignore_path = _resolve_path_if_exists(ignore_file, "Ignore file")
59
+ whitelist_path = _resolve_path_if_exists(whitelist_file, "Whitelist file")
60
+
61
+ ctx = TreeBuildContext(
62
+ base_dir=root_dir,
63
+ combined_spec=get_ignore_specs(root_dir, ignore_path, no_default_ignores, None),
64
+ output_file=None,
65
+ max_depth=max_depth,
66
+ no_content=no_content,
67
+ max_file_bytes=max_file_bytes,
68
+ whitelist_spec=get_whitelist_spec(whitelist_path, root_dir),
69
+ )
70
+
71
+ return {
72
+ "name": _root_display_name(path, root_dir),
73
+ "type": "directory",
74
+ "children": build_tree(root_dir, ctx),
75
+ }
76
+
77
+
78
+ def to_yaml(tree: dict[str, Any]) -> str:
79
+ return tree_to_string(tree, "yaml")
80
+
81
+
82
+ def to_json(tree: dict[str, Any]) -> str:
83
+ return tree_to_string(tree, "json")
84
+
85
+
86
+ def to_text(tree: dict[str, Any]) -> str:
87
+ return tree_to_string(tree, "txt")
88
+
89
+
90
+ def to_markdown(tree: dict[str, Any]) -> str:
91
+ return tree_to_string(tree, "md")
diffctx/__main__.py ADDED
@@ -0,0 +1,17 @@
1
+ import logging
2
+ import sys
3
+
4
+ # Initialize logging early to avoid Python 3.13 issues with argparse
5
+ # This ensures logging's internal state is fully set up before argparse runs
6
+ try:
7
+ logging.basicConfig(format="%(levelname)s: %(message)s", level=logging.ERROR)
8
+ # Force initialization of logging internals
9
+ logging.getLogger()
10
+ except (OSError, ValueError) as e:
11
+ # If logging initialization fails, warn but continue
12
+ print(f"Warning: logging init failed: {e}", file=sys.stderr)
13
+
14
+ from diffctx.cli import main
15
+
16
+ if __name__ == "__main__":
17
+ main()
diffctx/_app.py ADDED
@@ -0,0 +1,559 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import logging
5
+ import os
6
+ import re
7
+ import signal
8
+ import subprocess
9
+ import sys
10
+ from pathlib import Path
11
+ from typing import TYPE_CHECKING, Any, NoReturn, TypeVar
12
+
13
+ if TYPE_CHECKING:
14
+ from collections.abc import Callable
15
+
16
+ from ._diffctx import BUILD_LABEL as _BUILD_LABEL
17
+
18
+ if TYPE_CHECKING:
19
+ from ._native.pipeline import Delivery
20
+ from .cli import ParsedArgs
21
+
22
+ _T = TypeVar("_T")
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+ _EXIT_RUNTIME = 1
27
+ _EXIT_USAGE = 2
28
+ _EXIT_ENVIRONMENT = 3
29
+ _EXIT_TIMEOUT = 124
30
+ _EXIT_INTERRUPTED = 130
31
+ _EXIT_BROKEN_PIPE = 141
32
+
33
+
34
+ def _configure_windows_utf8() -> None:
35
+ reconfigure = getattr(sys.stdout, "reconfigure", None)
36
+ if reconfigure is None:
37
+ return
38
+ try:
39
+ reconfigure(encoding="utf-8")
40
+ except (AttributeError, ValueError, OSError):
41
+ pass
42
+
43
+
44
+ def _ensure_git_repo(root_dir: Path, prog: str, flag: str) -> None:
45
+ def refuse(why: str) -> NoReturn:
46
+ print(f"{prog}: {flag} {why}", file=sys.stderr)
47
+ sys.exit(_EXIT_ENVIRONMENT)
48
+
49
+ try:
50
+ result = subprocess.run(
51
+ ["git", "rev-parse", "--is-bare-repository"],
52
+ stdin=subprocess.DEVNULL,
53
+ cwd=str(root_dir),
54
+ capture_output=True,
55
+ text=True,
56
+ encoding="utf-8",
57
+ errors="replace",
58
+ check=False,
59
+ )
60
+ except OSError as exc:
61
+ refuse(f"requires git to be installed and on PATH ({exc}); install git or run without {flag}.")
62
+ if result.returncode != 0:
63
+ fatal = next((line for line in result.stderr.splitlines() if line.startswith("fatal:")), "")
64
+ if fatal and "not a git repository" not in fatal:
65
+ refuse(f"cannot run git in {root_dir}: {fatal}")
66
+ refuse(f"requires a git repository (cwd: {root_dir}); run it inside a git working tree.")
67
+ if result.stdout.strip() == "true":
68
+ refuse(f"requires a working tree (bare repository: {root_dir}); clone it with a working tree or run without {flag}.")
69
+
70
+ head_result = subprocess.run(
71
+ ["git", "rev-parse", "--verify", "-q", "HEAD"],
72
+ stdin=subprocess.DEVNULL,
73
+ cwd=str(root_dir),
74
+ stdout=subprocess.DEVNULL,
75
+ stderr=subprocess.DEVNULL,
76
+ check=False,
77
+ )
78
+ if head_result.returncode != 0:
79
+ refuse(
80
+ "requires at least one commit (no HEAD in this repository yet); "
81
+ f"commit first, or run without {flag} to map the working tree."
82
+ )
83
+
84
+
85
+ def _log_latency(latency: dict[str, Any] | None) -> None:
86
+ # Telemetry rides beside the artifact, never inside it: the native binary
87
+ # never renders it and `--budget` bounds the document alone.
88
+ if latency:
89
+ logger.info("latency (ms): %s", ", ".join(f"{key}={value}" for key, value in latency.items()))
90
+
91
+
92
+ def _say(notes: list[tuple[str, str]], quiet: bool, prog: str) -> None:
93
+ # What to say, and what is empty, partial or redacted, is the engine's
94
+ # (`diffctx::delivery`); the door only names itself and honours `-q`.
95
+ for kind, text in notes:
96
+ if kind == "warning":
97
+ print(f"{prog}: {text}", file=sys.stderr)
98
+ elif not quiet:
99
+ print(f"{prog}: {text}" if kind == "detail" else text, file=sys.stderr)
100
+
101
+
102
+ _WATCHDOG_GRACE_SECONDS = 30
103
+
104
+
105
+ def _call_with_wall_clock_deadline(build: Callable[[], _T], timeout_seconds: int, prog: str) -> _T:
106
+ # The Rust extension releases the GIL but offers no cancellation, so a
107
+ # pathological repo can hang far past any per-phase git timeout (#70).
108
+ # Mirror the standalone binary's watchdog: run the pipeline on a worker
109
+ # thread and hard-exit 124 on deadline — the runaway worker cannot be
110
+ # stopped, so finalizers must not run (os._exit, not sys.exit).
111
+ import threading
112
+
113
+ outcome: list[Any] = []
114
+
115
+ def worker() -> None:
116
+ try:
117
+ outcome.append(("ok", build()))
118
+ except Exception as exc: # KeyboardInterrupt/SystemExit stay on the main thread
119
+ outcome.append(("err", exc))
120
+
121
+ # The engine stops cooperatively at the deadline and returns a partial
122
+ # answer; the watchdog waits a grace period beyond it, as the binary
123
+ # does, or it would kill exactly the answer the deadline exists to save
124
+ # (#382). The test variable replaces the whole wait.
125
+ grace = _WATCHDOG_GRACE_SECONDS
126
+ wait = timeout_seconds + grace
127
+ override = os.environ.get("DIFFCTX_TEST_WATCHDOG_GRACE_SECS")
128
+ # ASCII digits within u64, as the binary reads it: "²" and "+5" are no
129
+ # override, and a wait past threading.TIMEOUT_MAX is clamped, not raised.
130
+ if override and override.isascii() and override.isdigit() and int(override) < 2**64:
131
+ grace = wait = min(int(override), int(threading.TIMEOUT_MAX))
132
+ thread = threading.Thread(target=worker, name="diffctx-pipeline", daemon=True)
133
+ thread.start()
134
+ thread.join(wait)
135
+ if thread.is_alive():
136
+ print(
137
+ f"{prog}: pipeline exceeded {timeout_seconds}s wall-clock deadline and did not stop "
138
+ f"cooperatively within {grace}s more; aborting before OOM/SIGKILL. Narrow the review "
139
+ "with an explicit '--diff <from>..<to>' range, run on a smaller subtree, or raise '--timeout'.",
140
+ file=sys.stderr,
141
+ )
142
+ sys.stderr.flush()
143
+ sys.stdout.flush()
144
+ os._exit(_EXIT_TIMEOUT)
145
+ if not outcome:
146
+ raise RuntimeError("pipeline worker terminated unexpectedly")
147
+ status, value = outcome[0]
148
+ if status == "err":
149
+ raise value
150
+ return value # type: ignore[no-any-return]
151
+
152
+
153
+ def _diff_scope(args: ParsedArgs) -> list[str]:
154
+ return [str(p.resolve()) for p in [*(args.extra_dirs or []), *(args.extra_files or [])]]
155
+
156
+
157
+ def _root_display_name(root_dir: Any) -> str:
158
+ from .tree import printable
159
+
160
+ name = root_dir.name
161
+ return printable(name if name else str(root_dir))
162
+
163
+
164
+ _LARGE_OUTPUT_WARN_BYTES = 10 * 1024 * 1024
165
+ # A bare `diffctx` with no path argument at all is the most common "just try
166
+ # it" first invocation — and the easiest to run somewhere unintended (e.g.
167
+ # /tmp, $HOME). Use a much lower bar for that specific case; an explicit path
168
+ # argument is a stronger signal the user knows what they're pointing at (#87).
169
+ _LARGE_OUTPUT_WARN_BYTES_NO_EXPLICIT_PATH = 1 * 1024 * 1024
170
+
171
+
172
+ def _warn_if_output_oversized(output_content: str, args: ParsedArgs) -> None:
173
+ if args.no_content:
174
+ return
175
+ threshold = _LARGE_OUTPUT_WARN_BYTES_NO_EXPLICIT_PATH if args.no_explicit_paths else _LARGE_OUTPUT_WARN_BYTES
176
+ size_bytes = len(output_content.encode("utf-8"))
177
+ if size_bytes < threshold:
178
+ return
179
+ mb = size_bytes / (1024 * 1024)
180
+ print(
181
+ f"Warning: output is {mb:.1f} MB. For large repos try --no-content (structure only), "
182
+ f"--diff RANGE (relevance-ranked context), or --save / -o FILE to keep it off the terminal.",
183
+ file=sys.stderr,
184
+ )
185
+
186
+
187
+ def _build_file_node(file_path: Path, base_dir: Path, no_content: bool, max_file_bytes: int | None) -> dict[str, Any]:
188
+ from .tree import printable, set_file_content
189
+
190
+ try:
191
+ rel = file_path.relative_to(base_dir).as_posix()
192
+ except ValueError:
193
+ try:
194
+ rel = file_path.relative_to(Path.cwd()).as_posix()
195
+ except ValueError:
196
+ rel = file_path.name
197
+ node: dict[str, Any] = {"name": printable(rel), "type": "file"}
198
+ if no_content:
199
+ return node
200
+ set_file_content(node, file_path, max_file_bytes)
201
+ return node
202
+
203
+
204
+ def _build_single_dir_tree(root_dir: Path, args: ParsedArgs) -> dict[str, Any]:
205
+ from .ignore import get_ignore_specs, get_whitelist_spec
206
+ from .tree import TreeBuildContext, build_tree
207
+
208
+ ctx = TreeBuildContext(
209
+ base_dir=root_dir,
210
+ combined_spec=get_ignore_specs(
211
+ root_dir, args.ignore_file, args.no_default_ignores, args.output_file, no_ignores=args.no_ignores
212
+ ),
213
+ output_file=args.output_file,
214
+ max_depth=args.max_depth,
215
+ no_content=args.no_content,
216
+ max_file_bytes=args.max_file_bytes,
217
+ whitelist_spec=get_whitelist_spec(args.whitelist_file, root_dir),
218
+ )
219
+ return {
220
+ "name": _root_display_name(root_dir),
221
+ "type": "directory",
222
+ "children": build_tree(root_dir, ctx),
223
+ }
224
+
225
+
226
+ def _build_standard_tree(args: ParsedArgs) -> dict[str, Any]:
227
+ if not args.extra_dirs and not args.extra_files:
228
+ return _build_single_dir_tree(args.root_dir, args)
229
+
230
+ children: list[dict[str, Any]] = []
231
+
232
+ for d in args.extra_dirs or []:
233
+ children.append(_build_single_dir_tree(d, args))
234
+
235
+ base = args.root_dir
236
+ for f in args.extra_files or []:
237
+ children.append(_build_file_node(f, base, args.no_content, args.max_file_bytes))
238
+
239
+ if len(children) == 1:
240
+ return children[0]
241
+
242
+ # Several directories have no single real parent, so "." names the
243
+ # synthetic root honestly. Files alone DO have one — the common parent the
244
+ # CLI rooted them at — and the tree says so.
245
+ name = "." if args.extra_dirs else _root_display_name(args.root_dir)
246
+ return {"name": name, "type": "directory", "children": children}
247
+
248
+
249
+ def _handle_clipboard(output_content: str, args: ParsedArgs, prog: str) -> bool:
250
+ from .clipboard import ClipboardError, copy_to_clipboard
251
+
252
+ if not args.copy:
253
+ return False
254
+ try:
255
+ copy_to_clipboard(output_content)
256
+ if not args.quiet:
257
+ print("Copied to clipboard", file=sys.stderr)
258
+ return True
259
+ except ClipboardError as exc:
260
+ print(f"{prog}: warning: clipboard unavailable ({exc}); writing to stdout instead", file=sys.stderr)
261
+ return False
262
+
263
+
264
+ def _handle_output_file(output_content: str, args: ParsedArgs, prog: str) -> None:
265
+ from .writer import write_string_to_file
266
+
267
+ if not args.output_file:
268
+ return
269
+ try:
270
+ write_string_to_file(output_content, args.output_file, args.output_format)
271
+ if not args.quiet:
272
+ print(f"Saved to {args.output_file}", file=sys.stderr)
273
+ except IsADirectoryError:
274
+ print(f"{prog}: error: '{args.output_file}' is a directory, not a file", file=sys.stderr)
275
+ sys.exit(_EXIT_RUNTIME)
276
+ except OSError as exc:
277
+ print(f"{prog}: error: cannot write '{args.output_file}': {exc.strerror or exc}", file=sys.stderr)
278
+ sys.exit(_EXIT_RUNTIME)
279
+
280
+
281
+ def _is_graph_mode(args: ParsedArgs) -> bool:
282
+ return args.command == "graph"
283
+
284
+
285
+ _ARCHITECTURAL_EDGE_TYPES: frozenset[str] = frozenset(
286
+ {"semantic", "structural", "key_match", "config_generic", "document", "sibling", "test_edge", "history"}
287
+ )
288
+
289
+
290
+ def _format_cycles(level: str, pg: Any) -> str:
291
+ from ._native.graph_analytics import detect_cycles
292
+
293
+ cycles = detect_cycles(pg, level=level, edge_types={"semantic"})
294
+ if not cycles:
295
+ return "No dependency cycles detected."
296
+ lines = [f"{len(cycles)} dependency cycle(s) detected:\n"]
297
+ for i, cycle in enumerate(cycles, 1):
298
+ chain = " → ".join(cycle) + " → " + cycle[0]
299
+ lines.append(f" Cycle {i} ({len(cycle)} nodes): {chain}")
300
+ return "\n".join(lines)
301
+
302
+
303
+ def _format_hotspots(pg: Any) -> str:
304
+ from ._native.graph_analytics import hotspots
305
+
306
+ hot = hotspots(pg, top=10, edge_types=set(_ARCHITECTURAL_EDGE_TYPES))
307
+ lines = [f"Top {len(hot)} hotspots:"]
308
+ for rank, (name, score, details) in enumerate(hot, 1):
309
+ lines.append(f" {rank}. {name} score={score:.4f} out_degree={details['out_degree']} churn={details['churn']}")
310
+ return "\n".join(lines)
311
+
312
+
313
+ def _format_metrics(level: str, pg: Any) -> str:
314
+ from ._native.graph_analytics import coupling_metrics
315
+
316
+ metrics = coupling_metrics(pg, level=level, edge_types=set(_ARCHITECTURAL_EDGE_TYPES))
317
+ lines = [f"Module metrics ({level} level):"]
318
+ for m in metrics:
319
+ flags = ""
320
+ if m.coupling > 0.7:
321
+ flags = " ⚠ high coupling"
322
+ elif m.cohesion > 0.8:
323
+ flags = " ✓ high cohesion"
324
+ lines.append(
325
+ f" {m.name} cohesion={m.cohesion:.3f} coupling={m.coupling:.3f} "
326
+ f"instability={m.instability:.3f} fan_in={m.fan_in} fan_out={m.fan_out}{flags}"
327
+ )
328
+ return "\n".join(lines)
329
+
330
+
331
+ def _graph_to_string(pg: Any, fmt: str, level: str = "directory", export_level: str = "fragment") -> str:
332
+ from ._native.graph_analytics import quotient_graph, to_mermaid
333
+ from ._native.graph_export import graph_to_graphml_string, graph_to_json_string
334
+
335
+ if fmt == "graphml":
336
+ return graph_to_graphml_string(pg, level=export_level)
337
+ if fmt == "mermaid":
338
+ qg = quotient_graph(pg, level=level)
339
+ return to_mermaid(qg)
340
+ return graph_to_json_string(pg, level=export_level)
341
+
342
+
343
+ def _handle_graph_mode(args: ParsedArgs) -> str:
344
+ from ._native.graph_export import graph_summary
345
+ from ._native.project_graph import build_project_graph
346
+
347
+ assert args.graph is not None
348
+ g = args.graph
349
+
350
+ pg = build_project_graph(
351
+ args.root_dir,
352
+ ignore_file=args.ignore_file,
353
+ no_default_ignores=args.no_default_ignores,
354
+ whitelist_file=args.whitelist_file,
355
+ )
356
+
357
+ parts: list[str] = []
358
+
359
+ if g.summary:
360
+ parts.extend(
361
+ [
362
+ graph_summary(pg, level=g.export_level),
363
+ _format_cycles(g.level, pg),
364
+ _format_hotspots(pg),
365
+ _format_metrics(g.level, pg),
366
+ ]
367
+ )
368
+
369
+ if not g.summary:
370
+ parts.append(_graph_to_string(pg, g.format, level=g.level, export_level=g.export_level))
371
+
372
+ return "\n".join(parts) + "\n" if parts else ""
373
+
374
+
375
+ def _run(argv: list[str] | None = None, *, prog: str = "diffctx", version: str = _BUILD_LABEL) -> None:
376
+ from .cli import parse_args
377
+ from .logger import setup_logging
378
+ from .tokens import print_token_summary
379
+ from .writer import tree_to_string, write_string_to_file
380
+
381
+ args = parse_args(argv, prog=prog, version=version)
382
+ setup_logging(args.verbosity)
383
+
384
+ def write_via_writer(content: str) -> None:
385
+ write_string_to_file(content, None, args.output_format)
386
+
387
+ if _is_graph_mode(args):
388
+ output_content = _handle_graph_mode(args)
389
+ if not args.quiet:
390
+ print_token_summary(output_content)
391
+ _emit(output_content, args, prog, write_stdout=sys.stdout.write)
392
+ return
393
+
394
+ if args.diff_range or (args.symbol and args.mode == "impact"):
395
+ delivery = _deliver_diff_mode(args, prog)
396
+ _log_latency(delivery.latency)
397
+ _say(delivery.notes, args.quiet, prog)
398
+ _emit(delivery.text, args, prog, write_stdout=write_via_writer)
399
+ if delivery.exit:
400
+ sys.exit(delivery.exit)
401
+ return
402
+
403
+ directory_tree = _build_standard_tree(args)
404
+ output_content = tree_to_string(directory_tree, args.output_format)
405
+ if not args.quiet:
406
+ print_token_summary(output_content)
407
+ _report_redactions(directory_tree, prog)
408
+ _warn_if_output_oversized(output_content, args)
409
+ _emit(output_content, args, prog, write_stdout=write_via_writer)
410
+
411
+
412
+ def _report_redactions(tree: dict[str, Any], prog: str) -> None:
413
+ from .tree import redaction_total
414
+
415
+ count = redaction_total(tree)
416
+ if count:
417
+ print(f"{prog}: {count} credential-shaped string(s) redacted", file=sys.stderr)
418
+
419
+
420
+ def _deliver_diff_mode(args: ParsedArgs, prog: str) -> Delivery:
421
+ """Every diff mode is one engine call: this door parses, waits for the
422
+ deadline and prints; what the answer says and how the run ends is decided
423
+ in `diffctx::delivery`."""
424
+ from ._native import deliver
425
+
426
+ _ensure_git_repo(args.root_dir, prog, "--symbol" if args.symbol else "--diff")
427
+ try:
428
+ return _call_with_wall_clock_deadline(
429
+ lambda: deliver(
430
+ root_dir=args.root_dir,
431
+ mode=args.mode,
432
+ diff_range=args.diff_range or "HEAD",
433
+ symbol=args.symbol,
434
+ paths=_diff_scope(args),
435
+ budget=args.budget,
436
+ format=args.output_format,
437
+ unfold=args.unfold,
438
+ alpha=args.alpha,
439
+ tau=args.tau,
440
+ scoring_mode=args.scoring,
441
+ timeout=args.timeout,
442
+ no_content=args.no_content,
443
+ full=args.full_diff,
444
+ with_raw_diff=args.with_raw_diff,
445
+ overflow=args.overflow,
446
+ ),
447
+ args.timeout,
448
+ prog,
449
+ )
450
+ except ValueError as exc:
451
+ if args.mode != "impact":
452
+ raise
453
+ # The engine refuses a `--symbol` that cannot name a definition.
454
+ print(f"{prog}: usage error: {exc}", file=sys.stderr)
455
+ sys.exit(_EXIT_USAGE)
456
+
457
+
458
+ def _emit(
459
+ output_content: str,
460
+ args: ParsedArgs,
461
+ prog: str,
462
+ *,
463
+ write_stdout: Callable[[str], object],
464
+ ) -> None:
465
+ clipboard_ok = _handle_clipboard(output_content, args, prog)
466
+ _handle_output_file(output_content, args, prog)
467
+ should_write_stdout = args.force_stdout or not args.copy or not clipboard_ok
468
+ if not args.output_file and should_write_stdout:
469
+ write_stdout(output_content)
470
+
471
+
472
+ _KNOWN_RUNTIME_ERRORS: tuple[type[BaseException], ...] = (
473
+ FileNotFoundError,
474
+ IsADirectoryError,
475
+ NotADirectoryError,
476
+ PermissionError,
477
+ RuntimeError,
478
+ )
479
+
480
+
481
+ def _format_runtime_error(exc: BaseException) -> str:
482
+ msg = str(exc).strip()
483
+ return msg if msg else exc.__class__.__name__
484
+
485
+
486
+ def _format_git_error(exc: BaseException) -> str:
487
+ msg = _format_runtime_error(exc)
488
+ if "unknown revision" in msg and "shallow clone" not in msg:
489
+ match = re.search(r"ambiguous argument '([^']+)'|unknown revision '([^']+)'", msg)
490
+ if match:
491
+ return f"unknown git revision '{match.group(1) or match.group(2)}'; check refs with: git log --oneline"
492
+ return f"git error: {msg}" if not msg.startswith("git ") else msg
493
+
494
+
495
+ def _is_usage_git_error(exc: BaseException) -> bool:
496
+ return _format_runtime_error(exc).startswith(("invalid duration", "invalid path"))
497
+
498
+
499
+ def _handle_unexpected_exception(exc: BaseException, prog: str = "diffctx") -> int:
500
+ logger.debug("internal error", exc_info=exc)
501
+ print(
502
+ f"{prog}: internal error: {exc.__class__.__name__}: {_format_runtime_error(exc)}",
503
+ file=sys.stderr,
504
+ )
505
+ return _EXIT_RUNTIME
506
+
507
+
508
+ # Never raised: the type an `except` clause gets when the extension is missing.
509
+ class _NativeUnavailableError(Exception):
510
+ pass
511
+
512
+
513
+ def _git_error_type() -> type[BaseException]:
514
+ # Evaluated while an exception is already propagating: if the native
515
+ # module is what failed, importing it here would raise INSIDE the except
516
+ # clause and bury the original error under an ImportError. A type nothing
517
+ # raises matches nothing and lets the real error reach the handlers below.
518
+ try:
519
+ from ._native import GitError
520
+ except ImportError:
521
+ return _NativeUnavailableError
522
+ return GitError
523
+
524
+
525
+ def run(argv: list[str] | None = None, *, prog: str | None = None, version: str | None = None) -> None:
526
+ prog = prog or "diffctx"
527
+ version = version or _BUILD_LABEL
528
+ _configure_windows_utf8()
529
+ try:
530
+ _run(argv, prog=prog, version=version)
531
+ except SystemExit:
532
+ raise
533
+ except KeyboardInterrupt:
534
+ signal.signal(signal.SIGINT, signal.SIG_IGN)
535
+ print("\nInterrupted", file=sys.stderr)
536
+ sys.exit(_EXIT_INTERRUPTED)
537
+ except BrokenPipeError:
538
+ sys.exit(_EXIT_BROKEN_PIPE)
539
+ except _git_error_type() as exc:
540
+ print(f"{prog}: {_format_git_error(exc)}", file=sys.stderr)
541
+ sys.exit(_EXIT_USAGE if _is_usage_git_error(exc) else _EXIT_ENVIRONMENT)
542
+ except argparse.ArgumentError as exc:
543
+ print(f"{prog}: usage error: {_format_runtime_error(exc)}", file=sys.stderr)
544
+ sys.exit(_EXIT_USAGE)
545
+ except _KNOWN_RUNTIME_ERRORS as exc:
546
+ print(f"{prog}: {_format_runtime_error(exc)}", file=sys.stderr)
547
+ sys.exit(_EXIT_RUNTIME)
548
+ except LookupError as exc:
549
+ # The engine refuses a name nothing defines with a bare LookupError;
550
+ # a KeyError or IndexError is a bug here and keeps its traceback.
551
+ if type(exc) is not LookupError:
552
+ sys.exit(_handle_unexpected_exception(exc, prog=prog))
553
+ print(f"{prog}: {_format_runtime_error(exc)}", file=sys.stderr)
554
+ sys.exit(_EXIT_RUNTIME)
555
+ except OSError as exc:
556
+ print(f"{prog}: {_format_runtime_error(exc)}", file=sys.stderr)
557
+ sys.exit(_EXIT_RUNTIME)
558
+ except Exception as exc:
559
+ sys.exit(_handle_unexpected_exception(exc, prog=prog))
diffctx/_diffctx.pyd ADDED
@@ -0,0 +1,4 @@
1
+ [diffend] Oversized file quarantined before diffing.
2
+ name: diffctx/_diffctx.pyd
3
+ size: 90022400 bytes
4
+ sha256: 2b8136b9226afdd03414bdb79147305598e3b7663a8c869ec4f777af50cbaa5f