calkit-python 0.50.7__py3-none-any.whl → 0.51.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 (76) hide show
  1. calkit/__init__.py +0 -1
  2. calkit/agent_skills/check-questions/SKILL.md +8 -1
  3. calkit/cli/check.py +5 -4
  4. calkit/cli/hub/__init__.py +2 -0
  5. calkit/cli/{hub.py → hub/core.py} +6 -0
  6. calkit/cli/hub/link.py +468 -0
  7. calkit/cli/import_.py +121 -66
  8. calkit/cli/latex.py +13 -4
  9. calkit/cli/main/core.py +200 -84
  10. calkit/cli/new.py +113 -0
  11. calkit/cli/open_.py +14 -3
  12. calkit/cli/show.py +10 -2
  13. calkit/cli/sync.py +7 -5
  14. calkit/cli/update.py +101 -0
  15. calkit/config.py +16 -4
  16. calkit/core.py +223 -35
  17. calkit/docx.py +17 -0
  18. calkit/dvc/core.py +188 -5
  19. calkit/dvc/zip.py +40 -1
  20. calkit/environments/core.py +132 -75
  21. calkit/git.py +26 -0
  22. calkit/hub/__init__.py +8 -0
  23. calkit/{hub.py → hub/core.py} +108 -13
  24. calkit/hub/link.py +4827 -0
  25. calkit/install.py +33 -1
  26. calkit/markdown.py +454 -50
  27. calkit/models/core.py +101 -13
  28. calkit/pipeline.py +65 -14
  29. calkit/provenance.py +141 -7
  30. calkit/questions.py +193 -30
  31. calkit/tests/cli/hub/__init__.py +0 -0
  32. calkit/tests/cli/{test_hub.py → hub/test_core.py} +21 -18
  33. calkit/tests/cli/hub/test_link.py +249 -0
  34. calkit/tests/cli/main/test_core.py +182 -52
  35. calkit/tests/cli/test_import.py +98 -0
  36. calkit/tests/cli/test_latex.py +3 -1
  37. calkit/tests/cli/test_new.py +176 -0
  38. calkit/tests/cli/test_open.py +11 -2
  39. calkit/tests/cli/test_show.py +7 -0
  40. calkit/tests/cli/test_update.py +129 -0
  41. calkit/tests/dvc/test_core.py +208 -4
  42. calkit/tests/dvc/test_zip.py +42 -0
  43. calkit/tests/environments/test_core.py +66 -0
  44. calkit/tests/hub/__init__.py +0 -0
  45. calkit/tests/{test_hub.py → hub/test_core.py} +136 -12
  46. calkit/tests/hub/test_link.py +3016 -0
  47. calkit/tests/models/test_core.py +57 -0
  48. calkit/tests/test_config.py +19 -0
  49. calkit/tests/test_core.py +59 -0
  50. calkit/tests/test_docx.py +21 -0
  51. calkit/tests/test_install.py +19 -0
  52. calkit/tests/test_markdown.py +262 -1
  53. calkit/tests/test_pipeline.py +41 -0
  54. calkit/tests/test_provenance.py +160 -0
  55. calkit/tests/test_questions.py +214 -2
  56. calkit/tests/test_upgrade.py +46 -0
  57. calkit/upgrade.py +32 -7
  58. {calkit_python-0.50.7.dist-info → calkit_python-0.51.0.dist-info}/METADATA +18 -4
  59. {calkit_python-0.50.7.dist-info → calkit_python-0.51.0.dist-info}/RECORD +75 -68
  60. calkit/server.py +0 -652
  61. {calkit_python-0.50.7.data → calkit_python-0.51.0.data}/data/etc/jupyter/jupyter_server_config.d/calkit.json +0 -0
  62. {calkit_python-0.50.7.data → calkit_python-0.51.0.data}/data/share/jupyter/labextensions/calkit/package.json +0 -0
  63. {calkit_python-0.50.7.data → calkit_python-0.51.0.data}/data/share/jupyter/labextensions/calkit/schemas/calkit/package.json.orig +0 -0
  64. {calkit_python-0.50.7.data → calkit_python-0.51.0.data}/data/share/jupyter/labextensions/calkit/schemas/calkit/plugin.json +0 -0
  65. {calkit_python-0.50.7.data → calkit_python-0.51.0.data}/data/share/jupyter/labextensions/calkit/static/506.c34b070098184e33.js +0 -0
  66. {calkit_python-0.50.7.data → calkit_python-0.51.0.data}/data/share/jupyter/labextensions/calkit/static/57d13a7399cec3c5.png +0 -0
  67. {calkit_python-0.50.7.data → calkit_python-0.51.0.data}/data/share/jupyter/labextensions/calkit/static/616.528427eb54a4a0c0.js +0 -0
  68. {calkit_python-0.50.7.data → calkit_python-0.51.0.data}/data/share/jupyter/labextensions/calkit/static/740.6bf87276e9e5788a.js +0 -0
  69. {calkit_python-0.50.7.data → calkit_python-0.51.0.data}/data/share/jupyter/labextensions/calkit/static/899.f9b9f9bf705a6493.js +0 -0
  70. {calkit_python-0.50.7.data → calkit_python-0.51.0.data}/data/share/jupyter/labextensions/calkit/static/935.46ecc6bf99aa593a.js +0 -0
  71. {calkit_python-0.50.7.data → calkit_python-0.51.0.data}/data/share/jupyter/labextensions/calkit/static/remoteEntry.109a3a8379365e59.js +0 -0
  72. {calkit_python-0.50.7.data → calkit_python-0.51.0.data}/data/share/jupyter/labextensions/calkit/static/style.js +0 -0
  73. {calkit_python-0.50.7.data → calkit_python-0.51.0.data}/data/share/jupyter/labextensions/calkit/static/third-party-licenses.json +0 -0
  74. {calkit_python-0.50.7.dist-info → calkit_python-0.51.0.dist-info}/WHEEL +0 -0
  75. {calkit_python-0.50.7.dist-info → calkit_python-0.51.0.dist-info}/entry_points.txt +0 -0
  76. {calkit_python-0.50.7.dist-info → calkit_python-0.51.0.dist-info}/licenses/LICENSE +0 -0
calkit/__init__.py CHANGED
@@ -93,7 +93,6 @@ _SUBMODULES = {
93
93
  "requirements",
94
94
  "resources",
95
95
  "schema",
96
- "server",
97
96
  "templates",
98
97
  "upgrade",
99
98
  "workspace",
@@ -38,6 +38,8 @@ Deterministic, done by `calkit check questions` — never re-derive by hand:
38
38
  - every clause of a conditional answer parses, names only evidence, and
39
39
  renders, including the clauses the current values don't select;
40
40
  - every publication `label` still exists in the LaTeX source;
41
+ - every `lines` range on a plain file entry, one with no `kind`, is still
42
+ within the file;
41
43
  - no evidence has changed (Git history for Git-tracked outputs, `dvc.lock`
42
44
  for DVC-tracked ones) since the commit that last edited the question;
43
45
  - no verification is stale, i.e., neither the approach nor any of the
@@ -54,7 +56,8 @@ Deterministic, done by `calkit check questions` — never re-derive by hand:
54
56
  nothing computes is a magic number;
55
57
  - each other evidence path is produced by a pipeline stage, or declared
56
58
  with `imported_from` or `created_by`. This one is advisory: it is
57
- reported as `unattributed` and does not fail the check.
59
+ reported as `unattributed` and does not fail the check. A file inside a
60
+ directory a stage lists as an output is produced by that stage.
58
61
 
59
62
  Judgment, done here — the check reads paths and hashes, and cannot read a
60
63
  sentence:
@@ -194,6 +197,10 @@ that is a false statement about the project, not a tidy-up.
194
197
  precision the claim needs: `{ratio:.1f}x`, `{error:.0%}`. When several
195
198
  come from one file, e.g., the outputs of one calculation, name them
196
199
  together in one `result` entry's `values`, a map of name to key.
200
+ - To cite a file as it is, e.g., a log, a transcript excerpt, or a
201
+ script, give just its `path`, with no `kind`, and the `lines` that
202
+ matter, e.g., `lines: 8` or `lines: 12-20`. Don't use `document` for
203
+ these; that is for write-ups a Markdown stage builds.
197
204
  - A `value` entry must read a file a pipeline stage writes. A placeholder
198
205
  over a results file written by hand, including one you write, is a
199
206
  retyped number with extra steps, and the check fails it. If no stage
calkit/cli/check.py CHANGED
@@ -2039,10 +2039,11 @@ def check_questions(
2039
2039
  Reports, worst first: evidence that isn't there (never run, never
2040
2040
  pushed, or pinned to a Git ref that doesn't exist); broken references
2041
2041
  (a key that doesn't resolve, a placeholder that names no evidence, a
2042
- label missing from the LaTeX); evidence the pipeline would rebuild;
2043
- and evidence from a frozen stage, or downstream of one, that no longer
2044
- matches dvc.lock, which won't be rerun, unless the citation pins a
2045
- git_ref. Subprojects' questions are checked too.
2042
+ label missing from the LaTeX, lines a cited file no longer has);
2043
+ evidence the pipeline would rebuild; and evidence from a frozen stage,
2044
+ or downstream of one, that no longer matches dvc.lock, which won't be
2045
+ rerun, unless the citation pins a git_ref. Subprojects' questions are
2046
+ checked too.
2046
2047
 
2047
2048
  Evidence pinned with a git_ref is checked at that ref rather than in
2048
2049
  the working tree. Exits with an error if any answered question is
@@ -0,0 +1,2 @@
1
+ from . import link # noqa: F401
2
+ from .core import * # noqa: F403
@@ -9,6 +9,7 @@ import typer
9
9
  import calkit
10
10
  from calkit.cli import raise_error
11
11
  from calkit.cli.config import hub_config_app
12
+ from calkit.cli.hub.link import link_app
12
13
 
13
14
  hub_app = typer.Typer(no_args_is_help=True)
14
15
  hub_app.add_typer(
@@ -16,6 +17,11 @@ hub_app.add_typer(
16
17
  name="config",
17
18
  help="Work with per-hub credentials (tokens).",
18
19
  )
20
+ hub_app.add_typer(
21
+ link_app,
22
+ name="link",
23
+ help="Manage this machine's hub link, to work on it from a hub.",
24
+ )
19
25
 
20
26
  _HUB_OPTION_HELP = (
21
27
  "URL of the hub to target, e.g., https://staging.calkit.io. Defaults "
calkit/cli/hub/link.py ADDED
@@ -0,0 +1,468 @@
1
+ """CLI for linking this machine to hubs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import re
7
+
8
+ import typer
9
+ from typing_extensions import Annotated
10
+
11
+ import calkit
12
+ from calkit.cli import AliasGroup, raise_error, warn
13
+
14
+ link_app = typer.Typer(cls=AliasGroup, no_args_is_help=True)
15
+
16
+ HubOption = Annotated[
17
+ str | None,
18
+ typer.Option(
19
+ "--hub",
20
+ help=(
21
+ "URL of the hub the hub link is for, e.g., https://calkit.io; "
22
+ "a machine can have one per hub. Defaults to the only one here, "
23
+ "or for linking, to your default hub."
24
+ ),
25
+ ),
26
+ ]
27
+
28
+
29
+ def _select_hub(hub: str | None, linking: bool = False) -> None:
30
+ """Choose which hub's link a command acts on."""
31
+ from calkit.hub import link as hub_link
32
+
33
+ if hub is not None:
34
+ if hub in ["test", "local", "staging", "production"]:
35
+ raise_error("--hub takes a hub URL, e.g., https://calkit.io")
36
+ hub_link.select_hub(hub)
37
+ return
38
+ hubs = [] if linking else hub_link.list_configured_hubs()
39
+ if len(hubs) > 1:
40
+ raise_error(
41
+ "This machine is linked to more than one hub ("
42
+ + ", ".join(hubs)
43
+ + "); choose one with --hub"
44
+ )
45
+ hub_link.select_hub(hubs[0] if hubs else None)
46
+
47
+
48
+ def _each_hub(hub: str | None) -> list[str | None]:
49
+ """The hubs a command acts on: the one asked for, else every one this
50
+ machine is linked to.
51
+ """
52
+ from calkit.hub import link as hub_link
53
+
54
+ if hub is not None:
55
+ return [hub]
56
+ # None, for the user's own hub, so a machine with none says so
57
+ return list(hub_link.list_configured_hubs()) or [None]
58
+
59
+
60
+ def _require_config() -> dict:
61
+ from calkit.hub import link as hub_link
62
+
63
+ cfg = hub_link.load_config()
64
+ if cfg is None:
65
+ raise_error(
66
+ "This machine isn't linked to this hub; run 'calkit hub link "
67
+ "install' first"
68
+ )
69
+ assert cfg is not None
70
+ return cfg
71
+
72
+
73
+ @link_app.command(name="install")
74
+ def install(
75
+ hub: HubOption = None,
76
+ login: Annotated[
77
+ bool,
78
+ typer.Option(
79
+ "--login",
80
+ help=(
81
+ "Start at login, not at boot (boot requires sudo on macOS "
82
+ "and Linux)."
83
+ ),
84
+ ),
85
+ ] = False,
86
+ cron: Annotated[
87
+ bool,
88
+ typer.Option(
89
+ "--cron",
90
+ help=(
91
+ "Have cron start it when the hub asks rather than running it "
92
+ "as a service, e.g., on a cluster's login node."
93
+ ),
94
+ ),
95
+ ] = False,
96
+ ssh: Annotated[
97
+ str | None,
98
+ typer.Option(
99
+ "--ssh",
100
+ help=(
101
+ "Link another machine over SSH, e.g., "
102
+ "'user@cluster.example.edu' or a host from ~/.ssh/config, "
103
+ "installing Calkit there if needed."
104
+ ),
105
+ ),
106
+ ] = None,
107
+ no_service: Annotated[
108
+ bool,
109
+ typer.Option(
110
+ "--no-service",
111
+ help=(
112
+ "Only register it, e.g., to run it with 'calkit hub link "
113
+ "start' inside tmux on a cluster."
114
+ ),
115
+ ),
116
+ ] = False,
117
+ ) -> None:
118
+ """Link this machine to a hub and run the hub link as a service."""
119
+ from calkit.cli import warn
120
+ from calkit.hub import link as hub_link
121
+
122
+ def explain(e: Exception) -> str:
123
+ # Registering takes a verified email, since setting up two-factor
124
+ # authentication proves itself by email
125
+ if "Verify your email first" in str(e):
126
+ from calkit.hub import get_hub_url
127
+
128
+ return (
129
+ f"Verify your email in your settings at {get_hub_url()}/settings,"
130
+ " then run this again"
131
+ )
132
+ # The hub's reason, without its status code
133
+ return re.sub(r"^\d{3}: ", "", str(e))
134
+
135
+ # Sessions would be root shells, and it asks for sudo when it needs it
136
+ try:
137
+ hub_link.refuse_root()
138
+ _select_hub(hub, linking=True)
139
+ hub_url = hub_link.use_own_hub()
140
+ except ValueError as e:
141
+ raise_error(str(e))
142
+ if ssh is not None:
143
+ from calkit.core import is_tty
144
+
145
+ try:
146
+ remote = hub_link.install_remote(
147
+ ssh,
148
+ cron=cron,
149
+ no_service=no_service,
150
+ login=login,
151
+ interactive=is_tty(),
152
+ )
153
+ except Exception as e:
154
+ raise_error(f"Failed to link {ssh}: {explain(e)}")
155
+ calkit.echo(f"✅ Linked machine '{remote['name']}' on {ssh}")
156
+ return
157
+ cfg = hub_link.load_config()
158
+ # One whose key the hub refused can't connect, so it's revoked, in case
159
+ # someone else holds its token, and registered again
160
+ if cfg is not None and cfg.get("key_rejected"):
161
+ typer.echo(
162
+ f"The hub refused machine '{cfg.get('name')}', so it will be "
163
+ "registered again"
164
+ )
165
+ try:
166
+ hub_link.revoke_self(cfg)
167
+ except Exception as e:
168
+ warn(f"Couldn't revoke '{cfg.get('name')}' on the hub ({e})")
169
+ cfg = None
170
+ # A revoked machine, or one from another hub, would exit at its first
171
+ # check-in, so it's registered again
172
+ if cfg is not None and not hub_link.is_registered(cfg):
173
+ typer.echo(f"Machine '{cfg.get('name')}' is no longer registered")
174
+ cfg = None
175
+ if cfg is None:
176
+ typer.echo(f"Registering this machine with {hub_url}")
177
+ try:
178
+ cfg = hub_link.register()
179
+ except Exception as e:
180
+ raise_error(f"Failed to register this machine: {explain(e)}")
181
+ calkit.echo(f"✅ Registered machine '{cfg['name']}'")
182
+ else:
183
+ typer.echo(f"Machine '{cfg['name']}' is already registered")
184
+ # Whatever ran it before is replaced, e.g., a service when switching to
185
+ # cron mode, so the two don't both run it
186
+ try:
187
+ hub_link.uninstall_service()
188
+ except RuntimeError as e:
189
+ raise_error(str(e))
190
+ if no_service:
191
+ typer.echo("Run 'calkit hub link start' to connect it")
192
+ return
193
+ if cron:
194
+ try:
195
+ hub_link.install_cron()
196
+ except NotImplementedError as e:
197
+ raise_error(str(e))
198
+ calkit.echo(
199
+ "✅ Installed the hub link in cron mode. It checks in every "
200
+ "5 minutes and connects when you open a workspace from the hub."
201
+ )
202
+ return
203
+ try:
204
+ notes = hub_link.install_service(login=login)
205
+ except NotImplementedError as e:
206
+ raise_error(str(e))
207
+ from calkit.hub import get_hub_url
208
+
209
+ calkit.echo(
210
+ "✅ Linked this machine. Its workspaces will show at "
211
+ f"{get_hub_url()}/workspaces."
212
+ )
213
+ for note in notes:
214
+ warn(note)
215
+
216
+
217
+ @link_app.command(name="start")
218
+ def start(
219
+ verbose: Annotated[
220
+ bool, typer.Option("--verbose", "-v", help="Log in more detail.")
221
+ ] = False,
222
+ # How it's being run, which the service and crontab entries set: in
223
+ # cron mode it only connects when the hub asks and stops when idle
224
+ mode: Annotated[str, typer.Option("--mode", hidden=True)] = "foreground",
225
+ hub: HubOption = None,
226
+ # Set for a service whose manager would otherwise open the log as root
227
+ log_file: Annotated[bool, typer.Option("--log-file", hidden=True)] = False,
228
+ ) -> None:
229
+ """Run the hub link in the foreground, e.g., inside tmux."""
230
+ import logging
231
+
232
+ from calkit.hub import link as hub_link
233
+
234
+ try:
235
+ hub_link.refuse_root()
236
+ except ValueError as e:
237
+ raise_error(str(e))
238
+ _select_hub(hub)
239
+ cfg = _require_config()
240
+ if log_file:
241
+ hub_link.log_to_file()
242
+ logging.basicConfig(
243
+ level=logging.DEBUG if verbose else logging.INFO,
244
+ format="%(asctime)s %(levelname)s %(message)s",
245
+ )
246
+ if mode not in ("foreground", "service", "cron"):
247
+ raise_error(f"Unknown mode '{mode}'")
248
+ if mode == "foreground":
249
+ typer.echo(
250
+ f"Starting the hub link for '{cfg['name']}' (Ctrl+C to stop)"
251
+ )
252
+ try:
253
+ if not hub_link.run(cfg, mode=mode):
254
+ # Cron starts one every few minutes, so this is routine there
255
+ if mode != "cron":
256
+ typer.echo(
257
+ "Another hub link to this hub is already running here"
258
+ )
259
+ # A failure, so the service manager tries again later rather
260
+ # than leaving it stopped
261
+ if mode == "service":
262
+ raise typer.Exit(1)
263
+ except hub_link.LinkKeyRejected:
264
+ # Already logged, and a clean exit, so a service manager doesn't
265
+ # restart it
266
+ pass
267
+ except hub_link.LinkRevoked:
268
+ # A clean exit, so a service manager doesn't restart it
269
+ typer.echo("This machine has been revoked on the hub; stopping")
270
+ except KeyboardInterrupt:
271
+ typer.echo("Stopped")
272
+
273
+
274
+ @link_app.command(name="status")
275
+ def status(hub: HubOption = None) -> None:
276
+ """Show this machine's hub links and their workspaces."""
277
+ from calkit.hub import link as hub_link
278
+
279
+ for i, hub_url in enumerate(_each_hub(hub)):
280
+ if i:
281
+ typer.echo()
282
+ _select_hub(hub_url)
283
+ cfg = _require_config()
284
+ typer.echo(f"Name: {cfg['name']}")
285
+ typer.echo(f"Hub: {hub_link.get_hub_url()}")
286
+ service = hub_link.get_service_status()
287
+ typer.echo(f"Installed as: {service or 'nothing; run it with start'}")
288
+ pid = hub_link.get_running_pid()
289
+ typer.echo(f"Running: {f'yes (PID {pid})' if pid else 'no'}")
290
+ typer.echo("Workspaces:")
291
+ for ws in hub_link.discover_workspaces(cfg):
292
+ project = ws.get("project") or "unknown project"
293
+ typer.echo(f" {ws['path']} ({ws['kind']}, {project})")
294
+
295
+
296
+ @link_app.command(name="stop")
297
+ def stop(hub: HubOption = None) -> None:
298
+ """Stop the hub link's service until it's restarted, for every hub
299
+ unless one is given.
300
+ """
301
+ from calkit.hub import link as hub_link
302
+
303
+ hubs = _each_hub(hub)
304
+ failed = False
305
+ for hub_url in hubs:
306
+ _select_hub(hub_url)
307
+ _require_config()
308
+ name = f" for {hub_link.get_hub_url()}" if len(hubs) > 1 else ""
309
+ try:
310
+ hub_link.set_service_running(False)
311
+ except RuntimeError as e:
312
+ warn(f"Couldn't stop the hub link{name}: {e}")
313
+ failed = True
314
+ continue
315
+ typer.echo(f"Stopped the hub link{name}")
316
+ if failed:
317
+ raise typer.Exit(1)
318
+
319
+
320
+ @link_app.command(name="restart")
321
+ def restart(hub: HubOption = None) -> None:
322
+ """Restart the hub link's service, e.g., after updating Calkit, for
323
+ every hub unless one is given.
324
+ """
325
+ import subprocess
326
+
327
+ from calkit.hub import link as hub_link
328
+
329
+ hubs = _each_hub(hub)
330
+ failed = False
331
+ for hub_url in hubs:
332
+ _select_hub(hub_url)
333
+ _require_config()
334
+ name = f" for {hub_link.get_hub_url()}" if len(hubs) > 1 else ""
335
+ try:
336
+ hub_link.restart_service()
337
+ except (RuntimeError, subprocess.CalledProcessError) as e:
338
+ warn(f"Couldn't restart the hub link{name}: {e}")
339
+ failed = True
340
+ continue
341
+ typer.echo(f"Restarted the hub link{name}")
342
+ if failed:
343
+ raise typer.Exit(1)
344
+
345
+
346
+ @link_app.command(name="logs")
347
+ def logs(
348
+ follow: Annotated[
349
+ bool, typer.Option("--follow", "-f", help="Keep printing new lines.")
350
+ ] = False,
351
+ hub: HubOption = None,
352
+ ) -> None:
353
+ """Show the hub link service's logs."""
354
+ import platform
355
+ import subprocess
356
+
357
+ from calkit.hub import link as hub_link
358
+
359
+ _select_hub(hub)
360
+ _require_config()
361
+ # Only a systemd service logs to the journal; cron and the others log
362
+ # to a file
363
+ if platform.system() == "Linux" and os.path.isfile(
364
+ hub_link._systemd_unit_path()
365
+ ):
366
+ cmd = ["journalctl", "--user", "-u", hub_link.systemd_unit()]
367
+ cmd += ["-f"] if follow else ["-n", "100", "--no-pager"]
368
+ else:
369
+ cmd = ["tail", "-n", "100"] + (["-f"] if follow else [])
370
+ cmd.append(hub_link.get_log_path())
371
+ try:
372
+ subprocess.run(cmd)
373
+ except KeyboardInterrupt:
374
+ pass
375
+
376
+
377
+ @link_app.command(name="add-workspace")
378
+ def add_workspace(
379
+ path: Annotated[
380
+ str, typer.Argument(help="Path to a Calkit project.")
381
+ ] = ".",
382
+ hub: HubOption = None,
383
+ ) -> None:
384
+ """Add a project as a workspace, e.g., one outside ~/calkit and ~/dev, or
385
+ one on another hub.
386
+ """
387
+ from calkit.hub import link as hub_link
388
+
389
+ _select_hub(hub)
390
+ cfg = _require_config()
391
+ path = os.path.realpath(path)
392
+ if not os.path.isfile(os.path.join(path, "calkit.yaml")):
393
+ raise_error(f"{path} is not a Calkit project")
394
+ workspaces = cfg.setdefault("workspaces", [])
395
+ if path in workspaces:
396
+ typer.echo(f"{path} is already a workspace")
397
+ return
398
+ workspaces.append(path)
399
+ hub_link.save_config(cfg)
400
+ typer.echo(f"Added {path}; it will show on the hub at the next check-in")
401
+
402
+
403
+ @link_app.command(name="git-credential", hidden=True)
404
+ def git_credential(
405
+ operation: Annotated[
406
+ str, typer.Argument(help="What Git asks: get, store, or erase.")
407
+ ],
408
+ ) -> None:
409
+ """Give Git a GitHub token for one repo in a hub link's session.
410
+
411
+ Sessions and actions the link runs set this up for https://github.com
412
+ only, with the repo's path.
413
+ """
414
+ import sys
415
+
416
+ from calkit.hub import core as hub
417
+
418
+ attrs = {}
419
+ for line in sys.stdin:
420
+ if not line.strip():
421
+ break
422
+ key, _, value = line.rstrip("\n").partition("=")
423
+ attrs[key] = value
424
+ if (
425
+ operation not in ("get", "erase")
426
+ or attrs.get("protocol") != "https"
427
+ or attrs.get("host") != "github.com"
428
+ or not attrs.get("path")
429
+ ):
430
+ return
431
+ try:
432
+ # Erasing is Git saying the last was refused
433
+ resp = hub.ask_link(
434
+ {
435
+ "type": "github.token",
436
+ "path": attrs["path"],
437
+ "forget": operation == "erase",
438
+ }
439
+ )
440
+ except hub.LinkCredentialError as e:
441
+ # Git carries on without, e.g., asking for a password
442
+ warn(str(e), err=True)
443
+ return
444
+ if operation == "get":
445
+ typer.echo(f"username=x-access-token\npassword={resp['token']}")
446
+
447
+
448
+ @link_app.command(name="uninstall")
449
+ def uninstall(hub: HubOption = None) -> None:
450
+ """Revoke this machine on the hub and remove its hub link."""
451
+ from calkit.hub import link as hub_link
452
+
453
+ _select_hub(hub)
454
+ cfg = _require_config()
455
+ try:
456
+ hub_link.uninstall_service()
457
+ except RuntimeError as e:
458
+ raise_error(str(e))
459
+ # With its own token, so it works however you're signed in here
460
+ try:
461
+ hub_link.revoke_self(cfg)
462
+ except Exception as e:
463
+ typer.echo(
464
+ f"Could not revoke '{cfg['name']}' on the hub ({e}); "
465
+ "revoke it from your hub settings"
466
+ )
467
+ os.remove(hub_link.get_config_path())
468
+ typer.echo(f"Unlinked machine '{cfg['name']}'")