pyvolt-cli 0.7.0__tar.gz → 0.8.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: pyvolt-cli
3
- Version: 0.7.0
3
+ Version: 0.8.0
4
4
  Summary: The command-line companion to Pyvolt: managed Python deployments on infrastructure you actually own.
5
5
  Project-URL: Homepage, https://pyvolt.com
6
6
  Project-URL: Repository, https://github.com/pyvolt-hq/pyvolt-cli
@@ -51,12 +51,18 @@ pyvolt deploy myapp --follow
51
51
  | `pyvolt metrics SERVER` | Latest CPU / memory / disk / network snapshot |
52
52
  | `pyvolt bans SERVER` | IPs banned by fail2ban, your own flagged |
53
53
  | `pyvolt unban SERVER [IP] [--me]` | Lift a ban — `--me` unbans your own IP, even while it's banned |
54
- | `pyvolt ssh SERVER [--app DOMAIN]` | Open a shell on the server (as the `pyvolt` user); `--app` cds into the app dir |
54
+ | `pyvolt ssh [SERVER] [--app DOMAIN]` | Open a shell on the server (as the `pyvolt` user); `--app` cds into the app's live release |
55
+ | `pyvolt run [-a DOMAIN] -- COMMAND` | Run a one-off command in the app's live release with its environment variables, e.g. `-- python manage.py createsuperuser` |
55
56
  | `pyvolt open DOMAIN` | Jump to the dashboard |
56
57
 
57
58
  `DOMAIN` is the app's domain, or any unambiguous fragment of it — domains
58
59
  are unique across the platform, so no server qualifier is ever needed.
59
60
 
61
+ In an app's repo folder you can leave it out: `pyvolt logs`, `pyvolt env list`,
62
+ `pyvolt run -- python manage.py migrate`, and `pyvolt ssh` with no server, use
63
+ the app that deploys from the folder's git remote. If that repo deploys to more
64
+ than one app (staging and production, say), pass the one you mean.
65
+
60
66
  Full guide: [pyvolt.com/docs/cli](https://pyvolt.com/docs/cli/) · HTTP API:
61
67
  [pyvolt.com/api/docs](https://pyvolt.com/api/docs)
62
68
 
@@ -21,12 +21,18 @@ pyvolt deploy myapp --follow
21
21
  | `pyvolt metrics SERVER` | Latest CPU / memory / disk / network snapshot |
22
22
  | `pyvolt bans SERVER` | IPs banned by fail2ban, your own flagged |
23
23
  | `pyvolt unban SERVER [IP] [--me]` | Lift a ban — `--me` unbans your own IP, even while it's banned |
24
- | `pyvolt ssh SERVER [--app DOMAIN]` | Open a shell on the server (as the `pyvolt` user); `--app` cds into the app dir |
24
+ | `pyvolt ssh [SERVER] [--app DOMAIN]` | Open a shell on the server (as the `pyvolt` user); `--app` cds into the app's live release |
25
+ | `pyvolt run [-a DOMAIN] -- COMMAND` | Run a one-off command in the app's live release with its environment variables, e.g. `-- python manage.py createsuperuser` |
25
26
  | `pyvolt open DOMAIN` | Jump to the dashboard |
26
27
 
27
28
  `DOMAIN` is the app's domain, or any unambiguous fragment of it — domains
28
29
  are unique across the platform, so no server qualifier is ever needed.
29
30
 
31
+ In an app's repo folder you can leave it out: `pyvolt logs`, `pyvolt env list`,
32
+ `pyvolt run -- python manage.py migrate`, and `pyvolt ssh` with no server, use
33
+ the app that deploys from the folder's git remote. If that repo deploys to more
34
+ than one app (staging and production, say), pass the one you mean.
35
+
30
36
  Full guide: [pyvolt.com/docs/cli](https://pyvolt.com/docs/cli/) · HTTP API:
31
37
  [pyvolt.com/api/docs](https://pyvolt.com/api/docs)
32
38
 
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "pyvolt-cli"
7
- version = "0.7.0"
7
+ version = "0.8.0"
8
8
  description = "The command-line companion to Pyvolt: managed Python deployments on infrastructure you actually own."
9
9
  readme = "README.md"
10
10
  license = { text = "MIT" }
@@ -7,6 +7,7 @@ import time
7
7
  import webbrowser
8
8
 
9
9
  import typer
10
+ from typer.core import TyperGroup
10
11
  from rich.console import Console
11
12
  from rich.table import Table
12
13
 
@@ -144,7 +145,7 @@ def servers():
144
145
 
145
146
  @app.command()
146
147
  def ssh(
147
- server: str = typer.Argument(..., metavar="SERVER"),
148
+ server: str = typer.Argument("", metavar="[SERVER]", help="Default: the server of the app this folder's repo deploys."),
148
149
  app_name: str = typer.Option("", "--app", "-a", help="cd into this app's directory on connect."),
149
150
  ):
150
151
  """Open an SSH shell on a server (as the pyvolt app-user).
@@ -158,19 +159,71 @@ def ssh(
158
159
  if not shutil.which("ssh"):
159
160
  raise fail("No `ssh` client found on PATH.")
160
161
  api = Api()
162
+ if not server:
163
+ # In an app's repo folder: its server, landing in its directory.
164
+ site = api.app(app_name)
165
+ server, app_name = site["server"], site["domain"]
161
166
  srv = api.resolve_server(server)
162
167
  if srv["status"] != "ready":
163
168
  raise fail(f"{srv['name']} is {srv['status']}, not ready.")
164
169
  target = f"{srv.get('ssh_user', 'pyvolt')}@{srv['ip_address']}"
165
170
  args = ["ssh", "-p", str(srv.get("ssh_port", 22)), target]
166
171
  if app_name:
167
- site = api.resolve_app(app_name)
172
+ site = api.app(app_name)
168
173
  # Drop into the app's checkout, then hand over an interactive shell.
169
- args += ["-t", f"cd sites/{site['domain']}/repo 2>/dev/null; exec \"$SHELL\" -l"]
174
+ args += ["-t", f"cd sites/{site['domain']}/current 2>/dev/null; exec \"$SHELL\" -l"]
170
175
  console.print(f"[dim]Connecting to {target}…[/dim]")
171
176
  os.execvp("ssh", args)
172
177
 
173
178
 
179
+ def _run_args(srv: dict, domain: str, command: list[str], tty: bool) -> list[str]:
180
+ """The ssh command line for `pyvolt run`: the app's run script, which each
181
+ deploy writes, with the command quoted for the remote shell."""
182
+ import shlex
183
+
184
+ target = f"{srv.get('ssh_user', 'pyvolt')}@{srv['ip_address']}"
185
+ args = ["ssh", "-p", str(srv.get("ssh_port", 22))]
186
+ args.append("-t" if tty else "-T")
187
+ return args + [target, shlex.join([f"sites/{domain}/run", *command])]
188
+
189
+
190
+ @app.command(
191
+ context_settings={"allow_extra_args": True, "ignore_unknown_options": True},
192
+ )
193
+ def run(
194
+ ctx: typer.Context,
195
+ app_name: str = typer.Option("", "--app", "-a", metavar="DOMAIN", help="The app; default: the one this folder's repo deploys."),
196
+ ):
197
+ """Run a one-off command in an app's live release, with its environment variables.
198
+
199
+ It runs in the app's project folder with its .env, virtualenv and settings
200
+ module, like its release commands. Put the command after --:
201
+
202
+ pyvolt run -a shop.example.com -- python manage.py createsuperuser
203
+
204
+ In the app's repo folder, -a can be left out. Interactive commands (a shell, createsuperuser) work from a terminal. The
205
+ exit code is the command's, so it works in scripts too. Needs your SSH key
206
+ on the server, like pyvolt ssh, and a deploy since the run script arrived."""
207
+ import os
208
+ import shutil
209
+ import sys
210
+
211
+ command = list(ctx.args)
212
+ if command and command[0] == "--":
213
+ command = command[1:]
214
+ if not command:
215
+ raise fail("Give the command to run after --, e.g. pyvolt run -- python manage.py migrate")
216
+ if not shutil.which("ssh"):
217
+ raise fail("No `ssh` client found on PATH.")
218
+ api = Api()
219
+ site = api.app(app_name)
220
+ srv = api.resolve_server(site["server"])
221
+ if srv["status"] != "ready":
222
+ raise fail(f"{srv['name']} is {srv['status']}, not ready.")
223
+ args = _run_args(srv, site["domain"], command, sys.stdin.isatty() and sys.stdout.isatty())
224
+ os.execvp("ssh", args)
225
+
226
+
174
227
  apps_app = typer.Typer(help="List your apps; `pyvolt apps create` makes a new one.")
175
228
  app.add_typer(apps_app, name="apps")
176
229
 
@@ -288,9 +341,9 @@ def apps_create(
288
341
 
289
342
 
290
343
  @app.command()
291
- def status(app_name: str = typer.Argument(..., metavar="DOMAIN")):
344
+ def status(app_name: str = typer.Argument("", metavar="[DOMAIN]", help="The app; default: the one this folder's repo deploys.")):
292
345
  """Show one app's details: status, URLs, repo and branch."""
293
- site = Api().resolve_app(app_name)
346
+ site = Api().app(app_name)
294
347
  if _emit(site):
295
348
  return
296
349
  t = _table("FIELD", "VALUE")
@@ -322,12 +375,12 @@ def _follow(api: Api, deployment_id: int) -> str:
322
375
 
323
376
  @app.command()
324
377
  def deploy(
325
- app_name: str = typer.Argument(..., metavar="DOMAIN"),
378
+ app_name: str = typer.Argument("", metavar="[DOMAIN]", help="The app; default: the one this folder's repo deploys."),
326
379
  follow: bool = typer.Option(False, "--follow", "-f", help="Stream the deploy log."),
327
380
  ):
328
381
  """Trigger a deployment."""
329
382
  api = Api()
330
- site = api.resolve_app(app_name)
383
+ site = api.app(app_name)
331
384
  r = api.post(f"/v1/apps/{site['id']}/deployments", ok=(201, 409))
332
385
  if r.status_code == 409:
333
386
  raise fail(r.json()["detail"])
@@ -344,7 +397,7 @@ def deploy(
344
397
 
345
398
  @app.command()
346
399
  def deployments(
347
- app_name: str = typer.Argument(..., metavar="DOMAIN"),
400
+ app_name: str = typer.Argument("", metavar="[DOMAIN]", help="The app; default: the one this folder's repo deploys."),
348
401
  watch: bool = typer.Option(
349
402
  False, "--watch", "-w",
350
403
  help="Wait for the next deployment (e.g. after a git push), stream its log, "
@@ -353,7 +406,7 @@ def deployments(
353
406
  ):
354
407
  """Recent deployments for an app."""
355
408
  api = Api()
356
- site = api.resolve_app(app_name)
409
+ site = api.app(app_name)
357
410
  data = api.get(f"/v1/apps/{site['id']}/deployments")
358
411
  if watch:
359
412
  running = next((d for d in data if d["status"] in ("queued", "running")), None)
@@ -390,12 +443,22 @@ def deployments(
390
443
 
391
444
  # ---- env ----------------------------------------------------------------------
392
445
 
393
- env_app = typer.Typer(no_args_is_help=True, help="Manage an app's environment variables.")
446
+ class _OptionalAppGroup(TyperGroup):
447
+ """A group whose first argument, the app, can be left out in the app's
448
+ repo folder: `pyvolt env list` as well as `pyvolt env DOMAIN list`."""
449
+
450
+ def parse_args(self, ctx, args):
451
+ if args and args[0] in self.commands:
452
+ args = ["", *args]
453
+ return super().parse_args(ctx, args)
454
+
455
+
456
+ env_app = typer.Typer(cls=_OptionalAppGroup, no_args_is_help=True, help="Manage an app's environment variables.")
394
457
  app.add_typer(env_app, name="env")
395
458
 
396
459
 
397
460
  @env_app.callback()
398
- def _env_main(ctx: typer.Context, app_name: str = typer.Argument(..., metavar="DOMAIN")):
461
+ def _env_main(ctx: typer.Context, app_name: str = typer.Argument("", metavar="[DOMAIN]", help="The app; default: the one this folder's repo deploys.")):
399
462
  ctx.obj = app_name
400
463
 
401
464
 
@@ -403,7 +466,7 @@ def _env_main(ctx: typer.Context, app_name: str = typer.Argument(..., metavar="D
403
466
  def env_list(ctx: typer.Context):
404
467
  """Show the app's variables (secret values masked)."""
405
468
  api = Api()
406
- site = api.resolve_app(ctx.obj)
469
+ site = api.app(ctx.obj)
407
470
  data = api.get(f"/v1/apps/{site['id']}/env")
408
471
  if _emit(data):
409
472
  return
@@ -417,7 +480,7 @@ def env_list(ctx: typer.Context):
417
480
  def env_get(ctx: typer.Context, key: str):
418
481
  """Show one variable's value — unmasked, since it's your own secret."""
419
482
  api = Api()
420
- site = api.resolve_app(ctx.obj)
483
+ site = api.app(ctx.obj)
421
484
  row = api.get(f"/v1/apps/{site['id']}/env/{key}")
422
485
  if _emit(row):
423
486
  return
@@ -428,7 +491,7 @@ def env_get(ctx: typer.Context, key: str):
428
491
  def env_set(ctx: typer.Context, pairs: list[str] = typer.Argument(..., metavar="KEY=VALUE...")):
429
492
  """Set one or more variables — pushes the .env and restarts the app."""
430
493
  api = Api()
431
- site = api.resolve_app(ctx.obj)
494
+ site = api.app(ctx.obj)
432
495
  for pair in pairs:
433
496
  if "=" not in pair:
434
497
  raise fail(f"Expected KEY=VALUE, got [bold]{pair}[/bold]")
@@ -441,7 +504,7 @@ def env_set(ctx: typer.Context, pairs: list[str] = typer.Argument(..., metavar="
441
504
  def env_rm(ctx: typer.Context, key: str):
442
505
  """Remove a variable — pushes the .env and restarts the app."""
443
506
  api = Api()
444
- site = api.resolve_app(ctx.obj)
507
+ site = api.app(ctx.obj)
445
508
  r = api.delete(f"/v1/apps/{site['id']}/env/{key}")
446
509
  if not r["deleted"]:
447
510
  raise fail(f"[bold]{key}[/bold] is not set.")
@@ -452,17 +515,20 @@ def env_rm(ctx: typer.Context, key: str):
452
515
 
453
516
  @app.command()
454
517
  def ps(
455
- app_name: str = typer.Argument(..., metavar="DOMAIN"),
518
+ app_name: str = typer.Argument("", metavar="[DOMAIN]", help="The app; default: the one this folder's repo deploys."),
456
519
  action: str = typer.Argument("", metavar="[restart]"),
457
520
  process: str = typer.Argument("", metavar="[NAME]"),
458
521
  ):
459
- """List background processes; `pyvolt ps APP restart NAME` restarts one."""
522
+ """List background processes; `pyvolt ps [DOMAIN] restart NAME` restarts one."""
523
+ if app_name == "restart" and not process:
524
+ # `pyvolt ps restart worker` in the app's folder: no domain given.
525
+ app_name, action, process = "", "restart", action
460
526
  api = Api()
461
- site = api.resolve_app(app_name)
527
+ site = api.app(app_name)
462
528
  procs = api.get(f"/v1/apps/{site['id']}/processes")
463
529
  if action:
464
530
  if action != "restart" or not process:
465
- raise fail("Usage: pyvolt ps DOMAIN restart NAME")
531
+ raise fail("Usage: pyvolt ps [DOMAIN] restart NAME")
466
532
  match = [p for p in procs if p["name"] == process]
467
533
  if not match:
468
534
  known = ", ".join(p["name"] for p in procs) or "none"
@@ -481,13 +547,13 @@ def ps(
481
547
 
482
548
  @app.command()
483
549
  def logs(
484
- app_name: str = typer.Argument(..., metavar="DOMAIN"),
550
+ app_name: str = typer.Argument("", metavar="[DOMAIN]", help="The app; default: the one this folder's repo deploys."),
485
551
  process: str = typer.Option("", "--process", "-p", help="A named background process instead of the web app."),
486
552
  lines: int = typer.Option(100, "--lines", "-n", help="How many lines (max 500)."),
487
553
  ):
488
554
  """Tail the app's journal."""
489
555
  api = Api()
490
- site = api.resolve_app(app_name)
556
+ site = api.app(app_name)
491
557
  params = {"lines": lines}
492
558
  if process:
493
559
  params["process"] = process
@@ -567,11 +633,11 @@ def unban(
567
633
 
568
634
  @app.command("open")
569
635
  def open_(
570
- app_name: str = typer.Argument(..., metavar="DOMAIN"),
636
+ app_name: str = typer.Argument("", metavar="[DOMAIN]", help="The app; default: the one this folder's repo deploys."),
571
637
  print_url: bool = typer.Option(False, "--print", "-p", help="Print the URLs instead of opening a browser."),
572
638
  ):
573
639
  """Open the app's dashboard in your browser (or --print the URLs)."""
574
- site = Api().resolve_app(app_name)
640
+ site = Api().app(app_name)
575
641
  if _emit({"site_url": site.get("site_url"), "dashboard_url": site.get("dashboard_url")}):
576
642
  return
577
643
  if print_url:
@@ -638,7 +704,7 @@ def keys_rm(key_id: int = typer.Argument(..., metavar="ID", help="Key ID from `p
638
704
 
639
705
  @apps_app.command("export-config")
640
706
  def apps_export_config(
641
- app_name: str = typer.Argument(..., metavar="DOMAIN"),
707
+ app_name: str = typer.Argument("", metavar="[DOMAIN]", help="The app; default: the one this folder's repo deploys."),
642
708
  write: bool = typer.Option(
643
709
  False, "--write", "-w", help="Write ./pyvolt.toml instead of printing it."
644
710
  ),
@@ -651,7 +717,7 @@ def apps_export_config(
651
717
  from pathlib import Path
652
718
 
653
719
  api = Api()
654
- site = api.resolve_app(app_name)
720
+ site = api.app(app_name)
655
721
  body = api.get(f"/v1/apps/{site['id']}/config")
656
722
  if _emit(body):
657
723
  return
@@ -68,6 +68,26 @@ class Api:
68
68
  ambiguous = ", ".join(s["name"] for s in matches)
69
69
  raise fail(f"[bold]{name}[/bold] is ambiguous: {ambiguous}")
70
70
 
71
+ def app(self, name: str = "") -> dict:
72
+ """The named app, or with no name, the one this folder deploys."""
73
+ return self.resolve_app(name) if name else self.app_for_cwd()
74
+
75
+ def app_for_cwd(self) -> dict:
76
+ """The app deployed from this folder's repo (its git remote), when
77
+ exactly one is. Several (staging and production, say) are never
78
+ guessed between."""
79
+ repo = repo_slug(_git_remote())
80
+ if not repo:
81
+ raise fail("Pass the app's domain, or run this in its repo folder.")
82
+ apps = self.get("/v1/apps")
83
+ matches = [a for a in apps if repo_slug(a.get("repo") or "") == repo]
84
+ if len(matches) == 1:
85
+ return matches[0]
86
+ if not matches:
87
+ raise fail(f"No app deploys from [bold]{repo}[/bold]. Pass the app's domain.")
88
+ domains = ", ".join(a["domain"] for a in matches)
89
+ raise fail(f"[bold]{repo}[/bold] deploys to more than one app ({domains}). Pass the one you mean.")
90
+
71
91
  def resolve_app(self, name: str) -> dict:
72
92
  """Match an app by exact domain, else unambiguous substring."""
73
93
  apps = self.get("/v1/apps")
@@ -82,3 +102,29 @@ class Api:
82
102
  raise fail(f"No app matches [bold]{name}[/bold]. Your apps: {known}")
83
103
  ambiguous = ", ".join(a["domain"] for a in matches)
84
104
  raise fail(f"[bold]{name}[/bold] is ambiguous: {ambiguous}")
105
+
106
+
107
+ def _git_remote() -> str:
108
+ """This folder's git remote URL (origin), or empty outside a repo."""
109
+ import subprocess
110
+
111
+ try:
112
+ out = subprocess.run(
113
+ ["git", "remote", "get-url", "origin"],
114
+ capture_output=True, text=True, timeout=5,
115
+ )
116
+ except (OSError, subprocess.TimeoutExpired):
117
+ return ""
118
+ return out.stdout.strip() if out.returncode == 0 else ""
119
+
120
+
121
+ def repo_slug(url: str) -> str:
122
+ """owner/repo from any form of a repo's address: git@host:owner/repo.git,
123
+ https://host/owner/repo, or a bare owner/repo. Lowercased, for matching."""
124
+ path = url.strip().removesuffix("/").removesuffix(".git")
125
+ if "://" in path:
126
+ path = path.split("://", 1)[1].split("/", 1)[-1]
127
+ elif "@" in path and ":" in path:
128
+ path = path.split(":", 1)[1]
129
+ parts = [p for p in path.split("/") if p]
130
+ return "/".join(parts[-2:]).lower() if len(parts) >= 2 else ""
File without changes
File without changes