|
| 1 | +# SPDX-FileCopyrightText: 2025 Helmholtz-Zentrum Dresden - Rossendorf (HZDR) |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +# SPDX-FileContributor: David Pape |
| 4 | + |
| 5 | +from pathlib import Path |
| 6 | + |
| 7 | +from docutils import nodes |
| 8 | +from sphinx.application import Sphinx |
| 9 | +from sphinx.util import logging |
| 10 | +from sphinx.util.console import colorize |
| 11 | +from sphinx.util.docutils import SphinxDirective |
| 12 | +from sphinx.util.fileutil import copy_asset |
| 13 | +from sphinx.util.typing import ExtensionMetadata |
| 14 | + |
| 15 | +logger = logging.getLogger(__name__) |
| 16 | + |
| 17 | + |
| 18 | +def log_message(text: str, detail: str = None) -> None: |
| 19 | + message = colorize("bold", "[Copy Files]") + " " + text |
| 20 | + if detail is not None: |
| 21 | + message += " " + colorize("darkgreen", detail) |
| 22 | + logger.info(message) |
| 23 | + |
| 24 | + |
| 25 | +class CopyExampleFilesDirective(SphinxDirective): |
| 26 | + required_arguments = 1 |
| 27 | + |
| 28 | + def run(self) -> list[nodes.Node]: |
| 29 | + filename = Path(self.get_source_info()[0]) # currently processed file |
| 30 | + directory = filename.parent |
| 31 | + |
| 32 | + source_file_or_directory = (directory / self.arguments[0]).resolve() |
| 33 | + |
| 34 | + # output directory of the builder |
| 35 | + output_directory = Path(self.state.document.settings.env.app.outdir) |
| 36 | + |
| 37 | + # output directory of the currently processed file |
| 38 | + current_output_directory = ( |
| 39 | + output_directory / self.state.document.settings.env.docname |
| 40 | + ).parent |
| 41 | + |
| 42 | + log_message( |
| 43 | + "Copying files", |
| 44 | + f"from: {source_file_or_directory} to {current_output_directory}", |
| 45 | + ) |
| 46 | + copy_asset(source_file_or_directory, current_output_directory, force=True) |
| 47 | + |
| 48 | + note = nodes.note() |
| 49 | + text = nodes.paragraph(text="Files were automatically added to this directory.") |
| 50 | + note.append(text) |
| 51 | + return [note] |
| 52 | + |
| 53 | + |
| 54 | +def setup(app: Sphinx) -> ExtensionMetadata: |
| 55 | + app.add_directive("copy-files", CopyExampleFilesDirective) |
| 56 | + |
| 57 | + return { |
| 58 | + "version": "0.1", |
| 59 | + "parallel_read_safe": True, |
| 60 | + "parallel_write_safe": True, |
| 61 | + } |
0 commit comments