ExtraFilesPlugin

Bases: BasePlugin[PluginConfig]

An mkdocs plugin.

This plugin defines the following event hooks:

  • on_config
  • on_files
  • on_serve

Check the Developing Plugins page of mkdocs for more information about its plugin system.

Source code in mkdocs_extrafiles/plugin.py
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
class ExtraFilesPlugin(BasePlugin[PluginConfig]):
    """
    An `mkdocs` plugin.

    This plugin defines the following event hooks:

    - `on_config`
    - `on_files`
    - `on_serve`

    Check the [Developing Plugins](https://www.mkdocs.org/user-guide/plugins/#developing-plugins) page of `mkdocs` for more information about its plugin system.
    """

    def on_config(self, config: MkDocsConfig) -> MkDocsConfig | None:
        """
        Instantiate our Markdown extension.

        Hook for the [`on_config` event](https://www.mkdocs.org/user-guide/plugins/#on_config).
        """
        if not self.plugin_enabled:
            logger.debug("extrafiles: plugin disabled, skipping.")
            return config

        config_path = getattr(config, "config_file_path", None)
        if config_path:
            self.config_dir = Path(config_path).resolve().parent
        else:
            self.config_dir = Path.cwd()

        logger.debug(
            f"extrafiles: docs_dir={Path(config['docs_dir']).resolve()} config_dir={self.config_dir}"
        )

        return config

    @property
    def plugin_enabled(self) -> bool:
        """
        Tell if the plugin is enabled or not.

        :return: Whether the plugin is enabled.
        :rtype: bool
        """
        return self.config.enabled

    def _glob_base_dir(self, pattern: str) -> Path:
        """
        Determine the base directory for a glob so relative paths are preserved.

        The base is derived from the leading non-glob path segments. For relative patterns it is anchored to the plugin's config directory. For absolute patterns the resolved absolute segments are used directly.
        """
        path_obj = Path(pattern)
        base_parts: list[str] = []
        for part in path_obj.parts:
            if any(ch in part for ch in ("*", "?", "[")):
                break
            base_parts.append(part)

        if path_obj.is_absolute():
            if base_parts:
                base_path = Path(*base_parts)
            else:
                base_path = Path(path_obj.anchor or path_obj.root or "/")
            return base_path.resolve()

        base_path = self.config_dir.joinpath(*base_parts)
        return base_path.resolve()

    def _assert_dest_relative(self, dest: str) -> None:
        if Path(dest).is_absolute():
            raise ValueError(f"extrafiles: dest must be relative, got {dest!r}")

    def _expand_item_file(self, src: str, dest: str) -> Iterator[tuple[Path, str]]:
        config_dir = self.config_dir
        p = Path(src)
        s = (config_dir / p).resolve() if not p.is_absolute() else p.resolve()
        dest_uri = PurePosixPath(dest.replace("\\", "/")).as_posix()
        yield s, dest_uri

    def _expand_item_glob(self, src: str, dest: str) -> Iterator[tuple[Path, str]]:
        if not dest.endswith(("/", "\\")):
            raise ValueError(
                f"When using glob in src='{src}', dest must be a directory (end with '/')."
            )

        config_dir = self.config_dir
        pattern_path = Path(src)
        pattern = (
            str(pattern_path)
            if pattern_path.is_absolute()
            else str((config_dir / pattern_path).resolve())
        )

        dest_root = PurePosixPath(dest.rstrip("/\\"))
        base_dir = self._glob_base_dir(src)

        for match in glob(pattern, recursive=True):
            s = Path(match).resolve()
            if not s.is_file():
                continue
            try:
                rel_path = s.relative_to(base_dir)
            except ValueError:
                rel_path = Path(s.name)
            if rel_path == Path("."):
                rel_path = Path(s.name)
            relative_posix = PurePosixPath(*rel_path.parts)
            yield s, (dest_root / relative_posix).as_posix()

    def _expand_items(self):
        """
        Yields (src_path, dest_uri) pairs. Supports:
        - single file -> file
        - glob -> directory (dest must end with '/')
        """
        if not self.plugin_enabled:
            logger.debug("extrafiles: plugin disabled, skipping item expansion.")
            return

        for item in self.config["files"]:
            src = item["src"]
            dest = item["dest"]
            self._assert_dest_relative(dest)
            if any(ch in src for ch in _GLOB_CHARS):
                yield from self._expand_item_glob(src, dest)
            else:
                yield from self._expand_item_file(src, dest)

    def _iter_watch_paths(self) -> set[Path]:
        """
        Collect paths to monitor for changes while serving with auto-resolve, so that newly added sources are watched witout requiring a restart.
        """
        if not self.plugin_enabled:
            return set()

        watch_paths: set[Path] = set()
        for item in self.config["files"]:
            src = item["src"]

            p = Path(src)
            if any(ch in src for ch in _GLOB_CHARS):
                watch_paths.add(self._glob_base_dir(src))
            else:
                if not p.is_absolute():
                    p = self.config_dir / p
                watch_paths.add(p.resolve())

        return watch_paths

    @staticmethod
    def _nearest_existing_path(path: Path) -> Path | None:
        """
        Return the path if it exists, otherwise return the nearest existing parent.

        This ensures directories are watched even if the given path does not yet exist.
        """
        for p in (path, *path.parents):
            if p.exists():
                return p.resolve()
        return None

    def on_files(self, files: Files, *, config: MkDocsConfig) -> Files:
        if not self.plugin_enabled:
            logger.debug("extrafiles: plugin disabled, skipping file staging.")
            return files

        staged = 0
        for src, dest_uri in self._expand_items():
            if not src.exists():
                raise FileNotFoundError(f"extrafiles: source not found: {src}")

            existing = files.get_file_from_path(dest_uri)
            if existing is not None:
                files.remove(existing)

            generated = File.generated(config, dest_uri, abs_src_path=str(src))
            files.append(generated)
            staged += 1

        logger.debug(
            "extrafiles: staged %s file(s) for build into %s",
            staged,
            config.site_dir,
        )
        return files

    def on_serve(
        self,
        server: LiveReloadServer,
        /,
        *,
        config: MkDocsConfig,
        builder: Callable[..., Any],
    ) -> LiveReloadServer | None:
        """Make MkDocs monitor the source files when serving auto-reload."""
        if not self.plugin_enabled:
            logger.debug(
                "extrafiles: plugin disabled, skipping live reload registration."
            )
            return server

        watched: set[Path] = set()

        def _watch_path(path: Path | None) -> None:
            if path is None or path in watched:
                return
            try:
                server.watch(str(path))
                watched.add(path)
            except Exception:
                logger.exception("extrafiles: failed to watch %s", path)

        # Register the nearest existing paths from configured watch paths
        for p in self._iter_watch_paths():
            _watch_path(self._nearest_existing_path(p))

        # Register expanded item sources, guarding expansion errors
        try:
            for src, _ in self._expand_items():
                if src.exists():
                    _watch_path(src.resolve())
        except Exception:
            logger.exception("extrafiles: failed while expanding items for watch")

        return server

plugin_enabled property

Tell if the plugin is enabled or not.

Returns:
  • bool

    Whether the plugin is enabled.

on_config(config)

Instantiate our Markdown extension.

Hook for the on_config event.

Source code in mkdocs_extrafiles/plugin.py
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
def on_config(self, config: MkDocsConfig) -> MkDocsConfig | None:
    """
    Instantiate our Markdown extension.

    Hook for the [`on_config` event](https://www.mkdocs.org/user-guide/plugins/#on_config).
    """
    if not self.plugin_enabled:
        logger.debug("extrafiles: plugin disabled, skipping.")
        return config

    config_path = getattr(config, "config_file_path", None)
    if config_path:
        self.config_dir = Path(config_path).resolve().parent
    else:
        self.config_dir = Path.cwd()

    logger.debug(
        f"extrafiles: docs_dir={Path(config['docs_dir']).resolve()} config_dir={self.config_dir}"
    )

    return config

on_serve(server, /, *, config, builder)

Make MkDocs monitor the source files when serving auto-reload.

Source code in mkdocs_extrafiles/plugin.py
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
def on_serve(
    self,
    server: LiveReloadServer,
    /,
    *,
    config: MkDocsConfig,
    builder: Callable[..., Any],
) -> LiveReloadServer | None:
    """Make MkDocs monitor the source files when serving auto-reload."""
    if not self.plugin_enabled:
        logger.debug(
            "extrafiles: plugin disabled, skipping live reload registration."
        )
        return server

    watched: set[Path] = set()

    def _watch_path(path: Path | None) -> None:
        if path is None or path in watched:
            return
        try:
            server.watch(str(path))
            watched.add(path)
        except Exception:
            logger.exception("extrafiles: failed to watch %s", path)

    # Register the nearest existing paths from configured watch paths
    for p in self._iter_watch_paths():
        _watch_path(self._nearest_existing_path(p))

    # Register expanded item sources, guarding expansion errors
    try:
        for src, _ in self._expand_items():
            if src.exists():
                _watch_path(src.resolve())
    except Exception:
        logger.exception("extrafiles: failed while expanding items for watch")

    return server

PluginConfig

Bases: Config

The configuration options of mkdocs_extrafiles, written in mkdocs.yml

Provide a list of source file paths relative to the MkDocs config directory and the destination they will resolve against (relative to the docs directory).

plugins:
  - extrafiles:
      files:
        - src: README.md              # file
          dest: external/README.md
        - src: LICENSE                # file -> rename/relocate
          dest: external/LICENSE.txt
        - src: assets/**              # glob (copies all matches)
          dest: external/assets/      # must end with '/' to indicate a directory
Source code in mkdocs_extrafiles/plugin.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class PluginConfig(Config):
    """
    The configuration options of `mkdocs_extrafiles`, written in `mkdocs.yml`

    Provide a list of source file paths relative to the MkDocs config directory and the destination they will resolve against (relative to the docs directory).

    ```yaml
    plugins:
      - extrafiles:
          files:
            - src: README.md              # file
              dest: external/README.md
            - src: LICENSE                # file -> rename/relocate
              dest: external/LICENSE.txt
            - src: assets/**              # glob (copies all matches)
              dest: external/assets/      # must end with '/' to indicate a directory
    ```
    """

    files = opt.Type(list, default=[])
    enabled = opt.Type(bool, default=True)