mdbake 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.
- mdbake/__init__.py +3 -0
- mdbake/builder.py +216 -0
- mdbake/builtin/__init__.py +1 -0
- mdbake/builtin/draft.py +29 -0
- mdbake/builtin/frontmatter_defaults.py +38 -0
- mdbake/cli.py +51 -0
- mdbake/config.py +130 -0
- mdbake/files.py +110 -0
- mdbake/frontmatter.py +34 -0
- mdbake/links.py +104 -0
- mdbake/markdown.py +111 -0
- mdbake/middleware.py +131 -0
- mdbake/nav.py +215 -0
- mdbake/page.py +79 -0
- mdbake/theme/base.html +46 -0
- mdbake/theme/nav.html +21 -0
- mdbake/theme/style.css +174 -0
- mdbake/theme/toc.html +8 -0
- mdbake/toc.py +33 -0
- mdbake-0.1.1.dist-info/METADATA +185 -0
- mdbake-0.1.1.dist-info/RECORD +23 -0
- mdbake-0.1.1.dist-info/WHEEL +4 -0
- mdbake-0.1.1.dist-info/entry_points.txt +2 -0
mdbake/__init__.py
ADDED
mdbake/builder.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
"""Orchestrates the build pipeline."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import posixpath
|
|
7
|
+
import re
|
|
8
|
+
import shutil
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
from urllib.parse import quote
|
|
13
|
+
|
|
14
|
+
import jinja2
|
|
15
|
+
|
|
16
|
+
from .config import Config
|
|
17
|
+
from .files import Files, discover
|
|
18
|
+
from .frontmatter import FrontmatterError, split_frontmatter
|
|
19
|
+
from .links import LinkRef, is_external, relative_url
|
|
20
|
+
from .markdown import create_markdown, pygments_css
|
|
21
|
+
from .middleware import Pipeline
|
|
22
|
+
from .nav import Navigation, build_nav
|
|
23
|
+
from .page import Page
|
|
24
|
+
from .toc import build_toc
|
|
25
|
+
|
|
26
|
+
log = logging.getLogger("mdbake")
|
|
27
|
+
|
|
28
|
+
THEME_DIR = Path(__file__).parent / "theme"
|
|
29
|
+
ASSETS_DIR = "_mdbake"
|
|
30
|
+
_ID_RE = re.compile(r"""\sid\s*=\s*["']([^"']+)["']""")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class BuildError(Exception):
|
|
34
|
+
pass
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(eq=False)
|
|
38
|
+
class Site:
|
|
39
|
+
"""Shared build state handed to middleware as ``site``."""
|
|
40
|
+
|
|
41
|
+
config: Config
|
|
42
|
+
files: Files
|
|
43
|
+
pipeline: Pipeline
|
|
44
|
+
pages: list[Page] = field(default_factory=list)
|
|
45
|
+
nav: Navigation | None = None
|
|
46
|
+
warnings: list[str] = field(default_factory=list)
|
|
47
|
+
|
|
48
|
+
def warn(self, message: str) -> None:
|
|
49
|
+
self.warnings.append(message)
|
|
50
|
+
log.warning(message)
|
|
51
|
+
|
|
52
|
+
def get_page(self, src_path: str) -> Page | None:
|
|
53
|
+
for page in self.pages:
|
|
54
|
+
if page.src_path == src_path:
|
|
55
|
+
return page
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def build(config: Config, *, pipeline: Pipeline | None = None, clean: bool = False) -> Site:
|
|
60
|
+
pipeline = pipeline if pipeline is not None else Pipeline.from_config(config)
|
|
61
|
+
|
|
62
|
+
# 1. config
|
|
63
|
+
config = pipeline.run("on_config", config)
|
|
64
|
+
docs_dir = Path(config.docs_dir)
|
|
65
|
+
if not docs_dir.is_dir():
|
|
66
|
+
raise BuildError(f"docs_dir does not exist: {docs_dir}")
|
|
67
|
+
|
|
68
|
+
# 2. files
|
|
69
|
+
files = discover(docs_dir, exclude=[config.site_dir])
|
|
70
|
+
files = pipeline.run("on_files", files, config=config)
|
|
71
|
+
site = Site(config=config, files=files, pipeline=pipeline)
|
|
72
|
+
|
|
73
|
+
# 3. read pages + frontmatter
|
|
74
|
+
for file in files.pages():
|
|
75
|
+
try:
|
|
76
|
+
text = file.abs_src_path.read_text(encoding="utf-8-sig")
|
|
77
|
+
except (OSError, UnicodeDecodeError) as exc:
|
|
78
|
+
site.warn(f"{file.src_path}: cannot read: {exc}")
|
|
79
|
+
files.remove(file)
|
|
80
|
+
continue
|
|
81
|
+
try:
|
|
82
|
+
meta, body = split_frontmatter(text)
|
|
83
|
+
except FrontmatterError as exc:
|
|
84
|
+
site.warn(f"{file.src_path}: {exc}")
|
|
85
|
+
meta, body = {}, text
|
|
86
|
+
page = pipeline.run("on_page_source", Page(file=file, meta=meta, markdown=body), site=site)
|
|
87
|
+
if page.skip:
|
|
88
|
+
log.debug("Skipping %s", file.src_path)
|
|
89
|
+
files.remove(file)
|
|
90
|
+
continue
|
|
91
|
+
site.pages.append(page)
|
|
92
|
+
|
|
93
|
+
# 4. nav (titles resolve lazily, so H1 titles found while rendering show up)
|
|
94
|
+
site.nav = pipeline.run("on_nav", build_nav(config.nav, site.pages, warn=site.warn), site=site)
|
|
95
|
+
if config.nav:
|
|
96
|
+
in_nav = {id(p) for p in site.nav.pages}
|
|
97
|
+
for page in site.pages:
|
|
98
|
+
if id(page) not in in_nav:
|
|
99
|
+
site.warn(f"{page.src_path}: page exists but is not in nav")
|
|
100
|
+
|
|
101
|
+
# 5. render markdown
|
|
102
|
+
md = create_markdown()
|
|
103
|
+
pipeline.md_setup(md)
|
|
104
|
+
link_refs: list[LinkRef] = []
|
|
105
|
+
for page in site.pages:
|
|
106
|
+
markdown = pipeline.run("on_page_markdown", page.markdown, page=page, site=site)
|
|
107
|
+
env: dict[str, Any] = {"page": page, "site": site, "files": site.files}
|
|
108
|
+
html = md.render(markdown, env)
|
|
109
|
+
headings = env.get("headings", [])
|
|
110
|
+
page.h1_title = next((title for level, title, _ in headings if level == 1 and title), None)
|
|
111
|
+
page.toc = build_toc(headings, config.toc_depth)
|
|
112
|
+
link_refs.extend(env.get("link_refs", []))
|
|
113
|
+
page.html = pipeline.run("on_page_html", html, page=page, site=site)
|
|
114
|
+
page.anchors = set(_ID_RE.findall(page.html))
|
|
115
|
+
|
|
116
|
+
# 6. validate links + anchors
|
|
117
|
+
pages_by_src = {p.src_path: p for p in site.pages}
|
|
118
|
+
for ref in link_refs:
|
|
119
|
+
if ref.broken:
|
|
120
|
+
site.warn(f"{ref.source.src_path}: broken link '{ref.url}'")
|
|
121
|
+
elif ref.fragment and ref.target is not None:
|
|
122
|
+
target = pages_by_src.get(ref.target.src_path)
|
|
123
|
+
if target is not None and ref.fragment not in target.anchors:
|
|
124
|
+
site.warn(
|
|
125
|
+
f"{ref.source.src_path}: link '{ref.url}' points to missing anchor "
|
|
126
|
+
f"'#{ref.fragment}' in {target.src_path}"
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
# 7. templates + output
|
|
130
|
+
site_dir = Path(config.site_dir)
|
|
131
|
+
if clean:
|
|
132
|
+
_clean_site_dir(site_dir, docs_dir)
|
|
133
|
+
_write_site(site, site_dir)
|
|
134
|
+
|
|
135
|
+
# 8. post build
|
|
136
|
+
pipeline.notify("on_post_build", site=site)
|
|
137
|
+
log.info("Built %d pages into %s", len(site.pages), site_dir)
|
|
138
|
+
return site
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _clean_site_dir(site_dir: Path, docs_dir: Path) -> None:
|
|
142
|
+
sd, dd = site_dir.resolve(), docs_dir.resolve()
|
|
143
|
+
forbidden = {dd, Path.cwd().resolve(), Path.home().resolve(), Path(sd.anchor)}
|
|
144
|
+
if sd in forbidden or sd in dd.parents:
|
|
145
|
+
raise BuildError(f"refusing to clean site_dir {sd}: it contains docs_dir or is unsafe")
|
|
146
|
+
if sd.exists():
|
|
147
|
+
shutil.rmtree(sd)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def make_jinja_env(config: Config) -> jinja2.Environment:
|
|
151
|
+
loaders: list[jinja2.BaseLoader] = []
|
|
152
|
+
if config.templates_dir is not None:
|
|
153
|
+
loaders.append(jinja2.FileSystemLoader(str(config.templates_dir)))
|
|
154
|
+
loaders.append(jinja2.FileSystemLoader(str(THEME_DIR)))
|
|
155
|
+
return jinja2.Environment(
|
|
156
|
+
loader=jinja2.ChoiceLoader(loaders),
|
|
157
|
+
autoescape=jinja2.select_autoescape(["html", "htm", "xml"]),
|
|
158
|
+
trim_blocks=True,
|
|
159
|
+
lstrip_blocks=True,
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def page_context(page: Page, site: Site) -> dict[str, Any]:
|
|
164
|
+
def url(target: str) -> str:
|
|
165
|
+
if is_external(target):
|
|
166
|
+
return target
|
|
167
|
+
return quote(relative_url(target, page.url), safe="/#")
|
|
168
|
+
|
|
169
|
+
base_url = posixpath.relpath(".", posixpath.dirname(page.url) or ".")
|
|
170
|
+
toc = page.toc
|
|
171
|
+
if len(toc) == 1 and toc[0].level == 1: # page H1 is the title; show its children
|
|
172
|
+
toc = toc[0].children
|
|
173
|
+
home = site.get_page("index.md") or site.get_page("README.md")
|
|
174
|
+
home_url = home.url if home else (site.nav.pages[0].url if site.nav and site.nav.pages else "index.html")
|
|
175
|
+
return {
|
|
176
|
+
"config": site.config,
|
|
177
|
+
"site_name": site.config.site_name,
|
|
178
|
+
"extra": site.config.extra,
|
|
179
|
+
"page": page,
|
|
180
|
+
"nav": site.nav,
|
|
181
|
+
"toc": toc,
|
|
182
|
+
"url": url,
|
|
183
|
+
"base_url": base_url,
|
|
184
|
+
"assets_url": f"{base_url}/{ASSETS_DIR}",
|
|
185
|
+
"home_url": url(home_url),
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _write_site(site: Site, site_dir: Path) -> None:
|
|
190
|
+
config = site.config
|
|
191
|
+
env = make_jinja_env(config)
|
|
192
|
+
try:
|
|
193
|
+
template = env.get_template("base.html")
|
|
194
|
+
except jinja2.TemplateError as exc:
|
|
195
|
+
raise BuildError(f"cannot load template: {exc}") from exc
|
|
196
|
+
|
|
197
|
+
for page in site.pages:
|
|
198
|
+
ctx = site.pipeline.run("on_page_context", page_context(page, site), page=page, site=site)
|
|
199
|
+
out = site_dir / page.file.dest_path
|
|
200
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
201
|
+
out.write_text(template.render(ctx), encoding="utf-8")
|
|
202
|
+
|
|
203
|
+
for asset in site.files.assets():
|
|
204
|
+
out = site_dir / asset.dest_path
|
|
205
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
206
|
+
shutil.copy2(asset.abs_src_path, out)
|
|
207
|
+
|
|
208
|
+
theme_out = site_dir / ASSETS_DIR
|
|
209
|
+
theme_out.mkdir(parents=True, exist_ok=True)
|
|
210
|
+
style = THEME_DIR / "style.css"
|
|
211
|
+
if config.templates_dir is not None and (config.templates_dir / "style.css").is_file():
|
|
212
|
+
style = config.templates_dir / "style.css"
|
|
213
|
+
shutil.copyfile(style, theme_out / "style.css")
|
|
214
|
+
(theme_out / "pygments.css").write_text(
|
|
215
|
+
pygments_css(config.pygments_style, config.pygments_dark_style), encoding="utf-8"
|
|
216
|
+
)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Bundled example middleware."""
|
mdbake/builtin/draft.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Drop pages whose frontmatter has ``draft: true``.
|
|
2
|
+
|
|
3
|
+
Usage::
|
|
4
|
+
|
|
5
|
+
middleware:
|
|
6
|
+
- mdbake.builtin.draft # module-level default
|
|
7
|
+
- path: mdbake.builtin.draft:Draft # or configurable
|
|
8
|
+
options: {include_drafts: true}
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import logging
|
|
14
|
+
|
|
15
|
+
log = logging.getLogger("mdbake")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Draft:
|
|
19
|
+
def __init__(self, include_drafts: bool = False):
|
|
20
|
+
self.include_drafts = include_drafts
|
|
21
|
+
|
|
22
|
+
def on_page_source(self, page, *, site):
|
|
23
|
+
if page.meta.get("draft") and not self.include_drafts:
|
|
24
|
+
log.info("Draft page excluded: %s", page.src_path)
|
|
25
|
+
page.skip = True
|
|
26
|
+
return page
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
on_page_source = Draft().on_page_source
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Inject default frontmatter values and validate required keys.
|
|
2
|
+
|
|
3
|
+
Usage::
|
|
4
|
+
|
|
5
|
+
middleware:
|
|
6
|
+
- path: mdbake.builtin.frontmatter_defaults:FrontmatterDefaults
|
|
7
|
+
options:
|
|
8
|
+
defaults: {author: Docs Team}
|
|
9
|
+
required: [title]
|
|
10
|
+
strict: false # true: raise instead of warn
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import copy
|
|
16
|
+
from collections.abc import Iterable
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class FrontmatterDefaults:
|
|
21
|
+
def __init__(self, defaults: dict[str, Any] | None = None,
|
|
22
|
+
required: Iterable[str] = (), strict: bool = False):
|
|
23
|
+
self.defaults = dict(defaults or {})
|
|
24
|
+
self.required = list(required)
|
|
25
|
+
self.strict = strict
|
|
26
|
+
|
|
27
|
+
def on_page_source(self, page, *, site):
|
|
28
|
+
if page.skip:
|
|
29
|
+
return page
|
|
30
|
+
for key, value in self.defaults.items():
|
|
31
|
+
page.meta.setdefault(key, copy.deepcopy(value))
|
|
32
|
+
missing = [key for key in self.required if key not in page.meta]
|
|
33
|
+
if missing:
|
|
34
|
+
message = f"{page.src_path}: missing required frontmatter: {', '.join(missing)}"
|
|
35
|
+
if self.strict:
|
|
36
|
+
raise ValueError(message)
|
|
37
|
+
site.warn(message)
|
|
38
|
+
return page
|
mdbake/cli.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Command line interface: ``mdbake build``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import click
|
|
9
|
+
|
|
10
|
+
from . import __version__
|
|
11
|
+
from .builder import BuildError, build as build_site
|
|
12
|
+
from .config import ConfigError, load_config
|
|
13
|
+
from .middleware import MiddlewareError
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@click.group()
|
|
17
|
+
@click.version_option(__version__, prog_name="mdbake")
|
|
18
|
+
def main() -> None:
|
|
19
|
+
"""mdbake - a minimal Markdown to HTML documentation generator."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@main.command()
|
|
23
|
+
@click.option("-f", "--config", "config_file", type=click.Path(dir_okay=False, path_type=Path),
|
|
24
|
+
help="Config file (default: ./mdbake.yml if present).")
|
|
25
|
+
@click.option("-d", "--docs-dir", type=click.Path(file_okay=False, path_type=Path),
|
|
26
|
+
help="Directory with Markdown sources (overrides config).")
|
|
27
|
+
@click.option("-o", "--site-dir", type=click.Path(file_okay=False, path_type=Path),
|
|
28
|
+
help="Output directory (overrides config).")
|
|
29
|
+
@click.option("--clean", is_flag=True, help="Delete site_dir before building.")
|
|
30
|
+
@click.option("-s", "--strict", is_flag=True, help="Exit with an error if there were warnings.")
|
|
31
|
+
@click.option("-v", "--verbose", is_flag=True, help="Verbose output.")
|
|
32
|
+
@click.option("-q", "--quiet", is_flag=True, help="Only show errors.")
|
|
33
|
+
def build(config_file: Path | None, docs_dir: Path | None, site_dir: Path | None,
|
|
34
|
+
clean: bool, strict: bool, verbose: bool, quiet: bool) -> None:
|
|
35
|
+
"""Build the documentation site."""
|
|
36
|
+
level = logging.ERROR if quiet else logging.DEBUG if verbose else logging.INFO
|
|
37
|
+
logging.basicConfig(format="%(levelname)-7s %(message)s", level=level)
|
|
38
|
+
try:
|
|
39
|
+
config = load_config(config_file, docs_dir=docs_dir, site_dir=site_dir)
|
|
40
|
+
site = build_site(config, clean=clean)
|
|
41
|
+
except (ConfigError, BuildError, MiddlewareError) as exc:
|
|
42
|
+
raise click.ClickException(str(exc)) from exc
|
|
43
|
+
if site.warnings:
|
|
44
|
+
msg = f"{len(site.warnings)} warning(s)"
|
|
45
|
+
if strict:
|
|
46
|
+
raise click.ClickException(f"Aborted: {msg} in strict mode")
|
|
47
|
+
logging.getLogger("mdbake").info(msg)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
if __name__ == "__main__": # pragma: no cover
|
|
51
|
+
main()
|
mdbake/config.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Load ``mdbake.yml`` into a frozen :class:`Config` dataclass."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import dataclasses
|
|
6
|
+
import logging
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import yaml
|
|
12
|
+
|
|
13
|
+
log = logging.getLogger("mdbake")
|
|
14
|
+
|
|
15
|
+
DEFAULT_CONFIG_NAMES = ("mdbake.yml", "mdbake.yaml")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ConfigError(Exception):
|
|
19
|
+
"""Raised for a missing or invalid configuration file."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class Config:
|
|
24
|
+
site_name: str = "Documentation"
|
|
25
|
+
docs_dir: Path = Path("docs")
|
|
26
|
+
site_dir: Path = Path("site")
|
|
27
|
+
templates_dir: Path | None = None
|
|
28
|
+
nav: list | None = None
|
|
29
|
+
middleware: list = field(default_factory=list)
|
|
30
|
+
extra: dict = field(default_factory=dict)
|
|
31
|
+
toc_depth: int = 3
|
|
32
|
+
pygments_style: str = "default"
|
|
33
|
+
pygments_dark_style: str = "monokai"
|
|
34
|
+
config_file: Path | None = None
|
|
35
|
+
|
|
36
|
+
def replace(self, **changes: Any) -> Config:
|
|
37
|
+
"""Return a copy with ``changes`` applied (for ``on_config`` middleware)."""
|
|
38
|
+
return dataclasses.replace(self, **changes)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
_KEYS = {f.name for f in dataclasses.fields(Config)} - {"config_file"}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _resolve(value: str | Path, base: Path) -> Path:
|
|
45
|
+
path = Path(value).expanduser()
|
|
46
|
+
return path if path.is_absolute() else (base / path).resolve()
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def find_config_file(directory: Path | None = None) -> Path | None:
|
|
50
|
+
directory = directory or Path.cwd()
|
|
51
|
+
for name in DEFAULT_CONFIG_NAMES:
|
|
52
|
+
candidate = directory / name
|
|
53
|
+
if candidate.is_file():
|
|
54
|
+
return candidate
|
|
55
|
+
return None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def load_config(
|
|
59
|
+
path: str | Path | None = None,
|
|
60
|
+
*,
|
|
61
|
+
docs_dir: str | Path | None = None,
|
|
62
|
+
site_dir: str | Path | None = None,
|
|
63
|
+
) -> Config:
|
|
64
|
+
"""Load configuration.
|
|
65
|
+
|
|
66
|
+
Paths inside the config file are relative to the file's directory; ``docs_dir``
|
|
67
|
+
and ``site_dir`` overrides (from the CLI) are relative to the current directory.
|
|
68
|
+
Without a config file, defaults are used relative to the current directory.
|
|
69
|
+
"""
|
|
70
|
+
cwd = Path.cwd()
|
|
71
|
+
if path is None:
|
|
72
|
+
path = find_config_file(cwd)
|
|
73
|
+
|
|
74
|
+
data: dict[str, Any] = {}
|
|
75
|
+
base = cwd
|
|
76
|
+
config_file = None
|
|
77
|
+
if path is not None:
|
|
78
|
+
config_file = Path(path).expanduser().resolve()
|
|
79
|
+
if not config_file.is_file():
|
|
80
|
+
raise ConfigError(f"Config file not found: {config_file}")
|
|
81
|
+
try:
|
|
82
|
+
raw = yaml.safe_load(config_file.read_text(encoding="utf-8"))
|
|
83
|
+
except yaml.YAMLError as exc:
|
|
84
|
+
raise ConfigError(f"Invalid YAML in {config_file}: {exc}") from exc
|
|
85
|
+
raw = raw or {}
|
|
86
|
+
if not isinstance(raw, dict):
|
|
87
|
+
raise ConfigError(f"{config_file}: top level must be a mapping")
|
|
88
|
+
unknown = sorted(set(raw) - _KEYS)
|
|
89
|
+
if unknown:
|
|
90
|
+
log.warning("Unknown config keys ignored: %s", ", ".join(unknown))
|
|
91
|
+
data = {k: v for k, v in raw.items() if k in _KEYS}
|
|
92
|
+
base = config_file.parent
|
|
93
|
+
|
|
94
|
+
defaults = Config()
|
|
95
|
+
|
|
96
|
+
site_name = data.get("site_name", defaults.site_name)
|
|
97
|
+
if not isinstance(site_name, str):
|
|
98
|
+
raise ConfigError("'site_name' must be a string")
|
|
99
|
+
|
|
100
|
+
nav = data.get("nav")
|
|
101
|
+
if nav is not None and not isinstance(nav, list):
|
|
102
|
+
raise ConfigError("'nav' must be a list")
|
|
103
|
+
|
|
104
|
+
middleware = data.get("middleware") or []
|
|
105
|
+
if not isinstance(middleware, list):
|
|
106
|
+
raise ConfigError("'middleware' must be a list")
|
|
107
|
+
|
|
108
|
+
extra = data.get("extra") or {}
|
|
109
|
+
if not isinstance(extra, dict):
|
|
110
|
+
raise ConfigError("'extra' must be a mapping")
|
|
111
|
+
|
|
112
|
+
toc_depth = data.get("toc_depth", defaults.toc_depth)
|
|
113
|
+
if not isinstance(toc_depth, int) or not 1 <= toc_depth <= 6:
|
|
114
|
+
raise ConfigError("'toc_depth' must be an integer between 1 and 6")
|
|
115
|
+
|
|
116
|
+
templates_dir = data.get("templates_dir")
|
|
117
|
+
|
|
118
|
+
return Config(
|
|
119
|
+
site_name=site_name,
|
|
120
|
+
docs_dir=_resolve(docs_dir, cwd) if docs_dir else _resolve(data.get("docs_dir", "docs"), base),
|
|
121
|
+
site_dir=_resolve(site_dir, cwd) if site_dir else _resolve(data.get("site_dir", "site"), base),
|
|
122
|
+
templates_dir=_resolve(templates_dir, base) if templates_dir else None,
|
|
123
|
+
nav=nav,
|
|
124
|
+
middleware=middleware,
|
|
125
|
+
extra=extra,
|
|
126
|
+
toc_depth=toc_depth,
|
|
127
|
+
pygments_style=str(data.get("pygments_style", defaults.pygments_style)),
|
|
128
|
+
pygments_dark_style=str(data.get("pygments_dark_style", defaults.pygments_dark_style)),
|
|
129
|
+
config_file=config_file,
|
|
130
|
+
)
|
mdbake/files.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""Discover Markdown pages and static assets; map source paths to output paths."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import posixpath
|
|
7
|
+
from collections.abc import Iterable, Iterator
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
PAGE_SUFFIXES = (".md", ".markdown")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def is_page_path(src_path: str) -> bool:
|
|
15
|
+
return src_path.lower().endswith(PAGE_SUFFIXES)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def dest_path_for(src_path: str, *, dir_has_index_md: bool = False) -> str:
|
|
19
|
+
"""Map a source path (posix, relative to docs_dir) to its output path.
|
|
20
|
+
|
|
21
|
+
``foo/bar.md`` -> ``foo/bar.html``; ``foo/index.md`` and ``foo/README.md`` ->
|
|
22
|
+
``foo/index.html`` (``README.md`` only when there is no ``index.md`` next to it).
|
|
23
|
+
Non-page files keep their path.
|
|
24
|
+
"""
|
|
25
|
+
if not is_page_path(src_path):
|
|
26
|
+
return src_path
|
|
27
|
+
directory, name = posixpath.split(src_path)
|
|
28
|
+
stem = name.rsplit(".", 1)[0]
|
|
29
|
+
if stem.lower() == "index" or (stem.lower() == "readme" and not dir_has_index_md):
|
|
30
|
+
return posixpath.join(directory, "index.html")
|
|
31
|
+
return posixpath.join(directory, stem + ".html")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(eq=False)
|
|
35
|
+
class File:
|
|
36
|
+
src_path: str # posix path relative to docs_dir
|
|
37
|
+
abs_src_path: Path
|
|
38
|
+
dest_path: str # posix path relative to site_dir
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def url(self) -> str:
|
|
42
|
+
"""Site-root-relative URL (unquoted)."""
|
|
43
|
+
return self.dest_path
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def is_page(self) -> bool:
|
|
47
|
+
return is_page_path(self.src_path)
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def is_index(self) -> bool:
|
|
51
|
+
return self.is_page and posixpath.basename(self.dest_path) == "index.html"
|
|
52
|
+
|
|
53
|
+
def __repr__(self) -> str:
|
|
54
|
+
return f"File({self.src_path!r} -> {self.dest_path!r})"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class Files:
|
|
58
|
+
"""Ordered collection of :class:`File` objects keyed by ``src_path``."""
|
|
59
|
+
|
|
60
|
+
def __init__(self, files: Iterable[File] = ()):
|
|
61
|
+
self._files: dict[str, File] = {}
|
|
62
|
+
for f in files:
|
|
63
|
+
self.add(f)
|
|
64
|
+
|
|
65
|
+
def __iter__(self) -> Iterator[File]:
|
|
66
|
+
return iter(list(self._files.values()))
|
|
67
|
+
|
|
68
|
+
def __len__(self) -> int:
|
|
69
|
+
return len(self._files)
|
|
70
|
+
|
|
71
|
+
def __contains__(self, src_path: object) -> bool:
|
|
72
|
+
return src_path in self._files
|
|
73
|
+
|
|
74
|
+
def get(self, src_path: str) -> File | None:
|
|
75
|
+
return self._files.get(src_path)
|
|
76
|
+
|
|
77
|
+
def add(self, file: File) -> None:
|
|
78
|
+
self._files[file.src_path] = file
|
|
79
|
+
|
|
80
|
+
def remove(self, file: File | str) -> None:
|
|
81
|
+
key = file if isinstance(file, str) else file.src_path
|
|
82
|
+
self._files.pop(key, None)
|
|
83
|
+
|
|
84
|
+
def pages(self) -> list[File]:
|
|
85
|
+
return [f for f in self._files.values() if f.is_page]
|
|
86
|
+
|
|
87
|
+
def assets(self) -> list[File]:
|
|
88
|
+
return [f for f in self._files.values() if not f.is_page]
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def discover(docs_dir: Path, *, exclude: Iterable[Path] = ()) -> Files:
|
|
92
|
+
"""Walk ``docs_dir`` recursively, skipping dotfiles/dot-dirs and ``exclude`` dirs."""
|
|
93
|
+
docs_dir = Path(docs_dir).resolve()
|
|
94
|
+
excluded = {Path(p).resolve() for p in exclude}
|
|
95
|
+
result = Files()
|
|
96
|
+
for root, dirs, names in os.walk(docs_dir):
|
|
97
|
+
root_path = Path(root)
|
|
98
|
+
dirs[:] = sorted(
|
|
99
|
+
d for d in dirs if not d.startswith(".") and (root_path / d).resolve() not in excluded
|
|
100
|
+
)
|
|
101
|
+
lowered = {n.lower() for n in names}
|
|
102
|
+
has_index = any(f"index{s}" in lowered for s in PAGE_SUFFIXES)
|
|
103
|
+
for name in sorted(names):
|
|
104
|
+
if name.startswith("."):
|
|
105
|
+
continue
|
|
106
|
+
abs_path = root_path / name
|
|
107
|
+
src_path = abs_path.relative_to(docs_dir).as_posix()
|
|
108
|
+
dest = dest_path_for(src_path, dir_has_index_md=has_index)
|
|
109
|
+
result.add(File(src_path=src_path, abs_src_path=abs_path, dest_path=dest))
|
|
110
|
+
return result
|
mdbake/frontmatter.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Split YAML frontmatter from a Markdown document."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import yaml
|
|
9
|
+
|
|
10
|
+
_FRONTMATTER_RE = re.compile(
|
|
11
|
+
r"\A---[ \t]*\r?\n(?P<yaml>.*?\r?\n)??(?:---|\.\.\.)[ \t]*(?:\r?\n|\Z)", re.DOTALL
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class FrontmatterError(ValueError):
|
|
16
|
+
"""Raised when frontmatter exists but is not a valid YAML mapping."""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def split_frontmatter(text: str) -> tuple[dict[str, Any], str]:
|
|
20
|
+
"""Return ``(meta, body)``. Documents without frontmatter yield ``({}, text)``."""
|
|
21
|
+
text = text.lstrip("")
|
|
22
|
+
match = _FRONTMATTER_RE.match(text)
|
|
23
|
+
if not match:
|
|
24
|
+
return {}, text
|
|
25
|
+
raw = match.group("yaml") or ""
|
|
26
|
+
try:
|
|
27
|
+
meta = yaml.safe_load(raw)
|
|
28
|
+
except yaml.YAMLError as exc:
|
|
29
|
+
raise FrontmatterError(f"invalid YAML frontmatter: {exc}") from exc
|
|
30
|
+
if meta is None:
|
|
31
|
+
meta = {}
|
|
32
|
+
if not isinstance(meta, dict):
|
|
33
|
+
raise FrontmatterError("frontmatter must be a YAML mapping")
|
|
34
|
+
return meta, text[match.end():]
|