calkit-python 0.52.0__py3-none-any.whl → 0.52.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.
- calkit/browser_link.py +509 -30
- calkit/cli/check.py +46 -2
- calkit/cli/latex.py +125 -0
- calkit/cli/main/core.py +125 -12
- calkit/cli/main/xr.py +28 -430
- calkit/cli/new.py +56 -15
- calkit/cli/notebooks.py +126 -44
- calkit/cli/update.py +5 -1
- calkit/core.py +143 -11
- calkit/dvc/core.py +14 -5
- calkit/environments/core.py +233 -0
- calkit/environments/texlive.py +31 -3
- calkit/git.py +7 -2
- calkit/models/core.py +21 -7
- calkit/models/pipeline.py +34 -17
- calkit/pipeline/__init__.py +3 -0
- calkit/{pipeline.py → pipeline/core.py} +145 -0
- calkit/pipeline/detect.py +717 -0
- calkit/provenance.py +130 -0
- calkit/releases.py +1 -1
- calkit/resources/__init__.py +144 -9
- calkit/resources/devcontainer/Dockerfile +9 -0
- calkit/tests/cli/main/test_core.py +241 -0
- calkit/tests/cli/test_check.py +43 -0
- calkit/tests/cli/test_latex.py +173 -0
- calkit/tests/cli/test_new.py +89 -3
- calkit/tests/cli/test_notebooks.py +94 -0
- calkit/tests/cli/test_update.py +29 -0
- calkit/tests/conftest.py +14 -2
- calkit/tests/environments/test_core.py +118 -0
- calkit/tests/environments/test_texlive.py +6 -0
- calkit/tests/models/test_pipeline.py +27 -1
- calkit/tests/pipeline/__init__.py +0 -0
- calkit/tests/{test_pipeline.py → pipeline/test_core.py} +131 -5
- calkit/tests/pipeline/test_detect.py +189 -0
- calkit/tests/test_browser_link.py +288 -3
- calkit/tests/test_core.py +71 -0
- calkit/tests/test_git.py +5 -0
- calkit/tests/test_provenance.py +60 -0
- calkit/tests/test_resources.py +194 -3
- {calkit_python-0.52.0.dist-info → calkit_python-0.52.1.dist-info}/METADATA +1 -1
- {calkit_python-0.52.0.dist-info → calkit_python-0.52.1.dist-info}/RECORD +58 -54
- {calkit_python-0.52.0.data → calkit_python-0.52.1.data}/data/etc/jupyter/jupyter_server_config.d/calkit.json +0 -0
- {calkit_python-0.52.0.data → calkit_python-0.52.1.data}/data/share/jupyter/labextensions/calkit/package.json +0 -0
- {calkit_python-0.52.0.data → calkit_python-0.52.1.data}/data/share/jupyter/labextensions/calkit/schemas/calkit/package.json.orig +0 -0
- {calkit_python-0.52.0.data → calkit_python-0.52.1.data}/data/share/jupyter/labextensions/calkit/schemas/calkit/plugin.json +0 -0
- {calkit_python-0.52.0.data → calkit_python-0.52.1.data}/data/share/jupyter/labextensions/calkit/static/506.c34b070098184e33.js +0 -0
- {calkit_python-0.52.0.data → calkit_python-0.52.1.data}/data/share/jupyter/labextensions/calkit/static/57d13a7399cec3c5.png +0 -0
- {calkit_python-0.52.0.data → calkit_python-0.52.1.data}/data/share/jupyter/labextensions/calkit/static/616.528427eb54a4a0c0.js +0 -0
- {calkit_python-0.52.0.data → calkit_python-0.52.1.data}/data/share/jupyter/labextensions/calkit/static/740.6bf87276e9e5788a.js +0 -0
- {calkit_python-0.52.0.data → calkit_python-0.52.1.data}/data/share/jupyter/labextensions/calkit/static/899.f9b9f9bf705a6493.js +0 -0
- {calkit_python-0.52.0.data → calkit_python-0.52.1.data}/data/share/jupyter/labextensions/calkit/static/935.46ecc6bf99aa593a.js +0 -0
- {calkit_python-0.52.0.data → calkit_python-0.52.1.data}/data/share/jupyter/labextensions/calkit/static/remoteEntry.109a3a8379365e59.js +0 -0
- {calkit_python-0.52.0.data → calkit_python-0.52.1.data}/data/share/jupyter/labextensions/calkit/static/style.js +0 -0
- {calkit_python-0.52.0.data → calkit_python-0.52.1.data}/data/share/jupyter/labextensions/calkit/static/third-party-licenses.json +0 -0
- {calkit_python-0.52.0.dist-info → calkit_python-0.52.1.dist-info}/WHEEL +0 -0
- {calkit_python-0.52.0.dist-info → calkit_python-0.52.1.dist-info}/entry_points.txt +0 -0
- {calkit_python-0.52.0.dist-info → calkit_python-0.52.1.dist-info}/licenses/LICENSE +0 -0
calkit/browser_link.py
CHANGED
|
@@ -23,9 +23,11 @@ import struct
|
|
|
23
23
|
import subprocess
|
|
24
24
|
import sys
|
|
25
25
|
import tempfile
|
|
26
|
+
from collections.abc import Callable, Iterable
|
|
26
27
|
from typing import Any, BinaryIO
|
|
27
28
|
|
|
28
29
|
import calkit
|
|
30
|
+
from calkit.core import get_calkit_cmd
|
|
29
31
|
|
|
30
32
|
HOST_NAME = "io.calkit.native"
|
|
31
33
|
CHROME_EXTENSION_IDS = ["idhdomgapfolnpffanajdckdaojencal"]
|
|
@@ -61,6 +63,9 @@ PULL_FRESH_SECONDS = 10
|
|
|
61
63
|
# How often an Overleaf project no checkout here syncs with is looked for
|
|
62
64
|
# again, since that searches the home folder too
|
|
63
65
|
LOOKUP_RESCAN_SECONDS = 600
|
|
66
|
+
# A file bigger than this is stored with DVC rather than in Git, as the
|
|
67
|
+
# hub stores an upload
|
|
68
|
+
FILE_GIT_MAX_BYTES = 1_000_000
|
|
64
69
|
# What a job, e.g., a pipeline run, can do, as the command it runs in the
|
|
65
70
|
# project's checkout, so nothing else can be run through one
|
|
66
71
|
JOB_KINDS = ("run", "sync", "clone", "install-editor")
|
|
@@ -80,6 +85,8 @@ CONCURRENT_REQUEST_TYPES = (
|
|
|
80
85
|
"checkouts.get",
|
|
81
86
|
"overleaf.lookup",
|
|
82
87
|
"publication.pdf",
|
|
88
|
+
"publication.synctex",
|
|
89
|
+
"publication.source",
|
|
83
90
|
"job.get",
|
|
84
91
|
"job.log",
|
|
85
92
|
"jobs.list",
|
|
@@ -89,9 +96,11 @@ MAX_JOBS_KEPT = 20
|
|
|
89
96
|
# How much of a PDF goes in each message, which base64 makes a third
|
|
90
97
|
# bigger, keeping it well under the browser's limit
|
|
91
98
|
PDF_CHUNK_BYTES = 600_000
|
|
99
|
+
# The most of a LaTeX file read for the extension, which no paper's comes near
|
|
100
|
+
SOURCE_MAX_BYTES = 1_000_000
|
|
92
101
|
OVERLEAF_AUTH_MISSING = (
|
|
93
|
-
"Calkit on this
|
|
94
|
-
"Overleaf to Calkit, which saves them for every
|
|
102
|
+
"Calkit on this machine has no Overleaf credentials that work; connect "
|
|
103
|
+
"Overleaf to Calkit, which saves them for every machine you use"
|
|
95
104
|
)
|
|
96
105
|
# Where each browser looks for hosts' manifests in the home folder, by
|
|
97
106
|
# platform; each is only written if the folder above it exists, i.e., the
|
|
@@ -178,6 +187,9 @@ def get_reply(msg: dict) -> dict:
|
|
|
178
187
|
- ``publication.pdf``: part of the PDF a folder synced with Overleaf
|
|
179
188
|
builds to, from ``offset``, with how fresh it is, so it can be shown
|
|
180
189
|
in place of Overleaf's.
|
|
190
|
+
- ``publication.source``: a LaTeX file in a folder synced with
|
|
191
|
+
Overleaf, as it is here, to map a line SyncTeX gives for a PDF built
|
|
192
|
+
here to the same line in Overleaf's copy.
|
|
181
193
|
- ``job.start``, ``job.get``, and ``jobs.list``: run something that
|
|
182
194
|
takes a while, i.e., a pipeline run, an Overleaf sync, or a clone, in
|
|
183
195
|
a process of its own, which outlives the host, and check on it.
|
|
@@ -221,7 +233,9 @@ def get_result(msg: dict) -> Any:
|
|
|
221
233
|
result: Any = {"version": calkit.__version__} | get_editor_info()
|
|
222
234
|
elif kind == "projects.find":
|
|
223
235
|
owner, name = split_project(msg.get("project"))
|
|
224
|
-
found = calkit.get_project_checkouts(
|
|
236
|
+
found = calkit.get_project_checkouts(
|
|
237
|
+
name, owner=owner, search_protected=False
|
|
238
|
+
)
|
|
225
239
|
result = {"paths": sorted(found)}
|
|
226
240
|
elif kind == "project.open":
|
|
227
241
|
owner, name = split_project(msg.get("project"))
|
|
@@ -265,7 +279,7 @@ def get_result(msg: dict) -> Any:
|
|
|
265
279
|
)
|
|
266
280
|
if "isn't on this machine" in error:
|
|
267
281
|
error = (
|
|
268
|
-
f"{owner}/{name} isn't on this
|
|
282
|
+
f"{owner}/{name} isn't on this machine; clone it "
|
|
269
283
|
f"with 'calkit clone {owner}/{name}'"
|
|
270
284
|
)
|
|
271
285
|
raise ValueError(error)
|
|
@@ -306,7 +320,7 @@ def get_result(msg: dict) -> Any:
|
|
|
306
320
|
owner, name = split_project(msg.get("project"))
|
|
307
321
|
paths = get_checkout_paths(owner, name)
|
|
308
322
|
if not paths:
|
|
309
|
-
raise ValueError(f"{owner}/{name} isn't on this
|
|
323
|
+
raise ValueError(f"{owner}/{name} isn't on this machine")
|
|
310
324
|
result = get_overleaf_sync_statuses(
|
|
311
325
|
paths[0],
|
|
312
326
|
overleaf_project_id=msg.get("overleaf_project_id"),
|
|
@@ -319,23 +333,57 @@ def get_result(msg: dict) -> Any:
|
|
|
319
333
|
owner, name = split_project(msg.get("project"))
|
|
320
334
|
paths = get_checkout_paths(owner, name)
|
|
321
335
|
if not paths:
|
|
322
|
-
raise ValueError(f"{owner}/{name} isn't on this
|
|
336
|
+
raise ValueError(f"{owner}/{name} isn't on this machine")
|
|
323
337
|
result = get_figures(paths[0])
|
|
338
|
+
elif kind == "project.contentPaths":
|
|
339
|
+
owner, name = split_project(msg.get("project"))
|
|
340
|
+
paths = get_checkout_paths(owner, name)
|
|
341
|
+
if not paths:
|
|
342
|
+
raise ValueError(f"{owner}/{name} isn't on this machine")
|
|
343
|
+
result = get_content_paths(paths[0])
|
|
344
|
+
elif kind == "project.stageFromScriptOrNotebook":
|
|
345
|
+
owner, name = split_project(msg.get("project"))
|
|
346
|
+
paths = get_checkout_paths(owner, name)
|
|
347
|
+
if not paths:
|
|
348
|
+
raise ValueError(f"{owner}/{name} isn't on this machine")
|
|
349
|
+
result = add_stage_from_script(paths[0], msg)
|
|
350
|
+
elif kind in ("project.recordOrigin", "project.addExportStage"):
|
|
351
|
+
owner, name = split_project(msg.get("project"))
|
|
352
|
+
paths = get_checkout_paths(owner, name)
|
|
353
|
+
if not paths:
|
|
354
|
+
raise ValueError(f"{owner}/{name} isn't on this machine")
|
|
355
|
+
if kind == "project.recordOrigin":
|
|
356
|
+
result = record_origin(paths[0], msg)
|
|
357
|
+
else:
|
|
358
|
+
result = add_export_stage(paths[0], msg)
|
|
324
359
|
elif kind == "project.pipeline":
|
|
325
360
|
owner, name = split_project(msg.get("project"))
|
|
326
361
|
paths = get_checkout_paths(owner, name)
|
|
327
362
|
if not paths:
|
|
328
|
-
raise ValueError(f"{owner}/{name} isn't on this
|
|
363
|
+
raise ValueError(f"{owner}/{name} isn't on this machine")
|
|
329
364
|
result = get_pipeline(paths[0])
|
|
330
|
-
elif kind
|
|
365
|
+
elif kind in ("publication.pdf", "publication.synctex"):
|
|
331
366
|
owner, name = split_project(msg.get("project"))
|
|
332
367
|
paths = get_checkout_paths(owner, name)
|
|
333
368
|
if not paths:
|
|
334
|
-
raise ValueError(f"{owner}/{name} isn't on this
|
|
369
|
+
raise ValueError(f"{owner}/{name} isn't on this machine")
|
|
335
370
|
offset = msg.get("offset", 0)
|
|
336
371
|
if not isinstance(offset, int) or offset < 0:
|
|
337
372
|
raise ValueError("An offset must be a whole number")
|
|
338
|
-
result = get_pdf_chunk(
|
|
373
|
+
result = get_pdf_chunk(
|
|
374
|
+
paths[0],
|
|
375
|
+
str(msg.get("folder")),
|
|
376
|
+
offset,
|
|
377
|
+
synctex=kind == "publication.synctex",
|
|
378
|
+
)
|
|
379
|
+
elif kind == "publication.source":
|
|
380
|
+
owner, name = split_project(msg.get("project"))
|
|
381
|
+
paths = get_checkout_paths(owner, name)
|
|
382
|
+
if not paths:
|
|
383
|
+
raise ValueError(f"{owner}/{name} isn't on this machine")
|
|
384
|
+
result = get_source_text(
|
|
385
|
+
paths[0], str(msg.get("folder")), str(msg.get("path"))
|
|
386
|
+
)
|
|
339
387
|
elif kind == "job.start":
|
|
340
388
|
result = start_job(msg)
|
|
341
389
|
elif kind == "job.get":
|
|
@@ -355,21 +403,6 @@ def get_result(msg: dict) -> Any:
|
|
|
355
403
|
return result
|
|
356
404
|
|
|
357
405
|
|
|
358
|
-
def get_calkit_cmd(module: str = "calkit") -> list[str]:
|
|
359
|
-
"""The command that runs one of Calkit's modules with this Python,
|
|
360
|
-
without importing anything from the folder it runs in first, e.g., a
|
|
361
|
-
project's own ``queue.py``.
|
|
362
|
-
"""
|
|
363
|
-
if sys.version_info >= (3, 11):
|
|
364
|
-
return [sys.executable, "-P", "-m", module]
|
|
365
|
-
return [
|
|
366
|
-
sys.executable,
|
|
367
|
-
"-c",
|
|
368
|
-
"import runpy, sys; sys.path.pop(0); "
|
|
369
|
-
f"runpy.run_module({module!r}, run_name='__main__', alter_sys=True)",
|
|
370
|
-
]
|
|
371
|
-
|
|
372
|
-
|
|
373
406
|
def start_detached(cmd: list[str], **kwargs: Any) -> subprocess.Popen:
|
|
374
407
|
"""Start a process that outlives the host, which the browser stops once
|
|
375
408
|
the extension's done with it, and, on Windows, the job object the
|
|
@@ -548,7 +581,11 @@ def get_checkout_paths(
|
|
|
548
581
|
os.path.isfile(os.path.join(p, "calkit.yaml")) for p in paths
|
|
549
582
|
)
|
|
550
583
|
):
|
|
551
|
-
paths = sorted(
|
|
584
|
+
paths = sorted(
|
|
585
|
+
calkit.get_project_checkouts(
|
|
586
|
+
name, owner=owner, search_protected=False
|
|
587
|
+
)
|
|
588
|
+
)
|
|
552
589
|
set_checkouts_found(key, [time.time(), paths])
|
|
553
590
|
return sort_checkouts(owner, name, paths)
|
|
554
591
|
|
|
@@ -696,7 +733,7 @@ def get_overleaf_links(overleaf_project_id: str) -> list[dict]:
|
|
|
696
733
|
not links
|
|
697
734
|
and time.time() - index["scanned"] > LOOKUP_RESCAN_SECONDS
|
|
698
735
|
):
|
|
699
|
-
for path in calkit.find_project_dirs():
|
|
736
|
+
for path in calkit.find_project_dirs(search_protected=False):
|
|
700
737
|
path = os.path.realpath(path)
|
|
701
738
|
if path not in index["checkouts"]:
|
|
702
739
|
index["checkouts"][path] = read_checkout(path)
|
|
@@ -921,11 +958,39 @@ def get_pdf_path(wdir: str, folder: str) -> str | None:
|
|
|
921
958
|
return None
|
|
922
959
|
|
|
923
960
|
|
|
924
|
-
def
|
|
961
|
+
def get_source_text(wdir: str, folder: str, path: str) -> dict:
|
|
962
|
+
"""A LaTeX file in a folder synced with Overleaf, by its path there, as
|
|
963
|
+
it is in this checkout.
|
|
964
|
+
"""
|
|
965
|
+
import posixpath
|
|
966
|
+
|
|
967
|
+
rel_path = posixpath.normpath(posixpath.join(folder, path))
|
|
968
|
+
full_path = os.path.join(wdir, rel_path)
|
|
969
|
+
if not os.path.realpath(full_path).startswith(
|
|
970
|
+
os.path.join(os.path.realpath(os.path.join(wdir, folder)), "")
|
|
971
|
+
):
|
|
972
|
+
raise ValueError(f"{path} isn't in {folder}")
|
|
973
|
+
if not rel_path.lower().endswith((".tex", ".sty", ".cls", ".bib")):
|
|
974
|
+
raise ValueError(f"{path} isn't a LaTeX file")
|
|
975
|
+
if not os.path.isfile(full_path):
|
|
976
|
+
raise ValueError(f"{rel_path} isn't on this machine")
|
|
977
|
+
if os.path.getsize(full_path) > SOURCE_MAX_BYTES:
|
|
978
|
+
raise ValueError(f"{rel_path} is too big to read")
|
|
979
|
+
with open(full_path, encoding="utf-8", errors="replace") as f:
|
|
980
|
+
return {"path": rel_path, "text": f.read()}
|
|
981
|
+
|
|
982
|
+
|
|
983
|
+
def get_pdf_chunk(
|
|
984
|
+
wdir: str, folder: str, offset: int, synctex: bool = False
|
|
985
|
+
) -> dict:
|
|
925
986
|
"""Part of the PDF a folder synced with Overleaf builds to, as base64
|
|
926
987
|
``data``, from ``offset``, with its ``size``, when it was built, the
|
|
927
988
|
commit that saved it, if any, whether it's changed since, and whether
|
|
928
989
|
anything else in the folder has, i.e., it's older than its source.
|
|
990
|
+
|
|
991
|
+
With ``synctex``, it's the build's compressed SyncTeX file instead,
|
|
992
|
+
which says where in the source each place in the PDF came from, with
|
|
993
|
+
only when it was built.
|
|
929
994
|
"""
|
|
930
995
|
import base64
|
|
931
996
|
|
|
@@ -934,6 +999,8 @@ def get_pdf_chunk(wdir: str, folder: str, offset: int) -> dict:
|
|
|
934
999
|
path = get_pdf_path(wdir, folder)
|
|
935
1000
|
if path is None:
|
|
936
1001
|
raise ValueError(f"No PDF is built from {folder}")
|
|
1002
|
+
if synctex:
|
|
1003
|
+
path = os.path.splitext(path)[0] + ".synctex.gz"
|
|
937
1004
|
full_path = os.path.join(wdir, path)
|
|
938
1005
|
if not os.path.realpath(full_path).startswith(
|
|
939
1006
|
os.path.join(os.path.realpath(wdir), "")
|
|
@@ -941,7 +1008,7 @@ def get_pdf_chunk(wdir: str, folder: str, offset: int) -> dict:
|
|
|
941
1008
|
raise ValueError(f"{path} isn't in the project")
|
|
942
1009
|
if not os.path.isfile(full_path):
|
|
943
1010
|
raise ValueError(
|
|
944
|
-
f"{path} hasn't been built on this
|
|
1011
|
+
f"{path} hasn't been built on this machine; run the pipeline"
|
|
945
1012
|
)
|
|
946
1013
|
stat = os.stat(full_path)
|
|
947
1014
|
with open(full_path, "rb") as f:
|
|
@@ -953,6 +1020,8 @@ def get_pdf_chunk(wdir: str, folder: str, offset: int) -> dict:
|
|
|
953
1020
|
"offset": offset,
|
|
954
1021
|
"data": base64.b64encode(data).decode("ascii"),
|
|
955
1022
|
}
|
|
1023
|
+
if synctex:
|
|
1024
|
+
return chunk | {"built": stat.st_mtime}
|
|
956
1025
|
# How fresh it is, only with the first part
|
|
957
1026
|
if offset == 0:
|
|
958
1027
|
repo = calkit.git.get_repo(wdir)
|
|
@@ -1216,7 +1285,7 @@ def start_job(msg: dict) -> dict:
|
|
|
1216
1285
|
else:
|
|
1217
1286
|
paths = get_checkout_paths(owner, name)
|
|
1218
1287
|
if not paths:
|
|
1219
|
-
raise ValueError(f"{owner}/{name} isn't on this
|
|
1288
|
+
raise ValueError(f"{owner}/{name} isn't on this machine")
|
|
1220
1289
|
wdir = paths[0]
|
|
1221
1290
|
if kind == "run":
|
|
1222
1291
|
# Saved and synced with Overleaf after unless asked not to
|
|
@@ -1480,6 +1549,416 @@ def get_figures(wdir: str) -> dict:
|
|
|
1480
1549
|
return {"items": items, "total": len(items)}
|
|
1481
1550
|
|
|
1482
1551
|
|
|
1552
|
+
def get_content_paths(wdir: str) -> list[str]:
|
|
1553
|
+
"""Every file in a checkout someone might pick, as the hub lists a
|
|
1554
|
+
project's: what Git tracks, and what the pipeline makes with DVC, by its
|
|
1555
|
+
own path rather than its ``.dvc`` file, with files not yet saved, e.g.,
|
|
1556
|
+
a script just written, since here they're there to pick.
|
|
1557
|
+
"""
|
|
1558
|
+
import calkit.dvc
|
|
1559
|
+
import calkit.git
|
|
1560
|
+
|
|
1561
|
+
lock_outs = {
|
|
1562
|
+
out["path"]
|
|
1563
|
+
for stage in calkit.dvc.read_lock_stages(wdir=wdir).values()
|
|
1564
|
+
if isinstance(stage, dict)
|
|
1565
|
+
for out in stage.get("outs") or []
|
|
1566
|
+
if isinstance(out, dict)
|
|
1567
|
+
and isinstance(out.get("path"), str)
|
|
1568
|
+
and not str(out.get("md5", "")).endswith(".dir")
|
|
1569
|
+
}
|
|
1570
|
+
repo = calkit.git.get_repo(wdir)
|
|
1571
|
+
# Unquoted, e.g., for names that aren't ASCII
|
|
1572
|
+
listed = repo.git.ls_files("-z", "-co", "--exclude-standard").split("\0")
|
|
1573
|
+
paths = set(lock_outs)
|
|
1574
|
+
for path in listed:
|
|
1575
|
+
if not path or path.startswith(".dvc/"):
|
|
1576
|
+
continue
|
|
1577
|
+
paths.add(path.removesuffix(".dvc"))
|
|
1578
|
+
return sorted(paths)
|
|
1579
|
+
|
|
1580
|
+
|
|
1581
|
+
def get_project_path(wdir: str, value: Any, what: str) -> str:
|
|
1582
|
+
"""A path the extension gave, relative to a checkout, refusing one
|
|
1583
|
+
that isn't in it, e.g., through a symlink.
|
|
1584
|
+
"""
|
|
1585
|
+
import posixpath
|
|
1586
|
+
|
|
1587
|
+
if not isinstance(value, str) or not value.strip():
|
|
1588
|
+
raise ValueError(f"A {what} path is required")
|
|
1589
|
+
# One given in full, e.g., from a file picker, is made relative
|
|
1590
|
+
path = posixpath.normpath(
|
|
1591
|
+
os.path.relpath(
|
|
1592
|
+
os.path.join(wdir, value.strip()), os.path.abspath(wdir)
|
|
1593
|
+
).replace("\\", "/")
|
|
1594
|
+
)
|
|
1595
|
+
real = os.path.realpath(os.path.join(wdir, path))
|
|
1596
|
+
if path.startswith("../") or not real.startswith(
|
|
1597
|
+
os.path.join(os.path.realpath(wdir), "")
|
|
1598
|
+
):
|
|
1599
|
+
raise ValueError(f"'{value}' isn't in the project")
|
|
1600
|
+
return path
|
|
1601
|
+
|
|
1602
|
+
|
|
1603
|
+
def is_dvc_tracked(wdir: str, path: str) -> bool:
|
|
1604
|
+
"""Whether a path in a checkout has its own .dvc file or a folder's,
|
|
1605
|
+
whether or not it's pulled.
|
|
1606
|
+
"""
|
|
1607
|
+
parts = path.split("/")
|
|
1608
|
+
return any(
|
|
1609
|
+
os.path.isfile(os.path.join(wdir, *parts[:n]) + ".dvc")
|
|
1610
|
+
for n in range(1, len(parts) + 1)
|
|
1611
|
+
)
|
|
1612
|
+
|
|
1613
|
+
|
|
1614
|
+
def get_changed_paths(repo: Any) -> set[str]:
|
|
1615
|
+
"""Paths in a checkout that aren't committed, untracked ones too."""
|
|
1616
|
+
# Unquoted, e.g., for names that aren't ASCII
|
|
1617
|
+
entries = iter(repo.git.status("--porcelain", "-z", "-uall").split("\0"))
|
|
1618
|
+
paths = set()
|
|
1619
|
+
for entry in entries:
|
|
1620
|
+
if len(entry) > 3:
|
|
1621
|
+
paths.add(entry[3:])
|
|
1622
|
+
# A rename or copy is followed by where it came from
|
|
1623
|
+
if entry[:1] in ("R", "C"):
|
|
1624
|
+
paths.add(next(entries, ""))
|
|
1625
|
+
return paths - {""}
|
|
1626
|
+
|
|
1627
|
+
|
|
1628
|
+
def commit_change(
|
|
1629
|
+
wdir: str,
|
|
1630
|
+
ck_info: dict,
|
|
1631
|
+
write: Callable[[], list[str]],
|
|
1632
|
+
message: str,
|
|
1633
|
+
checked: Iterable[str] = (),
|
|
1634
|
+
also_commit: Iterable[str] = (),
|
|
1635
|
+
compile_pipeline: bool = True,
|
|
1636
|
+
) -> None:
|
|
1637
|
+
"""Change a checkout as the hub would its clone, and commit only that,
|
|
1638
|
+
since anything else changed here is someone's work in progress.
|
|
1639
|
+
|
|
1640
|
+
``write`` writes any files, returning their paths, and may add to
|
|
1641
|
+
``ck_info``, which is written as calkit.yaml after it, and the pipeline
|
|
1642
|
+
compiled, unless ``compile_pipeline`` is false. Refused if calkit.yaml,
|
|
1643
|
+
dvc.yaml, or ``checked`` have unsaved changes, which would be swept up
|
|
1644
|
+
or overwritten; ``also_commit`` are committed even so, e.g., a new
|
|
1645
|
+
script. If any of it fails, files it changed are put back and files
|
|
1646
|
+
that appeared while it ran are deleted. Nothing's pushed; a run and
|
|
1647
|
+
sync does that.
|
|
1648
|
+
"""
|
|
1649
|
+
import calkit.git
|
|
1650
|
+
import calkit.pipeline
|
|
1651
|
+
|
|
1652
|
+
repo = calkit.git.get_repo(wdir)
|
|
1653
|
+
changed_before = get_changed_paths(repo)
|
|
1654
|
+
for path in ["calkit.yaml", "dvc.yaml", *checked]:
|
|
1655
|
+
if path in changed_before:
|
|
1656
|
+
raise ValueError(
|
|
1657
|
+
f"{path} has changes that aren't saved; save or discard "
|
|
1658
|
+
"them first"
|
|
1659
|
+
)
|
|
1660
|
+
try:
|
|
1661
|
+
written = write()
|
|
1662
|
+
with open(
|
|
1663
|
+
os.path.join(wdir, "calkit.yaml"), "w", encoding="utf-8"
|
|
1664
|
+
) as f:
|
|
1665
|
+
calkit.ryaml.dump(ck_info, f)
|
|
1666
|
+
if compile_pipeline:
|
|
1667
|
+
calkit.pipeline.to_dvc(ck_info=ck_info, wdir=wdir, write=True)
|
|
1668
|
+
commit_paths = sorted(
|
|
1669
|
+
(get_changed_paths(repo) - changed_before)
|
|
1670
|
+
| set(written)
|
|
1671
|
+
| {"calkit.yaml"}
|
|
1672
|
+
| (set(also_commit) & changed_before)
|
|
1673
|
+
)
|
|
1674
|
+
repo.git.add("--", *commit_paths)
|
|
1675
|
+
# Already as asked, e.g., when saved before
|
|
1676
|
+
if repo.git.diff("--cached", "--name-only", "--", *commit_paths):
|
|
1677
|
+
repo.git.commit("-m", message, "--", *commit_paths)
|
|
1678
|
+
except Exception:
|
|
1679
|
+
# Put back what was written, so it isn't left half done, and a try
|
|
1680
|
+
# again isn't refused for unsaved changes to it
|
|
1681
|
+
undo = sorted(get_changed_paths(repo) - changed_before)
|
|
1682
|
+
if undo:
|
|
1683
|
+
repo.git.reset("-q", "--", *undo)
|
|
1684
|
+
tracked = [
|
|
1685
|
+
p
|
|
1686
|
+
for p in repo.git.ls_files("-z", "--", *undo).split("\0")
|
|
1687
|
+
if p
|
|
1688
|
+
]
|
|
1689
|
+
if tracked:
|
|
1690
|
+
repo.git.checkout("--", *tracked)
|
|
1691
|
+
for path in set(undo) - set(tracked):
|
|
1692
|
+
if os.path.isfile(os.path.join(wdir, path)):
|
|
1693
|
+
os.remove(os.path.join(wdir, path))
|
|
1694
|
+
raise
|
|
1695
|
+
|
|
1696
|
+
|
|
1697
|
+
def add_stage_from_script(wdir: str, msg: dict) -> dict:
|
|
1698
|
+
"""Make a stage from a script already in a checkout, as the hub does
|
|
1699
|
+
for one in its clone, read rather than run, as ``calkit xr --dry-run``
|
|
1700
|
+
reads it.
|
|
1701
|
+
|
|
1702
|
+
Without ``save``, nothing is written, so what it would be can be shown
|
|
1703
|
+
first. With it, the stage, its environment, and each document changed
|
|
1704
|
+
to show what it makes from where it's made are committed, and only
|
|
1705
|
+
those, since anything else changed here is someone's work in progress.
|
|
1706
|
+
Nothing's pushed; a run and sync does that.
|
|
1707
|
+
"""
|
|
1708
|
+
import calkit.git
|
|
1709
|
+
import calkit.pipeline
|
|
1710
|
+
import calkit.pipeline.detect
|
|
1711
|
+
|
|
1712
|
+
script_path = get_project_path(wdir, msg.get("scriptPath"), "script")
|
|
1713
|
+
if not script_path.lower().endswith(calkit.pipeline.detect.SCRIPT_EXTS):
|
|
1714
|
+
raise ValueError(calkit.pipeline.detect.SCRIPT_EXTS_MESSAGE)
|
|
1715
|
+
# Uploads go through the hub, which reads them in a checkout of their
|
|
1716
|
+
# own; here the script and its data are already on this machine
|
|
1717
|
+
if msg.get("content") is not None:
|
|
1718
|
+
raise ValueError(
|
|
1719
|
+
"Put the script in the project's folder on this machine, then "
|
|
1720
|
+
"find it in the project"
|
|
1721
|
+
)
|
|
1722
|
+
if msg.get("data"):
|
|
1723
|
+
raise ValueError(
|
|
1724
|
+
"Move the data the script reads into the project's folder, and "
|
|
1725
|
+
"change the script to read it from there"
|
|
1726
|
+
)
|
|
1727
|
+
if not os.path.isfile(os.path.join(wdir, script_path)):
|
|
1728
|
+
raise ValueError(f"'{script_path}' isn't in the project")
|
|
1729
|
+
shows = msg.get("shows")
|
|
1730
|
+
produces = msg.get("produces")
|
|
1731
|
+
repo = calkit.git.get_repo(wdir)
|
|
1732
|
+
# Elsewhere, e.g., in CI, a stage couldn't run a script Git leaves out
|
|
1733
|
+
if repo.ignored(script_path):
|
|
1734
|
+
raise ValueError(
|
|
1735
|
+
f"'{script_path}' is ignored by Git, so the stage couldn't run "
|
|
1736
|
+
"anywhere else; stop ignoring it first"
|
|
1737
|
+
)
|
|
1738
|
+
# Read in this process from the checkout, as the pipeline's status is,
|
|
1739
|
+
# rather than by 'calkit xr' in one of its own; what's answered at the
|
|
1740
|
+
# same time uses full paths
|
|
1741
|
+
prev_wdir = os.getcwd()
|
|
1742
|
+
try:
|
|
1743
|
+
os.chdir(wdir)
|
|
1744
|
+
detected = calkit.pipeline.detect.detect_stage(
|
|
1745
|
+
[script_path], calkit.load_calkit_info()
|
|
1746
|
+
).model_dump()
|
|
1747
|
+
finally:
|
|
1748
|
+
os.chdir(prev_wdir)
|
|
1749
|
+
ck_info = calkit.load_calkit_info(wdir=wdir)
|
|
1750
|
+
plan = calkit.pipeline.detect.get_stage_from_script_plan(
|
|
1751
|
+
script_path,
|
|
1752
|
+
detected,
|
|
1753
|
+
ck_info,
|
|
1754
|
+
wdir=wdir,
|
|
1755
|
+
shows=get_project_path(wdir, shows, "shown") if shows else None,
|
|
1756
|
+
produces=(
|
|
1757
|
+
get_project_path(wdir, produces, "output") if produces else None
|
|
1758
|
+
),
|
|
1759
|
+
is_dvc_output=lambda path: is_dvc_tracked(wdir, path),
|
|
1760
|
+
)
|
|
1761
|
+
result = {
|
|
1762
|
+
key: value
|
|
1763
|
+
for key, value in plan.items()
|
|
1764
|
+
if key not in ("stage", "env", "included")
|
|
1765
|
+
} | {
|
|
1766
|
+
"rewritten": [],
|
|
1767
|
+
"included_in": sorted(plan["included"]),
|
|
1768
|
+
"git_repo_url": ck_info.get("git_repo_url") or "",
|
|
1769
|
+
"saved": False,
|
|
1770
|
+
}
|
|
1771
|
+
if not msg.get("save"):
|
|
1772
|
+
return result
|
|
1773
|
+
commit_change(
|
|
1774
|
+
wdir,
|
|
1775
|
+
ck_info,
|
|
1776
|
+
lambda: calkit.pipeline.write_stage_from_script(
|
|
1777
|
+
plan, ck_info, wdir=wdir
|
|
1778
|
+
),
|
|
1779
|
+
f"Add stage {plan['stage_name']} for {script_path}",
|
|
1780
|
+
checked=plan["included"],
|
|
1781
|
+
also_commit=[script_path],
|
|
1782
|
+
)
|
|
1783
|
+
result["saved"] = True
|
|
1784
|
+
return result
|
|
1785
|
+
|
|
1786
|
+
|
|
1787
|
+
def record_origin(wdir: str, msg: dict) -> dict:
|
|
1788
|
+
"""Record who made a file in a checkout or where it was imported from,
|
|
1789
|
+
as the hub records a misc artifact, committed here.
|
|
1790
|
+
"""
|
|
1791
|
+
import calkit.dvc
|
|
1792
|
+
import calkit.provenance
|
|
1793
|
+
|
|
1794
|
+
path = get_project_path(wdir, msg.get("path"), "file")
|
|
1795
|
+
created_by = msg.get("createdBy")
|
|
1796
|
+
imported_from = msg.get("importedFrom")
|
|
1797
|
+
if created_by is not None and not isinstance(created_by, list):
|
|
1798
|
+
raise ValueError("Who created it must be a list of people")
|
|
1799
|
+
if imported_from is not None and not isinstance(imported_from, dict):
|
|
1800
|
+
raise ValueError("Where it was imported from must be a mapping")
|
|
1801
|
+
ck_info = calkit.load_calkit_info(wdir=wdir)
|
|
1802
|
+
ck_info, entry = calkit.provenance.add_origin(
|
|
1803
|
+
ck_info, path, created_by=created_by, imported_from=imported_from
|
|
1804
|
+
)
|
|
1805
|
+
# Whether tracked by Git or DVC, or made by a stage and not pulled, it
|
|
1806
|
+
# has to be in the project to attribute
|
|
1807
|
+
lock_outs = [
|
|
1808
|
+
out["path"].rstrip("/")
|
|
1809
|
+
for stage in calkit.dvc.read_lock_stages(wdir=wdir).values()
|
|
1810
|
+
for out in (stage or {}).get("outs") or []
|
|
1811
|
+
if isinstance(out, dict) and isinstance(out.get("path"), str)
|
|
1812
|
+
]
|
|
1813
|
+
if not (
|
|
1814
|
+
os.path.exists(os.path.join(wdir, path))
|
|
1815
|
+
or is_dvc_tracked(wdir, path)
|
|
1816
|
+
or any(path == o or path.startswith(o + "/") for o in lock_outs)
|
|
1817
|
+
):
|
|
1818
|
+
raise ValueError(f"'{path}' isn't in the project")
|
|
1819
|
+
# Only calkit.yaml's artifacts change, which the pipeline doesn't read
|
|
1820
|
+
commit_change(
|
|
1821
|
+
wdir,
|
|
1822
|
+
ck_info,
|
|
1823
|
+
lambda: [],
|
|
1824
|
+
msg.get("message") or f"Record where {path} came from",
|
|
1825
|
+
compile_pipeline=False,
|
|
1826
|
+
)
|
|
1827
|
+
return entry
|
|
1828
|
+
|
|
1829
|
+
|
|
1830
|
+
def add_export_stage(wdir: str, msg: dict) -> dict:
|
|
1831
|
+
"""Add the stage that exports a figure from the file it's drawn in, as
|
|
1832
|
+
the hub does, committed here.
|
|
1833
|
+
|
|
1834
|
+
An app that can do it as the pipeline runs does, unless another is
|
|
1835
|
+
named; otherwise it's a manual step. Without ``save`` set false, it's
|
|
1836
|
+
added; with it, only shown. A file the stage needs that isn't in Git
|
|
1837
|
+
yet, e.g., a Photoshop file, is committed with it, or stored with DVC
|
|
1838
|
+
if it's too big for Git.
|
|
1839
|
+
"""
|
|
1840
|
+
import subprocess
|
|
1841
|
+
|
|
1842
|
+
import calkit.export
|
|
1843
|
+
import calkit.git
|
|
1844
|
+
import calkit.pipeline
|
|
1845
|
+
import calkit.provenance
|
|
1846
|
+
|
|
1847
|
+
source = get_project_path(wdir, msg.get("source"), "source")
|
|
1848
|
+
output = get_project_path(wdir, msg.get("output"), "output")
|
|
1849
|
+
app = msg.get("app") or None
|
|
1850
|
+
exporter = calkit.export.exporter_for(source, output, app=app)
|
|
1851
|
+
stage = calkit.export.export_stage(source, output, app=app)
|
|
1852
|
+
out = {
|
|
1853
|
+
"name": calkit.export.export_stage_name(output),
|
|
1854
|
+
"stage": stage,
|
|
1855
|
+
"exported_by": exporter.app if exporter else None,
|
|
1856
|
+
"saved": False,
|
|
1857
|
+
}
|
|
1858
|
+
if not msg.get("save", True):
|
|
1859
|
+
return out
|
|
1860
|
+
# Uploads go through the hub; here the files are already on this
|
|
1861
|
+
# machine
|
|
1862
|
+
files = []
|
|
1863
|
+
for file in msg.get("files") or []:
|
|
1864
|
+
if not isinstance(file, dict):
|
|
1865
|
+
raise ValueError("Each file must be a mapping")
|
|
1866
|
+
if file.get("content") is not None:
|
|
1867
|
+
raise ValueError(
|
|
1868
|
+
"Put the file in the project's folder on this machine, "
|
|
1869
|
+
"then find it in the project"
|
|
1870
|
+
)
|
|
1871
|
+
path = get_project_path(wdir, file.get("path"), "file")
|
|
1872
|
+
if not (
|
|
1873
|
+
os.path.isfile(os.path.join(wdir, path))
|
|
1874
|
+
or is_dvc_tracked(wdir, path)
|
|
1875
|
+
):
|
|
1876
|
+
raise ValueError(f"'{path}' isn't in the project")
|
|
1877
|
+
if file.get("created_by_me") and not (
|
|
1878
|
+
calkit.provenance.can_be_created_by_person(path)
|
|
1879
|
+
):
|
|
1880
|
+
raise ValueError(
|
|
1881
|
+
f"'{path}' is exported from something itself, so it can't "
|
|
1882
|
+
"be created by a person; add the file it's made from, e.g., "
|
|
1883
|
+
"a Photoshop file"
|
|
1884
|
+
)
|
|
1885
|
+
files.append((path, bool(file.get("created_by_me"))))
|
|
1886
|
+
repo = calkit.git.get_repo(wdir)
|
|
1887
|
+
ck_info = calkit.load_calkit_info(wdir=wdir)
|
|
1888
|
+
stage_name, stage = calkit.pipeline.get_stage_to_add(
|
|
1889
|
+
stage,
|
|
1890
|
+
ck_info,
|
|
1891
|
+
name=out["name"],
|
|
1892
|
+
is_tracked=lambda p: bool(repo.git.ls_files("--", p).strip()),
|
|
1893
|
+
)
|
|
1894
|
+
created = [path for path, by_me in files if by_me]
|
|
1895
|
+
if created:
|
|
1896
|
+
# Whoever commits here, as Git knows them
|
|
1897
|
+
with repo.config_reader() as config:
|
|
1898
|
+
email = config.get_value("user", "email", "")
|
|
1899
|
+
person_name = config.get_value("user", "name", "")
|
|
1900
|
+
if not email:
|
|
1901
|
+
raise ValueError(
|
|
1902
|
+
"Git doesn't know your email address, to record who made "
|
|
1903
|
+
f"{created[0]}; set it with 'git config --global user.email'"
|
|
1904
|
+
)
|
|
1905
|
+
person = {"email": str(email)}
|
|
1906
|
+
if person_name:
|
|
1907
|
+
person["name"] = str(person_name)
|
|
1908
|
+
ck_info = calkit.provenance.add_creator(ck_info, created, person)
|
|
1909
|
+
if not ck_info.get("pipeline"):
|
|
1910
|
+
ck_info["pipeline"] = {}
|
|
1911
|
+
if not ck_info["pipeline"].get("stages"):
|
|
1912
|
+
ck_info["pipeline"]["stages"] = {}
|
|
1913
|
+
ck_info["pipeline"]["stages"][stage_name] = stage
|
|
1914
|
+
untracked = [
|
|
1915
|
+
path
|
|
1916
|
+
for path, _ in files
|
|
1917
|
+
if not repo.git.ls_files("--", path).strip()
|
|
1918
|
+
and not is_dvc_tracked(wdir, path)
|
|
1919
|
+
]
|
|
1920
|
+
too_big = [
|
|
1921
|
+
path
|
|
1922
|
+
for path in untracked
|
|
1923
|
+
if os.path.getsize(os.path.join(wdir, path)) > FILE_GIT_MAX_BYTES
|
|
1924
|
+
]
|
|
1925
|
+
# Elsewhere, e.g., in CI, the stage couldn't read a file Git leaves out
|
|
1926
|
+
for path in untracked:
|
|
1927
|
+
if path not in too_big and repo.ignored(path):
|
|
1928
|
+
raise ValueError(
|
|
1929
|
+
f"'{path}' is ignored by Git, so the stage couldn't run "
|
|
1930
|
+
"anywhere else; stop ignoring it first"
|
|
1931
|
+
)
|
|
1932
|
+
|
|
1933
|
+
def write() -> list[str]:
|
|
1934
|
+
# Too big for Git, so stored with DVC, as the hub stores an upload;
|
|
1935
|
+
# in its own process, since DVC prints, and this one's output is
|
|
1936
|
+
# the extension's
|
|
1937
|
+
for path in too_big:
|
|
1938
|
+
res = subprocess.run(
|
|
1939
|
+
calkit.get_calkit_cmd() + ["dvc", "add", path],
|
|
1940
|
+
cwd=wdir,
|
|
1941
|
+
capture_output=True,
|
|
1942
|
+
text=True,
|
|
1943
|
+
)
|
|
1944
|
+
if res.returncode != 0:
|
|
1945
|
+
raise ValueError(
|
|
1946
|
+
f"DVC couldn't store {path}: "
|
|
1947
|
+
+ (res.stderr or res.stdout).strip()
|
|
1948
|
+
)
|
|
1949
|
+
return [path + ".dvc" for path in too_big]
|
|
1950
|
+
|
|
1951
|
+
commit_change(
|
|
1952
|
+
wdir,
|
|
1953
|
+
ck_info,
|
|
1954
|
+
write,
|
|
1955
|
+
f"Export {output} from {source}"
|
|
1956
|
+
+ (f" with {exporter.app}" if exporter else " manually"),
|
|
1957
|
+
also_commit=[p for p in untracked if p not in too_big],
|
|
1958
|
+
)
|
|
1959
|
+
return out | {"name": stage_name, "stage": stage, "saved": True}
|
|
1960
|
+
|
|
1961
|
+
|
|
1483
1962
|
def get_pipeline(wdir: str) -> dict:
|
|
1484
1963
|
"""A checkout's pipeline as the hub summarizes one: the stages in
|
|
1485
1964
|
calkit.yaml's order, each one's status here, and the compiled DVC
|