abysshub 1.0.1.dev9__tar.gz → 1.0.1.dev11__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev11}/PKG-INFO +1 -1
  2. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev11}/pyproject.toml +1 -1
  3. abysshub-1.0.1.dev11/src/abysshub/_command.py +496 -0
  4. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev11}/tests/test_command.py +19 -0
  5. abysshub-1.0.1.dev9/src/abysshub/_command.py +0 -293
  6. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev11}/.gitignore +0 -0
  7. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev11}/LICENSE +0 -0
  8. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev11}/README.md +0 -0
  9. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev11}/src/abysshub/__init__.py +0 -0
  10. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev11}/src/abysshub/__main__.py +0 -0
  11. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev11}/src/abysshub/_async_client.py +0 -0
  12. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev11}/src/abysshub/_client.py +0 -0
  13. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev11}/src/abysshub/_error.py +0 -0
  14. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev11}/src/abysshub/_files.py +0 -0
  15. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev11}/src/abysshub/_http.py +0 -0
  16. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev11}/src/abysshub/_run.py +0 -0
  17. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev11}/src/abysshub/_types.py +0 -0
  18. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev11}/src/abysshub/py.typed +0 -0
  19. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev11}/tests/caller.py +0 -0
  20. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev11}/tests/conftest.py +0 -0
  21. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev11}/tests/fake_server.py +0 -0
  22. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev11}/tests/test_client.py +0 -0
  23. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev11}/tests/test_files.py +0 -0
  24. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev11}/tests/test_http.py +0 -0
  25. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev11}/tests/test_package.py +0 -0
  26. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev11}/tests/test_replay.py +0 -0
  27. {abysshub-1.0.1.dev9 → abysshub-1.0.1.dev11}/tests/test_timeout.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: abysshub
3
- Version: 1.0.1.dev9
3
+ Version: 1.0.1.dev11
4
4
  Summary: Run a hosted tool, an Abyss Widget, from your own Python code and get its result and files. The official library for the Abyss API.
5
5
  Project-URL: Homepage, https://abysshub.com/docs#api
6
6
  Project-URL: Documentation, https://abysshub.com/docs
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "abysshub"
7
- version = "1.0.1.dev9"
7
+ version = "1.0.1.dev11"
8
8
  description = "Run a hosted tool, an Abyss Widget, from your own Python code and get its result and files. The official library for the Abyss API."
9
9
  keywords = [
10
10
  "abyss",
@@ -0,0 +1,496 @@
1
+ """The ``abysshub`` command. ``abysshub publish <folder>`` does what a person does on the
2
+ website's Publish page, through `/v1`'s routes that change a Widget. It asks nothing at a
3
+ prompt: it stops or it goes, and every stop exits non-zero with its ``code``."""
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import hashlib
8
+ import json
9
+ import os
10
+ import sys
11
+ from dataclasses import dataclass
12
+ from fnmatch import fnmatchcase
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ from ._client import Abyss, _expect, _has_ended, _is_key, _is_upload, _is_widget
17
+ from ._error import AbyssError
18
+ from ._files import file
19
+ from ._types import parse_upload
20
+
21
+ PUBLISH_FILE = "abyss.json"
22
+ TEST_INPUTS = "test_inputs.json"
23
+ INTERFACE = "interface.json"
24
+ ROOT_ENV = (".env", ".env.*")
25
+ """A root ``.env`` and its variants: never content, whatever the Junk list says."""
26
+ LISTING_FIELDS = ("title", "description", "tags", "visibility", "price", "free_runs")
27
+ """The Listing Fields the Publish File holds, beside its thumbnail."""
28
+ IMAGES = (".png", ".jpg", ".jpeg", ".webp", ".gif")
29
+ """The extensions a thumbnail may have: an image's."""
30
+ JSON = {"Content-Type": "application/json"}
31
+
32
+
33
+ def main(argv: list[str] | None = None) -> int:
34
+ """Runs the command and answers its exit code."""
35
+ parser = argparse.ArgumentParser(prog="abysshub", description="Publish a Widget folder to Abyss.")
36
+ verbs = parser.add_subparsers(dest="verb", metavar="<verb>")
37
+ verbs.required = True
38
+ publish_verb = verbs.add_parser(
39
+ "publish",
40
+ help="publish a Widget folder and print its link",
41
+ description=f"Publish a Widget folder, with its {PUBLISH_FILE} and {TEST_INPUTS}, and print its link.",
42
+ )
43
+ publish_verb.add_argument("folder", type=Path)
44
+ publish_verb.add_argument(
45
+ "--force", action="store_true", help="publish over a Widget that moved on Abyss: the folder wins"
46
+ )
47
+ args = parser.parse_args(argv)
48
+ widget_folder, faults = _read_folder(args.folder)
49
+ try:
50
+ abyss = Abyss()
51
+ except AbyssError as error:
52
+ return _stop([*faults, (error.code, error.message)])
53
+ with abyss:
54
+ faults.extend(_key_faults(abyss))
55
+ if faults:
56
+ return _stop(faults)
57
+ try:
58
+ print(publish(abyss, args.folder, widget_folder, args.force))
59
+ except AbyssError as error:
60
+ print(f"abysshub: stopped: {error.code}: {error.message}", file=sys.stderr)
61
+ if error.request_id:
62
+ print(f"request_id: {error.request_id}", file=sys.stderr)
63
+ return 1
64
+ except OSError as error:
65
+ # A file the folder names changed or became unreadable after the check.
66
+ print(f"abysshub: stopped: file_unreadable: {error}", file=sys.stderr)
67
+ return 1
68
+ return 0
69
+
70
+
71
+ @dataclass
72
+ class _Folder:
73
+ """A Widget folder as the command read it, before it sent anything."""
74
+
75
+ publish_file: dict[str, Any]
76
+ interface: list[Any] | None
77
+ test_input: dict[str, Any]
78
+ """The Test Run's input: the Test Inputs, and the default of each Field they leave out."""
79
+
80
+
81
+ def _stop(faults: list[tuple[str, str]]) -> int:
82
+ """Prints every fault, one line each with its code, and answers the exit code."""
83
+ for code, message in faults:
84
+ print(f"abysshub: stopped: {code}: {message}", file=sys.stderr)
85
+ return 1
86
+
87
+
88
+ def _read_folder(folder: Path) -> tuple[_Folder, list[tuple[str, str]]]:
89
+ """Reads the folder and finds every fault it shows on its own, all of them and not
90
+ only the first, without a request: a publish takes minutes, a fault stops it now."""
91
+ faults: list[tuple[str, str]] = []
92
+ for name, code in (("run.py", "run_py_missing"), ("requirements.txt", "requirements_missing")):
93
+ if not (folder / name).is_file():
94
+ faults.append((code, f"The folder has no {name}."))
95
+ publish_file = _read_json(folder / PUBLISH_FILE, "publish_file", dict, faults)
96
+ if publish_file is not None:
97
+ _check_listing(folder, publish_file, faults)
98
+ has_interface = (folder / INTERFACE).is_file()
99
+ interface = _read_json(folder / INTERFACE, "interface", list, faults) if has_interface else None
100
+ test_inputs = _read_json(folder / TEST_INPUTS, "test_inputs", dict, faults) if (folder / TEST_INPUTS).is_file() else {}
101
+ test_input: dict[str, Any] = {}
102
+ # An invalid interface.json skips the Field checks rather than calling every Test Input unknown.
103
+ if test_inputs is not None and (interface is not None or not has_interface):
104
+ test_input = _check_test_inputs(folder, interface or [], test_inputs, faults)
105
+ return _Folder(publish_file or {}, interface, test_input), faults
106
+
107
+
108
+ def _check_listing(folder: Path, publish_file: dict[str, Any], faults: list[tuple[str, str]]) -> None:
109
+ """The Publish File's faults: no title, no tag, and a thumbnail that is missing on a
110
+ first publish or names no image file in the folder."""
111
+ block = publish_file.get("widget") or {}
112
+ if not isinstance(block, dict):
113
+ faults.append(("publish_file_invalid", f"The widget block of {PUBLISH_FILE} is not a JSON object."))
114
+ title = publish_file.get("title")
115
+ if not isinstance(title, str) or not title.strip():
116
+ faults.append(("title_missing", f"{PUBLISH_FILE} has no title."))
117
+ tags = publish_file.get("tags")
118
+ if not isinstance(tags, list) or not any(isinstance(tag, str) and tag.strip() for tag in tags):
119
+ faults.append(("tag_missing", f"{PUBLISH_FILE} has no tag in tags."))
120
+ thumbnail = publish_file.get("thumbnail")
121
+ if not thumbnail:
122
+ if not (isinstance(block, dict) and "version" in block):
123
+ faults.append(("thumbnail_missing", f"A first publish needs a thumbnail, and {PUBLISH_FILE} names none."))
124
+ elif not (isinstance(thumbnail, str) and Path(thumbnail).suffix.lower() in IMAGES and _names_file(folder, thumbnail)):
125
+ faults.append(
126
+ ("thumbnail_not_image", f"The thumbnail {thumbnail!r} names no image file ({', '.join(IMAGES)}) in the folder.")
127
+ )
128
+
129
+
130
+ def _check_test_inputs(
131
+ folder: Path, interface: list[Any], test_inputs: dict[str, Any], faults: list[tuple[str, str]]
132
+ ) -> dict[str, Any]:
133
+ """The Test Inputs' faults against ``interface.json``: a name that is no Field, a
134
+ required Field with no value and no default, and a file Field's value that names no
135
+ file in the folder. Answers the Test Run's input, with the defaults filled in."""
136
+ fields = {
137
+ field["name"]: field for field in interface if isinstance(field, dict) and isinstance(field.get("name"), str)
138
+ }
139
+ for name in test_inputs:
140
+ if name not in fields:
141
+ faults.append(("test_input_unknown", f"{TEST_INPUTS} names {name!r}, which {INTERFACE} has no Field for."))
142
+ defaults = {name: field["default"] for name, field in fields.items() if "default" in field}
143
+ test_input = {**defaults, **test_inputs}
144
+ for name, field in fields.items():
145
+ value = test_input.get(name)
146
+ if value is None:
147
+ # A Field without isRequired counts as required.
148
+ if field.get("isRequired", True) is not False:
149
+ faults.append(("test_input_missing", f"The required Field {name!r} has no value in {TEST_INPUTS} and no default."))
150
+ elif field.get("type") == "file":
151
+ for path in value if isinstance(value, list) else [value]:
152
+ if not _names_file(folder, path):
153
+ faults.append(("test_input_file_missing", f"The file Field {name!r} names {path!r}, no file inside the folder."))
154
+ return test_input
155
+
156
+
157
+ def _key_faults(abyss: Abyss) -> list[tuple[str, str]]:
158
+ """The key's fault, read with ``GET /v1/key``: it is refused, or it does not manage Widgets."""
159
+ try:
160
+ key = abyss._get(abyss._start(None), f"{abyss.base_url}/v1/key", _is_key, "The key answered without a key.")
161
+ except AbyssError as error:
162
+ return [(error.code, error.message)]
163
+ if key.get("manage_widgets") is not True:
164
+ return [
165
+ (
166
+ "manage_widgets_required",
167
+ f"The key {key.get('key')} does not manage Widgets. Make a new key in your Cave, under Your API keys, "
168
+ "with Create a key and Manage Widgets switched on: a key is never given it after it is made.",
169
+ )
170
+ ]
171
+ return []
172
+
173
+
174
+ def _names_file(folder: Path, path: Any) -> bool:
175
+ """Whether ``path`` names a file inside the folder."""
176
+ if not isinstance(path, str) or not path:
177
+ return False
178
+ target = (folder / path).resolve()
179
+ return target.is_file() and folder.resolve() in target.parents
180
+
181
+
182
+ def publish(abyss: Abyss, folder: Path, widget_folder: _Folder, force: bool = False) -> str:
183
+ """Publishes a folder, and answers the Widget's link: a new Widget for a folder that was
184
+ never published, a new version of the same Widget for one that was.
185
+
186
+ A Draft's id goes into the Publish File as soon as it is made, and its Candidate's
187
+ number once committed, so a publish that stops is taken up again on the same Draft.
188
+ A published Widget is first compared with the folder, and a Widget that moved on
189
+ Abyss stops the publish before any upload, unless ``force``.
190
+ """
191
+ publish_file = widget_folder.publish_file
192
+ interface = widget_folder.interface
193
+ block = dict(publish_file.get("widget") or {})
194
+ widget = block.get("id")
195
+ # A Widget published already saves only what differs; a new one saves every Listing Field.
196
+ listing: dict[str, Any] | None = None
197
+ changes = _listing_fields(publish_file)
198
+ send_thumbnail = bool(publish_file.get("thumbnail"))
199
+ if "version" in block:
200
+ listing, changes, send_thumbnail = _compare(abyss, folder, block, publish_file, force)
201
+ base_version = listing["live_version"]
202
+ elif widget is None:
203
+ draft = _expect(
204
+ abyss._send(abyss._start(None), "POST", f"{abyss.base_url}/v1/widgets", retries=0),
205
+ _is_widget,
206
+ "The Draft answered without an id.",
207
+ )
208
+ widget = draft["id"]
209
+ block["id"] = widget
210
+ _write_block(folder, publish_file, block)
211
+ print(f"Made the Draft {widget}.")
212
+ base_version = None
213
+ else:
214
+ print(f"Publishing the Draft {widget}.")
215
+ base_version = block.get("candidate")
216
+ widget_url = abyss._widget_url(widget)
217
+
218
+ base = json.dumps({"base_version": base_version}).encode()
219
+ opened = _expect(
220
+ abyss._send(abyss._start(None), "POST", f"{widget_url}/versions", JSON, base),
221
+ _is_project_version,
222
+ "The version answered without its number, form and Junk list.",
223
+ )
224
+ sent, left_out = _folder_files(folder, opened["junk"], publish_file.get("thumbnail"))
225
+ for path in left_out:
226
+ print(f"Left out {path}")
227
+ upload = opened["upload"]
228
+ for path in sent:
229
+ fields = {**upload["fields"], "key": f"{upload['prefix']}/{path}"}
230
+ data = (folder / path).read_bytes()
231
+ abyss._store(abyss._start(None), upload["url"], fields, path, Path(path).name, data)
232
+ print(f"Sent {len(sent)} files.")
233
+
234
+ version = opened["version"]
235
+ commit = json.dumps({} if interface is None else {"interface": interface}).encode()
236
+ candidate = _expect(
237
+ abyss._send(abyss._start(None), "POST", f"{widget_url}/versions/{version}/commit", JSON, commit),
238
+ _is_candidate,
239
+ "The commit answered without a Candidate.",
240
+ )
241
+ block["candidate"] = candidate["version"]
242
+ _write_block(folder, publish_file, block)
243
+
244
+ print(f"Test Run of version {candidate['version']}...")
245
+ run = _test_run(abyss, folder, widget, candidate["version"], widget_folder.test_input, interface)
246
+ if run["status"] == "failed":
247
+ _print_logs(run.get("logs"))
248
+ error = run.get("error") or {}
249
+ raise AbyssError(
250
+ error.get("code", "platform_fault"),
251
+ f"The Test Run {run['id']} failed, so nothing was published. {error.get('message', '')}".rstrip(),
252
+ run_id=run["id"],
253
+ )
254
+
255
+ thumbnail = publish_file.get("thumbnail") if send_thumbnail else None
256
+ if listing is None or changes or thumbnail:
257
+ listing = _save_listing(abyss, folder, widget, changes, thumbnail)
258
+ if thumbnail:
259
+ block["thumbnail_sha256"] = _sha256(folder / thumbnail)
260
+ block["listing_revision"] = listing["listing_revision"]
261
+ _write_block(folder, publish_file, block)
262
+ published = _expect(
263
+ abyss._send(abyss._start(None), "POST", f"{widget_url}/publish"),
264
+ _is_widget,
265
+ "The publish answered without the Widget.",
266
+ )
267
+ block.pop("candidate")
268
+ block["version"] = candidate["version"]
269
+ _write_block(folder, publish_file, block)
270
+ return str(published["url"])
271
+
272
+
273
+ def _compare(
274
+ abyss: Abyss, folder: Path, block: dict[str, Any], publish_file: dict[str, Any], force: bool
275
+ ) -> tuple[dict[str, Any], dict[str, Any], bool]:
276
+ """Reads the Widget's listing and prints it beside the folder, before any upload. The
277
+ Widget moved when its listing revision or its live version is not the block's: then
278
+ the publish stops, unless ``force`` makes the folder win. Answers the listing, the
279
+ Listing Fields to save, and whether to send the thumbnail."""
280
+ widget = block["id"]
281
+ listing = abyss._get(
282
+ abyss._start(None),
283
+ f"{abyss._widget_url(widget)}/listing",
284
+ lambda value: _is_listing(value) and "live_version" in value,
285
+ "The listing answered without its revision and its live version.",
286
+ )
287
+ changes = {name: value for name, value in _listing_fields(publish_file).items() if listing.get(name) != value}
288
+ listing_moved = listing["listing_revision"] != block.get("listing_revision")
289
+ code_moved = listing["live_version"] != block.get("version")
290
+ thumbnail = publish_file.get("thumbnail")
291
+ send_thumbnail = bool(thumbnail) and (
292
+ (listing_moved and force) or _sha256(folder / thumbnail) != block.get("thumbnail_sha256")
293
+ )
294
+
295
+ print(f"{widget} on Abyss beside the folder:")
296
+ for name, value in changes.items():
297
+ print(f" {name}: {_shown(listing.get(name))} on Abyss, {_shown(value)} in the folder")
298
+ if send_thumbnail:
299
+ print(f" thumbnail: {thumbnail} in the folder")
300
+ if listing_moved:
301
+ print(" listing: changed on Abyss since the folder's last publish or pull")
302
+ if code_moved:
303
+ print(f" code: version {listing['live_version']} is live on Abyss, the folder's is version {block.get('version')}")
304
+ if not (changes or send_thumbnail or listing_moved or code_moved):
305
+ print(" nothing differs")
306
+
307
+ if (listing_moved or code_moved) and not force:
308
+ moved = " and ".join(what for what, did in (("its listing", listing_moved), ("its code", code_moved)) if did)
309
+ pull = "take the website's listing with `abysshub pull`, or " if listing_moved else ""
310
+ raise AbyssError(
311
+ "widget_moved",
312
+ f"{widget} moved on Abyss since this folder's last publish or pull: {moved} changed there. "
313
+ f"Nothing was sent. To go on, {pull}publish with --force to make the folder win.",
314
+ )
315
+ if listing_moved or code_moved:
316
+ print("--force: the folder wins over what moved on Abyss.")
317
+ return listing, changes, send_thumbnail
318
+
319
+
320
+ def _folder_files(folder: Path, junk: dict[str, Any], thumbnail: str | None) -> tuple[list[str], list[str]]:
321
+ """The folder's files to send, and what it leaves out, by their paths in the folder:
322
+ what the Junk list names, the Publish File, its thumbnail, and a root ``.env`` with its
323
+ variants. A folder that is left out is named once, with a ``/``."""
324
+ names = junk.get("names") or []
325
+ markers = junk.get("markers") or []
326
+ root_names = [*(junk.get("root") or []), *ROOT_ENV]
327
+ skipped = {PUBLISH_FILE}
328
+ if thumbnail:
329
+ skipped.add(Path(thumbnail).as_posix())
330
+ sent: list[str] = []
331
+ left_out: list[str] = []
332
+ for top, dirs, files in os.walk(folder):
333
+ here = Path(top)
334
+ at_root = here == folder
335
+ kept_dirs = []
336
+ for name in sorted(dirs):
337
+ path = here / name
338
+ if any(fnmatchcase(name, pattern) for pattern in names) or _holds_marker(path, markers):
339
+ left_out.append(f"{path.relative_to(folder).as_posix()}/")
340
+ else:
341
+ kept_dirs.append(name)
342
+ dirs[:] = kept_dirs
343
+ for name in sorted(files):
344
+ relative = (here / name).relative_to(folder).as_posix()
345
+ if (
346
+ any(fnmatchcase(name, pattern) for pattern in names)
347
+ or (at_root and any(fnmatchcase(name, pattern) for pattern in root_names))
348
+ or relative in skipped
349
+ ):
350
+ left_out.append(relative)
351
+ else:
352
+ sent.append(relative)
353
+ return sent, left_out
354
+
355
+
356
+ def _test_run(
357
+ abyss: Abyss,
358
+ folder: Path,
359
+ widget: str,
360
+ version: int,
361
+ test_input: dict[str, Any],
362
+ interface: list[Any] | None,
363
+ ) -> dict[str, Any]:
364
+ """Makes the Test Run of the Candidate from its input and waits for its ending,
365
+ as ``run()`` waits. A file Field's value is a path in the folder, uploaded for that
366
+ Candidate. Answers the run, failed or not."""
367
+ file_fields = {
368
+ field.get("name") for field in interface or [] if isinstance(field, dict) and field.get("type") == "file"
369
+ }
370
+
371
+ def value(name: str, item: Any) -> Any:
372
+ if name not in file_fields:
373
+ return item
374
+ if isinstance(item, list):
375
+ return [file(str(folder / path)) if isinstance(path, str) else path for path in item]
376
+ return file(str(folder / item)) if isinstance(item, str) else item
377
+
378
+ input = {name: value(name, item) for name, item in test_input.items()}
379
+ call = abyss._start(None)
380
+ press = abyss._press(call, widget, input, None, None, hold=True, version=version)
381
+ reply = press if _has_ended(press) else abyss._hold(call, abyss._wait_url(press), _has_ended)
382
+ assert reply.run is not None
383
+ return reply.run
384
+
385
+
386
+ def _save_listing(
387
+ abyss: Abyss, folder: Path, widget: str, save: dict[str, Any], thumbnail: str | None
388
+ ) -> dict[str, Any]:
389
+ """Saves these Listing Fields, and sends the thumbnail at that path in the folder
390
+ first, if any. Answers the listing as saved."""
391
+ widget_url = abyss._widget_url(widget)
392
+ save = dict(save)
393
+ if thumbnail:
394
+ path = folder / thumbnail
395
+ data = path.read_bytes()
396
+ call = abyss._start(None)
397
+ body = json.dumps({"filename": path.name, "size": len(data)}).encode()
398
+ grant = parse_upload(
399
+ _expect(
400
+ abyss._send(call, "POST", f"{widget_url}/listing/thumbnail", JSON, body),
401
+ _is_upload,
402
+ "The thumbnail answered without an id and a form.",
403
+ )
404
+ )
405
+ abyss._store(call, grant.upload.url, grant.upload.fields, "thumbnail", path.name, data)
406
+ save["thumbnail"] = grant.id
407
+ return _expect(
408
+ abyss._send(abyss._start(None), "PATCH", f"{widget_url}/listing", JSON, json.dumps(save).encode()),
409
+ _is_listing,
410
+ "The listing answered without its revision.",
411
+ )
412
+
413
+
414
+ def _listing_fields(publish_file: dict[str, Any]) -> dict[str, Any]:
415
+ """The Listing Fields the Publish File holds, ``private`` unless it says."""
416
+ fields = {name: publish_file[name] for name in LISTING_FIELDS if name in publish_file}
417
+ fields.setdefault("visibility", "private")
418
+ return fields
419
+
420
+
421
+ def _sha256(path: Path) -> str:
422
+ """The SHA-256 of a file, which tells whether the thumbnail changed since it was sent."""
423
+ return hashlib.sha256(path.read_bytes()).hexdigest()
424
+
425
+
426
+ def _shown(value: Any) -> str:
427
+ """A Listing Field's value as JSON, as the Publish File writes it."""
428
+ return json.dumps(value, ensure_ascii=False)
429
+
430
+
431
+ def _read_json(path: Path, kind: str, shape: type, faults: list[tuple[str, str]]) -> Any:
432
+ """Reads a JSON file of the folder, or adds its fault and answers None: ``<kind>_missing``
433
+ when it is absent, ``<kind>_invalid`` when it is not JSON of that shape."""
434
+ try:
435
+ value = json.loads(path.read_text("utf-8"))
436
+ except FileNotFoundError:
437
+ faults.append((f"{kind}_missing", f"The folder has no {path.name}."))
438
+ return None
439
+ except (OSError, ValueError) as error:
440
+ faults.append((f"{kind}_invalid", f"{path.name} is not valid JSON: {error}"))
441
+ return None
442
+ if not isinstance(value, shape):
443
+ faults.append((f"{kind}_invalid", f"{path.name} is not a JSON {'object' if shape is dict else 'array'}."))
444
+ return None
445
+ return value
446
+
447
+
448
+ def _write_block(folder: Path, publish_file: dict[str, Any], block: dict[str, Any]) -> None:
449
+ """Writes the ``widget`` block into the Publish File: which Widget the folder is."""
450
+ publish_file["widget"] = block
451
+ (folder / PUBLISH_FILE).write_text(json.dumps(publish_file, indent=2, ensure_ascii=False) + "\n", "utf-8")
452
+
453
+
454
+ def _holds_marker(path: Path, markers: list[str]) -> bool:
455
+ """Whether a folder holds a marker of a virtual environment: a file, or a folder when it ends in ``/``."""
456
+ for marker in markers:
457
+ if marker.endswith("/") and (path / marker.rstrip("/")).is_dir():
458
+ return True
459
+ if not marker.endswith("/") and (path / marker).is_file():
460
+ return True
461
+ return False
462
+
463
+
464
+ def _print_logs(logs: Any) -> None:
465
+ """Prints a Test Run's logs, which may be any JSON value."""
466
+ print("The Test Run's logs:", file=sys.stderr)
467
+ if logs is None:
468
+ print("(none)", file=sys.stderr)
469
+ elif isinstance(logs, str):
470
+ print(logs, file=sys.stderr)
471
+ elif isinstance(logs, list):
472
+ for line in logs:
473
+ print(line if isinstance(line, str) else json.dumps(line, ensure_ascii=False), file=sys.stderr)
474
+ else:
475
+ print(json.dumps(logs, indent=2, ensure_ascii=False), file=sys.stderr)
476
+
477
+
478
+ def _is_project_version(value: Any) -> bool:
479
+ if not isinstance(value, dict) or not isinstance(value.get("version"), int):
480
+ return False
481
+ upload = value.get("upload")
482
+ return (
483
+ isinstance(upload, dict)
484
+ and isinstance(upload.get("url"), str)
485
+ and isinstance(upload.get("fields"), dict)
486
+ and isinstance(upload.get("prefix"), str)
487
+ and isinstance(value.get("junk"), dict)
488
+ )
489
+
490
+
491
+ def _is_candidate(value: Any) -> bool:
492
+ return isinstance(value, dict) and isinstance(value.get("version"), int)
493
+
494
+
495
+ def _is_listing(value: Any) -> bool:
496
+ return isinstance(value, dict) and isinstance(value.get("listing_revision"), str)
@@ -36,3 +36,22 @@ def test_command(recording: dict[str, Any], monkeypatch: pytest.MonkeyPatch, cap
36
36
  assert_fields(json.loads((dir / path).read_text("utf-8")), fields, path)
37
37
  finally:
38
38
  server.close()
39
+
40
+
41
+ def test_publish_without_a_key_prints_every_fault_and_sends_nothing(
42
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
43
+ ) -> None:
44
+ server = Replay({"exchanges": []}, KEY)
45
+ try:
46
+ with with_files({"run.py": "print('words')\n", "requirements.txt": "\n"}) as dir:
47
+ monkeypatch.delenv("ABYSS_API_KEY", raising=False)
48
+ monkeypatch.setenv("ABYSS_BASE_URL", server.base)
49
+ exit = main(["publish", str(dir)])
50
+ printed = capsys.readouterr()
51
+
52
+ assert server.problems == []
53
+ assert exit == 1
54
+ assert "publish_file_missing" in printed.err
55
+ assert "invalid_api_key" in printed.err
56
+ finally:
57
+ server.close()
@@ -1,293 +0,0 @@
1
- """The ``abysshub`` command. ``abysshub publish <folder>`` does what a person does on the
2
- website's Publish page, through `/v1`'s routes that change a Widget. It asks nothing at a
3
- prompt: it stops or it goes, and every stop exits non-zero with its ``code``."""
4
- from __future__ import annotations
5
-
6
- import argparse
7
- import json
8
- import os
9
- import sys
10
- from fnmatch import fnmatchcase
11
- from pathlib import Path
12
- from typing import Any
13
-
14
- from ._client import Abyss, _expect, _has_ended, _is_upload, _is_widget
15
- from ._error import AbyssError
16
- from ._files import file
17
- from ._types import parse_upload
18
-
19
- PUBLISH_FILE = "abyss.json"
20
- TEST_INPUTS = "test_inputs.json"
21
- INTERFACE = "interface.json"
22
- ROOT_ENV = (".env", ".env.*")
23
- """A root ``.env`` and its variants: never content, whatever the Junk list says."""
24
- LISTING_FIELDS = ("title", "description", "tags", "visibility", "price", "free_runs")
25
- """The Listing Fields the Publish File holds, beside its thumbnail."""
26
- JSON = {"Content-Type": "application/json"}
27
-
28
-
29
- def main(argv: list[str] | None = None) -> int:
30
- """Runs the command and answers its exit code."""
31
- parser = argparse.ArgumentParser(prog="abysshub", description="Publish a Widget folder to Abyss.")
32
- verbs = parser.add_subparsers(dest="verb", metavar="<verb>")
33
- verbs.required = True
34
- publish_verb = verbs.add_parser(
35
- "publish",
36
- help="publish a Widget folder and print its link",
37
- description=f"Publish a Widget folder, with its {PUBLISH_FILE} and {TEST_INPUTS}, and print its link.",
38
- )
39
- publish_verb.add_argument("folder", type=Path)
40
- args = parser.parse_args(argv)
41
- try:
42
- with Abyss() as abyss:
43
- print(publish(abyss, args.folder))
44
- except AbyssError as error:
45
- print(f"abysshub: stopped: {error.code}: {error.message}", file=sys.stderr)
46
- if error.request_id:
47
- print(f"request_id: {error.request_id}", file=sys.stderr)
48
- return 1
49
- except OSError as error:
50
- # A file the folder names, such as the thumbnail or a Test Input, is missing or unreadable.
51
- print(f"abysshub: stopped: file_unreadable: {error}", file=sys.stderr)
52
- return 1
53
- return 0
54
-
55
-
56
- def publish(abyss: Abyss, folder: Path) -> str:
57
- """Publishes a folder that was never published, and answers the Widget's link.
58
-
59
- A Draft's id goes into the Publish File as soon as it is made, and its Candidate's
60
- number once committed, so a publish that stops is taken up again on the same Draft.
61
- """
62
- publish_file = _read_json(folder / PUBLISH_FILE, "publish_file_invalid")
63
- if not isinstance(publish_file, dict):
64
- raise AbyssError("publish_file_invalid", f"{PUBLISH_FILE} is not a JSON object.")
65
- test_inputs = _read_json(folder / TEST_INPUTS, "test_inputs_invalid") if (folder / TEST_INPUTS).is_file() else {}
66
- if not isinstance(test_inputs, dict):
67
- raise AbyssError("test_inputs_invalid", f"{TEST_INPUTS} is not a JSON object.")
68
- interface = _read_json(folder / INTERFACE, "interface_invalid") if (folder / INTERFACE).is_file() else None
69
- block = publish_file.get("widget") or {}
70
- if not isinstance(block, dict):
71
- raise AbyssError("publish_file_invalid", f"The widget block of {PUBLISH_FILE} is not a JSON object.")
72
- if "version" in block:
73
- raise AbyssError(
74
- "widget_published",
75
- f"This folder is {block.get('id')}, published already; this abysshub publishes a new Widget only.",
76
- )
77
-
78
- widget = block.get("id")
79
- if widget is None:
80
- draft = _expect(
81
- abyss._send(abyss._start(None), "POST", f"{abyss.base_url}/v1/widgets", retries=0),
82
- _is_widget,
83
- "The Draft answered without an id.",
84
- )
85
- widget = draft["id"]
86
- _write_block(folder, publish_file, {"id": widget})
87
- print(f"Made the Draft {widget}.")
88
- else:
89
- print(f"Publishing the Draft {widget}.")
90
- widget_url = abyss._widget_url(widget)
91
-
92
- base = json.dumps({"base_version": block.get("candidate")}).encode()
93
- opened = _expect(
94
- abyss._send(abyss._start(None), "POST", f"{widget_url}/versions", JSON, base),
95
- _is_project_version,
96
- "The version answered without its number, form and Junk list.",
97
- )
98
- sent, left_out = _folder_files(folder, opened["junk"], publish_file.get("thumbnail"))
99
- for path in left_out:
100
- print(f"Left out {path}")
101
- upload = opened["upload"]
102
- for path in sent:
103
- fields = {**upload["fields"], "key": f"{upload['prefix']}/{path}"}
104
- data = (folder / path).read_bytes()
105
- abyss._store(abyss._start(None), upload["url"], fields, path, Path(path).name, data)
106
- print(f"Sent {len(sent)} files.")
107
-
108
- version = opened["version"]
109
- commit = json.dumps({} if interface is None else {"interface": interface}).encode()
110
- candidate = _expect(
111
- abyss._send(abyss._start(None), "POST", f"{widget_url}/versions/{version}/commit", JSON, commit),
112
- _is_candidate,
113
- "The commit answered without a Candidate.",
114
- )
115
- _write_block(folder, publish_file, {"id": widget, "candidate": candidate["version"]})
116
-
117
- print(f"Test Run of version {candidate['version']}...")
118
- run = _test_run(abyss, folder, widget, candidate["version"], test_inputs, interface)
119
- if run["status"] == "failed":
120
- _print_logs(run.get("logs"))
121
- error = run.get("error") or {}
122
- raise AbyssError(
123
- error.get("code", "platform_fault"),
124
- f"The Test Run {run['id']} failed, so nothing was published. {error.get('message', '')}".rstrip(),
125
- run_id=run["id"],
126
- )
127
-
128
- listing = _save_listing(abyss, folder, widget, publish_file)
129
- published = _expect(
130
- abyss._send(abyss._start(None), "POST", f"{widget_url}/publish"),
131
- _is_widget,
132
- "The publish answered without the Widget.",
133
- )
134
- _write_block(
135
- folder,
136
- publish_file,
137
- {"id": widget, "version": candidate["version"], "listing_revision": listing["listing_revision"]},
138
- )
139
- return str(published["url"])
140
-
141
-
142
- def _folder_files(folder: Path, junk: dict[str, Any], thumbnail: str | None) -> tuple[list[str], list[str]]:
143
- """The folder's files to send, and what it leaves out, by their paths in the folder:
144
- what the Junk list names, the Publish File, its thumbnail, and a root ``.env`` with its
145
- variants. A folder that is left out is named once, with a ``/``."""
146
- names = junk.get("names") or []
147
- markers = junk.get("markers") or []
148
- root_names = [*(junk.get("root") or []), *ROOT_ENV]
149
- skipped = {PUBLISH_FILE}
150
- if thumbnail:
151
- skipped.add(Path(thumbnail).as_posix())
152
- sent: list[str] = []
153
- left_out: list[str] = []
154
- for top, dirs, files in os.walk(folder):
155
- here = Path(top)
156
- at_root = here == folder
157
- kept_dirs = []
158
- for name in sorted(dirs):
159
- path = here / name
160
- if any(fnmatchcase(name, pattern) for pattern in names) or _holds_marker(path, markers):
161
- left_out.append(f"{path.relative_to(folder).as_posix()}/")
162
- else:
163
- kept_dirs.append(name)
164
- dirs[:] = kept_dirs
165
- for name in sorted(files):
166
- relative = (here / name).relative_to(folder).as_posix()
167
- if (
168
- any(fnmatchcase(name, pattern) for pattern in names)
169
- or (at_root and any(fnmatchcase(name, pattern) for pattern in root_names))
170
- or relative in skipped
171
- ):
172
- left_out.append(relative)
173
- else:
174
- sent.append(relative)
175
- return sent, left_out
176
-
177
-
178
- def _test_run(
179
- abyss: Abyss,
180
- folder: Path,
181
- widget: str,
182
- version: int,
183
- test_inputs: dict[str, Any],
184
- interface: list[Any] | None,
185
- ) -> dict[str, Any]:
186
- """Makes the Test Run of the Candidate from the Test Inputs and waits for its ending,
187
- as ``run()`` waits. A file Field's value is a path in the folder, uploaded for that
188
- Candidate. Answers the run, failed or not."""
189
- file_fields = {
190
- field.get("name") for field in interface or [] if isinstance(field, dict) and field.get("type") == "file"
191
- }
192
-
193
- def value(name: str, item: Any) -> Any:
194
- if name not in file_fields:
195
- return item
196
- if isinstance(item, list):
197
- return [file(str(folder / path)) if isinstance(path, str) else path for path in item]
198
- return file(str(folder / item)) if isinstance(item, str) else item
199
-
200
- input = {name: value(name, item) for name, item in test_inputs.items()}
201
- call = abyss._start(None)
202
- press = abyss._press(call, widget, input, None, None, hold=True, version=version)
203
- reply = press if _has_ended(press) else abyss._hold(call, abyss._wait_url(press), _has_ended)
204
- assert reply.run is not None
205
- return reply.run
206
-
207
-
208
- def _save_listing(abyss: Abyss, folder: Path, widget: str, publish_file: dict[str, Any]) -> dict[str, Any]:
209
- """Saves the Publish File's Listing Fields, ``private`` unless it says, and sends the
210
- thumbnail it names first. Answers the listing as saved."""
211
- widget_url = abyss._widget_url(widget)
212
- save = {name: publish_file[name] for name in LISTING_FIELDS if name in publish_file}
213
- save.setdefault("visibility", "private")
214
- thumbnail = publish_file.get("thumbnail")
215
- if thumbnail:
216
- path = folder / thumbnail
217
- data = path.read_bytes()
218
- call = abyss._start(None)
219
- body = json.dumps({"filename": path.name, "size": len(data)}).encode()
220
- grant = parse_upload(
221
- _expect(
222
- abyss._send(call, "POST", f"{widget_url}/listing/thumbnail", JSON, body),
223
- _is_upload,
224
- "The thumbnail answered without an id and a form.",
225
- )
226
- )
227
- abyss._store(call, grant.upload.url, grant.upload.fields, "thumbnail", path.name, data)
228
- save["thumbnail"] = grant.id
229
- return _expect(
230
- abyss._send(abyss._start(None), "PATCH", f"{widget_url}/listing", JSON, json.dumps(save).encode()),
231
- _is_listing,
232
- "The listing answered without its revision.",
233
- )
234
-
235
-
236
- def _read_json(path: Path, code: str) -> Any:
237
- try:
238
- return json.loads(path.read_text("utf-8"))
239
- except FileNotFoundError:
240
- raise AbyssError(code, f"{path} is missing.") from None
241
- except ValueError as error:
242
- raise AbyssError(code, f"{path} is not valid JSON: {error}") from None
243
-
244
-
245
- def _write_block(folder: Path, publish_file: dict[str, Any], block: dict[str, Any]) -> None:
246
- """Writes the ``widget`` block into the Publish File: which Widget the folder is."""
247
- publish_file["widget"] = block
248
- (folder / PUBLISH_FILE).write_text(json.dumps(publish_file, indent=2, ensure_ascii=False) + "\n", "utf-8")
249
-
250
-
251
- def _holds_marker(path: Path, markers: list[str]) -> bool:
252
- """Whether a folder holds a marker of a virtual environment: a file, or a folder when it ends in ``/``."""
253
- for marker in markers:
254
- if marker.endswith("/") and (path / marker.rstrip("/")).is_dir():
255
- return True
256
- if not marker.endswith("/") and (path / marker).is_file():
257
- return True
258
- return False
259
-
260
-
261
- def _print_logs(logs: Any) -> None:
262
- """Prints a Test Run's logs, which may be any JSON value."""
263
- print("The Test Run's logs:", file=sys.stderr)
264
- if logs is None:
265
- print("(none)", file=sys.stderr)
266
- elif isinstance(logs, str):
267
- print(logs, file=sys.stderr)
268
- elif isinstance(logs, list):
269
- for line in logs:
270
- print(line if isinstance(line, str) else json.dumps(line, ensure_ascii=False), file=sys.stderr)
271
- else:
272
- print(json.dumps(logs, indent=2, ensure_ascii=False), file=sys.stderr)
273
-
274
-
275
- def _is_project_version(value: Any) -> bool:
276
- if not isinstance(value, dict) or not isinstance(value.get("version"), int):
277
- return False
278
- upload = value.get("upload")
279
- return (
280
- isinstance(upload, dict)
281
- and isinstance(upload.get("url"), str)
282
- and isinstance(upload.get("fields"), dict)
283
- and isinstance(upload.get("prefix"), str)
284
- and isinstance(value.get("junk"), dict)
285
- )
286
-
287
-
288
- def _is_candidate(value: Any) -> bool:
289
- return isinstance(value, dict) and isinstance(value.get("version"), int)
290
-
291
-
292
- def _is_listing(value: Any) -> bool:
293
- return isinstance(value, dict) and isinstance(value.get("listing_revision"), str)
File without changes
File without changes
File without changes