Source code for jcmsuite.templates.converter

# SPDX-License-Identifier: MIT
# Copyright (c) 2001-{{ COPYRIGHT_END_YEAR }} JCMwave GmbH

"""Template-processing namespace for `jcmsuite`."""

from __future__ import annotations

from collections.abc import Mapping
from pathlib import Path

from ..exceptions import InvalidConfigurationError
from .rendering import render_template


[docs] def jcmt2jcm( jcmt_file: str | Path, keys: Mapping[str, object] | None = None, outputfile: str | Path | None = None, ) -> Path: """Create a JCM file from a `.jcmt` or `.jcmpt` template. Parameters ---------- jcmt_file : str | Path Path to the template file. The file name must end in `.jcmt` or `.jcmpt`. keys : Mapping[str, object] | None, optional Project Key values to insert into the template. Python blocks in the template can also use these values. outputfile : str | Path | None, optional Path for the generated file. If omitted, the converter removes the trailing `t` from the template extension (`.jcmt` becomes `.jcm` and `.jcmpt` becomes `.jcmp`). Returns ------- Path Absolute path of the new JCM file. Raises ------ InvalidConfigurationError If the template path or extension is invalid. TemplateMappingError If the template contains an error. The error identifies the source position when possible. """ input_path: Path = Path(jcmt_file).expanduser().resolve() if input_path.suffix not in (".jcmt", ".jcmpt"): raise InvalidConfigurationError( f"Template file has unsupported extension: {input_path}" ) if not input_path.is_file(): raise InvalidConfigurationError(f"Template file does not exist: {input_path}") output_path: Path if outputfile is None: output_path = Path(str(input_path)[:-1]).resolve() else: output_path = Path(outputfile).expanduser().resolve() rendered_text: str _rendered_line_map: list[int] rendered_text, _rendered_line_map = render_template( input_path.read_text(encoding="utf-8"), keys={} if keys is None else keys, source=input_path, ) output_path.write_text(rendered_text, encoding="utf-8") return output_path