-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
232 lines (199 loc) · 7.8 KB
/
Copy pathcli.py
File metadata and controls
232 lines (199 loc) · 7.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
"""DevForge unified CLI entry point."""
import importlib.util
import subprocess
import sys
import typer
from devforge import TOOLS, __version__
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
app = typer.Typer(
name="devforge",
help="DevForge — unified CLI for developer tools.",
rich_markup_mode="rich",
)
console = Console()
def _show_version(value: bool) -> None:
if value:
console.print(f"[bold]devforge[/] v{__version__} — DevForge CLI")
raise typer.Exit()
@app.callback()
def main_callback(
version: bool = typer.Option(
False,
"--version",
"-V",
help="Show version and exit.",
callback=_show_version,
is_eager=True,
),
):
pass
@app.command(name="tools")
def list_tools(
name: str | None = typer.Argument(None, help="Show details for a specific tool."),
):
"""List available DevForge CLI tools."""
if name:
tool = TOOLS.get(name)
if not tool:
console.print(f"[red]Unknown tool: {name}[/red]")
raise typer.Exit(code=1)
console.print(
Panel.fit(
f"[bold]{tool['icon']} {name}[/bold]\n"
f"Package: [cyan]{tool['package']}[/cyan]\n"
f"Description: {tool['description']}\n"
f"Pricing: [yellow]{tool['pricing']}[/yellow]\n"
f"Status: [green]{tool['status']}[/green]\n"
f"URL: {tool['url']}",
title=f"devforge {name}",
)
)
else:
table = Table(title="DevForge CLI Tools")
table.add_column("Command", style="cyan")
table.add_column("Package", style="green")
table.add_column("Description")
table.add_column("Pricing", style="yellow")
table.add_column("Status", style="bold")
for cmd, tool in TOOLS.items():
table.add_row(
tool["icon"] + " " + cmd,
tool["package"],
tool["description"],
tool["pricing"],
"✅" if tool["status"] == "ready" else tool["status"],
)
console.print(table)
console.print(
'\n[dim]Install:[/dim] [green]pip install "git+https://github.com/Coding-Dev-Tools/devforge-cli.git[all]"[/green]'
)
console.print("[dim](devforge-tools is not on public PyPI — use the git+ form above.)[/dim]")
@app.command()
def install(
tool: str = typer.Argument(..., help="Tool to install: " + ", ".join(TOOLS.keys()) + ", or 'all'"),
):
"""Install a DevForge tool."""
if tool == "all":
targets = list(TOOLS.keys())
extras = "all"
elif tool in TOOLS:
targets = [tool]
extras = tool
else:
console.print(f"[red]Unknown tool: {tool}[/red]")
console.print(f"Available: {', '.join(TOOLS.keys())}, 'all'")
raise typer.Exit(code=1)
# devforge-tools is NOT published on public PyPI — install from GitHub source.
repo_url = "https://github.com/Coding-Dev-Tools/devforge-cli.git"
pkg = f"git+{repo_url}[{extras}]"
console.print(f"[yellow]Installing {pkg}...[/yellow]")
# Only catch OS-level failures here. A bare `except Exception` would also
# swallow the typer.Exit raised below (typer.Exit subclasses Exception),
# double-printing an error line ("Error: 1") after the failure message.
try:
result = subprocess.run(
[sys.executable, "-m", "pip", "install", pkg], capture_output=True, text=True
)
except OSError as e:
console.print(f"[red]Error running pip:[/red] {e}")
raise typer.Exit(code=1) from e
if result.returncode == 0:
console.print(f"[green]Successfully installed:[/green] {', '.join(targets)}")
else:
console.print(f"[red]Installation failed:[/red] {result.stderr[:500]}")
raise typer.Exit(code=1)
@app.command(name="versions")
def show_versions(
tool: str | None = typer.Argument(None, help="Check version of a specific tool."),
):
"""Show installed tool versions."""
if tool is not None and tool not in TOOLS:
console.print(f"[red]Unknown tool: {tool}[/red]")
console.print(f"Available: {', '.join(TOOLS.keys())}")
raise typer.Exit(code=1)
targets = [tool] if tool else list(TOOLS.keys())
for t in targets:
info = TOOLS[t]
try:
ver = _pip_version(info["package"])
except Exception as e:
console.print(f"[dim]{t:8}[/dim] [red]error checking ({e})[/red]")
continue
if ver is None:
console.print(f"[dim]{t:8}[/dim] [red]not installed[/red]")
elif ver == "":
# pip show succeeded but returned no Version metadata — never stay silent.
console.print(f"[dim]{t:8}[/dim] [yellow]installed, no version metadata[/yellow]")
else:
console.print(f"[cyan]{t:8}[/cyan] v{ver}")
def _pip_version(package: str) -> str | None:
"""Return the installed version of *package*, or None if not installed.
Returns "" when ``pip show`` succeeds but the output carries no
``Version:`` line (broken metadata) so callers can distinguish it from a
clean not-installed result instead of silently printing nothing.
"""
result = subprocess.run(
[sys.executable, "-m", "pip", "show", package], capture_output=True, text=True
)
if result.returncode != 0:
return None
for line in result.stdout.splitlines():
if line.startswith("Version:"):
return line.split(":", 1)[1].strip()
return ""
def _is_tool_installed(module_name: str) -> bool:
"""Return True if the module (Python package) is importable."""
return importlib.util.find_spec(module_name) is not None
# Dynamically add subcommands for each tool
def _make_dispatch(tool_name: str):
"""Create a typer command that dispatches to the underlying tool CLI."""
pkg = TOOLS[tool_name]["package"]
def dispatch(ctx: typer.Context):
info = TOOLS.get(tool_name)
if not info:
console.print(f"[red]Unknown tool: {tool_name}[/red]")
raise typer.Exit(code=1)
module_name = info["package"].replace("-", "_")
if not _is_tool_installed(module_name):
console.print(
f"[red]Tool '{tool_name}' is not installed.[/red]\n"
f'Run: [green]pip install "git+https://github.com/Coding-Dev-Tools/devforge-cli.git\\[{tool_name}]"[/green]',
soft_wrap=True,
)
raise typer.Exit(code=1)
# `ignore_unknown_options` + `allow_extra_args` let tool flags (e.g.
# `--config file.yaml`) reach the underlying CLI instead of being
# rejected by typer as "No such option".
forwarded = list(ctx.args)
try:
result = subprocess.run(
[sys.executable, "-m", module_name] + forwarded,
capture_output=True,
text=True,
)
except OSError as e:
console.print(f"[red]Error launching {tool_name}:[/red] {e}")
raise typer.Exit(code=1) from e
except KeyboardInterrupt:
# Forward Ctrl-C as a conventional 130 exit, not a raw traceback.
console.print("[yellow]Interrupted.[/yellow]")
sys.exit(130)
if result.stdout:
sys.stdout.write(result.stdout)
if result.stderr:
sys.stderr.write(result.stderr)
sys.exit(result.returncode)
dispatch.__name__ = tool_name
dispatch.__doc__ = f"Run `{pkg}` commands via the {tool_name} subcommand."
return app.command(
name=tool_name,
context_settings={"ignore_unknown_options": True, "allow_extra_args": True},
)(dispatch)
for cmd_name in TOOLS:
_make_dispatch(cmd_name)
def main():
app()
if __name__ == "__main__":
main()