abysshub 1.0.1.dev12__tar.gz → 1.0.1.dev14__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.dev12 → abysshub-1.0.1.dev14}/PKG-INFO +1 -1
  2. {abysshub-1.0.1.dev12 → abysshub-1.0.1.dev14}/pyproject.toml +1 -1
  3. {abysshub-1.0.1.dev12 → abysshub-1.0.1.dev14}/src/abysshub/_command.py +58 -4
  4. abysshub-1.0.1.dev14/src/abysshub/_env.py +77 -0
  5. {abysshub-1.0.1.dev12 → abysshub-1.0.1.dev14}/tests/fake_server.py +1 -1
  6. {abysshub-1.0.1.dev12 → abysshub-1.0.1.dev14}/tests/test_command.py +31 -0
  7. {abysshub-1.0.1.dev12 → abysshub-1.0.1.dev14}/.gitignore +0 -0
  8. {abysshub-1.0.1.dev12 → abysshub-1.0.1.dev14}/LICENSE +0 -0
  9. {abysshub-1.0.1.dev12 → abysshub-1.0.1.dev14}/README.md +0 -0
  10. {abysshub-1.0.1.dev12 → abysshub-1.0.1.dev14}/src/abysshub/__init__.py +0 -0
  11. {abysshub-1.0.1.dev12 → abysshub-1.0.1.dev14}/src/abysshub/__main__.py +0 -0
  12. {abysshub-1.0.1.dev12 → abysshub-1.0.1.dev14}/src/abysshub/_async_client.py +0 -0
  13. {abysshub-1.0.1.dev12 → abysshub-1.0.1.dev14}/src/abysshub/_client.py +0 -0
  14. {abysshub-1.0.1.dev12 → abysshub-1.0.1.dev14}/src/abysshub/_error.py +0 -0
  15. {abysshub-1.0.1.dev12 → abysshub-1.0.1.dev14}/src/abysshub/_files.py +0 -0
  16. {abysshub-1.0.1.dev12 → abysshub-1.0.1.dev14}/src/abysshub/_http.py +0 -0
  17. {abysshub-1.0.1.dev12 → abysshub-1.0.1.dev14}/src/abysshub/_run.py +0 -0
  18. {abysshub-1.0.1.dev12 → abysshub-1.0.1.dev14}/src/abysshub/_types.py +0 -0
  19. {abysshub-1.0.1.dev12 → abysshub-1.0.1.dev14}/src/abysshub/py.typed +0 -0
  20. {abysshub-1.0.1.dev12 → abysshub-1.0.1.dev14}/tests/caller.py +0 -0
  21. {abysshub-1.0.1.dev12 → abysshub-1.0.1.dev14}/tests/conftest.py +0 -0
  22. {abysshub-1.0.1.dev12 → abysshub-1.0.1.dev14}/tests/test_client.py +0 -0
  23. {abysshub-1.0.1.dev12 → abysshub-1.0.1.dev14}/tests/test_files.py +0 -0
  24. {abysshub-1.0.1.dev12 → abysshub-1.0.1.dev14}/tests/test_http.py +0 -0
  25. {abysshub-1.0.1.dev12 → abysshub-1.0.1.dev14}/tests/test_package.py +0 -0
  26. {abysshub-1.0.1.dev12 → abysshub-1.0.1.dev14}/tests/test_replay.py +0 -0
  27. {abysshub-1.0.1.dev12 → abysshub-1.0.1.dev14}/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.dev12
3
+ Version: 1.0.1.dev14
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.dev12"
7
+ version = "1.0.1.dev14"
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",
@@ -15,6 +15,7 @@ from pathlib import Path
15
15
  from typing import Any
16
16
 
17
17
  from ._client import Abyss, _expect, _has_ended, _is_key, _is_upload, _is_widget
18
+ from ._env import parse_env
18
19
  from ._error import AbyssError
19
20
  from ._files import file
20
21
  from ._run import _downloaded
@@ -32,6 +33,17 @@ IMAGES = (".png", ".jpg", ".jpeg", ".webp", ".gif")
32
33
  JSON = {"Content-Type": "application/json"}
33
34
  SOURCES = {"widget": "the Widget", "account": "your account"}
34
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_"
35
47
 
36
48
 
37
49
  def main(argv: list[str] | None = None) -> int:
@@ -48,6 +60,11 @@ def main(argv: list[str] | None = None) -> int:
48
60
  publish_verb.add_argument(
49
61
  "--force", action="store_true", help="publish over a Widget that moved on Abyss: the folder wins"
50
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
+ )
51
68
  status_verb = verbs.add_parser(
52
69
  "status",
53
70
  help="show the Widget on Abyss beside the folder, changing nothing",
@@ -82,7 +99,7 @@ def main(argv: list[str] | None = None) -> int:
82
99
  faults.extend(_key_faults(abyss))
83
100
  if faults:
84
101
  return _stop(faults)
85
- print(publish(abyss, args.folder, widget_folder, args.force))
102
+ print(publish(abyss, args.folder, widget_folder, args.force, args.use_env_file))
86
103
  elif args.verb == "status":
87
104
  status(abyss, args.folder, publish_file)
88
105
  else:
@@ -107,6 +124,8 @@ class _Folder:
107
124
  interface: list[Any] | None
108
125
  test_input: dict[str, Any]
109
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."""
110
129
 
111
130
 
112
131
  def _stop(faults: list[tuple[str, str]]) -> int:
@@ -133,7 +152,14 @@ def _read_folder(folder: Path) -> tuple[_Folder, list[tuple[str, str]]]:
133
152
  # An invalid interface.json skips the Field checks rather than calling every Test Input unknown.
134
153
  if test_inputs is not None and (interface is not None or not has_interface):
135
154
  test_input = _check_test_inputs(folder, interface or [], test_inputs, faults)
136
- 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
137
163
 
138
164
 
139
165
  def _read_publish_file(folder: Path) -> tuple[dict[str, Any], list[tuple[str, str]]]:
@@ -221,14 +247,17 @@ def _inside(folder: Path, path: str) -> bool:
221
247
  return bool(path) and folder.resolve() in (folder / path).resolve().parents
222
248
 
223
249
 
224
- def publish(abyss: Abyss, folder: Path, widget_folder: _Folder, force: bool = False) -> str:
250
+ def publish(
251
+ abyss: Abyss, folder: Path, widget_folder: _Folder, force: bool = False, use_env_file: bool = False
252
+ ) -> str:
225
253
  """Publishes a folder, and answers the Widget's link: a new Widget for a folder that was
226
254
  never published, a new version of the same Widget for one that was.
227
255
 
228
256
  A Draft's id goes into the Publish File as soon as it is made, and its Candidate's
229
257
  number once committed, so a publish that stops is taken up again on the same Draft.
230
258
  A published Widget is first compared with the folder, and a Widget that moved on
231
- 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.
232
261
  """
233
262
  publish_file = widget_folder.publish_file
234
263
  interface = widget_folder.interface
@@ -282,6 +311,8 @@ def publish(abyss: Abyss, folder: Path, widget_folder: _Folder, force: bool = Fa
282
311
  )
283
312
  block["candidate"] = candidate["version"]
284
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)
285
316
 
286
317
  print(f"Test Run of version {candidate['version']}...")
287
318
  run = _test_run(abyss, folder, widget, candidate["version"], widget_folder.test_input, interface)
@@ -514,6 +545,29 @@ def _folder_files(folder: Path, junk: dict[str, Any], thumbnail: str | None) ->
514
545
  return sent, left_out
515
546
 
516
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
+
517
571
  def _test_run(
518
572
  abyss: Abyss,
519
573
  folder: Path,
@@ -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
 
@@ -45,6 +46,9 @@ def test_command(recording: dict[str, Any], monkeypatch: pytest.MonkeyPatch, cap
45
46
  for path, content in before.items():
46
47
  if path not in outcome["written"]:
47
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"
48
52
  finally:
49
53
  server.close()
50
54
 
@@ -66,3 +70,30 @@ def test_publish_without_a_key_prints_every_fault_and_sends_nothing(
66
70
  assert "invalid_api_key" in printed.err
67
71
  finally:
68
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