| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import gzip |
| 4 |
import logging |
| 5 |
import os |
| 6 |
import time |
| 7 |
from typing import TYPE_CHECKING, Sequence |
| 8 |
from urllib.parse import urljoin, urlsplit |
| 9 |
|
| 10 |
import jinja2 |
| 11 |
from jinja2.exceptions import TemplateNotFound |
| 12 |
|
| 13 |
import mkdocs |
| 14 |
from mkdocs import utils |
| 15 |
from mkdocs.exceptions import Abort, BuildError |
| 16 |
from mkdocs.structure.files import File, Files, InclusionLevel, get_files, set_exclusions |
| 17 |
from mkdocs.structure.nav import Navigation, get_navigation |
| 18 |
from mkdocs.structure.pages import Page |
| 19 |
from mkdocs.utils import DuplicateFilter # noqa: F401 - legacy re-export |
| 20 |
from mkdocs.utils import templates |
| 21 |
|
| 22 |
if TYPE_CHECKING: |
| 23 |
from mkdocs.config.defaults import MkDocsConfig |
| 24 |
|
| 25 |
|
| 26 |
log = logging.getLogger(__name__) |
| 27 |
|
| 28 |
|
| 29 |
def get_context( |
| 30 |
nav: Navigation, |
| 31 |
files: Sequence[File] | Files, |
| 32 |
config: MkDocsConfig, |
| 33 |
page: Page | None = None, |
| 34 |
base_url: str = '', |
| 35 |
) -> templates.TemplateContext: |
| 36 |
"""Return the template context for a given page or template.""" |
| 37 |
if page is not None: |
| 38 |
base_url = utils.get_relative_url('.', page.url) |
| 39 |
|
| 40 |
extra_javascript = [ |
| 41 |
utils.normalize_url(str(script), page, base_url) for script in config.extra_javascript |
| 42 |
] |
| 43 |
extra_css = [utils.normalize_url(path, page, base_url) for path in config.extra_css] |
| 44 |
|
| 45 |
if isinstance(files, Files): |
| 46 |
files = files.documentation_pages() |
| 47 |
|
| 48 |
return templates.TemplateContext( |
| 49 |
nav=nav, |
| 50 |
pages=files, |
| 51 |
base_url=base_url, |
| 52 |
extra_css=extra_css, |
| 53 |
extra_javascript=extra_javascript, |
| 54 |
mkdocs_version=mkdocs.__version__, |
| 55 |
build_date_utc=utils.get_build_datetime(), |
| 56 |
config=config, |
| 57 |
page=page, |
| 58 |
) |
| 59 |
|
| 60 |
|
| 61 |
def _build_template( |
| 62 |
name: str, template: jinja2.Template, files: Files, config: MkDocsConfig, nav: Navigation |
| 63 |
) -> str: |
| 64 |
"""Return rendered output for given template as a string.""" |
| 65 |
# Run `pre_template` plugin events. |
| 66 |
template = config.plugins.on_pre_template(template, template_name=name, config=config) |
| 67 |
|
| 68 |
if utils.is_error_template(name): |
| 69 |
# Force absolute URLs in the nav of error pages and account for the |
| 70 |
# possibility that the docs root might be different than the server root. |
| 71 |
# See https://github.com/mkdocs/mkdocs/issues/77. |
| 72 |
# However, if site_url is not set, assume the docs root and server root |
| 73 |
# are the same. See https://github.com/mkdocs/mkdocs/issues/1598. |
| 74 |
base_url = urlsplit(config.site_url or '/').path |
| 75 |
else: |
| 76 |
base_url = utils.get_relative_url('.', name) |
| 77 |
|
| 78 |
context = get_context(nav, files, config, base_url=base_url) |
| 79 |
|
| 80 |
# Run `template_context` plugin events. |
| 81 |
context = config.plugins.on_template_context(context, template_name=name, config=config) |
| 82 |
|
| 83 |
output = template.render(context) |
| 84 |
|
| 85 |
# Run `post_template` plugin events. |
| 86 |
output = config.plugins.on_post_template(output, template_name=name, config=config) |
| 87 |
|
| 88 |
return output |
| 89 |
|
| 90 |
|
| 91 |
def _build_theme_template( |
| 92 |
template_name: str, env: jinja2.Environment, files: Files, config: MkDocsConfig, nav: Navigation |
| 93 |
) -> None: |
| 94 |
"""Build a template using the theme environment.""" |
| 95 |
log.debug(f"Building theme template: {template_name}") |
| 96 |
|
| 97 |
try: |
| 98 |
template = env.get_template(template_name) |
| 99 |
except TemplateNotFound: |
| 100 |
log.warning(f"Template skipped: '{template_name}' not found in theme directories.") |
| 101 |
return |
| 102 |
|
| 103 |
output = _build_template(template_name, template, files, config, nav) |
| 104 |
|
| 105 |
if output.strip(): |
| 106 |
output_path = os.path.join(config.site_dir, template_name) |
| 107 |
utils.write_file(output.encode('utf-8'), output_path) |
| 108 |
|
| 109 |
if template_name == 'sitemap.xml': |
| 110 |
log.debug(f"Gzipping template: {template_name}") |
| 111 |
gz_filename = f'{output_path}.gz' |
| 112 |
with open(gz_filename, 'wb') as f: |
| 113 |
timestamp = utils.get_build_timestamp( |
| 114 |
pages=[f.page for f in files.documentation_pages() if f.page is not None] |
| 115 |
) |
| 116 |
with gzip.GzipFile( |
| 117 |
fileobj=f, filename=gz_filename, mode='wb', mtime=timestamp |
| 118 |
) as gz_buf: |
| 119 |
gz_buf.write(output.encode('utf-8')) |
| 120 |
else: |
| 121 |
log.info(f"Template skipped: '{template_name}' generated empty output.") |
| 122 |
|
| 123 |
|
| 124 |
def _build_extra_template(template_name: str, files: Files, config: MkDocsConfig, nav: Navigation): |
| 125 |
"""Build user templates which are not part of the theme.""" |
| 126 |
log.debug(f"Building extra template: {template_name}") |
| 127 |
|
| 128 |
file = files.get_file_from_path(template_name) |
| 129 |
if file is None: |
| 130 |
log.warning(f"Template skipped: '{template_name}' not found in docs_dir.") |
| 131 |
return |
| 132 |
|
| 133 |
try: |
| 134 |
template = jinja2.Template(file.content_string) |
| 135 |
except Exception as e: |
| 136 |
log.warning(f"Error reading template '{template_name}': {e}") |
| 137 |
return |
| 138 |
|
| 139 |
output = _build_template(template_name, template, files, config, nav) |
| 140 |
|
| 141 |
if output.strip(): |
| 142 |
utils.write_file(output.encode('utf-8'), file.abs_dest_path) |
| 143 |
else: |
| 144 |
log.info(f"Template skipped: '{template_name}' generated empty output.") |
| 145 |
|
| 146 |
|
| 147 |
def _populate_page(page: Page, config: MkDocsConfig, files: Files, dirty: bool = False) -> None: |
| 148 |
"""Read page content from docs_dir and render Markdown.""" |
| 149 |
config._current_page = page |
| 150 |
try: |
| 151 |
# When --dirty is used, only read the page if the file has been modified since the |
| 152 |
# previous build of the output. |
| 153 |
if dirty and not page.file.is_modified(): |
| 154 |
return |
| 155 |
|
| 156 |
# Run the `pre_page` plugin event |
| 157 |
page = config.plugins.on_pre_page(page, config=config, files=files) |
| 158 |
|
| 159 |
page.read_source(config) |
| 160 |
assert page.markdown is not None |
| 161 |
|
| 162 |
# Run `page_markdown` plugin events. |
| 163 |
page.markdown = config.plugins.on_page_markdown( |
| 164 |
page.markdown, page=page, config=config, files=files |
| 165 |
) |
| 166 |
|
| 167 |
page.render(config, files) |
| 168 |
assert page.content is not None |
| 169 |
|
| 170 |
# Run `page_content` plugin events. |
| 171 |
page.content = config.plugins.on_page_content( |
| 172 |
page.content, page=page, config=config, files=files |
| 173 |
) |
| 174 |
except Exception as e: |
| 175 |
message = f"Error reading page '{page.file.src_uri}':" |
| 176 |
# Prevent duplicated the error message because it will be printed immediately afterwards. |
| 177 |
if not isinstance(e, BuildError): |
| 178 |
message += f" {e}" |
| 179 |
log.error(message) |
| 180 |
raise |
| 181 |
finally: |
| 182 |
config._current_page = None |
| 183 |
|
| 184 |
|
| 185 |
def _build_page( |
| 186 |
page: Page, |
| 187 |
config: MkDocsConfig, |
| 188 |
doc_files: Sequence[File], |
| 189 |
nav: Navigation, |
| 190 |
env: jinja2.Environment, |
| 191 |
dirty: bool = False, |
| 192 |
excluded: bool = False, |
| 193 |
) -> None: |
| 194 |
"""Pass a Page to theme template and write output to site_dir.""" |
| 195 |
config._current_page = page |
| 196 |
try: |
| 197 |
# When --dirty is used, only build the page if the file has been modified since the |
| 198 |
# previous build of the output. |
| 199 |
if dirty and not page.file.is_modified(): |
| 200 |
return |
| 201 |
|
| 202 |
log.debug(f"Building page {page.file.src_uri}") |
| 203 |
|
| 204 |
# Activate page. Signals to theme that this is the current page. |
| 205 |
page.active = True |
| 206 |
|
| 207 |
context = get_context(nav, doc_files, config, page) |
| 208 |
|
| 209 |
# Allow 'template:' override in md source files. |
| 210 |
template = env.get_template(page.meta.get('template', 'main.html')) |
| 211 |
|
| 212 |
# Run `page_context` plugin events. |
| 213 |
context = config.plugins.on_page_context(context, page=page, config=config, nav=nav) |
| 214 |
|
| 215 |
if excluded: |
| 216 |
page.content = ( |
| 217 |
'<div class="mkdocs-draft-marker" title="This page will not be included into the built site.">' |
| 218 |
'DRAFT' |
| 219 |
'</div>' + (page.content or '') |
| 220 |
) |
| 221 |
|
| 222 |
# Render the template. |
| 223 |
output = template.render(context) |
| 224 |
|
| 225 |
# Run `post_page` plugin events. |
| 226 |
output = config.plugins.on_post_page(output, page=page, config=config) |
| 227 |
|
| 228 |
# Write the output file. |
| 229 |
if output.strip(): |
| 230 |
utils.write_file( |
| 231 |
output.encode('utf-8', errors='xmlcharrefreplace'), page.file.abs_dest_path |
| 232 |
) |
| 233 |
else: |
| 234 |
log.info(f"Page skipped: '{page.file.src_uri}'. Generated empty output.") |
| 235 |
|
| 236 |
except Exception as e: |
| 237 |
message = f"Error building page '{page.file.src_uri}':" |
| 238 |
# Prevent duplicated the error message because it will be printed immediately afterwards. |
| 239 |
if not isinstance(e, BuildError): |
| 240 |
message += f" {e}" |
| 241 |
log.error(message) |
| 242 |
raise |
| 243 |
finally: |
| 244 |
# Deactivate page |
| 245 |
page.active = False |
| 246 |
config._current_page = None |
| 247 |
|
| 248 |
|
| 249 |
def build(config: MkDocsConfig, *, serve_url: str | None = None, dirty: bool = False) -> None: |
| 250 |
"""Perform a full site build.""" |
| 251 |
logger = logging.getLogger('mkdocs') |
| 252 |
|
| 253 |
# Add CountHandler for strict mode |
| 254 |
warning_counter = utils.CountHandler() |
| 255 |
warning_counter.setLevel(logging.WARNING) |
| 256 |
if config.strict: |
| 257 |
logging.getLogger('mkdocs').addHandler(warning_counter) |
| 258 |
|
| 259 |
inclusion = InclusionLevel.is_in_serve if serve_url else InclusionLevel.is_included |
| 260 |
|
| 261 |
try: |
| 262 |
start = time.monotonic() |
| 263 |
|
| 264 |
# Run `config` plugin events. |
| 265 |
config = config.plugins.on_config(config) |
| 266 |
|
| 267 |
# Run `pre_build` plugin events. |
| 268 |
config.plugins.on_pre_build(config=config) |
| 269 |
|
| 270 |
if not dirty: |
| 271 |
log.info("Cleaning site directory") |
| 272 |
utils.clean_directory(config.site_dir) |
| 273 |
else: # pragma: no cover |
| 274 |
# Warn user about problems that may occur with --dirty option |
| 275 |
log.warning( |
| 276 |
"A 'dirty' build is being performed, this will likely lead to inaccurate navigation and other" |
| 277 |
" links within your site. This option is designed for site development purposes only." |
| 278 |
) |
| 279 |
|
| 280 |
if not serve_url: # pragma: no cover |
| 281 |
log.info(f"Building documentation to directory: {config.site_dir}") |
| 282 |
if dirty and site_directory_contains_stale_files(config.site_dir): |
| 283 |
log.info("The directory contains stale files. Use --clean to remove them.") |
| 284 |
|
| 285 |
# First gather all data from all files/pages to ensure all data is consistent across all pages. |
| 286 |
|
| 287 |
files = get_files(config) |
| 288 |
env = config.theme.get_env() |
| 289 |
files.add_files_from_theme(env, config) |
| 290 |
|
| 291 |
# Run `files` plugin events. |
| 292 |
files = config.plugins.on_files(files, config=config) |
| 293 |
# If plugins have added files but haven't set their inclusion level, calculate it again. |
| 294 |
set_exclusions(files, config) |
| 295 |
|
| 296 |
nav = get_navigation(files, config) |
| 297 |
|
| 298 |
# Run `nav` plugin events. |
| 299 |
nav = config.plugins.on_nav(nav, config=config, files=files) |
| 300 |
|
| 301 |
log.debug("Reading markdown pages.") |
| 302 |
excluded = [] |
| 303 |
for file in files.documentation_pages(inclusion=inclusion): |
| 304 |
log.debug(f"Reading: {file.src_uri}") |
| 305 |
if file.page is None and file.inclusion.is_not_in_nav(): |
| 306 |
if serve_url and file.inclusion.is_excluded(): |
| 307 |
excluded.append(urljoin(serve_url, file.url)) |
| 308 |
Page(None, file, config) |
| 309 |
assert file.page is not None |
| 310 |
_populate_page(file.page, config, files, dirty) |
| 311 |
if excluded: |
| 312 |
log.info( |
| 313 |
"The following pages are being built only for the preview " |
| 314 |
"but will be excluded from `mkdocs build` per `draft_docs` config:\n - " |
| 315 |
+ "\n - ".join(excluded) |
| 316 |
) |
| 317 |
|
| 318 |
# Run `env` plugin events. |
| 319 |
env = config.plugins.on_env(env, config=config, files=files) |
| 320 |
|
| 321 |
# Start writing files to site_dir now that all data is gathered. Note that order matters. Files |
| 322 |
# with lower precedence get written first so that files with higher precedence can overwrite them. |
| 323 |
|
| 324 |
log.debug("Copying static assets.") |
| 325 |
files.copy_static_files(dirty=dirty, inclusion=inclusion) |
| 326 |
|
| 327 |
for template in config.theme.static_templates: |
| 328 |
_build_theme_template(template, env, files, config, nav) |
| 329 |
|
| 330 |
for template in config.extra_templates: |
| 331 |
_build_extra_template(template, files, config, nav) |
| 332 |
|
| 333 |
log.debug("Building markdown pages.") |
| 334 |
doc_files = files.documentation_pages(inclusion=inclusion) |
| 335 |
for file in doc_files: |
| 336 |
assert file.page is not None |
| 337 |
_build_page( |
| 338 |
file.page, config, doc_files, nav, env, dirty, excluded=file.inclusion.is_excluded() |
| 339 |
) |
| 340 |
|
| 341 |
log_level = config.validation.links.anchors |
| 342 |
for file in doc_files: |
| 343 |
assert file.page is not None |
| 344 |
file.page.validate_anchor_links(files=files, log_level=log_level) |
| 345 |
|
| 346 |
# Run `post_build` plugin events. |
| 347 |
config.plugins.on_post_build(config=config) |
| 348 |
|
| 349 |
if counts := warning_counter.get_counts(): |
| 350 |
msg = ', '.join(f'{v} {k.lower()}s' for k, v in counts) |
| 351 |
raise Abort(f'Aborted with {msg} in strict mode!') |
| 352 |
|
| 353 |
log.info(f'Documentation built in {time.monotonic() - start:.2f} seconds') |
| 354 |
|
| 355 |
except Exception as e: |
| 356 |
# Run `build_error` plugin events. |
| 357 |
config.plugins.on_build_error(error=e) |
| 358 |
if isinstance(e, BuildError): |
| 359 |
log.error(str(e)) |
| 360 |
raise Abort('Aborted with a BuildError!') |
| 361 |
raise |
| 362 |
|
| 363 |
finally: |
| 364 |
logger.removeHandler(warning_counter) |
| 365 |
|
| 366 |
|
| 367 |
def site_directory_contains_stale_files(site_directory: str) -> bool: |
| 368 |
"""Check if the site directory contains stale files from a previous build.""" |
| 369 |
return bool(os.path.exists(site_directory) and os.listdir(site_directory)) |