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.
- md2xarticle/__init__.py +3 -0
- md2xarticle/__main__.py +3 -0
- md2xarticle/check.py +82 -0
- md2xarticle/cli.py +459 -0
- md2xarticle/compose/__init__.py +1 -0
- md2xarticle/compose/base.py +42 -0
- md2xarticle/compose/body.py +27 -0
- md2xarticle/compose/cover.py +116 -0
- md2xarticle/compose/fit.py +54 -0
- md2xarticle/compose/measure.py +60 -0
- md2xarticle/customize.py +284 -0
- md2xarticle/errors.py +139 -0
- md2xarticle/factory.py +112 -0
- md2xarticle/fonts.py +33 -0
- md2xarticle/model.py +101 -0
- md2xarticle/outline.py +55 -0
- md2xarticle/parse/__init__.py +1 -0
- md2xarticle/parse/base.py +15 -0
- md2xarticle/parse/markdown_it.py +213 -0
- md2xarticle/pipeline.py +289 -0
- md2xarticle/platform/__init__.py +1 -0
- md2xarticle/platform/base.py +25 -0
- md2xarticle/platform/posix.py +23 -0
- md2xarticle/platform/windows.py +25 -0
- md2xarticle/platform/wsl.py +31 -0
- md2xarticle/privacy.py +262 -0
- md2xarticle/render/__init__.py +1 -0
- md2xarticle/render/base.py +25 -0
- md2xarticle/render/mermaidx.py +179 -0
- md2xarticle/render/svg_flowchart.py +175 -0
- md2xarticle/render/svg_gitgraph.py +458 -0
- md2xarticle/shape/__init__.py +1 -0
- md2xarticle/shape/captions.py +96 -0
- md2xarticle/shape/comments.py +12 -0
- md2xarticle/shape/headings.py +155 -0
- md2xarticle/shape/markers.py +63 -0
- md2xarticle/theme.py +88 -0
- md2xarticle/themes/__init__.py +0 -0
- md2xarticle/themes/mono.json +75 -0
- md2xarticle/themes/soft.json +75 -0
- md2xarticle/themes/warm.json +75 -0
- md2xarticle/themes/x-dark.json +86 -0
- md2xarticle/themes/x-light.json +86 -0
- md2xarticle/transform.py +42 -0
- md2xarticle/write/__init__.py +1 -0
- md2xarticle/write/base.py +19 -0
- md2xarticle/write/html.py +486 -0
- md2xarticle/write/manifest.py +65 -0
- md2xarticle-0.1.1.dist-info/METADATA +592 -0
- md2xarticle-0.1.1.dist-info/RECORD +53 -0
- md2xarticle-0.1.1.dist-info/WHEEL +4 -0
- md2xarticle-0.1.1.dist-info/entry_points.txt +2 -0
- md2xarticle-0.1.1.dist-info/licenses/LICENSE +21 -0
md2xarticle/__init__.py
ADDED
md2xarticle/__main__.py
ADDED
md2xarticle/check.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""``md2xarticle check ARTICLE.md``: privacy scan only, writes nothing."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from md2xarticle.errors import UsageError
|
|
9
|
+
from md2xarticle.privacy import (
|
|
10
|
+
findings_as_json,
|
|
11
|
+
format_findings,
|
|
12
|
+
load_deny_list,
|
|
13
|
+
resolve_deny_path,
|
|
14
|
+
scan_text,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
EXIT_OK, EXIT_FINDINGS = 0, 1
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def add_parser(sub: argparse._SubParsersAction) -> argparse.ArgumentParser:
|
|
21
|
+
p = sub.add_parser(
|
|
22
|
+
"check",
|
|
23
|
+
help="privacy scan only; print findings with line numbers and write nothing",
|
|
24
|
+
description="Scan ARTICLE.md for email, phone, local-path, secret, and deny-list shapes. Writes nothing.",
|
|
25
|
+
)
|
|
26
|
+
add_scan_arguments(p, require_privacy_flag=False)
|
|
27
|
+
return p
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def add_scan_arguments(p: argparse.ArgumentParser, *, require_privacy_flag: bool) -> None:
|
|
31
|
+
"""Flags shared by ``check`` and ``diagrams --check-privacy``."""
|
|
32
|
+
if require_privacy_flag:
|
|
33
|
+
p.add_argument(
|
|
34
|
+
"--check-privacy",
|
|
35
|
+
action="store_true",
|
|
36
|
+
help="run the privacy scan after writing (output is still written)",
|
|
37
|
+
)
|
|
38
|
+
p.add_argument(
|
|
39
|
+
"--deny-list",
|
|
40
|
+
type=Path,
|
|
41
|
+
default=None,
|
|
42
|
+
metavar="FILE",
|
|
43
|
+
help="optional local deny-list of names (or set MD2XARTICLE_PRIVACY_DENYLIST)",
|
|
44
|
+
)
|
|
45
|
+
if not require_privacy_flag:
|
|
46
|
+
p.add_argument("article", metavar="ARTICLE.md", type=Path)
|
|
47
|
+
p.add_argument("--json", action="store_true", help="print findings as JSON")
|
|
48
|
+
p.add_argument("-v", "--verbose", action="store_true", help="full error details")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def load_deny(flag: Path | None) -> tuple[str, ...]:
|
|
52
|
+
try:
|
|
53
|
+
return load_deny_list(resolve_deny_path(flag))
|
|
54
|
+
except FileNotFoundError as exc:
|
|
55
|
+
raise UsageError(str(exc)) from None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def read_article(path: Path) -> str:
|
|
59
|
+
try:
|
|
60
|
+
return path.read_text(encoding="utf-8")
|
|
61
|
+
except FileNotFoundError:
|
|
62
|
+
raise UsageError(f"file not found: {path}") from None
|
|
63
|
+
except (OSError, UnicodeDecodeError) as exc:
|
|
64
|
+
raise UsageError(f"cannot read {path}: {exc}") from None
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def run_check(args: argparse.Namespace) -> int:
|
|
68
|
+
text = read_article(args.article)
|
|
69
|
+
findings = scan_text(text, load_deny(args.deny_list))
|
|
70
|
+
if args.json:
|
|
71
|
+
print(
|
|
72
|
+
json.dumps(
|
|
73
|
+
{
|
|
74
|
+
"ok": not findings,
|
|
75
|
+
"privacy_findings": findings_as_json(args.article, findings),
|
|
76
|
+
},
|
|
77
|
+
indent=2,
|
|
78
|
+
)
|
|
79
|
+
)
|
|
80
|
+
else:
|
|
81
|
+
print(format_findings(args.article, findings), end="")
|
|
82
|
+
return EXIT_FINDINGS if findings else EXIT_OK
|
md2xarticle/cli.py
ADDED
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
"""Command line: the full conversion (``md2xarticle ARTICLE.md``) and the
|
|
2
|
+
``diagrams``, ``outline`` and ``check`` commands."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import argparse
|
|
7
|
+
import json
|
|
8
|
+
import sys
|
|
9
|
+
import time
|
|
10
|
+
import traceback
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from md2xarticle import __version__, check, factory, outline
|
|
14
|
+
from md2xarticle.shape.headings import MAP_AUTO, MAP_CHOICES, MAP_FLAT, OutlineEntry, format_outline
|
|
15
|
+
from md2xarticle.shape.markers import build_article
|
|
16
|
+
from md2xarticle.customize import Customization, load, parse_size
|
|
17
|
+
from md2xarticle.errors import UsageError, argparse_retry, print_error, usage_retry
|
|
18
|
+
from md2xarticle.pipeline import ConvertOptions, ConvertResult, DiagramsOptions, DiagramsResult
|
|
19
|
+
from md2xarticle.privacy import Finding, findings_as_json, format_findings, scan_text
|
|
20
|
+
from md2xarticle.theme import BUILTIN_THEMES, DEFAULT_THEME
|
|
21
|
+
|
|
22
|
+
EXIT_OK, EXIT_FINDINGS, EXIT_USAGE, EXIT_INTERNAL = 0, 1, 2, 3
|
|
23
|
+
COMMANDS = ("diagrams", "outline", "check")
|
|
24
|
+
CONVERT_USAGE = "md2xarticle ARTICLE.md [-o OUT] [options]"
|
|
25
|
+
DIAGRAMS_PREFIX = "md2xarticle diagrams"
|
|
26
|
+
# A shown anchor paragraph is cut to this many characters in the text summary.
|
|
27
|
+
ANCHOR_CHARS = 48
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def convert_cmd(cmd: str | None) -> str | None:
|
|
31
|
+
"""Turn a ``md2xarticle diagrams ...`` retry line into the full-conversion one."""
|
|
32
|
+
if cmd is not None and (cmd == DIAGRAMS_PREFIX or cmd.startswith(DIAGRAMS_PREFIX + " ")):
|
|
33
|
+
return "md2xarticle" + cmd[len(DIAGRAMS_PREFIX):]
|
|
34
|
+
return cmd
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class _ErrorParser(argparse.ArgumentParser):
|
|
38
|
+
"""Argparse errors use the same ``error:`` / ``try:`` shape as UsageError."""
|
|
39
|
+
|
|
40
|
+
def error(self, message: str) -> None:
|
|
41
|
+
print_error(message, try_cmd=argparse_retry(message, self.prog))
|
|
42
|
+
self.exit(EXIT_USAGE)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class _ConvertParser(_ErrorParser):
|
|
46
|
+
"""The full conversion's parser: retry lines name the full conversion."""
|
|
47
|
+
|
|
48
|
+
def error(self, message: str) -> None:
|
|
49
|
+
print_error(message, try_cmd=convert_cmd(argparse_retry(message, self.prog)))
|
|
50
|
+
self.exit(EXIT_USAGE)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _parse_only(text: str) -> frozenset[int]:
|
|
54
|
+
try:
|
|
55
|
+
values = frozenset(int(p) for p in text.split(",") if p.strip())
|
|
56
|
+
except ValueError:
|
|
57
|
+
raise argparse.ArgumentTypeError(f"expected N[,N...], got {text!r}") from None
|
|
58
|
+
if not values or min(values) < 1:
|
|
59
|
+
raise argparse.ArgumentTypeError("diagram numbers start at 1")
|
|
60
|
+
return values
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _add_render_arguments(d: argparse.ArgumentParser) -> None:
|
|
64
|
+
"""Flags shared by the full conversion and ``diagrams``."""
|
|
65
|
+
d.add_argument("article", metavar="ARTICLE.md", type=Path)
|
|
66
|
+
d.add_argument("-o", "--out", type=Path, default=None, help="output folder (default: out)")
|
|
67
|
+
d.add_argument("--cover", action="store_true", help="also write images/cover.png at 5:2")
|
|
68
|
+
d.add_argument(
|
|
69
|
+
"--theme",
|
|
70
|
+
default=None,
|
|
71
|
+
metavar="NAME",
|
|
72
|
+
help=f"diagram theme: {', '.join(BUILTIN_THEMES)} (default: {DEFAULT_THEME})",
|
|
73
|
+
)
|
|
74
|
+
d.add_argument("--custom-path", type=Path, default=None, metavar="FILE", help="TOML customization file")
|
|
75
|
+
d.add_argument("--size", default=None, metavar="WxH", help="body image size, 16:9 (default: 1600x900)")
|
|
76
|
+
d.add_argument("--only", type=_parse_only, default=None, metavar="N[,N]", help="render only these diagrams (1-based)")
|
|
77
|
+
d.add_argument(
|
|
78
|
+
"--renderer",
|
|
79
|
+
default=factory.DEFAULT_RENDERER,
|
|
80
|
+
metavar="NAME",
|
|
81
|
+
help="diagram renderer (default: mermaidx)",
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def build_convert_parser() -> argparse.ArgumentParser:
|
|
86
|
+
p = _ConvertParser(
|
|
87
|
+
prog="md2xarticle",
|
|
88
|
+
usage=CONVERT_USAGE,
|
|
89
|
+
description="The full conversion: article.html, outline.txt, images/ and manifest.json in OUT.",
|
|
90
|
+
)
|
|
91
|
+
_add_render_arguments(p)
|
|
92
|
+
p.add_argument(
|
|
93
|
+
"--heading-map",
|
|
94
|
+
choices=MAP_CHOICES,
|
|
95
|
+
default=MAP_AUTO,
|
|
96
|
+
help="override the heading restructuring (default: auto)",
|
|
97
|
+
)
|
|
98
|
+
p.add_argument("--json", action="store_true", help="print a JSON summary to stdout")
|
|
99
|
+
p.add_argument("-v", "--verbose", action="store_true", help="full error details")
|
|
100
|
+
p.add_argument("--open", action="store_true", help="open the output folder when done")
|
|
101
|
+
check.add_scan_arguments(p, require_privacy_flag=True)
|
|
102
|
+
return p
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
106
|
+
p = _ErrorParser(
|
|
107
|
+
prog="md2xarticle",
|
|
108
|
+
description=(
|
|
109
|
+
f"Markdown in, X Article out. Full conversion: {CONVERT_USAGE} "
|
|
110
|
+
"(md2xarticle ARTICLE.md --help lists its flags). Commands below do one part."
|
|
111
|
+
),
|
|
112
|
+
)
|
|
113
|
+
p.add_argument("--version", action="version", version=f"md2xarticle {__version__}")
|
|
114
|
+
sub = p.add_subparsers(dest="command", metavar="COMMAND", parser_class=_ErrorParser)
|
|
115
|
+
d = sub.add_parser(
|
|
116
|
+
"diagrams",
|
|
117
|
+
help="render every Mermaid block to a centered 16:9 PNG, plus an optional 5:2 cover",
|
|
118
|
+
description="Render every Mermaid block to a centered 16:9 PNG in OUT/images/.",
|
|
119
|
+
)
|
|
120
|
+
_add_render_arguments(d)
|
|
121
|
+
d.add_argument("--json", action="store_true", help="print a JSON summary to stdout")
|
|
122
|
+
d.add_argument("-v", "--verbose", action="store_true", help="full error details")
|
|
123
|
+
check.add_scan_arguments(d, require_privacy_flag=True)
|
|
124
|
+
outline.add_parser(sub)
|
|
125
|
+
check.add_parser(sub)
|
|
126
|
+
return p
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _short(message: str) -> str:
|
|
130
|
+
"""First line of a renderer error, plus the next line when the first ends in ':'."""
|
|
131
|
+
lines = [ln.strip() for ln in message.splitlines() if ln.strip()]
|
|
132
|
+
if not lines:
|
|
133
|
+
return "unknown error"
|
|
134
|
+
if lines[0].endswith(":") and len(lines) > 1:
|
|
135
|
+
return f"{lines[0]} near {lines[1]!r}"
|
|
136
|
+
return lines[0]
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _retry_hint(args: argparse.Namespace, index: int) -> str:
|
|
140
|
+
parts = ["md2xarticle", "diagrams", str(args.article)]
|
|
141
|
+
if args.custom_path is not None:
|
|
142
|
+
parts += ["--custom-path", str(args.custom_path)]
|
|
143
|
+
if args.theme is not None:
|
|
144
|
+
parts += ["--theme", args.theme]
|
|
145
|
+
parts += ["--only", str(index), "--verbose"]
|
|
146
|
+
return " ".join(parts)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _options(args: argparse.Namespace, custom: Customization, out_dir: Path, warn: list[str]) -> DiagramsOptions:
|
|
150
|
+
size = (1600, 900)
|
|
151
|
+
if args.size is not None:
|
|
152
|
+
size = parse_size(args.size, (16, 9), "--size")
|
|
153
|
+
if custom.size is not None:
|
|
154
|
+
if args.size is not None and custom.size != size:
|
|
155
|
+
warn.append("--size is overridden by the customization file")
|
|
156
|
+
size = custom.size
|
|
157
|
+
return DiagramsOptions(
|
|
158
|
+
out_dir=out_dir,
|
|
159
|
+
size=size,
|
|
160
|
+
cover=args.cover,
|
|
161
|
+
cover_size=custom.cover_size or (1500, 600),
|
|
162
|
+
cover_diagram=custom.cover_diagram,
|
|
163
|
+
cover_title_only=custom.cover_title_only,
|
|
164
|
+
cover_title=custom.cover_title,
|
|
165
|
+
cover_subtitle=custom.cover_subtitle,
|
|
166
|
+
only=args.only,
|
|
167
|
+
overrides=custom.diagrams,
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _write_manifest(args: argparse.Namespace, out_dir: Path, result: DiagramsResult) -> str:
|
|
172
|
+
included = {r.index: r.file for r in result.images if r.ok and r.file}
|
|
173
|
+
article = build_article(
|
|
174
|
+
result.document,
|
|
175
|
+
source=args.article.name,
|
|
176
|
+
cover=result.cover,
|
|
177
|
+
included=included,
|
|
178
|
+
)
|
|
179
|
+
paths = factory.make_writer().write(article, out_dir)
|
|
180
|
+
return paths[0].as_posix()
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _summary_json(
|
|
184
|
+
args: argparse.Namespace,
|
|
185
|
+
out_dir: Path,
|
|
186
|
+
result: DiagramsResult,
|
|
187
|
+
notes: list[str],
|
|
188
|
+
manifest: str,
|
|
189
|
+
findings: list[Finding] | None = None,
|
|
190
|
+
) -> dict:
|
|
191
|
+
data = {
|
|
192
|
+
"ok": not result.failed and not findings,
|
|
193
|
+
"out_dir": out_dir.as_posix(),
|
|
194
|
+
"manifest": manifest,
|
|
195
|
+
"images": [
|
|
196
|
+
{
|
|
197
|
+
"order": r.index,
|
|
198
|
+
"file": r.file,
|
|
199
|
+
"source_line": r.line,
|
|
200
|
+
"ok": r.ok,
|
|
201
|
+
"error": r.error,
|
|
202
|
+
}
|
|
203
|
+
for r in result.images
|
|
204
|
+
],
|
|
205
|
+
"cover": result.cover,
|
|
206
|
+
"warnings": result.warnings,
|
|
207
|
+
"notes": notes,
|
|
208
|
+
}
|
|
209
|
+
if findings is not None:
|
|
210
|
+
data["privacy_findings"] = findings_as_json(args.article, findings)
|
|
211
|
+
return data
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _inputs(args: argparse.Namespace, warnings: list[str]):
|
|
215
|
+
"""Theme, deny-list, customization and article text, shared by both renders."""
|
|
216
|
+
if args.theme is not None and args.theme not in BUILTIN_THEMES:
|
|
217
|
+
raise UsageError(
|
|
218
|
+
f"unknown theme {args.theme!r}; built-in themes: {', '.join(BUILTIN_THEMES)}",
|
|
219
|
+
try_cmd=f"md2xarticle diagrams {args.article} --theme {DEFAULT_THEME}",
|
|
220
|
+
)
|
|
221
|
+
deny = check.load_deny(args.deny_list) if args.check_privacy else ()
|
|
222
|
+
custom = load(args.custom_path) if args.custom_path is not None else Customization()
|
|
223
|
+
if custom.theme_name and args.theme and custom.theme_name != args.theme:
|
|
224
|
+
warnings.append("--theme is overridden by the customization file")
|
|
225
|
+
theme = custom.build_theme(args.theme or DEFAULT_THEME)
|
|
226
|
+
try:
|
|
227
|
+
text = args.article.read_text(encoding="utf-8")
|
|
228
|
+
except FileNotFoundError:
|
|
229
|
+
raise UsageError(
|
|
230
|
+
f"file not found: {args.article}",
|
|
231
|
+
try_cmd=f"md2xarticle diagrams {args.article}",
|
|
232
|
+
) from None
|
|
233
|
+
except (OSError, UnicodeDecodeError) as exc:
|
|
234
|
+
raise UsageError(
|
|
235
|
+
f"cannot read {args.article}: {exc}",
|
|
236
|
+
try_cmd=f"md2xarticle diagrams {args.article}",
|
|
237
|
+
) from None
|
|
238
|
+
return deny, custom, theme, text
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _print_failures(args: argparse.Namespace, result: DiagramsResult) -> None:
|
|
242
|
+
for r in result.failed:
|
|
243
|
+
message = r.error or "unknown error"
|
|
244
|
+
if not args.verbose:
|
|
245
|
+
message = _short(message)
|
|
246
|
+
print_error(
|
|
247
|
+
f"diagram {r.index:02d} ({args.article.name} line {r.line}) "
|
|
248
|
+
f"failed to render: {message}",
|
|
249
|
+
try_cmd=_retry_hint(args, r.index),
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def run_diagrams(args: argparse.Namespace) -> int:
|
|
254
|
+
warnings: list[str] = []
|
|
255
|
+
deny, custom, theme, text = _inputs(args, warnings)
|
|
256
|
+
|
|
257
|
+
platform = factory.detect_platform()
|
|
258
|
+
out_dir = args.out if args.out is not None else platform.default_output_dir()
|
|
259
|
+
opts = _options(args, custom, out_dir, warnings)
|
|
260
|
+
pipeline = factory.build_pipeline(
|
|
261
|
+
theme, renderer=args.renderer, platform=platform, article=args.article
|
|
262
|
+
)
|
|
263
|
+
result = pipeline.run_diagrams(text, opts)
|
|
264
|
+
result.warnings[:0] = warnings
|
|
265
|
+
notes = platform.notes()
|
|
266
|
+
findings = scan_text(text, deny) if args.check_privacy else None
|
|
267
|
+
manifest = _write_manifest(args, out_dir, result)
|
|
268
|
+
|
|
269
|
+
for w in result.warnings:
|
|
270
|
+
print(f"warning: {w}", file=sys.stderr)
|
|
271
|
+
_print_failures(args, result)
|
|
272
|
+
|
|
273
|
+
if args.json:
|
|
274
|
+
print(json.dumps(_summary_json(args, out_dir, result, notes, manifest, findings), indent=2))
|
|
275
|
+
else:
|
|
276
|
+
print(f"md2xarticle {__version__} diagrams {args.article.name} -> {out_dir.as_posix()}/")
|
|
277
|
+
for r in result.images:
|
|
278
|
+
status = r.file if r.ok else "FAILED"
|
|
279
|
+
print(f" {r.index:02d} {status} (line {r.line})")
|
|
280
|
+
if result.cover:
|
|
281
|
+
print(f" cover {result.cover} 5:2")
|
|
282
|
+
ok = sum(1 for r in result.images if r.ok)
|
|
283
|
+
if not result.images:
|
|
284
|
+
print("No Mermaid diagrams found.")
|
|
285
|
+
print(
|
|
286
|
+
f"Wrote {ok} image(s){' and a cover' if result.cover else ''} "
|
|
287
|
+
f"to {out_dir.as_posix()}/images/, and {manifest}"
|
|
288
|
+
)
|
|
289
|
+
for n in notes:
|
|
290
|
+
print(n)
|
|
291
|
+
if findings is not None:
|
|
292
|
+
print(format_findings(args.article, findings), end="")
|
|
293
|
+
return EXIT_FINDINGS if result.failed or findings else EXIT_OK
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _fallback_warnings(entries: tuple[OutlineEntry, ...], mapping: str) -> list[str]:
|
|
297
|
+
return [
|
|
298
|
+
f"heading on line {e.line} ({e.text!r}) has no row in the {mapping} mapping; treated as Heading"
|
|
299
|
+
for e in entries
|
|
300
|
+
]
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _anchor(text: str | None) -> str:
|
|
304
|
+
if not text:
|
|
305
|
+
return ""
|
|
306
|
+
if len(text) > ANCHOR_CHARS:
|
|
307
|
+
text = text[: ANCHOR_CHARS - 3].rstrip() + "..."
|
|
308
|
+
return f'(after "{text}")'
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def _convert_text(
|
|
312
|
+
args: argparse.Namespace,
|
|
313
|
+
out_dir: Path,
|
|
314
|
+
result: ConvertResult,
|
|
315
|
+
paths: dict[str, Path],
|
|
316
|
+
notes: list[str],
|
|
317
|
+
seconds: float,
|
|
318
|
+
) -> str:
|
|
319
|
+
d = result.diagrams
|
|
320
|
+
lines = [f"md2xarticle {__version__} {args.article.name} -> {out_dir.as_posix()}/", ""]
|
|
321
|
+
lines.append(format_outline(result.outline).rstrip("\n"))
|
|
322
|
+
lines.append("")
|
|
323
|
+
captions = {ref.order: ref for ref in result.article.images}
|
|
324
|
+
if d.images or d.cover:
|
|
325
|
+
lines.append("Images")
|
|
326
|
+
width = max((len(ref.caption) for ref in captions.values()), default=0)
|
|
327
|
+
for r in d.images:
|
|
328
|
+
if not r.ok:
|
|
329
|
+
lines.append(f" {r.index:02d} FAILED (line {r.line})")
|
|
330
|
+
continue
|
|
331
|
+
ref = captions[r.index]
|
|
332
|
+
lines.append(f" {r.index:02d} {r.file} {ref.caption.ljust(width)} {_anchor(ref.anchor_text)}".rstrip())
|
|
333
|
+
if d.cover:
|
|
334
|
+
lines.append(f" cover {d.cover} 5:2")
|
|
335
|
+
else:
|
|
336
|
+
lines.append("No Mermaid diagrams found.")
|
|
337
|
+
lines.append("")
|
|
338
|
+
count = sum(1 for r in d.images if r.ok) + (1 if d.cover else 0)
|
|
339
|
+
names = ", ".join(p.as_posix() for p in paths.values())
|
|
340
|
+
lines.append(f"Wrote {names}, {count} image{'' if count == 1 else 's'} in {seconds:.1f}s")
|
|
341
|
+
lines.append("")
|
|
342
|
+
html = paths.get("article.html", out_dir / "article.html").as_posix()
|
|
343
|
+
if count:
|
|
344
|
+
lines.append(f"Next: open {html}, copy all, paste into the X Article editor,")
|
|
345
|
+
lines.append("then upload images in order at each [Image NN] marker.")
|
|
346
|
+
else:
|
|
347
|
+
lines.append(f"Next: open {html}, copy all, paste into the X Article editor.")
|
|
348
|
+
lines.extend(notes)
|
|
349
|
+
return "\n".join(lines) + "\n"
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def run_convert(args: argparse.Namespace) -> int:
|
|
353
|
+
started = time.monotonic()
|
|
354
|
+
warnings: list[str] = []
|
|
355
|
+
deny, custom, theme, text = _inputs(args, warnings)
|
|
356
|
+
platform = factory.detect_platform()
|
|
357
|
+
out_dir = args.out if args.out is not None else platform.default_output_dir()
|
|
358
|
+
opts = ConvertOptions(
|
|
359
|
+
diagrams=_options(args, custom, out_dir, warnings),
|
|
360
|
+
source=args.article.name,
|
|
361
|
+
heading_map=args.heading_map,
|
|
362
|
+
deny=deny if args.check_privacy else None,
|
|
363
|
+
)
|
|
364
|
+
pipeline = factory.build_pipeline(theme, renderer=args.renderer, platform=platform, article=args.article)
|
|
365
|
+
result = pipeline.run(text, opts)
|
|
366
|
+
d = result.diagrams
|
|
367
|
+
fallbacks = result.outline.fallbacks
|
|
368
|
+
d.warnings[:0] = warnings
|
|
369
|
+
d.warnings.extend(_fallback_warnings(fallbacks, result.outline.mapping))
|
|
370
|
+
notes = platform.notes()
|
|
371
|
+
paths = {p.name: p for p in result.written}
|
|
372
|
+
|
|
373
|
+
for w in d.warnings:
|
|
374
|
+
print(f"warning: {w}", file=sys.stderr)
|
|
375
|
+
if fallbacks:
|
|
376
|
+
print(f"try: md2xarticle {args.article} --heading-map {MAP_FLAT}", file=sys.stderr)
|
|
377
|
+
_print_failures(args, d)
|
|
378
|
+
findings = result.findings
|
|
379
|
+
failed = bool(d.failed or findings or fallbacks)
|
|
380
|
+
|
|
381
|
+
if args.json:
|
|
382
|
+
data = {
|
|
383
|
+
"ok": not failed,
|
|
384
|
+
"out_dir": out_dir.as_posix(),
|
|
385
|
+
"html": _posix(paths.get("article.html")),
|
|
386
|
+
"outline": _posix(paths.get("outline.txt")),
|
|
387
|
+
"manifest": _posix(paths.get("manifest.json")),
|
|
388
|
+
"images": sum(1 for r in d.images if r.ok),
|
|
389
|
+
"cover": d.cover is not None,
|
|
390
|
+
"failed": [
|
|
391
|
+
{"order": r.index, "source_line": r.line, "error": r.error} for r in d.failed
|
|
392
|
+
],
|
|
393
|
+
"warnings": d.warnings,
|
|
394
|
+
"privacy_findings": findings_as_json(args.article, findings or []),
|
|
395
|
+
"notes": notes,
|
|
396
|
+
}
|
|
397
|
+
print(json.dumps(data, indent=2))
|
|
398
|
+
else:
|
|
399
|
+
sys.stdout.write(_convert_text(args, out_dir, result, paths, notes, time.monotonic() - started))
|
|
400
|
+
if findings is not None:
|
|
401
|
+
print(format_findings(args.article, findings), end="")
|
|
402
|
+
if args.open:
|
|
403
|
+
platform.open_result(out_dir)
|
|
404
|
+
return EXIT_FINDINGS if failed else EXIT_OK
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def _posix(path: Path | None) -> str | None:
|
|
408
|
+
return path.as_posix() if path is not None else None
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def _is_convert(argv: list[str]) -> bool:
|
|
412
|
+
return bool(argv) and argv[0] not in COMMANDS and argv[0] not in ("-h", "--help", "--version")
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def main(argv: list[str] | None = None) -> int:
|
|
416
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
417
|
+
convert = _is_convert(argv)
|
|
418
|
+
parser = build_convert_parser() if convert else build_parser()
|
|
419
|
+
args = parser.parse_args(argv)
|
|
420
|
+
if convert:
|
|
421
|
+
args.command = None
|
|
422
|
+
elif args.command is None:
|
|
423
|
+
parser.print_help(sys.stderr)
|
|
424
|
+
return EXIT_USAGE
|
|
425
|
+
shown = convert_cmd if convert else (lambda cmd: cmd)
|
|
426
|
+
try:
|
|
427
|
+
if convert:
|
|
428
|
+
return run_convert(args)
|
|
429
|
+
if args.command == "outline":
|
|
430
|
+
return outline.run(args)
|
|
431
|
+
if args.command == "check":
|
|
432
|
+
return check.run_check(args)
|
|
433
|
+
return run_diagrams(args)
|
|
434
|
+
except UsageError as exc:
|
|
435
|
+
print_error(
|
|
436
|
+
str(exc),
|
|
437
|
+
try_cmd=shown(
|
|
438
|
+
usage_retry(
|
|
439
|
+
exc,
|
|
440
|
+
article=getattr(args, "article", "article.md"),
|
|
441
|
+
command=args.command or "diagrams",
|
|
442
|
+
custom_path=getattr(args, "custom_path", None),
|
|
443
|
+
size_flag=getattr(args, "size", None) is not None,
|
|
444
|
+
)
|
|
445
|
+
),
|
|
446
|
+
or_cmd=shown(exc.or_cmd),
|
|
447
|
+
)
|
|
448
|
+
return EXIT_USAGE
|
|
449
|
+
except Exception as exc: # last-resort guard; exit 3 means a bug in md2xarticle
|
|
450
|
+
verbose = getattr(args, "verbose", False)
|
|
451
|
+
command = args.command or "diagrams"
|
|
452
|
+
article = getattr(args, "article", "article.md")
|
|
453
|
+
print_error(
|
|
454
|
+
f"internal error: {type(exc).__name__}: {exc}",
|
|
455
|
+
try_cmd=None if verbose else shown(f"md2xarticle {command} {article} --verbose"),
|
|
456
|
+
)
|
|
457
|
+
if verbose:
|
|
458
|
+
traceback.print_exc()
|
|
459
|
+
return EXIT_INTERNAL
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""See base.py for the interface."""
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
|
|
5
|
+
from PIL import Image
|
|
6
|
+
|
|
7
|
+
from md2xarticle.model import RenderedImage
|
|
8
|
+
from md2xarticle.theme import Theme
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class ImageComposer(ABC):
|
|
12
|
+
"""Places a rendered diagram on a fixed-size canvas.
|
|
13
|
+
|
|
14
|
+
Output is exactly ``size``, content centered within ``center_tolerance``
|
|
15
|
+
pixels, with at least 4% margin on every side.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
name: str = ""
|
|
19
|
+
ratio: tuple[int, int] = (16, 9)
|
|
20
|
+
default_size: tuple[int, int] = (1600, 900)
|
|
21
|
+
|
|
22
|
+
def __init__(self, theme: Theme) -> None:
|
|
23
|
+
self.theme = theme
|
|
24
|
+
|
|
25
|
+
@property
|
|
26
|
+
def center_tolerance(self) -> int:
|
|
27
|
+
return 4
|
|
28
|
+
|
|
29
|
+
def diagram_box(self, size: tuple[int, int]) -> tuple[int, int]:
|
|
30
|
+
"""The largest box the diagram is fitted into on a ``size`` canvas."""
|
|
31
|
+
m = self.theme.margin
|
|
32
|
+
return round(size[0] * (1 - 2 * m)), round(size[1] * (1 - 2 * m))
|
|
33
|
+
|
|
34
|
+
@abstractmethod
|
|
35
|
+
def compose(self, image: RenderedImage | None, size: tuple[int, int]) -> Image.Image:
|
|
36
|
+
"""Return an RGB image of exactly ``size``."""
|
|
37
|
+
|
|
38
|
+
def check_size(self, size: tuple[int, int]) -> None:
|
|
39
|
+
w, h = size
|
|
40
|
+
rw, rh = self.ratio
|
|
41
|
+
if w <= 0 or h <= 0 or w * rh != h * rw:
|
|
42
|
+
raise ValueError(f"{self.name} canvas must be {rw}:{rh}, got {w}x{h}")
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from PIL import Image
|
|
4
|
+
|
|
5
|
+
from md2xarticle.compose.base import ImageComposer
|
|
6
|
+
from md2xarticle.compose.fit import fit
|
|
7
|
+
from md2xarticle.model import RenderedImage
|
|
8
|
+
from md2xarticle.theme import hex_to_rgb
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class BodyImageComposer(ImageComposer):
|
|
12
|
+
"""16:9 body image: trim, scale to fit with even padding, center."""
|
|
13
|
+
|
|
14
|
+
name = "body"
|
|
15
|
+
ratio = (16, 9)
|
|
16
|
+
default_size = (1600, 900)
|
|
17
|
+
|
|
18
|
+
def compose(self, image: RenderedImage | None, size: tuple[int, int]) -> Image.Image:
|
|
19
|
+
self.check_size(size)
|
|
20
|
+
cw, ch = size
|
|
21
|
+
canvas = Image.new("RGB", size, hex_to_rgb(self.theme.canvas))
|
|
22
|
+
if image is None:
|
|
23
|
+
return canvas
|
|
24
|
+
fitted = fit(image, self.diagram_box(size), self.theme.canvas, self.theme.max_scale)
|
|
25
|
+
if fitted is not None:
|
|
26
|
+
canvas.paste(fitted, ((cw - fitted.width) // 2, (ch - fitted.height) // 2))
|
|
27
|
+
return canvas
|