Skip to content

Commit d97c5a2

Browse files
committed
Add introspection command
1 parent d624569 commit d97c5a2

3 files changed

Lines changed: 60 additions & 0 deletions

File tree

example_pkg/pyproject.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,9 @@ package = 'example_pkg'
4747
"Pip" = [
4848
"spin.cmds.pip.install"
4949
]
50+
"Meta" = [
51+
"spin.cmds.meta.introspect"
52+
]
5053

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

spin/__main__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,8 @@ def group(ctx):
148148
if option.name in default_kwargs:
149149
option.default = default_kwargs[option.name]
150150

151+
cmd_func.spec = cmd # store where this function is defined
152+
# for use in `introspect` command
151153
commands[cmd] = cmd_func
152154

153155
group.add_command(commands[cmd], section=section)

spin/cmds/meta.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import inspect
2+
3+
import click
4+
5+
from .util import get_commands, get_config
6+
7+
8+
def _highlight(src):
9+
from pygments import highlight
10+
from pygments.formatters import TerminalFormatter
11+
from pygments.lexers import PythonLexer
12+
13+
return highlight(src, PythonLexer(), TerminalFormatter())
14+
15+
16+
@click.command()
17+
@click.argument("cmd", nargs=1)
18+
def introspect(*, cmd):
19+
"""🔍 Print a command's location and source code."""
20+
cmds_by_section = get_commands()
21+
overrides = get_config().get("tool.spin.kwargs")
22+
23+
cmds = {}
24+
for section in cmds_by_section:
25+
cmds.update({cmd.name: cmd for cmd in cmds_by_section[section]})
26+
27+
if cmd not in cmds:
28+
raise SystemExit(f"Command `{cmd}` not found. Exiting.")
29+
30+
cmd_func = cmds[cmd]
31+
try:
32+
code = inspect.getsource(cmd_func.callback)
33+
except TypeError:
34+
code = inspect.getsource(cmd_func.callback.func)
35+
36+
click.secho(
37+
f"The `{cmd}` command is defined in `{cmd_func.spec}`:\n",
38+
bold=True,
39+
fg="magenta",
40+
)
41+
42+
try:
43+
code = _highlight(code)
44+
except ImportError:
45+
pass
46+
47+
print(code)
48+
49+
if cmd_func.spec in overrides:
50+
click.secho(
51+
"The function has the following keyword overrides defined:\n",
52+
bold=True,
53+
fg="magenta",
54+
)
55+
print(overrides[cmd_func.spec])

0 commit comments

Comments
 (0)