Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions doclang/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
```

Expand Down
357 changes: 282 additions & 75 deletions doclang/_packaging.py

Large diffs are not rendered by default.

48 changes: 35 additions & 13 deletions doclang/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 <track> elements of the document, and <src>
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 <track>
elements of the document, and <src> URIs that resolve to no part. Parts
that nothing accounts for are warned about.

Examples:

Expand Down Expand Up @@ -324,15 +324,28 @@ 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.<ext> (or source without an extension), "
"unless it is already packed, e.g. as --audio"
),
exists=True,
file_okay=True,
dir_okay=False,
),
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)"),
Expand All @@ -345,9 +358,11 @@ def pack(
--audio, --video-dir, --video) are placed under audio/ and video/ as
{N}.{ext} for the Nth <track>. 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.<ext>
(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 <document>.dclx next to the input file.

Expand All @@ -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)
Expand All @@ -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")

Expand Down Expand Up @@ -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:
Expand Down
15 changes: 10 additions & 5 deletions doclang/migration/_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -133,14 +135,15 @@ def _migrate(
path: Path,
members: Sequence[str] | None,
*,
relationship_targets: Collection[str] = (),
to: str,
source: str | None,
strict: bool,
input_validation: str,
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)
Expand Down Expand Up @@ -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:
Expand Down
31 changes: 26 additions & 5 deletions doclang/migration/_archive.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@
whole-track media (``audio/{N}.*``, ``video/{N}.*``, aligned with the N-th ``<track>``) and assets referenced
(via ``<src uri>``) 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.<ext>``.
"""

from __future__ import annotations

from collections.abc import Iterable
from collections.abc import Collection, Iterable

from lxml import etree

Expand All @@ -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.<ext>`` 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]
Expand All @@ -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 <track> {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 <track> {match[2]}")
elif new is None:
Expand All @@ -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
22 changes: 18 additions & 4 deletions doclang/packaging.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.<ext>``, 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
Expand All @@ -68,5 +81,6 @@ def pack(
video=video,
source=source,
source_mimetype=source_mimetype,
source_name=source_name,
validate=validate,
)
11 changes: 6 additions & 5 deletions doclang/validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 ``<track>`` elements of the
document, and ``<src>`` 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 ``<track>`` elements of the document, and ``<src>`` 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
Expand Down
Loading
Loading