| 1 |
"""Utilities for command line interface. |
| 2 |
|
| 3 |
Mostly contains converters, validators, console error helper and help formatters. |
| 4 |
|
| 5 |
""" |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
from glob import glob |
| 10 |
from pathlib import Path |
| 11 |
from typing import TYPE_CHECKING |
| 12 |
from typing import NamedTuple |
| 13 |
from typing import NoReturn |
| 14 |
import warnings |
| 15 |
|
| 16 |
from cyclopts.help import ColumnSpec |
| 17 |
from cyclopts.help import DefaultFormatter |
| 18 |
from cyclopts.help import HelpEntry |
| 19 |
from cyclopts.help import TableSpec |
| 20 |
from rich import box |
| 21 |
from rich.panel import Panel |
| 22 |
from rich.text import Text |
| 23 |
|
| 24 |
import pyvista as pv |
| 25 |
|
| 26 |
if TYPE_CHECKING: |
| 27 |
from collections.abc import Sequence |
| 28 |
|
| 29 |
from cyclopts import App |
| 30 |
from cyclopts import Token |
| 31 |
from rich.console import Console |
| 32 |
from rich.console import ConsoleOptions |
| 33 |
from rich.console import Group |
| 34 |
|
| 35 |
from pyvista import DataObject |
| 36 |
|
| 37 |
|
| 38 |
def default(entry: HelpEntry): # noqa: ANN202 |
| 39 |
return d if (d := entry.default) is not None else '-' |
| 40 |
|
| 41 |
|
| 42 |
def names(entry: HelpEntry): # noqa: ANN202 |
| 43 |
strings = (*entry.names, *entry.shorts) |
| 44 |
names = Text(' '.join(strings), style='cyan') |
| 45 |
return (Text('* ', style='red') + names) if entry.required else names |
| 46 |
|
| 47 |
|
| 48 |
def description(entry: HelpEntry): # noqa: ANN202 |
| 49 |
return entry.description |
| 50 |
|
| 51 |
|
| 52 |
class _PyvistaHelpFormatter(DefaultFormatter): |
| 53 |
def render_usage(self, console: Console, options: ConsoleOptions, usage: str) -> None: # noqa: ARG002 |
| 54 |
"""Render the usage line.""" |
| 55 |
if usage: # pragma: no branch |
| 56 |
console.print(usage) |
| 57 |
|
| 58 |
|
| 59 |
HELP_FORMATTER = _PyvistaHelpFormatter( |
| 60 |
table_spec=TableSpec(show_header=True), |
| 61 |
column_specs=( |
| 62 |
ColumnSpec( |
| 63 |
renderer=names, |
| 64 |
header='Option', |
| 65 |
header_style='bold purple', |
| 66 |
style='cyan', |
| 67 |
), |
| 68 |
ColumnSpec( |
| 69 |
renderer=default, |
| 70 |
header='Default', |
| 71 |
style='bold', |
| 72 |
header_style='bold purple', |
| 73 |
), |
| 74 |
ColumnSpec( |
| 75 |
renderer=description, |
| 76 |
header='Description', |
| 77 |
header_style='bold purple', |
| 78 |
), |
| 79 |
), |
| 80 |
) |
| 81 |
|
| 82 |
|
| 83 |
class _MeshAndPath(NamedTuple): |
| 84 |
mesh: DataObject |
| 85 |
path: Path |
| 86 |
|
| 87 |
|
| 88 |
def _console_error(*, app: App, message: str | Group, title: str = 'PyVista Error') -> NoReturn: |
| 89 |
panel = Panel( |
| 90 |
message, |
| 91 |
title=title, |
| 92 |
style='bold red', |
| 93 |
box=box.ROUNDED, |
| 94 |
expand=True, |
| 95 |
title_align='left', |
| 96 |
) |
| 97 |
app.error_console.print(panel) |
| 98 |
raise SystemExit(1) |
| 99 |
|
| 100 |
|
| 101 |
_GLOB_CHARS = ('*', '?', '[') |
| 102 |
|
| 103 |
|
| 104 |
def _expand_globs(values: list[str]) -> list[str]: |
| 105 |
"""Expand any glob patterns in-place, preserving order. |
| 106 |
|
| 107 |
Tokens without glob characters are kept as-is so non-existent literals still raise the |
| 108 |
"file not found" error downstream. Glob patterns with no matches are kept so they surface |
| 109 |
as the missing token in the same error. |
| 110 |
""" |
| 111 |
expanded: list[str] = [] |
| 112 |
for v in values: |
| 113 |
if any(c in v for c in _GLOB_CHARS): |
| 114 |
matches = sorted(glob(v, recursive=True)) # noqa: PTH207 |
| 115 |
if matches: |
| 116 |
expanded.extend(matches) |
| 117 |
else: |
| 118 |
expanded.append(v) |
| 119 |
else: |
| 120 |
expanded.append(v) |
| 121 |
return expanded |
| 122 |
|
| 123 |
|
| 124 |
def _check_paths_exist(paths: list[str]) -> list[Path]: |
| 125 |
"""Expand globs and verify each path exists. |
| 126 |
|
| 127 |
Raises a ``ValueError`` listing any missing paths. |
| 128 |
""" |
| 129 |
values = _expand_globs(paths) |
| 130 |
if not all((files := {v: Path(v).exists() for v in values}).values()): |
| 131 |
missing: str | list[str] = [k for k, v in files.items() if not v] |
| 132 |
n_missings = len(missing) |
| 133 |
|
| 134 |
literal_file = 'file' if n_missings == 1 else 'files' |
| 135 |
missing = missing[0] if n_missings == 1 else missing |
| 136 |
|
| 137 |
msg = f'{n_missings} {literal_file} not found: {missing}' |
| 138 |
raise ValueError(msg) |
| 139 |
return [Path(v) for v in values] |
| 140 |
|
| 141 |
|
| 142 |
_MULTIBLOCK_EXTS = frozenset({'.vtm', '.vtmb'}) |
| 143 |
|
| 144 |
|
| 145 |
def _filter_multiblock_children(paths: list[Path]) -> tuple[list[Path], list[Path]]: |
| 146 |
"""Drop paths that live inside a sibling sidecar directory of a MultiBlock parent. |
| 147 |
|
| 148 |
A ``.vtm`` / ``.vtmb`` file ``parent.vtm`` is paired on disk with a sidecar directory |
| 149 |
``parent/`` that holds the child blocks (e.g. ``parent/parent_0.vtp``). When both the |
| 150 |
parent and its sidecar children appear in the same input list, converting the children |
| 151 |
individually would duplicate work and break the 1:1 input/output mapping the user |
| 152 |
expects from a parent ``.vtm``. |
| 153 |
|
| 154 |
Children are filtered only when their parent is also in ``paths``. Standalone files |
| 155 |
inside an unrelated directory are left untouched. |
| 156 |
|
| 157 |
Returns a ``(kept, filtered)`` tuple; both lists preserve the input order. |
| 158 |
""" |
| 159 |
sidecar_dirs = [ |
| 160 |
(p.parent / p.stem).resolve() for p in paths if p.suffix.lower() in _MULTIBLOCK_EXTS |
| 161 |
] |
| 162 |
if not sidecar_dirs: |
| 163 |
return paths, [] |
| 164 |
|
| 165 |
kept: list[Path] = [] |
| 166 |
filtered: list[Path] = [] |
| 167 |
for p in paths: |
| 168 |
if p.suffix.lower() in _MULTIBLOCK_EXTS: |
| 169 |
kept.append(p) |
| 170 |
continue |
| 171 |
resolved_parents = set(p.resolve().parents) |
| 172 |
if any(sd in resolved_parents for sd in sidecar_dirs): |
| 173 |
filtered.append(p) |
| 174 |
else: |
| 175 |
kept.append(p) |
| 176 |
return kept, filtered |
| 177 |
|
| 178 |
|
| 179 |
def _load_paths(paths: list[str]) -> list[_MeshAndPath]: |
| 180 |
"""Expand globs, verify each path exists, and read it with ``pv.read``. |
| 181 |
|
| 182 |
Raises a ``ValueError`` if any path is missing or unreadable. |
| 183 |
""" |
| 184 |
checked = _check_paths_exist(paths) |
| 185 |
|
| 186 |
meshes_and_paths: list[_MeshAndPath] = [] |
| 187 |
not_readable: list[str] = [] |
| 188 |
for path in checked: |
| 189 |
try: |
| 190 |
with warnings.catch_warnings(): |
| 191 |
warnings.filterwarnings( |
| 192 |
'ignore', |
| 193 |
category=pv.InvalidMeshWarning, |
| 194 |
) |
| 195 |
mesh = pv.read(path) |
| 196 |
except Exception: # noqa: BLE001 |
| 197 |
not_readable.append(str(path)) |
| 198 |
else: |
| 199 |
meshes_and_paths.append(_MeshAndPath(mesh=mesh, path=path)) |
| 200 |
|
| 201 |
if len(not_readable) > 0: |
| 202 |
n = len(not_readable) |
| 203 |
literal_file = 'file' if n == 1 else 'files' |
| 204 |
msg = f'{n} {literal_file} not readable by PyVista:\n{not_readable}' |
| 205 |
raise ValueError(msg) |
| 206 |
|
| 207 |
return meshes_and_paths |
| 208 |
|
| 209 |
|
| 210 |
def _converter_files( |
| 211 |
type_: type, # noqa: ARG001 |
| 212 |
tokens: Sequence[Token], |
| 213 |
) -> list[_MeshAndPath]: |
| 214 |
"""Helper function used to read provided files. |
| 215 |
|
| 216 |
Raises errors if: |
| 217 |
|
| 218 |
- any file does not exits |
| 219 |
- any file is not readable with ``pv.read`` |
| 220 |
|
| 221 |
Glob patterns (``*``, ``?``, ``[...]``) are expanded before validation. |
| 222 |
|
| 223 |
""" # noqa: D401 |
| 224 |
return _load_paths([t.value for t in tokens]) |