sweatstack-cli 0.15.0__py3-none-any.whl → 0.17.0__py3-none-any.whl

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.
Files changed (30) hide show
  1. sweatstack_cli/api/client.py +9 -0
  2. sweatstack_cli/commands/tool.py +439 -0
  3. sweatstack_cli/config.py +3 -0
  4. sweatstack_cli/exceptions.py +4 -0
  5. sweatstack_cli/main.py +2 -1
  6. sweatstack_cli/project.py +44 -5
  7. sweatstack_cli/templates/tool/index.html +353 -0
  8. sweatstack_cli/templates/tool/vendor/duckdb.mjs +12652 -0
  9. sweatstack_cli/templates/tool/vendor/licenses/apache-arrow.txt +2261 -0
  10. sweatstack_cli/templates/tool/vendor/licenses/duckdb-wasm.txt +7 -0
  11. sweatstack_cli/templates/tool/vendor/licenses/uplot.txt +21 -0
  12. sweatstack_cli/templates/tool/vendor/sweatstack.js +44 -0
  13. sweatstack_cli/templates/tool/vendor/uPlot.iife.min-1.6.31.js +2 -0
  14. sweatstack_cli/templates/tool/vendor/uPlot.min-1.6.31.css +1 -0
  15. sweatstack_cli/templates/tool/vendor.json +7 -0
  16. sweatstack_cli/tools/__init__.py +1 -0
  17. sweatstack_cli/tools/check.py +184 -0
  18. sweatstack_cli/tools/content_types.json +55 -0
  19. sweatstack_cli/tools/deploy.py +174 -0
  20. sweatstack_cli/tools/policy.json +26 -0
  21. sweatstack_cli/tools/policy.py +155 -0
  22. sweatstack_cli/tools/rewrite.py +111 -0
  23. sweatstack_cli/tools/server.py +210 -0
  24. sweatstack_cli/tools/signin.py +468 -0
  25. sweatstack_cli/tools/template.py +110 -0
  26. {sweatstack_cli-0.15.0.dist-info → sweatstack_cli-0.17.0.dist-info}/METADATA +1 -1
  27. sweatstack_cli-0.17.0.dist-info/RECORD +47 -0
  28. sweatstack_cli-0.15.0.dist-info/RECORD +0 -27
  29. {sweatstack_cli-0.15.0.dist-info → sweatstack_cli-0.17.0.dist-info}/WHEEL +0 -0
  30. {sweatstack_cli-0.15.0.dist-info → sweatstack_cli-0.17.0.dist-info}/entry_points.txt +0 -0
@@ -172,6 +172,7 @@ class APIClient:
172
172
  status_code=response.status_code,
173
173
  code=code,
174
174
  detail=detail,
175
+ body=self._json_object(response),
175
176
  )
176
177
 
177
178
  # Handle empty responses
@@ -181,6 +182,14 @@ class APIClient:
181
182
  result: dict[str, Any] = response.json()
182
183
  return result
183
184
 
185
+ @staticmethod
186
+ def _json_object(response: httpx.Response) -> dict[str, object] | None:
187
+ try:
188
+ data = response.json()
189
+ except ValueError:
190
+ return None
191
+ return data if isinstance(data, dict) else None
192
+
184
193
  def _extract_error(self, response: httpx.Response) -> tuple[str, str | None]:
185
194
  """Extract the human-readable detail and optional machine-readable code.
186
195
 
@@ -0,0 +1,439 @@
1
+ """Tool commands: create a tool, serve and check it locally under the SweatStack Tools policy,
2
+ deploy it, roll it back and publish it. See plans/developer-kit/cli.md in sweatstack-tools.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import socket
8
+ import sys
9
+ from collections.abc import Iterator
10
+ from contextlib import contextmanager
11
+ from datetime import datetime
12
+ from pathlib import Path
13
+ from typing import Any, cast
14
+
15
+ import typer
16
+ from rich.progress import BarColumn, MofNCompleteColumn, Progress, SpinnerColumn, TextColumn
17
+
18
+ from sweatstack_cli.api import APIClient
19
+ from sweatstack_cli.config import get_settings
20
+ from sweatstack_cli.console import console
21
+ from sweatstack_cli.exceptions import APIError, AuthenticationError
22
+ from sweatstack_cli.project import CONFIG_FILENAME, ProjectConfig, ToolConfig, write_config
23
+ from sweatstack_cli.tools.check import REMOVED_KINDS, Finding, check_folder
24
+ from sweatstack_cli.tools.deploy import DeployError, collect
25
+ from sweatstack_cli.tools.deploy import deploy as deploy_files
26
+ from sweatstack_cli.tools.policy import Policy, load_policy
27
+ from sweatstack_cli.tools.server import make_server
28
+ from sweatstack_cli.tools.signin import SignIn
29
+ from sweatstack_cli.tools.template import DownloadError, scaffold
30
+
31
+ DOCS_DEPENDENCIES = "https://docs.sweatstack.no/learn/sweatstack-tools/dependencies/"
32
+
33
+ app = typer.Typer(
34
+ name="tool",
35
+ help="Build tools for SweatStack Tools: create, serve, check, deploy and publish them.",
36
+ no_args_is_help=True,
37
+ )
38
+
39
+
40
+ def _directory(directory: Path) -> Path:
41
+ if not directory.is_dir():
42
+ console.print(f"[red]Error:[/red] '{directory}' is not a directory.")
43
+ raise typer.Exit(1)
44
+ return directory.resolve()
45
+
46
+
47
+ def _policy() -> Policy:
48
+ policy = load_policy()
49
+ if policy.source == "cached":
50
+ console.print(
51
+ "[yellow]sweatstack.tools is unreachable: using the policy from the last run.[/yellow]"
52
+ )
53
+ elif policy.source == "built-in":
54
+ console.print(
55
+ "[yellow]sweatstack.tools is unreachable: using the policy this CLI shipped with.[/yellow]"
56
+ )
57
+ return policy
58
+
59
+
60
+ def _free_port(start: int, attempts: int = 100) -> int:
61
+ for port in range(start, start + attempts):
62
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:
63
+ try:
64
+ probe.bind(("localhost", port))
65
+ return port
66
+ except OSError:
67
+ continue
68
+ console.print(f"[red]Error:[/red] No free port from {start} to {start + attempts - 1}.")
69
+ raise typer.Exit(1)
70
+
71
+
72
+ @app.command()
73
+ def serve(
74
+ directory: Path | None = typer.Argument(
75
+ None, help="The tool's folder. From sweatstack.toml, or the current folder."
76
+ ),
77
+ port: int | None = typer.Option(
78
+ None, "--port", "-p", help="Port to serve on. The first free one from 8000 by default."
79
+ ),
80
+ slug: str | None = typer.Option(
81
+ None, "--slug", help="The tool's slug. From sweatstack.toml, or 'local'."
82
+ ),
83
+ ) -> None:
84
+ """Serve a tool locally, with the same network policy and sign-in as SweatStack Tools.
85
+
86
+ A tool in sweatstack.toml that declares data scopes signs in as it does on SweatStack Tools.
87
+ """
88
+ project = ProjectConfig.load()
89
+ tool = project.tool if project else None
90
+ root = _directory(directory or Path(tool.directory if tool and tool.directory else "."))
91
+ chosen_slug = slug or (tool.slug if tool and tool.slug else None) or "local"
92
+ sign_in = (
93
+ SignIn.for_tool(project.app.client_id, tool.scopes, get_settings().api_url)
94
+ if project and tool and tool.slug
95
+ else None
96
+ )
97
+ policy = _policy()
98
+ chosen = port if port is not None else _free_port(8000)
99
+ try:
100
+ server = make_server(root, policy, slug=chosen_slug, port=chosen, sign_in=sign_in)
101
+ except OSError as error:
102
+ console.print(f"[red]Error:[/red] Cannot serve on port {chosen}: {error.strerror}.")
103
+ raise typer.Exit(1)
104
+ console.print(
105
+ "Serving with the SweatStack Tools network policy: requests to other hosts are blocked, "
106
+ "as they will be when deployed. Blocked requests show in the browser console."
107
+ )
108
+ if sign_in:
109
+ console.print(
110
+ "Signing in as SweatStack Tools does, with the scopes in sweatstack.toml. "
111
+ "Use Chrome or Firefox: Safari keeps no sign-in cookie on http://localhost."
112
+ )
113
+ console.print(f" [cyan]{server.origin}[/cyan] ({root})")
114
+ try:
115
+ server.serve_forever()
116
+ except KeyboardInterrupt:
117
+ pass
118
+ finally:
119
+ server.server_close()
120
+
121
+
122
+ def say(text: str = "", *, highlight: bool = True) -> None:
123
+ """Print one line without wrapping."""
124
+ console.print(text, soft_wrap=True, highlight=highlight)
125
+
126
+
127
+ def print_findings(findings: list[Finding], directory: Path) -> None:
128
+ """The check's report, written for a person and for an agent: what, where, and the fix.
129
+
130
+ Lines never wrap, so each finding stays on one line with its whole URL, at any terminal width.
131
+ """
132
+ blocked = [f for f in findings if f.kind not in REMOVED_KINDS]
133
+ removed = [f for f in findings if f.kind in REMOVED_KINDS]
134
+ if blocked:
135
+ files = len({f.file for f in blocked})
136
+ say(
137
+ f"[red]✗[/red] {len(blocked)} load{'s' if len(blocked) != 1 else ''} in {files} "
138
+ f"file{'s' if files != 1 else ''} would be blocked on SweatStack Tools"
139
+ )
140
+ say()
141
+ width = max(len(f"{f.file}:{f.line}") for f in blocked)
142
+ kind_width = max(len(f.kind) for f in blocked)
143
+ for f in blocked:
144
+ say(
145
+ f" {f'{f.file}:{f.line}':<{width}} {f.kind:<{kind_width}} {f.url}",
146
+ highlight=False,
147
+ )
148
+ say()
149
+ say(" Tools can load only their own files and the SweatStack API.")
150
+ say(
151
+ " Download these files into your tool (for example into vendor/) and use relative paths."
152
+ )
153
+ say(f" How, including DuckDB and Pyodide: {DOCS_DEPENDENCIES}")
154
+ if removed:
155
+ if blocked:
156
+ say()
157
+ say(
158
+ f"[yellow]![/yellow] {len(removed)} element{'s' if len(removed) != 1 else ''} SweatStack Tools removes, so they do nothing there:"
159
+ )
160
+ say()
161
+ width = max(len(f"{f.file}:{f.line}") for f in removed)
162
+ for f in removed:
163
+ say(f" {f'{f.file}:{f.line}':<{width}} {f.kind} {f.url}", highlight=False)
164
+ say()
165
+ say(
166
+ " Speculation rules, preconnect and DNS prefetch are not available in SweatStack Tools."
167
+ )
168
+ if not findings:
169
+ say(f"[green]✓[/green] Nothing in {directory} loads from another site.")
170
+
171
+
172
+ @app.command()
173
+ def check(
174
+ directory: Path = typer.Argument(Path("."), help="The tool's folder."),
175
+ ) -> None:
176
+ """Check a tool for files it would load from other sites, which SweatStack Tools blocks.
177
+
178
+ Exits with 1 when anything would be blocked, so an agent's loop treats it as a failure to fix.
179
+ """
180
+ root = _directory(directory)
181
+ policy = _policy()
182
+ findings = check_folder(root, policy.load_origins())
183
+ print_findings(findings, directory)
184
+ if any(f.kind not in REMOVED_KINDS for f in findings):
185
+ raise typer.Exit(1)
186
+
187
+
188
+ # ---------------------------------------------------------------- the tool API
189
+
190
+ DEFAULT_SCOPES = ("activities:read",)
191
+
192
+
193
+ def _is_interactive() -> bool:
194
+ return sys.stdin.isatty()
195
+
196
+
197
+ @contextmanager
198
+ def _api() -> Iterator[APIClient]:
199
+ """An authenticated client. Any API error ends the command with its message."""
200
+ try:
201
+ yield APIClient()
202
+ except AuthenticationError as error:
203
+ console.print(f"[red]Error:[/red] {error}")
204
+ raise typer.Exit(2)
205
+ except APIError as error:
206
+ console.print(f"[red]Error:[/red] {error.detail or error}")
207
+ raise typer.Exit(3)
208
+
209
+
210
+ def _ask(value: str | None, prompt: str, option: str, default: str | None = None) -> str:
211
+ """An option's value, or a prompt for it. Without a terminal, a missing option is an error."""
212
+ if value:
213
+ return value
214
+ if not _is_interactive():
215
+ console.print(f"[red]Error:[/red] {option} is required when not running interactively.")
216
+ raise typer.Exit(1)
217
+ answer: str = typer.prompt(prompt, default=default)
218
+ return answer.strip()
219
+
220
+
221
+ def _project_tool() -> tuple[ProjectConfig, ToolConfig, str]:
222
+ project = ProjectConfig.load()
223
+ if not project or not project.tool.slug:
224
+ console.print(
225
+ f"[red]Error:[/red] No tool in {CONFIG_FILENAME} here. Run 'sweatstack tool create' first."
226
+ )
227
+ raise typer.Exit(1)
228
+ return project, project.tool, project.tool.slug
229
+
230
+
231
+ def _ensure_author(
232
+ client: APIClient, name: str, handle: str | None, public_name: str | None
233
+ ) -> str:
234
+ """The developer's handle, chosen now if this is their first tool."""
235
+ try:
236
+ return str(client.get("/api/v1/tools/author")["handle"])
237
+ except APIError as error:
238
+ if error.status_code != 404:
239
+ raise
240
+ console.print(
241
+ "Your first tool. Choose your handle: it is part of every tool's address, and cannot change."
242
+ )
243
+ handle = _ask(handle, "Handle (3 to 20 lowercase letters and digits)", "--handle")
244
+ public_name = _ask(public_name, "Public name, shown with your tools", "--public-name")
245
+ if _is_interactive():
246
+ typer.confirm(
247
+ f"Your tools will be at {name}-{handle}.sweatstack.tools. Continue?",
248
+ abort=True,
249
+ default=True,
250
+ )
251
+ return str(
252
+ client.put("/api/v1/tools/author", json={"handle": handle, "public_name": public_name})[
253
+ "handle"
254
+ ]
255
+ )
256
+
257
+
258
+ @app.command()
259
+ def create(
260
+ name: str | None = typer.Option(
261
+ None, "--name", help="The address part, such as power-duration. Fixed for good."
262
+ ),
263
+ title: str | None = typer.Option(
264
+ None, "--title", help="What people read, such as 'Power duration'."
265
+ ),
266
+ description: str | None = typer.Option(
267
+ None, "--description", help="One sentence on what the tool does."
268
+ ),
269
+ scopes: list[str] = typer.Option(
270
+ list(DEFAULT_SCOPES), "--scope", help="A scope the tool may ever get. Repeat for more."
271
+ ),
272
+ directory: Path = typer.Option(
273
+ Path("public"), "--dir", help="The tool's folder, scaffolded from the template."
274
+ ),
275
+ handle: str | None = typer.Option(None, "--handle", help="Your handle, on your first tool."),
276
+ public_name: str | None = typer.Option(
277
+ None, "--public-name", help="Your public name, on your first tool."
278
+ ),
279
+ force: bool = typer.Option(
280
+ False, "--force", help=f"Overwrite {CONFIG_FILENAME} and the template's files."
281
+ ),
282
+ ) -> None:
283
+ """Create a private tool, write sweatstack.toml, and scaffold the template.
284
+
285
+ The template signs in through SweatStack Tools and plots your latest activity. Run
286
+ 'sweatstack tool serve' to try it, and 'sweatstack tool deploy' to put it online.
287
+ """
288
+ config = Path(CONFIG_FILENAME)
289
+ if config.exists() and not force:
290
+ console.print(
291
+ f"[red]Error:[/red] {CONFIG_FILENAME} exists here. Use --force to replace it."
292
+ )
293
+ raise typer.Exit(1)
294
+ if directory.exists() and any(directory.iterdir()) and not force:
295
+ console.print(
296
+ f"[red]Error:[/red] {directory} is not empty. Use --force to write the template into it."
297
+ )
298
+ raise typer.Exit(1)
299
+
300
+ name = _ask(name, "Name, the address part (such as power-duration)", "--name")
301
+ title = _ask(title, "Title", "--title", default=name.replace("-", " ").capitalize())
302
+ description = _ask(description, "Description, one sentence", "--description")
303
+
304
+ with _api() as client:
305
+ handle = _ensure_author(client, name, handle, public_name)
306
+ # The template first: a failed download then leaves nothing behind on SweatStack.
307
+ with console.status("Writing the template, and downloading DuckDB-WASM..."):
308
+ try:
309
+ scaffold(directory, title=title)
310
+ except DownloadError as error:
311
+ console.print(f"[red]Error:[/red] {error}")
312
+ raise typer.Exit(1)
313
+ tool = client.post(
314
+ "/api/v1/tools",
315
+ json={"name": name, "title": title, "description": description, "scopes": scopes},
316
+ )
317
+
318
+ write_config(
319
+ config,
320
+ app_name=tool["title"],
321
+ client_id=tool["client_id"],
322
+ tool=ToolConfig(
323
+ slug=tool["slug"], directory=directory.as_posix(), scopes=tuple(tool["scopes"])
324
+ ),
325
+ )
326
+ console.print(
327
+ f"[green]✓[/green] Created [bold]{tool['slug']}[/bold], private: only you can open it."
328
+ )
329
+ console.print(f" Address: {tool['url']}")
330
+ console.print(f" Folder: {directory} (written to {CONFIG_FILENAME})")
331
+ console.print()
332
+ console.print("Next: 'sweatstack tool serve' to try it here, then 'sweatstack tool deploy'.")
333
+
334
+
335
+ @app.command()
336
+ def deploy(
337
+ allow_external: bool = typer.Option(
338
+ False,
339
+ "--allow-external",
340
+ help="Deploy even when files load from other sites, which will fail.",
341
+ ),
342
+ ) -> None:
343
+ """Deploy the tool in sweatstack.toml: check it, upload what changed, and make it current."""
344
+ _, tool, slug = _project_tool()
345
+ root = _directory(Path(tool.directory or "."))
346
+ findings = check_folder(root, _policy().load_origins())
347
+ if any(f.kind not in REMOVED_KINDS for f in findings):
348
+ print_findings(findings, root)
349
+ if not allow_external:
350
+ say()
351
+ say(
352
+ " Deploy anyway with --allow-external (these requests will fail for every visitor)."
353
+ )
354
+ raise typer.Exit(1)
355
+ try:
356
+ files = collect(root)
357
+ except DeployError as error:
358
+ console.print(f"[red]Error:[/red] {error}")
359
+ raise typer.Exit(1)
360
+
361
+ with (
362
+ _api() as client,
363
+ Progress(
364
+ SpinnerColumn(),
365
+ TextColumn("Uploading"),
366
+ BarColumn(),
367
+ MofNCompleteColumn(),
368
+ console=console,
369
+ transient=True,
370
+ ) as progress,
371
+ ):
372
+ task = progress.add_task("upload", total=None)
373
+ uploaded = 0
374
+
375
+ def on_upload(_: object) -> None:
376
+ nonlocal uploaded
377
+ uploaded += 1
378
+ progress.update(task, completed=uploaded)
379
+
380
+ try:
381
+ result: dict[str, Any] = deploy_files(client, slug, files, on_upload=on_upload)
382
+ except DeployError as error:
383
+ console.print(f"[red]Error:[/red] {error}")
384
+ raise typer.Exit(1)
385
+ console.print(
386
+ f"[green]✓[/green] Deployed [bold]{slug}[/bold]: {len(files)} files, {uploaded} uploaded."
387
+ )
388
+ console.print(f" {result['url']}")
389
+ for warning in result.get("warnings", []):
390
+ say(f"[yellow]![/yellow] {warning}")
391
+
392
+
393
+ @app.command()
394
+ def deploys() -> None:
395
+ """List the kept deploys of the tool in sweatstack.toml, newest first, for 'tool rollback'."""
396
+ _, _, slug = _project_tool()
397
+ with _api() as client:
398
+ kept = cast(list[dict[str, Any]], client.get(f"/api/v1/tools/{slug}/deploys"))
399
+ if not kept:
400
+ say(f"{slug} has no deploys yet. Run 'sweatstack tool deploy'.")
401
+ return
402
+ for item in kept:
403
+ created = datetime.fromisoformat(item["created_at"]).astimezone()
404
+ notes = [n for n, on in (("serving", item["current"]), ("flagged", item["flagged"])) if on]
405
+ say(f"{item['id']} {created:%Y-%m-%d %H:%M} {', '.join(notes)}".rstrip(), highlight=False)
406
+
407
+
408
+ @app.command()
409
+ def rollback(
410
+ deploy_id: str | None = typer.Argument(
411
+ None,
412
+ help="The deploy to serve again, from 'sweatstack tool deploys'. The previous one by default.",
413
+ ),
414
+ ) -> None:
415
+ """Serve an earlier deploy of the tool in sweatstack.toml again."""
416
+ _, _, slug = _project_tool()
417
+ with _api() as client:
418
+ tool = client.post(f"/api/v1/tools/{slug}/rollback", json={"deploy_id": deploy_id})
419
+ current = (tool.get("current_deploy") or {}).get("id", "?")
420
+ console.print(f"[green]✓[/green] {slug} serves deploy {current} again.")
421
+
422
+
423
+ @app.command()
424
+ def publish(
425
+ unlisted: bool = typer.Option(
426
+ False, "--unlisted", help="Anyone with the link, but not in the catalogue."
427
+ ),
428
+ ) -> None:
429
+ """Open the tool in sweatstack.toml to everyone, in the catalogue, or with --unlisted to anyone with the link."""
430
+ _, _, slug = _project_tool()
431
+ access = "unlisted" if unlisted else "listed"
432
+ with _api() as client:
433
+ tool = client.put(f"/api/v1/tools/{slug}/access", json={"access": access})
434
+ console.print(f"[green]✓[/green] {slug} is {tool['access']}: {tool['url']}")
435
+ missing = [item["label"] for item in tool.get("go_live_missing") or []]
436
+ if missing:
437
+ console.print("[yellow]Before anyone else can sign in:[/yellow]")
438
+ for label in missing:
439
+ say(f" - {label}", highlight=False)
sweatstack_cli/config.py CHANGED
@@ -7,6 +7,7 @@ from dataclasses import dataclass
7
7
  from functools import cache
8
8
 
9
9
  DEFAULT_API_URL = "https://app.sweatstack.no"
10
+ DEFAULT_TOOLS_URL = "https://sweatstack.tools"
10
11
 
11
12
 
12
13
  @dataclass(frozen=True, slots=True)
@@ -14,6 +15,7 @@ class Settings:
14
15
  """Immutable application settings."""
15
16
 
16
17
  api_url: str
18
+ tools_url: str
17
19
  version: str
18
20
 
19
21
 
@@ -28,5 +30,6 @@ def get_settings() -> Settings:
28
30
 
29
31
  return Settings(
30
32
  api_url=os.environ.get("SWEATSTACK_URL", DEFAULT_API_URL).rstrip("/"),
33
+ tools_url=os.environ.get("SWEATSTACK_TOOLS_URL", DEFAULT_TOOLS_URL).rstrip("/"),
31
34
  version=__version__,
32
35
  )
@@ -59,11 +59,15 @@ class APIError(CLIError):
59
59
  code: str | None = None,
60
60
  detail: str | None = None,
61
61
  exit_code: int | None = None,
62
+ body: dict[str, object] | None = None,
62
63
  ) -> None:
63
64
  super().__init__(message, exit_code)
64
65
  self.status_code = status_code
65
66
  self.code = code
66
67
  self.detail = detail
68
+ #: The error response's JSON object, for an answer with more than a detail, such as the
69
+ #: files a tool deploy still needs (`missing`).
70
+ self.body = body or {}
67
71
 
68
72
 
69
73
  class ValidationError(CLIError):
sweatstack_cli/main.py CHANGED
@@ -6,7 +6,7 @@ import typer
6
6
 
7
7
  from sweatstack_cli import __version__
8
8
  from sweatstack_cli.commands import app as app_commands
9
- from sweatstack_cli.commands import auth, page
9
+ from sweatstack_cli.commands import auth, page, tool
10
10
  from sweatstack_cli.console import console
11
11
  from sweatstack_cli.exceptions import CLIError
12
12
  from sweatstack_cli.version_check import get_update_message
@@ -23,6 +23,7 @@ app = typer.Typer(
23
23
  # Register command groups
24
24
  app.add_typer(page.app, name="page")
25
25
  app.add_typer(app_commands.app, name="app")
26
+ app.add_typer(tool.app, name="tool")
26
27
 
27
28
  # Register top-level auth commands for convenience
28
29
  # These are the most common operations, so we promote them to top level
sweatstack_cli/project.py CHANGED
@@ -2,8 +2,9 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import json
5
6
  import tomllib
6
- from dataclasses import dataclass
7
+ from dataclasses import dataclass, field
7
8
  from pathlib import Path
8
9
 
9
10
  CONFIG_FILENAME = "sweatstack.toml"
@@ -25,12 +26,24 @@ class AppConfig:
25
26
  client_id: str | None = None
26
27
 
27
28
 
29
+ @dataclass
30
+ class ToolConfig:
31
+ """A tool on SweatStack Tools. Its OAuth client ID is `[app].client_id`, because a tool is an
32
+ application under the hood. `scopes` are the scopes it declares, which `tool serve` signs in
33
+ with, as SweatStack Tools does."""
34
+
35
+ slug: str | None = None
36
+ directory: str | None = None
37
+ scopes: tuple[str, ...] = ()
38
+
39
+
28
40
  @dataclass
29
41
  class ProjectConfig:
30
42
  """Project configuration from sweatstack.toml."""
31
43
 
32
44
  app: AppConfig
33
45
  page: PageConfig
46
+ tool: ToolConfig = field(default_factory=ToolConfig)
34
47
 
35
48
  @classmethod
36
49
  def load(cls, path: Path | None = None) -> ProjectConfig | None:
@@ -55,6 +68,10 @@ class ProjectConfig:
55
68
 
56
69
  app_data = data.get("app", {})
57
70
  page_data = data.get("page", {})
71
+ tool_data = data.get("tool", {})
72
+ scopes = tool_data.get("scopes", [])
73
+ if not isinstance(scopes, list) or not all(isinstance(scope, str) for scope in scopes):
74
+ scopes = []
58
75
 
59
76
  return cls(
60
77
  app=AppConfig(
@@ -65,6 +82,11 @@ class ProjectConfig:
65
82
  slug=page_data.get("slug"),
66
83
  directory=page_data.get("directory"),
67
84
  ),
85
+ tool=ToolConfig(
86
+ slug=tool_data.get("slug"),
87
+ directory=tool_data.get("directory"),
88
+ scopes=tuple(scopes),
89
+ ),
68
90
  )
69
91
 
70
92
 
@@ -75,6 +97,7 @@ def write_config(
75
97
  client_id: str | None = None,
76
98
  page_slug: str | None = None,
77
99
  page_directory: str | None = None,
100
+ tool: ToolConfig | None = None,
78
101
  ) -> Path:
79
102
  """
80
103
  Write sweatstack.toml file.
@@ -85,25 +108,38 @@ def write_config(
85
108
  client_id: OAuth2 client ID.
86
109
  page_slug: Page slug.
87
110
  page_directory: Page directory.
111
+ tool: The `[tool]` table, written when it has any value.
88
112
 
89
113
  Returns:
90
114
  Path to the written config file.
91
115
  """
92
116
  config_path = path or Path(CONFIG_FILENAME)
93
117
 
118
+ # Every value is written as a JSON string, which is a valid TOML basic string with any
119
+ # character escaped, so a name with a quote or a backslash cannot break the file.
94
120
  lines = ["[app]"]
95
121
  if app_name:
96
- lines.append(f'name = "{app_name}"')
122
+ lines.append(f"name = {json.dumps(app_name)}")
97
123
  if client_id:
98
- lines.append(f'client_id = "{client_id}"')
124
+ lines.append(f"client_id = {json.dumps(client_id)}")
99
125
 
100
126
  if page_slug or page_directory:
101
127
  lines.append("")
102
128
  lines.append("[page]")
103
129
  if page_slug:
104
- lines.append(f'slug = "{page_slug}"')
130
+ lines.append(f"slug = {json.dumps(page_slug)}")
105
131
  if page_directory:
106
- lines.append(f'directory = "{page_directory}"')
132
+ lines.append(f"directory = {json.dumps(page_directory)}")
133
+
134
+ if tool and (tool.slug or tool.directory or tool.scopes):
135
+ lines.append("")
136
+ lines.append("[tool]")
137
+ if tool.slug:
138
+ lines.append(f"slug = {json.dumps(tool.slug)}")
139
+ if tool.directory:
140
+ lines.append(f"directory = {json.dumps(tool.directory)}")
141
+ if tool.scopes:
142
+ lines.append(f"scopes = [{', '.join(json.dumps(scope) for scope in tool.scopes)}]")
107
143
 
108
144
  lines.append("") # Trailing newline
109
145
  config_path.write_text("\n".join(lines), encoding="utf-8")
@@ -136,10 +172,13 @@ def update_config(
136
172
  if page_directory is not None:
137
173
  page_data["directory"] = page_directory
138
174
 
175
+ existing = ProjectConfig.load(config_path)
139
176
  return write_config(
140
177
  path=config_path,
141
178
  app_name=app_data.get("name"),
142
179
  client_id=app_data.get("client_id"),
143
180
  page_slug=page_data.get("slug"),
144
181
  page_directory=page_data.get("directory"),
182
+ # A tool's table survives a Pages command.
183
+ tool=existing.tool if existing else None,
145
184
  )