Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow setting default args for commands / callbacks #157

Merged
merged 4 commits into from
Apr 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,29 @@ def example():
print(config["tool.spin"])
```

### Argument overrides

Default arguments can be overridden for any command.
The custom command above, e.g., has the following signature:

```python
@click.command()
@click.option("-f", "--flag")
@click.option("-t", "--test", default="not set")
def example(flag, test, default_kwd=None):
"""🧪 Example custom command.
...
"""
```

Use the `[tool.spin.kwargs]` section to override default values for
click options or function keywords:

```toml
[tool.spin.kwargs]
".spin/cmds.py:example" = {"test" = "default override", "default_kwd" = 3}
```

### Advanced: adding arguments to built-in commands

Instead of rewriting a command from scratch, a project may want to add a flag to a built-in `spin` command, or perhaps do some pre- or post-processing.
Expand Down
8 changes: 7 additions & 1 deletion example_pkg/.spin/cmds.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@

@click.command()
@click.option("-f", "--flag")
def example(flag):
@click.option("-t", "--test", default="not set")
def example(flag, test, default_kwd=None):
"""🧪 Example custom command.

Accepts arbitrary flags, and shows how to access `pyproject.toml`
Expand All @@ -20,6 +21,11 @@ def example(flag):
click.secho("Flag provided with --flag is: ", fg="yellow", nl=False)
print(flag or None)

click.secho("Flag provided with --test is: ", fg="yellow", nl=False)
print(test or None)

click.secho(f"Default kwd is: {default_kwd}")

click.secho("\nDefined commands:", fg="yellow")
for section in commands:
print(f" {section}: ", end="")
Expand Down
3 changes: 3 additions & 0 deletions example_pkg/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,6 @@ package = 'example_pkg'
"Install" = [
"spin.cmds.pip.install"
]

[tool.spin.kwargs]
".spin/cmds.py:example" = {"test" = "default override", "default_kwd" = 3}
13 changes: 13 additions & 0 deletions spin/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ def group(ctx):
"spin.python": _cmds.meson.python,
"spin.shell": _cmds.meson.shell,
}
cmd_default_kwargs = toml_config.get("tool.spin.kwargs", {})

for section, cmds in config_cmds.items():
for cmd in cmds:
Expand Down Expand Up @@ -133,6 +134,18 @@ def group(ctx):
print(f"!! Could not load command `{func}` from file `{path}`.\n")
continue

default_kwargs = cmd_default_kwargs.get(cmd)
import functools

if default_kwargs:
callback = cmd_func.callback
cmd_func.callback = functools.partial(callback, **default_kwargs)

# Also override option defaults
for option in cmd_func.params:
if option.name in default_kwargs:
option.default = default_kwargs[option.name]

commands[cmd] = cmd_func

group.add_command(commands[cmd], section=section)
Expand Down
35 changes: 2 additions & 33 deletions spin/tests/test_build_cmds.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,41 +4,10 @@
import tempfile
from pathlib import Path

import pytest
from testutil import skip_on_windows, skip_unless_linux, spin, stdout

import spin as libspin
from spin.cmds.util import run

skip_on_windows = pytest.mark.skipif(
sys.platform.startswith("win"), reason="Skipped; platform is Windows"
)

on_linux = pytest.mark.skipif(
not sys.platform.startswith("linux"), reason="Skipped; platform not Linux"
)


def spin(*args, **user_kwargs):
default_kwargs = {
"stdout": subprocess.PIPE,
"stderr": subprocess.PIPE,
"sys_exit": True,
}
return run(["spin"] + list(args), **{**default_kwargs, **user_kwargs})


def stdout(p):
return p.stdout.decode("utf-8").strip()


def stderr(p):
return p.stderr.decode("utf-8").strip()


def test_get_version():
p = spin("--version")
assert stdout(p) == f"spin {libspin.__version__}"


def test_basic_build():
"""Does the package build?"""
Expand Down Expand Up @@ -145,7 +114,7 @@ def test_spin_install():
run(["pip", "uninstall", "-y", "--quiet", "example_pkg"])


@on_linux
@skip_unless_linux
def test_gdb():
p = spin(
"gdb",
Expand Down
17 changes: 17 additions & 0 deletions spin/tests/test_cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from testutil import spin, stdout

import spin as libspin


def test_get_version():
p = spin("--version")
assert stdout(p) == f"spin {libspin.__version__}"


def test_arg_override():
p = spin("example")
assert "--test is: default override" in stdout(p)
assert "Default kwd is: 3" in stdout(p)

p = spin("example", "-t", 6)
assert "--test is: 6" in stdout(p)
32 changes: 32 additions & 0 deletions spin/tests/testutil.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import subprocess
import sys

import pytest

from spin.cmds.util import run

skip_on_windows = pytest.mark.skipif(
sys.platform.startswith("win"), reason="Skipped; platform is Windows"
)

skip_unless_linux = pytest.mark.skipif(
not sys.platform.startswith("linux"), reason="Skipped; platform not Linux"
)


def spin(*args, **user_kwargs):
args = (str(el) for el in args)
default_kwargs = {
"stdout": subprocess.PIPE,
"stderr": subprocess.PIPE,
"sys_exit": True,
}
return run(["spin"] + list(args), **{**default_kwargs, **user_kwargs})


def stdout(p):
return p.stdout.decode("utf-8").strip()


def stderr(p):
return p.stderr.decode("utf-8").strip()
28 changes: 0 additions & 28 deletions spin/tests/util.py

This file was deleted.

Loading