Coverage for nexusLIMS/cli/__init__.py: 100%
26 statements
« prev ^ index » next coverage.py v7.11.3, created at 2026-03-24 05:23 +0000
« prev ^ index » next coverage.py v7.11.3, created at 2026-03-24 05:23 +0000
1"""CLI commands for NexusLIMS."""
3from __future__ import annotations
5import contextlib
6import re
7import sys
8from typing import TYPE_CHECKING
10if TYPE_CHECKING:
11 from collections.abc import Iterator
14def _format_version(prog_name: str) -> str:
15 """Format version string with release date if available."""
16 from nexusLIMS.version import __release_date__, __version__ # noqa: PLC0415
18 version_str = f"{prog_name} (NexusLIMS {__version__}"
19 if __release_date__:
20 version_str += f", released {__release_date__}"
21 version_str += ")"
22 return version_str
25@contextlib.contextmanager
26def handle_config_error() -> Iterator[None]:
27 """Context manager that catches config ``ValidationError`` and exits cleanly.
29 Instead of dumping a raw Pydantic traceback, this prints a short,
30 actionable message directing the user to ``nexuslims config edit``
31 and the online documentation.
33 Usage
34 -----
35 ::
37 with handle_config_error():
38 from nexusLIMS.config import settings
39 settings.NX_DATA_PATH # may raise ValidationError
40 """
41 import click # noqa: PLC0415
42 from pydantic import ValidationError # noqa: PLC0415
44 try:
45 yield
46 except ValidationError as exc:
47 from nexusLIMS.version import __version__ # noqa: PLC0415
49 doc_version = re.sub(r"\.dev.*$", "", __version__)
51 # Collect the missing / invalid field names from the Pydantic errors
52 fields = [e.get("loc", ("?",))[-1] for e in exc.errors()]
53 field_list = ", ".join(str(f) for f in fields)
55 # Build a compact, user-friendly message
56 lines = [
57 "Error: NexusLIMS configuration is incomplete or invalid.",
58 "",
59 f" Missing/invalid fields: {field_list}",
60 "",
61 "To fix this, either:",
62 "",
63 " 1. Run the interactive configurator:",
64 "",
65 " nexuslims config edit",
66 "",
67 " 2. Create a .env file manually (see documentation):",
68 "",
69 f" https://datasophos.github.io/NexusLIMS/{doc_version}"
70 "/user_guide/configuration.html",
71 "",
72 ]
74 click.echo("\n".join(lines), err=True)
75 sys.exit(1)