md2site-cli 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
md2site/nav.py ADDED
@@ -0,0 +1,286 @@
1
+ """Navigation tree builder, sorting, breadcrumbs, and prev/next ordering."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections import defaultdict
7
+ from collections.abc import Sequence
8
+ from pathlib import PurePosixPath
9
+ from typing import TYPE_CHECKING
10
+
11
+ from md2site.diagnostics import MD2S001, suggest_match
12
+ from md2site.model import Diagnostic, NavNode, Page
13
+ from md2site.titles import humanize
14
+
15
+ if TYPE_CHECKING:
16
+ from md2site.config import NavConfigEntry
17
+
18
+ _NUMERIC_PREFIX_RE = re.compile(r"^(\d+)[_\-. ]+")
19
+
20
+
21
+ def _numeric_prefix(name: str) -> float:
22
+ match = _NUMERIC_PREFIX_RE.match(name)
23
+ if match:
24
+ return float(int(match.group(1)))
25
+ return float("inf")
26
+
27
+
28
+ def _sort_key(node: NavNode, raw_name: str) -> tuple[float, float, str, int, str]:
29
+ order = (
30
+ node.page.order if node.page is not None and node.page.order is not None else float("inf")
31
+ )
32
+ prefix = _numeric_prefix(raw_name)
33
+ kind_rank = 0 if node.is_dir else 1
34
+ return (order, prefix, raw_name.lower(), kind_rank, raw_name)
35
+
36
+
37
+ def _index_visible_dirs(
38
+ visible: Sequence[Page],
39
+ ) -> tuple[dict[PurePosixPath, list[Page]], dict[PurePosixPath, set[PurePosixPath]]]:
40
+ pages_by_dir: dict[PurePosixPath, list[Page]] = defaultdict(list)
41
+ subdirs_by_dir: dict[PurePosixPath, set[PurePosixPath]] = defaultdict(set)
42
+
43
+ for page in visible:
44
+ parent = page.rel.parent
45
+ pages_by_dir[parent].append(page)
46
+ curr = parent
47
+ while curr != PurePosixPath("."):
48
+ anc = curr.parent
49
+ subdirs_by_dir[anc].add(curr)
50
+ curr = anc
51
+ return pages_by_dir, subdirs_by_dir
52
+
53
+
54
+ def _build_auto_children(
55
+ dir_rel: PurePosixPath,
56
+ pages_by_dir: dict[PurePosixPath, list[Page]],
57
+ subdirs_by_dir: dict[PurePosixPath, set[PurePosixPath]],
58
+ ) -> list[NavNode]:
59
+ items: list[tuple[tuple[float, float, str, int, str], NavNode]] = []
60
+
61
+ for page in sorted(pages_by_dir.get(dir_rel, []), key=lambda p: p.rel.as_posix()):
62
+ if page.out_rel.name == "index.html":
63
+ # Index page serves as its folder's landing link, not a child.
64
+ continue
65
+ node = NavNode(label=page.title, page=page, children=[], is_dir=False)
66
+ items.append((_sort_key(node, page.rel.stem), node))
67
+
68
+ for sub_rel in sorted(subdirs_by_dir.get(dir_rel, set()), key=lambda p: p.as_posix()):
69
+ sub_node = _build_auto_dir_node(sub_rel, pages_by_dir, subdirs_by_dir)
70
+ if sub_node is not None:
71
+ items.append((_sort_key(sub_node, sub_rel.name), sub_node))
72
+
73
+ items.sort(key=lambda pair: pair[0])
74
+ return [pair[1] for pair in items]
75
+
76
+
77
+ def _build_auto_dir_node(
78
+ sub_rel: PurePosixPath,
79
+ pages_by_dir: dict[PurePosixPath, list[Page]],
80
+ subdirs_by_dir: dict[PurePosixPath, set[PurePosixPath]],
81
+ ) -> NavNode | None:
82
+ sub_index: Page | None = None
83
+ for candidate in pages_by_dir.get(sub_rel, []):
84
+ if candidate.out_rel == sub_rel / "index.html":
85
+ sub_index = candidate
86
+ break
87
+ children = _build_auto_children(sub_rel, pages_by_dir, subdirs_by_dir)
88
+ if sub_index is None and not children:
89
+ return None
90
+ label = sub_index.title if sub_index is not None else humanize(sub_rel.name)
91
+ return NavNode(
92
+ label=label,
93
+ page=sub_index,
94
+ children=children,
95
+ is_dir=True,
96
+ )
97
+
98
+
99
+ def build_nav(pages: list[Page]) -> list[NavNode]:
100
+ """Build the sorted, hierarchical navigation tree from scanned pages."""
101
+ visible = [p for p in pages if not p.hidden]
102
+ pages_by_dir, subdirs_by_dir = _index_visible_dirs(visible)
103
+
104
+ root_dir = PurePosixPath(".")
105
+ top_nodes = _build_auto_children(root_dir, pages_by_dir, subdirs_by_dir)
106
+
107
+ root_index: Page | None = None
108
+ for candidate in pages_by_dir.get(root_dir, []):
109
+ if candidate.out_rel == PurePosixPath("index.html"):
110
+ root_index = candidate
111
+ break
112
+
113
+ if root_index is not None:
114
+ root_node = NavNode(label=root_index.title, page=root_index, children=[], is_dir=False)
115
+ return [root_node, *top_nodes]
116
+ return top_nodes
117
+
118
+
119
+ def resolve_nav(
120
+ pages: Sequence[Page],
121
+ nav_config: Sequence[NavConfigEntry] | None = None,
122
+ *,
123
+ config_file: str = "md2site.config.json",
124
+ ) -> tuple[list[NavNode], list[Diagnostic]]:
125
+ """Build navigation using explicit ``nav_config`` when provided, else auto-discovery."""
126
+ if nav_config is None:
127
+ return build_nav(list(pages)), []
128
+
129
+ pages_by_rel: dict[str, Page] = {p.rel.as_posix(): p for p in pages}
130
+ visible = [p for p in pages if not p.hidden]
131
+ pages_by_dir, subdirs_by_dir = _index_visible_dirs(visible)
132
+
133
+ all_dirs: set[PurePosixPath] = set()
134
+ for p in pages:
135
+ curr = p.rel.parent
136
+ while curr != PurePosixPath("."):
137
+ all_dirs.add(curr)
138
+ curr = curr.parent
139
+
140
+ dir_candidates = sorted(f"{d.as_posix()}/" for d in all_dirs)
141
+ page_candidates = sorted(pages_by_rel)
142
+ diags: list[Diagnostic] = []
143
+
144
+ def _build_entries(entries: Sequence[NavConfigEntry]) -> list[NavNode]:
145
+ nodes: list[NavNode] = []
146
+ for entry in entries:
147
+ if entry.is_dir_auto:
148
+ assert entry.path is not None
149
+ sub_rel = PurePosixPath(entry.path)
150
+ dir_node = _build_auto_dir_node(sub_rel, pages_by_dir, subdirs_by_dir)
151
+ if dir_node is not None:
152
+ nodes.append(dir_node)
153
+ elif sub_rel not in all_dirs:
154
+ raw_target = f"{entry.path}/"
155
+ diags.append(
156
+ Diagnostic(
157
+ level="warning",
158
+ code=MD2S001,
159
+ file=config_file,
160
+ line=None,
161
+ message=f"Nav directory not found: {raw_target}",
162
+ target=raw_target,
163
+ suggestion=suggest_match(raw_target, dir_candidates),
164
+ )
165
+ )
166
+ continue
167
+
168
+ is_section = entry.has_children or entry.path is None
169
+ if is_section:
170
+ sec_page: Page | None = None
171
+ if entry.path is not None:
172
+ matched = pages_by_rel.get(entry.path)
173
+ if matched is None:
174
+ diags.append(
175
+ Diagnostic(
176
+ level="warning",
177
+ code=MD2S001,
178
+ file=config_file,
179
+ line=None,
180
+ message=f"Nav page target not found: {entry.path}",
181
+ target=entry.path,
182
+ suggestion=suggest_match(entry.path, page_candidates),
183
+ )
184
+ )
185
+ elif not matched.hidden:
186
+ sec_page = matched
187
+
188
+ child_nodes = _build_entries(entry.children)
189
+ if entry.label is not None:
190
+ label = entry.label
191
+ elif sec_page is not None:
192
+ label = sec_page.title
193
+ elif entry.path is not None:
194
+ p_rel = PurePosixPath(entry.path)
195
+ raw_part = (
196
+ p_rel.parent.name
197
+ if p_rel.name.lower()
198
+ in ("index.md", "index.markdown", "readme.md", "readme.markdown")
199
+ and p_rel.parent != PurePosixPath(".")
200
+ else p_rel.stem
201
+ )
202
+ label = humanize(raw_part)
203
+ else:
204
+ label = ""
205
+ nodes.append(NavNode(label=label, page=sec_page, children=child_nodes, is_dir=True))
206
+ continue
207
+
208
+ assert entry.path is not None
209
+ leaf = pages_by_rel.get(entry.path)
210
+ if leaf is None:
211
+ diags.append(
212
+ Diagnostic(
213
+ level="warning",
214
+ code=MD2S001,
215
+ file=config_file,
216
+ line=None,
217
+ message=f"Nav page target not found: {entry.path}",
218
+ target=entry.path,
219
+ suggestion=suggest_match(entry.path, page_candidates),
220
+ )
221
+ )
222
+ continue
223
+ if leaf.hidden:
224
+ continue
225
+ leaf_label = entry.label if entry.label is not None else leaf.title
226
+ nodes.append(NavNode(label=leaf_label, page=leaf, children=[], is_dir=False))
227
+ return nodes
228
+
229
+ return _build_entries(nav_config), diags
230
+
231
+
232
+ def flatten(nav: list[NavNode]) -> list[Page]:
233
+ """Flatten the navigation tree in depth-first document order."""
234
+ ordered: list[Page] = []
235
+ for node in nav:
236
+ if node.page is not None:
237
+ ordered.append(node.page)
238
+ if node.children:
239
+ ordered.extend(flatten(node.children))
240
+ return ordered
241
+
242
+
243
+ def _find_nav_trail(nav: list[NavNode], target_rel: PurePosixPath) -> list[tuple[str, Page | None]]:
244
+ for node in nav:
245
+ if node.page is not None and node.page.rel == target_rel:
246
+ return [(node.label, node.page)]
247
+ if node.children:
248
+ sub_trail = _find_nav_trail(node.children, target_rel)
249
+ if sub_trail:
250
+ return [(node.label, node.page), *sub_trail]
251
+ return []
252
+
253
+
254
+ def breadcrumbs(nav: list[NavNode], page: Page) -> list[tuple[str, Page | None]]:
255
+ """Return breadcrumb ``(label, page)`` trail from root to ``page``."""
256
+ trail = _find_nav_trail(nav, page.rel)
257
+ if trail:
258
+ return trail
259
+
260
+ # Fallback for hidden pages not present in nav: walk matching directory nodes.
261
+ parts = page.rel.parent.parts
262
+ acc: list[tuple[str, Page | None]] = []
263
+ nodes = nav
264
+ for depth in range(len(parts)):
265
+ prefix = PurePosixPath(*parts[: depth + 1])
266
+ matched_node: NavNode | None = None
267
+ for node in nodes:
268
+ if not node.is_dir:
269
+ continue
270
+ if node.page is not None and node.page.rel.parent == prefix:
271
+ matched_node = node
272
+ break
273
+ if any(
274
+ child.page is not None and child.page.rel.parent == prefix
275
+ for child in node.children
276
+ ):
277
+ matched_node = node
278
+ break
279
+ if matched_node is None:
280
+ acc.append((humanize(parts[depth]), None))
281
+ nodes = []
282
+ else:
283
+ acc.append((matched_node.label, matched_node.page))
284
+ nodes = matched_node.children
285
+ acc.append((page.title, page))
286
+ return acc
md2site/paths.py ADDED
@@ -0,0 +1,130 @@
1
+ """Filesystem and POSIX URL path utilities for md2site."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections import defaultdict
7
+ from collections.abc import Sequence
8
+ from pathlib import PurePosixPath
9
+ from urllib.parse import quote
10
+
11
+ from md2site.model import Diagnostic
12
+
13
+ INDEX_STEMS = frozenset({"index", "README"})
14
+ _SAFE_SEG_RE = re.compile(r"^[A-Za-z0-9._~-]+$")
15
+
16
+
17
+ def _quote_seg(seg: str) -> str:
18
+ if _SAFE_SEG_RE.match(seg):
19
+ return seg
20
+ return quote(seg, safe="")
21
+
22
+
23
+ def out_rel_for(rel_md: PurePosixPath) -> PurePosixPath:
24
+ """Compute the default output HTML path for a source Markdown path."""
25
+ if rel_md.stem in INDEX_STEMS:
26
+ return rel_md.with_name("index.html")
27
+ return rel_md.with_suffix(".html")
28
+
29
+
30
+ def assign_out_rels(
31
+ rels: Sequence[PurePosixPath],
32
+ ) -> tuple[dict[PurePosixPath, PurePosixPath], list[Diagnostic]]:
33
+ """Assign output HTML paths for a collection of Markdown paths.
34
+
35
+ If a directory contains both ``index.*`` and ``README.*``, ``index.*`` takes
36
+ ``index.html``, ``README.*`` falls back to ``README.html``, and an
37
+ ``MD2S008`` warning diagnostic is emitted. Any remaining output path
38
+ collisions also emit ``MD2S008``.
39
+ """
40
+ by_dir: dict[PurePosixPath, list[PurePosixPath]] = defaultdict(list)
41
+ for rel in sorted(rels, key=lambda p: p.as_posix()):
42
+ by_dir[rel.parent].append(rel)
43
+
44
+ mapping: dict[PurePosixPath, PurePosixPath] = {}
45
+ diagnostics: list[Diagnostic] = []
46
+ seen_out: dict[PurePosixPath, PurePosixPath] = {}
47
+
48
+ for directory in sorted(by_dir, key=lambda p: p.as_posix()):
49
+ files = by_dir[directory]
50
+ index_files = [p for p in files if p.stem == "index"]
51
+ readme_files = [p for p in files if p.stem == "README"]
52
+ has_index = len(index_files) > 0
53
+
54
+ for rel in files:
55
+ if has_index and rel in readme_files:
56
+ candidate = rel.with_name("README.html")
57
+ diagnostics.append(
58
+ Diagnostic(
59
+ level="warning",
60
+ code="MD2S008",
61
+ file=rel.as_posix(),
62
+ line=None,
63
+ message=(
64
+ f"Folder already has {index_files[0].name}; "
65
+ f"emitting {rel.name} as {candidate.as_posix()}"
66
+ ),
67
+ target=index_files[0].as_posix(),
68
+ suggestion=candidate.as_posix(),
69
+ )
70
+ )
71
+ else:
72
+ candidate = out_rel_for(rel)
73
+
74
+ if candidate in seen_out:
75
+ first = seen_out[candidate]
76
+ diagnostics.append(
77
+ Diagnostic(
78
+ level="warning",
79
+ code="MD2S008",
80
+ file=rel.as_posix(),
81
+ line=None,
82
+ message=(
83
+ f"Output path collision at {candidate.as_posix()} "
84
+ f"(already claimed by {first.as_posix()})"
85
+ ),
86
+ target=first.as_posix(),
87
+ )
88
+ )
89
+ else:
90
+ seen_out[candidate] = rel
91
+ mapping[rel] = candidate
92
+
93
+ return mapping, diagnostics
94
+
95
+
96
+ def root_prefix(out_rel: PurePosixPath) -> str:
97
+ """Return the relative prefix from an output HTML file back to site root."""
98
+ depth = len(out_rel.parts) - 1
99
+ if depth <= 0:
100
+ return "./"
101
+ return "../" * depth
102
+
103
+
104
+ def quote_posix_path(path: PurePosixPath | str) -> str:
105
+ """Percent-encode each segment of a POSIX path while preserving ``/``."""
106
+ pure = PurePosixPath(path)
107
+ return "/".join(_quote_seg(part) for part in pure.parts)
108
+
109
+
110
+ def rel_url(from_out: PurePosixPath, to_out: PurePosixPath) -> str:
111
+ """Compute a relative, percent-encoded URL from one output file to another."""
112
+ from_dir_parts = from_out.parent.parts
113
+ to_dir_parts = to_out.parent.parts
114
+
115
+ common = 0
116
+ for a, b in zip(from_dir_parts, to_dir_parts, strict=False):
117
+ if a != b:
118
+ break
119
+ common += 1
120
+
121
+ ups = len(from_dir_parts) - common
122
+ remainder = to_out.parts[common:]
123
+ quoted_remainder = "/".join(_quote_seg(part) for part in remainder)
124
+
125
+ if ups == 0:
126
+ if len(remainder) == 1:
127
+ return f"./{quoted_remainder}"
128
+ return quoted_remainder
129
+
130
+ return f"{'../' * ups}{quoted_remainder}"