saturnin._scripts.repl

Read-Eval-Print Loop (REPL) implementation for Typer applications.

This module provides the core functionality for an interactive command-line interface, leveraging prompt-toolkit for advanced features like command history, auto-suggestion, and custom key bindings. It includes a custom completer (CustomClickCompleter) that integrates with Click/Typer’s command structure to offer context-aware command and parameter completion. The IOManager class handles input/output redirection and console management within the REPL environment.

Globals

saturnin._scripts.repl.kb

Prompt-toolkit key bindings instance.

Classes

class saturnin._scripts.repl.CustomClickCompleter(cli)[source]

Bases: Completer

Custom prompt-toolkit completer for Click/Typer applications.

This completer integrates with the Click command structure to provide context-aware completions for commands, subcommands, options, and argument values. It adapts Click’s internal shell completion logic for use with prompt-toolkit.

Parameters:

cli – The root Click/Typer command group object.

get_completions(document, complete_event=None)[source]

Yields completion suggestions based on the current input document.

This method parses the current command line input, resolves the Click context, and generates a list of relevant completions. Completions can include:

  • Subcommands of the current command group.

  • Options available for the current command.

  • Values for options (e.g., choices from click.Choice).

  • Values for arguments (e.g., choices or shell-completed values).

  • Special commands like ‘quit’.

It handles partial input by filtering suggestions that start with the incomplete word at the cursor.

Parameters:
  • document – The prompt_toolkit.document.Document representing the current state of the input buffer.

  • complete_event – The prompt_toolkit.completion.CompleteEvent triggering the completion (not directly used here).

Yields:

prompt_toolkit.completion.Completion – Completion objects for prompt-toolkit to display.

class saturnin._scripts.repl.IOManager(context, *, echo: Callable[[str], None] | None = None, console: Console | None = None)[source]

Bases: object

Manages I/O operations and state for the REPL.

This class handles command prompting, input sources (stdin or queued commands), output redirection (to console or file), and maintains the REPL’s interaction state. It also configures prompt-toolkit settings like history and autocompletion.

Parameters:
  • context – The current Click context.

  • echo (Callable[[str], None] | None) – Optional callback invoked with the command line string before it’s executed.

  • console (Console) – Custom Rich console for output. If None, Saturnin’s standard console (cm.std_console) is used.

__enter__() Self[source]

Enters the context, returning self.

Return type:

Self

__exit__(exc_type, exc_value, traceback) None[source]

Exits the context, restoring stdin/stdout and the console.

Return type:

None

_get_command() str[source]

Fetches the next command string.

Reads from run_commands list first, then from sys.stdin if not a TTY, otherwise prompts the user using prompt-toolkit.

Returns:

The command string entered by the user or read from input.

Return type:

str

_get_next_cmd() str[source]

Retrieves the next command from the internal cmd_queue.

This method also handles redirection of stdin/stdout for piped commands within the queue.

Returns:

The next command from the queue.

Return type:

str

_is_internal_cmd(cmd: str) bool[source]

Checks if a command string is an internal REPL command.

Internal commands include ‘help’, ‘quit’, and commands starting with ‘?’.

Parameters:

cmd (str) – The command string to check.

Returns:

True if the command is internal, False otherwise.

Return type:

bool

get_command() str[source]

Returns the next command to be executed.

Prioritizes commands from the internal queue (cmd_queue). If the queue is empty, it fetches a command using _get_command. If an echo callback is set, it’s invoked with the command.

Returns:

The command string.

Return type:

str

redirect_console(filename: Path) None[source]

Redirects REPL console output to the specified file.

If the filename has an HTML-like suffix (e.g., ‘.html’, ‘.htm’), the output will be recorded for saving as HTML.

Parameters:

filename (Path) – The path to the file for console output.

Return type:

None

reset_queue() None[source]

Clears the internal command queue (cmd_queue).

If commands were in the queue, a message is printed to the console. stdin and stdout are restored to their saved states.

Return type:

None

restore_console() None[source]

Restores console output to the original Rich console (cm.std_console).

If output was being redirected to a file, the file is closed. If HTML recording was active, console.save_html() is called.

Return type:

None

cmd_queue

Queue for pipelined commands.

console: Console

The Rich console instance for REPL output.

echo: Callable[[str], None] | None

Optional callback for echoing executed commands.

html_output: bool

Flag indicating if output is being recorded as HTML.

isatty: bool

True if stdin is a TTY, False otherwise.

output_file: TextIO | None

File object if output is redirected, else None.

output_filename: Path | None

Path to the output file if redirected.

prompt_kwargs: dict[str, Any]

Arguments passed to prompt_toolkit.prompt.

run_commands: list[str]

List of commands to run non-interactively.

Functions

saturnin._scripts.repl.repl(context, ioman: IOManager) bool[source]

Runs the main Read-Eval-Print Loop.

This function continuously prompts for commands, executes them using the Click/Typer application context, and handles exceptions and special REPL commands (like ‘quit’, ‘help’, ‘?’).

Parameters:
  • context – The current Click context for the REPL.

  • ioman (IOManager) – The IOManager instance managing REPL I/O.

Returns:

True if the REPL should be restarted (e.g., due to RestartError),

False otherwise for a normal exit.

Return type:

bool

Behavior:

  • If stdin is not a TTY, commands are read from stdin without a prompt.

  • Handles KeyboardInterrupt by continuing the loop.

  • Handles EOFError (e.g., Ctrl+D) by exiting the loop.

  • Internal commands (‘quit’, ‘help’, ‘?<cmd>’) are processed specially.

  • Other commands are parsed and invoked via the Click application group.

  • Catches and displays Click exceptions, SystemExit, and RestartError.