sphinx-exec-to-file 1.0.0__py3-none-any.whl
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.
- sphinx_exec_to_file-1.0.0.dist-info/METADATA +224 -0
- sphinx_exec_to_file-1.0.0.dist-info/RECORD +11 -0
- sphinx_exec_to_file-1.0.0.dist-info/WHEEL +5 -0
- sphinx_exec_to_file-1.0.0.dist-info/licenses/LICENSE +22 -0
- sphinx_exec_to_file-1.0.0.dist-info/top_level.txt +1 -0
- sphinxcontrib/exec_to_file/__init__.py +21 -0
- sphinxcontrib/exec_to_file/directive_abstract_exec.py +160 -0
- sphinxcontrib/exec_to_file/directive_code.py +41 -0
- sphinxcontrib/exec_to_file/directive_file.py +52 -0
- sphinxcontrib/exec_to_file/domain.py +72 -0
- sphinxcontrib/exec_to_file/py.typed +0 -0
|
@@ -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,11 @@
|
|
|
1
|
+
sphinx_exec_to_file-1.0.0.dist-info/licenses/LICENSE,sha256=SBbGmNbN9X9KwtYA26OIJVTVcv4DQ3V_vzt4cLbs4OQ,1093
|
|
2
|
+
sphinxcontrib/exec_to_file/__init__.py,sha256=xTy3T_TAnMseJ8liuzkZWuBbh34eWe17VwcmYgi-mKE,628
|
|
3
|
+
sphinxcontrib/exec_to_file/directive_abstract_exec.py,sha256=DfVNBKZhSqKBe4m-o4SoiAPLiKIZ3iJXNzFXTH6LHuU,6381
|
|
4
|
+
sphinxcontrib/exec_to_file/directive_code.py,sha256=8-L-Kecs567m1O-fszRhEvbPztQYP3nSKQQ1NRL2m0A,1309
|
|
5
|
+
sphinxcontrib/exec_to_file/directive_file.py,sha256=WAkdz4iHca5AocVYaE13YEp-O88LX0sWaoMXKagT6L4,1666
|
|
6
|
+
sphinxcontrib/exec_to_file/domain.py,sha256=VqekmH9_03vwYrw86r29AyrteRooVAe0hPUbQ649wD8,2615
|
|
7
|
+
sphinxcontrib/exec_to_file/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
sphinx_exec_to_file-1.0.0.dist-info/METADATA,sha256=cKcK-_Wl81YoqsrEYb2GZOSxt7RrMuj_--wQeFlbin4,6852
|
|
9
|
+
sphinx_exec_to_file-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
10
|
+
sphinx_exec_to_file-1.0.0.dist-info/top_level.txt,sha256=VJrV3_vaiKQVgVpR0I1iecxoO0drzGu-M0j40PVP2QQ,14
|
|
11
|
+
sphinx_exec_to_file-1.0.0.dist-info/RECORD,,
|
|
@@ -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 @@
|
|
|
1
|
+
sphinxcontrib
|
|
@@ -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
|
|
File without changes
|