### Install Runegraft from Source Source: https://runegraft.codesft.dev/quickstart Clones the Runegraft repository from GitHub and installs it locally using pip in editable mode. This method is useful for development or when you need the latest changes. ```bash git clone https://github.com/YOUR_ORG/runegraft cd runegraft pip install -e . ``` -------------------------------- ### Install Runegraft using pip Source: https://runegraft.codesft.dev/quickstart Installs the Runegraft package using pip, making it available for use in your Python environment. This is the standard method for adding Runegraft to your project. ```bash pip install runegraft ``` -------------------------------- ### Create a Basic CLI Application with Runegraft Source: https://runegraft.codesft.dev/quickstart Demonstrates how to define a simple CLI application using Runegraft. It includes routing for commands like 'install' and 'echo', with support for typed arguments and optional flags. This code can be placed in any Python module and executed. ```python from runegraft import CLI, opt cli = CLI("runegraft") @cli.root def _root(): # Running with no args opens the shell. return cli.shell() @cli.command("install ") def install( url: str, optional_flag: int = opt("--optional-flag", "-f", default=0, help="Example integer option"), ): print(f"Installing from {url} (optional_flag={optional_flag})") @cli.command("echo ") def echo(text: str, upper: bool = opt("--upper", "-u", default=False, help="Uppercase the text")): print(text.upper() if upper else text) def main(): raise SystemExit(cli.run()) if __name__ == "__main__": main() ``` -------------------------------- ### Run Runegraft CLI Source: https://runegraft.codesft.dev/quickstart Provides commands to interact with a Runegraft CLI application. The first command launches an interactive shell, while the subsequent commands demonstrate one-shot executions of the 'install' and 'echo' commands with sample arguments. ```bash python -m runegraft python -m runegraft install https://example.com/pkg.zip -f 3 python -m runegraft echo "hi there" --upper ``` -------------------------------- ### Run a CLI command with arguments Source: https://runegraft.codesft.dev/index This example demonstrates how to execute a CLI command installed via Runegraft, passing arguments and flags. It shows the typical input and the resulting output when the CLI is invoked. ```bash $ runegraft install https://example.com/pkg.zip --optional-flag 3 Installing from https://example.com/pkg.zip (optional_flag=3) ``` -------------------------------- ### Runegraft Shell Session Example Source: https://runegraft.codesft.dev/concepts/shell Demonstrates a typical interactive session with the Runegraft shell, showcasing commands like 'help', 'install', aliasing, 'history show', and 'exit'. This helps users understand the basic workflow and available functionalities. ```bash $ runegraft runegraft> help runegraft> install https://example.com/pkg.zip -f 3 runegraft> alias set i "install -f 3" runegraft> i https://example.com/pkg.zip runegraft> history show runegraft> exit ``` -------------------------------- ### Runegraft Command Route Syntax Examples Source: https://runegraft.codesft.dev/reference/routing-and-types Demonstrates the usage of Runegraft's route syntax for defining commands with required and optional arguments, including type annotations. ```python @cli.command("add ") @cli.command("spinner [seconds:float]") @cli.command("fetch [retries:int]") ``` -------------------------------- ### Installer-Style Command with Runegraft Source: https://runegraft.codesft.dev/recipes Demonstrates how to create an installer-style command using Runegraft. It includes URL validation and options for overwriting existing installations and specifying a target directory. The `` converter ensures input validity, and options like `--force` and `--target` enhance discoverability through generated help messages. ```python from runegraft import CLI, opt cli = CLI("installr") @cli.command("install ") def install( url: str, force: bool = opt("--force", "-f", default=False, help="Overwrite existing installs"), target: str = opt("--target", "-t", default="~/.installr", help="Install directory"), ): print(f"Installing {url} into {target} (force={force})") ``` -------------------------------- ### Install Runegraft using pip Source: https://runegraft.codesft.dev/index This snippet shows how to install the Runegraft package using pip. It's the standard way to add the library to your Python environment. For development, an editable install is also mentioned. ```python pip install runegraft ``` ```python pip install -e . ``` -------------------------------- ### Initialize and Run the Runegraft Shell Source: https://runegraft.codesft.dev/reference/shell-api Demonstrates how to instantiate and run the `Shell` class. It requires an `cli` object and a `ShellConfig`. The `shell.run()` method starts the interactive shell loop, which continues until the user exits. ```python from runegraft.shell import Shell from runegraft.cli import CLI # Assuming CLI is available # Assuming 'cli' is an instance of CLI cli = CLI() config = ShellConfig(history_path=Path("~/.runegraft/history/my_prog.txt"), prompt="forge> ") shell = Shell(cli, config) shell.run() ``` -------------------------------- ### Repeatable Workflows with Runegraft Scripts Source: https://runegraft.codesft.dev/recipes Illustrates how to create repeatable workflows by dropping frequently used commands into a `.rg` file and executing them using the `source` command within the Runegraft shell. This allows teams to share common setup scripts or sequences of operations, ensuring consistency in environment bootstrapping or deployment processes. ```text # team-setup.rg install https://example.com/pkg.zip -f alias set deploy-prod "deploy production --region us-east-1" history save ``` ```bash runegraft> source ./team-setup.rg ``` -------------------------------- ### Define CLI Command Options with Defaults and Help Text Source: https://runegraft.codesft.dev/concepts/options This Python snippet demonstrates how to define a CLI command named 'deploy' using Runegraft's `CLI` and `opt` helpers. It showcases setting default values and help text for boolean, string, and integer flags, which are automatically reflected in the generated CLI help output. Type hints ensure input validation. ```python from runegraft import CLI, opt cli = CLI("demo") @cli.command("deploy ") def deploy( env: str, dry_run: bool = opt("--dry-run", "-n", default=False, help="Print actions without executing"), region: str = opt("--region", "-r", default="us-east-1", help="Deployment region"), retries: int = opt("--retries", default=2, help="Retry failed steps"), ): ... # Command implementation here ``` -------------------------------- ### Construct a Runegraft CLI Application Source: https://runegraft.codesft.dev/reference/cli-api Instantiate the main CLI object to define the application's name and description. The `name` parameter influences the shell prompt, while `description` is shown in help messages. The CLI object also provides access to a Rich console for formatted output. ```python from runegraft import cli app = cli.CLI(name="forge", description="Package builder") ``` -------------------------------- ### Setting Runegraft Shell as Default CLI Handler Source: https://runegraft.codesft.dev/concepts/shell Shows how to configure the Runegraft CLI to launch the interactive shell when no arguments are provided. This involves wiring the root handler of the CLI application to return `cli.shell()`. ```python from runegraft import CLI cli = CLI("runegraft") @cli.root def _root(): return cli.shell() ``` -------------------------------- ### Define Python CLI Routes with Typed Arguments Source: https://runegraft.codesft.dev/concepts/command-routes Demonstrates defining CLI commands with typed arguments using Runegraft's `@cli.command` decorator. It shows how to specify argument types within the route pattern and handle them as typed parameters in Python functions. Built-in converters like 'url' are used, and optional arguments with flags are supported. ```python from runegraft import CLI, opt cli = CLI("demo") @cli.command("install ") def install(url: str, force: bool = opt("--force", "-f", default=False, help="Overwrite existing install")): print(f"Installing from {url} (force={force})") @cli.command("config set ") def set_config(key: str, value: str): print(f"Saved {key}={value}") @cli.command("config get ") def get_config(key: str): print(f"Fetching {key}...") ``` -------------------------------- ### Git-Style Subcommands with Runegraft Source: https://runegraft.codesft.dev/recipes Shows how to implement Git-style subcommands using Runegraft for better organization. Route prefixes like 'task add' and 'task list' group related commands, improving usability in the shell and help output. This pattern is useful for managing related operations under a common verb. ```python @cli.command("task add ") def task_add(name: str): print(f"Added task '{name}'") @cli.command("task list") def task_list(): print("Listing tasks...") ``` -------------------------------- ### Execute CLI Commands with `CLI.run` and `CLI.invoke` Source: https://runegraft.codesft.dev/reference/cli-api The `CLI.run()` method dispatches arguments, automatically handling `--help` and empty input. For pre-parsed arguments, `CLI.invoke()` can be used to execute a single command. Errors are raised as `CLIError` to be handled by Rich for user-friendly messaging. ```python # Example usage (not runnable code): # app.run() # app.invoke(['command', 'arg']) ``` -------------------------------- ### Implement Choices and Validation for CLI Options Source: https://runegraft.codesft.dev/concepts/options This Python snippet illustrates how to enforce a set of allowed values for a CLI option using Runegraft's `opt` helper. The 'channel' option is restricted to 'alpha', 'beta', or 'stable', with 'beta' as the default. If an invalid value is provided, Runegraft will display a clear error message and list the valid choices. ```python from runegraft import CLI, opt cli = CLI("demo") @cli.command("publish") def publish( channel: str = opt("--channel", choices=["alpha", "beta", "stable"], default="beta", help="Release channel"), notes: str = opt("--notes", help="Optional release notes"), ): ... # Command implementation here ``` -------------------------------- ### Runegraft Built-in Type Converters Source: https://runegraft.codesft.dev/reference/routing-and-types Illustrates the mapping between route tokens and their corresponding Python types and conversion notes within Runegraft. ```markdown | Token | Converts to | Notes | | ----------------------- | ------------------- | -------------------------------------------------- | | `str`, `string`, `text` | `str` | No transformation beyond trimming quotes. | | `int` | `int` | Raises if the input is not numeric. | | `float` | `float` | Accepts decimal input. | | `bool` | `bool` | Handles values like `true/false`, `yes/no`, `1/0`. | | `path` | `pathlib.Path` | Expands `~` on load. | | `url` | `str` | Requires a scheme; enforces host unless `file://`. | | `json` | `Any` | Parses JSON strings into Python objects. | | `uuid` | `uuid.UUID` | Validates canonical UUID text. | | `date` | `datetime.date` | ISO `YYYY-MM-DD`. | | `datetime` | `datetime.datetime` | ISO 8601 timestamp. ``` -------------------------------- ### Register Commands with Route String and Type Hinting Source: https://runegraft.codesft.dev/reference/cli-api Register commands using the `@app.command` decorator with a route string that includes arguments and their types. Type hints in the function signature are used for argument coercion and validation. The first line of the docstring serves as a help summary. ```python @app.command("install [target:path]") def install(url: str, target: Path | None = None): """Download and stage a package.""" ... ``` -------------------------------- ### Customize Shell Behavior by Subclassing Source: https://runegraft.codesft.dev/reference/shell-api Shows how to extend the `Shell` class to customize its behavior, specifically by overriding the `_build_completer` method. This allows for modification of the completer's structure or wrapping it with additional prompt_toolkit completers. ```python from runegraft.shell import Shell class MyShell(Shell): def _build_completer(self): completer = super()._build_completer() # Add custom completion logic here, e.g.: # completer.tree.insert_words_at_node("/my_custom_commands", ["cmd1", "cmd2"]) return completer ``` -------------------------------- ### Expand Aliases in Shell Commands Source: https://runegraft.codesft.dev/reference/shell-api Illustrates the usage of the `expand_alias` helper function, which is part of the Runegraft shell's utilities. This function takes an `AliasStore` and a command line string, replacing the first token if it matches an alias defined in the store. ```python from runegraft.builtins import AliasStore, expand_alias # Example AliasStore alias_store = AliasStore(aliases={'ll': 'ls -al'}) command_line = "ll -h" expanded_command = expand_alias(alias_store, command_line) print(f"Original: {command_line}") print(f"Expanded: {expanded_command}") # Example with no alias match command_line_no_match = "echo hello" expanded_no_match = expand_alias(alias_store, command_line_no_match) print(f"Original: {command_line_no_match}") print(f"Expanded: {expanded_no_match}") ``` -------------------------------- ### Define Options and Flags from Function Parameters Source: https://runegraft.codesft.dev/reference/cli-api Options and flags are automatically inferred from function parameters not present in the route string. Boolean parameters act as flags (e.g., `--dry-run`), while others expect a value (e.g., `--retries 3`). Defaults are taken from the function signature. ```python @app.command("ship ") def ship(pkg: str, dry_run: bool = False, retries: int = 1): ... ``` -------------------------------- ### Customize Option Behavior with `runegraft.cli.option` Source: https://runegraft.codesft.dev/reference/cli-api Use `runegraft.cli.option` to override default option behavior, such as specifying short and long flag names, providing default values, and adding help text. The `is_flag` parameter explicitly defines if an option behaves as a boolean flag. ```python from runegraft.cli import option @app.command("echo ") def echo( text: str, upper: bool = option("--upper", "-U", default=False, help="Uppercase output", is_flag=True), ): ... ``` -------------------------------- ### Clear Terminal Screen Cross-Platform Source: https://runegraft.codesft.dev/reference/shell-api Demonstrates the `clear_screen` helper function from `runegraft.builtins`. This utility provides a cross-platform way to clear the terminal, typically invoked by the `clear` command or a keyboard shortcut like `Ctrl+L` within the shell. ```python import os from runegraft.builtins import clear_screen # In a real shell context, this would clear the terminal. # For demonstration, we'll just show its potential usage. print("This text will be cleared.") # In an interactive shell, calling clear_screen() would: # clear_screen() # Simulating the effect for demonstration: if os.name == 'nt': # for Windows os.system('cls') else: # for Linux/OSX os.system('clear') print("Terminal cleared. This text appears after clearing.") ``` -------------------------------- ### Define Shell Configuration with dataclass Source: https://runegraft.codesft.dev/reference/shell-api Defines the `ShellConfig` dataclass for configuring the Runegraft shell. It specifies the path for command history and the prompt string displayed before user input. The parent directory for history is created automatically. ```python from dataclasses import dataclass from pathlib import Path @dataclass class ShellConfig: history_path: Path prompt: str ``` -------------------------------- ### Register Custom Type Converters for Route Tokens Source: https://runegraft.codesft.dev/reference/cli-api Extend the CLI's parsing capabilities by registering custom type converters using the `@app.type` decorator. These converters handle the transformation of raw string input from route tokens into specific Python types. Validation errors during conversion are automatically surfaced to the user. ```python @app.type("semver") def parse_semver(raw: str) -> tuple[int, int, int]: ... @app.command("bump ") def bump(version): ... ``` -------------------------------- ### Custom Port Type Converter in Python Source: https://runegraft.codesft.dev/concepts/types Defines a custom converter function 'port' to validate and convert string input into an integer representing a network port. It ensures the port is within the valid range of 1 to 65535 and raises a ConverterError for invalid inputs. This converter can then be used in Runegraft CLI command definitions. ```python from runegraft import CLI, opt, ConverterError cli = CLI("demo") def port(value: str) -> int: try: parsed = int(value) except ValueError as exc: raise ConverterError("Port must be an integer") from exc if not (1 <= parsed <= 65535): raise ConverterError("Port must be between 1 and 65535") return parsed @cli.command("serve ") def serve( port: int, host: str = opt("--host", default="127.0.0.1"), ): print(f"Serving on {host}:{port}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.