markdown-include-variants 0.0.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.
@@ -0,0 +1,4 @@
1
+ from ._main import IncludeVariantsExtension as IncludeVariantsExtension
2
+ from ._main import IncludeVariantsPreprocessor as IncludeVariantsPreprocessor
3
+ from ._main import makeExtension as makeExtension
4
+ from ._version import __version__ as __version__
@@ -0,0 +1,308 @@
1
+ import re
2
+ from dataclasses import dataclass
3
+ from pathlib import Path
4
+ from typing import Literal, Union
5
+
6
+ from markdown import Extension, Markdown
7
+ from markdown.preprocessors import Preprocessor
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class Variant:
12
+ path: Path
13
+ title: str
14
+ is_annotated: Union[bool, None]
15
+ version: Literal["py38", "py39", "py310"]
16
+
17
+
18
+ def calculate_variants(base_path: Path) -> dict[tuple[str, Union[bool, None]], Variant]:
19
+ base_name = base_path.stem
20
+ base_dir = base_path.parent
21
+ variants: dict[tuple[str, Union[bool, None]], Variant] = {}
22
+ an = "_an"
23
+ py39 = "_py39"
24
+ py310 = "_py310"
25
+ an_p310_path = base_dir / f"{base_name}{an}{py310}.py"
26
+ an_p39_path = base_dir / f"{base_name}{an}{py39}.py"
27
+ an_path = base_dir / f"{base_name}{an}.py"
28
+ p310_path = base_dir / f"{base_name}{py310}.py"
29
+ p39_path = base_dir / f"{base_name}{py39}.py"
30
+ if an_p310_path.exists():
31
+ v = Variant(
32
+ path=an_p310_path, title="Python 3.10+", is_annotated=True, version="py310"
33
+ )
34
+ variants[(v.version, v.is_annotated)] = v
35
+ if p310_path.exists():
36
+ v = Variant(
37
+ path=p310_path,
38
+ title="Python 3.10+ - non-Annotated",
39
+ is_annotated=False,
40
+ version="py310",
41
+ )
42
+ variants[(v.version, v.is_annotated)] = v
43
+ elif p310_path.exists():
44
+ v = Variant(
45
+ path=p310_path, title="Python 3.10+", is_annotated=None, version="py310"
46
+ )
47
+ variants[(v.version, v.is_annotated)] = v
48
+ if an_p39_path.exists():
49
+ v = Variant(
50
+ path=an_p39_path, title="Python 3.9+", is_annotated=True, version="py39"
51
+ )
52
+ variants[(v.version, v.is_annotated)] = v
53
+ if p39_path.exists():
54
+ v = Variant(
55
+ path=p39_path,
56
+ title="Python 3.9+ - non-Annotated",
57
+ is_annotated=False,
58
+ version="py39",
59
+ )
60
+ variants[(v.version, v.is_annotated)] = v
61
+ elif p39_path.exists():
62
+ v = Variant(
63
+ path=p39_path, title="Python 3.9+", is_annotated=None, version="py39"
64
+ )
65
+ variants[(v.version, v.is_annotated)] = v
66
+ if an_path.exists():
67
+ v = Variant(
68
+ path=an_path, title="Python 3.8+", is_annotated=True, version="py38"
69
+ )
70
+ variants[(v.version, v.is_annotated)] = v
71
+ if base_path.exists():
72
+ v = Variant(
73
+ path=base_path,
74
+ title="Python 3.8+ - non-Annotated",
75
+ is_annotated=False,
76
+ version="py38",
77
+ )
78
+ variants[(v.version, v.is_annotated)] = v
79
+ elif base_path.exists():
80
+ v = Variant(
81
+ path=base_path, title="Python 3.8+", is_annotated=None, version="py38"
82
+ )
83
+ variants[(v.version, v.is_annotated)] = v
84
+ return variants
85
+
86
+
87
+ def parse_lines_index(include_lines_config: str) -> list[tuple[int, int]]:
88
+ lines = []
89
+ for line in include_lines_config.strip().split(","):
90
+ clean_line = line.strip()
91
+ if ":" in clean_line:
92
+ start, end = clean_line.split(":")
93
+ lines.append((int(start), int(end)))
94
+ else:
95
+ lines.append((int(line), int(line)))
96
+ lines.sort()
97
+ return lines
98
+
99
+
100
+ @dataclass
101
+ class IncludeInfo:
102
+ start: int
103
+ end: int
104
+ offset: int
105
+ hl_lines: list[tuple[int, int]]
106
+
107
+ def computed_hl_lines(self) -> list[tuple[int, int]]:
108
+ return [
109
+ (
110
+ hl_line[0] - self.start + self.offset + 1,
111
+ hl_line[1] - self.start + self.offset + 1,
112
+ )
113
+ for hl_line in self.hl_lines
114
+ ]
115
+
116
+
117
+ def calculate_includes(
118
+ lines_to_include: list[tuple[int, int]], hl_lines: list[tuple[int, int]]
119
+ ) -> dict[tuple[int, int], IncludeInfo]:
120
+ lines_groups: dict[tuple[int, int], IncludeInfo] = {}
121
+ offset = 0
122
+ for i, line_group in enumerate(lines_to_include):
123
+ if line_group[0] > 1:
124
+ if i == 0:
125
+ offset = 2
126
+ else:
127
+ offset += 3
128
+ info = IncludeInfo(
129
+ start=line_group[0],
130
+ end=line_group[1],
131
+ offset=offset,
132
+ hl_lines=[],
133
+ )
134
+ offset += line_group[1] - line_group[0] + 1
135
+ for hl_line in hl_lines:
136
+ if hl_line[0] >= line_group[0] and hl_line[1] <= line_group[1]:
137
+ info.hl_lines.append(hl_line)
138
+ lines_groups[line_group] = info
139
+ return lines_groups
140
+
141
+
142
+ re_line = r"^\{\*\s*(\S+)\s*(.*)\*\}$"
143
+ re_config = r"(\w+)\[([^\]]+)\]"
144
+
145
+
146
+ class IncludeVariantsPreprocessor(Preprocessor):
147
+ def run(self, lines: list[str]) -> list[str]:
148
+ new_lines = []
149
+ for line in lines:
150
+ line_match = re.match(re_line, line)
151
+ if not line_match:
152
+ new_lines.append(line)
153
+ continue
154
+ block_lines = []
155
+ src_file_str = line_match.group(1)
156
+ base_path = Path(src_file_str)
157
+
158
+ configs_str = line_match.group(2).strip()
159
+ include_lines: list[tuple[int, int]] = []
160
+ highlight_lines: list[tuple[int, int]] = []
161
+ for config_match in re.finditer(re_config, configs_str):
162
+ if config_match:
163
+ name = config_match.group(1)
164
+ ranges_str = config_match.group(2)
165
+ ranges = parse_lines_index(ranges_str)
166
+ if name == "ln":
167
+ include_lines.extend(ranges)
168
+ elif name == "hl":
169
+ highlight_lines.extend(ranges)
170
+ use_hl_lines: list[tuple[int, int]] = []
171
+ if highlight_lines:
172
+ if include_lines:
173
+ include_infos = calculate_includes(include_lines, highlight_lines)
174
+ for info in include_infos.values():
175
+ use_hl_lines.extend(info.computed_hl_lines())
176
+ else:
177
+ use_hl_lines = highlight_lines
178
+ use_hl_lines_strs: list[str] = []
179
+ for hl_line in use_hl_lines:
180
+ if hl_line[0] == hl_line[1]:
181
+ use_hl_lines_strs.append(str(hl_line[0]))
182
+ else:
183
+ use_hl_lines_strs.append(f"{hl_line[0]}-{hl_line[1]}")
184
+ use_hl_lines_str = " ".join(use_hl_lines_strs)
185
+
186
+ variants = calculate_variants(base_path)
187
+ if len(variants) == 0:
188
+ raise FileNotFoundError(f"Could not find any variants for {base_path}")
189
+ sorted_variants: list[Variant] = []
190
+ for an in [True, False, None]:
191
+ for version in ["py310", "py39", "py38"]:
192
+ v = variants.get((version, an))
193
+ if v:
194
+ sorted_variants.append(v)
195
+ assert sorted_variants
196
+ preferred_variant = sorted_variants[0]
197
+ content_lines = preferred_variant.path.read_text().splitlines()
198
+
199
+ internal_block_lines: list[str] = []
200
+ if not include_lines:
201
+ internal_block_lines.append(
202
+ f"{{!{preferred_variant.path}!}}",
203
+ )
204
+ for i, line_group in enumerate(include_lines):
205
+ if i == 0 and line_group[0] > 1:
206
+ internal_block_lines.extend(
207
+ [
208
+ "# Code above omitted 👆",
209
+ "",
210
+ ]
211
+ )
212
+ if i >= 1:
213
+ internal_block_lines.extend(
214
+ [
215
+ "",
216
+ "# Code here omitted 👈",
217
+ "",
218
+ ]
219
+ )
220
+ internal_block_lines.append(
221
+ f"{{!{preferred_variant.path}[ln:{line_group[0]}-{line_group[1]}]!}}"
222
+ )
223
+ if i == len(include_lines) - 1 and line_group[1] < len(content_lines):
224
+ internal_block_lines.extend(
225
+ [
226
+ "",
227
+ "# Code below omitted 👇",
228
+ ]
229
+ )
230
+ first_line = "```python"
231
+ if use_hl_lines:
232
+ first_line += f' hl_lines="{use_hl_lines_str}"'
233
+
234
+ block_lines.extend(
235
+ [
236
+ f"//// tab | {preferred_variant.title}" "",
237
+ first_line,
238
+ *internal_block_lines,
239
+ "```",
240
+ "",
241
+ "////",
242
+ "",
243
+ ]
244
+ )
245
+ if include_lines:
246
+ block_lines.extend(
247
+ [
248
+ "//// details | 👀 Full file preview",
249
+ "",
250
+ "```python",
251
+ f"{{!{preferred_variant.path}!}}",
252
+ "```",
253
+ "",
254
+ "////",
255
+ "",
256
+ ]
257
+ )
258
+ if len(sorted_variants) > 1:
259
+ block_lines.extend(
260
+ [
261
+ "///// details | 🤓 Other versions and variants",
262
+ "",
263
+ ]
264
+ )
265
+
266
+ for variant in sorted_variants[1:]:
267
+ block_lines.extend([f"//// tab | {variant.title}", ""])
268
+ if variant.is_annotated is False:
269
+ block_lines.extend(
270
+ [
271
+ "/// tip",
272
+ "",
273
+ "Prefer to use the `Annotated` version if possible.",
274
+ "",
275
+ "///",
276
+ "",
277
+ ]
278
+ )
279
+
280
+ block_lines.extend(
281
+ [
282
+ "```python",
283
+ f"{{!{variant.path}!}}",
284
+ "```",
285
+ "////",
286
+ ]
287
+ )
288
+
289
+ block_lines.extend(
290
+ [
291
+ "",
292
+ "/////",
293
+ "",
294
+ ]
295
+ )
296
+ new_lines.extend(block_lines)
297
+ return new_lines
298
+
299
+
300
+ class IncludeVariantsExtension(Extension):
301
+ def extendMarkdown(self, md: Markdown) -> None:
302
+ md.preprocessors.register(
303
+ IncludeVariantsPreprocessor(md), "include_variants", 110
304
+ )
305
+
306
+
307
+ def makeExtension(*args, **kwargs): # pragma: no cover
308
+ return IncludeVariantsExtension(*args, **kwargs)
@@ -0,0 +1 @@
1
+ __version__ = "0.0.1"
File without changes
@@ -0,0 +1,145 @@
1
+ Metadata-Version: 2.3
2
+ Name: markdown-include-variants
3
+ Version: 0.0.1
4
+ Summary: Markdown extension to expand directives to include source example files to also include their variants. Only useful to tiangolo's projets. Don't use it. 😅
5
+ Project-URL: Homepage, https://github.com/tiangolo/markdown-include-variants
6
+ Project-URL: Repository, https://github.com/tiangolo/markdown-include-variants
7
+ Project-URL: Issues, https://github.com/tiangolo/markdown-include-variants/issues
8
+ Project-URL: Changelog, https://github.com/tiangolo/markdown-include-variants/release-notes.md
9
+ Author-email: Sebastián Ramírez <tiangolo@gmail.com>
10
+ License-File: LICENSE
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Typing :: Typed
14
+ Requires-Python: >=3.9
15
+ Requires-Dist: markdown>=3.7
16
+ Description-Content-Type: text/markdown
17
+
18
+ # markdown-include-variants
19
+
20
+ <a href="https://github.com/tiangolo/markdown-include-variants/actions?query=workflow%3ATest" target="_blank">
21
+ <img src="https://github.com/tiangolo/markdown-include-variants/workflows/Test/badge.svg" alt="Test">
22
+ </a>
23
+ <a href="https://github.com/tiangolo/markdown-include-variants/actions?query=workflow%3APublish" target="_blank">
24
+ <img src="https://github.com/tiangolo/markdown-include-variants/workflows/Publish/badge.svg" alt="Publish">
25
+ </a>
26
+ <a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/tiangolo/markdown-include-variants" target="_blank">
27
+ <img src="https://coverage-badge.samuelcolvin.workers.dev/tiangolo/markdown-include-variants.svg" alt="Coverage">
28
+ <a href="https://pypi.org/project/markdown-include-variants" target="_blank">
29
+ <img src="https://img.shields.io/pypi/v/markdown-include-variants?color=%2334D058&label=pypi%20package" alt="Package version">
30
+ </a>
31
+
32
+ ---
33
+
34
+ ## 🚨 Warning: Internal Project
35
+
36
+ This is an internal project, it is mainly useful for the docs in [@tiangolo](https://github.com/tiangolo)'s projects (e.g. all the [FastAPI](https://github.com/fastapi) projects).
37
+
38
+ It is probably **not useful** to you. You should probably not use it. 😅
39
+
40
+ There are no guarantees about behavior, it is made to suit the needs of these projects, to simplify writing documentation.
41
+
42
+ ## How to Use
43
+
44
+ If you're still here it's probably because you are getting involved in one of the projects that use it. 🤓
45
+
46
+ Here's how it works:
47
+
48
+ * You add a Python source example to the `docs_src` directory, with the minimum Python version supported by the project, and using the old format without `Annotated`, if that applies, it would be named something like `tutorial001.py`.
49
+ * Copy the file and update it to use `Annotated` (if that applies), and name the file with a "tag" (a prefix) of `an`, like: `tutorial001_an.py`.
50
+ * Run the internal script to generate the variants of the files for superior versions of Python, like `3.9`, `3.10`, etc. (this internal script is in the project itself). This would generate files like `tutorial001_py39.py`, `tutorial001_py310.py`, etc. and `tutorial001_an_py39.py`, `tutorial001_an_py310.py`, etc.
51
+ * In the Markdown file, include the simplest version of the file, using this syntax:
52
+
53
+ ```markdown
54
+ {* ./docs_src/first_steps/tutorial001.py *}
55
+ ```
56
+
57
+ That will be automatically expanded with [mdx-include](https://github.com/neurobin/mdx_include) to include the recommended version of the file (the highest version of Python, using `Annotated`), and will include the variants below in a collapsed `details` box.
58
+
59
+ ### Include Lines
60
+
61
+ To include specific line ranges, use the config `ln`:
62
+
63
+ ```markdown
64
+ {* ./docs_src/first_steps/tutorial001.py ln[3:6,8,10:11] *}
65
+ ```
66
+
67
+ That will include only:
68
+
69
+ * lines 3 to 6
70
+ * line 8
71
+ * lines 10 to 11
72
+
73
+ It will add blocks with comments in the middle like:
74
+
75
+ ```python
76
+ # Code here omitted 👈️
77
+ ```
78
+
79
+ If you include specific lines, it will also add another collapsed `details` box with the "Full file preview".
80
+
81
+ ### Highlight Lines
82
+
83
+ You can highlight specific lines using the config `hl`:
84
+
85
+ ```markdown
86
+ {* ./docs_src/first_steps/tutorial001.py hl[3,5:7,10] *}
87
+ ```
88
+
89
+ That will highlight:
90
+
91
+ * line 3
92
+ * lines 5 to 7
93
+ * line 10
94
+
95
+ Have in mind that the file path points to the simplest version of the file, the one without the `_an` suffix. But the main file shown will be the highest (recommended) version, and the highlights will apply to that file.
96
+
97
+ So, when deciding which lines to highlight, do that based on the highest version of the file.
98
+
99
+ ### Include Lines and Highlight
100
+
101
+ You can combine both `ln` and `hl`:
102
+
103
+ ```markdown
104
+ {* ./docs_src/first_steps/tutorial001.py ln[3:6,8,10:11] hl[3,5:6,10] *}
105
+ ```
106
+
107
+ The highlighted lines refer to the source file (for the highest/recommended version), not the final rendered code block.
108
+
109
+ This makes it easier to decide which lines to highlight just by opening the source file, without having to calculate the actual lines in the rendered block after included, the extra lines for comments when omitting lines, etc.
110
+
111
+ ### Include Lines and Highlight - Example
112
+
113
+ For example, you could have a source file with:
114
+
115
+ ```python
116
+ print("line 1")
117
+ print("line 2")
118
+ print("line 3")
119
+ print("line 4")
120
+ print("line 5")
121
+ print("line 6") # highlight this
122
+ print("line 7")
123
+ ```
124
+
125
+ Using a declaration like this:
126
+
127
+ ```markdown
128
+ {* ./docs_src/first_steps/tutorial001.py ln[5:7] hl[6] *}
129
+ ```
130
+
131
+ Could render something like:
132
+
133
+ ```python
134
+ # Code above omitted 👈️
135
+
136
+ print("line 5")
137
+ print("line 6") # highlight this
138
+ print("line 7")
139
+ ```
140
+
141
+ Notice that the comment above adds 2 extra lines, and only the desired lines are included, the result is that the actual highlighted line is the rendered line 4, but the source line 6, it's all calculated automatically. 🤓
142
+
143
+ ## License
144
+
145
+ This project is licensed under the terms of the [MIT license](https://github.com/tiangolo/markdown-include-variants/blob/main/LICENSE).
@@ -0,0 +1,8 @@
1
+ markdown_include_variants/__init__.py,sha256=RmaChbqZsW3M0uLEui5TuxIIRNyiDlAT5SZ3girx0Yg,249
2
+ markdown_include_variants/_main.py,sha256=hgg1J_ai-YTiCdGAGz1rlZPx1a-jtGZP6oaMd1C_GQo,10805
3
+ markdown_include_variants/_version.py,sha256=sXLh7g3KC4QCFxcZGBTpG2scR7hmmBsMjq6LqRptkRg,22
4
+ markdown_include_variants/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ markdown_include_variants-0.0.1.dist-info/METADATA,sha256=LzaTfegkmZgbXlPEnQDd-PVvVyW31VSVeQ7ihpU_lTI,5791
6
+ markdown_include_variants-0.0.1.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87
7
+ markdown_include_variants-0.0.1.dist-info/licenses/LICENSE,sha256=FqD5B4VbXJnefprQseE0U8llL6FxojC-i8muZy7YmSU,1086
8
+ markdown_include_variants-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.25.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 Sebastián Ramírez
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.