|
| 1 | +"""GEDCOM 7 serializer.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import re |
| 6 | +from typing import TYPE_CHECKING |
| 7 | + |
| 8 | +from . import const, grammar |
| 9 | +from .exceptions import GedcomSerializeError |
| 10 | + |
| 11 | +if TYPE_CHECKING: |
| 12 | + from collections.abc import Iterable |
| 13 | + from typing import IO |
| 14 | + |
| 15 | + from .types import GedcomStructure |
| 16 | + |
| 17 | +_EOL = re.compile(r"\r\n|\r|\n") |
| 18 | +_TAG = re.compile(grammar.tag) |
| 19 | +_XREF = re.compile(grammar.xref) |
| 20 | +_POINTER = re.compile(grammar.pointer) |
| 21 | +_BANNED = re.compile(grammar.banned) |
| 22 | +_TAGDEF = re.compile(grammar.tagdef) |
| 23 | + |
| 24 | +_BOM = "" |
| 25 | + |
| 26 | + |
| 27 | +def _escape(linestr: str) -> str: |
| 28 | + """Escape a line string's leading "@" by doubling it. |
| 29 | +
|
| 30 | + The inverse of the parser's unescaping: only a leading ``@`` is doubled, so |
| 31 | + ``@@@@`` is written as ``@@@@@``. |
| 32 | + """ |
| 33 | + return "@" + linestr if linestr.startswith("@") else linestr |
| 34 | + |
| 35 | + |
| 36 | +def _schema(records: Iterable[GedcomStructure]) -> dict[str, str]: |
| 37 | + """Map each URI declared by the header schema back to its extension tag.""" |
| 38 | + uris: dict[str, str] = {} |
| 39 | + for record in records: |
| 40 | + if record.tag != const.HEAD: |
| 41 | + continue |
| 42 | + for schema in record.children: |
| 43 | + if schema.tag != const.SCHMA: |
| 44 | + continue |
| 45 | + for definition in schema.children: |
| 46 | + if definition.tag != const.TAG: |
| 47 | + continue |
| 48 | + match = _TAGDEF.fullmatch(definition.text) |
| 49 | + # A schema should map only one tag to each URI; keep the first. |
| 50 | + if match is not None: |
| 51 | + uris.setdefault(match.group("uri"), match.group("exttag")) |
| 52 | + return uris |
| 53 | + |
| 54 | + |
| 55 | +def _lines( |
| 56 | + structure: GedcomStructure, level: int, uris: dict[str, str] |
| 57 | +) -> Iterable[str]: |
| 58 | + """Yield the lines encoding a structure and everything below it.""" |
| 59 | + tag = uris.get(structure.tag, structure.tag) |
| 60 | + if _TAG.fullmatch(tag) is None: |
| 61 | + hint = ( |
| 62 | + " Add a matching HEAD.SCHMA.TAG definition to abbreviate it." |
| 63 | + if "://" in tag |
| 64 | + else "" |
| 65 | + ) |
| 66 | + raise GedcomSerializeError(f"{tag!r} is not a valid tag.{hint}") |
| 67 | + |
| 68 | + parts = [str(level)] |
| 69 | + if structure.xref is not None and structure.xref != "": |
| 70 | + if level != 0: |
| 71 | + raise GedcomSerializeError( |
| 72 | + f"only records may have a cross-reference identifier, but {tag} " |
| 73 | + f"at level {level} has {structure.xref}" |
| 74 | + ) |
| 75 | + if _XREF.fullmatch(structure.xref) is None or structure.xref == const.VOIDPTR: |
| 76 | + raise GedcomSerializeError( |
| 77 | + f"{structure.xref!r} is not a valid cross-reference identifier" |
| 78 | + ) |
| 79 | + parts.append(structure.xref) |
| 80 | + parts.append(tag) |
| 81 | + |
| 82 | + if structure.pointer is not None and structure.pointer != "": |
| 83 | + if structure.text: |
| 84 | + raise GedcomSerializeError( |
| 85 | + f"{tag} has both a pointer and a text payload; a line value is " |
| 86 | + "one or the other" |
| 87 | + ) |
| 88 | + if _POINTER.fullmatch(structure.pointer) is None: |
| 89 | + raise GedcomSerializeError(f"{structure.pointer!r} is not a valid pointer") |
| 90 | + parts.append(structure.pointer) |
| 91 | + yield " ".join(parts) |
| 92 | + else: |
| 93 | + # A payload containing line terminators is split across the structure's |
| 94 | + # own line and one CONT pseudo-structure per subsequent line. |
| 95 | + payload = _EOL.split(structure.text) |
| 96 | + if payload[0]: |
| 97 | + parts.append(_escape(payload[0])) |
| 98 | + yield " ".join(parts) |
| 99 | + for continuation in payload[1:]: |
| 100 | + yield ( |
| 101 | + f"{level + 1} {const.CONT} {_escape(continuation)}" |
| 102 | + if continuation |
| 103 | + else f"{level + 1} {const.CONT}" |
| 104 | + ) |
| 105 | + |
| 106 | + for child in structure.children: |
| 107 | + yield from _lines(child, level + 1, uris) |
| 108 | + |
| 109 | + |
| 110 | +def dumps( |
| 111 | + records: Iterable[GedcomStructure], |
| 112 | + *, |
| 113 | + line_terminator: str = "\n", |
| 114 | + byte_order_mark: bool = True, |
| 115 | +) -> str: |
| 116 | + """Serialize structures to a GEDCOM 7 data stream. |
| 117 | +
|
| 118 | + Levels are derived from the structure tree, payloads containing line |
| 119 | + terminators are split into CONT pseudo-structures, and a leading "@" in a |
| 120 | + payload is escaped. Extension tags stored as URIs are abbreviated using the |
| 121 | + tag definitions in the header schema. |
| 122 | +
|
| 123 | + The specification says a data stream should begin with U+FEFF, so a byte |
| 124 | + order mark is included by default; pass ``byte_order_mark=False`` to omit it. |
| 125 | + Write the result with ``encoding="utf-8"``, not ``"utf-8-sig"``. |
| 126 | +
|
| 127 | + Raises :class:`~gedcom7.exceptions.GedcomSerializeError` if the structures |
| 128 | + cannot be encoded as conforming lines. |
| 129 | + """ |
| 130 | + if line_terminator not in ("\n", "\r\n", "\r"): |
| 131 | + raise GedcomSerializeError( |
| 132 | + f"{line_terminator!r} is not a valid line terminator; " |
| 133 | + "use '\\n', '\\r\\n' or '\\r'" |
| 134 | + ) |
| 135 | + |
| 136 | + records = list(records) |
| 137 | + uris = _schema(records) |
| 138 | + lines = [line for record in records for line in _lines(record, 0, uris)] |
| 139 | + |
| 140 | + string = "".join(line + line_terminator for line in lines) |
| 141 | + banned = _BANNED.search(string) |
| 142 | + if banned: |
| 143 | + raise GedcomSerializeError( |
| 144 | + f"banned character U+{ord(banned.group()):04X} in payload" |
| 145 | + ) |
| 146 | + return (_BOM if byte_order_mark else "") + string |
| 147 | + |
| 148 | + |
| 149 | +def dump( |
| 150 | + records: Iterable[GedcomStructure], |
| 151 | + fp: IO[str], |
| 152 | + *, |
| 153 | + line_terminator: str = "\n", |
| 154 | + byte_order_mark: bool = True, |
| 155 | +) -> None: |
| 156 | + """Serialize structures to a text file opened with ``encoding="utf-8"``.""" |
| 157 | + fp.write( |
| 158 | + dumps( |
| 159 | + records, |
| 160 | + line_terminator=line_terminator, |
| 161 | + byte_order_mark=byte_order_mark, |
| 162 | + ) |
| 163 | + ) |
0 commit comments