pywa-cloud-cli 0.1.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.
@@ -0,0 +1,497 @@
1
+ """A thin HTTP client for the Pywa Cloud API. It wraps requests and decides nothing itself; `http_client` lets
2
+ tests pass in their own `httpx.Client`."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import os
7
+ import platform
8
+ import sys
9
+ import time
10
+ from collections.abc import Callable
11
+ from typing import Any
12
+ from urllib.parse import quote
13
+
14
+ import httpx
15
+
16
+ # Marks "argument not passed", as opposed to an explicit None. Typed `Any` so it fits any optional parameter.
17
+ _UNSET: Any = object()
18
+
19
+
20
+ # Uploading a project can take a while on a slow connection, and the reply may wait on a long build.
21
+ _DEPLOY_TIMEOUT = httpx.Timeout(120.0, read=1500.0)
22
+ # A deploy is started and then followed by polling, so no single request has to stay open for long.
23
+ _POLL_S = 2.0
24
+ _BUILD_GIVE_UP_S = 30 * 60.0
25
+ _MAX_RETRY_WAIT_S = 30
26
+ _MAX_LOST_POLLS = (
27
+ 5 # consecutive failed status checks tolerated while following a build
28
+ )
29
+
30
+
31
+ def _q(value: object) -> str:
32
+ """A value placed in a URL path: `a/b?c` must stay one segment, not become a different route."""
33
+ return quote(str(value), safe="")
34
+
35
+
36
+ def _format_detail(detail: Any) -> str:
37
+ """FastAPI answers a rejected request body with a list of `{loc, msg, ...}` dicts: show "field: problem" instead
38
+ of the Python list."""
39
+ if (
40
+ isinstance(detail, list)
41
+ and detail
42
+ and all(isinstance(item, dict) and "msg" in item for item in detail)
43
+ ):
44
+ problems = []
45
+ for item in detail:
46
+ where = ".".join(
47
+ str(part)
48
+ for part in item.get("loc", ())
49
+ if part not in ("body", "query", "path")
50
+ )
51
+ problems.append(f"{where}: {item['msg']}" if where else str(item["msg"]))
52
+ return "; ".join(problems)
53
+ return str(detail)
54
+
55
+
56
+ def _retry_after(resp: httpx.Response) -> int | None:
57
+ """Seconds from a `Retry-After` header, if it is a plain positive number."""
58
+ value = resp.headers.get("retry-after", "")
59
+ return int(value) if value.isdigit() and int(value) > 0 else None
60
+
61
+
62
+ class ApiError(Exception):
63
+ def __init__(
64
+ self,
65
+ status_code: int,
66
+ detail: Any,
67
+ request_id: str | None = None,
68
+ retry_after: int | None = None,
69
+ ):
70
+ self.status_code = status_code
71
+ self.request_id = request_id
72
+ self.retry_after = retry_after
73
+ self.detail = (
74
+ detail # usually a str; a dict for endpoints that return structured errors
75
+ )
76
+ # Status 0 means no HTTP response arrived (connection failure); it is not shown as a number.
77
+ message = (
78
+ _format_detail(detail)
79
+ if status_code == 0
80
+ else f"{status_code}: {_format_detail(detail)}"
81
+ )
82
+ if status_code == 403 and detail == "Insufficient team role":
83
+ message += (
84
+ " - this needs the team owner or admin role; "
85
+ "ask one to run it or to change your role"
86
+ )
87
+ if status_code >= 500 and request_id:
88
+ message += f" (reference: {request_id})"
89
+ if status_code == 429 and retry_after:
90
+ message += (
91
+ f" - try again in {retry_after} second{'' if retry_after == 1 else 's'}"
92
+ )
93
+ super().__init__(message)
94
+
95
+
96
+ class DeployFailed(ApiError):
97
+ def __init__(
98
+ self,
99
+ deployment_id: str,
100
+ build_log: str,
101
+ reason: str | None = None,
102
+ stage: str | None = None,
103
+ ):
104
+ self.deployment_id = deployment_id
105
+ self.build_log = build_log
106
+ self.reason = reason # the cause, when the server sent it
107
+ self.stage = (
108
+ stage # where it stopped: preparing | building | validating | starting
109
+ )
110
+ super().__init__(422, f"deployment {deployment_id} failed")
111
+
112
+
113
+ def identity_headers() -> dict[str, str]:
114
+ """Tell the server which tool, version and platform made each call: it goes into the audit log next to the IP
115
+ (`X-Pywa-Client: cli/0.1.0; os=darwin; ci=github-actions`). The server also learns the tool from the login token;
116
+ this header adds the version, the OS and the CI provider."""
117
+ from pywa_cloud_cli import __version__
118
+
119
+ parts = [f"cli/{__version__}", f"os={platform.system().lower() or 'unknown'}"]
120
+ if os.environ.get("GITHUB_ACTIONS") == "true":
121
+ parts.append("ci=github-actions")
122
+ elif os.environ.get("GITLAB_CI"):
123
+ parts.append("ci=gitlab-ci")
124
+ elif os.environ.get("CI"):
125
+ parts.append("ci=other")
126
+ return {
127
+ "X-Pywa-Client": "; ".join(parts),
128
+ "User-Agent": f"pywa-cloud-cli/{__version__}",
129
+ }
130
+
131
+
132
+ _upgrade_notice_shown = False
133
+
134
+
135
+ def _note_upgrade(resp: httpx.Response) -> None:
136
+ """The server sends `X-Pywa-Upgrade: <version>` when this CLI is older than it recommends. Say so once per run, on
137
+ stderr so scripts reading stdout are unaffected."""
138
+ global _upgrade_notice_shown
139
+ target = resp.headers.get("x-pywa-upgrade")
140
+ if target and not _upgrade_notice_shown:
141
+ _upgrade_notice_shown = True
142
+ print( # noqa: T201
143
+ f"A newer pywa-cloud-cli ({target}) is available: pip install -U pywa-cloud-cli",
144
+ file=sys.stderr,
145
+ )
146
+
147
+
148
+ class PywaCloudClient:
149
+ def __init__(
150
+ self,
151
+ base_url: str,
152
+ token: str | None = None,
153
+ http_client: httpx.Client | None = None,
154
+ ):
155
+ headers = {
156
+ **identity_headers(),
157
+ **({"Authorization": f"Bearer {token}"} if token else {}),
158
+ }
159
+ if http_client is not None:
160
+ self._http = http_client
161
+ self._http.headers.update(headers)
162
+ else:
163
+ # Generous: some requests (connecting a number) make the server wait on several Meta calls.
164
+ self._http = httpx.Client(base_url=base_url, headers=headers, timeout=120.0)
165
+
166
+ def close(self) -> None:
167
+ self._http.close()
168
+
169
+ def __enter__(self) -> PywaCloudClient:
170
+ return self
171
+
172
+ def __exit__(self, *exc_info: object) -> None:
173
+ self.close()
174
+
175
+ def _request(
176
+ self, method: str, path: str, _retried: bool = False, **kwargs: Any
177
+ ) -> httpx.Response:
178
+ try:
179
+ resp = self._http.request(method, path, **kwargs)
180
+ except httpx.ConnectError as e:
181
+ raise ApiError(
182
+ 0, f"Could not reach Pywa Cloud at {self._http.base_url}"
183
+ ) from e
184
+ except httpx.TimeoutException as e:
185
+ raise ApiError(
186
+ 0,
187
+ "Pywa Cloud took too long to answer. What you asked for may still be running: "
188
+ "check again in a moment before repeating it.",
189
+ ) from e
190
+ except httpx.HTTPError as e:
191
+ raise ApiError(
192
+ 0,
193
+ f"The connection to Pywa Cloud at {self._http.base_url} failed ({type(e).__name__})",
194
+ ) from e
195
+ _note_upgrade(resp)
196
+ if resp.status_code == 429 and not _retried:
197
+ # Rate limited and told when to come back: wait once, if briefly, and repeat the call. A request with a
198
+ # streamed body cannot be repeated.
199
+ wait = _retry_after(resp)
200
+ if (
201
+ wait is not None
202
+ and wait <= _MAX_RETRY_WAIT_S
203
+ and not {"files", "content", "data"} & kwargs.keys()
204
+ ):
205
+ time.sleep(wait)
206
+ return self._request(method, path, _retried=True, **kwargs)
207
+ if resp.status_code >= 400:
208
+ try:
209
+ body = resp.json()
210
+ detail = (
211
+ body.get("detail", resp.text)
212
+ if isinstance(body, dict)
213
+ else resp.text
214
+ )
215
+ except ValueError:
216
+ detail = resp.text
217
+ raise ApiError(
218
+ resp.status_code,
219
+ detail,
220
+ resp.headers.get("x-request-id"),
221
+ _retry_after(resp),
222
+ )
223
+ return resp
224
+
225
+ def logout(self) -> None:
226
+ """Revokes this client's own token server-side (a no-op for a token that's already
227
+ expired or isn't a login JWT, e.g. a deploy token)."""
228
+ self._request("POST", "/auth/logout")
229
+
230
+ def whoami(self) -> dict:
231
+ return self._request("GET", "/whoami").json()
232
+
233
+ def start_device_login(self) -> dict:
234
+ return self._request("POST", "/auth/device/code").json()
235
+
236
+ def poll_device_token(self, device_code: str) -> dict | None:
237
+ """Returns None while the user hasn't confirmed the code yet (not an error - the CLI is
238
+ expected to call this repeatedly at the server-supplied interval until it gets a result
239
+ or the code expires)."""
240
+ try:
241
+ return self._request(
242
+ "POST", "/auth/device/token", json={"device_code": device_code}
243
+ ).json()
244
+ except ApiError as e:
245
+ if (
246
+ isinstance(e.detail, dict)
247
+ and e.detail.get("error") == "authorization_pending"
248
+ ):
249
+ return None
250
+ raise
251
+
252
+ def create_bot(
253
+ self,
254
+ name: str,
255
+ entrypoint_override: str | None = None,
256
+ bot_directory: str | None = None,
257
+ ) -> dict:
258
+ body: dict = {"name": name}
259
+ if entrypoint_override:
260
+ body["entrypoint_override"] = entrypoint_override
261
+ if bot_directory:
262
+ body["bot_directory"] = bot_directory
263
+ return self._request("POST", "/bots", json=body).json()
264
+
265
+ def list_bots(self) -> list[dict]:
266
+ return self._request("GET", "/bots").json()
267
+
268
+ def get_bot(self, bot_id: str) -> dict:
269
+ return self._request("GET", f"/bots/{_q(bot_id)}").json()
270
+
271
+ def update_bot(
272
+ self,
273
+ bot_id: str,
274
+ entrypoint_override: str | None = _UNSET,
275
+ bot_directory: str | None = _UNSET,
276
+ ) -> dict:
277
+ """A genuinely partial PATCH: a field is only sent (and so only touched server-side) when
278
+ the caller actually passed it - each of this CLI's `set-*` commands only ever wants to
279
+ touch its own field, and must not clear the other one by omission."""
280
+ body = {}
281
+ if entrypoint_override is not _UNSET:
282
+ body["entrypoint_override"] = entrypoint_override
283
+ if bot_directory is not _UNSET:
284
+ body["bot_directory"] = bot_directory
285
+ return self._request("PATCH", f"/bots/{_q(bot_id)}", json=body).json()
286
+
287
+ def set_env(
288
+ self, bot_id: str, key: str, value: str, is_secret: bool
289
+ ) -> tuple[dict, bool]:
290
+ """Create-or-update an env var. Returns (result, created). If the var already exists,
291
+ updates its value via PATCH and ignores `is_secret` - whether a var is secret is
292
+ immutable after creation."""
293
+ try:
294
+ return self._request(
295
+ "POST",
296
+ f"/bots/{_q(bot_id)}/env",
297
+ json={"key": key, "value": value, "is_secret": is_secret},
298
+ ).json(), True
299
+ except ApiError as e:
300
+ if e.status_code != 409:
301
+ raise
302
+ return self._request(
303
+ "PATCH", f"/bots/{_q(bot_id)}/env/{_q(key)}", json={"value": value}
304
+ ).json(), False
305
+
306
+ def reserved_env_keys(self) -> set[str]:
307
+ """The env var names the platform sets itself, which a bot's own variables cannot use."""
308
+ return set(self._request("GET", "/env-reserved-keys").json().get("keys", []))
309
+
310
+ def get_env(self, bot_id: str, key: str) -> dict:
311
+ return self._request("GET", f"/bots/{_q(bot_id)}/env/{_q(key)}").json()
312
+
313
+ def list_env(self, bot_id: str) -> list[dict]:
314
+ return self._request("GET", f"/bots/{_q(bot_id)}/env").json()
315
+
316
+ def delete_env(self, bot_id: str, key: str) -> None:
317
+ self._request("DELETE", f"/bots/{_q(bot_id)}/env/{_q(key)}")
318
+
319
+ def deploy(
320
+ self,
321
+ bot_id: str,
322
+ archive_bytes: bytes,
323
+ on_wait: Callable[[float, dict], None] | None = None,
324
+ ) -> dict:
325
+ """Uploads the project and waits for the build. The server answers at once (`wait=false`) and the build is
326
+ followed by polling; a server without that option builds first and answers with the finished deployment.
327
+ `on_wait(seconds_since_upload, deployment)` is called on every poll, so the caller can show that the build is alive and
328
+ which stage (`deployment['stage']`) it is in."""
329
+ try:
330
+ started = self._request(
331
+ "POST",
332
+ f"/bots/{_q(bot_id)}/deployments",
333
+ params={"wait": "false"},
334
+ files={"archive": ("bot.tar.gz", archive_bytes, "application/gzip")},
335
+ timeout=_DEPLOY_TIMEOUT,
336
+ ).json()
337
+ except ApiError as e:
338
+ self._raise_if_failed_build(e)
339
+ raise
340
+ return self._follow_build(bot_id, started, on_wait)
341
+
342
+ def _follow_build(
343
+ self,
344
+ bot_id: str,
345
+ deployment: dict,
346
+ on_wait: Callable[[float, dict], None] | None = None,
347
+ ) -> dict:
348
+ began = time.monotonic()
349
+ deadline = began + _BUILD_GIVE_UP_S
350
+ lost_polls = 0
351
+ while deployment.get("status") == "building":
352
+ if time.monotonic() > deadline:
353
+ raise ApiError(
354
+ 0,
355
+ f"The build is still running after {int(_BUILD_GIVE_UP_S // 60)} minutes. It carries on in the "
356
+ f"background: follow it with `pywa cloud deployments log {deployment['id']}`.",
357
+ )
358
+ time.sleep(_POLL_S)
359
+ try:
360
+ deployment = self.get_deployment(bot_id, deployment["id"])
361
+ lost_polls = 0
362
+ except ApiError as e:
363
+ # The build carries on server-side, so one dropped connection must not end the command; several in a row do.
364
+ if (
365
+ e.status_code == 0 or e.status_code >= 500
366
+ ) and lost_polls < _MAX_LOST_POLLS:
367
+ lost_polls += 1
368
+ continue
369
+ raise
370
+ if on_wait is not None:
371
+ on_wait(time.monotonic() - began, deployment)
372
+ if deployment.get("status") == "failed":
373
+ log = deployment.get("build_log") or ""
374
+ reason = deployment.get("failure_reason") or next(
375
+ (ln.strip() for ln in reversed(log.splitlines()) if ln.strip()), None
376
+ )
377
+ raise DeployFailed(deployment["id"], log, reason, deployment.get("stage"))
378
+ return deployment
379
+
380
+ @staticmethod
381
+ def _raise_if_failed_build(e: ApiError) -> None:
382
+ if (
383
+ e.status_code == 422
384
+ and isinstance(e.detail, dict)
385
+ and "deployment_id" in e.detail
386
+ ):
387
+ raise DeployFailed(
388
+ e.detail["deployment_id"],
389
+ e.detail["build_log"],
390
+ e.detail.get("reason"),
391
+ e.detail.get("stage"),
392
+ ) from None
393
+
394
+ def list_deployments(self, bot_id: str, limit: int = 50, skip: int = 0) -> list[dict]:
395
+ return self._request(
396
+ "GET",
397
+ f"/bots/{_q(bot_id)}/deployments",
398
+ params={"limit": limit, "skip": skip},
399
+ ).json()
400
+
401
+ def get_deployment(self, bot_id: str, deployment_id: str) -> dict:
402
+ return self._request(
403
+ "GET", f"/bots/{_q(bot_id)}/deployments/{_q(deployment_id)}"
404
+ ).json()
405
+
406
+ def rollback_deployment(self, bot_id: str, deployment_id: str) -> dict:
407
+ try:
408
+ return self._request(
409
+ "POST",
410
+ f"/bots/{_q(bot_id)}/deployments/{_q(deployment_id)}/rollback",
411
+ timeout=_DEPLOY_TIMEOUT,
412
+ ).json()
413
+ except ApiError as e:
414
+ if (
415
+ e.status_code == 422
416
+ and isinstance(e.detail, dict)
417
+ and "deployment_id" in e.detail
418
+ ):
419
+ raise DeployFailed(
420
+ e.detail["deployment_id"],
421
+ e.detail["build_log"],
422
+ e.detail.get("reason"),
423
+ e.detail.get("stage"),
424
+ ) from None
425
+ raise
426
+
427
+ def get_logs(self, bot_id: str, tail: int = 200, since: str | None = None) -> str:
428
+ params = {"since": since} if since else {"tail": tail}
429
+ return self._request("GET", f"/bots/{_q(bot_id)}/logs", params=params).text
430
+
431
+ def get_status(self, bot_id: str) -> dict:
432
+ return self._request("GET", f"/bots/{_q(bot_id)}/status").json()
433
+
434
+ def get_health(self, bot_id: str) -> dict:
435
+ return self._request("GET", f"/bots/{_q(bot_id)}/health").json()
436
+
437
+ def get_dev_credentials(self, bot_id: str) -> dict:
438
+ """`{"credentials": ..., "env": ...}`, decrypted: the live WhatsApp values Pywa Cloud generated for the bot
439
+ (token, phone id, ...), and the env vars and secrets its owner set."""
440
+ return self._request(
441
+ "GET", f"/bots/{_q(bot_id)}/whatsapp/dev-credentials"
442
+ ).json()
443
+
444
+ def stop(self, bot_id: str) -> None:
445
+ self._request("POST", f"/bots/{_q(bot_id)}/stop")
446
+
447
+ def start(self, bot_id: str) -> None:
448
+ self._request("POST", f"/bots/{_q(bot_id)}/start")
449
+
450
+ def restart(self, bot_id: str) -> None:
451
+ self._request("POST", f"/bots/{_q(bot_id)}/restart")
452
+
453
+ def create_deploy_token(self, bot_id: str, name: str, expires_in_days: int) -> dict:
454
+ return self._request(
455
+ "POST",
456
+ f"/bots/{_q(bot_id)}/deploy-tokens",
457
+ json={"name": name, "expires_in_days": expires_in_days},
458
+ ).json()
459
+
460
+ def list_deploy_tokens(self, bot_id: str) -> list[dict]:
461
+ return self._request("GET", f"/bots/{_q(bot_id)}/deploy-tokens").json()
462
+
463
+ def delete_deploy_token(self, bot_id: str, token_id: str) -> None:
464
+ self._request("DELETE", f"/bots/{_q(bot_id)}/deploy-tokens/{_q(token_id)}")
465
+
466
+ def regenerate_deploy_token(
467
+ self, bot_id: str, token_id: str, expires_in_days: int
468
+ ) -> dict:
469
+ return self._request(
470
+ "POST",
471
+ f"/bots/{_q(bot_id)}/deploy-tokens/{_q(token_id)}/regenerate",
472
+ json={"expires_in_days": expires_in_days},
473
+ ).json()
474
+
475
+ def list_waba_connections(self, team_id: str) -> list[dict]:
476
+ return self._request("GET", f"/teams/{_q(team_id)}/waba-connections").json()
477
+
478
+ def start_connect_session(self, team_id: str) -> dict:
479
+ return self._request("POST", f"/teams/{_q(team_id)}/connect").json()
480
+
481
+ def list_connection_phone_numbers(
482
+ self, team_id: str, connection_id: str
483
+ ) -> list[dict]:
484
+ return self._request(
485
+ "GET",
486
+ f"/teams/{_q(team_id)}/waba-connections/{_q(connection_id)}/phone-numbers",
487
+ ).json()
488
+
489
+ def assign_phone(self, bot_id: str, waba_connection_id: str, phone_id: str) -> dict:
490
+ return self._request(
491
+ "POST",
492
+ f"/bots/{_q(bot_id)}/whatsapp/assign",
493
+ json={"waba_connection_id": waba_connection_id, "phone_id": phone_id},
494
+ ).json()
495
+
496
+ def connect_status(self, bot_id: str) -> dict:
497
+ return self._request("GET", f"/bots/{_q(bot_id)}/connect/status").json()
@@ -0,0 +1,72 @@
1
+ """
2
+ Local CLI config: the auth token, stored at an OS-standard path - never in the
3
+ current/project directory.
4
+
5
+ `$PYWA_CLOUD_CLI_CONFIG_DIR` overrides the default location entirely - useful for tests and for
6
+ running multiple isolated logins on one machine.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import dataclasses
12
+ import json
13
+ import os
14
+ import pathlib
15
+ import sys
16
+
17
+ # The hosted platform.
18
+ API_URL = "https://api.pywa.cloud"
19
+ # Where the web dashboard lives: a separate host from the API (a browser GET on an API URL returns JSON, not a page).
20
+ DASHBOARD_URL = "https://dashboard.pywa.cloud"
21
+
22
+
23
+ def config_dir() -> pathlib.Path:
24
+ override = os.environ.get("PYWA_CLOUD_CLI_CONFIG_DIR")
25
+ if override:
26
+ return pathlib.Path(override)
27
+
28
+ if sys.platform == "darwin":
29
+ base = pathlib.Path.home() / "Library" / "Application Support"
30
+ elif sys.platform == "win32":
31
+ base = pathlib.Path(os.environ.get("APPDATA", pathlib.Path.home()))
32
+ else:
33
+ base = pathlib.Path(
34
+ os.environ.get("XDG_CONFIG_HOME", pathlib.Path.home() / ".config")
35
+ )
36
+ return base / "pywa-cloud"
37
+
38
+
39
+ def config_file() -> pathlib.Path:
40
+ return config_dir() / "auth.json"
41
+
42
+
43
+ @dataclasses.dataclass
44
+ class Config:
45
+ token: str
46
+
47
+
48
+ def load() -> Config | None:
49
+ path = config_file()
50
+ if not path.is_file():
51
+ return None
52
+ try:
53
+ data = json.loads(path.read_text())
54
+ return Config(token=data["token"])
55
+ except (ValueError, KeyError, TypeError, OSError):
56
+ # A truncated or hand-edited file is the same as no file: "Not logged in", and the next
57
+ # `login` overwrites it.
58
+ return None
59
+
60
+
61
+ def save(config: Config) -> None:
62
+ path = config_file()
63
+ path.parent.mkdir(parents=True, exist_ok=True)
64
+ # Created with mode 0o600 from the start, so the token is never readable by others, even briefly.
65
+ fd = os.open(str(path), os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o600)
66
+ with os.fdopen(fd, "w") as f:
67
+ f.write(json.dumps({"token": config.token}))
68
+ path.chmod(0o600)
69
+
70
+
71
+ def clear() -> None:
72
+ config_file().unlink(missing_ok=True)
pywa_cloud_cli/link.py ADDED
@@ -0,0 +1,55 @@
1
+ """
2
+ The per-project `.pywacloud/link.json` file that ties a local directory to a bot id. It lives (git-ignored) in the project, unlike the login in `config.py`.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import dataclasses
8
+ import json
9
+ import pathlib
10
+
11
+ LINK_DIR_NAME = ".pywacloud"
12
+ LINK_FILE_NAME = "link.json"
13
+ GITIGNORE_CONTENT = "*\n"
14
+ README_CONTENT = (
15
+ "This directory links this project to a Pywa Cloud bot - see `link.json`.\n"
16
+ "It's git-ignored; don't commit it. Re-run `pywa cloud link <bot-id>` if it's ever lost.\n"
17
+ )
18
+
19
+
20
+ @dataclasses.dataclass
21
+ class Link:
22
+ bot_id: str
23
+
24
+
25
+ def link_file(project_dir: pathlib.Path) -> pathlib.Path:
26
+ return project_dir / LINK_DIR_NAME / LINK_FILE_NAME
27
+
28
+
29
+ def load(project_dir: pathlib.Path) -> Link | None:
30
+ path = link_file(project_dir)
31
+ if not path.is_file():
32
+ return None
33
+ try:
34
+ bot_id = json.loads(path.read_text())["bot_id"]
35
+ except (ValueError, KeyError, TypeError, OSError):
36
+ return None # a damaged link file is the same as no link: the command says how to link again
37
+ return Link(bot_id=bot_id) if isinstance(bot_id, str) and bot_id else None
38
+
39
+
40
+ def save(project_dir: pathlib.Path, link: Link) -> None:
41
+ link_dir = project_dir / LINK_DIR_NAME
42
+ link_dir.mkdir(parents=True, exist_ok=True)
43
+ (link_dir / LINK_FILE_NAME).write_text(json.dumps({"bot_id": link.bot_id}))
44
+ (link_dir / ".gitignore").write_text(GITIGNORE_CONTENT)
45
+ (link_dir / "README.md").write_text(README_CONTENT)
46
+
47
+
48
+ def clear(project_dir: pathlib.Path) -> None:
49
+ link_dir = project_dir / LINK_DIR_NAME
50
+ for name in (LINK_FILE_NAME, ".gitignore", "README.md"):
51
+ (link_dir / name).unlink(missing_ok=True)
52
+ try:
53
+ link_dir.rmdir()
54
+ except OSError:
55
+ pass # something else lives there (or it never existed) - leave it
File without changes