"""CLI commands for managing and processing iMednet data dictionaries."""
from __future__ import annotations
import argparse
import json
import re
import sys
from datetime import datetime
from pathlib import Path
from typing import Any
from defusedxml import ElementTree as DefusedET
from defusedxml.common import DefusedXmlException
from ...datadict import (
OdmArchive,
diff,
get_schema,
load_from_api,
load_from_cdisc_odm,
load_from_csv,
load_from_redcap,
load_odm_archive,
to_file,
to_json,
to_odm_file,
to_odm_xml,
validate,
validate_dataset_json,
validate_odm_xml,
)
from ...datadict.emit import ODM_NS
from ...datadict.models import DataDictionary
from ...sdk import ImednetSDK
from ..decorators import redact_cli_secrets, validate_cli_path_segment, with_sdk
from ..utils import (
UniqueStoreAction,
add_simulation_arg,
add_study_key_args,
flush_stdout,
get_sdk,
load_offline_schema,
print_error,
resolve_output_format,
resolve_study_key,
simulation_mode_context,
write_stdout,
)
__all__ = ["get_sdk", "setup_parser"]
def _handle_to_odm(args: argparse.Namespace) -> None:
"""Handle `imednet datadict to-odm` command."""
try:
file_path = Path(args.file)
source_obj: DataDictionary | OdmArchive
if file_path.is_file() and file_path.suffix.lower() == ".json":
input_text = file_path.read_text(encoding="utf-8")
raw_payload = json.loads(input_text)
if isinstance(raw_payload, dict) and "dataDictionary" in raw_payload:
source_obj = OdmArchive.model_validate(raw_payload)
else:
source_obj = load_offline_schema(args.file)
else:
source_obj = load_offline_schema(args.file)
except Exception as exc:
print_error(redact_cli_secrets(f"Error reading data dictionary from '{args.file}': {exc}"))
sys.exit(1)
if args.output:
try:
to_odm_file(source_obj, args.output, file_oid=getattr(args, "file_oid", None))
print(f"Successfully wrote CDISC ODM XML to '{args.output}'", file=sys.stderr)
except OSError as exc:
print_error(
redact_cli_secrets(f"Error writing CDISC ODM XML to '{args.output}': {exc}")
)
sys.exit(1)
except Exception as exc:
print_error(redact_cli_secrets(f"Error exporting to CDISC ODM XML: {exc}"))
sys.exit(1)
else:
try:
odm_xml = to_odm_xml(source_obj, file_oid=getattr(args, "file_oid", None))
except Exception as exc:
print_error(redact_cli_secrets(f"Error exporting to CDISC ODM XML: {exc}"))
sys.exit(1)
if write_stdout(odm_xml, end=""):
flush_stdout()
def _handle_from_csv(args: argparse.Namespace) -> None:
"""Handle `imednet datadict from-csv` command."""
try:
dd = load_from_csv(
args.path,
study_key=getattr(args, "study_key", None),
strict=args.strict,
no_raw_xml=args.no_raw_xml,
)
except Exception as exc:
print_error(redact_cli_secrets(f"Error loading from CSV: {exc}"))
sys.exit(1)
if args.output:
try:
to_file(dd, args.output)
print(f"Successfully wrote data dictionary to '{args.output}'", file=sys.stderr)
except OSError as exc:
print_error(
redact_cli_secrets(f"Error writing data dictionary to '{args.output}': {exc}")
)
sys.exit(1)
elif write_stdout(to_json(dd), end=""):
flush_stdout()
def _handle_from_odm(args: argparse.Namespace) -> None:
"""Handle `imednet datadict from-odm` command."""
if getattr(args, "archive", False):
try:
archive = load_odm_archive(
args.path,
study_key=getattr(args, "study_key", None),
strict=args.strict,
no_raw_xml=args.no_raw_xml,
)
except Exception as exc:
print_error(redact_cli_secrets(f"Error loading from CDISC ODM: {exc}"))
sys.exit(1)
archive_json = (
json.dumps(
archive.model_dump(mode="json", by_alias=True, exclude_none=True),
indent=2,
ensure_ascii=False,
)
+ "\n"
)
if args.output:
try:
out_path = Path(args.output)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(archive_json, encoding="utf-8")
print(f"Successfully wrote ODM archive JSON to '{args.output}'", file=sys.stderr)
except OSError as exc:
print_error(
redact_cli_secrets(f"Error writing ODM archive to '{args.output}': {exc}")
)
sys.exit(1)
elif write_stdout(archive_json, end=""):
flush_stdout()
return
try:
dd = load_from_cdisc_odm(
args.path,
study_key=getattr(args, "study_key", None),
strict=args.strict,
no_raw_xml=args.no_raw_xml,
)
except Exception as exc:
print_error(redact_cli_secrets(f"Error loading from CDISC ODM: {exc}"))
sys.exit(1)
if args.output:
try:
to_file(dd, args.output)
print(f"Successfully wrote data dictionary to '{args.output}'", file=sys.stderr)
except OSError as exc:
print_error(
redact_cli_secrets(f"Error writing data dictionary to '{args.output}': {exc}")
)
sys.exit(1)
elif write_stdout(to_json(dd), end=""):
flush_stdout()
def _handle_from_redcap(args: argparse.Namespace) -> None:
"""Handle `imednet datadict from-redcap` command."""
try:
dd = load_from_redcap(
Path(args.path),
study_key=getattr(args, "study_key", None),
strict=args.strict,
no_raw_xml=args.no_raw_xml,
)
except Exception as exc:
print_error(redact_cli_secrets(f"Error loading from REDCap: {exc}"))
sys.exit(1)
if args.output:
try:
to_file(dd, args.output)
print(f"Successfully wrote data dictionary to '{args.output}'", file=sys.stderr)
except OSError as exc:
print_error(
redact_cli_secrets(f"Error writing data dictionary to '{args.output}': {exc}")
)
sys.exit(1)
elif write_stdout(to_json(dd), end=""):
flush_stdout()
@with_sdk
def _from_api(
sdk: ImednetSDK,
study_key: str,
output: str | None = None,
no_raw_xml: bool = False,
) -> None:
"""Load data dictionary from live API with managed SDK lifecycle and error redaction."""
dd = load_from_api(sdk, study_key, no_raw_xml=no_raw_xml)
if output:
try:
to_file(dd, output)
print(f"Successfully wrote data dictionary to '{output}'", file=sys.stderr)
except OSError as exc:
print_error(redact_cli_secrets(f"Error writing data dictionary to '{output}': {exc}"))
sys.exit(1)
elif write_stdout(to_json(dd), end=""):
flush_stdout()
def _handle_from_api(args: argparse.Namespace) -> None:
"""Handle `imednet datadict from-api` command."""
parser: argparse.ArgumentParser | None = getattr(args, "_api_parser", None)
if parser is not None:
study_key = resolve_study_key(parser, args, required=True)
else:
study_key = getattr(args, "study_key", None)
assert study_key is not None
validate_cli_path_segment(study_key, name="study_key")
with simulation_mode_context(bool(getattr(args, "simulation", False))):
_from_api(
study_key=study_key,
output=args.output,
no_raw_xml=args.no_raw_xml,
)
def _emit_validate_json(file_path: str, errors: list[str]) -> None:
"""Emit dedicated single-document JSON validation payload on stdout."""
payload = {
"schemaVersion": "1.0",
"file": redact_cli_secrets(str(file_path)),
"valid": len(errors) == 0,
"error_count": len(errors),
"errors": [redact_cli_secrets(err) for err in errors],
}
if write_stdout(json.dumps(payload, indent=2) + "\n", end=""):
flush_stdout()
_CLI_ODM_ISO_DATETIME_RE = re.compile(
r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})?$"
)
_CLI_ODM_VERSIONS = frozenset({"1.2", "1.3", "1.3.1", "1.3.2"})
_CLI_ODM_FILE_TYPES = frozenset({"Snapshot", "Transactional"})
_CLI_ODM_YES_NO = frozenset({"Yes", "No"})
_CLI_ODM_COMPARATORS = frozenset({"LT", "LE", "GT", "GE", "EQ", "NE", "IN", "NOTIN"})
_CLI_ODM_SOFT_HARD = frozenset({"Soft", "Hard"})
_CLI_ARCHIVE_CONTAINERS = frozenset({"admindata", "referencedata", "clinicaldata", "association"})
def _is_valid_odm_iso_datetime(val: str) -> bool:
if not _CLI_ODM_ISO_DATETIME_RE.fullmatch(val):
return False
try:
datetime.fromisoformat(val)
except ValueError:
return False
return True
def _validate_odm_xml_cli_file(
file_path: Path,
raw_arg: str,
schema_dict: dict[str, Any] | None,
) -> list[str]:
"""Validate an ODM XML file safely via ``defusedxml``, XSD gates, and strict OID checks."""
if not file_path.is_file():
return [f"FileNotFoundError: Target file '{raw_arg}' does not exist"]
xml_bytes = file_path.read_bytes()
try:
root = DefusedET.fromstring(xml_bytes)
except DefusedXmlException as exc:
return [f"DefusedXmlException ({type(exc).__name__}): {exc}"]
except DefusedET.ParseError as exc:
return [f"Invalid XML syntax: {exc}"]
if root.tag not in {f"{{{ODM_NS}}}ODM", "ODM"}:
return [f"Root element must be ODM, got '{root.tag}'"]
odm_ver = (root.attrib.get("ODMVersion") or "").strip()
has_archive_containers = any(
child.tag.rsplit("}", 1)[-1].lower() in _CLI_ARCHIVE_CONTAINERS for child in root
)
errors: list[str] = []
if odm_ver == "1.3.2" or has_archive_containers:
errors.extend(validate_odm_xml(xml_bytes))
try:
archive = load_odm_archive(file_path, strict=True)
except Exception as exc:
errors.append(str(exc))
else:
errors.extend(validate(archive.data_dictionary, schema=schema_dict))
else:
if odm_ver and odm_ver not in _CLI_ODM_VERSIONS:
errors.append(f"Invalid ODM/@ODMVersion '{odm_ver}'")
if (ft := root.attrib.get("FileType")) is not None and ft not in _CLI_ODM_FILE_TYPES:
errors.append(f"Invalid ODM/@FileType '{ft}'")
if (arch := root.attrib.get("Archival")) is not None and arch not in _CLI_ODM_YES_NO:
errors.append(f"Invalid ODM/@Archival '{arch}'")
for dt_attr in ("CreationDateTime", "AsOfDateTime"):
if (dt_val := root.attrib.get(dt_attr)) is not None and not _is_valid_odm_iso_datetime(
dt_val
):
errors.append(f"Invalid ODM/@{dt_attr} '{dt_val}'; expected ISO-8601 datetime")
for elem in root.iter():
local_name = elem.tag.rsplit("}", 1)[-1]
for yn_attr in ("Mandatory", "Repeating", "IsReferenceData"):
if (
yn_val := elem.attrib.get(yn_attr)
) is not None and yn_val not in _CLI_ODM_YES_NO:
errors.append(f"Invalid <{local_name}>/@{yn_attr} '{yn_val}'")
if local_name == "RangeCheck":
if (
comp := elem.attrib.get("Comparator")
) is not None and comp not in _CLI_ODM_COMPARATORS:
errors.append(f"Invalid <RangeCheck>/@Comparator '{comp}'")
if (sh := elem.attrib.get("SoftHard")) is not None and sh not in _CLI_ODM_SOFT_HARD:
errors.append(f"Invalid <RangeCheck>/@SoftHard '{sh}'")
try:
dd = load_from_cdisc_odm(file_path, strict=True)
except Exception as exc:
errors.append(str(exc))
else:
errors.extend(validate(dd, schema=schema_dict))
deduped: list[str] = []
seen: set[str] = set()
for err in errors:
if err not in seen:
seen.add(err)
deduped.append(err)
return deduped
def _is_dataset_json_cli_file(file_path: Path) -> bool:
"""Return True when a ``.json`` path represents a CDISC Dataset-JSON document."""
is_dsj_suffix = file_path.name.lower().endswith(".dataset.json")
if not file_path.is_file():
return is_dsj_suffix
try:
parsed = json.loads(file_path.read_text(encoding="utf-8"))
except Exception:
return is_dsj_suffix
if not isinstance(parsed, dict):
return is_dsj_suffix
if "forms" in parsed or "dataDictionary" in parsed:
return False
if any(
key in parsed
for key in (
"datasetJSONVersion",
"datasetJSONCreationDateTime",
"itemGroupOID",
"clinicalData",
"referenceData",
)
):
return True
if "columns" in parsed and "rows" in parsed:
return True
return is_dsj_suffix
def _handle_validate(args: argparse.Namespace) -> None:
"""Handle `imednet datadict validate` command."""
output_format = resolve_output_format(getattr(args, "format", None), default="text")
schema_dict = None
if args.schema:
try:
schema_text = Path(args.schema).read_text(encoding="utf-8")
schema_dict = json.loads(schema_text)
except Exception as exc:
err_msg = f"Error reading schema file '{args.schema}': {exc}"
if output_format == "json":
_emit_validate_json(args.file, [err_msg])
else:
print_error(redact_cli_secrets(err_msg))
sys.exit(1)
file_path = Path(args.file)
is_dataset_json = False
if not file_path.is_dir() and file_path.suffix.lower() == ".json":
if schema_dict is None and _is_dataset_json_cli_file(file_path):
is_dataset_json = True
errors = validate_dataset_json(file_path)
else:
errors = validate(args.file, schema=schema_dict)
elif not file_path.is_dir() and file_path.suffix.lower() == ".xml":
errors = _validate_odm_xml_cli_file(file_path, args.file, schema_dict)
else:
try:
dd = load_offline_schema(args.file)
except Exception as exc:
errors = [str(exc)]
else:
errors = validate(dd, schema=schema_dict)
if output_format == "json":
_emit_validate_json(args.file, errors)
if errors:
sys.exit(1)
return
if errors:
print_error(f"Validation failed with {len(errors)} error(s):")
for err in errors:
print_error(redact_cli_secrets(f" - {err}"))
sys.exit(1)
spec_label = (
"CDISC Dataset-JSON v1.1 specification"
if is_dataset_json
else "data dictionary specification"
)
if write_stdout(f"Validation passed: '{args.file}' conforms to the {spec_label}."):
flush_stdout()
def _handle_diff(args: argparse.Namespace) -> None:
"""Handle `imednet datadict diff` command."""
try:
old_dd = load_offline_schema(args.old)
except Exception as exc:
print_error(
redact_cli_secrets(f"Error reading baseline data dictionary '{args.old}': {exc}")
)
sys.exit(1)
try:
new_dd = load_offline_schema(args.new)
except Exception as exc:
print_error(redact_cli_secrets(f"Error reading target data dictionary '{args.new}': {exc}"))
sys.exit(1)
report = diff(old_dd, new_dd)
output_format = resolve_output_format(args.format, default="text")
if output_format == "json":
rendered_diff = report.to_json()
elif output_format == "md":
rendered_diff = report.to_markdown()
else:
rendered_diff = report.to_text()
if write_stdout(rendered_diff, end=""):
flush_stdout()
def _handle_schema(args: argparse.Namespace) -> None:
"""Handle `imednet datadict schema` command."""
schema_dict = get_schema()
json_text = json.dumps(schema_dict, indent=2) + "\n"
if args.output:
try:
Path(args.output).write_text(json_text, encoding="utf-8")
print(f"Successfully wrote schema to '{args.output}'", file=sys.stderr)
except Exception as exc:
print_error(redact_cli_secrets(f"Error writing schema to '{args.output}': {exc}"))
sys.exit(1)
elif write_stdout(json_text, end=""):
flush_stdout()
[docs]def setup_parser(subparsers: argparse._SubParsersAction) -> None: # type: ignore[type-arg]
"""Setup parser for `imednet datadict` commands."""
datadict_parser = subparsers.add_parser(
"datadict",
help="Manage, transform, and validate study data dictionaries.",
)
cmd_subparsers = datadict_parser.add_subparsers(dest="datadict_command")
# 1. from-csv
csv_parser = cmd_subparsers.add_parser(
"from-csv",
help="Compile canonical JSON data dictionary from CSV directory or ZIP archive.",
)
csv_parser.add_argument(
"path",
help="Path to directory or ZIP archive containing the 4 data dictionary CSV files.",
)
csv_parser.add_argument(
"-o",
"--output",
help="Destination JSON file path (default: stdout).",
)
csv_parser.add_argument(
"--study-key",
action=UniqueStoreAction,
help="Optional study key identifier override.",
)
csv_parser.add_argument(
"--strict",
action="store_true",
help="Fail fast on unknown columns, unreferenced forms, or format issues.",
)
csv_parser.add_argument(
"--no-raw-xml",
action="store_true",
help="Omit verbatim XML strings from business logic rules.",
)
csv_parser.set_defaults(func=_handle_from_csv)
# 1b. from-odm
odm_parser = cmd_subparsers.add_parser(
"from-odm",
help="Compile canonical JSON data dictionary from CDISC ODM 1.3 XML file.",
)
odm_parser.add_argument(
"path",
help="Path to CDISC ODM XML file.",
)
odm_parser.add_argument(
"-o",
"--output",
help="Destination JSON file path (default: stdout).",
)
odm_parser.add_argument(
"--study-key",
action=UniqueStoreAction,
help="Optional study key identifier override.",
)
odm_parser.add_argument(
"--strict",
action="store_true",
help="Fail fast on unknown elements, unreferenced definitions, or format issues.",
)
odm_parser.add_argument(
"--no-raw-xml",
action="store_true",
help="Omit verbatim XML strings from business logic rules.",
)
odm_parser.add_argument(
"--archive",
action="store_true",
help="Parse full ODM 1.3.2 archive including AdminData, ReferenceData, and ClinicalData.",
)
odm_parser.set_defaults(func=_handle_from_odm)
# 1b2. to-odm
to_odm_parser = cmd_subparsers.add_parser(
"to-odm",
help="Export data dictionary to CDISC ODM 1.3 XML format.",
)
to_odm_parser.add_argument(
"file",
help=(
"Path to data dictionary source (.json, .xml, .csv REDCap, .zip CSV archive, "
"or CSV directory) to export."
),
)
to_odm_parser.add_argument(
"-o",
"--output",
help="Destination XML file path (default: stdout).",
)
to_odm_parser.add_argument(
"--file-oid",
help="Optional ODM FileOID attribute override.",
)
to_odm_parser.set_defaults(func=_handle_to_odm)
# 1c. from-redcap
redcap_parser = cmd_subparsers.add_parser(
"from-redcap",
help="Compile canonical JSON data dictionary from REDCap CSV file.",
)
redcap_parser.add_argument(
"path",
help="Path to REDCap data dictionary CSV file.",
)
redcap_parser.add_argument(
"-o",
"--output",
help="Destination JSON file path (default: stdout).",
)
redcap_parser.add_argument(
"--study-key",
action=UniqueStoreAction,
help="Optional study key identifier override.",
)
redcap_parser.add_argument(
"--strict",
action="store_true",
help="Fail fast on unknown columns, unreferenced forms, or format issues.",
)
redcap_parser.add_argument(
"--no-raw-xml",
action="store_true",
help="Omit verbatim XML strings.",
)
redcap_parser.set_defaults(func=_handle_from_redcap)
# 2. from-api
api_parser = cmd_subparsers.add_parser(
"from-api",
help="Extract study forms and variables from live iMednet REST API.",
)
add_study_key_args(
api_parser,
flag_help="Study key identifier to query.",
)
api_parser.add_argument(
"-o",
"--output",
help="Destination JSON file path (default: stdout).",
)
api_parser.add_argument(
"--no-raw-xml",
action="store_true",
help="Omit verbatim XML strings.",
)
add_simulation_arg(api_parser)
api_parser.set_defaults(func=_handle_from_api, _api_parser=api_parser)
# 3. validate
val_parser = cmd_subparsers.add_parser(
"validate",
help="Validate a data dictionary source against model and schema rules.",
)
val_parser.add_argument(
"file",
help=(
"Path to data dictionary source (.json, .xml, .csv REDCap, .zip CSV archive, "
"or CSV directory) to validate."
),
)
val_parser.add_argument(
"--schema",
help="Optional path to custom JSON schema file for validation.",
)
val_parser.add_argument(
"--format",
choices=["text", "json"],
default=None,
help="Output format: text or json (default: text).",
)
val_parser.set_defaults(func=_handle_validate)
# 4. diff
diff_parser = cmd_subparsers.add_parser(
"diff",
help="Compare two data dictionary sources structurally.",
)
diff_parser.add_argument(
"old",
help="Baseline data dictionary (.json, .xml, .csv REDCap, .zip CSV archive, or CSV dir).",
)
diff_parser.add_argument(
"new",
help="Updated data dictionary (.json, .xml, .csv REDCap, .zip CSV archive, or CSV dir).",
)
diff_parser.add_argument(
"--format",
choices=["text", "json", "md"],
default=None,
help="Output format: text, json, or md (default: text).",
)
diff_parser.set_defaults(func=_handle_diff)
# 5. schema
schema_parser = cmd_subparsers.add_parser(
"schema",
help="Export the canonical JSON Schema for data dictionaries.",
)
schema_parser.add_argument(
"-o",
"--output",
help="Destination path for schema JSON file (default: stdout).",
)
schema_parser.set_defaults(func=_handle_schema)
datadict_parser.set_defaults(
func=lambda args: (
datadict_parser.print_help() if not getattr(args, "datadict_command", None) else None
)
)