abysshub 1.0.1.dev11__tar.gz → 1.0.1.dev13__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.dev11 → abysshub-1.0.1.dev13}/PKG-INFO +1 -1
  2. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev13}/pyproject.toml +1 -1
  3. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev13}/src/abysshub/_command.py +259 -39
  4. abysshub-1.0.1.dev13/src/abysshub/_env.py +77 -0
  5. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev13}/tests/fake_server.py +1 -1
  6. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev13}/tests/test_command.py +44 -2
  7. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev13}/.gitignore +0 -0
  8. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev13}/LICENSE +0 -0
  9. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev13}/README.md +0 -0
  10. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev13}/src/abysshub/__init__.py +0 -0
  11. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev13}/src/abysshub/__main__.py +0 -0
  12. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev13}/src/abysshub/_async_client.py +0 -0
  13. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev13}/src/abysshub/_client.py +0 -0
  14. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev13}/src/abysshub/_error.py +0 -0
  15. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev13}/src/abysshub/_files.py +0 -0
  16. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev13}/src/abysshub/_http.py +0 -0
  17. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev13}/src/abysshub/_run.py +0 -0
  18. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev13}/src/abysshub/_types.py +0 -0
  19. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev13}/src/abysshub/py.typed +0 -0
  20. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev13}/tests/caller.py +0 -0
  21. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev13}/tests/conftest.py +0 -0
  22. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev13}/tests/test_client.py +0 -0
  23. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev13}/tests/test_files.py +0 -0
  24. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev13}/tests/test_http.py +0 -0
  25. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev13}/tests/test_package.py +0 -0
  26. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev13}/tests/test_replay.py +0 -0
  27. {abysshub-1.0.1.dev11 → abysshub-1.0.1.dev13}/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.dev13
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.dev13"
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
@@ -14,8 +15,10 @@ from pathlib import Path
14
15
  from typing import Any
15
16
 
16
17
  from ._client import Abyss, _expect, _has_ended, _is_key, _is_upload, _is_widget
18
+ from ._env import parse_env
17
19
  from ._error import AbyssError
18
20
  from ._files import file
21
+ from ._run import _downloaded
19
22
  from ._types import parse_upload
20
23
 
21
24
  PUBLISH_FILE = "abyss.json"
@@ -28,6 +31,19 @@ LISTING_FIELDS = ("title", "description", "tags", "visibility", "price", "free_r
28
31
  IMAGES = (".png", ".jpg", ".jpeg", ".webp", ".gif")
29
32
  """The extensions a thumbnail may have: an image's."""
30
33
  JSON = {"Content-Type": "application/json"}
34
+ SOURCES = {"widget": "the Widget", "account": "your account"}
35
+ """Where an Environment name comes from, in words."""
36
+ OUTCOMES = {
37
+ "added": "added",
38
+ "added_over_account": "saved over the account's: your account holds another value, and this Widget's wins in its runs",
39
+ "skipped": "skipped: your account holds the same value, and the Widget uses the account's",
40
+ "kept": "kept: the Widget holds another value, which stays (--use-env-file puts the file's in its place)",
41
+ "replaced": "replaced: the file's value took the place of the Widget's",
42
+ "unchanged": "unchanged: the Widget holds the same value",
43
+ "refused": "refused",
44
+ }
45
+ """What became of each name of a root ``.env``, in words."""
46
+ ABYSS_KEY_PREFIX = "abyss_sk_"
31
47
 
32
48
 
33
49
  def main(argv: list[str] | None = None) -> int:
@@ -44,18 +60,50 @@ def main(argv: list[str] | None = None) -> int:
44
60
  publish_verb.add_argument(
45
61
  "--force", action="store_true", help="publish over a Widget that moved on Abyss: the folder wins"
46
62
  )
63
+ publish_verb.add_argument(
64
+ "--use-env-file",
65
+ action="store_true",
66
+ help="replace the values the Widget already holds with the root .env's",
67
+ )
68
+ status_verb = verbs.add_parser(
69
+ "status",
70
+ help="show the Widget on Abyss beside the folder, changing nothing",
71
+ description="Show the Widget on Abyss beside the folder: its link, its version, each Listing Field that "
72
+ "differs, where each Environment name comes from, and whether it moved. Changes nothing.",
73
+ )
74
+ status_verb.add_argument("folder", type=Path)
75
+ pull_verb = verbs.add_parser(
76
+ "pull",
77
+ help="take the Widget's listing and thumbnail from Abyss into the folder",
78
+ description=f"Write the Widget's Listing Fields into {PUBLISH_FILE} and its thumbnail into the folder. "
79
+ "Never touches code.",
80
+ )
81
+ pull_verb.add_argument("folder", type=Path)
47
82
  args = parser.parse_args(argv)
48
- widget_folder, faults = _read_folder(args.folder)
83
+ if args.verb == "publish":
84
+ widget_folder, faults = _read_folder(args.folder)
85
+ else:
86
+ publish_file, faults = _read_publish_file(args.folder)
87
+ if faults:
88
+ return _stop(faults)
89
+ if args.verb == "status" and "version" not in (publish_file.get("widget") or {}):
90
+ print(f"{args.folder} was never published: `abysshub publish {args.folder}` publishes it.")
91
+ return 0
49
92
  try:
50
93
  abyss = Abyss()
51
94
  except AbyssError as error:
52
95
  return _stop([*faults, (error.code, error.message)])
53
96
  with abyss:
54
- faults.extend(_key_faults(abyss))
55
- if faults:
56
- return _stop(faults)
57
97
  try:
58
- print(publish(abyss, args.folder, widget_folder, args.force))
98
+ if args.verb == "publish":
99
+ faults.extend(_key_faults(abyss))
100
+ if faults:
101
+ return _stop(faults)
102
+ print(publish(abyss, args.folder, widget_folder, args.force, args.use_env_file))
103
+ elif args.verb == "status":
104
+ status(abyss, args.folder, publish_file)
105
+ else:
106
+ pull(abyss, args.folder, publish_file)
59
107
  except AbyssError as error:
60
108
  print(f"abysshub: stopped: {error.code}: {error.message}", file=sys.stderr)
61
109
  if error.request_id:
@@ -76,6 +124,8 @@ class _Folder:
76
124
  interface: list[Any] | None
77
125
  test_input: dict[str, Any]
78
126
  """The Test Run's input: the Test Inputs, and the default of each Field they leave out."""
127
+ environment: dict[str, str] | None
128
+ """The names and values of the root ``.env``, or None without one."""
79
129
 
80
130
 
81
131
  def _stop(faults: list[tuple[str, str]]) -> int:
@@ -102,7 +152,23 @@ def _read_folder(folder: Path) -> tuple[_Folder, list[tuple[str, str]]]:
102
152
  # An invalid interface.json skips the Field checks rather than calling every Test Input unknown.
103
153
  if test_inputs is not None and (interface is not None or not has_interface):
104
154
  test_input = _check_test_inputs(folder, interface or [], test_inputs, faults)
105
- return _Folder(publish_file or {}, interface, test_input), faults
155
+ environment = None
156
+ root_env = folder / ".env"
157
+ if root_env.is_file():
158
+ try:
159
+ environment = parse_env(root_env.read_text("utf-8"))
160
+ except (OSError, ValueError) as error:
161
+ faults.append(("env_invalid", f"The root .env cannot be read: {error}"))
162
+ return _Folder(publish_file or {}, interface, test_input, environment), faults
163
+
164
+
165
+ def _read_publish_file(folder: Path) -> tuple[dict[str, Any], list[tuple[str, str]]]:
166
+ """Reads the Publish File alone, as ``status`` and ``pull`` need it, with its faults."""
167
+ faults: list[tuple[str, str]] = []
168
+ publish_file = _read_json(folder / PUBLISH_FILE, "publish_file", dict, faults)
169
+ if publish_file is not None and not isinstance(publish_file.get("widget") or {}, dict):
170
+ faults.append(("publish_file_invalid", f"The widget block of {PUBLISH_FILE} is not a JSON object."))
171
+ return publish_file or {}, faults
106
172
 
107
173
 
108
174
  def _check_listing(folder: Path, publish_file: dict[str, Any], faults: list[tuple[str, str]]) -> None:
@@ -173,20 +239,25 @@ def _key_faults(abyss: Abyss) -> list[tuple[str, str]]:
173
239
 
174
240
  def _names_file(folder: Path, path: Any) -> bool:
175
241
  """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
242
+ return isinstance(path, str) and _inside(folder, path) and (folder / path).is_file()
243
+
180
244
 
245
+ def _inside(folder: Path, path: str) -> bool:
246
+ """Whether ``path`` is inside the folder, whether or not a file is there."""
247
+ return bool(path) and folder.resolve() in (folder / path).resolve().parents
181
248
 
182
- def publish(abyss: Abyss, folder: Path, widget_folder: _Folder, force: bool = False) -> str:
249
+
250
+ def publish(
251
+ abyss: Abyss, folder: Path, widget_folder: _Folder, force: bool = False, use_env_file: bool = False
252
+ ) -> str:
183
253
  """Publishes a folder, and answers the Widget's link: a new Widget for a folder that was
184
254
  never published, a new version of the same Widget for one that was.
185
255
 
186
256
  A Draft's id goes into the Publish File as soon as it is made, and its Candidate's
187
257
  number once committed, so a publish that stops is taken up again on the same Draft.
188
258
  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``.
259
+ Abyss stops the publish before any upload, unless ``force``. A root ``.env`` goes to
260
+ the Widget's own environment before the Test Run, so the Test Run has it.
190
261
  """
191
262
  publish_file = widget_folder.publish_file
192
263
  interface = widget_folder.interface
@@ -240,6 +311,8 @@ def publish(abyss: Abyss, folder: Path, widget_folder: _Folder, force: bool = Fa
240
311
  )
241
312
  block["candidate"] = candidate["version"]
242
313
  _write_block(folder, publish_file, block)
314
+ if widget_folder.environment is not None:
315
+ _send_environment(abyss, widget, widget_folder.environment, use_env_file)
243
316
 
244
317
  print(f"Test Run of version {candidate['version']}...")
245
318
  run = _test_run(abyss, folder, widget, candidate["version"], widget_folder.test_input, interface)
@@ -270,51 +343,170 @@ def publish(abyss: Abyss, folder: Path, widget_folder: _Folder, force: bool = Fa
270
343
  return str(published["url"])
271
344
 
272
345
 
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(
346
+ def _read_listing(abyss: Abyss, widget: str) -> dict[str, Any]:
347
+ """Reads a Widget's Listing Fields with its listing revision and its live version."""
348
+ return abyss._get(
282
349
  abyss._start(None),
283
350
  f"{abyss._widget_url(widget)}/listing",
284
351
  lambda value: _is_listing(value) and "live_version" in value,
285
352
  "The listing answered without its revision and its live version.",
286
353
  )
354
+
355
+
356
+ @dataclass
357
+ class _Beside:
358
+ """A published Widget's listing on Abyss, beside the folder that was its last publish or pull."""
359
+
360
+ listing: dict[str, Any]
361
+ changes: dict[str, Any]
362
+ """The Publish File's Listing Fields whose value is not the website's."""
363
+ thumbnail_changed: bool
364
+ """The folder's thumbnail is not the one last sent or pulled."""
365
+ listing_moved: bool
366
+ code_moved: bool
367
+
368
+
369
+ def _beside(abyss: Abyss, folder: Path, block: dict[str, Any], publish_file: dict[str, Any]) -> _Beside:
370
+ """Reads the Widget's listing and prints it beside the folder. The Widget moved when
371
+ its listing revision or its live version is not the block's."""
372
+ widget = block["id"]
373
+ listing = _read_listing(abyss, widget)
287
374
  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
375
  thumbnail = publish_file.get("thumbnail")
291
- send_thumbnail = bool(thumbnail) and (
292
- (listing_moved and force) or _sha256(folder / thumbnail) != block.get("thumbnail_sha256")
376
+ path = folder / thumbnail if isinstance(thumbnail, str) and thumbnail else None
377
+ beside = _Beside(
378
+ listing,
379
+ changes,
380
+ path is not None and (not path.is_file() or _sha256(path) != block.get("thumbnail_sha256")),
381
+ listing["listing_revision"] != block.get("listing_revision"),
382
+ listing["live_version"] != block.get("version"),
293
383
  )
294
384
 
295
385
  print(f"{widget} on Abyss beside the folder:")
296
386
  for name, value in changes.items():
297
387
  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:
388
+ if beside.thumbnail_changed:
389
+ print(f" thumbnail: {thumbnail} changed in the folder")
390
+ if beside.listing_moved:
301
391
  print(" listing: changed on Abyss since the folder's last publish or pull")
302
- if code_moved:
392
+ if beside.code_moved:
303
393
  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")
394
+ else:
395
+ print(f" code: version {listing['live_version']} is live on Abyss, as in the folder")
396
+ if not (changes or beside.thumbnail_changed or beside.listing_moved or beside.code_moved):
397
+ print(" nothing else differs")
398
+ return beside
399
+
306
400
 
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 ""
401
+ def _moved(beside: _Beside) -> str:
402
+ """What moved on Abyss, in words: its listing, its code, or both."""
403
+ return " and ".join(
404
+ what for what, did in (("its listing", beside.listing_moved), ("its code", beside.code_moved)) if did
405
+ )
406
+
407
+
408
+ def _compare(
409
+ abyss: Abyss, folder: Path, block: dict[str, Any], publish_file: dict[str, Any], force: bool
410
+ ) -> tuple[dict[str, Any], dict[str, Any], bool]:
411
+ """Prints the Widget beside the folder, before any upload. A Widget that moved stops
412
+ the publish, unless ``force`` makes the folder win. Answers the listing, the Listing
413
+ Fields to save, and whether to send the thumbnail."""
414
+ widget = block["id"]
415
+ beside = _beside(abyss, folder, block, publish_file)
416
+ moved = beside.listing_moved or beside.code_moved
417
+ if moved and not force:
418
+ pull = "take the website's listing with `abysshub pull`, or " if beside.listing_moved else ""
310
419
  raise AbyssError(
311
420
  "widget_moved",
312
- f"{widget} moved on Abyss since this folder's last publish or pull: {moved} changed there. "
421
+ f"{widget} moved on Abyss since this folder's last publish or pull: {_moved(beside)} changed there. "
313
422
  f"Nothing was sent. To go on, {pull}publish with --force to make the folder win.",
314
423
  )
315
- if listing_moved or code_moved:
424
+ if moved:
316
425
  print("--force: the folder wins over what moved on Abyss.")
317
- return listing, changes, send_thumbnail
426
+ send_thumbnail = bool(publish_file.get("thumbnail")) and (
427
+ (beside.listing_moved and force) or beside.thumbnail_changed
428
+ )
429
+ return beside.listing, beside.changes, send_thumbnail
430
+
431
+
432
+ def status(abyss: Abyss, folder: Path, publish_file: dict[str, Any]) -> None:
433
+ """Prints a published Widget beside its folder, and sends nothing that changes anything:
434
+ its link, its version, each Listing Field that differs, where each Environment name
435
+ comes from (never a value), and whether it moved since the folder's last publish or pull."""
436
+ block = publish_file["widget"]
437
+ widget = block["id"]
438
+ print(f"{widget}: {abyss.widgets.get(widget).url}")
439
+ beside = _beside(abyss, folder, block, publish_file)
440
+ environment = abyss._get(
441
+ abyss._start(None),
442
+ f"{abyss._widget_url(widget)}/environment",
443
+ _is_environment,
444
+ "The environment answered without its names.",
445
+ )
446
+ print("Environment:")
447
+ for name, entry in sorted(environment["names"].items()):
448
+ print(f" {name}: from {SOURCES.get(entry.get('source'), entry.get('source'))}")
449
+ if not environment["names"]:
450
+ print(" no names")
451
+ if beside.listing_moved or beside.code_moved:
452
+ print(f"{widget} moved on Abyss since this folder's last publish or pull: {_moved(beside)} changed there.")
453
+ if beside.listing_moved:
454
+ print(f"`abysshub pull {folder}` takes the website's listing into the folder.")
455
+ if beside.code_moved:
456
+ print("Only `abysshub publish --force` replaces the code on Abyss with the folder's.")
457
+ else:
458
+ print(f"{widget} did not move on Abyss since this folder's last publish or pull.")
459
+
460
+
461
+ def pull(abyss: Abyss, folder: Path, publish_file: dict[str, Any]) -> None:
462
+ """Writes the website's value of each Listing Field the Publish File holds into it, the
463
+ Widget's thumbnail to the path the Publish File names, and the listing revision into the
464
+ ``widget`` block, and prints each value it changed. It never touches code: a newer live
465
+ version is only named."""
466
+ block = dict(publish_file.get("widget") or {})
467
+ if "version" not in block:
468
+ raise AbyssError(
469
+ "not_published",
470
+ f"{folder} was never published, so there is nothing to pull. `abysshub publish {folder}` publishes it.",
471
+ )
472
+ thumbnail = publish_file.get("thumbnail")
473
+ if thumbnail and not (
474
+ isinstance(thumbnail, str) and Path(thumbnail).suffix.lower() in IMAGES and _inside(folder, thumbnail)
475
+ ):
476
+ raise AbyssError(
477
+ "thumbnail_not_image",
478
+ f"The thumbnail {thumbnail!r} names no image file ({', '.join(IMAGES)}) inside the folder. Nothing was pulled.",
479
+ )
480
+ widget = block["id"]
481
+ listing = _read_listing(abyss, widget)
482
+ print(f"Pulled the listing of {widget} into the folder:")
483
+ changed = False
484
+ for name, value in _listing_fields(publish_file).items():
485
+ if listing[name] != value:
486
+ print(f" {name}: {_shown(listing[name])}, was {_shown(value)}")
487
+ publish_file[name] = listing[name]
488
+ changed = True
489
+ url = listing["thumbnail"]
490
+ # Only to the path the Publish File names: a path the command chose could be one of the folder's files.
491
+ if thumbnail and isinstance(url, str) and url:
492
+ answered, read = abyss._download(url, None)
493
+ data = _downloaded("the thumbnail", answered, read())
494
+ path = folder / thumbnail
495
+ if not path.is_file() or path.read_bytes() != data:
496
+ path.parent.mkdir(parents=True, exist_ok=True)
497
+ path.write_bytes(data)
498
+ print(f" thumbnail: written to {thumbnail}")
499
+ changed = True
500
+ block["thumbnail_sha256"] = hashlib.sha256(data).hexdigest()
501
+ if not changed:
502
+ print(" nothing changed")
503
+ block["listing_revision"] = listing["listing_revision"]
504
+ _write_block(folder, publish_file, block)
505
+ if listing["live_version"] != block["version"]:
506
+ print(
507
+ f"The code on Abyss is newer: version {listing['live_version']} is live, the folder's is version "
508
+ f"{block['version']}. A pull never touches code: only `abysshub publish --force` replaces it with the folder's."
509
+ )
318
510
 
319
511
 
320
512
  def _folder_files(folder: Path, junk: dict[str, Any], thumbnail: str | None) -> tuple[list[str], list[str]]:
@@ -353,6 +545,29 @@ def _folder_files(folder: Path, junk: dict[str, Any], thumbnail: str | None) ->
353
545
  return sent, left_out
354
546
 
355
547
 
548
+ def _send_environment(abyss: Abyss, widget: str, environment: dict[str, str], use_file_values: bool) -> None:
549
+ """Sends the root ``.env`` to the Widget's own environment and prints what became of
550
+ each name, never a value. A value that is an Abyss key is never sent: it is named."""
551
+ variables = {name: value for name, value in environment.items() if not value.startswith(ABYSS_KEY_PREFIX)}
552
+ print("Environment from .env:")
553
+ for name in environment:
554
+ if name not in variables:
555
+ print(f" {name}: left out: its value is an Abyss key, which never goes to a Widget")
556
+ if variables:
557
+ body = json.dumps({"variables": variables, "use_file_values": use_file_values}).encode()
558
+ saved = _expect(
559
+ abyss._send(abyss._start(None), "PUT", f"{abyss._widget_url(widget)}/environment", JSON, body),
560
+ _is_environment,
561
+ "The environment answered without its names.",
562
+ )
563
+ for name, entry in saved["names"].items():
564
+ outcome = entry.get("outcome")
565
+ code = f": {entry['code']}" if entry.get("code") else ""
566
+ print(f" {name}: {OUTCOMES.get(outcome, outcome)}{code}")
567
+ elif not environment:
568
+ print(" no names")
569
+
570
+
356
571
  def _test_run(
357
572
  abyss: Abyss,
358
573
  folder: Path,
@@ -494,3 +709,8 @@ def _is_candidate(value: Any) -> bool:
494
709
 
495
710
  def _is_listing(value: Any) -> bool:
496
711
  return isinstance(value, dict) and isinstance(value.get("listing_revision"), str)
712
+
713
+
714
+ def _is_environment(value: Any) -> bool:
715
+ names = value.get("names") if isinstance(value, dict) else None
716
+ return isinstance(names, dict) and all(isinstance(entry, dict) for entry in names.values())
@@ -0,0 +1,77 @@
1
+ """A root ``.env`` read as python-dotenv reads it, without depending on it: the value a
2
+ maker's Widget got on their machine is the value the command sends."""
3
+ from __future__ import annotations
4
+
5
+ import codecs
6
+ import re
7
+
8
+ _SPACE = re.compile(r"\s*", re.MULTILINE)
9
+ _EXPORT = re.compile(r"(?:export[^\S\r\n]+)?")
10
+ _QUOTED_KEY = re.compile(r"'([^']+)'")
11
+ _KEY = re.compile(r"([^=\#\s]+)")
12
+ _BLANK = re.compile(r"[^\S\r\n]*")
13
+ _EQUALS = re.compile(r"=[^\S\r\n]*")
14
+ _SINGLE = re.compile(r"'((?:\\'|[^'])*)'")
15
+ _DOUBLE = re.compile(r'"((?:\\"|[^"])*)"')
16
+ _PLAIN = re.compile(r"([^\r\n]*)")
17
+ _COMMENT = re.compile(r"(?:[^\S\r\n]*#[^\r\n]*)?")
18
+ _END = re.compile(r"[^\S\r\n]*(?:\r\n|\n|\r|$)")
19
+ _REST = re.compile(r"[^\r\n]*(?:\r|\n|\r\n)?")
20
+ _SINGLE_ESCAPES = re.compile(r"\\[\\']")
21
+ _DOUBLE_ESCAPES = re.compile(r"\\[\\'\"abfnrtv]")
22
+
23
+
24
+ class _Unread(Exception):
25
+ """A line python-dotenv skips, as it cannot read it."""
26
+
27
+
28
+ def parse_env(text: str) -> dict[str, str]:
29
+ """Each name of a ``.env`` and its value, as python-dotenv's parser gives them: quotes
30
+ and a comment removed, a double-quoted value's escapes decoded, a single-quoted one's
31
+ kept but for ``\\\\`` and ``\\'``. A line it cannot read is left out, a later line
32
+ wins, and a name without ``=`` unsets it. A ``${NAME}`` is kept as written."""
33
+ values: dict[str, str] = {}
34
+ at = 0
35
+
36
+ def read(regex: re.Pattern[str]) -> re.Match[str]:
37
+ nonlocal at
38
+ match = regex.match(text, at)
39
+ if match is None:
40
+ raise _Unread
41
+ at = match.end()
42
+ return match
43
+
44
+ while at < len(text):
45
+ read(_SPACE)
46
+ if at == len(text):
47
+ break
48
+ try:
49
+ read(_EXPORT)
50
+ key = None if text.startswith("#", at) else read(_QUOTED_KEY if text.startswith("'", at) else _KEY).group(1)
51
+ read(_BLANK)
52
+ value = None
53
+ if text.startswith("=", at):
54
+ read(_EQUALS)
55
+ first = text[at : at + 1]
56
+ if first == "'":
57
+ value = _decode(_SINGLE_ESCAPES, read(_SINGLE).group(1))
58
+ elif first == '"':
59
+ value = _decode(_DOUBLE_ESCAPES, read(_DOUBLE).group(1))
60
+ elif first in ("", "\n", "\r"):
61
+ value = ""
62
+ else:
63
+ value = re.sub(r"\s+#.*", "", read(_PLAIN).group(1)).rstrip()
64
+ read(_COMMENT)
65
+ read(_END)
66
+ except _Unread:
67
+ read(_REST)
68
+ continue
69
+ if key is not None and value is not None:
70
+ values[key] = value
71
+ elif key is not None:
72
+ values.pop(key, None)
73
+ return values
74
+
75
+
76
+ def _decode(escapes: re.Pattern[str], value: str) -> str:
77
+ return escapes.sub(lambda match: codecs.decode(match.group(0), "unicode-escape"), value)
@@ -60,7 +60,7 @@ class Replay:
60
60
  # The caller stopped listening, as a timeout does during a hold.
61
61
  self.close_connection = True
62
62
 
63
- do_POST = do_PATCH = do_GET
63
+ do_POST = do_PATCH = do_PUT = do_GET
64
64
 
65
65
  self._server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
66
66
  self._server.daemon_threads = True
@@ -11,6 +11,7 @@ from fake_server import Replay, load_exchanges
11
11
  from test_replay import KEY, assert_fields
12
12
 
13
13
  from abysshub._command import main
14
+ from abysshub._env import parse_env
14
15
 
15
16
  COMMANDS = [recording for recording in load_exchanges() if "command" in recording["call"]]
16
17
 
@@ -24,7 +25,12 @@ def test_command(recording: dict[str, Any], monkeypatch: pytest.MonkeyPatch, cap
24
25
  with with_files(call["files"]) as dir:
25
26
  monkeypatch.setenv("ABYSS_API_KEY", KEY)
26
27
  monkeypatch.setenv("ABYSS_BASE_URL", server.base)
27
- exit = main([*call["command"], str(dir)])
28
+ before = {path: (dir / path).read_bytes() for path in call["files"]}
29
+ commands = [call["command"], *(call.get("then") or [])]
30
+ # Each command before the last must go through.
31
+ for command in commands[:-1]:
32
+ assert main([*command, str(dir)]) == 0, capsys.readouterr().err
33
+ exit = main([*commands[-1], str(dir)])
28
34
  printed = capsys.readouterr()
29
35
 
30
36
  assert server.problems == []
@@ -33,7 +39,16 @@ def test_command(recording: dict[str, Any], monkeypatch: pytest.MonkeyPatch, cap
33
39
  for text in outcome["printed"]:
34
40
  assert text in printed.out + printed.err, f"printed {text}"
35
41
  for path, fields in outcome["written"].items():
36
- assert_fields(json.loads((dir / path).read_text("utf-8")), fields, path)
42
+ if isinstance(fields, str):
43
+ assert (dir / path).read_text("utf-8") == fields, path
44
+ else:
45
+ assert_fields(json.loads((dir / path).read_text("utf-8")), fields, path)
46
+ for path, content in before.items():
47
+ if path not in outcome["written"]:
48
+ assert (dir / path).read_bytes() == content, f"{path} was left as it was"
49
+ # A root .env's names are printed, never its values, an Abyss key left out included.
50
+ for value in parse_env(call["files"].get(".env", "")).values():
51
+ assert not value or value not in printed.out + printed.err, "printed a value of the .env"
37
52
  finally:
38
53
  server.close()
39
54
 
@@ -55,3 +70,30 @@ def test_publish_without_a_key_prints_every_fault_and_sends_nothing(
55
70
  assert "invalid_api_key" in printed.err
56
71
  finally:
57
72
  server.close()
73
+
74
+
75
+ def test_a_root_env_gives_the_values_python_dotenv_gives() -> None:
76
+ text = (
77
+ 'A="quoted" # note\n'
78
+ "B='single' # note\n"
79
+ 'C="line\\nbreak"\n'
80
+ "C2='line\\nkept'\n"
81
+ "D=plain # note\n"
82
+ "E=a#b\n"
83
+ "export F = spaced\n"
84
+ "# a comment\n"
85
+ "G=\n"
86
+ "H\n"
87
+ "K='abyss_sk_live_4f1c' # mine\n"
88
+ )
89
+ assert parse_env(text) == {
90
+ "A": "quoted",
91
+ "B": "single",
92
+ "C": "line\nbreak",
93
+ "C2": "line\\nkept",
94
+ "D": "plain",
95
+ "E": "a#b",
96
+ "F": "spaced",
97
+ "G": "",
98
+ "K": "abyss_sk_live_4f1c",
99
+ }
File without changes
File without changes