calkit-python 0.50.4__py3-none-any.whl → 0.50.6__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 (55) hide show
  1. calkit/agent_skills/connect-overleaf-project/SKILL.md +165 -0
  2. calkit/cli/config.py +2 -8
  3. calkit/cli/latex.py +2 -0
  4. calkit/cli/main/core.py +87 -16
  5. calkit/cli/main/xr.py +12 -1
  6. calkit/cli/open_.py +235 -0
  7. calkit/cli/scheduler.py +51 -5
  8. calkit/cli/update.py +24 -21
  9. calkit/config.py +3 -0
  10. calkit/detect.py +147 -16
  11. calkit/dvc/core.py +81 -0
  12. calkit/github.py +27 -0
  13. calkit/install.py +70 -3
  14. calkit/latex.py +81 -37
  15. calkit/models/pipeline.py +37 -5
  16. calkit/overleaf.py +22 -0
  17. calkit/pipeline.py +9 -0
  18. calkit/reproducibility.py +53 -0
  19. calkit/resources/__init__.py +151 -8
  20. calkit/resources/devcontainer/Dockerfile +5 -0
  21. calkit/resources/devcontainer/base.json +7 -0
  22. calkit/resources/devcontainer/devcontainer.json +8 -5
  23. calkit/resources/vscode/settings.json +2 -2
  24. calkit/tests/cli/main/test_core.py +86 -0
  25. calkit/tests/cli/main/test_xr.py +17 -0
  26. calkit/tests/cli/test_open.py +240 -0
  27. calkit/tests/cli/test_scheduler.py +73 -0
  28. calkit/tests/cli/test_update.py +42 -3
  29. calkit/tests/dvc/test_core.py +103 -0
  30. calkit/tests/test_detect.py +60 -2
  31. calkit/tests/test_github.py +28 -0
  32. calkit/tests/test_install.py +4 -0
  33. calkit/tests/test_overleaf.py +16 -0
  34. calkit/tests/test_pipeline.py +86 -4
  35. calkit/tests/test_reproducibility.py +54 -0
  36. calkit/tests/test_resources.py +141 -4
  37. calkit/workspace.py +1 -1
  38. {calkit_python-0.50.4.dist-info → calkit_python-0.50.6.dist-info}/METADATA +1 -1
  39. {calkit_python-0.50.4.dist-info → calkit_python-0.50.6.dist-info}/RECORD +55 -51
  40. {calkit_python-0.50.4.dist-info → calkit_python-0.50.6.dist-info}/WHEEL +1 -1
  41. {calkit_python-0.50.4.data → calkit_python-0.50.6.data}/data/etc/jupyter/jupyter_server_config.d/calkit.json +0 -0
  42. {calkit_python-0.50.4.data → calkit_python-0.50.6.data}/data/share/jupyter/labextensions/calkit/package.json +0 -0
  43. {calkit_python-0.50.4.data → calkit_python-0.50.6.data}/data/share/jupyter/labextensions/calkit/schemas/calkit/package.json.orig +0 -0
  44. {calkit_python-0.50.4.data → calkit_python-0.50.6.data}/data/share/jupyter/labextensions/calkit/schemas/calkit/plugin.json +0 -0
  45. {calkit_python-0.50.4.data → calkit_python-0.50.6.data}/data/share/jupyter/labextensions/calkit/static/506.c34b070098184e33.js +0 -0
  46. {calkit_python-0.50.4.data → calkit_python-0.50.6.data}/data/share/jupyter/labextensions/calkit/static/57d13a7399cec3c5.png +0 -0
  47. {calkit_python-0.50.4.data → calkit_python-0.50.6.data}/data/share/jupyter/labextensions/calkit/static/616.528427eb54a4a0c0.js +0 -0
  48. {calkit_python-0.50.4.data → calkit_python-0.50.6.data}/data/share/jupyter/labextensions/calkit/static/740.6bf87276e9e5788a.js +0 -0
  49. {calkit_python-0.50.4.data → calkit_python-0.50.6.data}/data/share/jupyter/labextensions/calkit/static/899.f9b9f9bf705a6493.js +0 -0
  50. {calkit_python-0.50.4.data → calkit_python-0.50.6.data}/data/share/jupyter/labextensions/calkit/static/935.46ecc6bf99aa593a.js +0 -0
  51. {calkit_python-0.50.4.data → calkit_python-0.50.6.data}/data/share/jupyter/labextensions/calkit/static/remoteEntry.109a3a8379365e59.js +0 -0
  52. {calkit_python-0.50.4.data → calkit_python-0.50.6.data}/data/share/jupyter/labextensions/calkit/static/style.js +0 -0
  53. {calkit_python-0.50.4.data → calkit_python-0.50.6.data}/data/share/jupyter/labextensions/calkit/static/third-party-licenses.json +0 -0
  54. {calkit_python-0.50.4.dist-info → calkit_python-0.50.6.dist-info}/entry_points.txt +0 -0
  55. {calkit_python-0.50.4.dist-info → calkit_python-0.50.6.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,165 @@
1
+ ---
2
+ name: connect-overleaf-project
3
+ description: Connect an Overleaf project, e.g., a paper, thesis, or poster,
4
+ to a Calkit project and the scripts and data behind it, so its figures and
5
+ numbers come from a pipeline. Use when the user invokes
6
+ `/calkit:connect-overleaf-project`, asks to connect an Overleaf project
7
+ (often one open in their browser) to Calkit, or asks to make an Overleaf
8
+ document reproducible. Not for only signing in to Overleaf.
9
+ ---
10
+
11
+ # Connect an Overleaf project to its analysis
12
+
13
+ The person writes in Overleaf, e.g., a paper, thesis, or poster, and their
14
+ scripts and data are somewhere on their machine or a shared drive. The job is
15
+ to connect the two: a Calkit project with the document in it, stages that make
16
+ what the document shows, and the document reading those outputs instead of
17
+ pasted copies. The writing stays theirs. Change only how the document includes
18
+ figures and numbers.
19
+
20
+ Work in two places:
21
+
22
+ - **The browser**, through the person's own Overleaf session, for what only
23
+ it can do: connecting the document, and checking the result in the editor.
24
+ This needs a browser tool, e.g., Claude in Chrome.
25
+ - **A local clone**, through the CLI, for everything else.
26
+
27
+ Never type passwords or tokens. If something asks the person to sign in,
28
+ stop and ask them to do it.
29
+
30
+ ## 1. Connect the document
31
+
32
+ In the Overleaf tab, open the Calkit panel from the launcher at the bottom
33
+ right, which reads "Calkit: not linked" when the document isn't connected. It's
34
+ in a shadow root, so it may not show in the page's accessibility tree; take a
35
+ screenshot to find it.
36
+
37
+ Click "Make this paper reproducible", check the project name, privacy, and
38
+ folder, and create the project. Name the folder for what the document is,
39
+ e.g., `paper` only for a paper, and `thesis` for a thesis. A project with
40
+ several publications may keep them under `pubs`, e.g., `pubs/paper-1` and
41
+ `pubs/thesis`, and presentations under `presentations`. The panel then
42
+ shows the project and "in sync". If the document should go in a project the
43
+ person already has, use "Use a project I already have" instead.
44
+
45
+ Without the browser extension, `calkit overleaf import URL SUBFOLDER` adds the
46
+ document to an existing local project, using Overleaf's Git access.
47
+
48
+ ## 2. Clone it
49
+
50
+ ```bash
51
+ calkit clone OWNER/NAME ~/calkit/NAME
52
+ ```
53
+
54
+ `~/calkit/` is the usual place, unless the person keeps projects elsewhere,
55
+ e.g., `~/research` or `~/dev`.
56
+
57
+ ## 3. Find what the document shows and where it came from
58
+
59
+ Read the document's `.tex` files and list:
60
+
61
+ - figures included from files in the document's folder, e.g., a pasted
62
+ `\includegraphics{drag.png}`
63
+ - numbers typed into the text that are results, e.g., a mean or a fit
64
+ parameter
65
+ - tables typed or pasted in
66
+
67
+ Then find the scripts and data that made them. Ask the person where they
68
+ keep their analysis before searching their files. Match a figure to its
69
+ script by its file name, `savefig` calls, axis labels, and data columns.
70
+ Don't move or delete anything in their folders; copy what the project needs.
71
+
72
+ ## 4. Bring in the scripts and data
73
+
74
+ Copy scripts into `scripts/` and data into `data/`, then change paths in the
75
+ scripts to be relative to the project root. Where a number in the text comes
76
+ from a script, have the script write it to a results file, e.g.,
77
+ `results/drag.json`, rather than only printing it.
78
+
79
+ Add each script as a stage, previewing first:
80
+
81
+ ```bash
82
+ calkit xr scripts/plot_drag.py --dry-run
83
+ calkit xr scripts/plot_drag.py
84
+ ```
85
+
86
+ Check the detected inputs, outputs, and environment in `calkit.yaml`. Large
87
+ data belongs in DVC; see the conventions skill.
88
+
89
+ ## 5. Have the document read the outputs
90
+
91
+ Load the package and swap each pasted figure and typed result for the
92
+ output that makes it:
93
+
94
+ ```latex
95
+ \usepackage{calkit}
96
+ ...
97
+ The mean drag coefficient was \ckvalue{results/drag.json}{mean_cd}.
98
+ \ckfigure[width=0.6\linewidth]{figures/drag.png}
99
+ \cktable{results/summary.tex}
100
+ ```
101
+
102
+ Remove the pasted copies the document no longer includes, and drop them from
103
+ the LaTeX stage's `inputs`.
104
+
105
+ ## 6. Say where everything starts
106
+
107
+ Data at the start of the chain needs an origin: `created_by` for data the
108
+ person measured or collected, or `imported_from` with a public URL or DOI
109
+ for data from elsewhere. A file on their laptop or a private drive isn't
110
+ somewhere it can be imported from. Ask the person which it is; don't guess.
111
+
112
+ ```yaml
113
+ datasets:
114
+ - path: data/drag_data_FINAL.csv
115
+ title: Drag measurements
116
+ created_by:
117
+ - name: Their Name
118
+ email: them@example.edu
119
+ ```
120
+
121
+ A PNG or PDF can't be created by a person, since an app or script exports
122
+ it. If no script makes it, ask the person what they made it in, copy that
123
+ file into the project, e.g., `figures/src/setup.svg`, and add a stage that
124
+ exports it. Inkscape SVGs and GIMP files are exported as the pipeline runs;
125
+ anything else is a manual step, which asks the person to export it again
126
+ when its file changes:
127
+
128
+ ```yaml
129
+ pipeline:
130
+ stages:
131
+ export-setup:
132
+ kind: inkscape-export # or gimp-export
133
+ source_path: figures/src/setup.svg
134
+ outputs:
135
+ - paper/setup.png
136
+ export-diagram:
137
+ kind: manual-step
138
+ message: In PowerPoint, export paper/diagram.png from slide 2
139
+ open:
140
+ app: PowerPoint
141
+ path: figures/src/diagram.pptx
142
+ inputs:
143
+ - figures/src/diagram.pptx
144
+ outputs:
145
+ - paper/diagram.png
146
+ ```
147
+
148
+ ## 7. Run, save, and sync
149
+
150
+ ```bash
151
+ calkit run --save --overleaf -m "Make the drag figure from its script"
152
+ calkit check repro
153
+ ```
154
+
155
+ Then, in the Overleaf tab:
156
+
157
+ 1. Dismiss Overleaf's "Document Updated Externally" notice, if shown.
158
+ 2. Reload the page, since the extension remembers what it last looked up.
159
+ 3. Recompile, and check that no "Origin not defined" marks remain in the
160
+ editor or on the PDF.
161
+ 4. Hover a `\ckvalue` or `\ckfigure` to confirm it traces back to its stage
162
+ and data.
163
+
164
+ Tell the person what you connected, what you asked them about, and anything
165
+ left without an origin.
calkit/cli/config.py CHANGED
@@ -263,12 +263,7 @@ def config_github_ssh():
263
263
 
264
264
  typer.echo("Checking if you can already connect to GitHub via SSH")
265
265
  # First check if we can already connect to GitHub
266
- ssh_test_cmd = ["ssh", "-T", "git@github.com"]
267
- p = subprocess.run(ssh_test_cmd, capture_output=True, text=True)
268
- if (
269
- "successfully authenticated" in p.stdout
270
- or "successfully authenticated" in p.stderr
271
- ):
266
+ if calkit.github.can_use_ssh(interactive=True):
272
267
  typer.echo("You can already connect to GitHub via SSH")
273
268
  go_on = typer.confirm("Do you want to add a new SSH key anyway?")
274
269
  if not go_on:
@@ -410,8 +405,7 @@ def config_github_ssh():
410
405
  typer.echo(f"Paste this into the public key field:\n\n{pub_key}\n")
411
406
  typer.confirm("Press Enter when done", default=True)
412
407
  typer.echo("Testing SSH connection to GitHub")
413
- p = subprocess.run(ssh_test_cmd, capture_output=True, text=True)
414
- if "successfully authenticated" in p.stderr:
408
+ if calkit.github.can_use_ssh(interactive=True):
415
409
  typer.echo("Successfully connected to GitHub via SSH!")
416
410
  else:
417
411
  raise_error(
calkit/cli/latex.py CHANGED
@@ -757,6 +757,8 @@ def build(
757
757
  dep="latexmk",
758
758
  env_vars=tex_env_vars,
759
759
  )
760
+ if verbose:
761
+ typer.echo(f"Latexmk command: {cmd}")
760
762
  log_dir = aux_dir or output_dir or tex_dir
761
763
  # A little early, for file systems that keep times coarsely
762
764
  started = time.time() - 2
calkit/cli/main/core.py CHANGED
@@ -71,6 +71,7 @@ from calkit.cli.list import list_app
71
71
  from calkit.cli.new import new_app
72
72
  from calkit.cli.notebooks import notebooks_app
73
73
  from calkit.cli.office import office_app
74
+ from calkit.cli.open_ import open_app
74
75
  from calkit.cli.overleaf import overleaf_app
75
76
  from calkit.cli.scheduler import scheduler_app
76
77
  from calkit.cli.show import show_app
@@ -97,6 +98,7 @@ app.add_typer(show_app, name="show", help="Show Calkit objects.")
97
98
  app.add_typer(describe_app, name="describe|desc", help="Describe things.")
98
99
  app.add_typer(import_app, name="import", help="Import objects.")
99
100
  app.add_typer(office_app, name="office", help="Work with Microsoft Office.")
101
+ app.add_typer(open_app, name="open", help="Open things.")
100
102
  app.add_typer(
101
103
  export_app,
102
104
  name="export",
@@ -366,16 +368,42 @@ def init(
366
368
 
367
369
  @app.command(name="clone")
368
370
  def clone(
369
- url: Annotated[str, typer.Argument(help="Repo URL.")],
371
+ url: Annotated[
372
+ str,
373
+ typer.Argument(
374
+ help=(
375
+ "Project as OWNER/NAME, or HUB/OWNER/NAME for one on another "
376
+ "hub, e.g., calkit.example.edu/someone/my-proj, or a Git "
377
+ "repo URL."
378
+ )
379
+ ),
380
+ ],
370
381
  location: Annotated[
371
382
  str | None,
372
383
  typer.Argument(
373
384
  help="Location to clone to (default will be ./{repo_name})"
374
385
  ),
375
386
  ] = None,
376
- ssh: Annotated[
377
- bool, typer.Option("--ssh", help="Use SSH with Git.")
378
- ] = False,
387
+ use_ssh: Annotated[
388
+ bool | None,
389
+ typer.Option(
390
+ "--ssh/--https",
391
+ help=(
392
+ "Use SSH or HTTPS with Git. Defaults to SSH for GitHub if "
393
+ "it's set up, i.e., GitHub accepts a key here."
394
+ ),
395
+ ),
396
+ ] = None,
397
+ hub: Annotated[
398
+ str | None,
399
+ typer.Option(
400
+ "--hub",
401
+ help=(
402
+ "URL of the project's hub, e.g., https://calkit.example.edu. "
403
+ "Defaults to calkit.io."
404
+ ),
405
+ ),
406
+ ] = None,
379
407
  no_config_remote: Annotated[
380
408
  bool,
381
409
  typer.Option(
@@ -394,16 +422,35 @@ def clone(
394
422
  ] = False,
395
423
  ) -> None:
396
424
  """Clone or download a copy of a project."""
397
- # If the URL looks like just a project owner and name, fetch its repo URL
398
- # first
399
- if not url.startswith("https://") and not url.startswith("git@"):
400
- url_split = url.split("/")
401
- if len(url_split) != 2:
425
+ from calkit.config import normalize_hub_url
426
+
427
+ def hub_url(hub: str) -> str:
428
+ # 'localhost' is the development hub, whose web app has a port
429
+ url = normalize_hub_url(hub)
430
+ return (
431
+ calkit.hub.HUB_URLS["local"] if url == "http://localhost" else url
432
+ )
433
+
434
+ # A project named by its owner and name, and maybe its hub, has its repo
435
+ # URL fetched from that hub
436
+ parts = url.split("/")
437
+ if url.startswith(("github.com/", "gitlab.com/")):
438
+ url = "https://" + url
439
+ elif not url.startswith(("https://", "http://", "git@")):
440
+ if len(parts) == 3:
441
+ if hub is not None and hub_url(hub) != hub_url(parts[0]):
442
+ raise_error(
443
+ f"--hub {hub} doesn't match the hub in {url}; give one"
444
+ )
445
+ hub, parts = parts[0], parts[1:]
446
+ if len(parts) != 2 or not all(parts):
402
447
  raise_error(
403
- "Calkit projects must be specified like "
404
- "{owner_name}/{project_name}"
448
+ "Calkit projects must be specified like OWNER/NAME, or "
449
+ "HUB/OWNER/NAME, e.g., calkit.example.edu/someone/my-proj"
405
450
  )
406
- owner_name, project_name = url_split
451
+ owner_name, project_name = parts
452
+ if hub is not None:
453
+ calkit.config.set_hub(hub_url(hub))
407
454
  typer.echo("Fetching Git repo URL from the hub")
408
455
  try:
409
456
  project = calkit.hub.get(f"/projects/{owner_name}/{project_name}")
@@ -412,9 +459,21 @@ def clone(
412
459
  url = project["git_repo_url"]
413
460
  if not url.endswith(".git"):
414
461
  url += ".git"
415
- if ssh:
416
- typer.echo("Converting URL to use with SSH")
417
- url = url.replace("https://github.com/", "git@github.com:")
462
+ # Set up the project for its hub, e.g., its DVC remote, even when it's
463
+ # given by its repo URL
464
+ if hub is not None:
465
+ calkit.config.set_hub(hub_url(hub))
466
+ # Use SSH for GitHub when it's set up, unless asked for one or the other,
467
+ # so pushing later needs no token
468
+ if use_ssh is False and url.startswith("git@github.com:"):
469
+ url = "https://github.com/" + url.removeprefix("git@github.com:")
470
+ on_github = url.startswith("https://github.com/")
471
+ if use_ssh is None:
472
+ use_ssh = on_github and calkit.github.can_use_ssh()
473
+ if use_ssh:
474
+ typer.echo("Cloning over SSH, which is set up for GitHub")
475
+ if use_ssh and on_github:
476
+ url = url.replace("https://github.com/", "git@github.com:")
418
477
  # Git clone
419
478
  cmd = ["git", "clone", url]
420
479
  if not non_recursive:
@@ -2549,6 +2608,7 @@ def _run_dvc_repro(argv: list[str]) -> int | None:
2549
2608
  """
2550
2609
  from dvc.cli import main as dvc_cli_main
2551
2610
 
2611
+ calkit.dvc.ensure_writable_site_cache()
2552
2612
  try:
2553
2613
  return int(dvc_cli_main(argv))
2554
2614
  except ModuleNotFoundError as e:
@@ -5460,7 +5520,18 @@ def run_jupyter(
5460
5520
  help: Annotated[bool, typer.Option("-h", "--help")] = False,
5461
5521
  ) -> None:
5462
5522
  """Run a command with the Jupyter CLI."""
5463
- process = subprocess.run([sys.executable, "-m", "jupyter"] + sys.argv[2:])
5523
+ args = sys.argv[2:]
5524
+ # Starting a server, not a subcommand like `server list`, in a scheduler
5525
+ # job is an interactive session worth tracking
5526
+ if (
5527
+ args
5528
+ and args[0] in ("lab", "notebook", "server")
5529
+ and (len(args) == 1 or args[1].startswith("-"))
5530
+ ):
5531
+ from calkit.cli.scheduler import record_interactive_job
5532
+
5533
+ record_interactive_job("jupyter")
5534
+ process = subprocess.run([sys.executable, "-m", "jupyter"] + args)
5464
5535
  sys.exit(process.returncode)
5465
5536
 
5466
5537
 
calkit/cli/main/xr.py CHANGED
@@ -11,7 +11,7 @@ from typing import Annotated, Any
11
11
  import typer
12
12
 
13
13
  import calkit
14
- from calkit.cli import raise_error
14
+ from calkit.cli import raise_error, warn
15
15
  from calkit.cli.main.core import (
16
16
  STAGE_RUNS_FPATH,
17
17
  app,
@@ -769,11 +769,13 @@ def execute_and_record(
769
769
  # Detect inputs and outputs if not disabled
770
770
  detected_inputs = list(docker_override_detected_inputs)
771
771
  detected_outputs = list(docker_override_detected_outputs)
772
+ external_inputs: list[str] = []
772
773
  if not no_detect_io and not (detected_inputs or detected_outputs):
773
774
  try:
774
775
  io_info = detect_io(stage)
775
776
  detected_inputs = io_info["inputs"]
776
777
  detected_outputs = io_info["outputs"]
778
+ external_inputs = io_info.get("external_inputs", [])
777
779
  except Exception as e:
778
780
  typer.echo(
779
781
  f"Warning: Failed to detect inputs/outputs: {e}",
@@ -869,6 +871,7 @@ def execute_and_record(
869
871
  "name": stage_name,
870
872
  "stage": stage,
871
873
  },
874
+ "external_inputs": external_inputs,
872
875
  }
873
876
  if execution_status is not None:
874
877
  result["execution"] = {
@@ -879,6 +882,14 @@ def execute_and_record(
879
882
  }
880
883
  return result
881
884
 
885
+ # Data read from outside the project is only on this machine
886
+ if not fmt_json:
887
+ for path in external_inputs:
888
+ warn(
889
+ f"This reads {path}, which is outside the project, so it "
890
+ "will fail on other machines; move the data into the project "
891
+ "and read it from there"
892
+ )
882
893
  # If dry-run, print environment and stage then return
883
894
  if dry_run:
884
895
  if fmt_json:
calkit/cli/open_.py ADDED
@@ -0,0 +1,235 @@
1
+ """CLI for opening things."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from typing import Annotated
7
+
8
+ import typer
9
+
10
+ import calkit
11
+ from calkit.cli import raise_error, warn
12
+
13
+ open_app = typer.Typer(no_args_is_help=True)
14
+
15
+ # Commands for the editors 'default_editor' can name
16
+ EDITOR_COMMANDS = {"vscode": "code", "jupyterlab": "jupyter lab"}
17
+
18
+
19
+ def split_command(command: str, windows: bool | None = None) -> list[str]:
20
+ """Split a command into its arguments the way the platform's shell
21
+ would, so a Windows path keeps its backslashes.
22
+ """
23
+ import shlex
24
+
25
+ if windows is None:
26
+ windows = os.name == "nt"
27
+ if not windows:
28
+ return shlex.split(command)
29
+ # Non-POSIX mode keeps backslashes, but also the quotes around a quoted
30
+ # argument, e.g., a path with spaces
31
+ return [
32
+ arg[1:-1] if len(arg) > 1 and arg[0] == arg[-1] == '"' else arg
33
+ for arg in shlex.split(command, posix=False)
34
+ ]
35
+
36
+
37
+ @open_app.command(name="project")
38
+ def open_project(
39
+ project: Annotated[
40
+ str,
41
+ typer.Argument(
42
+ help=(
43
+ "Project name, or owner and name, e.g., 'someone/my-proj', "
44
+ "with its hub to clone from another, e.g., "
45
+ "'calkit.example.edu/someone/my-proj'."
46
+ )
47
+ ),
48
+ ],
49
+ yes: Annotated[
50
+ bool,
51
+ typer.Option(
52
+ "--yes",
53
+ "-y",
54
+ help="Clone into ~/calkit without asking if it isn't here.",
55
+ ),
56
+ ] = False,
57
+ with_editor: Annotated[
58
+ str | None,
59
+ typer.Option(
60
+ "--with",
61
+ "-w",
62
+ help=(
63
+ "Editor to open it with instead of the default, e.g., "
64
+ "'jupyterlab', or a command that takes the folder."
65
+ ),
66
+ ),
67
+ ] = None,
68
+ ) -> None:
69
+ """Open a project on this machine in its editor, from anywhere.
70
+
71
+ Looks for it among the Calkit projects in your home folder, e.g., in
72
+ ~/calkit or ~/dev, and offers to clone it into ~/calkit if it isn't
73
+ there. The editor is the 'default_editor' setting, VS Code unless
74
+ set otherwise, e.g., with 'calkit config set default_editor cursor',
75
+ or the one given with '--with'.
76
+ """
77
+ import shutil
78
+ import subprocess
79
+
80
+ from calkit.core import is_tty
81
+
82
+ # A hub only matters for cloning, since checkouts are found by owner and
83
+ # name
84
+ hub, owner, name = ([""] * 2 + project.split("/"))[-3:]
85
+ if not name or project.count("/") > 2 or (hub and not owner):
86
+ raise_error("Give the project as NAME, OWNER/NAME, or HUB/OWNER/NAME")
87
+ # Read now, since cloning moves into the new repo, and a '.env' file
88
+ # there must not get to choose what runs
89
+ editor = with_editor or calkit.config.read().default_editor
90
+ home = os.path.expanduser("~")
91
+ default_path = os.path.join(home, "calkit", name)
92
+ # Find checkouts of it, by the owner and name each project says it has
93
+ found: dict[str, str] = {}
94
+ for path in calkit.find_project_dirs():
95
+ path = os.path.realpath(path)
96
+ try:
97
+ # Most projects say their name, which rules them out without
98
+ # asking Git for a remote
99
+ info = calkit.load_calkit_info(wdir=path, read_only=True)
100
+ declared = info.get("name") if isinstance(info, dict) else None
101
+ if declared is not None and declared != name:
102
+ continue
103
+ # A subproject without its own repo would look like its parent
104
+ repo = calkit.git.get_repo(path)
105
+ if os.path.realpath(str(repo.working_tree_dir)) != path:
106
+ continue
107
+ p_owner, p_name = calkit.detect_project_name(wdir=path).split(
108
+ "/", 1
109
+ )
110
+ except ValueError:
111
+ # It names no owner, so it can't be the one asked for
112
+ continue
113
+ except Exception as e:
114
+ # E.g., a calkit.yaml left with merge conflict markers
115
+ warn(f"Skipping {path}, which can't be read: {e}")
116
+ continue
117
+ if p_name == name and owner in ("", p_owner):
118
+ found[path] = p_owner
119
+ owners = sorted(set(found.values()))
120
+ if len(owners) > 1:
121
+ raise_error(
122
+ f"More than one project named '{name}' is on this machine; "
123
+ "give its owner, e.g., "
124
+ + ", ".join(f"'calkit open project {o}/{name}'" for o in owners)
125
+ )
126
+ paths = sorted(found)
127
+ # Clone it if it isn't here
128
+ if not paths:
129
+ if not owner:
130
+ raise_error(
131
+ f"No project named '{name}' is on this machine; give its "
132
+ f"owner to clone it, e.g., 'calkit open project OWNER/{name}'"
133
+ )
134
+ if os.path.exists(default_path):
135
+ raise_error(f"{default_path} exists, but isn't {owner}/{name}")
136
+ if not yes:
137
+ if not is_tty():
138
+ raise_error(
139
+ f"{owner}/{name} isn't on this machine; rerun with --yes "
140
+ f"to clone it into {default_path}"
141
+ )
142
+ if not typer.confirm(
143
+ f"{owner}/{name} isn't on this machine. Clone it into "
144
+ f"{default_path}?",
145
+ default=True,
146
+ ):
147
+ raise typer.Exit(1)
148
+ from calkit.cli.main.core import clone
149
+
150
+ clone(url=project, location=default_path)
151
+ paths = [default_path]
152
+ # With more than one checkout, e.g., Git worktrees, prefer the one in
153
+ # ~/calkit, then the main checkout, whose .git is a folder rather than a
154
+ # file pointing to it
155
+ if len(paths) > 1:
156
+ preferred = [
157
+ p for p in paths if p == os.path.realpath(default_path)
158
+ ] or [p for p in paths if os.path.isdir(os.path.join(p, ".git"))]
159
+ if len(preferred) != 1:
160
+ raise_error(
161
+ f"{owner or found[paths[0]]}/{name} is in more than one "
162
+ "place; open one with 'code PATH': " + ", ".join(paths)
163
+ )
164
+ paths = preferred
165
+ path = paths[0]
166
+ # Open it in the configured editor, which is either one we know the
167
+ # command for or a command itself
168
+ cmd = split_command(EDITOR_COMMANDS.get(editor, editor))
169
+ exe = shutil.which(cmd[0]) if cmd else None
170
+ if exe is None and editor == "vscode":
171
+ exe = find_or_install_vscode()
172
+ if exe is None:
173
+ warn(
174
+ f"The default editor's command ({' '.join(cmd)!r}) isn't on PATH, "
175
+ "so opening the folder instead; set another with 'calkit config "
176
+ "set default_editor'"
177
+ )
178
+ typer.launch(path)
179
+ return
180
+ calkit.echo(f"Opening {path} with {editor}")
181
+ subprocess.call([exe, *cmd[1:], path])
182
+
183
+
184
+ def find_or_install_vscode() -> str | None:
185
+ """Find VS Code's command, even where it isn't on PATH, or offer to
186
+ install it, optionally with Calkit's recommended extensions and
187
+ settings.
188
+ """
189
+ import click
190
+
191
+ from calkit import install
192
+ from calkit.core import is_tty
193
+
194
+ code = install.find("code")
195
+ if code is not None:
196
+ return code
197
+ entry = install.get_installer("code")
198
+ download_url = install.DOWNLOAD_PAGES["code"]
199
+ if not is_tty():
200
+ hint = install.get_unsupported_message("code") or (
201
+ "install it with 'calkit install code'"
202
+ )
203
+ warn(f"VS Code isn't installed; {hint}")
204
+ return None
205
+ if entry is None:
206
+ if typer.confirm(
207
+ "VS Code isn't installed. Open its download page?", default=True
208
+ ):
209
+ typer.launch(download_url)
210
+ return None
211
+ calkit.echo("VS Code isn't installed. Calkit can install it with:")
212
+ calkit.echo(f" {entry['script']}")
213
+ choice = typer.prompt(
214
+ "1. Install VS Code\n"
215
+ "2. Install VS Code, with Calkit's recommended extensions and "
216
+ "settings\n"
217
+ "3. Open VS Code's download page instead\n"
218
+ "4. Don't install it; open the folder\n"
219
+ "Choose",
220
+ default="1",
221
+ type=click.Choice(["1", "2", "3", "4"]),
222
+ )
223
+ if choice == "3":
224
+ typer.launch(download_url)
225
+ calkit.echo("Once it's installed, run this again to open the project")
226
+ return None
227
+ if choice == "4":
228
+ return None
229
+ if not install.install("code"):
230
+ warn("Couldn't install VS Code")
231
+ return None
232
+ code = install.find("code")
233
+ if code is not None and choice == "2":
234
+ install.add_vscode_recs(code)
235
+ return code