Source code for jcmsuite.templates.formatting

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

"""Conservative formatting for JCMsuite input and template files."""

from __future__ import annotations

import re
from collections.abc import Iterator
from pathlib import Path

_SCRIPT_TAG_PATTERN: re.Pattern[str] = re.compile(r"<\?(?:Python)?|\?>")
_ASSIGNMENT_PATTERN: re.Pattern[str] = re.compile(r"(?<![<>=!])\s*=\s*(?!=)")
_COMMA_PATTERN: re.Pattern[str] = re.compile(r"\s*,\s*")
_OPEN_BRACE_PATTERN: re.Pattern[str] = re.compile(r"[ \t]*\{")
_CLOSE_BRACE_PATTERN: re.Pattern[str] = re.compile(r"[ \t]*\}")


[docs] def format_jcm(source: str, *, indent: str = " ") -> str: """Format JCM source while preserving values and embedded Python. Parameters ---------- source : str Source text that contains JCM syntax and optional template Python. indent : str, default=" " Text to insert for each brace nesting level. The value must not be empty. Returns ------- str Formatted source. Raises ------ ValueError If the source contains unbalanced braces, an unterminated string, an invalid template boundary, or an empty ``indent`` value. """ if not indent: raise ValueError("indent must not be empty") formatted_parts: list[str] = [] cursor: int = 0 depth: int = 0 in_python: bool = False for tag_match in _SCRIPT_TAG_PATTERN.finditer(source): if in_python: formatted_parts.append(source[cursor : tag_match.start()]) formatted_parts.append(tag_match.group()) cursor = tag_match.end() if tag_match.group() == "?>": in_python = False continue if tag_match.group() == "?>": raise ValueError("template Python block closes without opening") jcm_text: str = source[cursor : tag_match.start()] formatted_jcm, depth = _format_jcm_fragment(jcm_text, depth, indent) formatted_parts.append(formatted_jcm) formatted_parts.append(tag_match.group()) cursor = tag_match.end() if tag_match.group().startswith("<?"): in_python = True if in_python: raise ValueError("unterminated template Python block") else: formatted_jcm, depth = _format_jcm_fragment(source[cursor:], depth, indent) formatted_parts.append(formatted_jcm) if depth != 0: raise ValueError(f"unbalanced braces: nesting level {depth}") return "".join(formatted_parts)
def _format_jcm_fragment(source: str, depth: int, indent: str) -> tuple[str, int]: """Format one JCM fragment and return its resulting brace depth.""" expanded_source: str = _expand_brace_lines(source) lines: list[str] = _expand_assignment_lines(expanded_source).splitlines( keepends=True ) formatted_lines: list[str] = [] for line in lines: content: str = line.rstrip("\r\n") line_ending: str = line[len(content) :] formatted, depth = _format_jcm_line(content, depth, indent) formatted_lines.append(formatted + line_ending) return "".join(formatted_lines), depth def _expand_assignment_lines(source: str) -> str: """Put consecutive top-level assignments on separate lines.""" expanded_lines: list[str] = [] for line in source.splitlines(keepends=True): content: str = line.rstrip("\r\n") line_ending: str = line[len(content) :] assignment_starts: list[int] = _assignment_starts(content) boundaries: list[int] = assignment_starts[1:] start: int = 0 for boundary in boundaries: expanded_lines.append(content[start:boundary].rstrip() + "\n") start = boundary expanded_lines.append(content[start:] + line_ending) return "".join(expanded_lines) def _assignment_starts(line: str) -> list[int]: """Return assignment-key starts outside strings and comments.""" assignment_starts: list[int] = [] quote: str | None = None escaped: bool = False in_comment: bool = False for index, character in enumerate(line): if in_comment: continue if escaped: escaped = False continue if quote is not None: if character == "\\": escaped = True elif character == quote: quote = None continue if character in ('"', "'"): quote = character elif character == "#": in_comment = True elif character == "=" and _is_assignment_operator(line, index): key_end: int = index while key_end > 0 and line[key_end - 1].isspace(): key_end -= 1 key_start: int = key_end while key_start > 0 and not line[key_start - 1].isspace(): key_start -= 1 assignment_starts.append(key_start) return assignment_starts def _is_assignment_operator(line: str, index: int) -> bool: """Return whether an equals sign is a standalone assignment operator.""" previous: str = line[index - 1] if index > 0 else "" following: str = line[index + 1] if index + 1 < len(line) else "" return previous not in "<>=!" and following not in "<=>" def _expand_brace_lines(source: str) -> str: """Put structural braces on separate lines without changing literals.""" expanded: list[str] = [] quote: str | None = None escaped: bool = False in_comment: bool = False for index, character in enumerate(source): if in_comment: expanded.append(character) if character == "\n": in_comment = False continue if escaped: expanded.append(character) escaped = False continue if quote is not None: expanded.append(character) if character == "\\": escaped = True elif character == quote: quote = None continue if character in ('"', "'"): quote = character expanded.append(character) elif character == "#": in_comment = True expanded.append(character) elif character in "{}": current_line: str = "".join(expanded).rsplit("\n", 1)[-1] if character == "{" and current_line.strip(): line_without_trailing_space: str = current_line.rstrip() block_name: str = line_without_trailing_space.rsplit(None, 1)[-1] block_name_start: int = len(line_without_trailing_space) - len( block_name ) prefix: str = line_without_trailing_space[:block_name_start] if _assignment_starts(prefix): line_start: int = len(expanded) - len(current_line) expanded.insert(line_start + block_name_start, "\n") if character == "}" and current_line.strip(): expanded.append("\n") expanded.append(character) next_character: str = source[index + 1] if index + 1 < len(source) else "" if next_character and next_character != "\n": expanded.append("\n") else: expanded.append(character) return "".join(expanded) def _format_jcm_line(line: str, depth: int, indent: str) -> tuple[str, int]: """Format one JCM line and update brace nesting.""" stripped: str = line.strip() if not stripped: return "", depth code, comment = _split_comment(stripped) if _has_unterminated_quote(code): raise ValueError("unterminated string") normalized_code: str = _normalize_code(code.strip()) closing_count: int = _leading_closing_braces(normalized_code) line_depth: int = depth - closing_count if line_depth < 0: raise ValueError("unbalanced closing brace") content: str = normalized_code if comment: separator: str = " " if content else "" content = f"{content}{separator}{comment}" formatted: str = f"{indent * line_depth}{content}" opens, closes = _brace_counts(code) new_depth: int = depth + opens - closes if new_depth < 0: raise ValueError("unbalanced closing brace") return formatted, new_depth def _split_comment(line: str) -> tuple[str, str]: """Split a line at a comment marker outside quoted strings.""" quote: str | None = None escaped: bool = False for index, character in enumerate(line): if escaped: escaped = False elif character == "\\" and quote is not None: escaped = True elif quote is not None and character == quote: quote = None elif quote is None and character in ('"', "'"): quote = character elif quote is None and character == "#": return line[:index], line[index:].rstrip() return line, "" def _normalize_code(code: str) -> str: """Normalize separators outside quoted strings.""" parts: list[str] = [] cursor: int = 0 for match in re.finditer(r'"(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\'', code): parts.append(_normalize_plain(code[cursor : match.start()])) parts.append(match.group()) cursor = match.end() parts.append(_normalize_plain(code[cursor:])) return "".join(parts).strip() def _normalize_plain(code: str) -> str: """Normalize punctuation in a non-string code fragment.""" normalized: str = _ASSIGNMENT_PATTERN.sub(" = ", code) normalized = _COMMA_PATTERN.sub(", ", normalized) normalized = _OPEN_BRACE_PATTERN.sub(" {", normalized) normalized = _CLOSE_BRACE_PATTERN.sub("}", normalized) return normalized def _leading_closing_braces(code: str) -> int: """Count closing braces at the start of a normalized code line.""" return len(code) - len(code.lstrip("}")) def _brace_counts(code: str) -> tuple[int, int]: """Count braces outside quoted strings and comments.""" opens: int = 0 closes: int = 0 quote: str | None = None escaped: bool = False for character in code: if escaped: escaped = False elif character == "\\" and quote is not None: escaped = True elif quote is not None and character == quote: quote = None elif quote is None and character in ('"', "'"): quote = character elif quote is None: opens += character == "{" closes += character == "}" return opens, closes def _has_unterminated_quote(code: str) -> bool: """Return whether a line ends inside a quoted string.""" quote: str | None = None escaped: bool = False for character in code: if escaped: escaped = False elif character == "\\" and quote is not None: escaped = True elif quote is not None and character == quote: quote = None elif quote is None and character in ('"', "'"): quote = character return quote is not None def format_path(path: str | Path, *, write: bool = False) -> str: """Format one JCM-family file and optionally write the result.""" file_path: Path = Path(path) source: str = file_path.read_text(encoding="utf-8") formatted: str = format_jcm(source) if write: file_path.write_text(formatted, encoding="utf-8") return formatted def iter_jcm_files(path: str | Path) -> Iterator[Path]: """Yield JCM-family files below a file or directory path.""" root: Path = Path(path) if root.is_file(): if root.suffix in {".jcm", ".jcmp", ".jcmt", ".jcmpt"}: yield root return yield from sorted( candidate for candidate in root.rglob("*") if candidate.is_file() and candidate.suffix in {".jcm", ".jcmp", ".jcmt", ".jcmpt"} )