sweatstack-cli 0.16.0__py3-none-any.whl → 0.17.1__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.
@@ -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
 
@@ -4,24 +4,29 @@ from __future__ import annotations
4
4
 
5
5
  import json
6
6
  import os
7
+ import re
7
8
  import time
8
9
  from dataclasses import dataclass
9
10
  from pathlib import Path
10
11
  from typing import Protocol
12
+ from urllib.parse import urlsplit
11
13
 
12
14
  import platformdirs
13
15
 
16
+ from sweatstack_cli.config import DEFAULT_API_URL, get_settings
14
17
 
15
- def get_tokens_path() -> Path:
18
+
19
+ def get_tokens_path(api_url: str | None = None) -> Path:
16
20
  """
17
- Get the path to the tokens file.
21
+ Get the path to the tokens file of the SweatStack at `api_url` (`SWEATSTACK_URL`'s by default).
18
22
 
19
- Uses platformdirs for OS-appropriate user data directory.
20
- This path is shared with the sweatstack Python library for
21
- seamless interoperability.
23
+ Uses platformdirs for OS-appropriate user data directory. Production's sign-in is
24
+ `tokens.json`, shared with the sweatstack Python library for seamless interoperability.
25
+ Any other SweatStack, such as staging, keeps its own file named after its host, so
26
+ signing in there never replaces the production sign-in.
22
27
 
23
28
  Returns:
24
- Path to tokens.json file.
29
+ Path to tokens.json, or tokens-{host}.json for another SweatStack.
25
30
 
26
31
  Platform-specific paths:
27
32
  - macOS: ~/Library/Application Support/SweatStack/tokens.json
@@ -29,7 +34,11 @@ def get_tokens_path() -> Path:
29
34
  - Windows: %APPDATA%\\SweatStack\\SweatStack\\tokens.json
30
35
  """
31
36
  data_dir = Path(platformdirs.user_data_dir("SweatStack", "SweatStack"))
32
- return data_dir / "tokens.json"
37
+ url = (api_url or get_settings().api_url).rstrip("/")
38
+ if url == DEFAULT_API_URL:
39
+ return data_dir / "tokens.json"
40
+ host = re.sub(r"[^A-Za-z0-9.-]", "-", urlsplit(url).netloc or url)
41
+ return data_dir / f"tokens-{host}.json"
33
42
 
34
43
 
35
44
  @dataclass(frozen=True, slots=True)
@@ -3,6 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  from datetime import datetime
6
+ from typing import Any
6
7
 
7
8
  import typer
8
9
 
@@ -10,7 +11,7 @@ from sweatstack_cli.api import APIClient
10
11
  from sweatstack_cli.auth import Authenticator
11
12
  from sweatstack_cli.auth.jwt import decode_jwt_payload
12
13
  from sweatstack_cli.console import console
13
- from sweatstack_cli.exceptions import APIError, AuthenticationError
14
+ from sweatstack_cli.exceptions import APIError, AuthenticationError, SecondFactorRequired
14
15
  from sweatstack_cli.version_check import check_for_update
15
16
 
16
17
 
@@ -92,18 +93,26 @@ def status() -> None:
92
93
  auth = Authenticator()
93
94
  tokens = auth.get_valid_tokens()
94
95
 
96
+ user: dict[str, Any] | None = None
97
+ if tokens is not None:
98
+ try:
99
+ user = APIClient(authenticator=auth).get("/api/v1/oauth/userinfo")
100
+ except SecondFactorRequired:
101
+ pass # A step-up is not a refusal of the sign-in.
102
+ except AuthenticationError:
103
+ # Stored tokens SweatStack refuses (revoked, or from another SweatStack) are no sign-in.
104
+ tokens = None
105
+ except APIError:
106
+ pass # SweatStack could not say who this is; the sign-in may still be good.
107
+
95
108
  if tokens is None:
96
109
  console.print("[red]✗[/red] Not authenticated")
97
110
  else:
98
111
  console.print("[green]✓[/green] Authenticated")
99
- try:
100
- client = APIClient(authenticator=auth)
101
- user = client.get("/api/v1/oauth/userinfo")
112
+ if user is not None:
102
113
  console.print(f" Name: {_display_name(user)}")
103
114
  console.print(f" Email: {user.get('email', 'unknown')}")
104
115
  console.print(f" ID: {user.get('sub', 'unknown')}")
105
- except (AuthenticationError, APIError):
106
- pass # Silently skip user info on error
107
116
  console.print(f" Passkey: {_confirmation(tokens.access_token)}")
108
117
 
109
118
  # Check version
@@ -1,26 +1,38 @@
1
- """Tool commands: serve a tool locally under the SweatStack Tools policy, and check it.
2
-
3
- `tool create`, `deploy`, `publish` and `rollback` follow when the SweatStack app's tool API exists.
4
- See plans/developer-kit/cli.md in sweatstack-tools.
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.
5
3
  """
6
4
 
7
5
  from __future__ import annotations
8
6
 
9
7
  import socket
8
+ import sys
9
+ from collections.abc import Iterator
10
+ from contextlib import contextmanager
11
+ from datetime import datetime
10
12
  from pathlib import Path
13
+ from typing import Any, cast
11
14
 
12
15
  import typer
16
+ from rich.progress import BarColumn, MofNCompleteColumn, Progress, SpinnerColumn, TextColumn
13
17
 
18
+ from sweatstack_cli.api import APIClient
19
+ from sweatstack_cli.config import get_settings
14
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
15
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
16
26
  from sweatstack_cli.tools.policy import Policy, load_policy
17
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
18
30
 
19
- DOCS_DEPENDENCIES = "https://docs.sweatstack.no/learn/tools/dependencies/"
31
+ DOCS_DEPENDENCIES = "https://docs.sweatstack.no/learn/sweatstack-tools/dependencies/"
20
32
 
21
33
  app = typer.Typer(
22
34
  name="tool",
23
- help="Build tools for SweatStack Tools: serve and check them locally.",
35
+ help="Build tools for SweatStack Tools: create, serve, check, deploy and publish them.",
24
36
  no_args_is_help=True,
25
37
  )
26
38
 
@@ -59,18 +71,33 @@ def _free_port(start: int, attempts: int = 100) -> int:
59
71
 
60
72
  @app.command()
61
73
  def serve(
62
- directory: Path = typer.Argument(Path("."), help="The tool's folder."),
74
+ directory: Path | None = typer.Argument(
75
+ None, help="The tool's folder. From sweatstack.toml, or the current folder."
76
+ ),
63
77
  port: int | None = typer.Option(
64
78
  None, "--port", "-p", help="Port to serve on. The first free one from 8000 by default."
65
79
  ),
66
- slug: str = typer.Option("local", "--slug", help="The tool's slug, for its report link."),
80
+ slug: str | None = typer.Option(
81
+ None, "--slug", help="The tool's slug. From sweatstack.toml, or 'local'."
82
+ ),
67
83
  ) -> None:
68
- """Serve a tool locally, with the same network policy as SweatStack Tools."""
69
- root = _directory(directory)
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
+ )
70
97
  policy = _policy()
71
98
  chosen = port if port is not None else _free_port(8000)
72
99
  try:
73
- server = make_server(root, policy, slug=slug, port=chosen)
100
+ server = make_server(root, policy, slug=chosen_slug, port=chosen, sign_in=sign_in)
74
101
  except OSError as error:
75
102
  console.print(f"[red]Error:[/red] Cannot serve on port {chosen}: {error.strerror}.")
76
103
  raise typer.Exit(1)
@@ -78,7 +105,12 @@ def serve(
78
105
  "Serving with the SweatStack Tools network policy: requests to other hosts are blocked, "
79
106
  "as they will be when deployed. Blocked requests show in the browser console."
80
107
  )
81
- console.print(f" [cyan]http://localhost:{chosen}[/cyan] ({root})")
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})")
82
114
  try:
83
115
  server.serve_forever()
84
116
  except KeyboardInterrupt:
@@ -151,3 +183,257 @@ def check(
151
183
  print_findings(findings, directory)
152
184
  if any(f.kind not in REMOVED_KINDS for f in findings):
153
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)
@@ -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/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
  )