diff --git a/README.md b/README.md index b6891b8..9e75872 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,19 @@ Each record is a `GedcomStructure` with a `tag`, an optional `xref` and `pointer `loads` and `dumps` are the string equivalents. Non-conforming input raises `GedcomParseError`, a `ValueError` carrying `line_number`. A pointer to a record that does not exist is kept rather than rejected; `gedcom7.validate(records)` lists each one as a `dangling-pointer` error. +### GEDZIP + +```python +with gedcom7.GedzipReader("family.gdz") as archive: + records = archive.records + with archive.open("media/photo.jpg") as f: # a FILE payload + data = f.read() + +gedcom7.dump_gedzip(records, "out.gdz", {"media/photo.jpg": data}) +``` + +File content can be given as bytes, a path, or a function returning an open binary file. Where the files are stored is left to the caller. + ## Development ``` diff --git a/gedcom7/__init__.py b/gedcom7/__init__.py index da6c531..a2712e4 100644 --- a/gedcom7/__init__.py +++ b/gedcom7/__init__.py @@ -9,6 +9,7 @@ GedcomValidationError, ) from .formatter import format_value, set_value +from .gedzip import GedzipReader, dump_gedzip from .parser import load, loads from .serializer import dump, dumps, generate_schema from .validator import Error, validate @@ -19,7 +20,9 @@ "GedcomSerializeError", "GedcomValidationError", "Error", + "GedzipReader", "dump", + "dump_gedzip", "dumps", "format_value", "generate_schema", diff --git a/gedcom7/gedzip.py b/gedcom7/gedzip.py new file mode 100644 index 0000000..59223cf --- /dev/null +++ b/gedcom7/gedzip.py @@ -0,0 +1,228 @@ +"""Read and write GEDZIP archives: a dataset and the local files it names.""" + +from __future__ import annotations + +import os +import posixpath +import re +import shutil +import zipfile +from typing import IO, TYPE_CHECKING, BinaryIO, Union, cast +from urllib.parse import quote, unquote + +from . import const, grammar +from .exceptions import GedcomParseError, GedcomSerializeError +from .parser import load +from .serializer import dumps + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable, Iterator, Mapping + from types import TracebackType + + from .types import GedcomStructure + +DATASET = "gedcom.ged" + +FILE_PATH = "https://gedcom.io/terms/v7/type-FilePath" + +# What a local file's content can be given as: its bytes, a path to read it +# from, or a function opening it. +FileSource = Union[bytes, str, "os.PathLike[str]", "Callable[[], IO[bytes]]"] + +_SCHEME = re.compile(r"[A-Za-z][A-Za-z0-9+.-]*:") +_BANNED = re.compile(grammar.banned) +# Characters a file path payload carries literally; anything else is escaped. +_SAFE = "/!$&'()*+,;=@-._~" +# A valid URL string: URL code points and percent escapes, no query or fragment. +_URL_PATH = re.compile( + r"(?:[A-Za-z0-9!$&'()*+,\-./:;=@_~]|%[0-9A-Fa-f]{2}|[^\x00-\x7f])*" +) + + +def is_local_file(path: str) -> bool: + """Say whether a file path payload names a local file, not a URL.""" + if not path or _SCHEME.match(path) or "?" in path or "#" in path: + return False + try: + name = unquote(path, errors="strict") + except UnicodeDecodeError: + return False + if name.startswith("/") or "\\" in name or _BANNED.search(name): + return False + return ".." not in name.split("/") + + +def entry_name(path: str) -> str: + """Get the archive entry a local file path payload names.""" + if not is_local_file(path): + raise ValueError(f"{path!r} is not a local file path") + return unquote(path, errors="strict") + + +def file_path(name: str) -> str: + """Get the file path payload naming an archive entry.""" + path = quote(name, safe=_SAFE) + if not is_local_file(path): + raise ValueError(f"{name!r} cannot be a local file in a GEDZIP") + return path + + +def file_structures( + records: Iterable[GedcomStructure], +) -> Iterator[GedcomStructure]: + """Yield every structure whose payload is a file path.""" + stack = list(reversed(list(records))) + while stack: + structure = stack.pop() + type_id = structure.type_id + if type_id is not None and const.payloads.get(type_id) == FILE_PATH: + yield structure + stack.extend(reversed(structure.children)) + + +def local_files(records: Iterable[GedcomStructure]) -> list[str]: + """List the local file paths a dataset names, each once, in order.""" + paths = (s.text for s in file_structures(records)) + return list(dict.fromkeys(p for p in paths if is_local_file(p))) + + +class GedzipReader: + """A GEDZIP archive opened for reading. + + :: + + with gedcom7.GedzipReader("family.gdz") as archive: + records = archive.records + with archive.open("media/photo.jpg") as f: + data = f.read() + """ + + def __init__(self, file: str | os.PathLike[str] | IO[bytes]) -> None: + """Open the archive and load its dataset.""" + try: + self._zip = zipfile.ZipFile(file) + except zipfile.BadZipFile as exc: + raise GedcomParseError(f"not a GEDZIP archive: {exc}") from exc + try: + with self._zip.open(DATASET) as fp: + self.records: list[GedcomStructure] = load(cast(BinaryIO, fp)) + except KeyError: + self._zip.close() + raise GedcomParseError(f"GEDZIP archive has no {DATASET}") from None + except BaseException: + self._zip.close() + raise + + def has(self, path: str) -> bool: + """Say whether the archive holds the local file a payload names.""" + try: + self._zip.getinfo(entry_name(path)) + except (KeyError, ValueError): + return False + return True + + def open(self, path: str) -> IO[bytes]: + """Open the local file a payload names. + + Raises :class:`KeyError` if the archive does not hold it. + """ + return self._zip.open(entry_name(path)) + + def missing(self) -> list[str]: + """List the local file paths the dataset names but the archive lacks.""" + return [p for p in local_files(self.records) if not self.has(p)] + + def close(self) -> None: + """Close the archive.""" + self._zip.close() + + def __enter__(self) -> GedzipReader: + """Enter a ``with`` block.""" + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + """Close the archive on leaving a ``with`` block.""" + self.close() + + +def _check_paths( + records: list[GedcomStructure], files: Mapping[str, FileSource | None] +) -> None: + for structure in file_structures(records): + path = structure.text + if is_local_file(path): + if path not in files: + raise GedcomSerializeError(f"no content given for local file {path}") + elif path.lower().startswith("file:"): + raise GedcomSerializeError(f"a GEDZIP cannot point at file URL {path}") + names: dict[str, str] = {} + for path, source in files.items(): + if not is_local_file(path) or not _URL_PATH.fullmatch(path): + raise GedcomSerializeError(f"{path!r} is not a valid local file path") + # Unzipping drops "." and empty segments, so names differing only in + # those land on the same file. + name = posixpath.normpath(entry_name(path)) + if name == DATASET: + raise GedcomSerializeError(f"a local file cannot be named {DATASET}") + if source is not None: + if name in names: + raise GedcomSerializeError( + f"{names[name]} and {path} name the same file {name}" + ) + names[name] = path + + +def _write_file(archive: zipfile.ZipFile, name: str, source: FileSource) -> None: + if isinstance(source, bytes): + archive.writestr(name, source) + return + # Not ZipFile.write, which would normalize the name. + with ( + ( + open(source, "rb") if isinstance(source, (str, os.PathLike)) else source() + ) as src, + archive.open(name, "w", force_zip64=True) as dst, + ): + shutil.copyfileobj(src, dst) + + +def dump_gedzip( + records: Iterable[GedcomStructure], + file: str | os.PathLike[str] | BinaryIO, + files: Mapping[str, FileSource | None], + *, + compress_files: bool = False, + line_terminator: str = "\n", + byte_order_mark: bool = True, + validate: bool = False, +) -> None: + """Write a dataset and its local files as a GEDZIP archive. + + ``files`` maps each local file path payload in the dataset to its content, + or to None to leave a file that is unavailable out. + The dataset is compressed; the files only with ``compress_files=True``, as + most media is compressed already. + + Raises :class:`~gedcom7.exceptions.GedcomSerializeError` if a local file has + no content, is named ``gedcom.ged``, is not a valid URL string, or shares its + name with another, or if a payload is a ``file:`` URL. + """ + records = list(records) + _check_paths(records, files) + data = dumps( + records, + line_terminator=line_terminator, + byte_order_mark=byte_order_mark, + validate=validate, + ).encode("utf-8") + method = zipfile.ZIP_DEFLATED if compress_files else zipfile.ZIP_STORED + with zipfile.ZipFile(file, "w", compression=method) as archive: + archive.writestr(DATASET, data, compress_type=zipfile.ZIP_DEFLATED) + for path, source in files.items(): + if source is not None: + _write_file(archive, entry_name(path), source) diff --git a/test/test_gedzip.py b/test/test_gedzip.py new file mode 100644 index 0000000..153509e --- /dev/null +++ b/test/test_gedzip.py @@ -0,0 +1,218 @@ +"""Tests for reading and writing GEDZIP archives.""" + +import io +import pathlib +import zipfile + +import pytest + +import gedcom7 +from gedcom7 import GedcomParseError, GedcomSerializeError, gedzip, types + + +def dataset(*paths: str) -> list[types.GedcomStructure]: + head = types.GedcomStructure(tag="HEAD") + gedc = types.GedcomStructure(tag="GEDC") + head.append_child(gedc) + gedc.append_child(types.GedcomStructure(tag="VERS", text="7.0")) + records = [head] + for number, path in enumerate(paths, start=1): + obje = types.GedcomStructure(tag="OBJE", xref=f"@O{number}@") + file = types.GedcomStructure(tag="FILE", text=path) + file.append_child(types.GedcomStructure(tag="FORM", text="image/jpeg")) + obje.append_child(file) + records.append(obje) + records.append(types.GedcomStructure(tag="TRLR")) + return records + + +@pytest.mark.parametrize( + "path", + [ + "photo.jpg", + "media/photo.jpg", + "media/a%20b.jpg", + "média/ü.jpg", + "./photo.jpg", + "media//photo.jpg", + ], +) +def test_local_file(path: str) -> None: + assert gedzip.is_local_file(path) + + +@pytest.mark.parametrize( + "path", + [ + "", + "https://example.com/a.jpg", + "file:///home/a.jpg", + "/abs/a.jpg", + "../a.jpg", + "media/%2E%2E/a.jpg", + "media\\a.jpg", + "media/a%5Cb.jpg", + "a.jpg?x=1", + "a.jpg#frag", + "a%01.jpg", + ], +) +def test_not_local_file(path: str) -> None: + assert not gedzip.is_local_file(path) + + +@pytest.mark.parametrize( + "name", ["media/a b.jpg", "media/50%.jpg", "c:d.jpg", "a#b?.jpg", "ü.jpg"] +) +def test_file_path_round_trip(name: str) -> None: + path = gedzip.file_path(name) + assert gedzip.is_local_file(path) + assert gedzip.entry_name(path) == name + + +@pytest.mark.parametrize("name", ["../a.jpg", "/a.jpg", "a\\b.jpg", ""]) +def test_file_path_rejects(name: str) -> None: + with pytest.raises(ValueError): + gedzip.file_path(name) + + +def test_round_trip(tmp_path: pathlib.Path) -> None: + on_disk = tmp_path / "c.jpg" + on_disk.write_bytes(b"from disk") + records = dataset("media/a%20b.jpg", "b.jpg", "c.jpg", "https://example.com/d.jpg") + target = tmp_path / "family.gdz" + gedcom7.dump_gedzip( + records, + target, + { + "media/a%20b.jpg": b"bytes", + "b.jpg": lambda: io.BytesIO(b"opened"), + "c.jpg": on_disk, + }, + ) + with zipfile.ZipFile(target) as archive: + assert sorted(archive.namelist()) == [ + "b.jpg", + "c.jpg", + "gedcom.ged", + "media/a b.jpg", + ] + assert archive.getinfo("gedcom.ged").compress_type == zipfile.ZIP_DEFLATED + assert archive.getinfo("b.jpg").compress_type == zipfile.ZIP_STORED + with gedcom7.GedzipReader(target) as archive: + assert archive.records == records + assert archive.missing() == [] + with archive.open("media/a%20b.jpg") as f: + assert f.read() == b"bytes" + with archive.open("b.jpg") as f: + assert f.read() == b"opened" + with archive.open("c.jpg") as f: + assert f.read() == b"from disk" + assert not archive.has("https://example.com/d.jpg") + + +def test_local_files_include_translations() -> None: + records = dataset("a.jpg", "a.jpg") + tran = types.GedcomStructure(tag="TRAN", text="b.jpg") + tran.append_child(types.GedcomStructure(tag="FORM", text="image/jpeg")) + records[1].children[0].append_child(tran) + assert gedzip.local_files(records) == ["a.jpg", "b.jpg"] + + +def test_reader_reports_missing() -> None: + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w") as archive: + archive.writestr("gedcom.ged", gedcom7.dumps(dataset("a.jpg", "b.jpg"))) + archive.writestr("a.jpg", b"") + with gedcom7.GedzipReader(buffer) as reader: + assert reader.missing() == ["b.jpg"] + with pytest.raises(KeyError): + reader.open("b.jpg") + + +def test_reader_needs_dataset() -> None: + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w") as archive: + archive.writestr("other.ged", b"") + with pytest.raises(GedcomParseError, match="gedcom.ged"): + gedcom7.GedzipReader(buffer) + + +def test_reader_needs_zip() -> None: + with pytest.raises(GedcomParseError, match="not a GEDZIP"): + gedcom7.GedzipReader(io.BytesIO(b"0 HEAD\n")) + + +def test_writer_needs_every_local_file() -> None: + with pytest.raises(GedcomSerializeError, match="b.jpg"): + gedcom7.dump_gedzip(dataset("a.jpg", "b.jpg"), io.BytesIO(), {"a.jpg": b""}) + + +def test_writer_rejects_dataset_name() -> None: + with pytest.raises(GedcomSerializeError, match="gedcom.ged"): + gedcom7.dump_gedzip(dataset("gedcom.ged"), io.BytesIO(), {"gedcom.ged": b""}) + + +def test_writer_rejects_file_url() -> None: + with pytest.raises(GedcomSerializeError, match="file URL"): + gedcom7.dump_gedzip(dataset("file:///home/a.jpg"), io.BytesIO(), {}) + + +def test_writer_leaves_out_unavailable_file() -> None: + buffer = io.BytesIO() + gedcom7.dump_gedzip( + dataset("a.jpg", "b.jpg"), buffer, {"a.jpg": b"", "b.jpg": None} + ) + with gedcom7.GedzipReader(buffer) as reader: + assert reader.missing() == ["b.jpg"] + + +def test_writer_finds_dot_segments() -> None: + with pytest.raises(GedcomSerializeError, match="./a.jpg"): + gedcom7.dump_gedzip(dataset("./a.jpg"), io.BytesIO(), {}) + + +@pytest.mark.parametrize("path", ["a%ZZ.jpg", "a%.jpg", "a<1>.jpg", "a b.jpg"]) +def test_writer_rejects_invalid_url(path: str) -> None: + with pytest.raises(GedcomSerializeError, match="not a valid local file path"): + gedcom7.dump_gedzip(dataset(path), io.BytesIO(), {path: b""}) + + +def test_writer_rejects_extra_dataset_entry() -> None: + with pytest.raises(GedcomSerializeError, match="gedcom.ged"): + gedcom7.dump_gedzip( + dataset("a.jpg"), io.BytesIO(), {"a.jpg": b"", "gedcom.ged": b""} + ) + + +def test_writer_rejects_names_decoding_alike() -> None: + with pytest.raises(GedcomSerializeError, match="same file a.jpg"): + gedcom7.dump_gedzip( + dataset("a.jpg", "%61.jpg"), io.BytesIO(), {"a.jpg": b"1", "%61.jpg": b"2"} + ) + + +def test_path_sources_keep_their_names(tmp_path: pathlib.Path) -> None: + on_disk = tmp_path / "x.jpg" + on_disk.write_bytes(b"1") + buffer = io.BytesIO() + gedcom7.dump_gedzip( + dataset("./a.jpg", "m//b.jpg"), + buffer, + {"./a.jpg": on_disk, "m//b.jpg": str(on_disk)}, + ) + with gedcom7.GedzipReader(buffer) as reader: + assert reader.missing() == [] + + +@pytest.mark.parametrize("extra", ["./gedcom.ged", ".//gedcom.ged"]) +def test_writer_rejects_dataset_name_in_disguise(extra: str) -> None: + with pytest.raises(GedcomSerializeError, match="gedcom.ged"): + gedcom7.dump_gedzip(dataset(), io.BytesIO(), {extra: b""}) + + +def test_writer_rejects_names_unzipping_alike() -> None: + with pytest.raises(GedcomSerializeError, match="same file a.jpg"): + gedcom7.dump_gedzip( + dataset("a.jpg", "./a.jpg"), io.BytesIO(), {"a.jpg": b"1", "./a.jpg": b"2"} + )