sphinx-exec-to-file 1.0.0__tar.gz

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.
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 BOUYER Gatien
4
+
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
@@ -0,0 +1,224 @@
1
+ Metadata-Version: 2.4
2
+ Name: sphinx-exec-to-file
3
+ Version: 1.0.0
4
+ Summary: Sphinx extension to include images and data files created by commands or code
5
+ Author-email: Gatien Bouyer <gatien.bouyer.dev+sphinx@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Source, https://github.com/GatienBouyer/sphinx-exec-to-file
8
+ Keywords: sphinx,sphinx-extension,generation
9
+ Classifier: Development Status :: 5 - Production/Stable
10
+ Classifier: Framework :: Sphinx
11
+ Classifier: Framework :: Sphinx :: Extension
12
+ Classifier: Topic :: Documentation :: Sphinx
13
+ Classifier: Topic :: Software Development :: Documentation
14
+ Requires-Python: >=3.11
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: sphinx
18
+ Provides-Extra: dev
19
+ Requires-Dist: mypy; extra == "dev"
20
+ Requires-Dist: types-docutils; extra == "dev"
21
+ Requires-Dist: isort; extra == "dev"
22
+ Requires-Dist: autopep8; extra == "dev"
23
+ Requires-Dist: pylint; extra == "dev"
24
+ Requires-Dist: pytest; extra == "dev"
25
+ Requires-Dist: coverage; extra == "dev"
26
+ Dynamic: license-file
27
+
28
+ # Sphinx extension exec-to-file
29
+
30
+ This Sphinx extension aims to generate images or data to be included in Sphinx documents,
31
+ such as CSV files generated by a script calling an API.
32
+
33
+ > [!TIP]
34
+ > We recommend the usage of specialized directives when they exists.
35
+ > For example, use the `.. plot::` directive - included in matplotlib - to create graphes.
36
+
37
+
38
+ ## Installation
39
+
40
+ We recommend the use of environment (a.k.a. "venv").
41
+ ```sh
42
+ pip install sphinx-exec-to-file
43
+ ```
44
+
45
+ Add the extension in your Sphinx configuration file `conf.py`:
46
+ ```python
47
+ extensions = [
48
+ "sphinxcontrib.exec_to_file",
49
+ ]
50
+ ```
51
+
52
+
53
+ ## Presentation
54
+
55
+ This extension introduces 2 directives: `exec-code` and `exec-file`.
56
+
57
+ The `exec-code` directive allows to run a shell command or a code snippet.
58
+ The language is specified as argument of the directive.
59
+ To run the code as a shell command the language must be `sh`, which is the default.
60
+
61
+ The `exec-file` directive allows to run a file.
62
+ The path is given as argument of the directive, relative to the Sphinx build directory.
63
+ The language is specified as option of the directive.
64
+ Use python to execute a python script file.
65
+
66
+ The command/code/file is executed in the Sphinx build directory,
67
+ i.e. where the 'conf.py' file is located.
68
+
69
+ The files listed in the capture options `capture-file`, `capture-stdout`, and `capture-stderr`
70
+ are replaced in the executed command/code/file, so they can be generated at the correct location.
71
+ E.g., for the capture of `assets/file.csv`, the replacement search for `<file.csv>` in the text,
72
+ and write `sphinx-build-dir/assets/file.csv` instead, with the actual sphinx-build-dir,
73
+ so other directives can use the file.
74
+
75
+ The intended usage for captured files is to be used with other Sphinx directives like
76
+ `csv-table`, `image`, `literalinclude`.
77
+
78
+
79
+ ## Usage example
80
+
81
+ ### Execute a command
82
+ ```rst
83
+ .. exec:code::
84
+ :capture-file:
85
+ assets/file.csv
86
+ assets/second file.csv
87
+ :hide-code:
88
+
89
+ prog.exe <file.csv> <second file.csv>
90
+ ```
91
+ The prog.exe program shall be accessible using the PATH environment variable,
92
+ or be in the Sphinx build directory, where the command is executed.
93
+
94
+ ### Execute a code snippet
95
+ ```rst
96
+ .. exec:code:: python
97
+ :capture-stdout: assets/file1.txt
98
+ :capture-stderr: assets/file2.txt
99
+
100
+ import sys
101
+ print("hello world")
102
+ print("hello errors", file=sys.stderr)
103
+ ```
104
+
105
+ ### Execute a file
106
+ ```rst
107
+ .. exec:file:: scripts/generate_image.py
108
+ :capture-file: assets/file.png
109
+ :language: python
110
+ ```
111
+
112
+ ### Show the generated table
113
+ ```rst
114
+ .. csv-table::
115
+ :file: assert/file.csv
116
+ ```
117
+
118
+ ### Show the generated text
119
+ ```rst
120
+ .. literalinclude:: assets/file1.txt
121
+ ```
122
+
123
+ ### Show the generated image
124
+ ```rst
125
+ .. image:: assets/file.png
126
+ ```
127
+
128
+ ### Show how it was generated
129
+ `exec:code` and `exec:file` inherit from
130
+ [code-block](https://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#directive-code-block)
131
+ and [literalinclude](https://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#directive-literalinclude).
132
+ You can display how the file was generated using their directive options.
133
+ If you don't want it in your output, use the option `:hide-code:`.
134
+
135
+
136
+ ## Extension configuration
137
+
138
+ You can configure the extension with the following option in your `conf.py`.
139
+ The configuration values shown are the default ones.
140
+
141
+ ### exec_code_runners
142
+ ```python
143
+ exec_code_runners = {
144
+ None: ["sh", "-c"], # the default language
145
+ "sh": ["sh", "-c"],
146
+ "python": [executable, "-c"],
147
+ }
148
+ ```
149
+
150
+ ### exec_file_runners
151
+ ```python
152
+ exec_file_runners = {
153
+ None: ["sh"], # the default language
154
+ "sh": ["sh"],
155
+ "python": [executable],
156
+ }
157
+ ```
158
+
159
+ ### exec_code_file_markers
160
+ ```python
161
+ exec_code_file_markers = "<>"
162
+ ```
163
+ To use other characters to identify the files to be captured,
164
+ instead of the default `<file.png>`.
165
+ E.g. "{}" would allow to use `{file.png}`.
166
+
167
+
168
+ ## Directive options
169
+
170
+ The `exec:code` and `exec-file` directives supports the same options.
171
+
172
+ They also inherits the options of the
173
+ [code-block](https://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#directive-code-block)
174
+ and [literalinclude](https://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#directive-literalinclude) directives.
175
+
176
+ ### capture-file
177
+ The capture-file identifies the list of files to replace in the code/command/file.
178
+
179
+ The option takes one file path per line.
180
+ They are replace in the executed text where the same file path is written
181
+ surrounded by the markers (as configured by exec_code_file_markers).
182
+
183
+ ### capture-stdout
184
+ Similar to the `capture-file` option, but capture the standard output of the executed text.
185
+
186
+ ### capture-stderr
187
+ Similar to the `capture-file` option, but capture the standard error output of the executed text.
188
+
189
+ It can have the same value as the `capture-stdout` option, to capture both outputs in the same file.
190
+ The apparition order of the outputs is preserved in the captured file.
191
+
192
+ ### ignore-exit
193
+ By default, the executed code shall return the exit-code status of 0.
194
+ This option disable this check.
195
+
196
+ ### timeout
197
+ By default, the executed code can run indefinitely.
198
+ This option set a timer on the execution of the directive.
199
+
200
+ ### hide-code
201
+ By default, the code/command/file is shown using Sphinx's `code-block` and `literalinclude` directives.
202
+ THis option disable this, so the directive shows nothing in the built documentation.
203
+
204
+
205
+ ## Development
206
+
207
+ Install necessary tools with `pip install -e .[dev]`.
208
+
209
+ Run tests with `pytest` or `coverage`. Run code analysis with `autopep8`, `isort`, `mypy` and `pylint`.
210
+ These tools are pre-configured, no options are required to run them,
211
+ you just have to give the path to analyse.
212
+
213
+ You can trigger the run of all these tools with `precommit`:
214
+
215
+ ```sh
216
+ pip install pre-commit && pre-commit install
217
+ ```
218
+
219
+ To build and distribute the package use:
220
+ ```sh
221
+ pip install build twine
222
+ python -m build
223
+ twine upload dist/*
224
+ ```
@@ -0,0 +1,197 @@
1
+ # Sphinx extension exec-to-file
2
+
3
+ This Sphinx extension aims to generate images or data to be included in Sphinx documents,
4
+ such as CSV files generated by a script calling an API.
5
+
6
+ > [!TIP]
7
+ > We recommend the usage of specialized directives when they exists.
8
+ > For example, use the `.. plot::` directive - included in matplotlib - to create graphes.
9
+
10
+
11
+ ## Installation
12
+
13
+ We recommend the use of environment (a.k.a. "venv").
14
+ ```sh
15
+ pip install sphinx-exec-to-file
16
+ ```
17
+
18
+ Add the extension in your Sphinx configuration file `conf.py`:
19
+ ```python
20
+ extensions = [
21
+ "sphinxcontrib.exec_to_file",
22
+ ]
23
+ ```
24
+
25
+
26
+ ## Presentation
27
+
28
+ This extension introduces 2 directives: `exec-code` and `exec-file`.
29
+
30
+ The `exec-code` directive allows to run a shell command or a code snippet.
31
+ The language is specified as argument of the directive.
32
+ To run the code as a shell command the language must be `sh`, which is the default.
33
+
34
+ The `exec-file` directive allows to run a file.
35
+ The path is given as argument of the directive, relative to the Sphinx build directory.
36
+ The language is specified as option of the directive.
37
+ Use python to execute a python script file.
38
+
39
+ The command/code/file is executed in the Sphinx build directory,
40
+ i.e. where the 'conf.py' file is located.
41
+
42
+ The files listed in the capture options `capture-file`, `capture-stdout`, and `capture-stderr`
43
+ are replaced in the executed command/code/file, so they can be generated at the correct location.
44
+ E.g., for the capture of `assets/file.csv`, the replacement search for `<file.csv>` in the text,
45
+ and write `sphinx-build-dir/assets/file.csv` instead, with the actual sphinx-build-dir,
46
+ so other directives can use the file.
47
+
48
+ The intended usage for captured files is to be used with other Sphinx directives like
49
+ `csv-table`, `image`, `literalinclude`.
50
+
51
+
52
+ ## Usage example
53
+
54
+ ### Execute a command
55
+ ```rst
56
+ .. exec:code::
57
+ :capture-file:
58
+ assets/file.csv
59
+ assets/second file.csv
60
+ :hide-code:
61
+
62
+ prog.exe <file.csv> <second file.csv>
63
+ ```
64
+ The prog.exe program shall be accessible using the PATH environment variable,
65
+ or be in the Sphinx build directory, where the command is executed.
66
+
67
+ ### Execute a code snippet
68
+ ```rst
69
+ .. exec:code:: python
70
+ :capture-stdout: assets/file1.txt
71
+ :capture-stderr: assets/file2.txt
72
+
73
+ import sys
74
+ print("hello world")
75
+ print("hello errors", file=sys.stderr)
76
+ ```
77
+
78
+ ### Execute a file
79
+ ```rst
80
+ .. exec:file:: scripts/generate_image.py
81
+ :capture-file: assets/file.png
82
+ :language: python
83
+ ```
84
+
85
+ ### Show the generated table
86
+ ```rst
87
+ .. csv-table::
88
+ :file: assert/file.csv
89
+ ```
90
+
91
+ ### Show the generated text
92
+ ```rst
93
+ .. literalinclude:: assets/file1.txt
94
+ ```
95
+
96
+ ### Show the generated image
97
+ ```rst
98
+ .. image:: assets/file.png
99
+ ```
100
+
101
+ ### Show how it was generated
102
+ `exec:code` and `exec:file` inherit from
103
+ [code-block](https://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#directive-code-block)
104
+ and [literalinclude](https://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#directive-literalinclude).
105
+ You can display how the file was generated using their directive options.
106
+ If you don't want it in your output, use the option `:hide-code:`.
107
+
108
+
109
+ ## Extension configuration
110
+
111
+ You can configure the extension with the following option in your `conf.py`.
112
+ The configuration values shown are the default ones.
113
+
114
+ ### exec_code_runners
115
+ ```python
116
+ exec_code_runners = {
117
+ None: ["sh", "-c"], # the default language
118
+ "sh": ["sh", "-c"],
119
+ "python": [executable, "-c"],
120
+ }
121
+ ```
122
+
123
+ ### exec_file_runners
124
+ ```python
125
+ exec_file_runners = {
126
+ None: ["sh"], # the default language
127
+ "sh": ["sh"],
128
+ "python": [executable],
129
+ }
130
+ ```
131
+
132
+ ### exec_code_file_markers
133
+ ```python
134
+ exec_code_file_markers = "<>"
135
+ ```
136
+ To use other characters to identify the files to be captured,
137
+ instead of the default `<file.png>`.
138
+ E.g. "{}" would allow to use `{file.png}`.
139
+
140
+
141
+ ## Directive options
142
+
143
+ The `exec:code` and `exec-file` directives supports the same options.
144
+
145
+ They also inherits the options of the
146
+ [code-block](https://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#directive-code-block)
147
+ and [literalinclude](https://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#directive-literalinclude) directives.
148
+
149
+ ### capture-file
150
+ The capture-file identifies the list of files to replace in the code/command/file.
151
+
152
+ The option takes one file path per line.
153
+ They are replace in the executed text where the same file path is written
154
+ surrounded by the markers (as configured by exec_code_file_markers).
155
+
156
+ ### capture-stdout
157
+ Similar to the `capture-file` option, but capture the standard output of the executed text.
158
+
159
+ ### capture-stderr
160
+ Similar to the `capture-file` option, but capture the standard error output of the executed text.
161
+
162
+ It can have the same value as the `capture-stdout` option, to capture both outputs in the same file.
163
+ The apparition order of the outputs is preserved in the captured file.
164
+
165
+ ### ignore-exit
166
+ By default, the executed code shall return the exit-code status of 0.
167
+ This option disable this check.
168
+
169
+ ### timeout
170
+ By default, the executed code can run indefinitely.
171
+ This option set a timer on the execution of the directive.
172
+
173
+ ### hide-code
174
+ By default, the code/command/file is shown using Sphinx's `code-block` and `literalinclude` directives.
175
+ THis option disable this, so the directive shows nothing in the built documentation.
176
+
177
+
178
+ ## Development
179
+
180
+ Install necessary tools with `pip install -e .[dev]`.
181
+
182
+ Run tests with `pytest` or `coverage`. Run code analysis with `autopep8`, `isort`, `mypy` and `pylint`.
183
+ These tools are pre-configured, no options are required to run them,
184
+ you just have to give the path to analyse.
185
+
186
+ You can trigger the run of all these tools with `precommit`:
187
+
188
+ ```sh
189
+ pip install pre-commit && pre-commit install
190
+ ```
191
+
192
+ To build and distribute the package use:
193
+ ```sh
194
+ pip install build twine
195
+ python -m build
196
+ twine upload dist/*
197
+ ```
@@ -0,0 +1,83 @@
1
+ [project]
2
+ name = "sphinx-exec-to-file"
3
+ version = "1.0.0"
4
+ description = "Sphinx extension to include images and data files created by commands or code"
5
+ keywords = ["sphinx", "sphinx-extension", "generation"]
6
+ authors = [
7
+ {name="Gatien Bouyer", email="gatien.bouyer.dev+sphinx@gmail.com"},
8
+ ]
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.11"
13
+ dependencies = [
14
+ "sphinx",
15
+ ]
16
+ classifiers = [
17
+ "Development Status :: 5 - Production/Stable",
18
+ "Framework :: Sphinx",
19
+ "Framework :: Sphinx :: Extension",
20
+ "Topic :: Documentation :: Sphinx",
21
+ "Topic :: Software Development :: Documentation",
22
+ ]
23
+
24
+ [project.urls]
25
+ "Source" = "https://github.com/GatienBouyer/sphinx-exec-to-file"
26
+
27
+ [project.optional-dependencies]
28
+ dev = [
29
+ "mypy",
30
+ "types-docutils",
31
+ "isort",
32
+ "autopep8",
33
+ "pylint",
34
+ "pytest",
35
+ "coverage",
36
+ ]
37
+
38
+ [build-system]
39
+ requires = ["setuptools"]
40
+ build-backend = "setuptools.build_meta"
41
+
42
+ [tool.isort]
43
+ force_single_line = true
44
+ skip_gitignore = true
45
+ quiet = true # to remove warning about skipped files
46
+
47
+ [tool.autopep8]
48
+ max_line_length = 100
49
+ recursive = true
50
+ exclude = ".*" # exclude hidden files
51
+
52
+ [tool.mypy]
53
+ strict = true
54
+ packages = ["sphinxcontrib.exec_to_file", "test"]
55
+
56
+ [tool.pylint]
57
+ recursive = true
58
+ ignore-patterns = ["^\\.", "conf.py"] # exclude hidden files
59
+ load-plugins=[
60
+ "pylint.extensions.bad_builtin",
61
+ ]
62
+ enable = ["useless-suppression"]
63
+ disable = [
64
+ "too-many-arguments", # too strict
65
+ "too-many-positional-arguments", # too strict
66
+ "too-few-public-methods", # too strict to have data classes
67
+ ]
68
+ bad-functions = ["print"]
69
+
70
+ [tool.pytest.ini_options]
71
+ addopts = "--show-capture=stdout" # hide logs for easier debug of sphinx tests
72
+ testpaths = ["test"]
73
+
74
+ [tool.coverage.run]
75
+ branch = true
76
+ command_line = "-m pytest"
77
+ source_pkgs = ["sphinxcontrib.exec_to_file", "test"]
78
+
79
+ [tool.coverage.report]
80
+ exclude_also = [
81
+ "raise NotImplementedError",
82
+ ]
83
+ fail_under = 100
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,21 @@
1
+ """
2
+ This Sphinx extension aims to include generated images or data to be included in Sphinx documents,
3
+ such as CSV files generated by a script calling an API.
4
+ """
5
+
6
+ from importlib.metadata import version
7
+
8
+ from sphinx.application import Sphinx
9
+ from sphinx.util.typing import ExtensionMetadata
10
+
11
+ from sphinxcontrib.exec_to_file.domain import ExecToFileDomain
12
+
13
+
14
+ def setup(app: Sphinx) -> ExtensionMetadata:
15
+ """Register the domain of the extension."""
16
+ ExecToFileDomain.register(app)
17
+ return {
18
+ "version": version("sphinx-exec-to-file"),
19
+ "parallel_read_safe": True,
20
+ "parallel_write_safe": True,
21
+ }
@@ -0,0 +1,160 @@
1
+ """Define the common directive options and associated code to be used in 'exec' directives."""
2
+ import subprocess
3
+ from abc import ABC
4
+ from collections.abc import Iterable
5
+ from collections.abc import Mapping
6
+ from collections.abc import Sequence
7
+ from pathlib import Path
8
+ from typing import IO
9
+ from typing import NamedTuple
10
+ from typing import TypeAlias
11
+
12
+ from docutils.nodes import Node
13
+ from docutils.parsers.rst import directives
14
+ from sphinx.util.docutils import SphinxDirective
15
+ from sphinx.util.logging import getLogger
16
+
17
+ logger = getLogger("sphinx.exec-to-file")
18
+
19
+
20
+ def option_positive_float(argument: str) -> float:
21
+ """
22
+ Converts the argument into a float. Raises ValueError for negative,
23
+ zero, or non-integer values. (Directive option conversion function.)
24
+ """
25
+ value = float(argument)
26
+ if value <= 0: # pragma: no cover
27
+ raise ValueError('negative or zero value; must be positive')
28
+ return value
29
+
30
+
31
+ StdIoFd: TypeAlias = IO[str] | IO[bytes] | int | None
32
+ """Type of what subprocess.run accepts for stdout and stderr."""
33
+
34
+
35
+ class Capture(NamedTuple):
36
+ """Files to be captured by the directive."""
37
+ paths_to_create: set[Path]
38
+ paths_to_replace: set[Path]
39
+ stdout_fd: StdIoFd
40
+ stderr_fd: StdIoFd
41
+
42
+
43
+ class AbstractExec(SphinxDirective, ABC):
44
+ """
45
+ Parent class of other 'exec-*' directives.
46
+ Store and handle the common directive options.
47
+ """
48
+ option_spec = {
49
+ "capture-stdout": directives.unchanged_required,
50
+ "capture-stderr": directives.unchanged_required,
51
+ "capture-file": directives.unchanged_required,
52
+ "ignore-exit": directives.flag,
53
+ "timeout": option_positive_float,
54
+ "hide-code": directives.flag,
55
+ }
56
+
57
+ @property
58
+ def cwd(self) -> Path:
59
+ """The directory from which the paths are constructed,
60
+ and from where the command is run."""
61
+ return Path(self.env.srcdir)
62
+
63
+ def get_captures(self) -> Capture:
64
+ """Parse the capture-file, capture-stdout, capture-sterr directive options."""
65
+ self.env.note_reread() # tell sphinx to re-run the directive each time
66
+ cwd = self.cwd
67
+ paths_to_create: set[Path] = set()
68
+ for file in self.options.get("capture-file", "").split("\n"):
69
+ if file.strip() == "":
70
+ continue
71
+ path = cwd / file
72
+ if path in paths_to_create:
73
+ raise self.warning(f"duplicate file '{file}' in '{self.name}' captured twice")
74
+ paths_to_create.add(path)
75
+
76
+ paths_to_replace = paths_to_create.copy()
77
+
78
+ # pylint: disable=consider-using-with # subprocess closes them by default, see close_fd
79
+ if stdout := self.options.get("capture-stdout", None):
80
+ if (stdout_path := cwd / stdout) in paths_to_create:
81
+ raise self.warning(f"duplicate file '{stdout}' in '{self.name}' captured twice")
82
+ paths_to_create.add(stdout_path)
83
+ stdout_path.parent.mkdir(parents=True, exist_ok=True)
84
+ stdout_fd = open(stdout_path, "wb")
85
+ else:
86
+ stdout_fd = None
87
+ if stderr := self.options.get("capture-stderr", None):
88
+ if stderr != stdout:
89
+ if (stderr_path := cwd / stderr) in paths_to_create:
90
+ raise self.warning(f"duplicate file '{stderr}' in '{self.name}' captured twice")
91
+ paths_to_create.add(stderr_path)
92
+ stderr_path.parent.mkdir(parents=True, exist_ok=True)
93
+ stderr_fd: StdIoFd = open(stderr_path, "wb")
94
+ else:
95
+ stderr_fd = subprocess.STDOUT
96
+ else:
97
+ stderr_fd = None
98
+
99
+ return Capture(
100
+ paths_to_create=paths_to_create,
101
+ paths_to_replace=paths_to_replace,
102
+ stdout_fd=stdout_fd,
103
+ stderr_fd=stderr_fd,
104
+ )
105
+
106
+ def make_replacements(self, paths: set[Path], srcf: Iterable[str]) -> Iterable[str]:
107
+ """Copy and replace the marked paths by the actual file paths
108
+ in the source file to the temporary file."""
109
+ marker_start, marker_end = self.config.exec_code_file_markers
110
+ remaining = paths.copy()
111
+ for line in srcf:
112
+ for path in paths:
113
+ path_as_arg = marker_start + path.name + marker_end
114
+ if path_as_arg in line:
115
+ remaining.discard(path)
116
+ line = line.replace(path_as_arg, path.as_posix())
117
+ yield line
118
+
119
+ for path in remaining:
120
+ raise self.warning(f"'{self.name}' does not use '{path.name}'")
121
+
122
+ def build_command(self, exes: Mapping[str | None, Sequence[str]],
123
+ language: str | None, args: Iterable[str]) -> list[str]:
124
+ """Build the command to be executed using the mapping option."""
125
+ if language in exes:
126
+ runner = exes[language]
127
+ else:
128
+ raise self.error(f"No executable defined for language '{language}'")
129
+
130
+ return [*runner, *args]
131
+
132
+ def exec(self, args: list[str], captures: Capture) -> Sequence[Node]:
133
+ """Execute the command composed of the given args with the specifiede executable.
134
+ Capture the stdout/stderr and check that the files are created.
135
+ Return the directive contained nodes."""
136
+ logged_command = " ".join(args)
137
+ logger.info(f"Command launched: {logged_command}")
138
+ timeout = self.options.get("timeout")
139
+
140
+ try:
141
+ res = subprocess.run(
142
+ args, cwd=self.cwd,
143
+ stdout=captures.stdout_fd, stderr=captures.stderr_fd,
144
+ check=False, timeout=timeout,
145
+ )
146
+ except subprocess.TimeoutExpired:
147
+ raise self.severe(f"Timeout expired in the '{self.name}' directive "
148
+ f"({timeout}s) for the command:\n{logged_command}\n") from None
149
+
150
+ if "ignore-exit" not in self.options and res.returncode != 0:
151
+ raise self.warning(f"Command executed by the '{self.name}' directive has failed:\n"
152
+ f"{logged_command}\n")
153
+ for path in captures.paths_to_create:
154
+ if not path.exists():
155
+ raise self.warning(f"Command executed but didn't create the file {path.name}:\n"
156
+ f"{logged_command}\n")
157
+
158
+ if "hide-code" not in self.options:
159
+ return super().run()
160
+ return []
@@ -0,0 +1,41 @@
1
+ """Define the `.. exec:code::` directive."""
2
+ from docutils.nodes import Node
3
+ from sphinx.directives.code import CodeBlock
4
+ from sphinx.util.logging import getLogger
5
+
6
+ from sphinxcontrib.exec_to_file.directive_abstract_exec import AbstractExec
7
+
8
+ logger = getLogger("sphinx.exec-to-file")
9
+
10
+
11
+ class ExecCodeDirective(AbstractExec, CodeBlock):
12
+ """Define the directive that execute code."""
13
+ name = "code"
14
+
15
+ has_content = True
16
+ required_arguments = 0
17
+ optional_arguments = 1 # the language
18
+ option_spec = {
19
+ **CodeBlock.option_spec,
20
+ **AbstractExec.option_spec,
21
+ }
22
+
23
+ def run(self) -> list[Node]:
24
+ """Implementation of the directive.
25
+
26
+ - Take the command from the content.
27
+ - Parse the capture options
28
+ - Replace the files that needs to be captured
29
+ - Build the command
30
+ - Run the command and check the output
31
+ """
32
+ self.assert_has_content()
33
+ script_lines = self.content
34
+ captures = self.get_captures()
35
+ lines = self.make_replacements(captures.paths_to_replace, script_lines)
36
+ args = self.build_command(
37
+ self.config.exec_code_runners,
38
+ self.arguments[0] if self.arguments else None,
39
+ ["\n".join(lines)],
40
+ )
41
+ return list(self.exec(args, captures))
@@ -0,0 +1,52 @@
1
+ """Define the `.. exec:file::` directive."""
2
+ import tempfile
3
+
4
+ from docutils.nodes import Node
5
+ from sphinx.directives.code import LiteralInclude
6
+ from sphinx.util.logging import getLogger
7
+
8
+ from sphinxcontrib.exec_to_file.directive_abstract_exec import AbstractExec
9
+
10
+ logger = getLogger("sphinx.exec-to-file")
11
+
12
+
13
+ class ExecFileDirective(AbstractExec, LiteralInclude):
14
+ """Define the directive that execute code."""
15
+ name = "file"
16
+
17
+ has_content = False
18
+ required_arguments = 1 # the file
19
+ optional_arguments = 0
20
+ option_spec = {
21
+ **LiteralInclude.option_spec,
22
+ **AbstractExec.option_spec,
23
+ }
24
+
25
+ def run(self) -> list[Node]:
26
+ """Implementation of the directive.
27
+
28
+ - Take the command from the content.
29
+ - Parse the capture options
30
+ - Replace the files that needs to be captured
31
+ - Build the command
32
+ - Run the command and check the output
33
+ """
34
+ file_to_exec = self.cwd / self.arguments[0]
35
+ if not file_to_exec.exists():
36
+ raise self.severe(f"Failed to found the file to execute: {file_to_exec}")
37
+
38
+ captures = self.get_captures()
39
+ with (
40
+ open(file_to_exec, "r", encoding="utf-8") as srcf,
41
+ tempfile.NamedTemporaryFile("w", encoding="utf-8") as tmpf,
42
+ ):
43
+ for line in self.make_replacements(captures.paths_to_replace, srcf):
44
+ tmpf.write(line)
45
+ tmpf.flush()
46
+
47
+ args = self.build_command(
48
+ self.config.exec_file_runners,
49
+ self.options.get("language"),
50
+ [tmpf.name],
51
+ )
52
+ return list(self.exec(args, captures))
@@ -0,0 +1,72 @@
1
+ """
2
+ Define the Sphinx domain that regroup all the features of the exec-to-file extension.
3
+ """
4
+ from collections.abc import Iterable
5
+ from sys import executable
6
+ from typing import Any
7
+
8
+ from docutils.nodes import Element
9
+ from docutils.nodes import reference
10
+ from sphinx.addnodes import pending_xref
11
+ from sphinx.application import Sphinx
12
+ from sphinx.builders import Builder
13
+ from sphinx.domains import Domain
14
+ from sphinx.environment import BuildEnvironment
15
+ from sphinx.util.logging import getLogger
16
+
17
+ from sphinxcontrib.exec_to_file.directive_code import ExecCodeDirective
18
+ from sphinxcontrib.exec_to_file.directive_file import ExecFileDirective
19
+
20
+ logger = getLogger("sphinx.exec-to-file")
21
+
22
+
23
+ class ExecToFileDomain(Domain):
24
+ """Domain that regroup all the features of the exec-to-file extension."""
25
+ name = "exec"
26
+ """Name of the domain, i.e. the directive and role prefix."""
27
+ data_version = 0
28
+ """Version of the format of the data attribute cached by Sphinx."""
29
+
30
+ @classmethod
31
+ def register(cls, app: Sphinx) -> None:
32
+ """Register the domain and its dependencies in the Sphinx registry."""
33
+ app.add_domain(cls)
34
+ app.add_directive_to_domain(cls.name, ExecCodeDirective.name, ExecCodeDirective)
35
+ app.add_directive_to_domain(cls.name, ExecFileDirective.name, ExecFileDirective)
36
+ app.add_config_value(
37
+ "exec_code_file_markers",
38
+ default="<>",
39
+ rebuild="env",
40
+ types=[tuple, str],
41
+ )
42
+ app.add_config_value(
43
+ "exec_code_runners",
44
+ default={
45
+ None: ["sh", "-c"], # the default language
46
+ "sh": ["sh", "-c"],
47
+ "python": [executable, "-c"],
48
+ },
49
+ rebuild="env",
50
+ types=[dict],
51
+ )
52
+ app.add_config_value(
53
+ "exec_file_runners",
54
+ default={
55
+ None: ["sh"], # the default language
56
+ "sh": ["sh"],
57
+ "python": [executable],
58
+ },
59
+ rebuild="env",
60
+ types=[dict],
61
+ )
62
+
63
+ def merge_domaindata(self, docnames: Iterable[str], otherdata: dict[str, Any]) -> None:
64
+ """Merge domain data of multiple document coming from different subprocesses.
65
+ Used in Sphinx parallel builds."""
66
+
67
+ def resolve_any_xref(
68
+ self, env: BuildEnvironment, fromdocname: str, builder: Builder,
69
+ target: str, node: pending_xref, contnode: Element
70
+ ) -> list[tuple[str, reference]]:
71
+ """Resolve the pending_xref *node* with the given *target* from the :any: role"""
72
+ raise NotImplementedError