diff --git a/doclang/README.md b/doclang/README.md index 5292f78..81fc8c4 100644 --- a/doclang/README.md +++ b/doclang/README.md @@ -93,6 +93,9 @@ doclang pack markup.dclg --pages screenshots/ doclang pack markup.dclg --page a.png --page b.png doclang pack markup.dclg --asset chart.svg=exports/diagram.svg doclang pack markup.dclg --assets payload/ +doclang pack markup.dclg --source report.pdf --keep-source-name # kept as source.pdf +doclang pack markup.dclg --source upload.bin --source-name "Q3 report.pdf" # also kept as source.pdf +doclang pack markup.dclg --audio episode-12.mp3 --source episode-12.mp3 --keep-source-name # reuses audio/1.mp3 doclang pack markup.dclg --validate ``` diff --git a/doclang/_packaging.py b/doclang/_packaging.py index 1c81f44..b85780f 100644 --- a/doclang/_packaging.py +++ b/doclang/_packaging.py @@ -23,7 +23,41 @@ _CONTENT_TYPES_NAMESPACE = "http://schemas.openxmlformats.org/package/2006/content-types" _RELATIONSHIPS_NAMESPACE = "http://schemas.openxmlformats.org/package/2006/relationships" -_DOCUMENT_RELATIONSHIP = "http://doclang.ai/ns/package/2026/relationships/document" + +_RELATIONSHIP_TYPES = "http://doclang.ai/ns/package/2026/relationships/" +_DOCUMENT_RELATIONSHIP = _RELATIONSHIP_TYPES + "document" +_SOURCE_RELATIONSHIP = _RELATIONSHIP_TYPES + "source" +_SOURCE_METADATA_RELATIONSHIP = _RELATIONSHIP_TYPES + "source-metadata" + +_SOURCE_METADATA_NAMESPACE = "http://doclang.ai/ns/package/2026/source-metadata" +_SOURCE_METADATA_CONTENT_TYPE = "application/vnd.doclang.source-metadata+xml" + +_DEFAULT_CONTENT_TYPES = { + "rels": "application/vnd.openxmlformats-package.relationships+xml", + "png": "image/png", + "jpg": "image/jpeg", + "jpeg": "image/jpeg", + "webp": "image/webp", + "svg": "image/svg+xml", + "mp3": "audio/mpeg", + "m4a": "audio/mp4", + "aac": "audio/aac", + "ogg": "audio/ogg", + "opus": "audio/ogg", + "wav": "audio/wav", + "flac": "audio/flac", + "mp4": "video/mp4", + "webm": "video/webm", + "mkv": "video/x-matroska", + "mov": "video/quicktime", + "pdf": "application/pdf", + "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + "pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation", + "doc": "application/msword", + "xls": "application/vnd.ms-excel", + "ppt": "application/vnd.ms-powerpoint", +} _DOCUMENT_CONTENT_TYPE = "application/vnd.doclang.document+xml" # Positional parts: ``pages/{N}.{ext}`` align with the N-th page, ``audio/{N}.{ext}`` and ``video/{N}.{ext}`` with @@ -38,38 +72,7 @@ # markup and on parts not accounted for. _FIRST_ARCHIVE_VERSION = (0, 8) _REFERENCES_VERSION = (0, 10) - -_CONTENT_TYPES_XML = """\ - - - - - - - - - - - - - - - - - - - - -""" - -_RELS_XML = """\ - - - - -""" +_SOURCE_VERSION = (0, 10) # the original source, located by a relationship PagesInput = Union[ str, @@ -89,6 +92,8 @@ SourceInput = Union[str, Path, bytes] _SOURCE_MIMETYPE_PATTERN = re.compile(r"[A-Za-z0-9!#$&^_.+-]+/[A-Za-z0-9!#$&^_.+-]+\Z") +# Extensions taken over from an original file name into the source part's name (``source.``). +_SOURCE_EXTENSION_PATTERN = re.compile(r"[a-z0-9]{1,16}\Z") class PackagingError(Exception): @@ -118,14 +123,19 @@ def _validate_archive_relative_path(path: str, *, label: str) -> None: raise PackagingError(f"Invalid {label} path: {path!r}") -def _copy_file(source: Path, destination: Path, *, label: str) -> None: +Placed = dict[Path, Path] +"""The input files placed in the stage so far: resolved input path → destination.""" + + +def _copy_file(source: Path, destination: Path, *, label: str, placed: Placed) -> None: _reject_symlink(source, label=label) _require_file(source, label=label) destination.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(source, destination) + placed.setdefault(source.resolve(), destination) -def _copy_tree_into(source: Path, destination: Path, *, label: str) -> None: +def _copy_tree_into(source: Path, destination: Path, *, label: str, placed: Placed) -> None: _reject_symlink(source, label=label) _require_directory(source, label=label) destination.mkdir(parents=True, exist_ok=True) @@ -133,9 +143,10 @@ def _copy_tree_into(source: Path, destination: Path, *, label: str) -> None: target = destination / item.name _reject_symlink(item, label=label) if item.is_dir(): - _copy_tree_into(item, target, label=label) + _copy_tree_into(item, target, label=label, placed=placed) else: shutil.copy2(item, target) + placed.setdefault(item.resolve(), target) def _place_document(stage: Path, document: Path) -> None: @@ -151,6 +162,7 @@ def _place_indexed( file_label: str, dir_label: str, number_label: str, + placed: Placed, ) -> None: """Place 1-based positionally-indexed files (``{N}.{ext}``) under ``stage/subdir``. @@ -164,20 +176,20 @@ def _place_indexed( raise PackagingError(f"{number_label} must be positive integers, got {number!r}") source_path = Path(source) destination = target_dir / f"{number}{source_path.suffix}" - _copy_file(source_path, destination, label=file_label) + _copy_file(source_path, destination, label=file_label, placed=placed) return if isinstance(spec, str | Path): - _copy_tree_into(Path(spec), target_dir, label=dir_label) + _copy_tree_into(Path(spec), target_dir, label=dir_label, placed=placed) return for index, source in enumerate(spec, start=1): source_path = Path(source) destination = target_dir / f"{index}{source_path.suffix}" - _copy_file(source_path, destination, label=file_label) + _copy_file(source_path, destination, label=file_label, placed=placed) -def _place_pages(stage: Path, pages: PagesInput) -> None: +def _place_pages(stage: Path, pages: PagesInput, placed: Placed) -> None: _place_indexed( stage, pages, @@ -185,10 +197,11 @@ def _place_pages(stage: Path, pages: PagesInput) -> None: file_label="Page file", dir_label="Pages directory", number_label="Page numbers", + placed=placed, ) -def _place_audio(stage: Path, audio: MediaInput) -> None: +def _place_audio(stage: Path, audio: MediaInput, placed: Placed) -> None: _place_indexed( stage, audio, @@ -196,10 +209,11 @@ def _place_audio(stage: Path, audio: MediaInput) -> None: file_label="Audio file", dir_label="Audio directory", number_label="Audio track numbers", + placed=placed, ) -def _place_video(stage: Path, video: MediaInput) -> None: +def _place_video(stage: Path, video: MediaInput, placed: Placed) -> None: _place_indexed( stage, video, @@ -207,39 +221,131 @@ def _place_video(stage: Path, video: MediaInput) -> None: file_label="Video file", dir_label="Video directory", number_label="Video track numbers", + placed=placed, ) -def _place_assets(stage: Path, assets: AssetsInput) -> None: +def _place_assets(stage: Path, assets: AssetsInput, placed: Placed) -> None: assets_dir = stage / "assets" if isinstance(assets, Mapping): for archive_path, source in assets.items(): _validate_archive_relative_path(archive_path, label="asset") destination = assets_dir / archive_path - _copy_file(Path(source), destination, label="Asset file") + _copy_file(Path(source), destination, label="Asset file", placed=placed) return - _copy_tree_into(Path(assets), assets_dir, label="Assets directory") + _copy_tree_into(Path(assets), assets_dir, label="Assets directory", placed=placed) -def _place_source(stage: Path, source: SourceInput, mimetype: str) -> None: - if _SOURCE_MIMETYPE_PATTERN.fullmatch(mimetype) is None: - raise PackagingError("Invalid source MIME type; expected type/subtype") +def _extension(part: str) -> str | None: + """The extension of the part ``part`` (as OPC matches ````), lowercased, or None.""" + name = part.rsplit("/", 1)[-1] + return name.rsplit(".", 1)[1].lower() if "." in name else None + + +def _source_part_name(source: SourceInput, name: str | None) -> str: + """``source.`` with the extensions of the original file name (up to two, e.g. ``source.tar.gz``), or + ``source`` without a reliable one.""" + original = name if name is not None else (None if isinstance(source, bytes) else Path(source).name) + if original is None: + return "source" + stem, *extensions = original.lower().split(".") + if not stem or not extensions or extensions[-1] == "rels": + return "source" + kept: list[str] = [] + for extension in reversed(extensions[-2:]): + if _SOURCE_EXTENSION_PATTERN.fullmatch(extension) is None: + break + kept.insert(0, extension) + return f"source.{'.'.join(kept)}" if kept else "source" + + +def _check_source_name(name: str) -> None: + if ( + not name + or name in {".", ".."} + or any(c in name for c in "/\\") + or any(ord(c) < 32 or ord(c) == 127 for c in name) + ): + raise PackagingError(f"Invalid source file name: {name!r}") + + +def _place_source(stage: Path, source: SourceInput, name: str | None, placed: Placed) -> str: + """Place the original source, unless it is a file already placed (e.g. the whole-track media of a single + recording); return its part name.""" + if not isinstance(source, bytes): + _reject_symlink(Path(source), label="Source document") + destination = placed.get(Path(source).resolve()) + if destination is not None: + return destination.relative_to(stage).as_posix() + part = _source_part_name(source, name) if isinstance(source, bytes): - (stage / "source").write_bytes(source) + (stage / part).write_bytes(source) else: - _copy_file(Path(source), stage / "source", label="Source document") + _copy_file(Path(source), stage / part, label="Source document", placed=placed) + return part -def _write_opc_metadata(stage: Path, *, source_mimetype: str | None = None) -> None: - content_types = _CONTENT_TYPES_XML - if source_mimetype is not None: - override = f' \n' - content_types = content_types.replace("", f"{override}") - (stage / "[Content_Types].xml").write_text(content_types, encoding="utf-8") +def _declare_content_type( + part: str, content_type: str | None, defaults: dict[str, str], overrides: dict[str, str] +) -> None: + """Make sure ``part`` has a content type (``content_type`` if given): a ```` for its extension if + there is none yet, else an ```` if the existing one differs.""" + extension = _extension(part) + current = overrides.get(part) or (defaults.get(extension) if extension else None) + if content_type is None: + if current is None: + raise PackagingError(f"No content type known for the source part {part!r}; pass its MIME type") + elif content_type != current: + if _SOURCE_MIMETYPE_PATTERN.fullmatch(content_type) is None: + raise PackagingError("Invalid source MIME type; expected type/subtype") + if extension is not None and extension not in defaults and part not in overrides: + defaults[extension] = content_type + else: + overrides[part] = content_type + + +def _source_metadata_xml(name: str) -> str: + return ( + '\n' + f"\n" + ) + + +def _write_opc_metadata( + stage: Path, + defaults: Mapping[str, str], + overrides: Mapping[str, str], + relationships: Sequence[tuple[str, str]], +) -> None: + """Write ``_rels/.rels`` and ``[Content_Types].xml``; ``relationships`` are (type, target part) pairs, and of + ``defaults`` only the extensions of parts without an override are declared.""" + lines = ['', f''] + for number, (relationship_type, target) in enumerate(relationships, start=1): + lines += [ + f' ", + ] + lines.append("") rels_dir = stage / "_rels" rels_dir.mkdir(parents=True, exist_ok=True) - (rels_dir / ".rels").write_text(_RELS_XML, encoding="utf-8") + (rels_dir / ".rels").write_text("\n".join(lines) + "\n", encoding="utf-8") + + used = { + _extension(part) + for part in (path.relative_to(stage).as_posix() for path in stage.rglob("*") if path.is_file()) + if part not in overrides and not _should_exclude_zip_member(part) + } + lines = ['', f''] + lines += [ + f" " + for ext, ct in defaults.items() + if ext in used + ] + lines += [f" " for p, ct in overrides.items()] + lines.append("") + (stage / "[Content_Types].xml").write_text("\n".join(lines) + "\n", encoding="utf-8") def _should_exclude_zip_member(arcname: str) -> bool: @@ -274,27 +380,41 @@ def _pack( video: MediaInput | None = None, source: SourceInput | None = None, source_mimetype: str | None = None, + source_name: str | None = None, validate: bool = False, ) -> Path: - if (source is None) != (source_mimetype is None): - raise PackagingError("source and source_mimetype must be provided together") + if source is None and (source_mimetype is not None or source_name is not None): + raise PackagingError("source_mimetype and source_name need source") + if source_name is not None: + _check_source_name(source_name) document_path = Path(document) output_path = Path(output) if output is not None else document_path.with_suffix(".dclx") with tempfile.TemporaryDirectory() as temp_dir: stage = Path(temp_dir) + placed: Placed = {} _place_document(stage, document_path) if pages is not None: - _place_pages(stage, pages) + _place_pages(stage, pages, placed) if assets is not None: - _place_assets(stage, assets) + _place_assets(stage, assets, placed) if audio is not None: - _place_audio(stage, audio) + _place_audio(stage, audio, placed) if video is not None: - _place_video(stage, video) - if source is not None and source_mimetype is not None: - _place_source(stage, source, source_mimetype) - _write_opc_metadata(stage, source_mimetype=source_mimetype) + _place_video(stage, video, placed) + defaults = dict(_DEFAULT_CONTENT_TYPES) + overrides = {"document.xml": _DOCUMENT_CONTENT_TYPE} + relationships = [(_DOCUMENT_RELATIONSHIP, "document.xml")] + if source is not None: + part = _place_source(stage, source, source_name, placed) + _declare_content_type(part, source_mimetype, defaults, overrides) + relationships.append((_SOURCE_RELATIONSHIP, part)) + if source_name is not None: + descriptor = "source-metadata.xml" + (stage / descriptor).write_text(_source_metadata_xml(source_name), encoding="utf-8") + overrides[descriptor] = _SOURCE_METADATA_CONTENT_TYPE + relationships.append((_SOURCE_METADATA_RELATIONSHIP, descriptor)) + _write_opc_metadata(stage, defaults, overrides, relationships) if validate: # the archive, before it replaces any existing output from doclang.validation import validate as validate_document @@ -359,11 +479,14 @@ def _write_archive( ) -> None: """Write a copy of the archive ``source`` to ``output`` with ``document`` as its ``document.xml``. - ``renames`` maps member names to new names, or to None to leave the member out. Every other member is - copied as is, with its zip metadata, in the original order. ``output`` may be ``source``. + ``renames`` maps member names to new names, or to None to leave the member out; package relationships and + content type overrides follow. Every other member is copied as is, with its zip metadata, in the original + order. ``output`` may be ``source``. """ output_path = Path(output) output_path.parent.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(source) as archive_in: + metadata = _renamed_opc_metadata(archive_in, renames) with tempfile.NamedTemporaryFile(dir=output_path.parent, suffix=".dclx", delete=False) as temp: temp_path = Path(temp.name) try: @@ -378,6 +501,8 @@ def _write_archive( if member.filename == "document.xml": info.date_time = time.localtime()[:6] archive_out.writestr(info, document) + elif member.filename in metadata: + archive_out.writestr(info, metadata[member.filename]) elif member.is_dir(): archive_out.writestr(info, b"") else: # streamed: media can be large @@ -406,12 +531,6 @@ def _archive_rules_apply(version: tuple[int, int] | None, since: tuple[int, int] return version is None or version >= since -def _extension(part: str) -> str | None: - """The extension of the part ``part`` (as OPC matches ````), lowercased, or None.""" - name = part.rsplit("/", 1)[-1] - return name.rsplit(".", 1)[1].lower() if "." in name else None - - def _parse_xml(data: bytes) -> etree._Element: return etree.fromstring(data, etree.XMLParser(resolve_entities=False, no_network=True)) @@ -504,7 +623,8 @@ def _relationship_targets_of_parts(archive: zipfile.ZipFile, parts: list[str]) - def _check_archive(path: Union[str, Path], version: tuple[int, int] | None) -> tuple[Problems, Problems]: """The errors and warnings on the rules of Annex B for a document of the spec ``version`` (None for the latest) in the archive ``path``, apart from the validity of its ``document.xml``: the OPC metadata - (``[Content_Types].xml``, ``_rels/.rels``), the positional parts (``pages/``, ``audio/``, ``video/``), and + (``[Content_Types].xml``, ``_rels/.rels``), the original source and its descriptor, the positional parts + (``pages/``, ``audio/``, ``video/``), and the parts referenced from the markup or not accounted for. The archive must be readable (see ``_read_archive``). """ @@ -521,6 +641,8 @@ def warning(location: str, message: str) -> None: parts = [name for name in archive.namelist() if not name.endswith("/")] _check_content_types(archive, parts, error) _check_package_relationships(archive, error) + if _archive_rules_apply(version, _SOURCE_VERSION): + _check_source(archive, parts, error) try: root = _parse_xml(archive.read("document.xml")) except etree.XMLSyntaxError: @@ -602,3 +724,88 @@ def _check_references( or any(pattern.fullmatch(part) for pattern in (_RELATIONSHIP_PART_RE, _PAGE_RE, _TRACK_MEDIA_RE)) ): warning(part, "Not referenced by the markup or a relationship, nor a page image or whole-track media") + + +def _check_source(archive: zipfile.ZipFile, parts: list[str], error: Callable[[str, str], None]) -> None: + """The rules on the original source and its descriptor (their content types are checked with all parts').""" + try: + relationships = _package_relationships(archive) or [] + except etree.XMLSyntaxError: + return # reported with the package relationships + by_type: dict[str, list[etree._Element]] = {} + for relationship in relationships: + by_type.setdefault(relationship.get("Type", ""), []).append(relationship) + for relationship_type, label in ( + (_SOURCE_RELATIONSHIP, "source"), + (_SOURCE_METADATA_RELATIONSHIP, "source descriptor"), + ): + found = by_type.get(relationship_type, []) + if len(found) > 1: + error("_rels/.rels", f"More than one {relationship_type} relationship") + for relationship in found: + if relationship.get("TargetMode") == "External": + error("_rels/.rels", f"The {label} relationship must target a part of the archive") + continue + part = _relationship_target_part(relationship.get("Target", "")) + if part not in parts: + error("_rels/.rels", f"The {label} part {part!r} is missing") + continue + if relationship_type == _SOURCE_METADATA_RELATIONSHIP: + try: + root = _parse_xml(archive.read(part)) + except etree.XMLSyntaxError as exc: + error(part, f"Not well-formed XML: {exc}") + continue + if root.tag != f"{{{_SOURCE_METADATA_NAMESPACE}}}source": + error(part, f"The root element must be source in the namespace {_SOURCE_METADATA_NAMESPACE}") + if _SOURCE_METADATA_RELATIONSHIP in by_type and _SOURCE_RELATIONSHIP not in by_type: + error("_rels/.rels", "A source-metadata relationship without a source relationship") + + +def _relationship_targets(path: Union[str, Path]) -> set[str]: + """The parts targeted by relationships, apart from the main document (e.g. the original source).""" + with zipfile.ZipFile(path) as archive: + return _relationship_targets_of_parts(archive, archive.namelist()) - {"document.xml"} + + +def _renamed_opc_metadata(archive: zipfile.ZipFile, renames: Mapping[str, str | None]) -> dict[str, bytes]: + """``_rels/.rels`` and ``[Content_Types].xml`` updated for the parts in ``renames`` (relationship targets and + ```` part names follow a renamed part; an ```` of a removed part is dropped). Only the + ones that change are returned; ones that are not well-formed are left alone.""" + updated: dict[str, bytes] = {} + names = set(archive.namelist()) + if "_rels/.rels" in names: + try: + root = _parse_xml(archive.read("_rels/.rels")) + except etree.XMLSyntaxError: + root = None + changed = False + for relationship in [] if root is None else root.iterfind(f"{{{_RELATIONSHIPS_NAMESPACE}}}Relationship"): + target = relationship.get("Target", "") + if relationship.get("TargetMode") == "External": + continue + new = renames.get(_relationship_target_part(target)) + if new is not None: + relationship.set("Target", f"/{new}" if target.startswith("/") else new) + changed = True + if changed: + updated["_rels/.rels"] = etree.tostring(root, xml_declaration=True, encoding="UTF-8") + if "[Content_Types].xml" in names: + try: + root = _parse_xml(archive.read("[Content_Types].xml")) + except etree.XMLSyntaxError: + root = None + lowered = {old.lower(): new for old, new in renames.items()} + changed = False + for override in [] if root is None else list(root.iterfind(f"{{{_CONTENT_TYPES_NAMESPACE}}}Override")): + part = override.get("PartName", "").lstrip("/").lower() + if part not in lowered: + continue + if lowered[part] is None: + root.remove(override) + else: + override.set("PartName", f"/{lowered[part]}") + changed = True + if changed: + updated["[Content_Types].xml"] = etree.tostring(root, xml_declaration=True, encoding="UTF-8") + return updated diff --git a/doclang/cli.py b/doclang/cli.py index a40dd7f..668fced 100644 --- a/doclang/cli.py +++ b/doclang/cli.py @@ -93,10 +93,10 @@ def validate( For a .dclx archive, its document.xml is validated, and (unless --xsd-only or --schematron-only) its other parts are checked against the archive rules - (Annex B, from version 0.8): the OPC metadata, page images and whole-track - media beyond the pages and elements of the document, and - URIs that resolve to no part. Parts that nothing accounts for are warned - about. + (Annex B, from version 0.8): the OPC metadata, the original source and its + descriptor, page images and whole-track media beyond the pages and + elements of the document, and URIs that resolve to no part. Parts + that nothing accounts for are warned about. Examples: @@ -324,7 +324,10 @@ def pack( source_file: Path | None = typer.Option( None, "--source", - help="Original source document stored unchanged as /source (requires --source-mimetype)", + help=( + "Original source document, stored unchanged as source. (or source without an extension), " + "unless it is already packed, e.g. as --audio" + ), exists=True, file_okay=True, dir_okay=False, @@ -332,7 +335,17 @@ def pack( source_mimetype: str | None = typer.Option( None, "--source-mimetype", - help="MIME type of --source, e.g. application/pdf", + help="MIME type of the original source, e.g. application/pdf (needed if its extension has no known type)", + ), + source_name: str | None = typer.Option( + None, + "--source-name", + help="Original file name of the source, recorded in a source descriptor (source-metadata.xml)", + ), + keep_source_name: bool = typer.Option( + False, + "--keep-source-name", + help="Record the --source file's own name as its original file name (instead of --source-name)", ), validate_before_pack: bool = typer.Option(False, "--validate", help="Validate document before packing"), quiet: bool = typer.Option(False, "--quiet", "-q", help="Quiet mode (exit code only)"), @@ -345,9 +358,11 @@ def pack( --audio, --video-dir, --video) are placed under audio/ and video/ as {N}.{ext} for the Nth . Optional payload files (--assets, --asset) are placed under assets/ for URIs referenced in the markup. An optional - original source document (--source with --source-mimetype) is stored - unchanged as /source, its MIME type recorded in [Content_Types].xml. OPC metadata - ([Content_Types].xml, _rels/.rels) is generated automatically. + original source document (--source) is stored unchanged as source. + (unless it is already packed, e.g. as --audio, which is then reused) and + located through a package relationship; --keep-source-name also records + its file name, or --source-name another original file name. OPC metadata ([Content_Types].xml, _rels/.rels) is + generated automatically. By default, writes .dclx next to the input file. @@ -359,11 +374,9 @@ def pack( doclang pack markup.dclg --asset chart.svg=exports/diagram.svg doclang pack markup.dclg --audio-dir recordings/ --video-dir recordings/ doclang pack markup.dclg --assets payload/ --validate - doclang pack markup.dclg --source report.pdf --source-mimetype application/pdf + doclang pack markup.dclg --source report.pdf --source-name "Q3 report.pdf" + doclang pack markup.dclg --audio episode-12.mp3 --source episode-12.mp3 --keep-source-name """ - if (source_file is None) != (source_mimetype is None): - typer.echo("Error: --source and --source-mimetype must be given together", err=True) - raise typer.Exit(1) if pages_dir is not None and page_files: typer.echo("Error: --pages and --page are mutually exclusive", err=True) raise typer.Exit(1) @@ -376,6 +389,14 @@ def pack( if video_dir is not None and video_files: typer.echo("Error: --video-dir and --video are mutually exclusive", err=True) raise typer.Exit(1) + if keep_source_name and source_name is not None: + typer.echo("Error: --keep-source-name and --source-name are mutually exclusive", err=True) + raise typer.Exit(1) + if keep_source_name: + if source_file is None: + typer.echo("Error: --keep-source-name needs --source", err=True) + raise typer.Exit(1) + source_name = source_file.name output_path = output or document.with_suffix(".dclx") @@ -408,6 +429,7 @@ def pack( video=video, source=source_file, source_mimetype=source_mimetype, + source_name=source_name, validate=validate_before_pack, ) except ValidationError as exc: diff --git a/doclang/migration/_api.py b/doclang/migration/_api.py index 7cbd9c9..226d8ad 100644 --- a/doclang/migration/_api.py +++ b/doclang/migration/_api.py @@ -5,14 +5,14 @@ import re import tempfile import warnings -from collections.abc import Callable, Sequence +from collections.abc import Callable, Collection, Sequence from dataclasses import dataclass, field from pathlib import Path from typing import Any, Union from lxml import etree -from doclang._packaging import PackagingError, _is_archive, _read_archive, _write_archive +from doclang._packaging import PackagingError, _is_archive, _read_archive, _relationship_targets, _write_archive from doclang._schemas import UnsupportedVersionError, _available_versions, _head_description, _version_key from doclang.migration import _archive from doclang.migration._plan import NoMigrationPath, _load_steps, _plan @@ -123,7 +123,9 @@ def migrate( with tempfile.TemporaryDirectory() as tmp: document_path = Path(tmp) / "document.xml" document_path.write_bytes(document) - result, renames = _migrate(document_path, [m.filename for m in members], **options) + result, renames = _migrate( + document_path, [m.filename for m in members], relationship_targets=_relationship_targets(path), **options + ) if output is not None: _write_archive(path, output, result.xml.encode("utf-8"), renames) return result @@ -133,6 +135,7 @@ def _migrate( path: Path, members: Sequence[str] | None, *, + relationship_targets: Collection[str] = (), to: str, source: str | None, strict: bool, @@ -140,7 +143,7 @@ def _migrate( output_validation: str, ) -> tuple[MigrationResult, dict[str, str | None]]: """Migrate the XML file ``path`` (see :func:`migrate`), with the renames of the archive ``members`` (or - of none, if it is no archive's).""" + of none, if it is no archive's); ``relationship_targets`` are the members targeted by package relationships.""" available = _available_versions() newest = max(available, key=_version_key) if available else None head = _head_version(newest) @@ -191,7 +194,9 @@ def _migrate( tracks, assets = _archive.tracks(root), _archive.asset_references(root) for step in steps: step.apply(root, changes) - renames = {} if members is None else _archive.member_renames(members, tracks, assets, root, changes) + renames = ( + {} if members is None else _archive.member_renames(members, tracks, assets, root, changes, relationship_targets) + ) changed = [c for c in changes.items if c["kind"] != "orphaned"] if strict and changed: diff --git a/doclang/migration/_archive.py b/doclang/migration/_archive.py index 6d48cac..ab192c1 100644 --- a/doclang/migration/_archive.py +++ b/doclang/migration/_archive.py @@ -4,12 +4,13 @@ whole-track media (``audio/{N}.*``, ``video/{N}.*``, aligned with the N-th ````) and assets referenced (via ````) only by removed elements. Such members are kept (and reported as orphaned), except that the media of the remaining tracks is renumbered to stay aligned with them, and that of removed tracks is removed if -tracks remain (it would pair with another track). +tracks remain (it would pair with another track), unless a package relationship targets it (e.g. as the archive's +original source): then it is moved out of the way to ``source.``. """ from __future__ import annotations -from collections.abc import Iterable +from collections.abc import Collection, Iterable from lxml import etree @@ -29,14 +30,16 @@ def member_renames( assets_before: set[str], root: etree._Element, changes: Changes, + targets: Collection[str] = (), ) -> dict[str, str | None]: """The members to rename (to their new name) or remove (to None) after the migration of ``root``. ``tracks_before`` and ``assets_before`` are the tracks and asset references before the migration (a track is recognized as kept by identity). Whole-track media of the kept tracks is renumbered; that of removed tracks is removed if any tracks remain, otherwise it is kept and reported as orphaned, like the assets - referenced only by removed elements. Media numbered beyond the original tracks and other members are left - alone. + referenced only by removed elements. Media of removed tracks that is the target of a package relationship + (one of ``targets``) is moved to ``source.`` instead of being removed. Media numbered beyond the original + tracks and other members are left alone. """ positions = {id(track): n for n, track in enumerate(tracks(root), start=1)} new_positions = [positions.get(id(track)) for track in tracks_before] @@ -46,7 +49,15 @@ def member_renames( match = _TRACK_MEDIA_RE.fullmatch(name) if match and int(match[2]) <= len(tracks_before): new = new_positions[int(match[2]) - 1] - if new is None and positions: + if new is None and positions and name in targets: + renames[name] = _free_name(f"source{match[3]}", set(names) | set(renames.values())) + changes.record_member( + "renamed", + name, + f"renamed to {renames[name]}: a package relationship targets this whole-track media of the " + f"removed {match[2]}, which would otherwise pair with another track", + ) + elif new is None and positions: renames[name] = None changes.record_member("removed", name, f"whole-track media of the removed {match[2]}") elif new is None: @@ -61,3 +72,13 @@ def member_renames( elif name in assets_before and name not in referenced: changes.record_member("orphaned", name, "kept, but only removed elements referenced it") return renames + + +def _free_name(name: str, taken: Collection[str | None]) -> str: + """``name``, or ``name`` with a number before its extension, whichever is not ``taken``.""" + stem, dot, extension = name.partition(".") + number = 1 + while name in taken: + number += 1 + name = f"{stem}-{number}{dot}{extension}" + return name diff --git a/doclang/packaging.py b/doclang/packaging.py index d0590b9..2141356 100644 --- a/doclang/packaging.py +++ b/doclang/packaging.py @@ -21,6 +21,7 @@ def pack( video: (Union[str, Path] | Sequence[Union[str, Path]] | Mapping[int, Union[str, Path]] | None) = None, source: Union[str, Path, bytes, None] = None, source_mimetype: str | None = None, + source_name: str | None = None, validate: bool = False, ) -> Path: """Pack a DocLang markup file and optional media into a ``.dclx`` OPC archive. @@ -44,10 +45,22 @@ def pack( ``assets`` may be a directory (copied into ``assets/``) or a mapping of archive-relative asset path to source file. - ``source`` is the original document as raw bytes or a file path. Provide - ``source_mimetype`` with it. The archive stores the bytes unchanged in the - root-level ``source`` part and records the MIME type as that part's - content type in ``[Content_Types].xml``. + ``source`` is the original document (from which the markup was produced) as + raw bytes or a file path. The archive stores the bytes unchanged in the part + ``source.``, with the extension(s) of the original file name (up to + two, e.g. ``source.tar.gz``) (``source_name`` + if given, else the file's own name), or in ``source`` without a reliable one, + and locates it with a package relationship in ``_rels/.rels``. A source file + that is also packed otherwise (e.g. as ``audio`` when converting a single + recording) is not stored twice: the relationship targets that part. + + ``source_mimetype`` is the original's MIME type. It is needed when the part's + extension has no content type yet (always for bytes without ``source_name``), + and is recorded in ``[Content_Types].xml``. + + ``source_name`` is the original file name. When given, it is recorded in a + source descriptor part (``source-metadata.xml``); otherwise the original name is not + kept, as the part's name is only a storage name. Symbolic links are refused for ``pages``, ``audio``, ``video``, ``assets`` and a source file (including entries inside directories) so pack does not @@ -68,5 +81,6 @@ def pack( video=video, source=source, source_mimetype=source_mimetype, + source_name=source_name, validate=validate, ) diff --git a/doclang/validation.py b/doclang/validation.py index 1eb3b65..32e7751 100644 --- a/doclang/validation.py +++ b/doclang/validation.py @@ -90,11 +90,12 @@ def validate( For an archive, its ``document.xml`` is validated, and, unless ``xsd_only`` or ``schematron_only`` is set, the rules of Annex B on its other parts are checked too (reported as ``ValidationError.archive_errors``): - the OPC metadata, the page images and whole-track media beyond the pages and ```` elements of the - document, and ```` URIs that resolve to no part. Parts that nothing accounts for (neither OPC metadata - nor a relationship target, a page image or whole-track media, or referenced from the markup) are reported - as :class:`UserWarning`. The archive rules apply as of the spec version they were introduced in (Annex B - in 0.8): that of ``spec_version`` if given, else the declared one, else the latest. + the OPC metadata, the original source and its descriptor, the page images and whole-track media beyond the + pages and ```` elements of the document, and ```` URIs that resolve to no part. Parts that nothing + accounts for (neither OPC metadata nor a relationship target, a page image or whole-track media, or + referenced from the markup) are reported as :class:`UserWarning`. The archive rules apply as of the spec + version they were introduced in (Annex B in 0.8): that of ``spec_version`` if given, else the declared one, + else the latest. The spec version to validate against is ``spec_version`` if given, else the ``version`` attribute of the root element. If neither is set the version is unspecified: the latest schema diff --git a/spec.md b/spec.md index 8484dd2..feacab4 100644 --- a/spec.md +++ b/spec.md @@ -3483,20 +3483,19 @@ None (empty element). A **DocLang archive** is a [ZIP](https://pkware.cachefly.net/webdocs/APPNOTE/APPNOTE-6.3.10.TXT) file using the [Open Packaging Conventions (OPC)](https://www.ecma-international.org/publications-and-standards/standards/ecma-376/) container model. Recommended extension: **`.dclx`**. -An archive is a **package** of **parts** (files in the ZIP). Each part has a path (e.g. `/document.xml`) and a content type declared in `[Content_Types].xml`. The package root relationship file `_rels/.rels` identifies the main DocLang instance part. +An archive is a **package** of **parts** (files in the ZIP). Each part has a path (e.g. `/document.xml`) and a content type declared in `[Content_Types].xml`. The package root relationship file `_rels/.rels` identifies the main DocLang instance part and, optionally, the original source. #### Layout ``` -[Content_Types].xml # required — OPC content types +[Content_Types].xml # required — OPC content types _rels/ - .rels # required — package → main document -document.xml # required — valid DocLang instance -pages/ # optional — page images, e.g. 1.png, 2.png -audio/ # optional — whole-track audio, e.g. 2.mp3, 4.ogg -video/ # optional — whole-track video, e.g. 3.mp4, 4.mkv -assets/ # optional — files referenced from markup -source # optional — original source document (type in [Content_Types].xml) + .rels # required — identifies the DocLang instance and, optionally, the original source +document.xml # required — valid DocLang instance +pages/ # optional — page images, e.g. 1.png, 2.png +audio/ # optional — whole-track audio, e.g. 2.mp3, 4.ogg +video/ # optional — whole-track video, e.g. 3.mp4, 4.mkv +assets/ # optional — files referenced from markup ``` Relative URIs in the markup resolve from the archive root. The relative URI of a [``](#src) MUST resolve to a part of the archive. Every part SHOULD be one of: OPC metadata (`[Content_Types].xml` and relationship parts such as `_rels/.rels`), the target of a relationship, a page image or whole-track media file aligned with a page or [``](#track), or a part referenced by a relative URI in the markup. @@ -3520,7 +3519,7 @@ Example: ##### `_rels/.rels` (required) -Package-level relationships. MUST contain exactly one relationship of type `http://doclang.ai/ns/package/2026/relationships/document` targeting `document.xml`. +Package-level relationships. MUST contain exactly one relationship of type `http://doclang.ai/ns/package/2026/relationships/document` targeting `document.xml`. MAY contain one relationship of type `http://doclang.ai/ns/package/2026/relationships/source` and, only together with it, one of type `http://doclang.ai/ns/package/2026/relationships/source-metadata` (see [Original source](#original-source-optional)). Example: @@ -3551,17 +3550,50 @@ Optional whole-track media. Name files `{N}.{ext}` where `N` is the 1-based posi Optional payload referenced by relative URIs in markup (e.g. ``). URIs resolve from the archive root. -##### `source` (optional) +##### Original source (optional) -The root-level part `/source` is reserved for the original document from which the main DocLang instance was produced. It is a single file with no extension, holding the original bytes unmodified (no base64 encoding). Its MIME type is not stored in the archive as a separate file; when `/source` is present, `[Content_Types].xml` MUST contain an `` for it, e.g.: +An archive MAY carry the original document from which the main DocLang instance was produced (e.g. a PDF, a word-processing document or an audio recording), its bytes unmodified (no base64 encoding). Its part is identified by the package relationship of type `http://doclang.ai/ns/package/2026/relationships/source` in `_rels/.rels`. Consumers MUST locate the original source through this relationship and MUST NOT rely on the part's path. The relationship MUST target a part of the archive (not an external resource), and that part MUST have a content type in `[Content_Types].xml`, through a `` for its extension or an `` for its path. + +Producers SHOULD store the original source: + +- as `/source.`, where `` is the extension of the original file name, or its last two extensions (e.g. `/source.tar.gz`), so that a `` for the last extension declares its content type; +- as `/source`, with an ``, when the original has no reliable extension; +- or, when the archive already contains the same bytes (e.g. converting a single MP3 file whose bytes are also `audio/1.mp3`, or an asset), by targeting that part, without a second copy. + +The name of the part is only a storage name: it does not convey the original file name. A producer MAY record the original file name in a **source descriptor**: an XML part identified by the package relationship of type `http://doclang.ai/ns/package/2026/relationships/source-metadata`, which MUST NOT be present without the `source` relationship. The descriptor has the content type `application/vnd.doclang.source-metadata+xml`, and its root element is `source` in the namespace `http://doclang.ai/ns/package/2026/source-metadata`, with an optional `name` attribute holding the original file name. Consumers SHOULD ignore attributes and child elements of the descriptor that they do not recognize. Recommended part name: `/source-metadata.xml`. Without a descriptor, the original file name is unknown. + +Example, for an archive produced from a single recording `episode-12.mp3`, whose bytes are also the whole-track audio of the first track. `_rels/.rels`: + +```xml + + + + + +``` + +`[Content_Types].xml`: ```xml - + + ``` +`source-metadata.xml`: + +```xml + +``` + #### Page alignment Review tools split markup (excluding ``) on ``; segment *N* corresponds to page *N*. Page count is determined by markup: the number of `` elements plus one. Page images are optional and individual gaps are allowed, but page files must not exceed this count (e.g. two `` elements define three pages, so `4.png` is out of bounds). diff --git a/tests/test_cli.py b/tests/test_cli.py index a5d6042..f0a736d 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -258,15 +258,15 @@ def test_cli_validate_reports_archive_errors(tmp_path): assert valid.exit_code == 0 and "Archive validation passed" in valid.output with zipfile.ZipFile(archive, "a") as zf: - zf.writestr("video/2.mp4", b"beyond the tracks") + zf.writestr("audio/2.wav", b"beyond the tracks") text = runner.invoke(app, ["validate", str(archive)]) assert text.exit_code == 1 - assert "Archive validation failed" in text.output and "video/2.mp4" in text.output + assert "Archive validation failed" in text.output and "audio/2.wav" in text.output as_json = runner.invoke(app, ["validate", str(archive), "--format", "json"]) payload = json.loads(as_json.stdout) - assert [e["location"] for e in payload["archive"]["errors"]] == ["video/2.mp4"] + assert [e["location"] for e in payload["archive"]["errors"]] == ["audio/2.wav"] assert payload["xsd"]["valid"] and payload["schematron"]["valid"] xsd_only = runner.invoke(app, ["validate", str(archive), "--xsd-only"]) @@ -275,18 +275,37 @@ def test_cli_validate_reports_archive_errors(tmp_path): def test_cli_pack_with_source(tmp_path): document = Path(__file__).resolve().parents[1] / "examples" / "archive-demo" / "document.xml" - original = tmp_path / "original.pdf" + original = tmp_path / "upload.bin" original.write_bytes(b"%PDF-1.7\n") out = tmp_path / "out.dclx" - args = ["pack", str(document), "-o", str(out), "--source", str(original)] + args = ["pack", str(document), "-o", str(out), "--source", str(original), "--source-name", "report.pdf"] result = runner.invoke(app, [*args, "--source-mimetype", "application/pdf"]) assert result.exit_code == 0, result.output with zipfile.ZipFile(out) as zf: - assert zf.read("source") == b"%PDF-1.7\n" - assert '' in zf.read("[Content_Types].xml").decode( - "utf-8" - ) + assert zf.read("source.pdf") == b"%PDF-1.7\n" + assert 'name="report.pdf"' in zf.read("source-metadata.xml").decode("utf-8") + assert 'Target="source.pdf"' in zf.read("_rels/.rels").decode("utf-8") - incomplete = runner.invoke(app, args) - assert incomplete.exit_code == 1 and "must be given together" in incomplete.output + unknown_type = runner.invoke(app, [*args[:-1], "report.xyz"]) + assert unknown_type.exit_code == 1 and "No content type known" in unknown_type.output + + +def test_cli_pack_reuses_an_already_packed_source(tmp_path): + demo = Path(__file__).resolve().parents[1] / "examples" / "archive-demo" + out = tmp_path / "out.dclx" + args = ["pack", str(demo / "document.xml"), "-o", str(out), "--audio-dir", str(demo / "audio")] + + source = ["--source", str(demo / "audio" / "1.wav")] + + result = runner.invoke(app, [*args, *source, "--keep-source-name"]) + assert result.exit_code == 0, result.output + with zipfile.ZipFile(out) as zf: + assert 'Target="audio/1.wav"' in zf.read("_rels/.rels").decode("utf-8") + assert "source.wav" not in zf.namelist() + assert 'name="1.wav"' in zf.read("source-metadata.xml").decode("utf-8") + + both = runner.invoke(app, [*args, *source, "--keep-source-name", "--source-name", "x.wav"]) + assert both.exit_code == 1 and "mutually exclusive" in both.output + no_source = runner.invoke(app, [*args, "--keep-source-name"]) + assert no_source.exit_code == 1 and "needs --source" in no_source.output diff --git a/tests/test_migration.py b/tests/test_migration.py index 8e10aac..b243f93 100644 --- a/tests/test_migration.py +++ b/tests/test_migration.py @@ -526,6 +526,42 @@ def drop_first_track(root, changes): } +def test_package_relationships_and_overrides_follow_renamed_media(tmp_path, monkeypatch): + def drop_first_track(root, changes): + track = root.find(f"{{{NS}}}track") + changes.record("dropped", track, "dropped") + root.remove(track) + + _with_unreleased_head(monkeypatch, drop_first_track) + source = "http://doclang.ai/ns/package/2026/relationships/source" + rels = ( + '' + f'' + ) + content_types = ( + '' + '' + '' + ) + members = { + "_rels/.rels": rels.encode(), + "[Content_Types].xml": content_types.encode(), + "audio/1.mp3": b"a1", # the source, and the removed track's media + "audio/2.wav": b"a2", + } + out = tmp_path / "out.dclx" + result = migrate(_archive(tmp_path, f"{TRACK}{TRACK}", members, version=NEWEST), to=NEXT, output=out) + + assert [(c["kind"], c["location"]) for c in result.changes][1:] == [ + ("renamed", "audio/1.mp3"), # kept as the source, out of the tracks' way + ("renamed", "audio/2.wav"), + ] + written = _members(out) + assert (written["source.mp3"], written["audio/1.wav"]) == (b"a1", b"a2") + assert 'Target="/source.mp3"' in written["_rels/.rels"].decode() + assert 'PartName="/audio/1.wav"' in written["[Content_Types].xml"].decode() + + def test_strict_fails_on_the_dropped_elements_not_on_orphaned_members(tmp_path): out = tmp_path / "out.dclx" with pytest.raises(MigrationError, match="would change 1 part") as info: diff --git a/tests/test_packaging.py b/tests/test_packaging.py index 5ef9333..8c8d1a7 100644 --- a/tests/test_packaging.py +++ b/tests/test_packaging.py @@ -9,6 +9,7 @@ import pytest from doclang import PackagingError, ValidationError, pack +from doclang._packaging import _check_archive REPO_ROOT = Path(__file__).resolve().parents[1] ARCHIVE_DEMO = REPO_ROOT / "examples" / "archive-demo" @@ -45,57 +46,193 @@ def test_pack_markup_only_explicit_output(tmp_path: Path) -> None: assert "document.xml" in members +SOURCE_RELATIONSHIP = "http://doclang.ai/ns/package/2026/relationships/source" +SOURCE_METADATA_RELATIONSHIP = "http://doclang.ai/ns/package/2026/relationships/source-metadata" + + +def _content_types(archive_path: Path) -> tuple[dict[str, str], dict[str, str]]: + """The ```` content types by extension and the ```` ones by part name.""" + with zipfile.ZipFile(archive_path) as archive: + content_types = ElementTree.fromstring(archive.read("[Content_Types].xml")) + defaults = {e.attrib["Extension"]: e.attrib["ContentType"] for e in content_types if e.tag.endswith("Default")} + overrides = {e.attrib["PartName"]: e.attrib["ContentType"] for e in content_types if e.tag.endswith("Override")} + return defaults, overrides + + +def _relationships(archive_path: Path) -> dict[str, str]: + """The targets of the package relationships by type.""" + with zipfile.ZipFile(archive_path) as archive: + rels = ElementTree.fromstring(archive.read("_rels/.rels")) + return {e.attrib["Type"]: e.attrib["Target"] for e in rels} + + @pytest.mark.parametrize("from_path", [False, True]) @pytest.mark.parametrize("original", [b"%PDF-1.7\n\x00\xff\n", b""]) -def test_pack_with_original_source(tmp_path: Path, from_path: bool, original: bytes) -> None: +def test_pack_source_is_stored_with_the_extension_of_its_name(tmp_path: Path, from_path: bool, original: bytes) -> None: source_path = tmp_path / "original.pdf" source_path.write_bytes(original) - source = source_path if from_path else original output = tmp_path / "with-source.dclx" pack( ARCHIVE_DEMO / "document.xml", output=output, - source=source, + source=source_path if from_path else original, + source_name=None if from_path else "original.pdf", source_mimetype="application/pdf", ) with zipfile.ZipFile(output) as archive: - assert archive.read("source") == original - assert not any(name.startswith("source/") for name in archive.namelist()) - assert _overrides(output)["/source"] == "application/pdf" + assert archive.read("source.pdf") == original + defaults, overrides = _content_types(output) + assert defaults["pdf"] == "application/pdf" and "/source.pdf" not in overrides + assert _relationships(output)[SOURCE_RELATIONSHIP] == "source.pdf" + assert _check_archive(output, None) == ([], []) -def _overrides(archive_path: Path) -> dict[str, str]: - with zipfile.ZipFile(archive_path) as archive: - content_types = ElementTree.fromstring(archive.read("[Content_Types].xml")) - return { - element.attrib["PartName"]: element.attrib["ContentType"] - for element in content_types - if element.tag.endswith("Override") - } +def test_pack_source_with_a_known_extension_needs_no_mimetype(tmp_path: Path) -> None: + recording = tmp_path / "Episode 12.MP3" + recording.write_bytes(b"mp3") + output = tmp_path / "out.dclx" + pack(ARCHIVE_DEMO / "document.xml", output=output, source=recording) -def test_pack_escapes_source_mimetype(tmp_path: Path) -> None: - output = tmp_path / "escaped.dclx" - mimetype = "application/x-a&b" + assert "source.mp3" in _zip_members(output) + defaults, overrides = _content_types(output) + assert defaults["mp3"] == "audio/mpeg" and "/source.mp3" not in overrides + assert SOURCE_METADATA_RELATIONSHIP not in _relationships(output) # the original name is opt-in + assert "source-metadata.xml" not in _zip_members(output) - pack(ARCHIVE_DEMO / "document.xml", output=output, source=b"data", source_mimetype=mimetype) - assert _overrides(output)["/source"] == mimetype +@pytest.mark.parametrize("name", [None, "notes", "archive.tar~", ".bashrc", "x.rels"]) +def test_pack_source_without_a_reliable_extension_gets_an_override(tmp_path: Path, name: str | None) -> None: + output = tmp_path / "out.dclx" + + pack(ARCHIVE_DEMO / "document.xml", output=output, source=b"data", source_name=name, source_mimetype="text/plain") + + assert "source" in _zip_members(output) + assert _content_types(output)[1]["/source"] == "text/plain" + assert _relationships(output)[SOURCE_RELATIONSHIP] == "source" + assert _check_archive(output, None) == ([], []) + + +def test_pack_source_mimetype_differing_from_the_default_gets_an_override(tmp_path: Path) -> None: + output = tmp_path / "out.dclx" + pack(ARCHIVE_DEMO / "document.xml", output=output, source=b"v", source_name="clip.ogg", source_mimetype="video/ogg") + + defaults, overrides = _content_types(output) + assert overrides["/source.ogg"] == "video/ogg" and "ogg" not in defaults # no part left for the default + + +def test_pack_declares_only_the_extensions_present(tmp_path: Path) -> None: + output = tmp_path / "out.dclx" + + pack( + ARCHIVE_DEMO / "document.xml", output=output, audio=ARCHIVE_DEMO / "audio", source=b"%PDF", source_name="a.pdf" + ) + + defaults, _ = _content_types(output) + assert set(defaults) == {"rels", "wav", "pdf"} + + +def test_pack_source_without_a_content_type_is_refused(tmp_path: Path) -> None: + output = tmp_path / "out.dclx" + with pytest.raises(PackagingError, match="No content type known"): + pack(ARCHIVE_DEMO / "document.xml", output=output, source=b"data") + with pytest.raises(PackagingError, match="No content type known"): + pack(ARCHIVE_DEMO / "document.xml", output=output, source=b"data", source_name="report.xyz") + assert not output.exists() -def test_pack_rejects_incomplete_original_source(tmp_path: Path) -> None: + +def test_pack_source_name_is_recorded_in_a_descriptor(tmp_path: Path) -> None: + original = tmp_path / "upload-3f2a.bin" + original.write_bytes(b"%PDF") + output = tmp_path / "out.dclx" + + pack( + ARCHIVE_DEMO / "document.xml", + output=output, + source=original, + source_name='Q3 "final" & co.pdf', + source_mimetype="application/pdf", + ) + + relationships = _relationships(output) + assert relationships[SOURCE_RELATIONSHIP] == "source.pdf" # the extension of the original name + assert relationships[SOURCE_METADATA_RELATIONSHIP] == "source-metadata.xml" + with zipfile.ZipFile(output) as archive: + descriptor = ElementTree.fromstring(archive.read("source-metadata.xml")) + assert descriptor.tag == "{http://doclang.ai/ns/package/2026/source-metadata}source" + assert descriptor.attrib == {"name": 'Q3 "final" & co.pdf'} + assert _content_types(output)[1]["/source-metadata.xml"] == "application/vnd.doclang.source-metadata+xml" + assert _check_archive(output, None) == ([], []) + + +@pytest.mark.parametrize( + ("name", "part"), + [ + ("backup.tar.gz", "source.tar.gz"), + ("Report.Final.PDF", "source.final.pdf"), + ("a.b.c.gz", "source.c.gz"), # at most two extensions + ("x.tar~.gz", "source.gz"), # only reliable ones + ("tar.gz", "source.gz"), # the stem is not an extension + ("data.xml", "source.xml"), # no clash with the descriptor + ], +) +def test_pack_source_keeps_up_to_two_extensions(tmp_path: Path, name: str, part: str) -> None: + output = tmp_path / "out.dclx" + + pack(ARCHIVE_DEMO / "document.xml", output=output, source=b"x", source_name=name, source_mimetype="text/x-test") + + relationships = _relationships(output) + assert relationships[SOURCE_RELATIONSHIP] == part + assert relationships[SOURCE_METADATA_RELATIONSHIP] == "source-metadata.xml" + defaults, overrides = _content_types(output) + assert defaults.get(part.rsplit(".", 1)[1]) == "text/x-test" or overrides.get(f"/{part}") == "text/x-test" + assert _check_archive(output, None) == ([], []) + + +@pytest.mark.parametrize("as_mapping", [False, True]) +def test_pack_reuses_a_source_file_already_packed(tmp_path: Path, as_mapping: bool) -> None: + output = tmp_path / "out.dclx" + recording = ARCHIVE_DEMO / "audio" / "1.wav" + + pack( + ARCHIVE_DEMO / "document.xml", + output=output, + audio={1: recording} if as_mapping else ARCHIVE_DEMO / "audio", + source=recording, + source_name="episode-12.wav", + ) + + assert _relationships(output)[SOURCE_RELATIONSHIP] == "audio/1.wav" + assert "source.wav" not in _zip_members(output) # no second copy + assert _check_archive(output, None) == ([], []) + + +def test_pack_rejects_inconsistent_source_options(tmp_path: Path) -> None: document = ARCHIVE_DEMO / "document.xml" - output = tmp_path / "incomplete.dclx" + output = tmp_path / "bad.dclx" - with pytest.raises(PackagingError, match="provided together"): - pack(document, output=output, source=b"") - with pytest.raises(PackagingError, match="provided together"): + with pytest.raises(PackagingError, match="need source"): pack(document, output=output, source_mimetype="application/pdf") + with pytest.raises(PackagingError, match="need source"): + pack(document, output=output, source_name="a.pdf") + for name in ["", "dir/a.pdf", "a\nb.pdf"]: + with pytest.raises(PackagingError, match="Invalid source file name"): + pack(document, output=output, source=b"", source_name=name, source_mimetype="application/pdf") assert not output.exists() +def test_pack_escapes_source_mimetype(tmp_path: Path) -> None: + output = tmp_path / "escaped.dclx" + mimetype = "application/x-a&b" + + pack(ARCHIVE_DEMO / "document.xml", output=output, source=b"data", source_mimetype=mimetype) + + assert _content_types(output)[1]["/source"] == mimetype + + def test_pack_rejects_invalid_source_mimetype(tmp_path: Path) -> None: output = tmp_path / "invalid-mimetype.dclx" diff --git a/tests/test_validation.py b/tests/test_validation.py index d5cc8db..ae60070 100644 --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -663,3 +663,70 @@ def test_reference_rules_apply_from_0_10(tmp_path: Path, version: str, applies: document = _REFERENCING.format(version=f' version="{version}"') found = _warnings_and_errors(_archive(tmp_path, {"assets/b.png": b""}, document=document)) assert (found != ([], [])) is applies + + +# The source rules apply from 0.10. +_SOURCE_DOCUMENT = _DOCUMENT.replace('version="0.9"', 'version="0.10"') +_DESCRIPTOR = b'' +_DESCRIPTOR_TYPE = ( + '' +) + + +@pytest.mark.filterwarnings("ignore:No schema for declared DocLang version 0.10") +@pytest.mark.parametrize( + "members", + [ + {"_rels/.rels": _rels(("source", "source.mp3")), "source.mp3": b""}, + {"_rels/.rels": _rels(("source", "/audio/1.mp3")), "audio/1.mp3": b""}, # an existing part, no second copy + { + "_rels/.rels": _rels(("source", "source")), + "source": b"%PDF", + "[Content_Types].xml": _CONTENT_TYPES.replace( + "", '' + ), + }, + { + "_rels/.rels": _rels(("source", "source.mp3"), ("source-metadata", "source-metadata.xml")), + "source.mp3": b"", + "source-metadata.xml": _DESCRIPTOR, + "[Content_Types].xml": _CONTENT_TYPES.replace("", _DESCRIPTOR_TYPE), + }, + ], +) +def test_valid_archive_with_source(tmp_path: Path, members): + assert _archive_errors(_archive(tmp_path, members, document=_SOURCE_DOCUMENT)) == [] + + +@pytest.mark.filterwarnings("ignore:No schema for declared DocLang version 0.10") +@pytest.mark.parametrize( + ("members", "location", "message"), + [ + ({"_rels/.rels": _rels(("source", "source.mp3"))}, "_rels/.rels", "The source part 'source.mp3' is missing"), + ({"_rels/.rels": _rels(("source", "source.pdf")), "source.pdf": b""}, "source.pdf", "No content type"), + ( + {"_rels/.rels": _rels(("source", "http://example.com/a.pdf"))}, + "_rels/.rels", + "must target a part of the archive", + ), + ( + {"_rels/.rels": _rels(("source", "a.mp3"), ("source", "b.mp3")), "a.mp3": b"", "b.mp3": b""}, + "_rels/.rels", + "More than one http://doclang.ai/ns/package/2026/relationships/source relationship", + ), + ( + {"_rels/.rels": _rels(("source-metadata", "s.mp3")), "s.mp3": _DESCRIPTOR}, + "_rels/.rels", + "source-metadata relationship without a source relationship", + ), + ( + {"_rels/.rels": _rels(("source", "a.mp3"), ("source-metadata", "s.mp3")), "a.mp3": b"", "s.mp3": b""}, + "s.mp3", + "The root element must be source", + ), + ], +) +def test_invalid_archive_with_source(tmp_path: Path, members, location, message): + errors = _archive_errors(_archive(tmp_path, members, document=_SOURCE_DOCUMENT)) + assert [e[0] for e in errors] == [location] + assert message in errors[0][1] diff --git a/utils/validate_markdown_snippets.py b/utils/validate_markdown_snippets.py index d54653c..f281509 100644 --- a/utils/validate_markdown_snippets.py +++ b/utils/validate_markdown_snippets.py @@ -25,6 +25,7 @@ from pathlib import Path from doclang import ValidationError, validate +from doclang.utils import _DOCLANG_NAMESPACE _XML_FENCE_RE = re.compile(r"^```xml\n(.*?)^```", re.MULTILINE | re.DOTALL) _TOP_LEVEL_ELLIPSIS_RE = re.compile(r"^(\s*)\.\.\.(\s*)$") @@ -34,6 +35,7 @@ r"^\s*(?:<\?xml[^?]*\?\>\s*)?<(Types|Relationships)\b", re.IGNORECASE, ) +_ROOT_NAMESPACE_RE = re.compile(r"^\s*(?:<\?xml[^?]*\?\>\s*)?<[\w.-]+\s[^>]*?\bxmlns=\"([^\"]*)\"") _DEFAULT_MARKDOWN_FILES = ( Path("spec.md"), @@ -98,7 +100,8 @@ def _replace_top_level_ellipsis(content: str) -> str: def _is_skippable_snippet(content: str) -> bool: """Return True for XML examples that are not DocLang document fragments.""" - return bool(_NON_DOCLANG_ROOT_RE.match(content)) + namespace = _ROOT_NAMESPACE_RE.match(content) + return bool(_NON_DOCLANG_ROOT_RE.match(content)) or (namespace is not None and namespace[1] != _DOCLANG_NAMESPACE) def _prepare_snippet_for_validation(content: str) -> str: