mddoco 2.2.1__tar.gz → 2.3.0__tar.gz
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.
- {mddoco-2.2.1/src/mddoco.egg-info → mddoco-2.3.0}/PKG-INFO +59 -8
- {mddoco-2.2.1 → mddoco-2.3.0}/README.md +58 -7
- {mddoco-2.2.1 → mddoco-2.3.0}/pyproject.toml +1 -1
- mddoco-2.3.0/src/mddoco/__init__.py +1 -0
- {mddoco-2.2.1 → mddoco-2.3.0}/src/mddoco/cli.py +2 -2
- {mddoco-2.2.1 → mddoco-2.3.0}/src/mddoco/converter.py +13 -8
- mddoco-2.3.0/src/mddoco/d2.py +83 -0
- {mddoco-2.2.1 → mddoco-2.3.0}/src/mddoco/themes/_site_base.html +2 -1
- {mddoco-2.2.1 → mddoco-2.3.0}/src/mddoco/themes/academic.html +3 -2
- {mddoco-2.2.1 → mddoco-2.3.0}/src/mddoco/themes/dark.html +3 -2
- {mddoco-2.2.1 → mddoco-2.3.0}/src/mddoco/themes/default.html +3 -2
- {mddoco-2.2.1 → mddoco-2.3.0}/src/mddoco/themes/paged-professional.html +2 -1
- {mddoco-2.2.1 → mddoco-2.3.0}/src/mddoco/themes/professional.html +2 -1
- mddoco-2.3.0/src/mddoco/toc.py +63 -0
- {mddoco-2.2.1 → mddoco-2.3.0/src/mddoco.egg-info}/PKG-INFO +59 -8
- {mddoco-2.2.1 → mddoco-2.3.0}/src/mddoco.egg-info/SOURCES.txt +4 -1
- mddoco-2.3.0/tests/test_d2.py +113 -0
- {mddoco-2.2.1 → mddoco-2.3.0}/tests/test_preprocessor.py +1 -1
- mddoco-2.3.0/tests/test_toc.py +65 -0
- mddoco-2.2.1/src/mddoco/__init__.py +0 -1
- mddoco-2.2.1/src/mddoco/toc.py +0 -15
- {mddoco-2.2.1 → mddoco-2.3.0}/LICENSE +0 -0
- {mddoco-2.2.1 → mddoco-2.3.0}/setup.cfg +0 -0
- {mddoco-2.2.1 → mddoco-2.3.0}/src/mddoco/graph.py +0 -0
- {mddoco-2.2.1 → mddoco-2.3.0}/src/mddoco/mermaid.py +0 -0
- {mddoco-2.2.1 → mddoco-2.3.0}/src/mddoco/pdf.py +0 -0
- {mddoco-2.2.1 → mddoco-2.3.0}/src/mddoco/preprocessor.py +0 -0
- {mddoco-2.2.1 → mddoco-2.3.0}/src/mddoco/renderer.py +0 -0
- {mddoco-2.2.1 → mddoco-2.3.0}/src/mddoco/scanner.py +0 -0
- {mddoco-2.2.1 → mddoco-2.3.0}/src/mddoco/themes/academic-wide.html +0 -0
- {mddoco-2.2.1 → mddoco-2.3.0}/src/mddoco/themes/dark-wide.html +0 -0
- {mddoco-2.2.1 → mddoco-2.3.0}/src/mddoco/themes/default-wide.html +0 -0
- {mddoco-2.2.1 → mddoco-2.3.0}/src/mddoco/themes/professional-wide.html +0 -0
- {mddoco-2.2.1 → mddoco-2.3.0}/src/mddoco/themes/site-dark.html +0 -0
- {mddoco-2.2.1 → mddoco-2.3.0}/src/mddoco/themes/site-professional.html +0 -0
- {mddoco-2.2.1 → mddoco-2.3.0}/src/mddoco/themes/site-terminal.html +0 -0
- {mddoco-2.2.1 → mddoco-2.3.0}/src/mddoco/themes/site.html +0 -0
- {mddoco-2.2.1 → mddoco-2.3.0}/src/mddoco/themes/vanilla.html +0 -0
- {mddoco-2.2.1 → mddoco-2.3.0}/src/mddoco/writer.py +0 -0
- {mddoco-2.2.1 → mddoco-2.3.0}/src/mddoco.egg-info/dependency_links.txt +0 -0
- {mddoco-2.2.1 → mddoco-2.3.0}/src/mddoco.egg-info/entry_points.txt +0 -0
- {mddoco-2.2.1 → mddoco-2.3.0}/src/mddoco.egg-info/requires.txt +0 -0
- {mddoco-2.2.1 → mddoco-2.3.0}/src/mddoco.egg-info/top_level.txt +0 -0
- {mddoco-2.2.1 → mddoco-2.3.0}/tests/test_themes.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: mddoco
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.3.0
|
|
4
4
|
Summary: Markdown to HTML/PDF document converter
|
|
5
5
|
Author-email: Phil Massyn <phil.massyn@icloud.com>
|
|
6
6
|
Project-URL: Homepage, https://github.com/massyn/mddoco
|
|
@@ -22,12 +22,14 @@ Dynamic: license-file
|
|
|
22
22
|
|
|
23
23
|
# mddoco
|
|
24
24
|
|
|
25
|
-
A CLI tool that converts markdown files to a single HTML
|
|
25
|
+
A CLI tool that converts markdown files to a single HTML or PDF document.
|
|
26
26
|
|
|
27
27
|
[](https://github.com/massyn/mddoco/actions/workflows/ci.yml)
|
|
28
28
|
 
|
|
29
29
|
## Installation
|
|
30
30
|
|
|
31
|
+
mddoco needs Python 3.10 or newer.
|
|
32
|
+
|
|
31
33
|
```bash
|
|
32
34
|
pip install mddoco
|
|
33
35
|
```
|
|
@@ -48,6 +50,10 @@ pip install -e .
|
|
|
48
50
|
> playwright install chromium
|
|
49
51
|
> ```
|
|
50
52
|
|
|
53
|
+
> **The `d2` command-line tool is required only if your documents contain
|
|
54
|
+
> [D2 diagrams](#d2-diagrams).** It is a separate program, not a Python
|
|
55
|
+
> package, so `pip` does not install it. See [Installing the D2 CLI](#installing-the-d2-cli).
|
|
56
|
+
|
|
51
57
|
## Usage
|
|
52
58
|
|
|
53
59
|
```
|
|
@@ -60,8 +66,8 @@ mddoco [OPTIONS] INPUT_PATH
|
|
|
60
66
|
|
|
61
67
|
| Option | Short | Default | Description |
|
|
62
68
|
|---|---|---|---|
|
|
63
|
-
| `--output PATH` | `-o` | `.` |
|
|
64
|
-
| `--format [html\|pdf]` | `-f` | `html` | Output format |
|
|
69
|
+
| `--output PATH` | `-o` | `.` | Output directory, or an explicit file path if it has an extension (`-o out/report.html`) |
|
|
70
|
+
| `--format [html\|pdf]` | `-f` | `html` | Output format (PDF needs Playwright; the `site-*` themes are HTML only) |
|
|
65
71
|
| `--title TEXT` | `-t` | _(none)_ | Document title shown at the top of the page |
|
|
66
72
|
| `--theme NAME` | | `default` | Theme to use for rendering |
|
|
67
73
|
| `--toc / --no-toc` | | off | Generate a table of contents |
|
|
@@ -89,11 +95,11 @@ mddoco ./docs --title "My Project" --toc --output ./out
|
|
|
89
95
|
|
|
90
96
|
## Output
|
|
91
97
|
|
|
92
|
-
All matched markdown files are combined into a single
|
|
98
|
+
All matched markdown files are combined into a single document in the output directory, as HTML (the default) or PDF (`--format pdf`). The filename is derived from the input folder or file name, with the `.html` or `.pdf` extension. If `--output` ends in an extension, it is used as the exact output file path instead.
|
|
93
99
|
|
|
94
100
|
## Examples
|
|
95
101
|
|
|
96
|
-
The [`examples/`](examples/) directory contains
|
|
102
|
+
The [`examples/`](examples/) directory contains six runnable input folders, each
|
|
97
103
|
covering a different feature:
|
|
98
104
|
|
|
99
105
|
| Folder | Demonstrates |
|
|
@@ -103,6 +109,7 @@ covering a different feature:
|
|
|
103
109
|
| [`examples/03_themed_report`](examples/03_themed_report) | Themes and a table of contents |
|
|
104
110
|
| [`examples/04_jinja_data`](examples/04_jinja_data) | Jinja2 templates with JSON and CSV data files |
|
|
105
111
|
| [`examples/05_security_findings`](examples/05_security_findings) | CSV data grouped in a Jinja2 template and fed into a `graph` chart |
|
|
112
|
+
| [`examples/06_d2_diagrams`](examples/06_d2_diagrams) | D2 diagrams (requires the `d2` CLI) |
|
|
106
113
|
|
|
107
114
|
```bash
|
|
108
115
|
mddoco examples/03_themed_report --theme professional --title "Q3 Platform Review" --toc --output ./out
|
|
@@ -205,7 +212,9 @@ All themes support:
|
|
|
205
212
|
|
|
206
213
|
- Optional document title
|
|
207
214
|
- Optional table of contents (the `site-*` themes use their side nav instead)
|
|
208
|
-
- [
|
|
215
|
+
- Syntax highlighting for code blocks ([highlight.js](https://highlightjs.org), loaded from a CDN only when code blocks are present)
|
|
216
|
+
- [Mermaid.js](https://mermaid.js.org) diagram support (loaded from a CDN only when diagrams are present)
|
|
217
|
+
- [D2](https://d2lang.com) diagrams, rendered to inline SVG at build time (needs the `d2` CLI, only when diagrams are present)
|
|
209
218
|
- Graph diagram blocks
|
|
210
219
|
|
|
211
220
|
### Site themes
|
|
@@ -249,7 +258,7 @@ Use ` ```graph ` fenced blocks with a JSON payload. The only required field is `
|
|
|
249
258
|
```
|
|
250
259
|
````
|
|
251
260
|
|
|
252
|
-
Series are inferred from the data keys (everything except `x`). Each series defaults to a line chart in
|
|
261
|
+
Series are inferred from the data keys (everything except `x`). Each series defaults to a line chart, coloured from a built-in palette.
|
|
253
262
|
|
|
254
263
|
**Full schema:**
|
|
255
264
|
|
|
@@ -307,3 +316,45 @@ graph TD
|
|
|
307
316
|
````
|
|
308
317
|
|
|
309
318
|
mddoco detects mermaid blocks automatically and loads the Mermaid.js CDN only when needed.
|
|
319
|
+
|
|
320
|
+
### D2 diagrams
|
|
321
|
+
|
|
322
|
+
[D2](https://d2lang.com) diagrams use the same fenced-block syntax:
|
|
323
|
+
|
|
324
|
+
````markdown
|
|
325
|
+
```d2
|
|
326
|
+
direction: right
|
|
327
|
+
client -> server: request
|
|
328
|
+
server -> db: query
|
|
329
|
+
```
|
|
330
|
+
````
|
|
331
|
+
|
|
332
|
+
Unlike Mermaid, D2 diagrams are rendered while mddoco builds the document, by the `d2` command-line tool, and embedded as inline SVG. The output has no extra scripts, works offline, and prints to PDF without waiting for anything to load.
|
|
333
|
+
|
|
334
|
+
- The `d2` CLI must be installed and on your `PATH` (see below). It is only needed when a document contains a `d2` block; otherwise mddoco never looks for it.
|
|
335
|
+
- A diagram that fails to compile stops the build with D2's error message, the same as an invalid `graph` block.
|
|
336
|
+
- A diagram that takes longer than 30 seconds to compile stops the build with a timeout error.
|
|
337
|
+
|
|
338
|
+
#### Installing the D2 CLI
|
|
339
|
+
|
|
340
|
+
`d2` is a standalone program from the [D2 project](https://d2lang.com), not a Python package. Install it with one of the following, then check that it is on your `PATH`:
|
|
341
|
+
|
|
342
|
+
```bash
|
|
343
|
+
d2 --version
|
|
344
|
+
```
|
|
345
|
+
|
|
346
|
+
| Platform | Command |
|
|
347
|
+
|---|---|
|
|
348
|
+
| macOS (Homebrew) | `brew install d2` |
|
|
349
|
+
| Linux and macOS (install script) | `curl -fsSL https://d2lang.com/install.sh \| sh -s --` |
|
|
350
|
+
| Windows (Scoop) | `scoop install main/d2` |
|
|
351
|
+
| Windows (Chocolatey) | `choco install d2` |
|
|
352
|
+
| Windows (installer) | Download the `.msi` from the [releases page](https://github.com/d2lang/d2/releases); it adds `d2` to your `PATH` |
|
|
353
|
+
| Any platform with Go | `go install github.com/d2lang/d2@latest` |
|
|
354
|
+
|
|
355
|
+
- **Install script:** run it with `--dry-run` first (`curl -fsSL https://d2lang.com/install.sh | sh -s -- --dry-run`) to see what it will do. It uses a package manager when it finds one, and otherwise installs under `/usr/local`, or `~/.local` if `/usr/local` needs `sudo`. If it tells you to adjust `PATH`, do that.
|
|
356
|
+
- **Standalone download:** archives for each platform are on the [releases page](https://github.com/d2lang/d2/releases). Extract one and run `make install`, or `make install PREFIX=$HOME/.local` to install without `sudo`.
|
|
357
|
+
- **Other options and details:** see the [D2 install guide](https://d2lang.com/tour/install).
|
|
358
|
+
- **CI:** install `d2` in the workflow before building documents that contain D2 diagrams, for example by downloading a pinned release archive as this repository's own [workflow](.github/workflows/ci.yml) does.
|
|
359
|
+
|
|
360
|
+
If `d2` is missing, mddoco stops with an error pointing to the install guide, and only when it finds a `d2` block.
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
# mddoco
|
|
2
2
|
|
|
3
|
-
A CLI tool that converts markdown files to a single HTML
|
|
3
|
+
A CLI tool that converts markdown files to a single HTML or PDF document.
|
|
4
4
|
|
|
5
5
|
[](https://github.com/massyn/mddoco/actions/workflows/ci.yml)
|
|
6
6
|
 
|
|
7
7
|
## Installation
|
|
8
8
|
|
|
9
|
+
mddoco needs Python 3.10 or newer.
|
|
10
|
+
|
|
9
11
|
```bash
|
|
10
12
|
pip install mddoco
|
|
11
13
|
```
|
|
@@ -26,6 +28,10 @@ pip install -e .
|
|
|
26
28
|
> playwright install chromium
|
|
27
29
|
> ```
|
|
28
30
|
|
|
31
|
+
> **The `d2` command-line tool is required only if your documents contain
|
|
32
|
+
> [D2 diagrams](#d2-diagrams).** It is a separate program, not a Python
|
|
33
|
+
> package, so `pip` does not install it. See [Installing the D2 CLI](#installing-the-d2-cli).
|
|
34
|
+
|
|
29
35
|
## Usage
|
|
30
36
|
|
|
31
37
|
```
|
|
@@ -38,8 +44,8 @@ mddoco [OPTIONS] INPUT_PATH
|
|
|
38
44
|
|
|
39
45
|
| Option | Short | Default | Description |
|
|
40
46
|
|---|---|---|---|
|
|
41
|
-
| `--output PATH` | `-o` | `.` |
|
|
42
|
-
| `--format [html\|pdf]` | `-f` | `html` | Output format |
|
|
47
|
+
| `--output PATH` | `-o` | `.` | Output directory, or an explicit file path if it has an extension (`-o out/report.html`) |
|
|
48
|
+
| `--format [html\|pdf]` | `-f` | `html` | Output format (PDF needs Playwright; the `site-*` themes are HTML only) |
|
|
43
49
|
| `--title TEXT` | `-t` | _(none)_ | Document title shown at the top of the page |
|
|
44
50
|
| `--theme NAME` | | `default` | Theme to use for rendering |
|
|
45
51
|
| `--toc / --no-toc` | | off | Generate a table of contents |
|
|
@@ -67,11 +73,11 @@ mddoco ./docs --title "My Project" --toc --output ./out
|
|
|
67
73
|
|
|
68
74
|
## Output
|
|
69
75
|
|
|
70
|
-
All matched markdown files are combined into a single
|
|
76
|
+
All matched markdown files are combined into a single document in the output directory, as HTML (the default) or PDF (`--format pdf`). The filename is derived from the input folder or file name, with the `.html` or `.pdf` extension. If `--output` ends in an extension, it is used as the exact output file path instead.
|
|
71
77
|
|
|
72
78
|
## Examples
|
|
73
79
|
|
|
74
|
-
The [`examples/`](examples/) directory contains
|
|
80
|
+
The [`examples/`](examples/) directory contains six runnable input folders, each
|
|
75
81
|
covering a different feature:
|
|
76
82
|
|
|
77
83
|
| Folder | Demonstrates |
|
|
@@ -81,6 +87,7 @@ covering a different feature:
|
|
|
81
87
|
| [`examples/03_themed_report`](examples/03_themed_report) | Themes and a table of contents |
|
|
82
88
|
| [`examples/04_jinja_data`](examples/04_jinja_data) | Jinja2 templates with JSON and CSV data files |
|
|
83
89
|
| [`examples/05_security_findings`](examples/05_security_findings) | CSV data grouped in a Jinja2 template and fed into a `graph` chart |
|
|
90
|
+
| [`examples/06_d2_diagrams`](examples/06_d2_diagrams) | D2 diagrams (requires the `d2` CLI) |
|
|
84
91
|
|
|
85
92
|
```bash
|
|
86
93
|
mddoco examples/03_themed_report --theme professional --title "Q3 Platform Review" --toc --output ./out
|
|
@@ -183,7 +190,9 @@ All themes support:
|
|
|
183
190
|
|
|
184
191
|
- Optional document title
|
|
185
192
|
- Optional table of contents (the `site-*` themes use their side nav instead)
|
|
186
|
-
- [
|
|
193
|
+
- Syntax highlighting for code blocks ([highlight.js](https://highlightjs.org), loaded from a CDN only when code blocks are present)
|
|
194
|
+
- [Mermaid.js](https://mermaid.js.org) diagram support (loaded from a CDN only when diagrams are present)
|
|
195
|
+
- [D2](https://d2lang.com) diagrams, rendered to inline SVG at build time (needs the `d2` CLI, only when diagrams are present)
|
|
187
196
|
- Graph diagram blocks
|
|
188
197
|
|
|
189
198
|
### Site themes
|
|
@@ -227,7 +236,7 @@ Use ` ```graph ` fenced blocks with a JSON payload. The only required field is `
|
|
|
227
236
|
```
|
|
228
237
|
````
|
|
229
238
|
|
|
230
|
-
Series are inferred from the data keys (everything except `x`). Each series defaults to a line chart in
|
|
239
|
+
Series are inferred from the data keys (everything except `x`). Each series defaults to a line chart, coloured from a built-in palette.
|
|
231
240
|
|
|
232
241
|
**Full schema:**
|
|
233
242
|
|
|
@@ -285,3 +294,45 @@ graph TD
|
|
|
285
294
|
````
|
|
286
295
|
|
|
287
296
|
mddoco detects mermaid blocks automatically and loads the Mermaid.js CDN only when needed.
|
|
297
|
+
|
|
298
|
+
### D2 diagrams
|
|
299
|
+
|
|
300
|
+
[D2](https://d2lang.com) diagrams use the same fenced-block syntax:
|
|
301
|
+
|
|
302
|
+
````markdown
|
|
303
|
+
```d2
|
|
304
|
+
direction: right
|
|
305
|
+
client -> server: request
|
|
306
|
+
server -> db: query
|
|
307
|
+
```
|
|
308
|
+
````
|
|
309
|
+
|
|
310
|
+
Unlike Mermaid, D2 diagrams are rendered while mddoco builds the document, by the `d2` command-line tool, and embedded as inline SVG. The output has no extra scripts, works offline, and prints to PDF without waiting for anything to load.
|
|
311
|
+
|
|
312
|
+
- The `d2` CLI must be installed and on your `PATH` (see below). It is only needed when a document contains a `d2` block; otherwise mddoco never looks for it.
|
|
313
|
+
- A diagram that fails to compile stops the build with D2's error message, the same as an invalid `graph` block.
|
|
314
|
+
- A diagram that takes longer than 30 seconds to compile stops the build with a timeout error.
|
|
315
|
+
|
|
316
|
+
#### Installing the D2 CLI
|
|
317
|
+
|
|
318
|
+
`d2` is a standalone program from the [D2 project](https://d2lang.com), not a Python package. Install it with one of the following, then check that it is on your `PATH`:
|
|
319
|
+
|
|
320
|
+
```bash
|
|
321
|
+
d2 --version
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
| Platform | Command |
|
|
325
|
+
|---|---|
|
|
326
|
+
| macOS (Homebrew) | `brew install d2` |
|
|
327
|
+
| Linux and macOS (install script) | `curl -fsSL https://d2lang.com/install.sh \| sh -s --` |
|
|
328
|
+
| Windows (Scoop) | `scoop install main/d2` |
|
|
329
|
+
| Windows (Chocolatey) | `choco install d2` |
|
|
330
|
+
| Windows (installer) | Download the `.msi` from the [releases page](https://github.com/d2lang/d2/releases); it adds `d2` to your `PATH` |
|
|
331
|
+
| Any platform with Go | `go install github.com/d2lang/d2@latest` |
|
|
332
|
+
|
|
333
|
+
- **Install script:** run it with `--dry-run` first (`curl -fsSL https://d2lang.com/install.sh | sh -s -- --dry-run`) to see what it will do. It uses a package manager when it finds one, and otherwise installs under `/usr/local`, or `~/.local` if `/usr/local` needs `sudo`. If it tells you to adjust `PATH`, do that.
|
|
334
|
+
- **Standalone download:** archives for each platform are on the [releases page](https://github.com/d2lang/d2/releases). Extract one and run `make install`, or `make install PREFIX=$HOME/.local` to install without `sudo`.
|
|
335
|
+
- **Other options and details:** see the [D2 install guide](https://d2lang.com/tour/install).
|
|
336
|
+
- **CI:** install `d2` in the workflow before building documents that contain D2 diagrams, for example by downloading a pinned release archive as this repository's own [workflow](.github/workflows/ci.yml) does.
|
|
337
|
+
|
|
338
|
+
If `d2` is missing, mddoco stops with an error pointing to the install guide, and only when it finds a `d2` block.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "2.3.0"
|
|
@@ -8,7 +8,7 @@ from mddoco.pdf import html_to_pdf
|
|
|
8
8
|
from mddoco.preprocessor import load_context
|
|
9
9
|
from mddoco.renderer import check_theme_format, render_html
|
|
10
10
|
from mddoco.scanner import find_markdown_files
|
|
11
|
-
from mddoco.toc import
|
|
11
|
+
from mddoco.toc import build_toc
|
|
12
12
|
from mddoco.writer import write_output
|
|
13
13
|
|
|
14
14
|
|
|
@@ -82,7 +82,7 @@ def main(
|
|
|
82
82
|
except Exception as exc:
|
|
83
83
|
raise click.ClickException(str(exc)) from exc
|
|
84
84
|
sections = [(p, html) for p, html, _ in raw]
|
|
85
|
-
toc_html =
|
|
85
|
+
toc_html = build_toc([e for _, _, entries in raw for e in entries]) if toc else None
|
|
86
86
|
has_mermaid = any('<div class="mermaid">' in html for _, html in sections)
|
|
87
87
|
has_code = any("<pre><code" in html for _, html in sections)
|
|
88
88
|
|
|
@@ -2,9 +2,11 @@ from pathlib import Path
|
|
|
2
2
|
|
|
3
3
|
import markdown
|
|
4
4
|
|
|
5
|
+
from mddoco.d2 import process_d2
|
|
5
6
|
from mddoco.graph import process_graph
|
|
6
7
|
from mddoco.mermaid import process_mermaid
|
|
7
8
|
from mddoco.preprocessor import render_j2
|
|
9
|
+
from mddoco.toc import TocEntry, flatten_tokens
|
|
8
10
|
|
|
9
11
|
|
|
10
12
|
def convert_file(
|
|
@@ -12,12 +14,12 @@ def convert_file(
|
|
|
12
14
|
toc: bool = False,
|
|
13
15
|
toc_depth: int = 3,
|
|
14
16
|
context: dict | None = None,
|
|
15
|
-
) -> tuple[str,
|
|
17
|
+
) -> tuple[str, list[TocEntry]]:
|
|
16
18
|
"""Convert a markdown (or .md.j2) file to an HTML fragment.
|
|
17
19
|
|
|
18
20
|
.md.j2 files are rendered with Jinja2 first using the supplied context,
|
|
19
21
|
then the resulting Markdown is converted as normal.
|
|
20
|
-
Returns (html_body,
|
|
22
|
+
Returns (html_body, toc_entries). toc_entries is empty when toc=False.
|
|
21
23
|
"""
|
|
22
24
|
if path.suffix.lower() == ".j2":
|
|
23
25
|
text = render_j2(path, context or {})
|
|
@@ -35,9 +37,10 @@ def convert_file(
|
|
|
35
37
|
html = md.convert(text)
|
|
36
38
|
html, _ = process_mermaid(html)
|
|
37
39
|
html, _ = process_graph(html)
|
|
40
|
+
html, _ = process_d2(html)
|
|
38
41
|
|
|
39
|
-
|
|
40
|
-
return html,
|
|
42
|
+
toc_entries = flatten_tokens(md.toc_tokens) if toc else []
|
|
43
|
+
return html, toc_entries
|
|
41
44
|
|
|
42
45
|
|
|
43
46
|
def convert_files(
|
|
@@ -45,10 +48,12 @@ def convert_files(
|
|
|
45
48
|
toc: bool = False,
|
|
46
49
|
toc_depth: int = 3,
|
|
47
50
|
context: dict | None = None,
|
|
48
|
-
) -> list[tuple[Path, str,
|
|
49
|
-
"""Convert markdown files, returning (path, html_body,
|
|
51
|
+
) -> list[tuple[Path, str, list[TocEntry]]]:
|
|
52
|
+
"""Convert markdown files, returning (path, html_body, toc_entries) tuples."""
|
|
50
53
|
results = []
|
|
51
54
|
for p in paths:
|
|
52
|
-
html,
|
|
53
|
-
|
|
55
|
+
html, toc_entries = convert_file(
|
|
56
|
+
p, toc=toc, toc_depth=toc_depth, context=context
|
|
57
|
+
)
|
|
58
|
+
results.append((p, html, toc_entries))
|
|
54
59
|
return results
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import re
|
|
3
|
+
import shutil
|
|
4
|
+
import subprocess
|
|
5
|
+
from html import unescape
|
|
6
|
+
|
|
7
|
+
log = logging.getLogger(__name__)
|
|
8
|
+
|
|
9
|
+
_D2_BLOCK = re.compile(
|
|
10
|
+
r'<pre><code class="language-d2">(.*?)</code></pre>',
|
|
11
|
+
re.DOTALL,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
_OUTER_SVG = re.compile(r'(?P<tag><svg\b[^>]*)\sviewBox="(?P<dims>[^"]+)"')
|
|
15
|
+
|
|
16
|
+
_INSTALL_HINT = (
|
|
17
|
+
"D2 diagrams require the 'd2' command-line tool, which was not found on "
|
|
18
|
+
"PATH. Install it from https://d2lang.com/tour/install"
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
_TIMEOUT_SECONDS = 30
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _render_d2(source: str) -> str:
|
|
25
|
+
"""Compile D2 source with the d2 CLI and return an inline SVG element."""
|
|
26
|
+
d2 = shutil.which("d2")
|
|
27
|
+
if d2 is None:
|
|
28
|
+
raise RuntimeError(_INSTALL_HINT)
|
|
29
|
+
|
|
30
|
+
try:
|
|
31
|
+
result = subprocess.run(
|
|
32
|
+
[d2, "-", "-"],
|
|
33
|
+
input=unescape(source),
|
|
34
|
+
capture_output=True,
|
|
35
|
+
text=True,
|
|
36
|
+
encoding="utf-8",
|
|
37
|
+
timeout=_TIMEOUT_SECONDS,
|
|
38
|
+
)
|
|
39
|
+
except subprocess.TimeoutExpired as exc:
|
|
40
|
+
raise RuntimeError(f"d2 timed out after {_TIMEOUT_SECONDS}s") from exc
|
|
41
|
+
|
|
42
|
+
if result.returncode != 0:
|
|
43
|
+
detail = result.stderr.strip() or f"exit code {result.returncode}"
|
|
44
|
+
raise RuntimeError(f"d2 failed: {detail}")
|
|
45
|
+
|
|
46
|
+
start = result.stdout.find("<svg") # skip the XML declaration
|
|
47
|
+
svg = result.stdout[max(start, 0) :]
|
|
48
|
+
svg = _OUTER_SVG.sub(_with_natural_size, svg, count=1)
|
|
49
|
+
return f'<div class="d2">{svg}</div>'
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _with_natural_size(m: re.Match) -> str:
|
|
53
|
+
"""Give the outer <svg> its viewBox size so it is not stretched to fit."""
|
|
54
|
+
dims = m.group("dims")
|
|
55
|
+
width, height = (round(float(v)) for v in dims.split()[2:])
|
|
56
|
+
return f'{m.group("tag")} viewBox="{dims}" width="{width}" height="{height}"'
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def process_d2(html: str) -> tuple[str, bool]:
|
|
60
|
+
"""Replace fenced d2 blocks with SVG diagrams rendered by the d2 CLI.
|
|
61
|
+
|
|
62
|
+
Raises on any render failure — errors are logged before raising so the
|
|
63
|
+
caller sees the problem on the console.
|
|
64
|
+
Returns (processed_html, found).
|
|
65
|
+
"""
|
|
66
|
+
found = bool(_D2_BLOCK.search(html))
|
|
67
|
+
errors: list[Exception] = []
|
|
68
|
+
|
|
69
|
+
def replace(m: re.Match) -> str:
|
|
70
|
+
try:
|
|
71
|
+
return _render_d2(m.group(1))
|
|
72
|
+
except Exception as exc:
|
|
73
|
+
errors.append(exc)
|
|
74
|
+
return ""
|
|
75
|
+
|
|
76
|
+
processed = _D2_BLOCK.sub(replace, html)
|
|
77
|
+
|
|
78
|
+
for exc in errors:
|
|
79
|
+
log.error("D2 error: %s", exc)
|
|
80
|
+
if errors:
|
|
81
|
+
raise errors[0]
|
|
82
|
+
|
|
83
|
+
return processed, found
|
|
@@ -171,7 +171,8 @@
|
|
|
171
171
|
}
|
|
172
172
|
blockquote p { margin: 0.3em 0; }
|
|
173
173
|
|
|
174
|
-
.mermaid { text-align: center; margin: 1.5em 0; }
|
|
174
|
+
.mermaid, .d2 { text-align: center; margin: 1.5em 0; }
|
|
175
|
+
.d2 svg { max-width: 100%; height: auto; }
|
|
175
176
|
|
|
176
177
|
/* ── Previous / next ──────────────────────────────────────── */
|
|
177
178
|
.site-pager {
|
|
@@ -140,11 +140,12 @@
|
|
|
140
140
|
.toc-block a { color: #111; font-size: 0.9em; text-decoration: none; }
|
|
141
141
|
.toc-block a:hover { text-decoration: underline; }
|
|
142
142
|
|
|
143
|
-
/* Mermaid diagrams */
|
|
144
|
-
.mermaid {
|
|
143
|
+
/* Mermaid and D2 diagrams */
|
|
144
|
+
.mermaid, .d2 {
|
|
145
145
|
text-align: center;
|
|
146
146
|
margin: 1.5em 0;
|
|
147
147
|
}
|
|
148
|
+
.d2 svg { max-width: 100%; height: auto; }
|
|
148
149
|
|
|
149
150
|
@media print {
|
|
150
151
|
body { padding: 0; font-size: 12pt; }
|
|
@@ -141,11 +141,12 @@
|
|
|
141
141
|
.toc-block > ul > li > a { font-weight: 700; }
|
|
142
142
|
.toc-block a { color: var(--accent); font-size: 0.9em; }
|
|
143
143
|
|
|
144
|
-
/* Mermaid diagrams */
|
|
145
|
-
.mermaid {
|
|
144
|
+
/* Mermaid and D2 diagrams */
|
|
145
|
+
.mermaid, .d2 {
|
|
146
146
|
text-align: center;
|
|
147
147
|
margin: 1.5em 0;
|
|
148
148
|
}
|
|
149
|
+
.d2 svg { max-width: 100%; height: auto; }
|
|
149
150
|
/* body raises specificity above highlight.js's own pre code.hljs rule, which loads later */
|
|
150
151
|
body pre code.hljs { background: transparent; padding: 0; }
|
|
151
152
|
/* Print: no trailing space after the content, which would spill
|
|
@@ -122,11 +122,12 @@
|
|
|
122
122
|
.toc-block > ul > li > a { font-weight: 700; }
|
|
123
123
|
.toc-block a { color: #0366d6; font-size: 0.9em; }
|
|
124
124
|
|
|
125
|
-
/* Mermaid diagrams */
|
|
126
|
-
.mermaid {
|
|
125
|
+
/* Mermaid and D2 diagrams */
|
|
126
|
+
.mermaid, .d2 {
|
|
127
127
|
text-align: center;
|
|
128
128
|
margin: 1.5em 0;
|
|
129
129
|
}
|
|
130
|
+
.d2 svg { max-width: 100%; height: auto; }
|
|
130
131
|
/* body raises specificity above highlight.js's own pre code.hljs rule, which loads later */
|
|
131
132
|
body pre code.hljs { background: transparent; padding: 0; }
|
|
132
133
|
/* Print: no trailing space after the content, which would spill
|
|
@@ -212,7 +212,8 @@
|
|
|
212
212
|
.toc-block a:hover { color: var(--accent); }
|
|
213
213
|
|
|
214
214
|
/* ── Mermaid ────────────────────────────────────────────────── */
|
|
215
|
-
.mermaid { text-align: center; margin: 1.5em 0; }
|
|
215
|
+
.mermaid, .d2 { text-align: center; margin: 1.5em 0; }
|
|
216
|
+
.d2 svg { max-width: 100%; height: auto; }
|
|
216
217
|
/* body raises specificity above highlight.js's own pre code.hljs rule, which loads later */
|
|
217
218
|
body pre code.hljs { background: transparent; padding: 0; }
|
|
218
219
|
</style>
|
|
@@ -177,7 +177,8 @@
|
|
|
177
177
|
.toc-block a:hover { color: var(--accent); }
|
|
178
178
|
|
|
179
179
|
/* ── Mermaid ───────────────────────────────────────────────── */
|
|
180
|
-
.mermaid { text-align: center; margin: 1.5em 0; }
|
|
180
|
+
.mermaid, .d2 { text-align: center; margin: 1.5em 0; }
|
|
181
|
+
.d2 svg { max-width: 100%; height: auto; }
|
|
181
182
|
/* body raises specificity above highlight.js's own pre code.hljs rule, which loads later */
|
|
182
183
|
body pre code.hljs { background: transparent; padding: 0; }
|
|
183
184
|
/* Print: no trailing space after the content, which would spill
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
from dataclasses import dataclass, field
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
@dataclass
|
|
5
|
+
class TocEntry:
|
|
6
|
+
"""One heading in the table of contents, at its absolute heading level."""
|
|
7
|
+
|
|
8
|
+
level: int
|
|
9
|
+
anchor: str
|
|
10
|
+
label: str
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class _Node:
|
|
15
|
+
entry: TocEntry | None
|
|
16
|
+
children: list["_Node"] = field(default_factory=list)
|
|
17
|
+
|
|
18
|
+
def to_html(self) -> str:
|
|
19
|
+
"""Render this node's link (if any) followed by its children as a <ul>."""
|
|
20
|
+
link = (
|
|
21
|
+
f'<a href="#{self.entry.anchor}">{self.entry.label}</a>'
|
|
22
|
+
if self.entry
|
|
23
|
+
else ""
|
|
24
|
+
)
|
|
25
|
+
if not self.children:
|
|
26
|
+
return link
|
|
27
|
+
items = "\n".join(f"<li>{child.to_html()}</li>" for child in self.children)
|
|
28
|
+
return f"{link}<ul>\n{items}\n</ul>"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def flatten_tokens(tokens: list[dict]) -> list[TocEntry]:
|
|
32
|
+
"""Flatten Python-Markdown ``toc_tokens`` into entries in document order.
|
|
33
|
+
|
|
34
|
+
``label`` is the token's ``name``, which Python-Markdown has already
|
|
35
|
+
HTML-escaped, so it is safe to place in markup as-is.
|
|
36
|
+
"""
|
|
37
|
+
entries: list[TocEntry] = []
|
|
38
|
+
for token in tokens:
|
|
39
|
+
entries.append(TocEntry(token["level"], token["id"], token["name"]))
|
|
40
|
+
entries.extend(flatten_tokens(token["children"]))
|
|
41
|
+
return entries
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def build_toc(entries: list[TocEntry]) -> str:
|
|
45
|
+
"""Render entries from all files as one nested <ul>, nested by heading level.
|
|
46
|
+
|
|
47
|
+
Nesting follows the absolute heading level, so an H2 always sits one
|
|
48
|
+
level below the top whatever file it came from. An H2 with no H1 before
|
|
49
|
+
it is placed in an unlabelled top-level item rather than promoted.
|
|
50
|
+
"""
|
|
51
|
+
root = _Node(None)
|
|
52
|
+
stack: list[_Node] = [] # stack[d] is the open node at heading level d + 1
|
|
53
|
+
for entry in entries:
|
|
54
|
+
del stack[entry.level - 1 :]
|
|
55
|
+
while len(stack) < entry.level - 1:
|
|
56
|
+
placeholder = _Node(None)
|
|
57
|
+
(stack[-1] if stack else root).children.append(placeholder)
|
|
58
|
+
stack.append(placeholder)
|
|
59
|
+
node = _Node(entry)
|
|
60
|
+
(stack[-1] if stack else root).children.append(node)
|
|
61
|
+
stack.append(node)
|
|
62
|
+
|
|
63
|
+
return root.to_html()
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: mddoco
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.3.0
|
|
4
4
|
Summary: Markdown to HTML/PDF document converter
|
|
5
5
|
Author-email: Phil Massyn <phil.massyn@icloud.com>
|
|
6
6
|
Project-URL: Homepage, https://github.com/massyn/mddoco
|
|
@@ -22,12 +22,14 @@ Dynamic: license-file
|
|
|
22
22
|
|
|
23
23
|
# mddoco
|
|
24
24
|
|
|
25
|
-
A CLI tool that converts markdown files to a single HTML
|
|
25
|
+
A CLI tool that converts markdown files to a single HTML or PDF document.
|
|
26
26
|
|
|
27
27
|
[](https://github.com/massyn/mddoco/actions/workflows/ci.yml)
|
|
28
28
|
 
|
|
29
29
|
## Installation
|
|
30
30
|
|
|
31
|
+
mddoco needs Python 3.10 or newer.
|
|
32
|
+
|
|
31
33
|
```bash
|
|
32
34
|
pip install mddoco
|
|
33
35
|
```
|
|
@@ -48,6 +50,10 @@ pip install -e .
|
|
|
48
50
|
> playwright install chromium
|
|
49
51
|
> ```
|
|
50
52
|
|
|
53
|
+
> **The `d2` command-line tool is required only if your documents contain
|
|
54
|
+
> [D2 diagrams](#d2-diagrams).** It is a separate program, not a Python
|
|
55
|
+
> package, so `pip` does not install it. See [Installing the D2 CLI](#installing-the-d2-cli).
|
|
56
|
+
|
|
51
57
|
## Usage
|
|
52
58
|
|
|
53
59
|
```
|
|
@@ -60,8 +66,8 @@ mddoco [OPTIONS] INPUT_PATH
|
|
|
60
66
|
|
|
61
67
|
| Option | Short | Default | Description |
|
|
62
68
|
|---|---|---|---|
|
|
63
|
-
| `--output PATH` | `-o` | `.` |
|
|
64
|
-
| `--format [html\|pdf]` | `-f` | `html` | Output format |
|
|
69
|
+
| `--output PATH` | `-o` | `.` | Output directory, or an explicit file path if it has an extension (`-o out/report.html`) |
|
|
70
|
+
| `--format [html\|pdf]` | `-f` | `html` | Output format (PDF needs Playwright; the `site-*` themes are HTML only) |
|
|
65
71
|
| `--title TEXT` | `-t` | _(none)_ | Document title shown at the top of the page |
|
|
66
72
|
| `--theme NAME` | | `default` | Theme to use for rendering |
|
|
67
73
|
| `--toc / --no-toc` | | off | Generate a table of contents |
|
|
@@ -89,11 +95,11 @@ mddoco ./docs --title "My Project" --toc --output ./out
|
|
|
89
95
|
|
|
90
96
|
## Output
|
|
91
97
|
|
|
92
|
-
All matched markdown files are combined into a single
|
|
98
|
+
All matched markdown files are combined into a single document in the output directory, as HTML (the default) or PDF (`--format pdf`). The filename is derived from the input folder or file name, with the `.html` or `.pdf` extension. If `--output` ends in an extension, it is used as the exact output file path instead.
|
|
93
99
|
|
|
94
100
|
## Examples
|
|
95
101
|
|
|
96
|
-
The [`examples/`](examples/) directory contains
|
|
102
|
+
The [`examples/`](examples/) directory contains six runnable input folders, each
|
|
97
103
|
covering a different feature:
|
|
98
104
|
|
|
99
105
|
| Folder | Demonstrates |
|
|
@@ -103,6 +109,7 @@ covering a different feature:
|
|
|
103
109
|
| [`examples/03_themed_report`](examples/03_themed_report) | Themes and a table of contents |
|
|
104
110
|
| [`examples/04_jinja_data`](examples/04_jinja_data) | Jinja2 templates with JSON and CSV data files |
|
|
105
111
|
| [`examples/05_security_findings`](examples/05_security_findings) | CSV data grouped in a Jinja2 template and fed into a `graph` chart |
|
|
112
|
+
| [`examples/06_d2_diagrams`](examples/06_d2_diagrams) | D2 diagrams (requires the `d2` CLI) |
|
|
106
113
|
|
|
107
114
|
```bash
|
|
108
115
|
mddoco examples/03_themed_report --theme professional --title "Q3 Platform Review" --toc --output ./out
|
|
@@ -205,7 +212,9 @@ All themes support:
|
|
|
205
212
|
|
|
206
213
|
- Optional document title
|
|
207
214
|
- Optional table of contents (the `site-*` themes use their side nav instead)
|
|
208
|
-
- [
|
|
215
|
+
- Syntax highlighting for code blocks ([highlight.js](https://highlightjs.org), loaded from a CDN only when code blocks are present)
|
|
216
|
+
- [Mermaid.js](https://mermaid.js.org) diagram support (loaded from a CDN only when diagrams are present)
|
|
217
|
+
- [D2](https://d2lang.com) diagrams, rendered to inline SVG at build time (needs the `d2` CLI, only when diagrams are present)
|
|
209
218
|
- Graph diagram blocks
|
|
210
219
|
|
|
211
220
|
### Site themes
|
|
@@ -249,7 +258,7 @@ Use ` ```graph ` fenced blocks with a JSON payload. The only required field is `
|
|
|
249
258
|
```
|
|
250
259
|
````
|
|
251
260
|
|
|
252
|
-
Series are inferred from the data keys (everything except `x`). Each series defaults to a line chart in
|
|
261
|
+
Series are inferred from the data keys (everything except `x`). Each series defaults to a line chart, coloured from a built-in palette.
|
|
253
262
|
|
|
254
263
|
**Full schema:**
|
|
255
264
|
|
|
@@ -307,3 +316,45 @@ graph TD
|
|
|
307
316
|
````
|
|
308
317
|
|
|
309
318
|
mddoco detects mermaid blocks automatically and loads the Mermaid.js CDN only when needed.
|
|
319
|
+
|
|
320
|
+
### D2 diagrams
|
|
321
|
+
|
|
322
|
+
[D2](https://d2lang.com) diagrams use the same fenced-block syntax:
|
|
323
|
+
|
|
324
|
+
````markdown
|
|
325
|
+
```d2
|
|
326
|
+
direction: right
|
|
327
|
+
client -> server: request
|
|
328
|
+
server -> db: query
|
|
329
|
+
```
|
|
330
|
+
````
|
|
331
|
+
|
|
332
|
+
Unlike Mermaid, D2 diagrams are rendered while mddoco builds the document, by the `d2` command-line tool, and embedded as inline SVG. The output has no extra scripts, works offline, and prints to PDF without waiting for anything to load.
|
|
333
|
+
|
|
334
|
+
- The `d2` CLI must be installed and on your `PATH` (see below). It is only needed when a document contains a `d2` block; otherwise mddoco never looks for it.
|
|
335
|
+
- A diagram that fails to compile stops the build with D2's error message, the same as an invalid `graph` block.
|
|
336
|
+
- A diagram that takes longer than 30 seconds to compile stops the build with a timeout error.
|
|
337
|
+
|
|
338
|
+
#### Installing the D2 CLI
|
|
339
|
+
|
|
340
|
+
`d2` is a standalone program from the [D2 project](https://d2lang.com), not a Python package. Install it with one of the following, then check that it is on your `PATH`:
|
|
341
|
+
|
|
342
|
+
```bash
|
|
343
|
+
d2 --version
|
|
344
|
+
```
|
|
345
|
+
|
|
346
|
+
| Platform | Command |
|
|
347
|
+
|---|---|
|
|
348
|
+
| macOS (Homebrew) | `brew install d2` |
|
|
349
|
+
| Linux and macOS (install script) | `curl -fsSL https://d2lang.com/install.sh \| sh -s --` |
|
|
350
|
+
| Windows (Scoop) | `scoop install main/d2` |
|
|
351
|
+
| Windows (Chocolatey) | `choco install d2` |
|
|
352
|
+
| Windows (installer) | Download the `.msi` from the [releases page](https://github.com/d2lang/d2/releases); it adds `d2` to your `PATH` |
|
|
353
|
+
| Any platform with Go | `go install github.com/d2lang/d2@latest` |
|
|
354
|
+
|
|
355
|
+
- **Install script:** run it with `--dry-run` first (`curl -fsSL https://d2lang.com/install.sh | sh -s -- --dry-run`) to see what it will do. It uses a package manager when it finds one, and otherwise installs under `/usr/local`, or `~/.local` if `/usr/local` needs `sudo`. If it tells you to adjust `PATH`, do that.
|
|
356
|
+
- **Standalone download:** archives for each platform are on the [releases page](https://github.com/d2lang/d2/releases). Extract one and run `make install`, or `make install PREFIX=$HOME/.local` to install without `sudo`.
|
|
357
|
+
- **Other options and details:** see the [D2 install guide](https://d2lang.com/tour/install).
|
|
358
|
+
- **CI:** install `d2` in the workflow before building documents that contain D2 diagrams, for example by downloading a pinned release archive as this repository's own [workflow](.github/workflows/ci.yml) does.
|
|
359
|
+
|
|
360
|
+
If `d2` is missing, mddoco stops with an error pointing to the install guide, and only when it finds a `d2` block.
|
|
@@ -4,6 +4,7 @@ pyproject.toml
|
|
|
4
4
|
src/mddoco/__init__.py
|
|
5
5
|
src/mddoco/cli.py
|
|
6
6
|
src/mddoco/converter.py
|
|
7
|
+
src/mddoco/d2.py
|
|
7
8
|
src/mddoco/graph.py
|
|
8
9
|
src/mddoco/mermaid.py
|
|
9
10
|
src/mddoco/pdf.py
|
|
@@ -33,5 +34,7 @@ src/mddoco/themes/site-professional.html
|
|
|
33
34
|
src/mddoco/themes/site-terminal.html
|
|
34
35
|
src/mddoco/themes/site.html
|
|
35
36
|
src/mddoco/themes/vanilla.html
|
|
37
|
+
tests/test_d2.py
|
|
36
38
|
tests/test_preprocessor.py
|
|
37
|
-
tests/test_themes.py
|
|
39
|
+
tests/test_themes.py
|
|
40
|
+
tests/test_toc.py
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import shutil
|
|
2
|
+
import subprocess
|
|
3
|
+
|
|
4
|
+
import pytest
|
|
5
|
+
|
|
6
|
+
from mddoco import d2
|
|
7
|
+
from mddoco.d2 import process_d2
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _block(source: str) -> str:
|
|
11
|
+
return f'<pre><code class="language-d2">{source}</code></pre>'
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _fake_run(stdout="", stderr="", returncode=0, calls=None):
|
|
15
|
+
def run(cmd, **kwargs):
|
|
16
|
+
if calls is not None:
|
|
17
|
+
calls.append((cmd, kwargs))
|
|
18
|
+
return subprocess.CompletedProcess(cmd, returncode, stdout, stderr)
|
|
19
|
+
|
|
20
|
+
return run
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@pytest.fixture
|
|
24
|
+
def fake_d2(monkeypatch):
|
|
25
|
+
monkeypatch.setattr(d2.shutil, "which", lambda name: "/usr/bin/d2")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def test_no_d2_blocks_leaves_html_untouched_and_needs_no_binary(monkeypatch):
|
|
29
|
+
monkeypatch.setattr(d2.shutil, "which", lambda name: None)
|
|
30
|
+
html = "<p>hello</p><pre><code>plain</code></pre>"
|
|
31
|
+
assert process_d2(html) == (html, False)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def test_block_replaced_with_inline_svg(fake_d2, monkeypatch):
|
|
35
|
+
svg = '<?xml version="1.0"?><svg viewBox="0 0 1 1"></svg>'
|
|
36
|
+
monkeypatch.setattr(d2.subprocess, "run", _fake_run(stdout=svg))
|
|
37
|
+
html, found = process_d2(f"<p>a</p>{_block('x -> y')}<p>b</p>")
|
|
38
|
+
assert found
|
|
39
|
+
assert html == (
|
|
40
|
+
'<p>a</p><div class="d2">'
|
|
41
|
+
'<svg viewBox="0 0 1 1" width="1" height="1"></svg></div><p>b</p>'
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def test_outer_svg_gets_its_natural_size(fake_d2, monkeypatch):
|
|
46
|
+
svg = '<svg xmlns="x" viewBox="0 0 255.4 455"><svg width="1"></svg></svg>'
|
|
47
|
+
monkeypatch.setattr(d2.subprocess, "run", _fake_run(stdout=svg))
|
|
48
|
+
html, _ = process_d2(_block("x"))
|
|
49
|
+
assert '<svg xmlns="x" viewBox="0 0 255.4 455" width="255" height="455">' in html
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def test_source_is_unescaped_and_sent_on_stdin(fake_d2, monkeypatch):
|
|
53
|
+
calls = []
|
|
54
|
+
monkeypatch.setattr(
|
|
55
|
+
d2.subprocess, "run", _fake_run(stdout="<svg></svg>", calls=calls)
|
|
56
|
+
)
|
|
57
|
+
process_d2(_block("x -> y: "hi" & bye"))
|
|
58
|
+
cmd, kwargs = calls[0]
|
|
59
|
+
assert cmd == ["/usr/bin/d2", "-", "-"]
|
|
60
|
+
assert kwargs["input"] == 'x -> y: "hi" & bye'
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def test_multiple_blocks_each_rendered(fake_d2, monkeypatch):
|
|
64
|
+
calls = []
|
|
65
|
+
monkeypatch.setattr(
|
|
66
|
+
d2.subprocess, "run", _fake_run(stdout="<svg></svg>", calls=calls)
|
|
67
|
+
)
|
|
68
|
+
html, _ = process_d2(_block("a -> b") + _block("c -> d"))
|
|
69
|
+
assert html.count('<div class="d2">') == 2
|
|
70
|
+
assert len(calls) == 2
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def test_compile_failure_raises_with_d2_message(fake_d2, monkeypatch):
|
|
74
|
+
monkeypatch.setattr(
|
|
75
|
+
d2.subprocess,
|
|
76
|
+
"run",
|
|
77
|
+
_fake_run(stderr="err: maps must be terminated", returncode=1),
|
|
78
|
+
)
|
|
79
|
+
html = _block("a -> {")
|
|
80
|
+
with pytest.raises(RuntimeError, match="maps must be terminated"):
|
|
81
|
+
process_d2(html)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def test_timeout_raises(fake_d2, monkeypatch):
|
|
85
|
+
def run(cmd, **kwargs):
|
|
86
|
+
raise subprocess.TimeoutExpired(cmd, kwargs["timeout"])
|
|
87
|
+
|
|
88
|
+
monkeypatch.setattr(d2.subprocess, "run", run)
|
|
89
|
+
html = _block("a -> b")
|
|
90
|
+
with pytest.raises(RuntimeError, match="timed out"):
|
|
91
|
+
process_d2(html)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def test_missing_binary_gives_install_hint(monkeypatch):
|
|
95
|
+
monkeypatch.setattr(d2.shutil, "which", lambda name: None)
|
|
96
|
+
html = _block("a -> b")
|
|
97
|
+
with pytest.raises(RuntimeError, match="d2lang.com/tour/install"):
|
|
98
|
+
process_d2(html)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@pytest.mark.skipif(shutil.which("d2") is None, reason="d2 CLI not installed")
|
|
102
|
+
def test_real_d2_renders_svg():
|
|
103
|
+
html, found = process_d2(_block("a -> b: hello"))
|
|
104
|
+
assert found
|
|
105
|
+
assert html.startswith('<div class="d2"><svg')
|
|
106
|
+
assert "<?xml" not in html
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@pytest.mark.skipif(shutil.which("d2") is None, reason="d2 CLI not installed")
|
|
110
|
+
def test_real_d2_rejects_invalid_source():
|
|
111
|
+
html = _block("a -> {")
|
|
112
|
+
with pytest.raises(RuntimeError, match="d2 failed"):
|
|
113
|
+
process_d2(html)
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
|
|
3
|
+
from mddoco.converter import convert_file
|
|
4
|
+
from mddoco.toc import TocEntry, build_toc
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def _toc_for(tmp_path: Path, *documents: str, toc_depth: int = 3) -> str:
|
|
8
|
+
entries = []
|
|
9
|
+
for i, text in enumerate(documents):
|
|
10
|
+
path = tmp_path / f"{i:02d}.md"
|
|
11
|
+
path.write_text(text, encoding="utf-8")
|
|
12
|
+
_, file_entries = convert_file(path, toc=True, toc_depth=toc_depth)
|
|
13
|
+
entries.extend(file_entries)
|
|
14
|
+
return build_toc(entries)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def test_h1_with_subheadings_nests_under_it(tmp_path):
|
|
18
|
+
toc = _toc_for(tmp_path, "# One\n\n## Two\n\n### Three\n")
|
|
19
|
+
assert toc == (
|
|
20
|
+
'<ul>\n<li><a href="#one">One</a><ul>\n'
|
|
21
|
+
'<li><a href="#two">Two</a><ul>\n'
|
|
22
|
+
'<li><a href="#three">Three</a></li>\n</ul></li>\n'
|
|
23
|
+
"</ul></li>\n</ul>"
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def test_file_without_h1_nests_its_h2_under_previous_h1(tmp_path):
|
|
28
|
+
toc = _toc_for(tmp_path, "# Intro\n", "## Detail\n")
|
|
29
|
+
assert toc == (
|
|
30
|
+
'<ul>\n<li><a href="#intro">Intro</a><ul>\n'
|
|
31
|
+
'<li><a href="#detail">Detail</a></li>\n'
|
|
32
|
+
"</ul></li>\n</ul>"
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def test_leading_h2_is_not_promoted_to_top_level(tmp_path):
|
|
37
|
+
toc = _toc_for(tmp_path, "## Orphan\n\n# Real\n")
|
|
38
|
+
assert toc == (
|
|
39
|
+
'<ul>\n<li><ul>\n<li><a href="#orphan">Orphan</a></li>\n</ul></li>\n'
|
|
40
|
+
'<li><a href="#real">Real</a></li>\n</ul>'
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def test_toc_depth_limits_entries(tmp_path):
|
|
45
|
+
toc = _toc_for(tmp_path, "# One\n\n## Two\n\n### Three\n", toc_depth=2)
|
|
46
|
+
assert "#two" in toc
|
|
47
|
+
assert "#three" not in toc
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def test_heading_text_is_escaped(tmp_path):
|
|
51
|
+
toc = _toc_for(tmp_path, "# Fish & chips < 5\n")
|
|
52
|
+
assert "Fish & chips < 5" in toc
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def test_skipped_level_gets_unlabelled_parent():
|
|
56
|
+
toc = build_toc([TocEntry(1, "a", "A"), TocEntry(3, "c", "C")])
|
|
57
|
+
assert toc == (
|
|
58
|
+
'<ul>\n<li><a href="#a">A</a><ul>\n'
|
|
59
|
+
'<li><ul>\n<li><a href="#c">C</a></li>\n</ul></li>\n'
|
|
60
|
+
"</ul></li>\n</ul>"
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def test_no_entries_gives_empty_string():
|
|
65
|
+
assert build_toc([]) == ""
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
__version__ = "2.2.1"
|
mddoco-2.2.1/src/mddoco/toc.py
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import re
|
|
2
|
-
|
|
3
|
-
_INNER_UL = re.compile(r"<ul>(.*)</ul>", re.DOTALL)
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
def combine_toc(fragments: list[str]) -> str:
|
|
7
|
-
"""Merge per-file TOC HTML fragments into a single <ul> block."""
|
|
8
|
-
items: list[str] = []
|
|
9
|
-
for fragment in fragments:
|
|
10
|
-
m = _INNER_UL.search(fragment)
|
|
11
|
-
if m:
|
|
12
|
-
items.append(m.group(1).strip())
|
|
13
|
-
if not items:
|
|
14
|
-
return ""
|
|
15
|
-
return "<ul>\n" + "\n".join(items) + "\n</ul>"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|