diff options
| author | Christophe Besson <cbesson@gmail.com> | 2026-10-15 17:42:30 +0200 |
|---|---|---|
| committer | Christophe Besson <cbesson@gmail.com> | 2026-10-15 17:45:41 +0200 |
| commit | 41d03f0a35a95daa7d54e7f29ab924776bedf6e4 (patch) | |
| tree | 2e631013746f913413b9811562b9c9a4734a0e41 /packages/meshbay-cli/src | |
| parent | 39cac2878de059992cb09a1ccf09b6bcece99fae (diff) | |
| download | meshbay-41d03f0a35a95daa7d54e7f29ab924776bedf6e4.tar.gz | |
fix(cli): make the command-line client work on Windows
Its suite had only run on Linux. On Windows, against a real hub and node and
from the installed meshbay-cli.exe:
- secrets.enc was written in text mode (os.open without O_BINARY): every 0x0A
of the ciphertext became CR LF and the saved session "does not open with
its key" on the next run.
- isatty() is true for NUL, so a script run with `< NUL` or by the Task
Scheduler was asked questions instead of told to pass --yes;
output.terminal() checks for a real console.
- Ctrl+C waited for the selector loop's next timer, up to half a minute in
`chat --follow`; the loop now points the signal wakeup at its self-pipe,
as the proactor does.
- Right-click copy and paste raised: asyncio cannot start a process on the
selector loop; the clipboard tool runs in a thread.
- Tab completion of remote paths ran on the default (proactor) loop, which
never opens a node, and wrote in the locale encoding; the PowerShell script
now reads it as UTF-8.
- `get -R` into a folder past MAX_PATH died with a traceback; get, put, the
resume file and the interactive mode use the extended form at each disk
call, as the node does.
- `groups` showed a SQLite hub's naive UTC time as local time.
The opt-in end-to-end suite now runs on Windows (16 tests: Chrome found under
Program Files and started with the real environment, VLC as the player, Ctrl+C
through a console of its own, PowerShell 5.1 completion of an accented name).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'packages/meshbay-cli/src')
19 files changed, 165 insertions, 64 deletions
diff --git a/packages/meshbay-cli/src/meshbay_cli/__main__.py b/packages/meshbay-cli/src/meshbay_cli/__main__.py index f5cee22..597e2fe 100644 --- a/packages/meshbay-cli/src/meshbay_cli/__main__.py +++ b/packages/meshbay-cli/src/meshbay_cli/__main__.py @@ -8,7 +8,9 @@ import argparse import asyncio import logging import os +import signal import sys +import threading from . import __version__ from .commands import ( @@ -113,15 +115,35 @@ async def _run(args: argparse.Namespace) -> int: await ctx.aclose() +class _WindowsSelectorLoop(asyncio.SelectorEventLoop): + """ + A selector loop that Ctrl+C wakes. Windows' select() is not interrupted by + a console event, and unlike the proactor (`windows_events.ProactorEventLoop. + run_forever`) this loop never points the signal wakeup at its self-pipe: Ctrl+C + waited for the next timer, which in `chat --follow` or `stream` can be half + a minute away (measured: 29 s on a loop whose next timer was 30 s off). + """ + + def run_forever(self): + if threading.current_thread() is not threading.main_thread(): + return super().run_forever() # signals reach the main thread only + old = signal.set_wakeup_fd(self._csock.fileno()) + try: + super().run_forever() + finally: + signal.set_wakeup_fd(old) + + def loop_factory(): """aiortc's ICE needs a selector loop: Windows' default proactor never completes a DataChannel handshake.""" - return asyncio.SelectorEventLoop if sys.platform == "win32" else None + return _WindowsSelectorLoop if sys.platform == "win32" else None def main(argv: list[str] | None = None) -> int: argv = sys.argv[1:] if argv is None else argv if argv[:1] == ["__complete"]: + _utf8_output() # what the completion scripts read from .complete import main as complete return complete(argv[1:]) if not argv and os.environ.get("MESHBAY_CLI_SELFTEST") == "1": diff --git a/packages/meshbay-cli/src/meshbay_cli/client/store.py b/packages/meshbay-cli/src/meshbay_cli/client/store.py index c48fe89..00ff9f3 100644 --- a/packages/meshbay-cli/src/meshbay_cli/client/store.py +++ b/packages/meshbay-cli/src/meshbay_cli/client/store.py @@ -63,7 +63,10 @@ def data_dir() -> Path: def _write_private(path: Path, data: bytes) -> None: """Atomically, readable by this user only.""" tmp = path.with_name(path.name + ".tmp") - fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + # O_BINARY: without it Windows opens in text mode and writes every 0x0A of + # the ciphertext as CR LF, and the secrets no longer open. + flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, "O_BINARY", 0) + fd = os.open(tmp, flags, 0o600) try: os.write(fd, data) os.fsync(fd) diff --git a/packages/meshbay-cli/src/meshbay_cli/client/transfers.py b/packages/meshbay-cli/src/meshbay_cli/client/transfers.py index 2cbf4cd..177c78b 100644 --- a/packages/meshbay-cli/src/meshbay_cli/client/transfers.py +++ b/packages/meshbay-cli/src/meshbay_cli/client/transfers.py @@ -128,7 +128,8 @@ class Resume: sidecar = target.with_name(target.name + PART_SUFFIX + ".json") done = 0 try: - meta = json.loads(sidecar.read_text(encoding="utf-8")) + with open(long_path(sidecar), encoding="utf-8") as f: + meta = json.load(f) if meta.get("id") == entry["id"] and meta.get("size") == entry["size"]: # Every chunk but the last is whole, so the complete ones are # what the part's length says. @@ -198,8 +199,8 @@ def _prepare_part(resume: Resume, entry: dict, start: int) -> None: pass else: os.truncate(part, start * DOWNLOAD_CHUNK) - resume.sidecar.write_text(json.dumps({"id": entry["id"], "size": entry["size"]}), - encoding="utf-8") + with open(long_path(resume.sidecar), "w", encoding="utf-8") as f: + json.dump({"id": entry["id"], "size": entry["size"]}, f) def _publish(resume: Resume, target: Path, overwrite: bool) -> None: @@ -220,7 +221,7 @@ def _publish(resume: Resume, target: Path, overwrite: bool) -> None: raise TransferError(f"{target} already exists.") from None os.replace(part, dest) with contextlib.suppress(OSError): - resume.sidecar.unlink() + os.unlink(long_path(resume.sidecar)) if sys.platform == "win32": mark_of_the_web(target) diff --git a/packages/meshbay-cli/src/meshbay_cli/client/upload_plan.py b/packages/meshbay-cli/src/meshbay_cli/client/upload_plan.py index 070e686..b4ec781 100644 --- a/packages/meshbay-cli/src/meshbay_cli/client/upload_plan.py +++ b/packages/meshbay-cli/src/meshbay_cli/client/upload_plan.py @@ -12,7 +12,7 @@ import stat from dataclasses import dataclass from pathlib import Path -from meshbay_common.paths import fold +from meshbay_common.paths import fold, long_path from ..errors import USAGE, CliError from ..output import safe @@ -36,7 +36,7 @@ def plan_upload(sources: list[str], recursive: bool): for src in sources: path = Path(src).expanduser() try: - st = path.stat() + st = os.stat(long_path(path)) except OSError as e: problems.append(f"{src}: {e.strerror}") continue @@ -51,18 +51,18 @@ def plan_upload(sources: list[str], recursive: bool): elif stat.S_ISDIR(st.st_mode): if not recursive: raise CliError(USAGE, f"{safe(src)} is a folder; use -R.") - for here, subdirs, names in os.walk(path): + for here, subdirs, names in _walk(path): rel = [top] + list(Path(here).relative_to(path).parts) dirs.append(rel) for d in list(subdirs): - if (Path(here) / d).is_symlink(): + if os.path.islink(long_path(Path(here) / d)): subdirs.remove(d) problems.append(f"{Path(here) / d} is a link to a folder; not " "followed") for n in names: p = Path(here) / n try: - st_n = p.stat() + st_n = os.stat(long_path(p)) except OSError as e: problems.append(f"{p}: {e.strerror}") continue @@ -74,6 +74,29 @@ def plan_upload(sources: list[str], recursive: bool): return dirs, files, problems +def _walk(top: Path): + """`os.walk` for a tree that may go past Windows' MAX_PATH: each folder is + listed under its long form (`long_path`, which only prefixes a long path, so + a short top alone would not do) and the paths given back stay plain.""" + stack = [top] + while stack: + here = stack.pop() + try: + with os.scandir(long_path(here)) as it: + entries = list(it) + except OSError: + continue + subdirs, names = [], [] + for e in entries: + try: + is_dir = e.is_dir() + except OSError: + is_dir = False + (subdirs if is_dir else names).append(e.name) + yield here, subdirs, names # the caller prunes and orders subdirs + stack.extend(here / d for d in reversed(subdirs)) + + def taken_names(tree: Tree, folder: str, names: list[str]) -> set[str]: """The names among `names` already in `folder`, compared without case.""" there = [i.name for i in tree.children(folder, include_unavailable=True)] diff --git a/packages/meshbay-cli/src/meshbay_cli/commands/account.py b/packages/meshbay-cli/src/meshbay_cli/commands/account.py index 4499f0b..1fbef13 100644 --- a/packages/meshbay-cli/src/meshbay_cli/commands/account.py +++ b/packages/meshbay-cli/src/meshbay_cli/commands/account.py @@ -35,7 +35,7 @@ from ..client.passphrase import passphrase_problem, solve_captcha from ..client.rewrap import Carried, carry from ..client.store import FILE_KEY_NOTICE, KEY_FILE from ..errors import AUTH, NOT_FOUND, REFUSED, USAGE, CliError -from ..output import confirm, err, safe, sentence +from ..output import confirm, err, safe, sentence, terminal from .context import Context HELP = ("your account: show it, register, verify, change or reset the passphrase, " @@ -102,7 +102,7 @@ async def run(ctx: Context) -> int: def _ask(prompt: str, given: str | None, what: str) -> str: if given: return given.strip() - if not sys.stdin.isatty(): + if not terminal(sys.stdin): raise CliError(USAGE, f"Name the {what}: there is no terminal to ask on.") value = input(prompt).strip() if not value: @@ -121,7 +121,7 @@ def _read_first_line(path: str) -> str: def _new_passphrase(given: str | None) -> str: """A new passphrase: `given`, else typed twice at a terminal; held to the floor.""" if given is None: - if not sys.stdin.isatty(): + if not terminal(sys.stdin): raise NoPassphrase("A new passphrase is needed and there is no terminal to " "ask on.") given = getpass.getpass("New passphrase: ") @@ -224,7 +224,7 @@ async def _register(ctx: Context) -> int: "Keep it somewhere safe, apart from your passphrase. If you forget the " "passphrase, it is what gives you your groups back.") del raw - if not sys.stdin.isatty() or ctx.args.json: + if not terminal(sys.stdin) or ctx.args.json: err(f"A code was sent to {safe(email)}. Then: meshbay-cli account verify CODE " f"--email {safe(email)}") return 0 @@ -355,7 +355,7 @@ async def _reset(ctx: Context) -> int: raise _hub_refusal(e, "No code sent") from e err(f"If {safe(username)} and {safe(email)} are an account's, a code is on its " "way there (valid one hour).") - if not sys.stdin.isatty(): + if not terminal(sys.stdin): err(f"Then: meshbay-cli account reset -u {safe(username)} --code CODE") return 0 code = _ask("The code: ", None, "code") @@ -365,7 +365,7 @@ async def _reset(ctx: Context) -> int: text = (sys.stdin.read() if a.recovery_key_file == "-" else Path(a.recovery_key_file).read_text(encoding="utf-8")) recovery = text.strip() - elif sys.stdin.isatty(): + elif terminal(sys.stdin): recovery = input("Your recovery key (Enter if you have none): ").strip() rkey = None if recovery: @@ -429,7 +429,7 @@ async def _email(ctx: Context, account: Account) -> int: await account.call(account.hub.change_email, address, ak) except HubError as e: raise _hub_refusal(e, "Not changed") from e - if ctx.args.json or not sys.stdin.isatty(): + if ctx.args.json or not terminal(sys.stdin): _say(ctx, {"email_verification_required": True, "email": address}, f"A code was sent to {safe(address)}. Then: meshbay-cli account email " "--code CODE") diff --git a/packages/meshbay-cli/src/meshbay_cli/commands/chat.py b/packages/meshbay-cli/src/meshbay_cli/commands/chat.py index e410a6a..557592e 100644 --- a/packages/meshbay-cli/src/meshbay_cli/commands/chat.py +++ b/packages/meshbay-cli/src/meshbay_cli/commands/chat.py @@ -28,7 +28,7 @@ from ..client.groups import my_groups, open_group from ..client.paths import group_arg, handle, resolve_group from ..client.roster import RosterCheck from ..errors import NODE, USAGE, CliError -from ..output import date, err, human_size, safe, sentence +from ..output import date, err, human_size, safe, sentence, terminal from .context import Context HELP = ("chat: alone, interactively; with a group, its last 10 messages (-N for N), " @@ -90,7 +90,7 @@ async def run(ctx: Context) -> int: if a.group is None: if a.message is not None or a.follow: raise CliError(USAGE, "Name the group to post to.") - if not (sys.stdin.isatty() and sys.stdout.isatty()): + if not (terminal(sys.stdin) and terminal(sys.stdout)): raise CliError(USAGE, "The interactive chat needs a terminal; name a group " "to read it, or to post with -m.") from ..tui.app import run_interactive diff --git a/packages/meshbay-cli/src/meshbay_cli/commands/completion.py b/packages/meshbay-cli/src/meshbay_cli/commands/completion.py index 831c012..0fc3f30 100644 --- a/packages/meshbay-cli/src/meshbay_cli/commands/completion.py +++ b/packages/meshbay-cli/src/meshbay_cli/commands/completion.py @@ -51,7 +51,15 @@ Register-ArgumentCompleter -Native -CommandName 'meshbay-cli', 'meshbay-cli.exe' $index = $i } } - $found = @(& meshbay-cli __complete powershell $index @words 2>$null) + # The client writes UTF-8; Windows PowerShell reads a program's output in the + # console's code page, which turns an accented name into another name. + $encoding = [Console]::OutputEncoding + try { [Console]::OutputEncoding = [Text.Encoding]::UTF8 } catch { } + try { + $found = @(& meshbay-cli __complete powershell $index @words 2>$null) + } finally { + try { [Console]::OutputEncoding = $encoding } catch { } + } $quote = { param($s) if ($s -match '[\s''"`$&|;(){}@,#]') { "'" + ($s -replace "'", "''") + "'" } else { $s } diff --git a/packages/meshbay-cli/src/meshbay_cli/commands/context.py b/packages/meshbay-cli/src/meshbay_cli/commands/context.py index 827c101..0f7e842 100644 --- a/packages/meshbay-cli/src/meshbay_cli/commands/context.py +++ b/packages/meshbay-cli/src/meshbay_cli/commands/context.py @@ -12,7 +12,7 @@ from ..client.hub import DEFAULT_HUB, Hub from ..client.paths import handle from ..client.store import Store from ..errors import USAGE, CliError -from ..output import safe +from ..output import safe, terminal class Context: @@ -45,7 +45,7 @@ class Context: if value is None: value = os.environ.get("MESHBAY_PASSWORD") if value is None: - if not sys.stdin.isatty(): + if not terminal(sys.stdin): raise NoPassphrase("A passphrase is needed and there is no terminal to ask " "on; pass --password-file or set MESHBAY_PASSWORD.") value = getpass.getpass(f"Passphrase for {self.username or self.stored_username}" @@ -62,7 +62,7 @@ class Context: def _device_code(self, group: dict, pending, *, first: bool) -> bool: """Show the code once. Wait only where somebody is there to approve it.""" - waiting = sys.stderr.isatty() and not self.args.quiet + waiting = terminal(sys.stderr) and not self.args.quiet if first: minutes = max(1, int((pending.expires_at - time.time()) // 60)) print(f"This machine is not yet a device of yours on the node hosting " diff --git a/packages/meshbay-cli/src/meshbay_cli/commands/get.py b/packages/meshbay-cli/src/meshbay_cli/commands/get.py index eec73c4..33a9637 100644 --- a/packages/meshbay-cli/src/meshbay_cli/commands/get.py +++ b/packages/meshbay-cli/src/meshbay_cli/commands/get.py @@ -12,7 +12,7 @@ import os from dataclasses import dataclass from pathlib import Path -from meshbay_common.paths import fold +from meshbay_common.paths import fold, long_path from ..client.groups import my_groups from ..client.names import UnsafeName, local_path @@ -147,7 +147,8 @@ async def _run(ctx: Context, account, pool: Pool) -> int: planned.add(key) if changed: renamed.append((shown, target)) - if target.exists() and not target.with_name(target.name + PART_SUFFIX).exists(): + if os.path.exists(long_path(target)) and not os.path.exists( + long_path(target.with_name(target.name + PART_SUFFIX))): if a.skip: return if not a.force: @@ -181,7 +182,7 @@ async def _run(ctx: Context, account, pool: Pool) -> int: for problem in problems: progress.note(f"meshbay-cli: {safe(problem)}") for d in dirs: - d.mkdir(parents=True, exist_ok=True) + os.makedirs(long_path(d), exist_ok=True) progress.plan(len(jobs), sum(int(j.entry["size"]) for j in jobs)) failed = len(problems) @@ -224,12 +225,12 @@ def _destination(dest: str | None, single_file: bool) -> tuple[Path, str | None] return Path.cwd(), None path = Path(dest).expanduser() if dest.endswith(("/", os.sep)): - path.mkdir(parents=True, exist_ok=True) + os.makedirs(long_path(path), exist_ok=True) return path, None - if path.is_dir(): + if os.path.isdir(long_path(path)): return path, None if single_file: - if not path.parent.is_dir(): + if not os.path.isdir(long_path(path.parent)): raise CliError(USAGE, f"{path.parent} is not a folder.") return path.parent, path.name raise CliError(USAGE, f"{dest} is not a folder (end it with / to create it).") diff --git a/packages/meshbay-cli/src/meshbay_cli/commands/groups.py b/packages/meshbay-cli/src/meshbay_cli/commands/groups.py index 04395dd..5ee1356 100644 --- a/packages/meshbay-cli/src/meshbay_cli/commands/groups.py +++ b/packages/meshbay-cli/src/meshbay_cli/commands/groups.py @@ -10,7 +10,7 @@ operator is another notion. import contextlib import json import sys -from datetime import datetime +from datetime import UTC, datetime from ..client.groups import my_groups from ..client.hub import HubError @@ -38,9 +38,12 @@ def local_time(iso: str | None) -> str: if not iso: return "" try: - return datetime.fromisoformat(iso).astimezone().strftime("%Y-%m-%d %H:%M") + moment = datetime.fromisoformat(iso) except ValueError: return "" + if moment.tzinfo is None: # a hub on SQLite sends UTC without saying so + moment = moment.replace(tzinfo=UTC) + return moment.astimezone().strftime("%Y-%m-%d %H:%M") async def run(ctx: Context) -> int: diff --git a/packages/meshbay-cli/src/meshbay_cli/commands/join.py b/packages/meshbay-cli/src/meshbay_cli/commands/join.py index ee75c96..06494dd 100644 --- a/packages/meshbay-cli/src/meshbay_cli/commands/join.py +++ b/packages/meshbay-cli/src/meshbay_cli/commands/join.py @@ -18,7 +18,7 @@ from ..client.invite import parse_link from ..client.paths import group_arg, handle, resolve_group from ..client.session import DeviceLinkPending, NodeRefusal from ..errors import AUTH, NODE, NOT_FOUND, USAGE, CliError -from ..output import err, safe, sentence +from ..output import err, safe, sentence, terminal from .context import Context from .invitations import find_invitation @@ -102,7 +102,7 @@ async def run(ctx: Context) -> int: except NodeRefusal as e: if e.refusal_code != "code_required" or code: raise - if not sys.stdin.isatty(): + if not terminal(sys.stdin): raise CliError(NODE, f"You are a member of {safe(name)}; its node has not " "admitted you yet and needs your invitation's code:\n" f" meshbay-cli join {name} --code CODE") from e diff --git a/packages/meshbay-cli/src/meshbay_cli/commands/login.py b/packages/meshbay-cli/src/meshbay_cli/commands/login.py index cbd16ef..f26691c 100644 --- a/packages/meshbay-cli/src/meshbay_cli/commands/login.py +++ b/packages/meshbay-cli/src/meshbay_cli/commands/login.py @@ -8,7 +8,7 @@ from ..client.account import Account from ..client.groups import my_groups from ..client.store import FILE_KEY_NOTICE, KEY_FILE from ..errors import USAGE, CliError -from ..output import err, safe, sentence +from ..output import err, safe, sentence, terminal from .context import Context from .logout import sign_out_stored @@ -24,7 +24,7 @@ def add_parser(sub, parent) -> None: async def run(ctx: Context) -> int: username = ctx.username or ctx.stored_username if not username: - if not sys.stdin.isatty(): + if not terminal(sys.stdin): raise CliError(USAGE, "Name the account with --user.") username = input("Username: ").strip() ctx.username = username diff --git a/packages/meshbay-cli/src/meshbay_cli/commands/put.py b/packages/meshbay-cli/src/meshbay_cli/commands/put.py index 01a7233..cf80e02 100644 --- a/packages/meshbay-cli/src/meshbay_cli/commands/put.py +++ b/packages/meshbay-cli/src/meshbay_cli/commands/put.py @@ -18,6 +18,8 @@ import tempfile import threading from pathlib import Path +from meshbay_common.paths import long_path + from ..client.groups import my_groups from ..client.paths import handle, parse, resolve_group from ..client.pool import Pool @@ -156,7 +158,7 @@ async def _send(ctx: Context, session, group: dict, folder: str, dirs: list[list progress.start(safe(name)) lock = threading.Lock() try: - with open(job.local, "rb") as fh: + with open(long_path(job.local), "rb") as fh: def read(offset: int, length: int) -> bytes: with lock: fh.seek(offset) diff --git a/packages/meshbay-cli/src/meshbay_cli/complete.py b/packages/meshbay-cli/src/meshbay_cli/complete.py index ac590ce..249d5b7 100644 --- a/packages/meshbay-cli/src/meshbay_cli/complete.py +++ b/packages/meshbay-cli/src/meshbay_cli/complete.py @@ -300,7 +300,9 @@ def candidates(shell: str, cword: int, words: list[str]) -> list[str]: return [c[:-1] for c in found if c.count("/") == 1] return found try: - found = asyncio.run(asyncio.wait_for(go(), DEADLINE)) + # The client's loop: on Windows the default one never opens a node. + from .__main__ import loop_factory + found = asyncio.run(asyncio.wait_for(go(), DEADLINE), loop_factory=loop_factory()) except Exception: found = [] return ([FILES] if kind[0] == "files+remote" else []) + found diff --git a/packages/meshbay-cli/src/meshbay_cli/output.py b/packages/meshbay-cli/src/meshbay_cli/output.py index d4c0758..1d46981 100644 --- a/packages/meshbay-cli/src/meshbay_cli/output.py +++ b/packages/meshbay-cli/src/meshbay_cli/output.py @@ -54,8 +54,36 @@ def columns(names: list[str]) -> str: return "\n".join(lines) +def terminal(stream) -> bool: + """ + Whether `stream` is a terminal a person sits at. `isatty()` alone is wrong on + Windows, where it means "a character device" and so says yes for NUL: a + script run with `< NUL`, or by the Task Scheduler, was asked questions it + could not answer instead of being told to pass --yes. + """ + try: + if not stream.isatty(): + return False + except (AttributeError, ValueError): + return False + if sys.platform != "win32": + return True + try: + fd = stream.fileno() + except (OSError, ValueError): + return True # not a file at all: take its word + import ctypes + import msvcrt + try: + handle = msvcrt.get_osfhandle(fd) + except OSError: + return False + mode = ctypes.c_uint32() + return bool(ctypes.windll.kernel32.GetConsoleMode(handle, ctypes.byref(mode))) + + def is_tty() -> bool: - return sys.stdout.isatty() + return terminal(sys.stdout) def err(message: str) -> None: @@ -71,7 +99,7 @@ class Progress: def __init__(self, arrow: str, *, quiet: bool = False, as_json: bool = False): self.arrow = arrow - self.live = sys.stderr.isatty() and not quiet and not as_json + self.live = terminal(sys.stderr) and not quiet and not as_json self.as_json = as_json and not quiet self.files_total = 0 self.files_done = 0 @@ -149,7 +177,7 @@ def confirm(question: str, yes: bool) -> None: from .errors import USAGE, CliError if yes: return - if not sys.stdin.isatty(): + if not terminal(sys.stdin): raise CliError(USAGE, f"{question} Not done: there is no terminal to ask on; " "pass --yes to confirm.") # On stderr, like every other word to the person: stdout is the result. diff --git a/packages/meshbay-cli/src/meshbay_cli/tui/chat.py b/packages/meshbay-cli/src/meshbay_cli/tui/chat.py index e4ea1fe..989ffe2 100644 --- a/packages/meshbay-cli/src/meshbay_cli/tui/chat.py +++ b/packages/meshbay-cli/src/meshbay_cli/tui/chat.py @@ -21,6 +21,7 @@ import os import time from pathlib import Path +from meshbay_common.paths import long_path from rich.segment import Segment from rich.text import Text from textual import events @@ -412,9 +413,10 @@ class ChatRoomScreen(Screen): async def _put(self, arg: str) -> None: path = Path(os.path.abspath(os.path.expanduser(arg))) - if not path.is_file(): + if not os.path.isfile(long_path(path)): self.note(f"! {safe(arg)}: " + ("a folder; /put sends one file." - if path.is_dir() else "no such file."), style="bold red") + if os.path.isdir(long_path(path)) else "no such file."), + style="bold red") return name = path.name if problems := refused_names([name], []): @@ -430,9 +432,9 @@ class ChatRoomScreen(Screen): if found is None: return _, folder = found - size = path.stat().st_size + size = os.stat(long_path(path)).st_size advance, queued = self._progress("↑", name, size) - with open(path, "rb") as fh: + with open(long_path(path), "rb") as fh: def read(offset: int, length: int) -> bytes: fh.seek(offset) return fh.read(length) @@ -475,7 +477,8 @@ class ChatRoomScreen(Screen): style="bold red") return target = Path.cwd() / name.rsplit("/", 1)[-1] - if target.exists() and not target.with_name(target.name + PART_SUFFIX).exists(): + if os.path.exists(long_path(target)) and not os.path.exists( + long_path(target.with_name(target.name + PART_SUFFIX))): self.note(f"! {safe(str(target))} is here already; nothing was downloaded.", style="bold red") return diff --git a/packages/meshbay-cli/src/meshbay_cli/tui/clipboard.py b/packages/meshbay-cli/src/meshbay_cli/tui/clipboard.py index 1a1f0d7..e0bd315 100644 --- a/packages/meshbay-cli/src/meshbay_cli/tui/clipboard.py +++ b/packages/meshbay-cli/src/meshbay_cli/tui/clipboard.py @@ -12,6 +12,7 @@ skipped, never an error. import asyncio import os import shutil +import subprocess import sys TIMEOUT = 3.0 @@ -40,24 +41,25 @@ def _encode(text: str) -> bytes: return ("" + text).encode("utf-16-le") if sys.platform == "win32" else text.encode() -async def _run(cmd: list[str], data: bytes | None) -> bytes | None: +def _run_blocking(cmd: list[str], data: bytes | None) -> bytes | None: if shutil.which(cmd[0]) is None: return None env = {**os.environ, "LC_CTYPE": "UTF-8"} if sys.platform == "darwin" else None try: - proc = await asyncio.create_subprocess_exec( - *cmd, stdin=asyncio.subprocess.PIPE if data is not None else asyncio.subprocess.DEVNULL, - stdout=asyncio.subprocess.PIPE if data is None else asyncio.subprocess.DEVNULL, - stderr=asyncio.subprocess.DEVNULL, env=env) - except OSError: - return None - try: - out, _ = await asyncio.wait_for(proc.communicate(data), TIMEOUT) - except TimeoutError: - proc.kill() - await proc.wait() + proc = subprocess.run( + cmd, input=data, stdin=None if data is not None else subprocess.DEVNULL, + stdout=subprocess.PIPE if data is None else subprocess.DEVNULL, + stderr=subprocess.DEVNULL, env=env, timeout=TIMEOUT, + creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0)) + except (OSError, subprocess.TimeoutExpired): return None - return (out or b"") if proc.returncode == 0 else None + return (proc.stdout or b"") if proc.returncode == 0 else None + + +async def _run(cmd: list[str], data: bytes | None) -> bytes | None: + # In a thread, not asyncio's subprocesses: on Windows the client runs a + # selector loop (aiortc's ICE needs one), which cannot start a process. + return await asyncio.to_thread(_run_blocking, cmd, data) async def read_text() -> str | None: diff --git a/packages/meshbay-cli/src/meshbay_cli/tui/panes.py b/packages/meshbay-cli/src/meshbay_cli/tui/panes.py index d1e3dd0..417e0c6 100644 --- a/packages/meshbay-cli/src/meshbay_cli/tui/panes.py +++ b/packages/meshbay-cli/src/meshbay_cli/tui/panes.py @@ -13,6 +13,7 @@ import stat from dataclasses import dataclass, field from pathlib import Path +from meshbay_common.paths import long_path from rich.text import Text from textual.app import ComposeResult from textual.binding import Binding @@ -274,7 +275,7 @@ class LocalPane(Pane): def _scan(path: Path) -> list[Row]: rows = [] - with os.scandir(path) as it: + with os.scandir(long_path(path)) as it: for e in it: try: st = e.stat() diff --git a/packages/meshbay-cli/src/meshbay_cli/tui/screens.py b/packages/meshbay-cli/src/meshbay_cli/tui/screens.py index 0306325..39b5df3 100644 --- a/packages/meshbay-cli/src/meshbay_cli/tui/screens.py +++ b/packages/meshbay-cli/src/meshbay_cli/tui/screens.py @@ -14,9 +14,11 @@ the node's operator) or none is, then asked once for the batch. import asyncio import contextlib +import os import threading from pathlib import Path +from meshbay_common.paths import long_path from rich.text import Text from textual.app import ComposeResult from textual.binding import Binding @@ -214,8 +216,8 @@ class MainScreen(Screen): problems.append(str(e)) for p in problems: self.app.notify(p, severity="warning", markup=False) - existing = [t for _, t in plan if t.exists() - and not t.with_name(t.name + PART_SUFFIX).exists()] + existing = [t for _, t in plan if os.path.exists(long_path(t)) + and not os.path.exists(long_path(t.with_name(t.name + PART_SUFFIX)))] overwrite = False if existing: names = ", ".join(safe(t.name) for t in existing[:5]) + ( @@ -229,7 +231,7 @@ class MainScreen(Screen): if not overwrite: plan = [(e, t) for e, t in plan if t not in existing] for d in dirs: - await asyncio.to_thread(d.mkdir, parents=True, exist_ok=True) + await asyncio.to_thread(os.makedirs, long_path(d), exist_ok=True) remote.marks.clear() remote.redraw() session = await self.pool.session(group) @@ -320,7 +322,7 @@ class MainScreen(Screen): self.strip.update_job(job, state="running") lock = threading.Lock() try: - with open(item.local, "rb") as fh: + with open(long_path(item.local), "rb") as fh: def read(offset: int, length: int) -> bytes: with lock: fh.seek(offset) |