mercury-cli-sdk 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,90 @@
1
+ from __future__ import annotations
2
+ import os
3
+ from pathlib import Path
4
+ import re
5
+ import sys
6
+ from .errors import MercuryError
7
+
8
+ MANAGED_SHIM_FAMILY = 'mercury-managed-shim'
9
+ HOMEBREW_COMMANDS = ('/opt/homebrew/bin/mercury', '/usr/local/bin/mercury', '/home/linuxbrew/.linuxbrew/bin/mercury')
10
+
11
+
12
+ def executable_of(executable: str | list[str] | None, env: dict[str, str] | None = None, cwd: str | None = None, platform: str | None = None) -> list[str]:
13
+ environment: dict[str, str] = dict(os.environ) if env is None else env
14
+ win = (sys.platform if platform is None else platform) == 'win32'
15
+ def variable(name: str) -> str | None:
16
+ if name in environment or not win: return environment.get(name)
17
+ return next((value for key, value in environment.items() if key.upper() == name), None)
18
+ parts = [variable('MERCURY_BIN') or 'mercury'] if executable is None else [executable] if isinstance(executable, str) else list(executable)
19
+ if not parts or not parts[0]: raise MercuryError('the mercury executable is empty')
20
+ command, *args = parts
21
+ base = Path(cwd or '.')
22
+ def absolute(path: Path) -> Path: return Path(os.path.abspath(path))
23
+ def runnable(path: Path) -> bool: return path.is_file() and (win or os.access(path, os.X_OK))
24
+ pathext = variable('PATHEXT')
25
+ extensions = [ext for ext in ('.COM;.EXE;.BAT;.CMD' if pathext is None else pathext).split(';') if ext] if win else ['']
26
+ def spellings(name: str) -> list[str]: return ([name] if re.search(r'\.[^\\/.]+$', name) else []) + [name + ext.lower() for ext in extensions] if win else [name]
27
+ def on_path(name: str) -> Path | None:
28
+ return next((candidate for entry in (variable('PATH') or '').split(';' if win else ':') if entry for candidate in (absolute(base / entry / spelling) for spelling in spellings(name)) if runnable(candidate)), None)
29
+ def is_shim(path: str) -> bool: return path.lower().endswith(('.cmd', '.bat', '.ps1'))
30
+ def is_script(path: str) -> bool: return path.lower().endswith(('.mjs', '.cjs', '.js'))
31
+ def head(path: Path) -> str:
32
+ try:
33
+ with open(path, 'rb') as handle: return handle.read(8192).decode('utf-8', errors='replace')
34
+ except OSError: return ''
35
+ def vendored_runtime(directory: Path) -> Path: return directory / 'vendor' / 'node' / ('node.exe' if win else 'bin/node')
36
+ def runtime_for(script: Path) -> str:
37
+ pinned = variable('MERCURY_NODE')
38
+ if pinned:
39
+ if runnable(Path(pinned)): return pinned
40
+ raise MercuryError(f'MERCURY_NODE names no executable file: {pinned}; point it at a Node binary, or unset it so {script} runs on the runtime vendored beside it or node from PATH')
41
+ vendored = vendored_runtime(script.parent)
42
+ if runnable(vendored): return str(vendored)
43
+ found = on_path('node')
44
+ return str(found) if found else 'node'
45
+ home = Path((variable('USERPROFILE') or variable('HOME') if win else variable('HOME')) or Path.home())
46
+ versions_dir = Path(variable('MERCURY_VERSIONS_DIR') or Path(variable('MERCURY_CONFIG_DIR') or variable('MERCURY_HOME') or home / '.mercury') / 'versions')
47
+ def managed() -> list[str] | None:
48
+ try: pointer = (versions_dir / 'current.txt').read_text(encoding='utf-8')
49
+ except OSError: return None
50
+ version = next((line.replace('"', '').rstrip() for line in pointer.splitlines() if line.strip()), None)
51
+ if not version or re.search(r'[\\/]|\.\.', version): return None
52
+ bundle = versions_dir / version / 'mercury.mjs'
53
+ return [runtime_for(bundle), str(bundle)] if bundle.is_file() else None
54
+ layout = f'{versions_dir / "current.txt"} must name a version directory under {versions_dir} that holds mercury.mjs'
55
+ def shim(path: Path) -> list[str]:
56
+ source = head(path)
57
+ if MANAGED_SHIM_FAMILY in source:
58
+ bundle = managed()
59
+ if bundle: return bundle
60
+ raise MercuryError(f"{path} is Mercury's managed command, but the install it points at was not found: {layout}; run `mercury install` from an extracted release, or pass [node, script]")
61
+ match = re.search(r'"(?:%dp0%|%~dp0)[\\/]([^"\r\n]+\.(?:mjs|cjs|js))"', source, re.IGNORECASE)
62
+ script = path.parent / match[1].replace('\\', '/') if match else path.parent / 'mercury.mjs'
63
+ if not script.is_file(): raise MercuryError(f"the executable is a command shim without a readable Node entry point: {path} is neither Mercury's managed command ({layout}) nor an npm shim, and no mercury.mjs sits beside it; pass [node, script]")
64
+ local_node = path.parent / 'node.exe'
65
+ if match: return [str(local_node) if local_node.is_file() else str(on_path('node') or 'node'), str(script)]
66
+ return [runtime_for(script), str(script)]
67
+ def wrapped(source: str) -> list[str] | None:
68
+ match = re.search(r'^exec "([^"\r\n]+)" "\$@"\s*$', source, re.MULTILINE)
69
+ if not match or not os.path.isabs(match[1]): return None
70
+ bundle = Path(match[1]).parent / 'mercury.mjs'
71
+ return [runtime_for(bundle), str(bundle)] if bundle.is_file() and runnable(vendored_runtime(bundle.parent)) else None
72
+ def file(path: str) -> list[str]:
73
+ placed = absolute(base / path)
74
+ if is_shim(path): return shim(placed)
75
+ if is_script(path):
76
+ if not placed.is_file(): raise MercuryError(f'the executable is a JavaScript entry point that does not exist: {placed}')
77
+ return [runtime_for(placed), str(placed)]
78
+ source = head(placed)
79
+ if MANAGED_SHIM_FAMILY in source: return shim(placed)
80
+ return wrapped(source) or [str(placed) if '/' in path or '\\' in path else path]
81
+ if command == 'mercury':
82
+ bundle = managed()
83
+ if bundle: return [*bundle, *args]
84
+ stable = Path(variable('LOCALAPPDATA') or home / 'AppData' / 'Local') / 'Mercury' / 'bin' / 'mercury.cmd' if win else home / '.local' / 'bin' / 'mercury'
85
+ prefix = variable('HOMEBREW_PREFIX')
86
+ brew = [] if win or not variable('PATH') else [*([Path(prefix, 'bin', 'mercury')] if prefix else []), *(Path(path) for path in HOMEBREW_COMMANDS)]
87
+ found = on_path(command) or next((candidate for candidate in (stable, home / '.mercury' / 'bin' / 'mercury', *brew) if runnable(candidate)), None)
88
+ return [*file(str(found)), *args] if found else [command, *args]
89
+ named = str(on_path(command) or command) if is_shim(command) and '/' not in command and '\\' not in command else command
90
+ return [*file(named), *args]
@@ -0,0 +1,26 @@
1
+ from __future__ import annotations
2
+ import asyncio
3
+ from typing import AsyncIterator
4
+ from .errors import MercuryWireError
5
+ from .generated import MAX_LINE_BYTES
6
+ from .parse import Issue
7
+
8
+
9
+ async def read_lines(stream: asyncio.StreamReader) -> AsyncIterator[str]:
10
+ buffer = bytearray()
11
+ while True:
12
+ chunk = await stream.read(65536)
13
+ if not chunk:
14
+ if buffer: yield buffer.decode('utf-8', errors='replace').lstrip('\ufeff')
15
+ return
16
+ start = 0
17
+ while start < len(chunk):
18
+ end = chunk.find(b'\n', start)
19
+ part = chunk[start:] if end < 0 else chunk[start:end]
20
+ buffer.extend(part)
21
+ if len(buffer) > MAX_LINE_BYTES:
22
+ raise MercuryWireError(buffer.decode('utf-8', errors='replace'), 'invalid', issues=[Issue('', f'line exceeds {MAX_LINE_BYTES} bytes')])
23
+ if end < 0: break
24
+ yield buffer.decode('utf-8', errors='replace').lstrip('\ufeff')
25
+ buffer.clear()
26
+ start = end + 1