Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .claude/settings.local.json
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,9 @@
"PowerShell(.venv/Scripts/python -m pytest tests/dictionary/test_schema.py -x -q 2>&1 | Select-Object -Last 5)",
"PowerShell(.venv/Scripts/python -m pytest -q --tb=short 2>&1 | Select-Object -Last 5)",
"PowerShell(.venv/Scripts/python -m radon cc src/cifflow/dictionary/schema.py --show-complexity --min C 2>&1)",
"PowerShell(.venv/Scripts/python -m xenon src/ --max-average B --max-modules C --max-absolute D 2>&1)"
"PowerShell(.venv/Scripts/python -m xenon src/ --max-average B --max-modules C --max-absolute D 2>&1)",
"PowerShell(.venv/Scripts/python -m pytest -x -q --no-header 2>&1 | Select-Object -Last 5)",
"PowerShell(.venv/Scripts/ruff check src/cifflow/inspect/ 2>&1)"
]
}
}
31 changes: 27 additions & 4 deletions src/cifflow/inspect/_common.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Shared utilities for the inspect package."""

import pathlib
import sys
from typing import IO, TextIO, Union

_Source = Union[str, pathlib.Path, IO[str]]
Expand All @@ -19,10 +20,31 @@ def resolve_source(source: _Source) -> str:
return source.read()


# -- ANSI colours (suppressed when stdout is not a tty) -----------------------
# -- ANSI colours (suppressed when stdout is not a tty or VT is unavailable) --

def supports_colour(file: TextIO) -> bool:
return hasattr(file, 'isatty') and file.isatty()
"""Return True if *file* is a TTY that can render ANSI colour sequences."""
if not (hasattr(file, 'isatty') and file.isatty()):
return False
if sys.platform == 'win32':
try:
import ctypes
import ctypes.wintypes
std_handles = {0: -10, 1: -11, 2: -12}
handle_id = std_handles.get(file.fileno())
if handle_id is None:
# Non-standard fd (e.g. a pipe or test double) — trust isatty().
return True
kernel32 = ctypes.windll.kernel32
handle = kernel32.GetStdHandle(handle_id)
mode = ctypes.wintypes.DWORD()
if not kernel32.GetConsoleMode(handle, ctypes.byref(mode)):
return False
return bool(mode.value & 0x0004) # ENABLE_VIRTUAL_TERMINAL_PROCESSING
except Exception:
# fileno() unsupported or ctypes unavailable — trust isatty().
return True
return True


RESET = '\033[0m'
Expand All @@ -36,8 +58,9 @@ def supports_colour(file: TextIO) -> bool:
MAGENTA = '\033[35m'


def c(text: str, *codes: str, file: TextIO) -> str:
if not supports_colour(file):
def c(text: str, *codes: str, file: TextIO, use_colour: bool = True) -> str:
"""Return *text* wrapped in ANSI *codes*, or plain *text* if colour is off."""
if not use_colour or not supports_colour(file):
return text
return ''.join(codes) + text + RESET

Expand Down
33 changes: 24 additions & 9 deletions src/cifflow/inspect/_ingest.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ def inspect_ingest(
propagate_fk: bool = False,
dataset_id: str | None = None,
file: Optional[TextIO] = None,
use_colour: bool = True,
) -> list[TraceEvent]:
"""Run ingestion, capture events, and pretty-print a diagnostic trace.

Expand All @@ -68,6 +69,9 @@ def inspect_ingest(
Forwarded to ``ingest()``.
file:
Where to write the trace. Defaults to ``sys.stdout``.
use_colour:
If False, suppress all ANSI colour codes regardless of terminal type.
Default True.

Returns
-------
Expand All @@ -81,7 +85,7 @@ def inspect_ingest(

events: list[TraceEvent] = []

print(c('-- inspect_ingest --', BOLD, DIM, file=file), file=file)
print(c('-- inspect_ingest --', BOLD, DIM, file=file, use_colour=use_colour), file=file)

try:
_, ingest_errors = ingest(
Expand All @@ -102,29 +106,40 @@ def inspect_ingest(
errors_ev = [e for e in events if e.kind == 'error']

if warnings_ev:
print(c(f' {len(warnings_ev)} semantic warning(s):', YELLOW, file=file), file=file)
print(c(f' {len(warnings_ev)} semantic warning(s):', YELLOW,
file=file, use_colour=use_colour), file=file)
for ev in warnings_ev:
print(f' {c("~", YELLOW, file=file)} {ev.detail}', file=file)
print(f' {c("~", YELLOW, file=file, use_colour=use_colour)} {ev.detail}',
file=file)

if errors_ev:
print(c(f' {len(errors_ev)} error(s):', RED, BOLD, file=file), file=file)
print(c(f' {len(errors_ev)} error(s):', RED, BOLD,
file=file, use_colour=use_colour), file=file)
for ev in errors_ev:
print(f' {c("!", RED, file=file)} {ev.detail}', file=file)
print(f' {c("!", RED, file=file, use_colour=use_colour)} {ev.detail}',
file=file)

if not warnings_ev and not errors_ev:
print(c(' Ingestion completed with no warnings.', GREEN, file=file), file=file)
print(c(' Ingestion completed with no warnings.', GREEN,
file=file, use_colour=use_colour), file=file)

_print_trace_summary(events, file)
_print_trace_summary(events, file, use_colour=use_colour)
return events


def _print_trace_summary(events: list[TraceEvent], file: TextIO) -> None:
def _print_trace_summary(
events: list[TraceEvent],
file: TextIO,
*,
use_colour: bool = True,
) -> None:
"""Print the warning/error count footer."""
warnings = sum(1 for e in events if e.kind == 'warning')
errors = sum(1 for e in events if e.kind == 'error')
print(
c(
f' [{warnings} warning(s) {errors} error(s)]',
DIM, file=file,
DIM, file=file, use_colour=use_colour,
),
file=file,
)
Expand Down
27 changes: 18 additions & 9 deletions src/cifflow/inspect/_lexer.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ def inspect_lexer(
*,
version: Optional[CifVersion] = None,
file: TextIO = sys.stdout,
use_colour: bool = True,
) -> None:
"""Print the full token stream for *source* to *file*.

Expand All @@ -26,6 +27,9 @@ def inspect_lexer(
If None (default), auto-detected from the magic line.
file:
Output stream (default ``sys.stdout``).
use_colour:
If False, suppress all ANSI colour codes regardless of terminal type.
Default True.
"""
from cifflow import cifflow_core
from cifflow.parser.version import detect_version
Expand All @@ -43,44 +47,49 @@ def inspect_lexer(
if v_errors:
for ve in v_errors:
print(
c(f'[VERSION ERROR] line {ve.line}: {ve.message}', RED, BOLD, file=file),
c(f'[VERSION ERROR] line {ve.line}: {ve.message}', RED, BOLD,
file=file, use_colour=use_colour),
file=file,
)

tokens, detected_version = cifflow_core.lex_cif(source, mode)

ver_label = detected_version.value
print(
c(f'-- token stream (CIF {ver_label}) --', BOLD, DIM, file=file),
c(f'-- token stream (CIF {ver_label}) --', BOLD, DIM,
file=file, use_colour=use_colour),
file=file,
)
print(
c(
f"{'line':>5} {'col':>4} {'token_type':<10} {'value_type':<22} value",
DIM, file=file,
DIM, file=file, use_colour=use_colour,
),
file=file,
)
print(c('-' * 72, DIM, file=file), file=file)
print(c('-' * 72, DIM, file=file, use_colour=use_colour), file=file)

for tok in tokens:
vtype = tok['value_type'].value if tok['value_type'] is not None else ''
raw = repr(tok['value'])
if len(raw) > 50:
raw = raw[:47] + '…' + raw[-1]

line_part = c(f'{tok["line"]:>5} {tok["column"]:>4}', DIM, file=file)
type_part = c(f'{tok["token_type"].value:<10}', CYAN, file=file)
vtype_part = c(f'{vtype:<22}', BLUE, file=file)
val_part = c(raw, GREEN if tok['token_type'].value == 'value' else YELLOW, file=file)
line_part = c(f'{tok["line"]:>5} {tok["column"]:>4}', DIM,
file=file, use_colour=use_colour)
type_part = c(f'{tok["token_type"].value:<10}', CYAN,
file=file, use_colour=use_colour)
vtype_part = c(f'{vtype:<22}', BLUE, file=file, use_colour=use_colour)
val_part = c(raw, GREEN if tok['token_type'].value == 'value' else YELLOW,
file=file, use_colour=use_colour)

print(f' {line_part} {type_part} {vtype_part} {val_part}', file=file)

for err in tok['errors']:
print(
c(
f' ^ LEX ERROR col {err["column"]}: {err["message"]}',
RED, file=file,
RED, file=file, use_colour=use_colour,
),
file=file,
)
Expand Down
53 changes: 31 additions & 22 deletions src/cifflow/inspect/_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from cifflow.types import ParseError


def _print_namespace(ns, *, indent: int, file: TextIO) -> None:
def _print_namespace(ns, *, indent: int, file: TextIO, use_colour: bool) -> None:
"""Print tags and loops from a CifBlock or CifSaveFrame."""
pad = ' ' * indent

Expand Down Expand Up @@ -57,21 +57,23 @@ def _print_namespace(ns, *, indent: int, file: TextIO) -> None:
for ci, cell in enumerate(row_cells):
widths[ci] = max(widths[ci], len(cell))

rows_label = c(f'({row_count} rows)', DIM, file=file)
print(f'{pad}{c("loop_", CYAN, file=file)} {rows_label}', file=file)
rows_label = c(f'({row_count} rows)', DIM, file=file, use_colour=use_colour)
print(f'{pad}{c("loop_", CYAN, file=file, use_colour=use_colour)} {rows_label}',
file=file)

header = ' '.join(
c(t.ljust(widths[ci]), YELLOW, file=file)
c(t.ljust(widths[ci]), YELLOW, file=file, use_colour=use_colour)
for ci, t in enumerate(loop)
)
print(f'{pad} {header}', file=file)

for ri, row_cells in zip(show, cells):
if ri == -1:
print(f'{pad} {c("...", DIM, file=file)}', file=file)
print(f'{pad} {c("...", DIM, file=file, use_colour=use_colour)}',
file=file)
else:
row = ' '.join(
c(cell.ljust(widths[ci]), GREEN, file=file)
c(cell.ljust(widths[ci]), GREEN, file=file, use_colour=use_colour)
for ci, cell in enumerate(row_cells)
)
print(f'{pad} {row}', file=file)
Expand All @@ -82,33 +84,35 @@ def _print_namespace(ns, *, indent: int, file: TextIO) -> None:
values = ns[tag]
first = fmt_value(values[0])
n = len(values)
suffix = (' ' + c(f'({n} values)', DIM, file=file)) if n > 1 else ''
suffix = (' ' + c(f'({n} values)', DIM, file=file, use_colour=use_colour)) if n > 1 else ''
print(
f'{pad}{c(tag, YELLOW, file=file)} {c(first, GREEN, file=file)}{suffix}',
f'{pad}{c(tag, YELLOW, file=file, use_colour=use_colour)}'
f' {c(first, GREEN, file=file, use_colour=use_colour)}{suffix}',
file=file,
)
printed.add(tag)

if hasattr(ns, 'save_frames'):
for sf_name in ns.save_frames:
sf = ns[sf_name]
print(f'{pad}{c(f"save: {sf_name}", CYAN, file=file)}', file=file)
_print_namespace(sf, indent=indent + 1, file=file)
print(f'{pad}{c(f"save: {sf_name}", CYAN, file=file, use_colour=use_colour)}',
file=file)
_print_namespace(sf, indent=indent + 1, file=file, use_colour=use_colour)


def _print_model(cif, *, file: TextIO) -> None:
def _print_model(cif, *, file: TextIO, use_colour: bool) -> None:
"""Print a summary of a CifFile."""
print(c('-- CifFile summary --', BOLD, DIM, file=file), file=file)
print(c('-- CifFile summary --', BOLD, DIM, file=file, use_colour=use_colour), file=file)

if not cif.blocks:
print(c(' (no blocks)', DIM, file=file), file=file)
print(c(' (no blocks)', DIM, file=file, use_colour=use_colour), file=file)
print(file=file)
return

for block_name in cif.blocks:
block = cif[block_name]
print(c(f'block: {block_name}', BOLD, file=file), file=file)
_print_namespace(block, indent=1, file=file)
print(c(f'block: {block_name}', BOLD, file=file, use_colour=use_colour), file=file)
_print_namespace(block, indent=1, file=file, use_colour=use_colour)

print(file=file)

Expand All @@ -120,6 +124,7 @@ def inspect_model(
file: TextIO = sys.stdout,
show_values: bool = True,
show_tokens: bool = True,
use_colour: bool = True,
) -> None:
"""Run the full pipeline through the CIF model and print a summary.

Expand All @@ -138,29 +143,33 @@ def inspect_model(
Forward to ``ParseHandler``; set False to suppress ``add_value`` lines.
show_tokens:
If True (default), also print the lexer token stream before events.
use_colour:
If False, suppress all ANSI colour codes regardless of terminal type.
Default True.
"""
from cifflow.cifmodel.builder import CifBuilder

source = resolve_source(source)

if show_tokens:
inspect_lexer(source, file=file)
inspect_lexer(source, file=file, use_colour=use_colour)

errors: list[ParseError] = []
from cifflow import cifflow_core
builder = CifBuilder(on_error=errors.append, mode=mode)
handler = ParseHandler(builder, file=file, show_values=show_values)
handler = ParseHandler(builder, file=file, show_values=show_values, use_colour=use_colour)
cifflow_core.parse(source, handler)
print(file=file)

_print_model(builder.result, file=file)
_print_model(builder.result, file=file, use_colour=use_colour)

if errors:
print(c('-- errors --', BOLD, DIM, file=file), file=file)
print(c('-- errors --', BOLD, DIM, file=file, use_colour=use_colour), file=file)
for err in errors:
loc = c(f'line {err.line} col {err.column}', DIM, file=file)
kind = c(f'[{err.error_type.upper()}]', RED, BOLD, file=file)
loc = c(f'line {err.line} col {err.column}', DIM, file=file, use_colour=use_colour)
kind = c(f'[{err.error_type.upper()}]', RED, BOLD, file=file, use_colour=use_colour)
print(f' {kind} {loc} {err.message}', file=file)
if err.recovery_action:
print(f' {c("->", DIM, file=file)} {err.recovery_action}', file=file)
print(f' {c("->", DIM, file=file, use_colour=use_colour)} {err.recovery_action}',
file=file)
print(file=file)
Loading
Loading