feat: add Bash and Zsh completion with persistent shell setup

This commit is contained in:
Meghdad committed 2026-10-01 04:32:53 +03:30
1 parent 0f000a8912
commit f1217f8864
5 files changed
+188 -3

No files matched your search

+31 -1
View File
@@ -23,7 +23,36 @@ From the repository root:
python3 -m pip install . python3 -m pip install .
``` ```
This installs the `ravin` command and its browser automation dependency. The equivalent module entry point is `python3 -m ravin`. This installs the `ravin` command, browser automation, and shell completion support. The equivalent module entry point is `python3 -m ravin`.
### Shell tab completion
Install completion once for your shell:
```bash
ravin completion bash --install
```
For Zsh (the default shell on current macOS):
```zsh
ravin completion zsh --install
```
Open a new terminal afterward. The command saves a managed setup block in
`~/.bashrc` (`~/.bash_profile` on macOS) or `~/.zshrc` (honoring `ZDOTDIR`).
Running it again updates the block without duplicating it or replacing other
settings. It uses the Python environment where you ran the setup, so completion
also loads before you activate that environment. Rerun setup if you move or
replace the environment. Package installation itself does not edit shell settings.
To enable completion only in the current session, use
`eval "$(ravin completion bash)"`, or `eval "$(ravin completion zsh)"` in Zsh
with `compinit` initialized.
Press Tab to complete commands, options, choice values such as
`ravin transcribe --device`, and file paths. Completion uses the current command
definitions and does not log in or contact the LMS.
Whisper and PyTorch are large, platform-specific dependencies, so install them only on the machine that will transcribe media: Whisper and PyTorch are large, platform-specific dependencies, so install them only on the machine that will transcribe media:
@@ -468,6 +497,7 @@ When an older generated `library/courses.json` exists and `public/` has no manif
```text ```text
ravin login ravin login
ravin scan [COURSE_ID ...] [--offline] [--json] [--public PATH] ravin scan [COURSE_ID ...] [--offline] [--json] [--public PATH]
ravin completion [bash|zsh] [--install]
ravin download COURSE_ID [--overwrite] [--retries N] [--json] [--public PATH] ravin download COURSE_ID [--overwrite] [--retries N] [--json] [--public PATH]
ravin transcribe [COURSE_ID ...] [--model MODEL] [--device DEVICE] [--language LANGUAGE] ravin transcribe [COURSE_ID ...] [--model MODEL] [--device DEVICE] [--language LANGUAGE]
ravin summarize [COURSE_ID ...] [--model MODEL] [--retries N] [--timeout SECONDS] ravin summarize [COURSE_ID ...] [--model MODEL] [--retries N] [--timeout SECONDS]
+1 -1
View File
@@ -24,7 +24,7 @@ classifiers = [
"Programming Language :: Python :: 3.14", "Programming Language :: Python :: 3.14",
"Topic :: Education", "Topic :: Education",
] ]
dependencies = ["selenium>=4.46,<5"] dependencies = ["selenium>=4.46,<5", "argcomplete>=3.6,<4"]
[project.optional-dependencies] [project.optional-dependencies]
pdf = ["playwright>=1.50,<2", "markdown-it-py>=3,<5"] pdf = ["playwright>=1.50,<2", "markdown-it-py>=3,<5"]
+21 -1
View File
@@ -8,6 +8,8 @@ import os
import sys import sys
from pathlib import Path from pathlib import Path
import argcomplete
from .auth import ( from .auth import (
_authenticate_browser_session, _authenticate_browser_session,
_browser_session_values, _browser_session_values,
@@ -68,6 +70,10 @@ def build_parser() -> argparse.ArgumentParser:
parser.add_argument("--login-timeout", type=int, default=600, help="interactive login timeout") parser.add_argument("--login-timeout", type=int, default=600, help="interactive login timeout")
subparsers = parser.add_subparsers(dest="command", required=True) subparsers = parser.add_subparsers(dest="command", required=True)
completion_parser = subparsers.add_parser("completion", help="print shell tab-completion setup")
completion_parser.add_argument("shell", choices=("bash", "zsh"), nargs="?", default="bash")
completion_parser.add_argument("--install", action="store_true", help="save setup in your shell startup file")
subparsers.add_parser("login", help="open a browser and refresh the saved LMS session") subparsers.add_parser("login", help="open a browser and refresh the saved LMS session")
pdf_parser = subparsers.add_parser("pdf", help="create a course PDF from its local summaries") pdf_parser = subparsers.add_parser("pdf", help="create a course PDF from its local summaries")
@@ -302,7 +308,21 @@ def _authenticate(args: argparse.Namespace) -> tuple[MoodleClient, str]:
def main(argv: list[str] | None = None) -> int: def main(argv: list[str] | None = None) -> int:
args = build_parser().parse_args(argv) parser = build_parser()
argcomplete.autocomplete(parser)
args = parser.parse_args(argv)
if args.command == "completion":
if args.install:
from .completion import install_completion
try:
startup = install_completion(args.shell)
except (OSError, ValueError) as exc:
print(f"Could not install completion: {exc}", file=sys.stderr)
return 1
print(f"Installed {args.shell} completion in {startup}. Open a new shell to enable it.")
return 0
print(argcomplete.shellcode(["ravin"], shell=args.shell))
return 0
try: try:
if args.command == "pdf": if args.command == "pdf":
from .course_pdf import create_course_pdf from .course_pdf import create_course_pdf
+47
View File
@@ -0,0 +1,47 @@
"""Persistent, repeatable shell completion setup."""
from pathlib import Path
import os
import shlex
import sys
def install_completion(shell: str) -> Path:
if shell == "zsh":
startup = Path(os.environ.get("ZDOTDIR") or Path.home()) / ".zshrc"
else:
startup = Path.home() / (".bash_profile" if sys.platform == "darwin" else ".bashrc")
start = "# >>> ravin completion >>>"
end = "# <<< ravin completion <<<"
original = startup.read_text() if startup.exists() else ""
if start in original or end in original:
if original.count(start) != 1 or original.count(end) != 1:
raise ValueError(f"Invalid Ravin completion markers in {startup}")
first = original.index(start)
last = original.index(end)
if last < first:
raise ValueError(f"Invalid Ravin completion markers in {startup}")
before = original[:first]
after = original[last + len(end):].lstrip("\n")
else:
before = original + ("\n" if original and not original.endswith("\n") else "")
after = ""
python = shlex.quote(sys.executable)
initialize = (
" if ! (( $+functions[compdef] )); then\n"
" autoload -Uz compinit\n"
" compinit\n"
" fi\n"
) if shell == "zsh" else ""
block = (
f"{start}\n"
f"if [ -x {python} ]; then\n"
f"{initialize}"
f' eval "$({python} -m ravin completion {shell})"\n'
f"fi\n{end}\n"
)
updated = before + block + after
if updated != original:
startup.parent.mkdir(parents=True, exist_ok=True)
startup.write_text(updated)
return startup
+88
View File
@@ -0,0 +1,88 @@
"""Exercise shell completion through argcomplete's shell protocol."""
import contextlib
import io
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
from ravin.cli import main
class CompletionTests(unittest.TestCase):
def complete(self, line):
with tempfile.TemporaryDirectory() as directory:
output = Path(directory) / "completions"
env = dict(os.environ, COMP_LINE=line, COMP_POINT=str(len(line)),
_ARGCOMPLETE="1", _ARGCOMPLETE_IFS="\n",
_ARGCOMPLETE_STDOUT_FILENAME=str(output))
result = subprocess.run(
[sys.executable, "-c", "from ravin.cli import main; main()"],
env=env, capture_output=True, text=True, timeout=10,
)
self.assertEqual(result.returncode, 0, result.stderr)
return [candidate.rstrip(" ") for candidate in output.read_text().splitlines()]
def test_commands_and_aliases(self):
self.assertIn("scan", self.complete("ravin sc"))
self.assertIn("recordings", self.complete("ravin recording"))
def test_command_options_and_choices(self):
self.assertIn("--no-keep-awake", self.complete("ravin transcribe --no-k"))
self.assertIn("cuda", self.complete("ravin transcribe --device cu"))
self.assertNotIn("--device", self.complete("ravin serve --d"))
def test_file_paths(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "questions.md"
path.touch()
self.assertIn(str(path), self.complete(f"ravin questions 44 12 {directory}/qu"))
def test_setup_requires_no_authentication(self):
for shell in ("bash", "zsh"):
with self.subTest(shell=shell), patch("ravin.cli._authenticate") as authenticate:
output = io.StringIO()
with contextlib.redirect_stdout(output):
self.assertEqual(main(["completion", shell]), 0)
self.assertIn("ravin", output.getvalue())
authenticate.assert_not_called()
class PersistentCompletionTests(unittest.TestCase):
def test_install_preserves_settings_and_is_repeatable(self):
from ravin.completion import install_completion
for shell, filename in (("bash", ".bashrc"), ("zsh", ".zshrc")):
with self.subTest(shell=shell), tempfile.TemporaryDirectory() as directory:
home = Path(directory)
startup = home / filename
startup.write_text("# existing settings\nexport EXAMPLE=yes\n")
with patch("ravin.completion.Path.home", return_value=home), \
patch("ravin.completion.sys.platform", "linux"), \
patch.dict(os.environ, {"ZDOTDIR": ""}):
self.assertEqual(install_completion(shell), startup)
first = startup.read_text()
install_completion(shell)
self.assertEqual(startup.read_text(), first)
self.assertTrue(first.startswith("# existing settings\nexport EXAMPLE=yes\n"))
self.assertEqual(first.count("# >>> ravin completion >>>"), 1)
result = subprocess.run([shell, "-n", str(startup)], capture_output=True)
self.assertEqual(result.returncode, 0, result.stderr)
def test_zdotdir(self):
from ravin.completion import install_completion
with tempfile.TemporaryDirectory() as directory, patch.dict(os.environ, {"ZDOTDIR": directory}):
self.assertEqual(install_completion("zsh"), Path(directory) / ".zshrc")
def test_invalid_markers_preserve_file(self):
from ravin.completion import install_completion
with tempfile.TemporaryDirectory() as directory, patch.dict(os.environ, {"ZDOTDIR": directory}):
startup = Path(directory) / ".zshrc"
original = "# >>> ravin completion >>>\n# user settings\n"
startup.write_text(original)
with self.assertRaises(ValueError):
install_completion("zsh")
self.assertEqual(startup.read_text(), original)