Skip to content

serve

Class info

🛈 DocStrings

_serve

_serve(
    config_file: str | None | YAMLInput = None,
    livereload: bool = True,
    build_type: Literal["clean", "dirty"] | None = None,
    watch_theme: bool = False,
    watch: list[str] | None = None,
    **kwargs: Any
) -> None

Start the MkDocs development server.

By default it will serve the documentation on http://localhost:8000/ and it will rebuild the documentation and refresh the page automatically whenever a file is edited.

Parameters:

Name Type Description Default
config_file str | None | YAMLInput

Config file to use

None
livereload bool

Reload on file changes

True
build_type Literal['clean', 'dirty'] | None

Type of the build

None
watch_theme bool

Whether to watch the theme for file changes

False
watch list[str] | None

Additional files / folders to watch

None
kwargs Any

Additional config values. Overrides values from config_file

{}
Source code in mkdocs_mknodes/commands/serve.py
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
def _serve(
    config_file: str | None | yamling.YAMLInput = None,
    livereload: bool = True,
    build_type: Literal["clean", "dirty"] | None = None,
    watch_theme: bool = False,
    watch: list[str] | None = None,
    **kwargs: Any,
) -> None:
    """Start the MkDocs development server.

    By default it will serve the documentation on http://localhost:8000/ and
    it will rebuild the documentation and refresh the page automatically
    whenever a file is edited.

    Args:
        config_file: Config file to use
        livereload: Reload on file changes
        build_type: Type of the build
        watch_theme: Whether to watch the theme for file changes
        watch: Additional files / folders to watch
        kwargs: Additional config values. Overrides values from config_file
    """
    watch = watch or []
    site_dir = pathlib.Path(tempfile.mkdtemp(prefix="mkdocs_"))

    def mount_path(config: mknodesconfig.MkNodesConfig) -> str:
        return urlsplit(config.site_url or "/").path

    def get_config() -> mknodesconfig.MkNodesConfig:
        config = mknodesconfig.MkNodesConfig.from_yaml(
            config_file=config_file,  # type: ignore[arg-type]
            site_dir=str(site_dir),
            **kwargs,
        )
        config.watch.extend(watch)
        config.site_url = f"http://{config.dev_addr}{mount_path(config)}"
        return config

    is_clean = build_type == "clean"
    is_dirty = build_type == "dirty"
    config = get_config()
    config.plugins.on_startup(command=("build" if is_clean else "serve"), dirty=is_dirty)

    host, port = config.dev_addr
    suffix = mount_path(config).lstrip("/").rstrip("/")
    url = None if is_clean else f"http://{host}:{port}/{suffix}/"

    def builder(config: mknodesconfig.MkNodesConfig | None = None):
        logger.info("Building documentation...")
        if config is None:
            config = get_config()
        build_page._build(config, live_server_url=url, dirty=is_dirty)

    server = liveserver.LiveServer(
        builder=builder,
        host=host,
        port=port,
        root=str(site_dir),
        mount_path=mount_path(config),
    )

    with catch_exceptions(config):
        # Perform the initial build
        builder(config)

        if livereload:
            # Watch the documentation files, the config file and the theme files.
            server.watch(config.docs_dir)
            if config.config_file_path:
                server.watch(config.config_file_path)

            if watch_theme:
                for d in config.theme.dirs:
                    server.watch(d)

            # Run `serve` plugin events.
            server = config.plugins.on_serve(server, config=config, builder=builder)  # type: ignore[arg-type]

            for item in config.watch:
                server.watch(item)

        try:
            server.serve()
        except KeyboardInterrupt:
            logger.info("Shutting down...")
        finally:
            server.shutdown()

catch_exceptions

catch_exceptions(config: MkNodesConfig)

Context manager used to clean up in case of build error.

Parameters:

Name Type Description Default
config MkNodesConfig

Build config.

required
Source code in mkdocs_mknodes/commands/serve.py
51
52
53
54
55
56
57
58
59
60
61
62
63
@contextlib.contextmanager
def catch_exceptions(config: mknodesconfig.MkNodesConfig):
    """Context manager used to clean up in case of build error.

    Args:
        config: Build config.
    """
    try:
        yield
    finally:
        config.plugins.on_shutdown()
        if pathlib.Path(config.site_dir).is_dir():
            shutil.rmtree(config.site_dir)

serve

serve(
    config_path: str | PathLike[str] = CFG_DEFAULT,
    theme: str | None = None,
    **kwargs: Any
)

Serve a MkNodes-based website.

Parameters:

Name Type Description Default
config_path str | PathLike[str]

The path to the config file to use

CFG_DEFAULT
repo_path

Path to the repository a page should be built for

required
build_fn

Callable to use for creating the webpage

required
clone_depth

If repository is remote, the amount of commits to fetch

required
theme str | None

Theme to use

None
kwargs Any

Optional config values (overrides value from config)

{}
Source code in mkdocs_mknodes/commands/serve.py
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
def serve(
    config_path: str | os.PathLike[str] = paths.CFG_DEFAULT,
    theme: str | None = None,
    **kwargs: Any,
):
    """Serve a MkNodes-based website.

    Args:
        config_path: The path to the config file to use
        repo_path: Path to the repository a page should be built for
        build_fn: Callable to use for creating the webpage
        clone_depth: If repository is remote, the amount of commits to fetch
        theme: Theme to use
        kwargs: Optional config values (overrides value from config)
    """
    if theme and theme != "material":
        kwargs["theme"] = theme
    text = upath.UPath(config_path).read_text()
    stream = io.StringIO(text)
    stream.name = str(config_path)
    _serve(config_file=stream, livereload=False, **kwargs)  # type: ignore[arg-type]