abysshub 1.0.1.dev11__tar.gz → 1.0.1.dev12__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 (26) hide show
  1. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev12}/PKG-INFO +1 -1
  2. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev12}/pyproject.toml +1 -1
  3. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev12}/src/abysshub/_command.py +202 -36
  4. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev12}/tests/test_command.py +13 -2
  5. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev12}/.gitignore +0 -0
  6. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev12}/LICENSE +0 -0
  7. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev12}/README.md +0 -0
  8. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev12}/src/abysshub/__init__.py +0 -0
  9. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev12}/src/abysshub/__main__.py +0 -0
  10. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev12}/src/abysshub/_async_client.py +0 -0
  11. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev12}/src/abysshub/_client.py +0 -0
  12. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev12}/src/abysshub/_error.py +0 -0
  13. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev12}/src/abysshub/_files.py +0 -0
  14. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev12}/src/abysshub/_http.py +0 -0
  15. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev12}/src/abysshub/_run.py +0 -0
  16. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev12}/src/abysshub/_types.py +0 -0
  17. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev12}/src/abysshub/py.typed +0 -0
  18. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev12}/tests/caller.py +0 -0
  19. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev12}/tests/conftest.py +0 -0
  20. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev12}/tests/fake_server.py +0 -0
  21. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev12}/tests/test_client.py +0 -0
  22. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev12}/tests/test_files.py +0 -0
  23. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev12}/tests/test_http.py +0 -0
  24. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev12}/tests/test_package.py +0 -0
  25. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev12}/tests/test_replay.py +0 -0
  26. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev12}/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.dev11
3
+ Version: 1.0.1.dev12
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.dev11"
7
+ version = "1.0.1.dev12"
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",
@@ -1,6 +1,7 @@
1
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``."""
2
+ website's Publish page, through `/v1`'s routes that change a Widget; ``abysshub status``
3
+ shows the Widget on Abyss beside the folder, and ``abysshub pull`` takes its listing. It
4
+ asks nothing at a prompt: it stops or it goes, and every stop exits non-zero with its ``code``."""
4
5
  from __future__ import annotations
5
6
 
6
7
  import argparse
@@ -16,6 +17,7 @@ from typing import Any
16
17
  from ._client import Abyss, _expect, _has_ended, _is_key, _is_upload, _is_widget
17
18
  from ._error import AbyssError
18
19
  from ._files import file
20
+ from ._run import _downloaded
19
21
  from ._types import parse_upload
20
22
 
21
23
  PUBLISH_FILE = "abyss.json"
@@ -28,6 +30,8 @@ LISTING_FIELDS = ("title", "description", "tags", "visibility", "price", "free_r
28
30
  IMAGES = (".png", ".jpg", ".jpeg", ".webp", ".gif")
29
31
  """The extensions a thumbnail may have: an image's."""
30
32
  JSON = {"Content-Type": "application/json"}
33
+ SOURCES = {"widget": "the Widget", "account": "your account"}
34
+ """Where an Environment name comes from, in words."""
31
35
 
32
36
 
33
37
  def main(argv: list[str] | None = None) -> int:
@@ -44,18 +48,45 @@ def main(argv: list[str] | None = None) -> int:
44
48
  publish_verb.add_argument(
45
49
  "--force", action="store_true", help="publish over a Widget that moved on Abyss: the folder wins"
46
50
  )
51
+ status_verb = verbs.add_parser(
52
+ "status",
53
+ help="show the Widget on Abyss beside the folder, changing nothing",
54
+ description="Show the Widget on Abyss beside the folder: its link, its version, each Listing Field that "
55
+ "differs, where each Environment name comes from, and whether it moved. Changes nothing.",
56
+ )
57
+ status_verb.add_argument("folder", type=Path)
58
+ pull_verb = verbs.add_parser(
59
+ "pull",
60
+ help="take the Widget's listing and thumbnail from Abyss into the folder",
61
+ description=f"Write the Widget's Listing Fields into {PUBLISH_FILE} and its thumbnail into the folder. "
62
+ "Never touches code.",
63
+ )
64
+ pull_verb.add_argument("folder", type=Path)
47
65
  args = parser.parse_args(argv)
48
- widget_folder, faults = _read_folder(args.folder)
66
+ if args.verb == "publish":
67
+ widget_folder, faults = _read_folder(args.folder)
68
+ else:
69
+ publish_file, faults = _read_publish_file(args.folder)
70
+ if faults:
71
+ return _stop(faults)
72
+ if args.verb == "status" and "version" not in (publish_file.get("widget") or {}):
73
+ print(f"{args.folder} was never published: `abysshub publish {args.folder}` publishes it.")
74
+ return 0
49
75
  try:
50
76
  abyss = Abyss()
51
77
  except AbyssError as error:
52
78
  return _stop([*faults, (error.code, error.message)])
53
79
  with abyss:
54
- faults.extend(_key_faults(abyss))
55
- if faults:
56
- return _stop(faults)
57
80
  try:
58
- print(publish(abyss, args.folder, widget_folder, args.force))
81
+ if args.verb == "publish":
82
+ faults.extend(_key_faults(abyss))
83
+ if faults:
84
+ return _stop(faults)
85
+ print(publish(abyss, args.folder, widget_folder, args.force))
86
+ elif args.verb == "status":
87
+ status(abyss, args.folder, publish_file)
88
+ else:
89
+ pull(abyss, args.folder, publish_file)
59
90
  except AbyssError as error:
60
91
  print(f"abysshub: stopped: {error.code}: {error.message}", file=sys.stderr)
61
92
  if error.request_id:
@@ -105,6 +136,15 @@ def _read_folder(folder: Path) -> tuple[_Folder, list[tuple[str, str]]]:
105
136
  return _Folder(publish_file or {}, interface, test_input), faults
106
137
 
107
138
 
139
+ def _read_publish_file(folder: Path) -> tuple[dict[str, Any], list[tuple[str, str]]]:
140
+ """Reads the Publish File alone, as ``status`` and ``pull`` need it, with its faults."""
141
+ faults: list[tuple[str, str]] = []
142
+ publish_file = _read_json(folder / PUBLISH_FILE, "publish_file", dict, faults)
143
+ if publish_file is not None and not isinstance(publish_file.get("widget") or {}, dict):
144
+ faults.append(("publish_file_invalid", f"The widget block of {PUBLISH_FILE} is not a JSON object."))
145
+ return publish_file or {}, faults
146
+
147
+
108
148
  def _check_listing(folder: Path, publish_file: dict[str, Any], faults: list[tuple[str, str]]) -> None:
109
149
  """The Publish File's faults: no title, no tag, and a thumbnail that is missing on a
110
150
  first publish or names no image file in the folder."""
@@ -173,10 +213,12 @@ def _key_faults(abyss: Abyss) -> list[tuple[str, str]]:
173
213
 
174
214
  def _names_file(folder: Path, path: Any) -> bool:
175
215
  """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
216
+ return isinstance(path, str) and _inside(folder, path) and (folder / path).is_file()
217
+
218
+
219
+ def _inside(folder: Path, path: str) -> bool:
220
+ """Whether ``path`` is inside the folder, whether or not a file is there."""
221
+ return bool(path) and folder.resolve() in (folder / path).resolve().parents
180
222
 
181
223
 
182
224
  def publish(abyss: Abyss, folder: Path, widget_folder: _Folder, force: bool = False) -> str:
@@ -270,51 +312,170 @@ def publish(abyss: Abyss, folder: Path, widget_folder: _Folder, force: bool = Fa
270
312
  return str(published["url"])
271
313
 
272
314
 
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(
315
+ def _read_listing(abyss: Abyss, widget: str) -> dict[str, Any]:
316
+ """Reads a Widget's Listing Fields with its listing revision and its live version."""
317
+ return abyss._get(
282
318
  abyss._start(None),
283
319
  f"{abyss._widget_url(widget)}/listing",
284
320
  lambda value: _is_listing(value) and "live_version" in value,
285
321
  "The listing answered without its revision and its live version.",
286
322
  )
323
+
324
+
325
+ @dataclass
326
+ class _Beside:
327
+ """A published Widget's listing on Abyss, beside the folder that was its last publish or pull."""
328
+
329
+ listing: dict[str, Any]
330
+ changes: dict[str, Any]
331
+ """The Publish File's Listing Fields whose value is not the website's."""
332
+ thumbnail_changed: bool
333
+ """The folder's thumbnail is not the one last sent or pulled."""
334
+ listing_moved: bool
335
+ code_moved: bool
336
+
337
+
338
+ def _beside(abyss: Abyss, folder: Path, block: dict[str, Any], publish_file: dict[str, Any]) -> _Beside:
339
+ """Reads the Widget's listing and prints it beside the folder. The Widget moved when
340
+ its listing revision or its live version is not the block's."""
341
+ widget = block["id"]
342
+ listing = _read_listing(abyss, widget)
287
343
  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
344
  thumbnail = publish_file.get("thumbnail")
291
- send_thumbnail = bool(thumbnail) and (
292
- (listing_moved and force) or _sha256(folder / thumbnail) != block.get("thumbnail_sha256")
345
+ path = folder / thumbnail if isinstance(thumbnail, str) and thumbnail else None
346
+ beside = _Beside(
347
+ listing,
348
+ changes,
349
+ path is not None and (not path.is_file() or _sha256(path) != block.get("thumbnail_sha256")),
350
+ listing["listing_revision"] != block.get("listing_revision"),
351
+ listing["live_version"] != block.get("version"),
293
352
  )
294
353
 
295
354
  print(f"{widget} on Abyss beside the folder:")
296
355
  for name, value in changes.items():
297
356
  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:
357
+ if beside.thumbnail_changed:
358
+ print(f" thumbnail: {thumbnail} changed in the folder")
359
+ if beside.listing_moved:
301
360
  print(" listing: changed on Abyss since the folder's last publish or pull")
302
- if code_moved:
361
+ if beside.code_moved:
303
362
  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")
363
+ else:
364
+ print(f" code: version {listing['live_version']} is live on Abyss, as in the folder")
365
+ if not (changes or beside.thumbnail_changed or beside.listing_moved or beside.code_moved):
366
+ print(" nothing else differs")
367
+ return beside
368
+
306
369
 
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 ""
370
+ def _moved(beside: _Beside) -> str:
371
+ """What moved on Abyss, in words: its listing, its code, or both."""
372
+ return " and ".join(
373
+ what for what, did in (("its listing", beside.listing_moved), ("its code", beside.code_moved)) if did
374
+ )
375
+
376
+
377
+ def _compare(
378
+ abyss: Abyss, folder: Path, block: dict[str, Any], publish_file: dict[str, Any], force: bool
379
+ ) -> tuple[dict[str, Any], dict[str, Any], bool]:
380
+ """Prints the Widget beside the folder, before any upload. A Widget that moved stops
381
+ the publish, unless ``force`` makes the folder win. Answers the listing, the Listing
382
+ Fields to save, and whether to send the thumbnail."""
383
+ widget = block["id"]
384
+ beside = _beside(abyss, folder, block, publish_file)
385
+ moved = beside.listing_moved or beside.code_moved
386
+ if moved and not force:
387
+ pull = "take the website's listing with `abysshub pull`, or " if beside.listing_moved else ""
310
388
  raise AbyssError(
311
389
  "widget_moved",
312
- f"{widget} moved on Abyss since this folder's last publish or pull: {moved} changed there. "
390
+ f"{widget} moved on Abyss since this folder's last publish or pull: {_moved(beside)} changed there. "
313
391
  f"Nothing was sent. To go on, {pull}publish with --force to make the folder win.",
314
392
  )
315
- if listing_moved or code_moved:
393
+ if moved:
316
394
  print("--force: the folder wins over what moved on Abyss.")
317
- return listing, changes, send_thumbnail
395
+ send_thumbnail = bool(publish_file.get("thumbnail")) and (
396
+ (beside.listing_moved and force) or beside.thumbnail_changed
397
+ )
398
+ return beside.listing, beside.changes, send_thumbnail
399
+
400
+
401
+ def status(abyss: Abyss, folder: Path, publish_file: dict[str, Any]) -> None:
402
+ """Prints a published Widget beside its folder, and sends nothing that changes anything:
403
+ its link, its version, each Listing Field that differs, where each Environment name
404
+ comes from (never a value), and whether it moved since the folder's last publish or pull."""
405
+ block = publish_file["widget"]
406
+ widget = block["id"]
407
+ print(f"{widget}: {abyss.widgets.get(widget).url}")
408
+ beside = _beside(abyss, folder, block, publish_file)
409
+ environment = abyss._get(
410
+ abyss._start(None),
411
+ f"{abyss._widget_url(widget)}/environment",
412
+ _is_environment,
413
+ "The environment answered without its names.",
414
+ )
415
+ print("Environment:")
416
+ for name, entry in sorted(environment["names"].items()):
417
+ print(f" {name}: from {SOURCES.get(entry.get('source'), entry.get('source'))}")
418
+ if not environment["names"]:
419
+ print(" no names")
420
+ if beside.listing_moved or beside.code_moved:
421
+ print(f"{widget} moved on Abyss since this folder's last publish or pull: {_moved(beside)} changed there.")
422
+ if beside.listing_moved:
423
+ print(f"`abysshub pull {folder}` takes the website's listing into the folder.")
424
+ if beside.code_moved:
425
+ print("Only `abysshub publish --force` replaces the code on Abyss with the folder's.")
426
+ else:
427
+ print(f"{widget} did not move on Abyss since this folder's last publish or pull.")
428
+
429
+
430
+ def pull(abyss: Abyss, folder: Path, publish_file: dict[str, Any]) -> None:
431
+ """Writes the website's value of each Listing Field the Publish File holds into it, the
432
+ Widget's thumbnail to the path the Publish File names, and the listing revision into the
433
+ ``widget`` block, and prints each value it changed. It never touches code: a newer live
434
+ version is only named."""
435
+ block = dict(publish_file.get("widget") or {})
436
+ if "version" not in block:
437
+ raise AbyssError(
438
+ "not_published",
439
+ f"{folder} was never published, so there is nothing to pull. `abysshub publish {folder}` publishes it.",
440
+ )
441
+ thumbnail = publish_file.get("thumbnail")
442
+ if thumbnail and not (
443
+ isinstance(thumbnail, str) and Path(thumbnail).suffix.lower() in IMAGES and _inside(folder, thumbnail)
444
+ ):
445
+ raise AbyssError(
446
+ "thumbnail_not_image",
447
+ f"The thumbnail {thumbnail!r} names no image file ({', '.join(IMAGES)}) inside the folder. Nothing was pulled.",
448
+ )
449
+ widget = block["id"]
450
+ listing = _read_listing(abyss, widget)
451
+ print(f"Pulled the listing of {widget} into the folder:")
452
+ changed = False
453
+ for name, value in _listing_fields(publish_file).items():
454
+ if listing[name] != value:
455
+ print(f" {name}: {_shown(listing[name])}, was {_shown(value)}")
456
+ publish_file[name] = listing[name]
457
+ changed = True
458
+ url = listing["thumbnail"]
459
+ # Only to the path the Publish File names: a path the command chose could be one of the folder's files.
460
+ if thumbnail and isinstance(url, str) and url:
461
+ answered, read = abyss._download(url, None)
462
+ data = _downloaded("the thumbnail", answered, read())
463
+ path = folder / thumbnail
464
+ if not path.is_file() or path.read_bytes() != data:
465
+ path.parent.mkdir(parents=True, exist_ok=True)
466
+ path.write_bytes(data)
467
+ print(f" thumbnail: written to {thumbnail}")
468
+ changed = True
469
+ block["thumbnail_sha256"] = hashlib.sha256(data).hexdigest()
470
+ if not changed:
471
+ print(" nothing changed")
472
+ block["listing_revision"] = listing["listing_revision"]
473
+ _write_block(folder, publish_file, block)
474
+ if listing["live_version"] != block["version"]:
475
+ print(
476
+ f"The code on Abyss is newer: version {listing['live_version']} is live, the folder's is version "
477
+ f"{block['version']}. A pull never touches code: only `abysshub publish --force` replaces it with the folder's."
478
+ )
318
479
 
319
480
 
320
481
  def _folder_files(folder: Path, junk: dict[str, Any], thumbnail: str | None) -> tuple[list[str], list[str]]:
@@ -494,3 +655,8 @@ def _is_candidate(value: Any) -> bool:
494
655
 
495
656
  def _is_listing(value: Any) -> bool:
496
657
  return isinstance(value, dict) and isinstance(value.get("listing_revision"), str)
658
+
659
+
660
+ def _is_environment(value: Any) -> bool:
661
+ names = value.get("names") if isinstance(value, dict) else None
662
+ return isinstance(names, dict) and all(isinstance(entry, dict) for entry in names.values())
@@ -24,7 +24,12 @@ def test_command(recording: dict[str, Any], monkeypatch: pytest.MonkeyPatch, cap
24
24
  with with_files(call["files"]) as dir:
25
25
  monkeypatch.setenv("ABYSS_API_KEY", KEY)
26
26
  monkeypatch.setenv("ABYSS_BASE_URL", server.base)
27
- exit = main([*call["command"], str(dir)])
27
+ before = {path: (dir / path).read_bytes() for path in call["files"]}
28
+ commands = [call["command"], *(call.get("then") or [])]
29
+ # Each command before the last must go through.
30
+ for command in commands[:-1]:
31
+ assert main([*command, str(dir)]) == 0, capsys.readouterr().err
32
+ exit = main([*commands[-1], str(dir)])
28
33
  printed = capsys.readouterr()
29
34
 
30
35
  assert server.problems == []
@@ -33,7 +38,13 @@ def test_command(recording: dict[str, Any], monkeypatch: pytest.MonkeyPatch, cap
33
38
  for text in outcome["printed"]:
34
39
  assert text in printed.out + printed.err, f"printed {text}"
35
40
  for path, fields in outcome["written"].items():
36
- assert_fields(json.loads((dir / path).read_text("utf-8")), fields, path)
41
+ if isinstance(fields, str):
42
+ assert (dir / path).read_text("utf-8") == fields, path
43
+ else:
44
+ assert_fields(json.loads((dir / path).read_text("utf-8")), fields, path)
45
+ for path, content in before.items():
46
+ if path not in outcome["written"]:
47
+ assert (dir / path).read_bytes() == content, f"{path} was left as it was"
37
48
  finally:
38
49
  server.close()
39
50
 
File without changes
File without changes