arctiq-cli 0.2.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.
- arctiq_cli/__init__.py +9 -0
- arctiq_cli/__main__.py +3 -0
- arctiq_cli/aws_nitro_root_g1.pem +14 -0
- arctiq_cli/client.py +156 -0
- arctiq_cli/credentials.py +109 -0
- arctiq_cli/main.py +1068 -0
- arctiq_cli/project.py +100 -0
- arctiq_cli/seal.py +217 -0
- arctiq_cli/tui/__init__.py +19 -0
- arctiq_cli/tui/app.py +1208 -0
- arctiq_cli/tui/draw.py +307 -0
- arctiq_cli/tui/folder.py +148 -0
- arctiq_cli/tui/source.py +98 -0
- arctiq_cli-0.2.0.dist-info/METADATA +116 -0
- arctiq_cli-0.2.0.dist-info/RECORD +19 -0
- arctiq_cli-0.2.0.dist-info/WHEEL +5 -0
- arctiq_cli-0.2.0.dist-info/entry_points.txt +2 -0
- arctiq_cli-0.2.0.dist-info/licenses/LICENSE +202 -0
- arctiq_cli-0.2.0.dist-info/top_level.txt +1 -0
arctiq_cli/main.py
ADDED
|
@@ -0,0 +1,1068 @@
|
|
|
1
|
+
"""arctiq login | link | status | artefacts | new | upload | files | download | remove | submit |
|
|
2
|
+
open | pin | resources | ask | tui | logout"""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import argparse
|
|
7
|
+
import contextlib
|
|
8
|
+
import json
|
|
9
|
+
import re
|
|
10
|
+
import socket
|
|
11
|
+
import sys
|
|
12
|
+
import time
|
|
13
|
+
import webbrowser
|
|
14
|
+
from collections.abc import Callable
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import TextIO
|
|
17
|
+
|
|
18
|
+
from arctiq_cli import __version__, credentials, project
|
|
19
|
+
from arctiq_cli.client import Api, ApiError, Transport, part, urllib_transport
|
|
20
|
+
|
|
21
|
+
STATE_WORDS = {
|
|
22
|
+
"draft": "draft",
|
|
23
|
+
"submitted": "submitted · checks running",
|
|
24
|
+
"validating": "submitted · checks running",
|
|
25
|
+
"needs_review": "submitted · waiting for review",
|
|
26
|
+
"approved": "approved",
|
|
27
|
+
"ingested": "approved",
|
|
28
|
+
"live": "live in Discover",
|
|
29
|
+
"revision_requested": "sent back for changes",
|
|
30
|
+
"rejected": "rejected",
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Failed(Exception):
|
|
35
|
+
"""A message for the person; the command ends with status 1."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
ASK_ADDRESS = "Your ARCTIQ address (like https://arctiq.example.com/platform): "
|
|
39
|
+
GIVE_ADDRESS = "Give your ARCTIQ address: arctiq login --server https://arctiq.example.com/platform"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def ask_terminal(prompt: str) -> str:
|
|
43
|
+
"""Ask the person at the terminal; with no terminal (CI, a pipe), say what to pass instead."""
|
|
44
|
+
if not sys.stdin.isatty():
|
|
45
|
+
raise Failed(GIVE_ADDRESS)
|
|
46
|
+
try:
|
|
47
|
+
return input(prompt)
|
|
48
|
+
except EOFError:
|
|
49
|
+
raise Failed(GIVE_ADDRESS) from None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class Cli:
|
|
53
|
+
def __init__(
|
|
54
|
+
self,
|
|
55
|
+
out: TextIO = sys.stdout,
|
|
56
|
+
transport: Transport = urllib_transport,
|
|
57
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
58
|
+
cwd: Path | None = None,
|
|
59
|
+
opener: Callable[[str], object] = webbrowser.open,
|
|
60
|
+
prompt: Callable[[str], str] = ask_terminal,
|
|
61
|
+
) -> None:
|
|
62
|
+
self.out, self.transport, self.sleep = out, transport, sleep
|
|
63
|
+
self.cwd, self.opener, self.prompt = cwd, opener, prompt
|
|
64
|
+
|
|
65
|
+
def say(self, text: str = "") -> None:
|
|
66
|
+
self.out.write(f"{text}\n")
|
|
67
|
+
|
|
68
|
+
def api(self, *, signed_in: bool = True) -> Api:
|
|
69
|
+
saved = credentials.load()
|
|
70
|
+
if signed_in and not saved.token:
|
|
71
|
+
raise Failed("You're not signed in. Run: arctiq login")
|
|
72
|
+
if not saved.server:
|
|
73
|
+
raise Failed("Which ARCTIQ? Run: arctiq login (or set ARCTIQ_SERVER with ARCTIQ_TOKEN)")
|
|
74
|
+
return Api(saved.server, saved.token, self.transport)
|
|
75
|
+
|
|
76
|
+
def here(self) -> tuple[Path, project.Linked]:
|
|
77
|
+
try:
|
|
78
|
+
folder = project.root(self.cwd)
|
|
79
|
+
except project.ProjectError as exc:
|
|
80
|
+
raise Failed(str(exc)) from None
|
|
81
|
+
linked = project.read(folder)
|
|
82
|
+
if linked is None:
|
|
83
|
+
raise Failed("This folder isn't linked to ARCTIQ yet. Run: arctiq link")
|
|
84
|
+
return folder, linked
|
|
85
|
+
|
|
86
|
+
def target(self, repo: str | None) -> project.Linked:
|
|
87
|
+
"""The repository: `--repo organisation/repository`, else this folder's `.arctiq.yml`."""
|
|
88
|
+
if repo:
|
|
89
|
+
org, sep, slug = repo.strip().strip("/").partition("/")
|
|
90
|
+
if not (sep and org and slug) or "/" in slug:
|
|
91
|
+
raise Failed("Give --repo as organisation/repository, like my-org/my-repo.")
|
|
92
|
+
return project.Linked(org.lower(), slug.lower())
|
|
93
|
+
try:
|
|
94
|
+
return self.here()[1]
|
|
95
|
+
except Failed:
|
|
96
|
+
raise Failed(
|
|
97
|
+
"Run this inside a folder linked with `arctiq link`, or name the repository: "
|
|
98
|
+
"--repo organisation/repository"
|
|
99
|
+
) from None
|
|
100
|
+
|
|
101
|
+
@staticmethod
|
|
102
|
+
def base(linked: project.Linked) -> str:
|
|
103
|
+
return f"/orgs/{part(linked.organisation)}/repos/{part(linked.repository)}"
|
|
104
|
+
|
|
105
|
+
def _artefacts(self, linked: project.Linked) -> list[dict]:
|
|
106
|
+
found = self.api().get(f"{self.base(linked)}/artefacts?limit=200")
|
|
107
|
+
return found if isinstance(found, list) else []
|
|
108
|
+
|
|
109
|
+
def pick(self, linked: project.Linked, wanted: str | None) -> dict:
|
|
110
|
+
"""One artefact: by its id, the start of its id (6 or more characters), or the start of
|
|
111
|
+
its title. With nothing given, the repository's only artefact."""
|
|
112
|
+
everything = self._artefacts(linked)
|
|
113
|
+
if not everything:
|
|
114
|
+
raise Failed(f"{linked.repository} has no artefacts yet. Start one: arctiq new")
|
|
115
|
+
if not wanted:
|
|
116
|
+
if len(everything) == 1:
|
|
117
|
+
return everything[0]
|
|
118
|
+
raise Failed("This repository has several artefacts: say which with --artefact.\n"
|
|
119
|
+
+ _listing(everything)) # fmt: skip
|
|
120
|
+
key = wanted.strip().lower()
|
|
121
|
+
by_id = [
|
|
122
|
+
a for a in everything if a["id"] == key or (len(key) >= 6 and a["id"].startswith(key))
|
|
123
|
+
]
|
|
124
|
+
if len(by_id) == 1:
|
|
125
|
+
return by_id[0]
|
|
126
|
+
exact = [a for a in everything if _title(a).lower() == key]
|
|
127
|
+
close = exact or [a for a in everything if _title(a).lower().startswith(key)]
|
|
128
|
+
if len(close) == 1:
|
|
129
|
+
return close[0]
|
|
130
|
+
why = "More than one artefact matches" if close else "No artefact matches"
|
|
131
|
+
raise Failed(f'{why} "{wanted}". Give more of its title, or its id.\n'
|
|
132
|
+
+ _listing(close or everything)) # fmt: skip
|
|
133
|
+
|
|
134
|
+
# ------------------------------------------------------------------ the TUI
|
|
135
|
+
def tui(self, org: str | None) -> None:
|
|
136
|
+
"""Open the terminal app (ADR 0027) for an organisation: `--org`, else the one this
|
|
137
|
+
folder is linked to, else your only one."""
|
|
138
|
+
try:
|
|
139
|
+
from arctiq_cli import tui
|
|
140
|
+
except ImportError:
|
|
141
|
+
raise Failed(
|
|
142
|
+
'The TUI needs the tui extra: pipx install "arctiq-cli[tui]" '
|
|
143
|
+
'(or pip install "arctiq-cli[tui]")'
|
|
144
|
+
) from None
|
|
145
|
+
api = self.api()
|
|
146
|
+
folder, linked = None, None
|
|
147
|
+
with contextlib.suppress(Failed): # not in a linked folder: the TUI opens on Home
|
|
148
|
+
folder, linked = self.here()
|
|
149
|
+
chosen = (org or "").strip().lower() or (linked.organisation if linked else None)
|
|
150
|
+
if chosen is None:
|
|
151
|
+
orgs = api.get("/orgs")
|
|
152
|
+
orgs = orgs if isinstance(orgs, list) else []
|
|
153
|
+
if not orgs:
|
|
154
|
+
raise Failed("You don't belong to an organisation yet. Make one on the pages.")
|
|
155
|
+
if len(orgs) > 1:
|
|
156
|
+
names = "\n".join(f" {o['slug']} {o['name']}" for o in orgs)
|
|
157
|
+
raise Failed(f"Say which organisation: arctiq tui --org <slug>\n{names}")
|
|
158
|
+
chosen = orgs[0]["slug"]
|
|
159
|
+
here = linked is not None and linked.organisation == chosen
|
|
160
|
+
tui.run(api, chosen, linked_repo=linked.repository if here and linked else None,
|
|
161
|
+
folder=folder if here else None) # fmt: skip
|
|
162
|
+
|
|
163
|
+
# ------------------------------------------------------------------ artefacts and files
|
|
164
|
+
def artefacts(self, repo: str | None) -> None:
|
|
165
|
+
linked = self.target(repo)
|
|
166
|
+
everything = self._artefacts(linked)
|
|
167
|
+
if not everything:
|
|
168
|
+
self.say(f"{linked.repository} has no artefacts yet. Start one: arctiq new")
|
|
169
|
+
return
|
|
170
|
+
self.say(_listing(everything))
|
|
171
|
+
|
|
172
|
+
def new(self, repo: str | None, fields: dict[str, str | None]) -> None:
|
|
173
|
+
linked = self.target(repo)
|
|
174
|
+
made = self.api().post(
|
|
175
|
+
f"{self.base(linked)}/artefacts", {k: v for k, v in fields.items() if v}
|
|
176
|
+
)
|
|
177
|
+
assert isinstance(made, dict)
|
|
178
|
+
self.say(f'Started a draft: {made["id"][:8]} "{_title(made)}"')
|
|
179
|
+
self.say(f"Add files: arctiq upload FILE... --artefact {made['id'][:8]}")
|
|
180
|
+
self.say(f"In ARCTIQ: {made['web_url']}")
|
|
181
|
+
|
|
182
|
+
def upload(self, repo: str | None, artefact: str | None, paths: list[str]) -> bool:
|
|
183
|
+
linked = self.target(repo)
|
|
184
|
+
chosen = self.pick(linked, artefact)
|
|
185
|
+
url = f"{self.base(linked)}/artefacts/{part(chosen['id'])}/files"
|
|
186
|
+
self.say(f'Uploading to {chosen["id"][:8]} "{_title(chosen)}"')
|
|
187
|
+
ok = True
|
|
188
|
+
for raw in paths:
|
|
189
|
+
path = Path(raw).expanduser()
|
|
190
|
+
if not path.is_absolute():
|
|
191
|
+
path = (self.cwd or Path.cwd()) / path
|
|
192
|
+
if not path.is_file():
|
|
193
|
+
self.say(f" x {raw}: no such file")
|
|
194
|
+
ok = False
|
|
195
|
+
continue
|
|
196
|
+
try:
|
|
197
|
+
stored = self.api().upload(url, path.name, path.read_bytes())
|
|
198
|
+
except ApiError as exc:
|
|
199
|
+
self.say(f" x {path.name}: {exc.detail}")
|
|
200
|
+
ok = False
|
|
201
|
+
continue
|
|
202
|
+
assert isinstance(stored, dict)
|
|
203
|
+
scan = ""
|
|
204
|
+
if stored.get("screening"):
|
|
205
|
+
scan = f" · {stored['screening']}"
|
|
206
|
+
if stored.get("risk") is not None:
|
|
207
|
+
scan += f" · risk {stored['risk']} · fit {stored.get('fit')}"
|
|
208
|
+
self.say(f" ok {stored['filename']} · {_size(stored['size_bytes'])}{scan}")
|
|
209
|
+
return ok
|
|
210
|
+
|
|
211
|
+
def files(self, repo: str | None, artefact: str | None) -> None:
|
|
212
|
+
linked = self.target(repo)
|
|
213
|
+
chosen = self.pick(linked, artefact)
|
|
214
|
+
listed = self.api().get(f"{self.base(linked)}/artefacts/{part(chosen['id'])}/files")
|
|
215
|
+
listed = listed if isinstance(listed, list) else []
|
|
216
|
+
self.say(f'{chosen["id"][:8]} "{_title(chosen)}" · {len(listed)} file(s)')
|
|
217
|
+
width = max((len(f["filename"]) for f in listed), default=0)
|
|
218
|
+
for f in listed:
|
|
219
|
+
self.say(
|
|
220
|
+
f" {f['filename']:<{width + 2}}{_size(f['size_bytes']):>9} sha256 {f['sha256'][:12]}…"
|
|
221
|
+
)
|
|
222
|
+
|
|
223
|
+
def _file(self, linked: project.Linked, chosen: dict, name: str) -> dict:
|
|
224
|
+
listed = self.api().get(f"{self.base(linked)}/artefacts/{part(chosen['id'])}/files")
|
|
225
|
+
listed = listed if isinstance(listed, list) else []
|
|
226
|
+
match = [f for f in listed if f["filename"] == name or f["id"] == name]
|
|
227
|
+
if len(match) != 1:
|
|
228
|
+
names = ", ".join(f["filename"] for f in listed) or "none"
|
|
229
|
+
raise Failed(f'No file called "{name}" on that artefact. Its files: {names}')
|
|
230
|
+
return match[0]
|
|
231
|
+
|
|
232
|
+
def download(
|
|
233
|
+
self, repo: str | None, artefact: str | None, name: str, to: str | None, force: bool
|
|
234
|
+
) -> None:
|
|
235
|
+
linked = self.target(repo)
|
|
236
|
+
chosen = self.pick(linked, artefact)
|
|
237
|
+
stored = self._file(linked, chosen, name)
|
|
238
|
+
folder = Path(to).expanduser() if to else (self.cwd or Path.cwd())
|
|
239
|
+
if not folder.is_dir():
|
|
240
|
+
raise Failed(f"{folder} isn't a folder.")
|
|
241
|
+
dest = folder / Path(stored["filename"]).name
|
|
242
|
+
if dest.exists() and not force:
|
|
243
|
+
raise Failed(f"{dest} already exists. Add --force to replace it.")
|
|
244
|
+
data = self.api().download(
|
|
245
|
+
f"{self.base(linked)}/artefacts/{part(chosen['id'])}/files/{part(stored['id'])}/content"
|
|
246
|
+
)
|
|
247
|
+
dest.write_bytes(data)
|
|
248
|
+
self.say(f"Saved {dest} · {_size(len(data))}")
|
|
249
|
+
|
|
250
|
+
def remove(self, repo: str | None, artefact: str | None, name: str) -> None:
|
|
251
|
+
linked = self.target(repo)
|
|
252
|
+
chosen = self.pick(linked, artefact)
|
|
253
|
+
stored = self._file(linked, chosen, name)
|
|
254
|
+
self.api().delete(
|
|
255
|
+
f"{self.base(linked)}/artefacts/{part(chosen['id'])}/files/{part(stored['id'])}"
|
|
256
|
+
)
|
|
257
|
+
self.say(f"Removed {stored['filename']} from {chosen['id'][:8]}.")
|
|
258
|
+
|
|
259
|
+
def submit(self, repo: str | None, artefact: str | None) -> None:
|
|
260
|
+
linked = self.target(repo)
|
|
261
|
+
chosen = self.pick(linked, artefact)
|
|
262
|
+
done = self.api().post(f"{self.base(linked)}/artefacts/{part(chosen['id'])}/submit", {})
|
|
263
|
+
assert isinstance(done, dict)
|
|
264
|
+
state = STATE_WORDS.get(done["state"], done["state"])
|
|
265
|
+
self.say(f'Submitted {done["id"][:8]} "{_title(done)}" · {state}')
|
|
266
|
+
if done.get("submission_hash"):
|
|
267
|
+
self.say(f"Submission hash {done['submission_hash'][:16]}… (fixed from now on)")
|
|
268
|
+
|
|
269
|
+
def open(self, repo: str | None, artefact: str | None) -> None:
|
|
270
|
+
linked = self.target(repo)
|
|
271
|
+
if artefact:
|
|
272
|
+
url = self.pick(linked, artefact)["web_url"]
|
|
273
|
+
else:
|
|
274
|
+
found = self.api().get(self.base(linked))
|
|
275
|
+
assert isinstance(found, dict)
|
|
276
|
+
url = found["web_url"]
|
|
277
|
+
self.say(url)
|
|
278
|
+
self.opener(url)
|
|
279
|
+
|
|
280
|
+
# ------------------------------------------------------------------ login, logout
|
|
281
|
+
def login(self, server: str | None, name: str | None) -> None:
|
|
282
|
+
found = credentials.address(server or credentials.load().server or "")
|
|
283
|
+
if not found: # the first sign-in: there is no built-in server
|
|
284
|
+
found = credentials.address(self.prompt(ASK_ADDRESS))
|
|
285
|
+
if not found:
|
|
286
|
+
raise Failed(GIVE_ADDRESS)
|
|
287
|
+
api = Api(found, None, self.transport)
|
|
288
|
+
started = api.post(
|
|
289
|
+
"/device/code",
|
|
290
|
+
{
|
|
291
|
+
"client_name": name or f"arctiq CLI on {socket.gethostname()[:40]}",
|
|
292
|
+
"scopes": ["read", "write"],
|
|
293
|
+
},
|
|
294
|
+
)
|
|
295
|
+
assert isinstance(started, dict)
|
|
296
|
+
self.say(f"Open {started['verification_uri']} and enter {started['user_code']}")
|
|
297
|
+
interval = float(started.get("interval") or 5)
|
|
298
|
+
deadline = time.monotonic() + float(started.get("expires_in") or 600)
|
|
299
|
+
while True:
|
|
300
|
+
self.sleep(interval)
|
|
301
|
+
try:
|
|
302
|
+
token = api.post("/device/token", {"device_code": started["device_code"]})
|
|
303
|
+
break
|
|
304
|
+
except ApiError as exc:
|
|
305
|
+
if exc.error == "authorization_pending" and time.monotonic() < deadline:
|
|
306
|
+
continue
|
|
307
|
+
if exc.error == "slow_down":
|
|
308
|
+
interval += 5
|
|
309
|
+
continue
|
|
310
|
+
if exc.error == "access_denied":
|
|
311
|
+
raise Failed("The sign-in was refused in the browser.") from None
|
|
312
|
+
if exc.error == "expired_token" or time.monotonic() >= deadline:
|
|
313
|
+
raise Failed("The code expired. Run arctiq login again.") from None
|
|
314
|
+
raise
|
|
315
|
+
assert isinstance(token, dict)
|
|
316
|
+
where = credentials.save(api.server, token["access_token"])
|
|
317
|
+
me = Api(api.server, token["access_token"], self.transport).get("/me")
|
|
318
|
+
assert isinstance(me, dict)
|
|
319
|
+
scopes = "read and change" if "write" in token.get("scope", "") else "read only"
|
|
320
|
+
kept = "the system keyring" if where == "keyring" else "a file only you can read"
|
|
321
|
+
self.say(
|
|
322
|
+
f'Signed in as {me["display_name"]} · token "{token["name"]}" · {scopes} · '
|
|
323
|
+
f"until {str(token['expires_at'])[:10]}"
|
|
324
|
+
)
|
|
325
|
+
self.say(f"The token is kept in {kept}. It is listed in Settings, Access tokens.")
|
|
326
|
+
|
|
327
|
+
def logout(self) -> None:
|
|
328
|
+
saved = credentials.load()
|
|
329
|
+
if saved.where == "environment":
|
|
330
|
+
raise Failed("The token comes from ARCTIQ_TOKEN: unset it to sign out.")
|
|
331
|
+
if saved.token and saved.server:
|
|
332
|
+
api = Api(saved.server, saved.token, self.transport)
|
|
333
|
+
try:
|
|
334
|
+
mine = api.get("/tokens")
|
|
335
|
+
for t in mine if isinstance(mine, list) else []:
|
|
336
|
+
if saved.token.startswith(str(t.get("prefix") or "\0")):
|
|
337
|
+
api.delete(f"/tokens/{part(str(t['id']))}")
|
|
338
|
+
except ApiError:
|
|
339
|
+
pass # already revoked or expired: forgetting it is enough
|
|
340
|
+
credentials.forget(saved.server)
|
|
341
|
+
self.say("Signed out. The token is revoked and forgotten.")
|
|
342
|
+
|
|
343
|
+
# ------------------------------------------------------------------ link
|
|
344
|
+
def link(self) -> None:
|
|
345
|
+
try:
|
|
346
|
+
folder = project.root(self.cwd)
|
|
347
|
+
owner, name = project.github_of(folder)
|
|
348
|
+
except project.ProjectError as exc:
|
|
349
|
+
raise Failed(str(exc)) from None
|
|
350
|
+
self.say(f"This folder is {owner}/{name} on GitHub.")
|
|
351
|
+
try:
|
|
352
|
+
found = self.api().get(f"/github/{part(owner)}/{part(name)}")
|
|
353
|
+
except ApiError as exc:
|
|
354
|
+
if exc.status == 404:
|
|
355
|
+
raise Failed(
|
|
356
|
+
f"No ARCTIQ repository you can open is linked to {owner}/{name}. An Owner "
|
|
357
|
+
"or Admin links it in ARCTIQ, under Connections."
|
|
358
|
+
) from None
|
|
359
|
+
raise
|
|
360
|
+
assert isinstance(found, dict)
|
|
361
|
+
repo = found["repository"]
|
|
362
|
+
project.write(folder, project.Linked(found["organisation"], repo["slug"]))
|
|
363
|
+
self.say(
|
|
364
|
+
f"Linked to the ARCTIQ repository {repo['slug']} ({found['organisation_name']}). "
|
|
365
|
+
f"Wrote {project.CONFIG}"
|
|
366
|
+
)
|
|
367
|
+
|
|
368
|
+
# ------------------------------------------------------------------ status, resources
|
|
369
|
+
def _status(self) -> dict:
|
|
370
|
+
_, linked = self.here()
|
|
371
|
+
status = self.api().get(
|
|
372
|
+
f"/orgs/{part(linked.organisation)}/repos/{part(linked.repository)}/status"
|
|
373
|
+
)
|
|
374
|
+
assert isinstance(status, dict)
|
|
375
|
+
return status
|
|
376
|
+
|
|
377
|
+
def status(self) -> None:
|
|
378
|
+
s = self._status()
|
|
379
|
+
repo = s["repository"]
|
|
380
|
+
facts = [repo["slug"], str(repo["type"]).replace("_", " ").capitalize()]
|
|
381
|
+
facts.append("listed in Discover" if s["listed_in_discover"] else "not listed in Discover")
|
|
382
|
+
if s["open_to"]:
|
|
383
|
+
facts.append("open to " + ", ".join(s["open_to"]))
|
|
384
|
+
self.say(f"{'Repository':<13}{' · '.join(facts)}")
|
|
385
|
+
if s.get("github"):
|
|
386
|
+
self.say(f"{'GitHub':<13}{s['github']}")
|
|
387
|
+
lines = s["artefacts"] or []
|
|
388
|
+
width = max((len(a["title"]) for a in lines[:10]), default=0)
|
|
389
|
+
for i, a in enumerate(lines[:10]):
|
|
390
|
+
label = "Artefacts" if i == 0 else ""
|
|
391
|
+
state = STATE_WORDS.get(a["state"], a["state"])
|
|
392
|
+
pins = f" · {a['pins']} pinned" if a["pins"] else ""
|
|
393
|
+
self.say(f"{label:<13}{a['title']:<{width + 2}}{state}{pins}")
|
|
394
|
+
if not lines:
|
|
395
|
+
self.say(f"{'Artefacts':<13}none yet")
|
|
396
|
+
if s.get("proposals_waiting") is not None:
|
|
397
|
+
n = s["proposals_waiting"]
|
|
398
|
+
self.say(f"{'Proposals':<13}" + (f"{n} waiting for you" if n else "none waiting"))
|
|
399
|
+
check = s.get("last_check")
|
|
400
|
+
if check:
|
|
401
|
+
words = {"success": "passed", "neutral": "passed", "failure": "failed"}
|
|
402
|
+
notes = (
|
|
403
|
+
f" · {check['notes']} note{'s' if check['notes'] != 1 else ''}"
|
|
404
|
+
if check["notes"]
|
|
405
|
+
else ""
|
|
406
|
+
)
|
|
407
|
+
self.say(
|
|
408
|
+
f"{'Last check':<13}pull request #{check['pull_request']} · "
|
|
409
|
+
f"{words.get(check['conclusion'], check['conclusion'])}{notes}"
|
|
410
|
+
)
|
|
411
|
+
self.say(f"{'In ARCTIQ':<13}{repo['web_url']}")
|
|
412
|
+
|
|
413
|
+
# ------------------------------------------------------------------ resources (ADR 0030)
|
|
414
|
+
def _resources(self, linked: project.Linked) -> dict:
|
|
415
|
+
found = self.api().get(f"{self.base(linked)}/resources")
|
|
416
|
+
assert isinstance(found, dict)
|
|
417
|
+
return found
|
|
418
|
+
|
|
419
|
+
def resources(self, repo: str | None, as_json: bool = False) -> None:
|
|
420
|
+
"""The Resources tab: the repository's code, data and documents, then partners'."""
|
|
421
|
+
linked = self.target(repo)
|
|
422
|
+
found = self._resources(linked)
|
|
423
|
+
if as_json:
|
|
424
|
+
self.say(json.dumps(found, indent=2, default=str))
|
|
425
|
+
return
|
|
426
|
+
yours, theirs = found["yours"], found["from_partners"]
|
|
427
|
+
n = len(yours) + len(theirs)
|
|
428
|
+
self.say(f"{found['repository_name']} · {found['organisation_name']} · "
|
|
429
|
+
f"{n} resource{'s' if n != 1 else ''}") # fmt: skip
|
|
430
|
+
if not n:
|
|
431
|
+
self.say("Nothing yet. Add a dataset or a document: arctiq resources add FILE")
|
|
432
|
+
return
|
|
433
|
+
if yours:
|
|
434
|
+
self.say()
|
|
435
|
+
self.say(_row("YOURS", "", "WHERE", "OFFERED UP TO", "SPACES"))
|
|
436
|
+
for r in yours:
|
|
437
|
+
where = r["where"] + (f" · {_size(r['size_bytes'])}" if r.get("size_bytes") else "")
|
|
438
|
+
version = f" v{r['version']}" if r.get("version") else ""
|
|
439
|
+
spaces = ", ".join(p.split()[0] for p in r["spaces"]) or "–"
|
|
440
|
+
self.say(_row(r["kind"], r["name"] + version, where, _level(r), spaces))
|
|
441
|
+
if theirs:
|
|
442
|
+
self.say()
|
|
443
|
+
self.say(_row("FROM PARTNERS", "", "SPACE", "LEVEL", "UNTIL"))
|
|
444
|
+
for r in theirs:
|
|
445
|
+
until = _date(r["until"]) if r.get("until") else "–"
|
|
446
|
+
if r.get("days_left") is not None:
|
|
447
|
+
until += f" · {r['days_left']} day{'s' if r['days_left'] != 1 else ''}"
|
|
448
|
+
self.say(_row(r["kind"], r["name"], r["partner"], _level(r), until))
|
|
449
|
+
self.say()
|
|
450
|
+
self.say("--json for scripts · arctiq resources show <name> for one")
|
|
451
|
+
|
|
452
|
+
def _pick_resource(self, linked: project.Linked, wanted: str) -> dict:
|
|
453
|
+
"""One resource, yours or a partner's: by its id (or 6+ characters of it), its name, or
|
|
454
|
+
its name as words joined by hyphens (`field-run-magnetometer-records`)."""
|
|
455
|
+
found = self._resources(linked)
|
|
456
|
+
every = [r for r in found["yours"] if r.get("id")] + found["from_partners"]
|
|
457
|
+
key = wanted.strip().lower()
|
|
458
|
+
by_id = [r for r in every if r["id"] == key or (len(key) >= 6 and r["id"].startswith(key))]
|
|
459
|
+
if len(by_id) == 1:
|
|
460
|
+
return by_id[0]
|
|
461
|
+
exact = [r for r in every if key in (r["name"].lower(), _slug(r["name"]))]
|
|
462
|
+
close = exact or [r for r in every
|
|
463
|
+
if r["name"].lower().startswith(key) or _slug(r["name"]).startswith(key)] # fmt: skip
|
|
464
|
+
if len(close) == 1:
|
|
465
|
+
return close[0]
|
|
466
|
+
names = "\n".join(f" {r['id'][:8]} {r['name']}" for r in (close or every)[:50])
|
|
467
|
+
why = "More than one resource matches" if close else "No resource matches"
|
|
468
|
+
raise Failed(f'{why} "{wanted}". Give more of its name, or its id.\n{names}')
|
|
469
|
+
|
|
470
|
+
def show_resource(self, repo: str | None, wanted: str, as_json: bool = False) -> None:
|
|
471
|
+
linked = self.target(repo)
|
|
472
|
+
chosen = self._pick_resource(linked, wanted)
|
|
473
|
+
one = self.api().get(f"{self.base(linked)}/resources/{part(chosen['id'])}")
|
|
474
|
+
assert isinstance(one, dict)
|
|
475
|
+
if as_json:
|
|
476
|
+
self.say(json.dumps(one, indent=2, default=str))
|
|
477
|
+
return
|
|
478
|
+
version = f" · v{one['version']}" if one.get("version") else ""
|
|
479
|
+
self.say(f"{one['name']} · {one['kind']}{version}")
|
|
480
|
+
self.say(f"{'Where':<13}{one['where']} · {one['where_note']}")
|
|
481
|
+
self.say(f"{'Level':<13}{_level(one) if one.get('level') else 'Not offered'}")
|
|
482
|
+
if one.get("personal_data"):
|
|
483
|
+
self.say(f"{'':<13}Contains personal data: at most 3 · Try it")
|
|
484
|
+
if one.get("description"):
|
|
485
|
+
self.say(f"{'About it':<13}{' '.join(str(one['description']).split())[:300]}")
|
|
486
|
+
summary = one.get("summary")
|
|
487
|
+
if summary:
|
|
488
|
+
self._summary(one, summary)
|
|
489
|
+
else:
|
|
490
|
+
width = max((len(c["name"]) for c in one["columns"]), default=0)
|
|
491
|
+
for i, c in enumerate(one["columns"]):
|
|
492
|
+
key = " · key" if c["key"] else ""
|
|
493
|
+
unit = f" · {c['unit']}" if c.get("unit") else ""
|
|
494
|
+
limits = c.get("range")
|
|
495
|
+
declared = f" · {_number(limits[0])} to {_number(limits[1])}" if limits else ""
|
|
496
|
+
self.say(f"{'Columns' if i == 0 else '':<13}{c['name']:<{width + 2}}"
|
|
497
|
+
f"{c['type']}{key}{unit}{declared}") # fmt: skip
|
|
498
|
+
if one.get("summary_problem"):
|
|
499
|
+
self.say(
|
|
500
|
+
f"{'Shape':<13}Its summary can't be made just now: {one['summary_problem']}"
|
|
501
|
+
)
|
|
502
|
+
for i, f in enumerate(one["files"]):
|
|
503
|
+
scan = f" · {f['scan']}" if f.get("scan") else ""
|
|
504
|
+
self.say(f"{'Files' if i == 0 else '':<13}{f['name']} · {_size(f['size_bytes'])}{scan}")
|
|
505
|
+
|
|
506
|
+
def _summary(self, one: dict, summary: dict) -> None:
|
|
507
|
+
"""A partner's dataset at 2 · See its shape: each column summarised, counts with noise."""
|
|
508
|
+
made = str(summary["made_at"])[:10]
|
|
509
|
+
source = f"v{summary['version']}" if summary["version"] else "their bucket"
|
|
510
|
+
self.say(f"{'Shape':<13}about {summary['rows']:,} rows · summarised for this space on "
|
|
511
|
+
f"{made}, from {source} · counts carry noise") # fmt: skip
|
|
512
|
+
cols = summary["columns"]
|
|
513
|
+
width = max((len(c["name"]) for c in cols), default=0)
|
|
514
|
+
kinds = max((len(c["kind"]) for c in cols), default=0)
|
|
515
|
+
for c in cols:
|
|
516
|
+
detail = c["summary"]
|
|
517
|
+
if c["shares"]:
|
|
518
|
+
detail += ": " + ", ".join(f"{s['value']} about {s['percent']}%"
|
|
519
|
+
for s in c["shares"]) # fmt: skip
|
|
520
|
+
if c["bars"]:
|
|
521
|
+
detail += " " + "".join(_BARS[min(len(_BARS) - 1, h * len(_BARS) // 100)]
|
|
522
|
+
for h in c["bars"]) # fmt: skip
|
|
523
|
+
if c["note"]:
|
|
524
|
+
detail += f" ({c['note']})"
|
|
525
|
+
self.say(f"{'':<13}{c['name']:<{width + 2}}{c['kind']:<{kinds + 2}}{detail}")
|
|
526
|
+
self.say(f"{'Sample':<13}arctiq resources sample {_quoted(one['name'])}: "
|
|
527
|
+
"12 made-up rows, --csv FILE to save them") # fmt: skip
|
|
528
|
+
|
|
529
|
+
def sample(self, repo: str | None, wanted: str, seed: int | None = None,
|
|
530
|
+
csv_path: str | None = None, as_json: bool = False) -> None: # fmt: skip
|
|
531
|
+
"""A partner's synthetic sample: made-up rows drawn from its summary, none of them real."""
|
|
532
|
+
linked = self.target(repo)
|
|
533
|
+
chosen = self._pick_resource(linked, wanted)
|
|
534
|
+
if not chosen.get("partner"):
|
|
535
|
+
raise Failed(f"{chosen['name']} is yours. A sample is drawn from what partners share "
|
|
536
|
+
"with this repository: arctiq resources") # fmt: skip
|
|
537
|
+
path = f"{self.base(linked)}/resources/{part(chosen['id'])}/sample"
|
|
538
|
+
try:
|
|
539
|
+
got = self.api().get(path + (f"?seed={seed}" if seed is not None else ""))
|
|
540
|
+
except ApiError as exc:
|
|
541
|
+
if exc.status in (403, 409):
|
|
542
|
+
raise Failed(f"No sample: {exc.detail}") from None
|
|
543
|
+
raise
|
|
544
|
+
assert isinstance(got, dict)
|
|
545
|
+
if as_json:
|
|
546
|
+
self.say(json.dumps(got, indent=2, default=str))
|
|
547
|
+
return
|
|
548
|
+
if csv_path:
|
|
549
|
+
target = Path(csv_path).expanduser()
|
|
550
|
+
target.write_text(got["csv"], encoding="utf-8")
|
|
551
|
+
self.say(f"Saved {len(got['rows'])} made-up rows to {target} · seed {got['seed']}")
|
|
552
|
+
return
|
|
553
|
+
widths = [
|
|
554
|
+
max([len(h)] + [len(r[i]) for r in got["rows"]]) for i, h in enumerate(got["headings"])
|
|
555
|
+
]
|
|
556
|
+
self.say(
|
|
557
|
+
" ".join(h.upper().ljust(w) for h, w in zip(got["headings"], widths, strict=True))
|
|
558
|
+
)
|
|
559
|
+
for row in got["rows"]:
|
|
560
|
+
self.say(
|
|
561
|
+
" ".join((v or "–").ljust(w) for v, w in zip(row, widths, strict=True)).rstrip()
|
|
562
|
+
)
|
|
563
|
+
self.say(f"Made up from {got['partner']}'s summary, each column on its own: no row is "
|
|
564
|
+
f"real. --seed {got['seed']} for the same rows.") # fmt: skip
|
|
565
|
+
|
|
566
|
+
def add_resource(self, repo: str | None, paths: list[str], fields: dict) -> None:
|
|
567
|
+
"""Files to ARCTIQ storage, in parts (each sealed as it arrives, then screened), then the
|
|
568
|
+
resource they make. With no files, a resource described only."""
|
|
569
|
+
linked = self.target(repo)
|
|
570
|
+
files = [Path(p).expanduser() for p in paths]
|
|
571
|
+
for f in files:
|
|
572
|
+
if not f.is_file():
|
|
573
|
+
raise Failed(f"{f} isn't a file.")
|
|
574
|
+
api, base = self.api(), f"{self.base(linked)}/resources"
|
|
575
|
+
body = {k: v for k, v in fields.items() if v is not None}
|
|
576
|
+
body.setdefault("name", files[0].stem.replace("_", " ") if files else "")
|
|
577
|
+
if not body["name"]:
|
|
578
|
+
raise Failed("Give it a name: --name")
|
|
579
|
+
if files:
|
|
580
|
+
draft = api.post(f"{base}/drafts", {"kind": body.get("kind", "dataset")})
|
|
581
|
+
assert isinstance(draft, dict)
|
|
582
|
+
for f in files:
|
|
583
|
+
kept = self._send_file(api, f"{base}/{part(draft['id'])}", f)
|
|
584
|
+
scan = "" if kept.get("scan") in (None, "clean") else f" · {kept['scan']}"
|
|
585
|
+
cols = kept.get("columns") or 0
|
|
586
|
+
cols_note = f" · {cols} column{'s' if cols != 1 else ''} read" if cols else ""
|
|
587
|
+
self.say(f"Sent {kept['name']} · {_size(kept['size_bytes'])}{scan}{cols_note}")
|
|
588
|
+
body.update(location="arctiq", draft=draft["id"])
|
|
589
|
+
else:
|
|
590
|
+
body.setdefault("location", "described")
|
|
591
|
+
made = api.post(base, body)
|
|
592
|
+
assert isinstance(made, dict)
|
|
593
|
+
level = f" · offered up to {_level(made)}" if made.get("level") else " · not offered"
|
|
594
|
+
self.say(f"Added {made['name']} ({made['kind']}) · {made['where']}{level}")
|
|
595
|
+
|
|
596
|
+
def add_version(self, repo: str | None, wanted: str, paths: list[str], *,
|
|
597
|
+
local_stand_in: bool = False) -> None: # fmt: skip
|
|
598
|
+
"""Files as the next version of one of your datasets. A dataset sealed for enclaves gets
|
|
599
|
+
them sealed here first, to its enclave key, once that key's attestation checks out."""
|
|
600
|
+
linked = self.target(repo)
|
|
601
|
+
files = [Path(p).expanduser() for p in paths]
|
|
602
|
+
for f in files:
|
|
603
|
+
if not f.is_file():
|
|
604
|
+
raise Failed(f"{f} isn't a file.")
|
|
605
|
+
chosen = self._pick_resource(linked, wanted)
|
|
606
|
+
if chosen.get("partner"):
|
|
607
|
+
raise Failed(
|
|
608
|
+
f"{chosen['name']} is {chosen['partner']}'s: only its owner adds versions."
|
|
609
|
+
)
|
|
610
|
+
api = self.api()
|
|
611
|
+
base = f"{self.base(linked)}/resources/{part(chosen['id'])}"
|
|
612
|
+
one = api.get(base)
|
|
613
|
+
assert isinstance(one, dict)
|
|
614
|
+
key = None
|
|
615
|
+
if one.get("sealed"):
|
|
616
|
+
from arctiq_cli import seal
|
|
617
|
+
|
|
618
|
+
got = api.get(f"{base}/enclave-key")
|
|
619
|
+
assert isinstance(got, dict)
|
|
620
|
+
try:
|
|
621
|
+
checked = seal.check_key(got, local_stand_in=local_stand_in)
|
|
622
|
+
except seal.SealFailed as exc:
|
|
623
|
+
raise Failed(str(exc)) from None
|
|
624
|
+
key = got
|
|
625
|
+
self.say(f"{one['name']} is sealed for enclaves. Its key was made in {checked.image}, "
|
|
626
|
+
f"checked against {checked.root}'s root.\n PCR0 {checked.pcr0}") # fmt: skip
|
|
627
|
+
if checked.root == "the local stand-in":
|
|
628
|
+
self.say("The local stand-in runs in ARCTIQ's own process: it protects nothing "
|
|
629
|
+
"from ARCTIQ.") # fmt: skip
|
|
630
|
+
for f in files:
|
|
631
|
+
kept = self._send_file(api, base, f, key)
|
|
632
|
+
scan = "" if kept.get("scan") in (None, "clean", "reading") else f" · {kept['scan']}"
|
|
633
|
+
sealed = " · sealed here" if key else ""
|
|
634
|
+
self.say(f"Sent {kept['name']} · {_size(kept['size_bytes'])}{sealed}{scan}")
|
|
635
|
+
if key is not None:
|
|
636
|
+
self._wait_for_reading(api, base)
|
|
637
|
+
made = api.post(f"{base}/versions", {})
|
|
638
|
+
assert isinstance(made, dict)
|
|
639
|
+
self.say(f"{one['name']} is now at version {made['version']}. Each space holding it waits "
|
|
640
|
+
"for you to check it there.") # fmt: skip
|
|
641
|
+
|
|
642
|
+
def _wait_for_reading(self, api: Api, base: str) -> None:
|
|
643
|
+
"""Sealed files are read in an enclave after they are sent: the version waits for every
|
|
644
|
+
one (an hour at most). Those the enclave didn't keep are said, with why."""
|
|
645
|
+
one = api.get(base)
|
|
646
|
+
assert isinstance(one, dict)
|
|
647
|
+
said = False
|
|
648
|
+
deadline = time.monotonic() + 65 * 60
|
|
649
|
+
while one.get("reading") and time.monotonic() < deadline:
|
|
650
|
+
if not said:
|
|
651
|
+
n = len(one["reading"])
|
|
652
|
+
self.say(f"Waiting for an enclave to read {n} file{'s' if n != 1 else ''} (about "
|
|
653
|
+
"3 minutes when none is running)…") # fmt: skip
|
|
654
|
+
said = True
|
|
655
|
+
self.sleep(3)
|
|
656
|
+
one = api.get(base)
|
|
657
|
+
assert isinstance(one, dict)
|
|
658
|
+
for gone in one.get("not_kept") or []:
|
|
659
|
+
self.say(f"Not kept: {gone['name']}. {gone['why']}")
|
|
660
|
+
if one.get("reading"):
|
|
661
|
+
raise Failed("The files weren't read within an hour. Send them again later.")
|
|
662
|
+
|
|
663
|
+
def _send_file(self, api: Api, base: str, f: Path, key: dict | None = None) -> dict:
|
|
664
|
+
"""One file in parts. `key`: the dataset's enclave key, checked; the file is then sealed
|
|
665
|
+
here, frame by frame as it is sent, with a key made for it alone (never resumed: that key
|
|
666
|
+
was this run's only)."""
|
|
667
|
+
size = f.stat().st_size
|
|
668
|
+
body: dict = {"filename": f.name, "size": size,
|
|
669
|
+
"fingerprint": f"{f.name}:{size}:{int(f.stat().st_mtime)}"} # fmt: skip
|
|
670
|
+
if key is not None:
|
|
671
|
+
from arctiq_cli import seal
|
|
672
|
+
|
|
673
|
+
body.update(size=seal.sealed_size(size), sealed=True)
|
|
674
|
+
upload = api.post(f"{base}/uploads", body)
|
|
675
|
+
assert isinstance(upload, dict)
|
|
676
|
+
url = f"{base}/uploads/{part(upload['id'])}"
|
|
677
|
+
finish: dict = {}
|
|
678
|
+
if key is None:
|
|
679
|
+
with f.open("rb") as source:
|
|
680
|
+
for n in range(1, upload["parts"] + 1):
|
|
681
|
+
if n in upload["received"]:
|
|
682
|
+
continue # resumed: already there
|
|
683
|
+
source.seek((n - 1) * upload["part_size"])
|
|
684
|
+
api.put_bytes(f"{url}/parts/{n}", source.read(upload["part_size"]))
|
|
685
|
+
else:
|
|
686
|
+
secret = seal.new_key()
|
|
687
|
+
buffer, n, size_part = bytearray(), 1, upload["part_size"]
|
|
688
|
+
for frame in seal.frames(secret, upload["blob_key"], f):
|
|
689
|
+
buffer += frame
|
|
690
|
+
while len(buffer) >= size_part:
|
|
691
|
+
api.put_bytes(f"{url}/parts/{n}", bytes(buffer[:size_part]))
|
|
692
|
+
del buffer[:size_part]
|
|
693
|
+
n += 1
|
|
694
|
+
if buffer:
|
|
695
|
+
api.put_bytes(f"{url}/parts/{n}", bytes(buffer))
|
|
696
|
+
finish = {"wrapped": seal.wrap(key["public_key"].encode(), secret)}
|
|
697
|
+
kept = api.post(f"{url}/done", finish)
|
|
698
|
+
assert isinstance(kept, dict)
|
|
699
|
+
return kept
|
|
700
|
+
|
|
701
|
+
# ------------------------------------------------------------------ ask (ADR 0030)
|
|
702
|
+
def ask(self, repo: str | None, wanted: str, question: dict, as_json: bool = False,
|
|
703
|
+
wait: bool = True) -> int: # fmt: skip
|
|
704
|
+
"""Try it from a terminal: the same rules, noise, budget and log as the space's page. A
|
|
705
|
+
question answered in a sealed enclave, or in its owner's cloud, is waited for (`wait`),
|
|
706
|
+
or left to come later."""
|
|
707
|
+
linked = self.target(repo)
|
|
708
|
+
chosen = self._pick_resource(linked, wanted)
|
|
709
|
+
if not chosen.get("partner"):
|
|
710
|
+
raise Failed(f"{chosen['name']} is yours. Questions are for what partners share with "
|
|
711
|
+
"this repository: arctiq resources") # fmt: skip
|
|
712
|
+
base = f"{self.base(linked)}/resources/{part(chosen['id'])}"
|
|
713
|
+
try:
|
|
714
|
+
answer = self.api().post(f"{base}/ask", question)
|
|
715
|
+
except ApiError as exc:
|
|
716
|
+
if exc.status == 403:
|
|
717
|
+
raise Failed(f"Refused: {exc.detail}") from None
|
|
718
|
+
raise
|
|
719
|
+
assert isinstance(answer, dict)
|
|
720
|
+
if answer.get("waiting"):
|
|
721
|
+
if not wait:
|
|
722
|
+
if as_json:
|
|
723
|
+
self.say(json.dumps(answer, indent=2, default=str))
|
|
724
|
+
else:
|
|
725
|
+
self.say(f"{answer['question']}: asked. It's answered in a sealed enclave "
|
|
726
|
+
"or its owner's cloud, and logged for both sides when it is: "
|
|
727
|
+
f"arctiq ask again, or read it at {answer.get('url')}") # fmt: skip
|
|
728
|
+
return 0
|
|
729
|
+
answer = self._wait_for_answer(base, answer, as_json)
|
|
730
|
+
if as_json:
|
|
731
|
+
self.say(json.dumps(answer, indent=2, default=str))
|
|
732
|
+
return 0 if answer["answered"] else 1
|
|
733
|
+
noise = " · noise added" if answer["noise"] else ""
|
|
734
|
+
self.say(f"{answer['resource']} · {answer['partner']} · {answer['level']} "
|
|
735
|
+
f"{_LEVELS.get(answer['level'], '')}{noise}") # fmt: skip
|
|
736
|
+
self.say(f"{answer['question']}")
|
|
737
|
+
if not answer["answered"]:
|
|
738
|
+
clause = f", {answer['clause']}" if answer.get("clause") else ""
|
|
739
|
+
self.say(f"Refused: {answer['refused']} (rule {answer['rule']}{clause})")
|
|
740
|
+
return 1
|
|
741
|
+
self.say()
|
|
742
|
+
table = [answer["headings"], *answer["rows"]]
|
|
743
|
+
widths = [max(len(str(r[i])) for r in table) for i in range(len(answer["headings"]))]
|
|
744
|
+
for row in table:
|
|
745
|
+
self.say(" ".join(str(v).ljust(w) for v, w in zip(row, widths, strict=True)).rstrip())
|
|
746
|
+
notes = []
|
|
747
|
+
if answer["hidden"]:
|
|
748
|
+
h = answer["hidden"]
|
|
749
|
+
fewer = f"fewer than {answer['smallest_group']} rows" if answer.get("smallest_group") \
|
|
750
|
+
else "too few rows" # fmt: skip
|
|
751
|
+
notes.append(f"{h} group{'s' if h != 1 else ''} hidden ({fewer})")
|
|
752
|
+
if answer["more"]:
|
|
753
|
+
notes.append(
|
|
754
|
+
f"{answer['more']} more group{'s' if answer['more'] != 1 else ''} not shown"
|
|
755
|
+
)
|
|
756
|
+
if answer.get("budget_left") is not None:
|
|
757
|
+
notes.append(f"privacy budget {answer['budget_left']}% left")
|
|
758
|
+
notes.append("logged for both sides")
|
|
759
|
+
self.say()
|
|
760
|
+
self.say(" · ".join(notes))
|
|
761
|
+
return 0
|
|
762
|
+
|
|
763
|
+
def _wait_for_answer(self, base: str, answer: dict, quiet: bool) -> dict:
|
|
764
|
+
"""A question waiting to be answered elsewhere, asked again every few seconds until it
|
|
765
|
+
is (an hour at most: then it's given up, and its budget given back)."""
|
|
766
|
+
if not quiet:
|
|
767
|
+
self.say(f"{answer['question']}: waiting for an enclave to answer it (about 3 "
|
|
768
|
+
"minutes when none is running; Ctrl-C leaves it to come later)…") # fmt: skip
|
|
769
|
+
deadline = time.monotonic() + 65 * 60
|
|
770
|
+
while answer.get("waiting") and time.monotonic() < deadline:
|
|
771
|
+
self.sleep(3)
|
|
772
|
+
got = self.api().get(f"{base}/questions/{part(str(answer['question_id']))}")
|
|
773
|
+
assert isinstance(got, dict)
|
|
774
|
+
answer = got
|
|
775
|
+
if answer.get("waiting"):
|
|
776
|
+
raise Failed("No answer came within an hour. It's given up, and nothing was spent.")
|
|
777
|
+
return answer
|
|
778
|
+
|
|
779
|
+
# ------------------------------------------------------------------ pin
|
|
780
|
+
def pin(self, tag: str, artefact: str | None, repo: str | None = None) -> None:
|
|
781
|
+
linked = self.target(repo)
|
|
782
|
+
artefact_id = self.pick(linked, artefact)["id"]
|
|
783
|
+
made = self.api().post(
|
|
784
|
+
f"{self.base(linked)}/artefacts/{part(artefact_id)}/pins", {"tag": tag}
|
|
785
|
+
)
|
|
786
|
+
assert isinstance(made, dict)
|
|
787
|
+
size = made["size_bytes"] / (1024 * 1024)
|
|
788
|
+
self.say(
|
|
789
|
+
f"Pinned commit {made['commit'][:7]} (tag {made['tag']}) and a private copy, "
|
|
790
|
+
f"{size:.1f} MB, sha256 {made['sha256'][:8]}…{made['sha256'][-4:]}"
|
|
791
|
+
)
|
|
792
|
+
if made.get("timestamped_at"):
|
|
793
|
+
authority = re.sub(r"^https?://", "", str(made.get("timestamp_authority") or "")).split(
|
|
794
|
+
"/"
|
|
795
|
+
)[0]
|
|
796
|
+
self.say(
|
|
797
|
+
f"Timestamped by {authority} (RFC 3161) at {str(made['timestamped_at'])[:19]}Z · "
|
|
798
|
+
"added to the artefact's evidence"
|
|
799
|
+
)
|
|
800
|
+
else:
|
|
801
|
+
self.say(
|
|
802
|
+
f"Added to the artefact's evidence. Not timestamped: {made.get('timestamp_note')}."
|
|
803
|
+
)
|
|
804
|
+
|
|
805
|
+
|
|
806
|
+
_LEVELS = {2: "See its shape", 3: "Try it", 4: "Use it"}
|
|
807
|
+
|
|
808
|
+
|
|
809
|
+
def _level(r: dict) -> str:
|
|
810
|
+
return f"{r['level']} {_LEVELS.get(r['level'], '')}" if r.get("level") else "–"
|
|
811
|
+
|
|
812
|
+
|
|
813
|
+
def _slug(name: str) -> str:
|
|
814
|
+
return re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")
|
|
815
|
+
|
|
816
|
+
|
|
817
|
+
def _cut(text: str, width: int) -> str:
|
|
818
|
+
return text if len(text) <= width else text[: width - 1] + "…"
|
|
819
|
+
|
|
820
|
+
|
|
821
|
+
def _row(kind: str, name: str, where: str, level: str, last: str) -> str:
|
|
822
|
+
if not name: # a heading: its first word spans the kind and name columns
|
|
823
|
+
return f"{kind:<35}{where:<40}{level:<18}{last}"
|
|
824
|
+
return f"{kind:<10}{_cut(name, 24):<25}{_cut(where, 38):<40}{level:<18}{last}"
|
|
825
|
+
|
|
826
|
+
|
|
827
|
+
def _date(iso: str) -> str:
|
|
828
|
+
import datetime as dt
|
|
829
|
+
|
|
830
|
+
day = dt.date.fromisoformat(str(iso)[:10])
|
|
831
|
+
return f"{day.day} {day:%b %Y}"
|
|
832
|
+
|
|
833
|
+
|
|
834
|
+
def _title(artefact: dict) -> str:
|
|
835
|
+
words = " ".join(str((artefact.get("record") or {}).get("problem") or "Untitled draft").split())
|
|
836
|
+
return words if len(words) <= 60 else words[:59].rstrip() + "…"
|
|
837
|
+
|
|
838
|
+
|
|
839
|
+
_BARS = "▁▂▃▄▅▆▇█"
|
|
840
|
+
|
|
841
|
+
|
|
842
|
+
def _number(value: float) -> str:
|
|
843
|
+
return str(int(value)) if float(value).is_integer() else f"{value:g}"
|
|
844
|
+
|
|
845
|
+
|
|
846
|
+
def _quoted(name: str) -> str:
|
|
847
|
+
return f'"{name}"' if " " in name else name
|
|
848
|
+
|
|
849
|
+
|
|
850
|
+
def _size(n: int) -> str:
|
|
851
|
+
if n < 1024:
|
|
852
|
+
return f"{n} bytes"
|
|
853
|
+
size = float(n)
|
|
854
|
+
for unit in ("KB", "MB", "GB"):
|
|
855
|
+
size /= 1024
|
|
856
|
+
if size < 1024 or unit == "GB":
|
|
857
|
+
break
|
|
858
|
+
return f"{size:.1f} {unit}"
|
|
859
|
+
|
|
860
|
+
|
|
861
|
+
def _listing(artefacts: list[dict]) -> str:
|
|
862
|
+
lines = []
|
|
863
|
+
for a in artefacts[:50]:
|
|
864
|
+
state = STATE_WORDS.get(a["state"], a["state"])
|
|
865
|
+
files = len(a.get("files") or [])
|
|
866
|
+
lines.append(
|
|
867
|
+
f" {a['id'][:8]} {_title(a):<62}{state} · {files} file{'s' if files != 1 else ''}"
|
|
868
|
+
)
|
|
869
|
+
return "\n".join(lines)
|
|
870
|
+
|
|
871
|
+
|
|
872
|
+
def parser() -> argparse.ArgumentParser:
|
|
873
|
+
p = argparse.ArgumentParser(prog="arctiq", description="ARCTIQ from a terminal.")
|
|
874
|
+
p.add_argument("--version", action="version", version=f"arctiq {__version__}")
|
|
875
|
+
sub = p.add_subparsers(dest="command", required=True)
|
|
876
|
+
login = sub.add_parser("login", help="sign in from the terminal")
|
|
877
|
+
login.add_argument(
|
|
878
|
+
"--server",
|
|
879
|
+
help="your ARCTIQ address; asked for the first time if not given, then remembered",
|
|
880
|
+
)
|
|
881
|
+
login.add_argument("--name", help="the token's name, shown in Settings, Access tokens")
|
|
882
|
+
sub.add_parser("logout", help="revoke and forget the token")
|
|
883
|
+
sub.add_parser("link", help="tie this folder's GitHub repository to its ARCTIQ repository")
|
|
884
|
+
sub.add_parser(
|
|
885
|
+
"status", help="the repository, its artefacts, what waits for you, the last check"
|
|
886
|
+
)
|
|
887
|
+
where = argparse.ArgumentParser(add_help=False)
|
|
888
|
+
where.add_argument(
|
|
889
|
+
"--repo", help="organisation/repository; by default, this folder's .arctiq.yml"
|
|
890
|
+
)
|
|
891
|
+
which = argparse.ArgumentParser(add_help=False)
|
|
892
|
+
which.add_argument(
|
|
893
|
+
"--artefact",
|
|
894
|
+
help="its id (or the first 6+ characters), or the start of its title; "
|
|
895
|
+
"not needed when the repository has only one",
|
|
896
|
+
)
|
|
897
|
+
sub.add_parser("artefacts", parents=[where], help="the repository's artefacts")
|
|
898
|
+
new = sub.add_parser("new", parents=[where], help="start a draft artefact")
|
|
899
|
+
new.add_argument("--problem", required=True, help="the problem it solves (also its title)")
|
|
900
|
+
new.add_argument("--domain", required=True, help="the field, like Quantum error correction")
|
|
901
|
+
new.add_argument("--approach", required=True, help="the kind of approach")
|
|
902
|
+
new.add_argument("--mechanism", help="how it works (optional, private by default)")
|
|
903
|
+
new.add_argument("--implementation", help="how it is built (optional, private by default)")
|
|
904
|
+
upload = sub.add_parser(
|
|
905
|
+
"upload", parents=[where, which], help="add files to an artefact; each is scanned"
|
|
906
|
+
)
|
|
907
|
+
upload.add_argument("paths", nargs="+", metavar="FILE")
|
|
908
|
+
sub.add_parser("files", parents=[where, which], help="an artefact's files")
|
|
909
|
+
download = sub.add_parser("download", parents=[where, which], help="save one of its files")
|
|
910
|
+
download.add_argument("name", help="the file's name")
|
|
911
|
+
download.add_argument("--to", help="the folder to save into (default: here)")
|
|
912
|
+
download.add_argument("--force", action="store_true", help="replace a file already there")
|
|
913
|
+
remove = sub.add_parser("remove", parents=[where, which], help="remove a file from a draft")
|
|
914
|
+
remove.add_argument("name", help="the file's name")
|
|
915
|
+
sub.add_parser("submit", parents=[where, which], help="submit an artefact for review")
|
|
916
|
+
sub.add_parser(
|
|
917
|
+
"open", parents=[where, which], help="open the repository (or an artefact) in ARCTIQ"
|
|
918
|
+
)
|
|
919
|
+
pin = sub.add_parser(
|
|
920
|
+
"pin", parents=[where, which], help="pin a tagged release as evidence for an artefact"
|
|
921
|
+
)
|
|
922
|
+
pin.add_argument("tag", help="the release's tag on GitHub, like v1.3.0")
|
|
923
|
+
# On `resources show` and `resources add`, given after the action; given before it, kept.
|
|
924
|
+
where_after = argparse.ArgumentParser(add_help=False)
|
|
925
|
+
where_after.add_argument("--repo", default=argparse.SUPPRESS,
|
|
926
|
+
help="organisation/repository; by default, this folder's .arctiq.yml") # fmt: skip
|
|
927
|
+
res = sub.add_parser("resources", parents=[where],
|
|
928
|
+
help="the repository's code, data and documents, and partners'") # fmt: skip
|
|
929
|
+
res.add_argument("--json", action="store_true", help="for scripts")
|
|
930
|
+
res_sub = res.add_subparsers(dest="action")
|
|
931
|
+
show = res_sub.add_parser("show", parents=[where_after], help="one resource, with its columns")
|
|
932
|
+
show.add_argument("name", help="its name (or the start of it), or its id")
|
|
933
|
+
show.add_argument("--json", action="store_true", default=argparse.SUPPRESS, help="for scripts")
|
|
934
|
+
sample = res_sub.add_parser("sample", parents=[where_after],
|
|
935
|
+
help="a partner's synthetic sample: made-up rows, none real") # fmt: skip
|
|
936
|
+
sample.add_argument("name", help="the dataset's name (or the start of it), or its id")
|
|
937
|
+
sample.add_argument("--seed", type=int, help="the same rows as an earlier sample")
|
|
938
|
+
sample.add_argument("--csv", metavar="FILE", help="save the rows as CSV")
|
|
939
|
+
sample.add_argument(
|
|
940
|
+
"--json", action="store_true", default=argparse.SUPPRESS, help="for scripts"
|
|
941
|
+
)
|
|
942
|
+
add = res_sub.add_parser("add", parents=[where_after],
|
|
943
|
+
help="add a dataset or document; files go to ARCTIQ storage") # fmt: skip
|
|
944
|
+
add.add_argument("paths", nargs="*", metavar="FILE", help="none: a resource described only")
|
|
945
|
+
add.add_argument("--name", help="default: the first file's name")
|
|
946
|
+
add.add_argument("--kind", choices=("dataset", "document"), default="dataset")
|
|
947
|
+
add.add_argument("--description")
|
|
948
|
+
add.add_argument("--level", type=int, choices=(2, 3, 4),
|
|
949
|
+
help="the highest level to offer: 2 See its shape, 3 Try it, 4 Use it") # fmt: skip
|
|
950
|
+
add.add_argument("--personal-data", action="store_true",
|
|
951
|
+
help="it holds personal data (then at most 3 Try it)") # fmt: skip
|
|
952
|
+
add.add_argument("--source-url", help="for a resource described only: where it lives")
|
|
953
|
+
version = res_sub.add_parser("add-version", parents=[where_after],
|
|
954
|
+
help="files as the next version of your dataset; sealed here "
|
|
955
|
+
'for a dataset sealed for enclaves (needs "arctiq-cli[seal]")') # fmt: skip
|
|
956
|
+
version.add_argument("name", help="the dataset's name (or the start of it), or its id")
|
|
957
|
+
version.add_argument("paths", nargs="+", metavar="FILE")
|
|
958
|
+
version.add_argument("--local-stand-in", action="store_true",
|
|
959
|
+
help="seal to a local enclave stand-in, which protects nothing from "
|
|
960
|
+
"ARCTIQ (for trying it out)") # fmt: skip
|
|
961
|
+
ask = sub.add_parser("ask", parents=[where],
|
|
962
|
+
help="Try it: a question on a dataset a partner shares, under its rules") # fmt: skip
|
|
963
|
+
ask.add_argument("name", help="the dataset's name (or the start of it), or its id")
|
|
964
|
+
measure = ask.add_mutually_exclusive_group()
|
|
965
|
+
measure.add_argument("--count", action="store_true", help="count rows (the default)")
|
|
966
|
+
for word in ("mean", "sum", "min", "max", "median"):
|
|
967
|
+
measure.add_argument(f"--{word}", metavar="COLUMN", help=f"the {word} of a number column")
|
|
968
|
+
ask.add_argument("--by", action="append", default=[], metavar="COLUMN",
|
|
969
|
+
help="group by a column (twice for two)") # fmt: skip
|
|
970
|
+
ask.add_argument("--where", action="append", default=[], metavar="COLUMN=VALUE", dest="filters",
|
|
971
|
+
help="keep rows where COLUMN=VALUE (also !=, <, <=, >, >=)") # fmt: skip
|
|
972
|
+
ask.add_argument("--json", action="store_true", help="for scripts")
|
|
973
|
+
ask.add_argument("--no-wait", action="store_true",
|
|
974
|
+
help="don't wait for an answer made in a sealed enclave or the owner's "
|
|
975
|
+
"cloud: it comes later, logged for both sides") # fmt: skip
|
|
976
|
+
tui = sub.add_parser("tui", help='the terminal app (needs "arctiq-cli[tui]")')
|
|
977
|
+
tui.add_argument(
|
|
978
|
+
"--org", help="the organisation's slug (default: this folder's, or your only one)"
|
|
979
|
+
)
|
|
980
|
+
return p
|
|
981
|
+
|
|
982
|
+
|
|
983
|
+
_OPS = {"!=": "ne", "<=": "le", ">=": "ge", "<": "lt", ">": "gt", "=": "eq"}
|
|
984
|
+
_FILTER = re.compile(r"^\s*([^=!<>]+?)\s*(!=|<=|>=|<|>|=)\s*(.*?)\s*$")
|
|
985
|
+
|
|
986
|
+
|
|
987
|
+
def _question(args: argparse.Namespace) -> dict:
|
|
988
|
+
measure, column = "count", None
|
|
989
|
+
for word in ("mean", "sum", "min", "max", "median"):
|
|
990
|
+
if getattr(args, word):
|
|
991
|
+
measure, column = word, getattr(args, word)
|
|
992
|
+
if len(args.by) > 2:
|
|
993
|
+
raise Failed("Group by at most two columns.")
|
|
994
|
+
filters = []
|
|
995
|
+
for raw in args.filters:
|
|
996
|
+
found = _FILTER.match(raw)
|
|
997
|
+
if found is None:
|
|
998
|
+
raise Failed(f'Give --where as COLUMN=VALUE (or !=, <, <=, >, >=), not "{raw}".')
|
|
999
|
+
filters.append({"column": found[1], "op": _OPS[found[2]], "value": found[3]})
|
|
1000
|
+
return {"measure": measure, "column": column, "group_by": args.by, "filters": filters}
|
|
1001
|
+
|
|
1002
|
+
|
|
1003
|
+
def main(argv: list[str] | None = None, cli: Cli | None = None) -> int:
|
|
1004
|
+
args = parser().parse_args(argv)
|
|
1005
|
+
cli = cli or Cli()
|
|
1006
|
+
try:
|
|
1007
|
+
if args.command == "login":
|
|
1008
|
+
cli.login(args.server, args.name)
|
|
1009
|
+
elif args.command == "logout":
|
|
1010
|
+
cli.logout()
|
|
1011
|
+
elif args.command == "link":
|
|
1012
|
+
cli.link()
|
|
1013
|
+
elif args.command == "status":
|
|
1014
|
+
cli.status()
|
|
1015
|
+
elif args.command == "artefacts":
|
|
1016
|
+
cli.artefacts(args.repo)
|
|
1017
|
+
elif args.command == "new":
|
|
1018
|
+
cli.new(args.repo, {"problem": args.problem, "domain": args.domain,
|
|
1019
|
+
"approach_class": args.approach, "mechanism": args.mechanism,
|
|
1020
|
+
"implementation": args.implementation}) # fmt: skip
|
|
1021
|
+
elif args.command == "upload":
|
|
1022
|
+
if not cli.upload(args.repo, args.artefact, args.paths):
|
|
1023
|
+
return 1
|
|
1024
|
+
elif args.command == "files":
|
|
1025
|
+
cli.files(args.repo, args.artefact)
|
|
1026
|
+
elif args.command == "download":
|
|
1027
|
+
cli.download(args.repo, args.artefact, args.name, args.to, args.force)
|
|
1028
|
+
elif args.command == "remove":
|
|
1029
|
+
cli.remove(args.repo, args.artefact, args.name)
|
|
1030
|
+
elif args.command == "submit":
|
|
1031
|
+
cli.submit(args.repo, args.artefact)
|
|
1032
|
+
elif args.command == "open":
|
|
1033
|
+
cli.open(args.repo, args.artefact)
|
|
1034
|
+
elif args.command == "pin":
|
|
1035
|
+
cli.pin(args.tag, args.artefact, args.repo)
|
|
1036
|
+
elif args.command == "resources":
|
|
1037
|
+
if args.action == "show":
|
|
1038
|
+
cli.show_resource(args.repo, args.name, args.json)
|
|
1039
|
+
elif args.action == "sample":
|
|
1040
|
+
cli.sample(args.repo, args.name, args.seed, args.csv, args.json)
|
|
1041
|
+
elif args.action == "add-version":
|
|
1042
|
+
cli.add_version(args.repo, args.name, args.paths,
|
|
1043
|
+
local_stand_in=args.local_stand_in) # fmt: skip
|
|
1044
|
+
elif args.action == "add":
|
|
1045
|
+
cli.add_resource(args.repo, args.paths, {
|
|
1046
|
+
"name": args.name, "kind": args.kind, "description": args.description,
|
|
1047
|
+
"level": args.level, "personal_data": args.personal_data or None,
|
|
1048
|
+
"source_url": args.source_url,
|
|
1049
|
+
}) # fmt: skip
|
|
1050
|
+
else:
|
|
1051
|
+
cli.resources(args.repo, args.json)
|
|
1052
|
+
elif args.command == "ask":
|
|
1053
|
+
return cli.ask(args.repo, args.name, _question(args), args.json,
|
|
1054
|
+
wait=not args.no_wait) # fmt: skip
|
|
1055
|
+
elif args.command == "tui":
|
|
1056
|
+
cli.tui(args.org)
|
|
1057
|
+
except Failed as exc:
|
|
1058
|
+
sys.stderr.write(f"{exc}\n")
|
|
1059
|
+
return 1
|
|
1060
|
+
except ApiError as exc:
|
|
1061
|
+
if exc.status == 401:
|
|
1062
|
+
sys.stderr.write("Your sign-in has ended or was revoked. Run: arctiq login\n")
|
|
1063
|
+
else:
|
|
1064
|
+
sys.stderr.write(f"{exc.detail}\n")
|
|
1065
|
+
return 1
|
|
1066
|
+
except KeyboardInterrupt:
|
|
1067
|
+
return 130
|
|
1068
|
+
return 0
|