VoiceStudio is the open-source, fully-local ElevenLabs alternative — voice cloning, voice design, video dubbing, dictation, transcription & audiobook creation in 646 languages.
Python aiaudiobookcudadubbingelevenlabs-alternativehuggingfacelocal-firstmlxomnivoice-studiospeech-to-texttext-to-speechtranscriptiontranslatettsvoice-aivoice-cloningvoice-generationvoicestudioworkflow
feat(release): arrow-key menus in the release helper
velixio886c5340a6ca
diff --git a/docs/RELEASING.md b/docs/RELEASING.mdindex b778a27d9..b180b3a5a 100644--- a/docs/RELEASING.md+++ b/docs/RELEASING.md@@ -176,7 +176,9 @@ branch. It shows the last release and the version on `main`, then asks **stableor beta** and suggests the new tag (`v0.5.7`, or `v0.5.7-beta.1`, `-beta.2`, ...for a beta; the beta suffix is always `-beta.N`). If `package.json` already namesthe upcoming release it uses that version; if that version is already tagged it-moves to the next patch. It then asks **draft or publish**, prints the plan+moves to the next patch. Choices are arrow-key menus (up/down or `j`/`k`,+Enter; Esc cancels) that fall back to typed answers when there is no terminal.+It then asks **draft or publish**, prints the plan(including switching to `main` and fast-forwarding it), and only proceeds when youtype the tag name.diff --git a/scripts/release.py b/scripts/release.pyindex 8cdd0fa18..70259982f 100644--- a/scripts/release.py+++ b/scripts/release.py@@ -17,6 +17,7 @@ from __future__ import annotationsimport argparseimport datetimeimport json+import osimport reimport subprocessimport sys@@ -119,6 +120,79 @@ def ask(question: str, choices: list[str], default: str | None = None) -> str:print(f" Please answer one of: {', '.join(choices)}")+def interactive() -> bool:+ return sys.stdin.isatty() and sys.stdout.isatty()+++def read_key() -> str:+ """One keypress as up/down/enter/esc or the character itself (stdlib only)."""+ if os.name == "nt":+ import msvcrt++ ch = msvcrt.getwch()+ if ch in ("\x00", "\xe0"):+ return {"H": "up", "P": "down"}.get(msvcrt.getwch(), "")+ return {"\r": "enter", "\x03": "interrupt", "\x1b": "esc"}.get(ch, ch)+ import select+ import termios+ import tty++ fd = sys.stdin.fileno()+ saved = termios.tcgetattr(fd)+ try:+ tty.setcbreak(fd) # keeps Ctrl-C working+ # Unbuffered: sys.stdin would swallow the rest of an arrow's escape sequence.+ ch = os.read(fd, 1).decode("latin-1")+ if ch == "\x1b":+ if not select.select([fd], [], [], 0.05)[0]:+ return "esc"+ seq = os.read(fd, 2).decode("latin-1")+ return {"[A": "up", "[B": "down", "OA": "up", "OB": "down"}.get(seq, "")+ return "enter" if ch in ("\r", "\n") else ch+ finally:+ termios.tcsetattr(fd, termios.TCSADRAIN, saved)+++def select_option(question: str, options: list[tuple[str, str]], default: int = 0) -> str:+ """Arrow-key menu (up/down or k/j, Enter). Typed prompt when not on a terminal."""+ values = [value for value, _ in options]+ if not interactive():+ return ask(question, values, values[default])+ if os.name == "nt":+ os.system("") # enable ANSI escapes in legacy Windows consoles+ index = default+ out = sys.stdout++ def draw(redraw: bool) -> None:+ if redraw:+ out.write(f"\x1b[{len(options)}A")+ for i, (value, label) in enumerate(options):+ line = f"{'>' if i == index else ' '} {value:<9} {label}"+ out.write("\x1b[2K" + (f"\x1b[1;36m{line}\x1b[0m" if i == index else line) + "\n")+ out.flush()++ out.write(f"{question} (up/down to move, Enter to select)\n\x1b[?25l")+ draw(False)+ try:+ while True:+ key = read_key()+ if key in ("up", "k"):+ index = (index - 1) % len(options)+ elif key in ("down", "j"):+ index = (index + 1) % len(options)+ elif key == "enter":+ break+ elif key in ("interrupt", "esc", "q"):+ raise KeyboardInterrupt+ draw(True)+ finally:+ out.write("\x1b[?25h")+ # Collapse the menu to the chosen answer.+ out.write(f"\x1b[{len(options) + 1}A\x1b[J{question} {values[index]}\n")+ out.flush()+ return values[index]++def check_ready(tag: str | None = None) -> None:"""Read-only checks for anything the helper cannot fix on its own."""problems = []@@ -166,7 +240,10 @@ def publish_existing(tag: str) -> None:raise SystemExit("gh is not authenticated (run: gh auth login)")unsigned = Falseif missing_signing_secrets():- unsigned = ask("Signing secrets missing or unreadable. Ship UNSIGNED installers?", ["y", "n"], "n") == "y"+ unsigned = select_option(+ "Signing secrets missing or unreadable. Ship UNSIGNED installers?",+ [("no", "cancel"), ("yes", "trust warnings, macOS updates unverified")],+ ) == "yes"print(f"\nPublish {tag} ({channel}) from its existing build{' (unsigned)' if unsigned else ''}.")if input(f"Type {tag} to confirm: ").strip() != tag:raise SystemExit("Cancelled.")@@ -184,7 +261,11 @@ def release(args: argparse.Namespace) -> None:check_ready()print(f"Last release: {last} package.json on main: {current}")- channel = ask("Release channel?", ["stable", "beta"])+ channel = select_option(+ "Release channel?",+ [("stable", "GitHub latest, :stable Docker, all stores"),+ ("beta", "opt-in prerelease, never latest, :beta Docker")],+ )suggestion = next_version(current, channel, tags)shape = "X.Y.Z-beta.N, e.g. 0.5.7-beta.1" if channel == "beta" else "X.Y.Z"print(f" New release: v{suggestion} (last release {last}; format {shape})")@@ -193,11 +274,18 @@ def release(args: argparse.Namespace) -> None:raise SystemExit(f"{version} is not a {channel} version ({shape})")tag = f"v{version}"check_ready(tag)- mode = ask("Draft (build only, publish later) or publish now?", ["draft", "publish"], "draft")+ mode = select_option(+ "Draft or publish?",+ [("draft", "build only, nothing public; publish later"),+ ("publish", "build and publish now")],+ )unsigned = Falseif mode == "publish" and missing_signing_secrets():print("Signing secrets are missing or unreadable (Mac/Windows signing).")- unsigned = ask("Ship UNSIGNED installers?", ["y", "n"], "n") == "y"+ unsigned = select_option(+ "Ship UNSIGNED installers?",+ [("no", "cancel; configure signing or choose draft"), ("yes", "trust warnings, macOS updates unverified")],+ ) == "yes"if not unsigned:raise SystemExit("Cancelled: configure signing, or choose draft.")diff --git a/tests/test_release_script.py b/tests/test_release_script.pyindex 441f769fe..9c72642c0 100644--- a/tests/test_release_script.py+++ b/tests/test_release_script.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport datetimeimport importlib.utilimport json+import sysfrom pathlib import Pathimport pytest@@ -180,8 +181,98 @@ def test_draft_pushes_the_tag_but_never_dispatches_a_publish(release, monkeypatcdef test_publish_without_signing_is_refused_unless_unsigned_is_accepted(release, monkeypatch):tag = "v0.5.7"with pytest.raises(SystemExit, match="configure signing"):- _drive(release, monkeypatch, ["stable", "", "publish", "n"], dry_run=False,+ _drive(release, monkeypatch, ["stable", "", "publish", "no"], dry_run=False,secrets_missing=["APPLE_ID"])- calls = _drive(release, monkeypatch, ["stable", "", "publish", "y", tag], dry_run=False,+ calls = _drive(release, monkeypatch, ["stable", "", "publish", "yes", tag], dry_run=False,secrets_missing=["APPLE_ID"])assert ("dispatch", tag, True) in calls+++def _menu(release, monkeypatch, keys, default=0):+ feed = iter(keys)+ monkeypatch.setattr(release, "interactive", lambda: True)+ monkeypatch.setattr(release, "read_key", lambda: next(feed))+ options = [("stable", "a"), ("beta", "b"), ("other", "c")]+ return release.select_option("Channel?", options, default)+++ ("keys", "expected"),+ [+ (["enter"], "stable"),+ (["down", "enter"], "beta"),+ (["down", "down", "enter"], "other"),+ (["down", "down", "down", "enter"], "stable"), # wraps around+ (["up", "enter"], "other"),+ (["j", "j", "k", "enter"], "beta"),+ (["x", "", "enter"], "stable"), # unknown keys are ignored+ ],+)+def test_select_moves_with_arrows_and_vim_keys(release, monkeypatch, keys, expected):+ assert _menu(release, monkeypatch, keys) == expected+++def test_select_collapses_to_the_chosen_answer(release, monkeypatch, capsys):+ _menu(release, monkeypatch, ["down", "enter"])+ out = capsys.readouterr().out+ assert out.endswith("Channel? beta\n") and "\x1b[?25h" in out++[email protected]("key", ["esc", "q", "interrupt"])+def test_select_cancels_on_escape_and_restores_the_cursor(release, monkeypatch, capsys, key):+ with pytest.raises(KeyboardInterrupt):+ _menu(release, monkeypatch, [key])+ assert "\x1b[?25h" in capsys.readouterr().out+++def test_select_falls_back_to_a_typed_answer_without_a_terminal(release, monkeypatch):+ monkeypatch.setattr(release, "interactive", lambda: False)+ monkeypatch.setattr("builtins.input", lambda prompt="": "beta")+ assert release.select_option("Channel?", [("stable", "a"), ("beta", "b")]) == "beta"++[email protected](sys.platform == "win32", reason="needs a POSIX pseudo-terminal")+def test_menu_reads_real_arrow_key_bytes_from_a_terminal():+ """Regression: buffered stdin swallowed the rest of an arrow's escape sequence,+ so every arrow press read as a lone Esc and cancelled the menu."""+ import os+ import pty+ import re+ import select+ import time++ driver = (+ "import importlib.util\n"+ "s = importlib.util.spec_from_file_location('r', 'scripts/release.py')\n"+ "m = importlib.util.module_from_spec(s); s.loader.exec_module(m)\n"+ "print('RESULT=' + m.select_option('Channel?', [('stable', 'x'), ('beta', 'y')]))\n"+ "print('RESULT=' + m.select_option('Mode?', [('draft', 'x'), ('publish', 'y')]))\n"+ )+ pid, fd = pty.fork()+ if pid == 0:+ os.chdir(ROOT)+ os.execvp(sys.executable, [sys.executable, "-c", driver])+ output = b""++ def pump(seconds: float) -> None:+ nonlocal output+ end = time.time() + seconds+ while time.time() < end:+ if select.select([fd], [], [], 0.05)[0]:+ try:+ output += os.read(fd, 4096)+ except OSError:+ return++ pump(1.0)+ os.write(fd, b"\x1b[B") # down+ pump(0.3)+ os.write(fd, b"\r")+ pump(0.5)+ os.write(fd, b"\x1b[B\x1b[A\x1b[B") # down, up, down+ pump(0.3)+ os.write(fd, b"\r")+ pump(0.8)+ os.waitpid(pid, 0)+ text = re.sub(r"\x1b\[[0-9;?]*[A-Za-z]", "", output.decode(errors="replace"))+ assert re.findall(r"RESULT=(\w+)", text) == ["beta", "publish"], text