md2xarticle 0.1.1__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.
Files changed (53) hide show
  1. md2xarticle/__init__.py +3 -0
  2. md2xarticle/__main__.py +3 -0
  3. md2xarticle/check.py +82 -0
  4. md2xarticle/cli.py +459 -0
  5. md2xarticle/compose/__init__.py +1 -0
  6. md2xarticle/compose/base.py +42 -0
  7. md2xarticle/compose/body.py +27 -0
  8. md2xarticle/compose/cover.py +116 -0
  9. md2xarticle/compose/fit.py +54 -0
  10. md2xarticle/compose/measure.py +60 -0
  11. md2xarticle/customize.py +284 -0
  12. md2xarticle/errors.py +139 -0
  13. md2xarticle/factory.py +112 -0
  14. md2xarticle/fonts.py +33 -0
  15. md2xarticle/model.py +101 -0
  16. md2xarticle/outline.py +55 -0
  17. md2xarticle/parse/__init__.py +1 -0
  18. md2xarticle/parse/base.py +15 -0
  19. md2xarticle/parse/markdown_it.py +213 -0
  20. md2xarticle/pipeline.py +289 -0
  21. md2xarticle/platform/__init__.py +1 -0
  22. md2xarticle/platform/base.py +25 -0
  23. md2xarticle/platform/posix.py +23 -0
  24. md2xarticle/platform/windows.py +25 -0
  25. md2xarticle/platform/wsl.py +31 -0
  26. md2xarticle/privacy.py +262 -0
  27. md2xarticle/render/__init__.py +1 -0
  28. md2xarticle/render/base.py +25 -0
  29. md2xarticle/render/mermaidx.py +179 -0
  30. md2xarticle/render/svg_flowchart.py +175 -0
  31. md2xarticle/render/svg_gitgraph.py +458 -0
  32. md2xarticle/shape/__init__.py +1 -0
  33. md2xarticle/shape/captions.py +96 -0
  34. md2xarticle/shape/comments.py +12 -0
  35. md2xarticle/shape/headings.py +155 -0
  36. md2xarticle/shape/markers.py +63 -0
  37. md2xarticle/theme.py +88 -0
  38. md2xarticle/themes/__init__.py +0 -0
  39. md2xarticle/themes/mono.json +75 -0
  40. md2xarticle/themes/soft.json +75 -0
  41. md2xarticle/themes/warm.json +75 -0
  42. md2xarticle/themes/x-dark.json +86 -0
  43. md2xarticle/themes/x-light.json +86 -0
  44. md2xarticle/transform.py +42 -0
  45. md2xarticle/write/__init__.py +1 -0
  46. md2xarticle/write/base.py +19 -0
  47. md2xarticle/write/html.py +486 -0
  48. md2xarticle/write/manifest.py +65 -0
  49. md2xarticle-0.1.1.dist-info/METADATA +592 -0
  50. md2xarticle-0.1.1.dist-info/RECORD +53 -0
  51. md2xarticle-0.1.1.dist-info/WHEEL +4 -0
  52. md2xarticle-0.1.1.dist-info/entry_points.txt +2 -0
  53. md2xarticle-0.1.1.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,116 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+ from PIL import Image, ImageDraw, ImageFont
6
+
7
+ from md2xarticle.compose.base import ImageComposer
8
+ from md2xarticle.compose.fit import fit
9
+ from md2xarticle.model import RenderedImage
10
+ from md2xarticle.theme import Theme, hex_to_rgb
11
+
12
+ TITLE_HEIGHT = 0.09 # starting title font size, fraction of canvas height
13
+ SUBTITLE_HEIGHT = 0.05 # starting subtitle font size, fraction of canvas height
14
+ SUBTITLE_GAP = 0.025 # space between title and subtitle, fraction of canvas height
15
+ TITLE_GAP = 0.05 # space between the text and the diagram, fraction of canvas height
16
+ MIN_FONT_PX = 10
17
+
18
+ _Font = ImageFont.FreeTypeFont | ImageFont.ImageFont
19
+
20
+
21
+ class CoverComposer(ImageComposer):
22
+ """5:2 cover: an optional title and subtitle above an optional diagram,
23
+ centered as one block."""
24
+
25
+ name = "cover"
26
+ ratio = (5, 2)
27
+ default_size = (1500, 600)
28
+
29
+ def __init__(
30
+ self,
31
+ theme: Theme,
32
+ title: str | None = None,
33
+ font_path: Path | None = None,
34
+ subtitle: str | None = None,
35
+ subtitle_font_path: Path | None = None,
36
+ ) -> None:
37
+ super().__init__(theme)
38
+ self.title = title or None
39
+ self.subtitle = subtitle or None
40
+ self.font_path = font_path
41
+ self.subtitle_font_path = subtitle_font_path or font_path
42
+
43
+ @property
44
+ def center_tolerance(self) -> int:
45
+ return 8 if (self.title or self.subtitle) else 4
46
+
47
+ @staticmethod
48
+ def _font(path: Path | None, px: int) -> _Font:
49
+ if path is not None:
50
+ return ImageFont.truetype(str(path), size=px)
51
+ return ImageFont.load_default(size=px)
52
+
53
+ @classmethod
54
+ def _text_layout(cls, text: str, path: Path | None, start_px: int, max_w: int):
55
+ """The largest font from ``start_px`` down whose text fits ``max_w``."""
56
+ draw = ImageDraw.Draw(Image.new("RGB", (1, 1)))
57
+ px = max(MIN_FONT_PX, start_px)
58
+ while True:
59
+ font = cls._font(path, px)
60
+ box = draw.textbbox((0, 0), text, font=font)
61
+ if box[2] - box[0] <= max_w or px <= MIN_FONT_PX:
62
+ return font, box
63
+ px = max(MIN_FONT_PX, int(px * 0.9))
64
+
65
+ def _lines(self, size: tuple[int, int]) -> tuple[list[tuple[str, _Font, tuple[int, int, int, int]]], int]:
66
+ """Title and subtitle lines with their fonts and boxes, and the text height."""
67
+ cw, ch = size
68
+ avail_w = round(cw * (1 - 2 * self.theme.margin))
69
+ lines: list[tuple[str, _Font, tuple[int, int, int, int]]] = []
70
+ if self.title:
71
+ font, box = self._text_layout(self.title, self.font_path, round(ch * TITLE_HEIGHT), avail_w)
72
+ lines.append((self.title, font, box))
73
+ self._title_lines = len(lines)
74
+ if self.subtitle:
75
+ font, box = self._text_layout(
76
+ self.subtitle, self.subtitle_font_path, round(ch * SUBTITLE_HEIGHT), avail_w
77
+ )
78
+ lines.append((self.subtitle, font, box))
79
+ text_h = sum(b[3] - b[1] for _, _, b in lines) + round(ch * SUBTITLE_GAP) * max(0, len(lines) - 1)
80
+ return lines, text_h
81
+
82
+ def diagram_box(self, size: tuple[int, int]) -> tuple[int, int]:
83
+ avail_w, avail_h = super().diagram_box(size)
84
+ lines, text_h = self._lines(size)
85
+ if not lines:
86
+ return avail_w, avail_h
87
+ return avail_w, max(1, avail_h - text_h - round(size[1] * TITLE_GAP))
88
+
89
+ def compose(self, image: RenderedImage | None, size: tuple[int, int]) -> Image.Image:
90
+ self.check_size(size)
91
+ cw, ch = size
92
+ canvas = Image.new("RGB", size, hex_to_rgb(self.theme.canvas))
93
+ lines, text_h = self._lines(size)
94
+ sub_gap = round(ch * SUBTITLE_GAP)
95
+
96
+ fitted = None
97
+ gap = round(ch * TITLE_GAP) if lines else 0
98
+ if image is not None:
99
+ fitted = fit(image, self.diagram_box(size), self.theme.canvas, self.theme.max_scale)
100
+ if fitted is None:
101
+ gap = 0
102
+
103
+ block_h = text_h + gap + (fitted.height if fitted is not None else 0)
104
+ y = (ch - block_h) // 2
105
+ draw = ImageDraw.Draw(canvas)
106
+ sub_color = self.theme.subtitle_color or self.theme.title_color
107
+ for i, (text, font, tbox) in enumerate(lines):
108
+ tw = tbox[2] - tbox[0]
109
+ fill = self.theme.title_color if i < self._title_lines else sub_color
110
+ draw.text(((cw - tw) // 2 - tbox[0], y - tbox[1]), text, font=font, fill=fill)
111
+ y += tbox[3] - tbox[1] + sub_gap
112
+ if lines:
113
+ y += gap - sub_gap
114
+ if fitted is not None:
115
+ canvas.paste(fitted, ((cw - fitted.width) // 2, y))
116
+ return canvas
@@ -0,0 +1,54 @@
1
+ """Trim a rendered diagram and size it to fit a box. Shared by the composers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from io import BytesIO
6
+
7
+ from PIL import Image
8
+
9
+ from md2xarticle.compose.measure import content_bbox
10
+ from md2xarticle.model import RenderedImage
11
+ from md2xarticle.theme import hex_to_rgb
12
+
13
+ # Rasterize this much larger than the target, then downsample, for clean edges.
14
+ SUPERSAMPLE = 1.5
15
+
16
+
17
+ def _decode(png: bytes, background: tuple[int, int, int]) -> Image.Image:
18
+ with Image.open(BytesIO(png)) as im:
19
+ im.load()
20
+ if im.mode in ("RGBA", "LA", "P"):
21
+ rgba = im.convert("RGBA")
22
+ flat = Image.new("RGBA", rgba.size, background + (255,))
23
+ return Image.alpha_composite(flat, rgba).convert("RGB")
24
+ return im.convert("RGB")
25
+
26
+
27
+ def fit(
28
+ image: RenderedImage, box: tuple[int, int], canvas: str, max_scale: float
29
+ ) -> Image.Image | None:
30
+ """Content of ``image`` trimmed, scaled to fit inside ``box``.
31
+
32
+ Never larger than ``max_scale`` times the native size, so a tiny diagram
33
+ is not blown up. ``None`` when the render has no visible content.
34
+ """
35
+ bg = hex_to_rgb(canvas)
36
+ box_w, box_h = max(1, box[0]), max(1, box[1])
37
+ native = _decode(image.rasterize(1), bg)
38
+ bbox = content_bbox(native, bg)
39
+ if bbox is None:
40
+ return None
41
+ nw, nh = bbox[2] - bbox[0], bbox[3] - bbox[1]
42
+ want = min(box_w / nw, box_h / nh, max_scale)
43
+ limit_w, limit_h = min(box_w, nw * want), min(box_h, nh * want)
44
+
45
+ raster_scale = max(1.0, want * SUPERSAMPLE)
46
+ src = native if raster_scale == 1 else _decode(image.rasterize(raster_scale), bg)
47
+ bbox = content_bbox(src, bg) or (0, 0, src.width, src.height)
48
+ trimmed = src.crop(bbox)
49
+ tw, th = trimmed.size
50
+ f = min(limit_w / tw, limit_h / th)
51
+ size = (max(1, round(tw * f)), max(1, round(th * f)))
52
+ if size == trimmed.size:
53
+ return trimmed
54
+ return trimmed.resize(size, Image.Resampling.LANCZOS)
@@ -0,0 +1,60 @@
1
+ """Measure where content sits on a canvas. Used by composers and by tests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+ from PIL import Image, ImageChops
8
+
9
+ BG_TOLERANCE = 16
10
+ MIN_MARGIN_FRACTION = 0.04
11
+
12
+
13
+ def content_bbox(
14
+ image: Image.Image, background: tuple[int, int, int], tolerance: int = BG_TOLERANCE
15
+ ) -> tuple[int, int, int, int] | None:
16
+ """Box (left, top, right, bottom; right and bottom exclusive) of non-background pixels."""
17
+ rgb = image.convert("RGB")
18
+ diff = ImageChops.difference(rgb, Image.new("RGB", rgb.size, background)).convert("L")
19
+ return diff.point(lambda p: 255 if p > tolerance else 0).getbbox()
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class Margins:
24
+ left: int
25
+ top: int
26
+ right: int
27
+ bottom: int
28
+ width: int
29
+ height: int
30
+
31
+ @property
32
+ def off_center_x(self) -> int:
33
+ return abs(self.left - self.right)
34
+
35
+ @property
36
+ def off_center_y(self) -> int:
37
+ return abs(self.top - self.bottom)
38
+
39
+ def problems(
40
+ self, center_tolerance: int, min_fraction: float = MIN_MARGIN_FRACTION
41
+ ) -> list[str]:
42
+ out = []
43
+ if self.off_center_x > center_tolerance:
44
+ out.append(f"off center horizontally by {self.off_center_x}px")
45
+ if self.off_center_y > center_tolerance:
46
+ out.append(f"off center vertically by {self.off_center_y}px")
47
+ if min(self.left, self.right) < min_fraction * self.width:
48
+ out.append(f"side margin under {min_fraction:.0%}")
49
+ if min(self.top, self.bottom) < min_fraction * self.height:
50
+ out.append(f"top or bottom margin under {min_fraction:.0%}")
51
+ return out
52
+
53
+
54
+ def measure(image: Image.Image, background: tuple[int, int, int]) -> Margins | None:
55
+ box = content_bbox(image, background)
56
+ if box is None:
57
+ return None
58
+ w, h = image.size
59
+ left, top, right, bottom = box
60
+ return Margins(left, top, w - right, h - bottom, w, h)
@@ -0,0 +1,284 @@
1
+ """Load a ``--custom-path`` TOML file into a validated ``Customization``.
2
+
3
+ Schema (every key optional)::
4
+
5
+ theme = "mono" # built-in base theme
6
+ size = "1600x900" # body images, must be 16:9
7
+ cover_size = "1500x600" # cover, must be 5:2
8
+ cover = "diagram:2" # "diagram:N" or "title" (title only)
9
+ cover_title = "Title" # "" turns the title off
10
+ cover_subtitle = "Sub" # "" turns the subtitle off
11
+
12
+ [style]
13
+ corner_radius = 8 # px, node corner radius
14
+ spacing = 24 # px, padding inside flowchart nodes
15
+ node_spacing = 60 # px, between nodes in a rank
16
+ rank_spacing = 70 # px, between ranks
17
+ edge_width = 2.0 # px
18
+ wrap_width = 320 # px, flowchart label wrapping (default: automatic)
19
+ rotate_commit_labels = true # gitGraph: false draws commit labels level
20
+ compact_tall = true # tall or wide flowcharts and tall sequences may render compact
21
+ margin = 0.06 # fraction of each canvas side, 0.04 to 0.25
22
+
23
+ [palette] # #RRGGBB colors
24
+ canvas = "#FFFFFF"
25
+ title = "#111111"
26
+ subtitle = "#536471" # cover subtitle (default: the title color)
27
+ primary = "#D9EEF2"
28
+ primary_border = "#2F8A8A"
29
+ primary_text = "#163239"
30
+ secondary = "#E4EEF8"
31
+ tertiary = "#E8F4EA"
32
+ line = "#5A7380"
33
+ text = "#1A2A30"
34
+
35
+ [theme_variables] # raw Mermaid themeVariables, applied last
36
+
37
+ [[diagrams]] # per-diagram overrides, by 1-based index
38
+ id = 1
39
+ layout = "LR" # TD, TB, BT, RL, or LR (flowchart and graph only)
40
+ """
41
+
42
+ from __future__ import annotations
43
+
44
+ import tomllib
45
+ from dataclasses import dataclass, field
46
+ from pathlib import Path
47
+ from typing import Any
48
+
49
+ from md2xarticle.errors import UsageError
50
+ from md2xarticle.theme import BUILTIN_THEMES, Theme, hex_to_rgb, load_builtin
51
+
52
+ LAYOUTS = ("TD", "TB", "BT", "RL", "LR")
53
+
54
+ _TOP_KEYS = {
55
+ "theme",
56
+ "size",
57
+ "cover_size",
58
+ "cover",
59
+ "cover_title",
60
+ "cover_subtitle",
61
+ "style",
62
+ "palette",
63
+ "theme_variables",
64
+ "diagrams",
65
+ }
66
+ _STYLE_KEYS = {
67
+ "corner_radius",
68
+ "spacing",
69
+ "node_spacing",
70
+ "rank_spacing",
71
+ "edge_width",
72
+ "margin",
73
+ "wrap_width",
74
+ "rotate_commit_labels",
75
+ "compact_tall",
76
+ }
77
+ _PALETTE_TO_VARS = {
78
+ "primary": ("primaryColor", "mainBkg", "actorBkg"),
79
+ "primary_border": ("primaryBorderColor", "nodeBorder", "actorBorder"),
80
+ "primary_text": ("primaryTextColor", "actorTextColor"),
81
+ "secondary": ("secondaryColor",),
82
+ "tertiary": ("tertiaryColor",),
83
+ "line": ("lineColor",),
84
+ "text": ("textColor", "titleColor"),
85
+ }
86
+ _PALETTE_KEYS = set(_PALETTE_TO_VARS) | {"canvas", "title", "subtitle"}
87
+ _DIAGRAM_KEYS = {"id", "layout"}
88
+
89
+
90
+ @dataclass(frozen=True)
91
+ class DiagramOverride:
92
+ layout: str | None = None
93
+
94
+
95
+ @dataclass(frozen=True)
96
+ class Customization:
97
+ theme_name: str | None = None
98
+ size: tuple[int, int] | None = None
99
+ cover_size: tuple[int, int] | None = None
100
+ cover_diagram: int | None = None
101
+ cover_title_only: bool = False
102
+ cover_title: str | None = None
103
+ cover_subtitle: str | None = None
104
+ style: dict[str, Any] = field(default_factory=dict)
105
+ palette: dict[str, str] = field(default_factory=dict)
106
+ theme_variables: dict[str, Any] = field(default_factory=dict)
107
+ diagrams: dict[int, DiagramOverride] = field(default_factory=dict)
108
+
109
+ def build_theme(self, fallback_name: str) -> Theme:
110
+ """The base theme (file wins over ``fallback_name``) with overrides applied."""
111
+ theme = load_builtin(self.theme_name or fallback_name)
112
+ tv = dict(theme.theme_variables)
113
+ flow = dict(theme.flowchart)
114
+ changes: dict[str, Any] = {}
115
+ for key, names in _PALETTE_TO_VARS.items():
116
+ if key in self.palette:
117
+ for name in names:
118
+ tv[name] = self.palette[key]
119
+ if "canvas" in self.palette:
120
+ changes["canvas"] = self.palette["canvas"]
121
+ if "title" in self.palette:
122
+ changes["title_color"] = self.palette["title"]
123
+ if "subtitle" in self.palette:
124
+ changes["subtitle_color"] = self.palette["subtitle"]
125
+ tv.update(self.theme_variables)
126
+ s = self.style
127
+ if "corner_radius" in s:
128
+ changes["corner_radius"] = s["corner_radius"]
129
+ if "edge_width" in s:
130
+ changes["edge_width"] = float(s["edge_width"])
131
+ if "margin" in s:
132
+ changes["margin"] = float(s["margin"])
133
+ if "spacing" in s:
134
+ flow["padding"] = s["spacing"]
135
+ if "node_spacing" in s:
136
+ flow["nodeSpacing"] = s["node_spacing"]
137
+ if "rank_spacing" in s:
138
+ flow["rankSpacing"] = s["rank_spacing"]
139
+ if "wrap_width" in s:
140
+ flow["wrappingWidth"] = s["wrap_width"]
141
+ if "compact_tall" in s:
142
+ changes["compact_tall"] = s["compact_tall"]
143
+ if "rotate_commit_labels" in s:
144
+ changes["git_graph"] = {**theme.git_graph, "rotateCommitLabel": s["rotate_commit_labels"]}
145
+ return theme.with_overrides(theme_variables=tv, flowchart=flow, **changes)
146
+
147
+
148
+ def parse_size(text: str, ratio: tuple[int, int], what: str) -> tuple[int, int]:
149
+ """Parse ``WxH`` and require the exact ratio, for example 16:9."""
150
+ try:
151
+ w_s, h_s = text.lower().split("x")
152
+ w, h = int(w_s), int(h_s)
153
+ except (ValueError, AttributeError):
154
+ raise UsageError(f"{what} must look like WxH, got {text!r}") from None
155
+ if w <= 0 or h <= 0:
156
+ raise UsageError(f"{what} must be positive, got {text!r}")
157
+ rw, rh = ratio
158
+ if w * rh != h * rw:
159
+ raise UsageError(f"{what} must be {rw}:{rh} for now, got {text!r}")
160
+ return w, h
161
+
162
+
163
+ def _unknown(keys: set[str], allowed: set[str], where: str) -> None:
164
+ extra = sorted(keys - allowed)
165
+ if extra:
166
+ raise UsageError(f"unknown key(s) in {where}: {', '.join(extra)}")
167
+
168
+
169
+ def _int_range(value: Any, lo: int, hi: int, where: str) -> int:
170
+ if isinstance(value, bool) or not isinstance(value, int) or not lo <= value <= hi:
171
+ raise UsageError(f"{where} must be an integer from {lo} to {hi}, got {value!r}")
172
+ return value
173
+
174
+
175
+ def _num_range(value: Any, lo: float, hi: float, where: str) -> float:
176
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not lo <= value <= hi:
177
+ raise UsageError(f"{where} must be a number from {lo} to {hi}, got {value!r}")
178
+ return float(value)
179
+
180
+
181
+ def from_dict(data: dict[str, Any], where: str = "customization") -> Customization:
182
+ _unknown(set(data), _TOP_KEYS, where)
183
+ kw: dict[str, Any] = {}
184
+
185
+ if "theme" in data:
186
+ if data["theme"] not in BUILTIN_THEMES:
187
+ raise UsageError(
188
+ f"{where}: unknown theme {data['theme']!r}; built-in themes: "
189
+ f"{', '.join(BUILTIN_THEMES)}"
190
+ )
191
+ kw["theme_name"] = data["theme"]
192
+ if "size" in data:
193
+ kw["size"] = parse_size(str(data["size"]), (16, 9), f"{where}: size")
194
+ if "cover_size" in data:
195
+ kw["cover_size"] = parse_size(str(data["cover_size"]), (5, 2), f"{where}: cover_size")
196
+ if "cover" in data:
197
+ cover = data["cover"]
198
+ if cover == "title":
199
+ kw["cover_title_only"] = True
200
+ elif isinstance(cover, str) and cover.startswith("diagram:"):
201
+ try:
202
+ kw["cover_diagram"] = int(cover.split(":", 1)[1])
203
+ except ValueError:
204
+ raise UsageError(f"{where}: cover must be 'diagram:N' or 'title'") from None
205
+ if kw["cover_diagram"] < 1:
206
+ raise UsageError(f"{where}: cover diagram index starts at 1")
207
+ else:
208
+ raise UsageError(f"{where}: cover must be 'diagram:N' or 'title', got {cover!r}")
209
+ for key in ("cover_title", "cover_subtitle"):
210
+ if key in data:
211
+ if not isinstance(data[key], str):
212
+ raise UsageError(f"{where}: {key} must be a string")
213
+ kw[key] = data[key]
214
+
215
+ style = data.get("style", {})
216
+ if not isinstance(style, dict):
217
+ raise UsageError(f"{where}: [style] must be a table")
218
+ _unknown(set(style), _STYLE_KEYS, f"{where} [style]")
219
+ checked: dict[str, Any] = {}
220
+ for key in ("corner_radius", "spacing", "node_spacing", "rank_spacing"):
221
+ if key in style:
222
+ checked[key] = _int_range(style[key], 0, 400, f"{where} [style] {key}")
223
+ if "compact_tall" in style:
224
+ if not isinstance(style["compact_tall"], bool):
225
+ raise UsageError(f"{where} [style] compact_tall must be true or false")
226
+ checked["compact_tall"] = style["compact_tall"]
227
+ if "rotate_commit_labels" in style:
228
+ if not isinstance(style["rotate_commit_labels"], bool):
229
+ raise UsageError(f"{where} [style] rotate_commit_labels must be true or false")
230
+ checked["rotate_commit_labels"] = style["rotate_commit_labels"]
231
+ if "wrap_width" in style:
232
+ checked["wrap_width"] = _int_range(style["wrap_width"], 80, 1000, f"{where} [style] wrap_width")
233
+ if "edge_width" in style:
234
+ checked["edge_width"] = _num_range(style["edge_width"], 0.5, 12, f"{where} [style] edge_width")
235
+ if "margin" in style:
236
+ checked["margin"] = _num_range(style["margin"], 0.04, 0.25, f"{where} [style] margin")
237
+ kw["style"] = checked
238
+
239
+ palette = data.get("palette", {})
240
+ if not isinstance(palette, dict):
241
+ raise UsageError(f"{where}: [palette] must be a table")
242
+ _unknown(set(palette), _PALETTE_KEYS, f"{where} [palette]")
243
+ for key, value in palette.items():
244
+ try:
245
+ hex_to_rgb(str(value))
246
+ except UsageError:
247
+ raise UsageError(f"{where} [palette] {key} must be #RRGGBB, got {value!r}") from None
248
+ kw["palette"] = dict(palette)
249
+
250
+ tv = data.get("theme_variables", {})
251
+ if not isinstance(tv, dict):
252
+ raise UsageError(f"{where}: [theme_variables] must be a table")
253
+ kw["theme_variables"] = dict(tv)
254
+
255
+ diagrams: dict[int, DiagramOverride] = {}
256
+ for i, entry in enumerate(data.get("diagrams", []), start=1):
257
+ if not isinstance(entry, dict):
258
+ raise UsageError(f"{where}: [[diagrams]] entry {i} must be a table")
259
+ _unknown(set(entry), _DIAGRAM_KEYS, f"{where} [[diagrams]] entry {i}")
260
+ if "id" not in entry:
261
+ raise UsageError(f"{where}: [[diagrams]] entry {i} needs id = N (1-based)")
262
+ idx = _int_range(entry["id"], 1, 10_000, f"{where} [[diagrams]] id")
263
+ layout = entry.get("layout")
264
+ if layout is not None and layout not in LAYOUTS:
265
+ raise UsageError(
266
+ f"{where}: [[diagrams]] id {idx} layout must be one of {', '.join(LAYOUTS)}"
267
+ )
268
+ diagrams[idx] = DiagramOverride(layout=layout)
269
+ kw["diagrams"] = diagrams
270
+ return Customization(**kw)
271
+
272
+
273
+ def load(path: Path) -> Customization:
274
+ try:
275
+ raw = path.read_text(encoding="utf-8")
276
+ except FileNotFoundError:
277
+ raise UsageError(f"customization file not found: {path}") from None
278
+ except OSError as exc:
279
+ raise UsageError(f"cannot read customization file {path}: {exc.strerror}") from None
280
+ try:
281
+ data = tomllib.loads(raw)
282
+ except tomllib.TOMLDecodeError as exc:
283
+ raise UsageError(f"{path.name}: invalid TOML: {exc}") from None
284
+ return from_dict(data, where=path.name)
md2xarticle/errors.py ADDED
@@ -0,0 +1,139 @@
1
+ """Error types and the Output-contract message format.
2
+
3
+ Every error prints ``error: ...`` and the exact next command to try
4
+ (``try:`` / ``or:`` lines) on stderr.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import sys
10
+ from pathlib import Path
11
+ from typing import TextIO
12
+
13
+ # Planned renderer names are recognised before they ship. Only renderers
14
+ # whose install command works today get a pip hint; the rest point at the
15
+ # working fallback until their extras land in pyproject.toml.
16
+ KNOWN_RENDERERS = ("mermaidx", "mmdc", "mmdr")
17
+ RENDERER_INSTALL_HINTS = {
18
+ "mermaidx": "pip install md2xarticle",
19
+ }
20
+
21
+
22
+ class Md2xError(Exception):
23
+ """Base class for md2xarticle errors."""
24
+
25
+
26
+ class UsageError(Md2xError):
27
+ """Bad flag, missing file, or bad customization value. Exit code 2."""
28
+
29
+ def __init__(
30
+ self,
31
+ message: str,
32
+ try_cmd: str | None = None,
33
+ or_cmd: str | None = None,
34
+ ) -> None:
35
+ super().__init__(message)
36
+ self.try_cmd = try_cmd
37
+ self.or_cmd = or_cmd
38
+
39
+
40
+ class DiagramRenderError(Md2xError):
41
+ """A single diagram failed to render. Exit code 1 for the run."""
42
+
43
+
44
+ def format_error(
45
+ message: str,
46
+ try_cmd: str | None = None,
47
+ or_cmd: str | None = None,
48
+ ) -> str:
49
+ """``error:`` plus optional ``try:`` / ``or:`` lines, as in the README."""
50
+ lines = [f"error: {message}"]
51
+ if try_cmd:
52
+ lines.append(f"try: {try_cmd}")
53
+ if or_cmd:
54
+ lines.append(f"or: {or_cmd}")
55
+ return "\n".join(lines)
56
+
57
+
58
+ def print_error(
59
+ message: str,
60
+ try_cmd: str | None = None,
61
+ or_cmd: str | None = None,
62
+ file: TextIO | None = None,
63
+ ) -> None:
64
+ """Write a contract-shaped error to stderr."""
65
+ print(format_error(message, try_cmd=try_cmd, or_cmd=or_cmd), file=file or sys.stderr)
66
+
67
+
68
+ def diagrams_command(article: str | Path, *flags: str) -> str:
69
+ """Build a ``md2xarticle diagrams ARTICLE.md ...`` retry command."""
70
+ parts = ["md2xarticle", "diagrams", str(article), *flags]
71
+ return " ".join(parts)
72
+
73
+
74
+ def renderer_usage(name: str, article: str | Path = "article.md") -> UsageError:
75
+ """Unknown renderer, a planned one not shipped yet, or one not installed."""
76
+ fallback = diagrams_command(article, "--renderer", "mermaidx")
77
+ hint = RENDERER_INSTALL_HINTS.get(name)
78
+ if hint is not None:
79
+ # The fallback is this same renderer, so an ``or:`` line would loop.
80
+ return UsageError(f"renderer {name!r} is not installed", try_cmd=hint)
81
+ if name in KNOWN_RENDERERS:
82
+ return UsageError(f"renderer {name!r} is planned and not available yet", try_cmd=fallback)
83
+ known = ", ".join(KNOWN_RENDERERS)
84
+ return UsageError(
85
+ f"unknown renderer {name!r}; known renderers: {known}",
86
+ try_cmd=fallback,
87
+ )
88
+
89
+
90
+ def usage_retry(
91
+ exc: BaseException,
92
+ *,
93
+ article: str | Path = "article.md",
94
+ command: str = "diagrams",
95
+ custom_path: str | Path | None = None,
96
+ size_flag: bool = False,
97
+ ) -> str | None:
98
+ """A ``try:`` command for a UsageError that did not carry one."""
99
+ if isinstance(exc, UsageError) and exc.try_cmd:
100
+ return exc.try_cmd
101
+ msg = str(exc)
102
+ path = str(article)
103
+ cmd = command or "diagrams"
104
+ if custom_path is not None and (
105
+ "customization" in msg
106
+ or "invalid TOML" in msg
107
+ or "unknown key" in msg
108
+ or str(custom_path) in msg
109
+ or Path(str(custom_path)).name in msg
110
+ ):
111
+ return f"md2xarticle {cmd} {path} --custom-path {custom_path}"
112
+ if size_flag or "--size" in msg or "must be 16:9" in msg or "must look like WxH" in msg:
113
+ return f"md2xarticle {cmd} {path} --size 1600x900"
114
+ if "unknown theme" in msg:
115
+ from md2xarticle.theme import DEFAULT_THEME
116
+
117
+ return f"md2xarticle {cmd} {path} --theme {DEFAULT_THEME}"
118
+ if "renderer" in msg:
119
+ return f"md2xarticle {cmd} {path} --renderer mermaidx"
120
+ if "--only" in msg:
121
+ return f"md2xarticle {cmd} {path} --only 1"
122
+ if "file not found" in msg or "cannot read" in msg:
123
+ return f"md2xarticle {cmd} {path}"
124
+ return f"md2xarticle {cmd} --help"
125
+
126
+
127
+ def argparse_retry(message: str, prog: str = "md2xarticle") -> str:
128
+ """A ``try:`` command for an argparse usage error.
129
+
130
+ ``prog`` is the failing parser's prog (``md2xarticle check`` for a
131
+ subcommand), so the hint names the command the user actually ran.
132
+ """
133
+ low = message.lower()
134
+ if "diagram numbers start at 1" in low or "expected n[" in low:
135
+ return "md2xarticle diagrams article.md --only 1"
136
+ if "required" in low and "article.md" in low:
137
+ sub = prog if prog != "md2xarticle" else "md2xarticle diagrams"
138
+ return f"{sub} article.md"
139
+ return f"{prog} --help"