Debian Codegraph @

docs/plugin/getting_started.rst

raw
1 ###################
2 Your first plugin
3 ###################
4
5 You can define plugins directly in your project by creating a ``toxfile.py`` file next to your tox configuration file.
6 This avoids the need to package and install a separate plugin. All the same hooks are available.
7
8 **************************************
9 Your first plugin: adding a CLI flag
10 **************************************
11
12 Create a ``toxfile.py`` that adds a ``--magic`` flag to the tox CLI:
13
14 .. code-block:: python
15
16 from tox.config.cli.parser import ToxParser
17 from tox.plugin import impl
18
19
20 @impl
21 def tox_add_option(parser: ToxParser) -> None:
22 parser.add_argument("--magic", action="store_true", help="enable magic mode")
23
24 Place this file next to your ``tox.toml`` or ``tox.ini``. When tox starts, it discovers and loads ``toxfile.py``
25 automatically.
26
27 ************************
28 Appending version info
29 ************************
30
31 A ``toxfile.py`` that appends text to the ``tox --version`` output:
32
33 .. code-block:: python
34
35 from tox.plugin import impl
36
37
38 @impl
39 def tox_append_version_info() -> str:
40 return "magic"
41
42 ************************
43 Providing environments
44 ************************
45
46 Plugins can dynamically inject tox environments that don't need to be declared in ``tox.toml`` or ``tox.ini``. This uses
47 two hooks together: :func:`tox_extend_envs <tox.plugin.spec.tox_extend_envs>` to declare the environment name, and
48 :func:`tox_add_core_config <tox.plugin.spec.tox_add_core_config>` with :class:`~tox.config.loader.memory.MemoryLoader`
49 to configure it.
50
51 For example, a ``toxfile.py`` that adds a ``lint`` environment running `pre-commit <https://pre-commit.com>`_:
52
53 .. code-block:: python
54
55 from collections.abc import Iterable
56
57 from tox.config.loader.memory import MemoryLoader
58 from tox.config.sets import ConfigSet
59 from tox.plugin import impl
60 from tox.session.state import State
61
62
63 @impl
64 def tox_extend_envs() -> Iterable[str]:
65 return ("lint",)
66
67
68 @impl
69 def tox_add_core_config(core_conf: ConfigSet, state: State) -> None:
70 state.conf.memory_seed_loaders["lint"].append(
71 MemoryLoader(
72 description="run pre-commit linters",
73 commands=[["pre-commit", "run", "--all-files"]],
74 deps=["pre-commit"],
75 ),
76 )
77
78 With this ``toxfile.py`` in your project root, ``tox list`` shows the ``lint`` environment and ``tox run -e lint``
79 executes it -- no configuration file entry needed.
80
81 Any :ref:`configuration key <conf-testenv>` accepted by the environment can be passed as a keyword argument to
82 ``MemoryLoader``. Values from ``MemoryLoader`` act as defaults and can still be overridden by the configuration file or
83 CLI ``--override``.