Debian Codegraph @

docs/plugin/howto.rst

raw
1 ######################
2 Plugin How-to Guides
3 ######################
4
5 ***********************
6 Plugin hook lifecycle
7 ***********************
8
9 The diagram below shows when each plugin hook fires during a tox run:
10
11 .. mermaid::
12
13 flowchart TD
14 start(( )) --> register[tox_register_tox_env]
15 register --> add_option[tox_add_option]
16 add_option --> extend[tox_extend_envs]
17 extend --> core_config[tox_add_core_config]
18 core_config --> env_config[tox_add_env_config]
19
20 env_config --> envloop
21
22 subgraph envloop [for each environment]
23 direction TB
24 on_install[tox_on_install]
25 on_install --> before[tox_before_run_commands]
26 before --> cmds[run commands]
27 cmds --> after[tox_after_run_commands]
28 after --> teardown[tox_env_teardown]
29 end
30
31 teardown --> done(( ))
32
33 classDef setupStyle fill:#dbeafe,stroke:#3b82f6,stroke-width:2px,color:#1e3a5f
34 classDef envStyle fill:#dcfce7,stroke:#22c55e,stroke-width:2px,color:#14532d
35 classDef cmdStyle fill:#ede9fe,stroke:#8b5cf6,stroke-width:2px,color:#3b0764
36 classDef installStyle fill:#ffedd5,stroke:#f97316,stroke-width:2px,color:#7c2d12
37
38 class register,add_option,extend,core_config,env_config setupStyle
39 class before,after,teardown envStyle
40 class cmds cmdStyle
41 class on_install installStyle
42
43 *************************************
44 Add custom config to an environment
45 *************************************
46
47 Use :func:`tox_add_env_config <tox.plugin.spec.tox_add_env_config>` to register new configuration keys on every tox
48 environment. Users can then set these keys in ``tox.toml`` or ``tox.ini`` like any built-in setting.
49
50 .. code-block:: python
51
52 from tox.config.sets import EnvConfigSet
53 from tox.plugin import impl
54 from tox.session.state import State
55
56
57 @impl
58 def tox_add_env_config(env_conf: EnvConfigSet, state: State) -> None:
59 env_conf.add_config(
60 keys=["my_timeout"],
61 of_type=int,
62 default=30,
63 desc="timeout in seconds for custom checks",
64 )
65
66 Access the value later via ``env_conf["my_timeout"]``.
67
68 ***********************************
69 Run code before or after commands
70 ***********************************
71
72 Use :func:`tox_before_run_commands <tox.plugin.spec.tox_before_run_commands>` and :func:`tox_after_run_commands
73 <tox.plugin.spec.tox_after_run_commands>` to execute logic around the ``commands`` phase. The ``tox_after_run_commands``
74 hook receives the exit code and the list of :class:`~tox.execute.api.Outcome` objects for each command.
75
76 .. code-block:: python
77
78 import time
79
80 from tox.execute import Outcome
81 from tox.plugin import impl
82 from tox.tox_env.api import ToxEnv
83
84 _start: float = 0
85
86
87 @impl
88 def tox_before_run_commands(tox_env: ToxEnv) -> None:
89 global _start # noqa: PLW0603
90 _start = time.monotonic()
91
92
93 @impl
94 def tox_after_run_commands(
95 tox_env: ToxEnv, exit_code: int, outcomes: list[Outcome]
96 ) -> None:
97 elapsed = time.monotonic() - _start
98 tox_env.conf.core["report"].verbosity0(
99 f"{tox_env.conf['env_name']} finished in {elapsed:.1f}s "
100 f"(exit code {exit_code})",
101 )
102
103 *********************************
104 Intercept package installations
105 *********************************
106
107 Use :func:`tox_on_install <tox.plugin.spec.tox_on_install>` to run logic whenever tox installs packages (deps, the
108 project itself, etc.). The ``section`` and ``of_type`` parameters identify which install phase triggered the call.
109
110 .. code-block:: python
111
112 from typing import Any
113
114 from tox.plugin import impl
115 from tox.tox_env.api import ToxEnv
116
117
118 @impl
119 def tox_on_install(tox_env: ToxEnv, arguments: Any, section: str, of_type: str) -> None:
120 print(f"Installing [{section}] {of_type}: {arguments}") # noqa: T201
121
122 *******************************
123 Clean up after an environment
124 *******************************
125
126 Use :func:`tox_env_teardown <tox.plugin.spec.tox_env_teardown>` to run cleanup logic after an environment finishes,
127 regardless of whether commands succeeded or failed.
128
129 .. code-block:: python
130
131 from tox.plugin import impl
132 from tox.tox_env.api import ToxEnv
133
134
135 @impl
136 def tox_env_teardown(tox_env: ToxEnv) -> None:
137 cache_dir = tox_env.env_dir / ".cache"
138 if cache_dir.exists():
139 import shutil
140
141 shutil.rmtree(cache_dir)
142
143 **************************************
144 Register a custom environment runner
145 **************************************
146
147 Use :func:`tox_register_tox_env <tox.plugin.spec.tox_register_tox_env>` to register a custom run or package environment
148 type. This is the hook used by plugins like ``tox-uv`` to replace the default virtualenv-based runner.
149
150 .. code-block:: python
151
152 from tox.plugin import impl
153 from tox.tox_env.python.virtual_env.runner import VirtualEnvRunner
154 from tox.tox_env.register import ToxEnvRegister
155
156
157 class MyRunner(VirtualEnvRunner):
158 @staticmethod
159 def id() -> str:
160 return "my-runner"
161
162 # override methods to customize behavior
163
164
165 @impl
166 def tox_register_tox_env(register: ToxEnvRegister) -> None:
167 register.add_run_env(MyRunner)
168
169 Set ``runner = my-runner`` in a tox environment to use it.
170
171 ***********************************
172 Package a plugin for distribution
173 ***********************************
174
175 While ``toxfile.py`` works for project-local plugins, distributable plugins are standard Python packages that declare
176 the ``tox`` entry point.
177
178 In ``pyproject.toml``:
179
180 .. code-block:: toml
181
182 [project]
183 name = "tox-myplugin"
184 version = "1.0.0"
185 dependencies = ["tox>=4"]
186
187 [project.entry-points.tox]
188 myplugin = "tox_myplugin"
189
190 In ``src/tox_myplugin/__init__.py``, define your hooks exactly as in ``toxfile.py``:
191
192 .. code-block:: python
193
194 from tox.plugin import impl
195
196
197 @impl
198 def tox_append_version_info() -> str:
199 return "myplugin-1.0.0"
200
201 After ``pip install tox-myplugin``, tox discovers the plugin automatically via the entry point.
202
203 *****************
204 Testing plugins
205 *****************
206
207 tox ships a pytest plugin at :mod:`tox.pytest` with fixtures for spinning up isolated tox projects, faking package
208 indexes, and capturing output. To use it, declare a dependency on the ``testing`` extra so that ``pytest``,
209 ``pytest-mock`` and ``devpi-process`` are pulled in:
210
211 .. code-block:: toml
212
213 [dependency-groups]
214 test = [
215 "tox[testing]",
216 ]
217
218 Then register the plugin in your ``conftest.py``:
219
220 .. code-block:: python
221
222 pytest_plugins = "tox.pytest"
223
224 *********
225 Logging
226 *********
227
228 tox uses Python's standard :mod:`logging` module. Plugin authors can use it to emit messages that integrate with tox's
229 output. The root logger is configured by tox at startup, so any ``logging`` call from plugin code is automatically
230 handled.
231
232 Getting a logger
233 ================
234
235 Use :func:`logging.getLogger` with your plugin's package name:
236
237 .. code-block:: python
238
239 import logging
240
241 logger = logging.getLogger(__name__)
242
243 You can also call module-level functions like ``logging.info(...)`` directly, but using a named logger makes it easier
244 for users to filter output.
245
246 Verbosity levels
247 ================
248
249 tox maps its ``-v`` / ``-q`` flags to standard logging levels:
250
251 .. list-table::
252 :header-rows: 1
253 :widths: 15 25 60
254
255 - - Flags
256 - Logging level
257 - Notes
258 - - ``-q`` (quiet)
259 - ``CRITICAL``
260 - Almost nothing is shown.
261 - - *(default)*
262 - ``ERROR``
263 - Only errors are shown.
264 - - ``-v``
265 - ``WARNING``
266 - Warnings and above are shown. This is the first level that appears in normal output.
267 - - ``-vv``
268 - ``INFO``
269 - Informational messages appear.
270 - - ``-vvv``
271 - ``DEBUG``
272 - Debug messages appear, along with timestamps and source file locations.
273
274 .. tip::
275
276 For messages that should be visible during normal usage (e.g. ``tox -v``), use ``logging.warning()``. Use
277 ``logging.info()`` for detail that is only useful when diagnosing issues.
278
279 Coloring
280 ========
281
282 tox applies color automatically based on the log level (when color output is enabled):
283
284 - **ERROR** and above: red
285 - **WARNING**: cyan
286 - **INFO** and below: white
287
288 There is a special convention for the ``WARNING`` level: if the message format string is ``"%s%s> %s"`` the second
289 argument is rendered in a dimmed style and the ``>`` acts as a separator. This is the pattern tox itself uses to show
290 the tox-environment prefix:
291
292 .. code-block:: python
293
294 # The second argument (plugin name) appears dimmed, followed by "> message"
295 logging.warning("%s%s> %s", "", "my-plugin", "This is a warning message")
296
297 For other levels (including ``ERROR``), the entire line is colored, so inline formatting is not possible.
298
299 .. note::
300
301 Color is controlled by the ``--colored`` flag and the ``NO_COLOR`` / ``FORCE_COLOR`` environment variables. Plugin
302 code does not need to handle color escapes manually.
303
304 Debug output
305 ============
306
307 At ``-vvv`` (``DEBUG`` level), tox adds extra metadata to every log line:
308
309 - elapsed time in milliseconds
310 - one-letter level indicator (``D``, ``I``, ``W``, ``E``, ``C``)
311 - source file and line number
312
313 This is useful for profiling and tracing plugin behavior.
314
315 Complete example
316 ================
317
318 .. code-block:: python
319
320 import logging
321
322 from tox.plugin import impl
323 from tox.tox_env.api import ToxEnv
324
325 logger = logging.getLogger(__name__)
326
327
328 @impl
329 def tox_before_run_commands(tox_env: ToxEnv) -> None:
330 # Visible at -vv or higher
331 logger.info("preparing environment %s", tox_env.name)
332 # Visible at -v or higher, with dimmed plugin name prefix
333 logger.warning(
334 "%s%s> %s", "", __package__, f"running pre-checks for {tox_env.name}"
335 )
336
337 ******************
338 Extension points
339 ******************
340
341 .. automodule:: tox.plugin
342 :members:
343 :exclude-members: impl
344
345 .. autodata:: tox.plugin.impl
346 :no-value:
347
348 .. automodule:: tox.plugin.spec
349 :members:
350
351 **************************************************
352 Adopting a plugin under the tox-dev organization
353 **************************************************
354
355 You're free to host your plugin on your favorite platform. However, the core tox development happens on GitHub under the
356 ``tox-dev`` organization. We are happy to adopt tox plugins under the ``tox-dev`` organization if:
357
358 - the plugin solves a valid use case and is not malicious,
359 - it's released on PyPI with at least 100 downloads per month (to ensure it's actively used).
360
361 What's in it for you:
362
363 - you get owner rights on the repository under the tox-dev organization,
364 - exposure of your plugin under the core umbrella,
365 - backup maintainers from other tox plugin developers.
366
367 How to apply:
368
369 - create an issue under the ``tox-dev/tox`` GitHub repository with the title :gh:`Adopt plugin \<name\>
370 <login?return_to=https%3A%2F%2Fgithub.com%2Ftox-dev%2Ftox%2Fissues%2Fnew%3Flabels%3Dfeature%253Anew%26template%3Dfeature_request.md%26title%3DAdopt%2520plugin%26body%3D>`,
371 - wait for the green light by one of the maintainers (see :ref:`current-maintainers`),
372 - follow the `guidance by GitHub
373 <https://docs.github.com/en/repositories/creating-and-managing-repositories/transferring-a-repository>`_,
374 - (optionally) add at least one other person as co-maintainer on PyPI.