adflux 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
adflux/__init__.py ADDED
@@ -0,0 +1,25 @@
1
+ """adflux: pure-Python Markdown ↔ Atlassian Document Format (ADF) converter."""
2
+
3
+ from adflux.api import convert, inspect_ast, list_formats, validate
4
+ from adflux.errors import (
5
+ AdfluxError,
6
+ InvalidADFError,
7
+ MappingError,
8
+ UnrepresentableNodeError,
9
+ UnsupportedFormatError,
10
+ )
11
+
12
+ __version__ = "0.1.0"
13
+
14
+ __all__ = [
15
+ "AdfluxError",
16
+ "InvalidADFError",
17
+ "MappingError",
18
+ "UnrepresentableNodeError",
19
+ "UnsupportedFormatError",
20
+ "__version__",
21
+ "convert",
22
+ "inspect_ast",
23
+ "list_formats",
24
+ "validate",
25
+ ]
adflux/api.py ADDED
@@ -0,0 +1,82 @@
1
+ """High-level public API for adflux.
2
+
3
+ The :func:`convert` function is the library's primary entry point. It dispatches
4
+ to the reader/writer registry populated in :mod:`adflux.formats`.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import TYPE_CHECKING, Any
10
+
11
+ from adflux.errors import UnsupportedFormatError
12
+ from adflux.formats import get_reader, get_writer, registered_formats
13
+ from adflux.profiles import Profile, resolve_profile
14
+
15
+ if TYPE_CHECKING:
16
+ import panflute as pf
17
+
18
+
19
+ def convert(
20
+ source: str | bytes,
21
+ *,
22
+ src: str,
23
+ dst: str,
24
+ profile: str | Profile = "strict-adf",
25
+ options: dict[str, Any] | None = None,
26
+ ) -> str:
27
+ """Convert ``source`` from format ``src`` to format ``dst``.
28
+
29
+ Args:
30
+ source: Input document (text for Markdown, JSON text for ADF).
31
+ src: Source-format identifier (``"md"`` / ``"markdown"`` or ``"adf"``).
32
+ dst: Target-format identifier.
33
+ profile: Fidelity profile name or :class:`Profile` instance.
34
+ options: Optional per-format options, forwarded to reader/writer.
35
+
36
+ Returns:
37
+ Converted document as a string.
38
+
39
+ Raises:
40
+ UnsupportedFormatError: If ``src`` or ``dst`` is not registered.
41
+ InvalidADFError: If ADF input fails schema validation.
42
+ UnrepresentableNodeError: When ``fail-loud`` profile cannot represent a node.
43
+ """
44
+ opts = options or {}
45
+ resolved = resolve_profile(profile)
46
+ reader = get_reader(src)
47
+ writer = get_writer(dst)
48
+ doc: pf.Doc = reader(source, profile=resolved, options=opts)
49
+ return writer(doc, profile=resolved, options=opts)
50
+
51
+
52
+ def validate(source: str | bytes, *, fmt: str) -> None:
53
+ """Validate ``source`` as format ``fmt``. Raises on failure.
54
+
55
+ Currently meaningful for ``fmt="adf"`` (JSON-schema validation). Other
56
+ formats are accepted unconditionally.
57
+ """
58
+ if fmt not in registered_formats():
59
+ raise UnsupportedFormatError(fmt)
60
+ if fmt == "adf":
61
+ from adflux.formats.adf.schema import validate_adf
62
+
63
+ validate_adf(source)
64
+
65
+
66
+ def inspect_ast(source: str | bytes, *, src: str) -> str:
67
+ """Parse ``source`` and return the internal IR as pretty-printed JSON."""
68
+ import io
69
+ import json as _json
70
+
71
+ import panflute as pf
72
+
73
+ reader = get_reader(src)
74
+ doc = reader(source, profile=resolve_profile("strict-adf"), options={})
75
+ buffer = io.StringIO()
76
+ pf.dump(doc, buffer)
77
+ return _json.dumps(_json.loads(buffer.getvalue()), indent=2)
78
+
79
+
80
+ def list_formats() -> list[str]:
81
+ """Return the list of registered format identifiers, sorted."""
82
+ return sorted(registered_formats())
adflux/cli.py ADDED
@@ -0,0 +1,129 @@
1
+ """Typer-based CLI for adflux.
2
+
3
+ Subcommands:
4
+
5
+ * ``adflux convert`` — convert between formats.
6
+ * ``adflux validate`` — validate a document (currently only ADF).
7
+ * ``adflux inspect-ast`` — dump the internal IR as JSON.
8
+ * ``adflux list-formats`` — list registered formats and profiles.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import sys
14
+ from pathlib import Path
15
+ from typing import Annotated
16
+
17
+ import typer
18
+
19
+ from adflux.api import convert as api_convert
20
+ from adflux.api import inspect_ast as api_inspect_ast
21
+ from adflux.api import list_formats as api_list_formats
22
+ from adflux.api import validate as api_validate
23
+ from adflux.errors import AdfluxError
24
+ from adflux.logging import configure_logging
25
+ from adflux.profiles import all_profile_names
26
+
27
+ app = typer.Typer(
28
+ name="adflux",
29
+ help="Pure-Python Markdown ↔ Atlassian Document Format (ADF) converter.",
30
+ no_args_is_help=True,
31
+ add_completion=False,
32
+ )
33
+
34
+
35
+ def _read_input(input_path: Path | None) -> str:
36
+ if input_path is None:
37
+ return sys.stdin.read()
38
+ return input_path.read_text(encoding="utf-8")
39
+
40
+
41
+ def _write_output(text: str, output_path: Path | None) -> None:
42
+ if output_path is None:
43
+ sys.stdout.write(text)
44
+ if not text.endswith("\n"):
45
+ sys.stdout.write("\n")
46
+ else:
47
+ output_path.write_text(text, encoding="utf-8")
48
+
49
+
50
+ @app.command("convert")
51
+ def convert_cmd(
52
+ input_path: Annotated[
53
+ Path | None,
54
+ typer.Argument(exists=True, dir_okay=False, readable=True, help="Input file (or stdin)."),
55
+ ] = None,
56
+ src: Annotated[str, typer.Option("--from", "-f", help="Source format.")] = "md",
57
+ dst: Annotated[str, typer.Option("--to", "-t", help="Target format.")] = "adf",
58
+ profile: Annotated[
59
+ str,
60
+ typer.Option(
61
+ "--profile",
62
+ "-p",
63
+ help=f"Fidelity profile: {', '.join(all_profile_names())}.",
64
+ ),
65
+ ] = "strict-adf",
66
+ output: Annotated[
67
+ Path | None, typer.Option("--output", "-o", help="Output file (or stdout).")
68
+ ] = None,
69
+ verbose: Annotated[bool, typer.Option("--verbose", "-v", help="Verbose logging.")] = False,
70
+ ) -> None:
71
+ """Convert INPUT_PATH (or stdin) from ``--from`` to ``--to``."""
72
+ configure_logging(level=10 if verbose else 20)
73
+ try:
74
+ source = _read_input(input_path)
75
+ result = api_convert(source, src=src, dst=dst, profile=profile)
76
+ _write_output(result, output)
77
+ except AdfluxError as exc:
78
+ typer.secho(f"error: {exc}", fg=typer.colors.RED, err=True)
79
+ raise typer.Exit(code=2) from exc
80
+
81
+
82
+ @app.command("validate")
83
+ def validate_cmd(
84
+ input_path: Annotated[
85
+ Path | None,
86
+ typer.Argument(exists=True, dir_okay=False, readable=True, help="Input file (or stdin)."),
87
+ ] = None,
88
+ fmt: Annotated[str, typer.Option("--format", "-f", help="Format to validate.")] = "adf",
89
+ ) -> None:
90
+ """Validate a document (currently only meaningful for ADF)."""
91
+ try:
92
+ source = _read_input(input_path)
93
+ api_validate(source, fmt=fmt)
94
+ typer.secho("ok", fg=typer.colors.GREEN)
95
+ except AdfluxError as exc:
96
+ typer.secho(f"invalid: {exc}", fg=typer.colors.RED, err=True)
97
+ raise typer.Exit(code=1) from exc
98
+
99
+
100
+ @app.command("inspect-ast")
101
+ def inspect_ast_cmd(
102
+ input_path: Annotated[
103
+ Path | None,
104
+ typer.Argument(exists=True, dir_okay=False, readable=True, help="Input file (or stdin)."),
105
+ ] = None,
106
+ src: Annotated[str, typer.Option("--from", "-f", help="Source format.")] = "md",
107
+ ) -> None:
108
+ """Parse INPUT_PATH with the ``--from`` reader and dump the internal IR as JSON."""
109
+ try:
110
+ source = _read_input(input_path)
111
+ typer.echo(api_inspect_ast(source, src=src))
112
+ except AdfluxError as exc:
113
+ typer.secho(f"error: {exc}", fg=typer.colors.RED, err=True)
114
+ raise typer.Exit(code=2) from exc
115
+
116
+
117
+ @app.command("list-formats")
118
+ def list_formats_cmd() -> None:
119
+ """List registered formats and fidelity profiles."""
120
+ typer.echo("formats:")
121
+ for fmt in api_list_formats():
122
+ typer.echo(f" - {fmt}")
123
+ typer.echo("profiles:")
124
+ for name in all_profile_names():
125
+ typer.echo(f" - {name}")
126
+
127
+
128
+ if __name__ == "__main__":
129
+ app()
adflux/errors.py ADDED
@@ -0,0 +1,55 @@
1
+ """Typed exception hierarchy for adflux.
2
+
3
+ All public exceptions inherit from :class:`AdfluxError` to allow callers to
4
+ catch the whole library's errors with a single ``except`` clause.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+
10
+ class AdfluxError(Exception):
11
+ """Base class for all adflux errors."""
12
+
13
+
14
+ class UnsupportedFormatError(AdfluxError):
15
+ """Raised when a requested source or target format is not registered."""
16
+
17
+ def __init__(self, fmt: str, *, role: str = "format") -> None:
18
+ super().__init__(f"Unsupported {role}: {fmt!r}")
19
+ self.fmt = fmt
20
+ self.role = role
21
+
22
+
23
+ class InvalidADFError(AdfluxError):
24
+ """Raised when an ADF document fails JSON-schema validation.
25
+
26
+ Attributes:
27
+ pointer: JSON pointer into the offending node, if available.
28
+ validator_errors: Underlying ``jsonschema`` errors.
29
+ """
30
+
31
+ def __init__(
32
+ self,
33
+ message: str,
34
+ *,
35
+ pointer: str | None = None,
36
+ validator_errors: list[object] | None = None,
37
+ ) -> None:
38
+ super().__init__(message)
39
+ self.pointer = pointer
40
+ self.validator_errors = validator_errors or []
41
+
42
+
43
+ class MappingError(AdfluxError):
44
+ """Raised when the ADF YAML mapping table is malformed or incomplete."""
45
+
46
+
47
+ class UnrepresentableNodeError(AdfluxError):
48
+ """Raised (in ``fail-loud`` profile) when a node cannot be represented in the target."""
49
+
50
+ def __init__(self, node_type: str, target_format: str) -> None:
51
+ super().__init__(
52
+ f"Node type {node_type!r} has no representation in target format {target_format!r}"
53
+ )
54
+ self.node_type = node_type
55
+ self.target_format = target_format
@@ -0,0 +1,74 @@
1
+ """Reader/writer registry and format auto-registration.
2
+
3
+ Each format module calls :func:`register_reader` and :func:`register_writer` at
4
+ import time. Importing :mod:`adflux.formats` triggers registration of all
5
+ built-in formats.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Callable
11
+ from typing import TYPE_CHECKING, Any
12
+
13
+ from adflux.errors import UnsupportedFormatError
14
+
15
+ if TYPE_CHECKING:
16
+ import panflute as pf
17
+
18
+ from adflux.profiles import Profile
19
+
20
+ Reader = Callable[[str | bytes, "Profile", dict[str, Any]], "pf.Doc"]
21
+ Writer = Callable[["pf.Doc", "Profile", dict[str, Any]], str]
22
+
23
+ _READERS: dict[str, Reader] = {}
24
+ _WRITERS: dict[str, Writer] = {}
25
+
26
+
27
+ def register_reader(fmt: str, reader: Reader) -> None:
28
+ """Register a reader function for format ``fmt``."""
29
+ _READERS[fmt] = reader
30
+
31
+
32
+ def register_writer(fmt: str, writer: Writer) -> None:
33
+ """Register a writer function for format ``fmt``."""
34
+ _WRITERS[fmt] = writer
35
+
36
+
37
+ def _wrap_reader(fn: Reader) -> Callable[..., pf.Doc]:
38
+ def _call(source: str | bytes, *, profile: Profile, options: dict[str, Any]) -> pf.Doc:
39
+ return fn(source, profile, options)
40
+
41
+ return _call
42
+
43
+
44
+ def _wrap_writer(fn: Writer) -> Callable[..., str]:
45
+ def _call(doc: pf.Doc, *, profile: Profile, options: dict[str, Any]) -> str:
46
+ return fn(doc, profile, options)
47
+
48
+ return _call
49
+
50
+
51
+ def get_reader(fmt: str) -> Callable[..., pf.Doc]:
52
+ """Return the kwargs-based reader callable for format ``fmt``."""
53
+ try:
54
+ return _wrap_reader(_READERS[fmt])
55
+ except KeyError as exc:
56
+ raise UnsupportedFormatError(fmt, role="source format") from exc
57
+
58
+
59
+ def get_writer(fmt: str) -> Callable[..., str]:
60
+ """Return the kwargs-based writer callable for format ``fmt``."""
61
+ try:
62
+ return _wrap_writer(_WRITERS[fmt])
63
+ except KeyError as exc:
64
+ raise UnsupportedFormatError(fmt, role="target format") from exc
65
+
66
+
67
+ def registered_formats() -> set[str]:
68
+ """Return the set of formats that have at least a reader or a writer."""
69
+ return set(_READERS) | set(_WRITERS)
70
+
71
+
72
+ # Auto-register built-in formats. Keep imports at bottom to avoid cycles.
73
+ from adflux.formats import adf as _adf # noqa: E402,F401
74
+ from adflux.formats import markdown as _markdown # noqa: E402,F401
@@ -0,0 +1,15 @@
1
+ """ADF (Atlassian Document Format) reader/writer registration.
2
+
3
+ The reader and writer implementations live in :mod:`adflux.formats.adf.reader`
4
+ and :mod:`adflux.formats.adf.writer`. This module wires them into the format
5
+ registry under the ``"adf"`` identifier.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from adflux.formats import register_reader, register_writer
11
+ from adflux.formats.adf.reader import read_adf
12
+ from adflux.formats.adf.writer import write_adf
13
+
14
+ register_reader("adf", read_adf)
15
+ register_writer("adf", write_adf)
@@ -0,0 +1,137 @@
1
+ """YAML-driven ADF node-mapping table.
2
+
3
+ The mapping is a simple declarative registry:
4
+
5
+ .. code-block:: yaml
6
+
7
+ version: 1
8
+ nodes:
9
+ panel:
10
+ pandoc: Div
11
+ kind: block
12
+ envelope_class: adf-panel
13
+ attrs: { panelType: string }
14
+ status:
15
+ pandoc: Span
16
+ kind: inline
17
+ envelope_class: adf-status
18
+ attrs: { text: string, color: string, localId: string }
19
+
20
+ The reader/writer don't interpret every field — several are advisory
21
+ (``asciidoc_native``, ``attrs`` schema) and reserved for future post-
22
+ processors and validators.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ from dataclasses import dataclass, field
28
+ from pathlib import Path
29
+ from typing import Any, Literal
30
+
31
+ import yaml
32
+
33
+ from adflux.errors import MappingError
34
+
35
+ _DEFAULT_MAPPING_PATH = Path(__file__).with_name("mapping.yaml")
36
+
37
+
38
+ @dataclass(slots=True, frozen=True)
39
+ class MappingEntry:
40
+ """One ADF node type's mapping metadata."""
41
+
42
+ node_type: str
43
+ pandoc: str
44
+ """Pandoc element name, e.g. ``"Div"``, ``"Span"``, ``"Image"``."""
45
+ kind: Literal["block", "inline"]
46
+ envelope_class: str | None = None
47
+ attrs: dict[str, str] = field(default_factory=dict)
48
+ children: list[str] = field(default_factory=list)
49
+ asciidoc_native: str | None = None
50
+ content_kind: Literal["block", "inline", "none"] = "block"
51
+ """Shape of the node's ``content`` array in ADF JSON.
52
+
53
+ ``block`` — standard (paragraph, heading, nested blocks).
54
+ ``inline`` — direct inline text runs (taskItem, decisionItem).
55
+ ``none`` — the node has no content array at all (bare extensions).
56
+ """
57
+
58
+
59
+ class MappingTable:
60
+ """Lookup wrapper over a parsed mapping.yaml."""
61
+
62
+ def __init__(self, entries: dict[str, MappingEntry], version: int) -> None:
63
+ self._entries = entries
64
+ self.version = version
65
+
66
+ def get(self, node_type: str | None) -> MappingEntry | None:
67
+ """Return the :class:`MappingEntry` for ``node_type`` or None."""
68
+ if node_type is None:
69
+ return None
70
+ return self._entries.get(node_type)
71
+
72
+ def __contains__(self, node_type: str) -> bool:
73
+ return node_type in self._entries
74
+
75
+ def names(self) -> list[str]:
76
+ """Return all mapped ADF node type names."""
77
+ return sorted(self._entries)
78
+
79
+
80
+ def load_mapping(path: Path | str) -> MappingTable:
81
+ """Load and validate a mapping YAML file."""
82
+ p = Path(path)
83
+ try:
84
+ raw = yaml.safe_load(p.read_text(encoding="utf-8"))
85
+ except FileNotFoundError as exc:
86
+ raise MappingError(f"mapping file not found: {p}") from exc
87
+ except yaml.YAMLError as exc:
88
+ raise MappingError(f"mapping YAML parse error: {exc}") from exc
89
+ return _parse_mapping(raw)
90
+
91
+
92
+ def load_default_mapping() -> MappingTable:
93
+ """Load the bundled default mapping table."""
94
+ return load_mapping(_DEFAULT_MAPPING_PATH)
95
+
96
+
97
+ def _parse_mapping(raw: Any) -> MappingTable:
98
+ if not isinstance(raw, dict):
99
+ raise MappingError("mapping root must be a mapping")
100
+ version = raw.get("version")
101
+ if not isinstance(version, int):
102
+ raise MappingError("mapping.version (int) is required")
103
+ nodes = raw.get("nodes")
104
+ if not isinstance(nodes, dict):
105
+ raise MappingError("mapping.nodes (mapping) is required")
106
+
107
+ entries: dict[str, MappingEntry] = {}
108
+ for name, spec in nodes.items():
109
+ if not isinstance(spec, dict):
110
+ raise MappingError(f"node {name!r} must be a mapping")
111
+ kind = spec.get("kind")
112
+ if kind not in ("block", "inline"):
113
+ raise MappingError(f"node {name!r}: kind must be 'block' or 'inline'")
114
+ pandoc = spec.get("pandoc")
115
+ if not isinstance(pandoc, str):
116
+ raise MappingError(f"node {name!r}: pandoc (str) is required")
117
+ attrs = spec.get("attrs") or {}
118
+ if not isinstance(attrs, dict):
119
+ raise MappingError(f"node {name!r}: attrs must be a mapping")
120
+ children = spec.get("children") or []
121
+ if not isinstance(children, list):
122
+ raise MappingError(f"node {name!r}: children must be a list")
123
+ content_kind = spec.get("content_kind", "block")
124
+ if content_kind not in ("block", "inline", "none"):
125
+ raise MappingError(f"node {name!r}: content_kind must be 'block', 'inline', or 'none'")
126
+ entries[name] = MappingEntry(
127
+ node_type=name,
128
+ pandoc=pandoc,
129
+ kind=kind,
130
+ envelope_class=spec.get("envelope_class"),
131
+ attrs={str(k): str(v) for k, v in attrs.items()},
132
+ children=[str(c) for c in children],
133
+ asciidoc_native=spec.get("asciidoc_native"),
134
+ content_kind=content_kind,
135
+ )
136
+
137
+ return MappingTable(entries, version=version)