slashed


Nameslashed JSON
Version 0.12.0 PyPI version JSON
download
home_pageNone
SummarySlash commands and autocompletions
upload_time2025-10-06 20:33:11
maintainerNone
docs_urlNone
authorPhilipp Temminghoff
requires_python>=3.12
licenseMIT License Copyright (c) 2024, Philipp Temminghoff Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Slashed

[![PyPI License](https://img.shields.io/pypi/l/slashed.svg)](https://pypi.org/project/slashed/)
[![Package status](https://img.shields.io/pypi/status/slashed.svg)](https://pypi.org/project/slashed/)
[![Monthly downloads](https://img.shields.io/pypi/dm/slashed.svg)](https://pypi.org/project/slashed/)
[![Distribution format](https://img.shields.io/pypi/format/slashed.svg)](https://pypi.org/project/slashed/)
[![Wheel availability](https://img.shields.io/pypi/wheel/slashed.svg)](https://pypi.org/project/slashed/)
[![Python version](https://img.shields.io/pypi/pyversions/slashed.svg)](https://pypi.org/project/slashed/)
[![Implementation](https://img.shields.io/pypi/implementation/slashed.svg)](https://pypi.org/project/slashed/)
[![Releases](https://img.shields.io/github/downloads/phil65/slashed/total.svg)](https://github.com/phil65/slashed/releases)
[![Github Contributors](https://img.shields.io/github/contributors/phil65/slashed)](https://github.com/phil65/slashed/graphs/contributors)
[![Github Discussions](https://img.shields.io/github/discussions/phil65/slashed)](https://github.com/phil65/slashed/discussions)
[![Github Forks](https://img.shields.io/github/forks/phil65/slashed)](https://github.com/phil65/slashed/forks)
[![Github Issues](https://img.shields.io/github/issues/phil65/slashed)](https://github.com/phil65/slashed/issues)
[![Github Issues](https://img.shields.io/github/issues-pr/phil65/slashed)](https://github.com/phil65/slashed/pulls)
[![Github Watchers](https://img.shields.io/github/watchers/phil65/slashed)](https://github.com/phil65/slashed/watchers)
[![Github Stars](https://img.shields.io/github/stars/phil65/slashed)](https://github.com/phil65/slashed/stars)
[![Github Repository size](https://img.shields.io/github/repo-size/phil65/slashed)](https://github.com/phil65/slashed)
[![Github last commit](https://img.shields.io/github/last-commit/phil65/slashed)](https://github.com/phil65/slashed/commits)
[![Github release date](https://img.shields.io/github/release-date/phil65/slashed)](https://github.com/phil65/slashed/releases)
[![Github language count](https://img.shields.io/github/languages/count/phil65/slashed)](https://github.com/phil65/slashed)
[![Github commits this month](https://img.shields.io/github/commit-activity/m/phil65/slashed)](https://github.com/phil65/slashed)
[![Package status](https://codecov.io/gh/phil65/slashed/branch/main/graph/badge.svg)](https://codecov.io/gh/phil65/slashed/)
[![PyUp](https://pyup.io/repos/github/phil65/slashed/shield.svg)](https://pyup.io/repos/github/phil65/slashed/)

[Read the documentation!](https://phil65.github.io/slashed/)

A Python library for implementing slash commands with rich autocompletion support.

## Features

- Simple command registration system
- Rich autocompletion support with multiple providers
- Type-safe command and context handling:
  - Generic typing for context data
  - Type-checked command parameters
  - Safe data access patterns
- Built-in completers for:
  - File paths
  - Choice lists
  - Keyword arguments
  - Multi-value inputs
  - Callback based lists
  - Environment variables
- Extensible completion provider system
- Modern Python features (requires Python 3.12+)
- UI framework integration:
  - Textual support
  - prompt_toolkit support
- Built-in help system


**Slashed** could be compared to cmd2, both providing interactive command systems with completion and history support,
but **Slashed** offers a modern async-first design with rich (generic) type hints, improved autocompletion,
and flexible UI framework integration for both terminal (prompt-toolkit) and TUI (Textual) applications.
Unlike cmd2's tight coupling to its own REPL, **Slashed** is framework-agnostic and provides multiple ways to define commands,
making it more adaptable to different application needs while maintaining a clean, type-safe API.

## Installation

```bash
pip install slashed
```

## Quick Example

```python
from dataclasses import dataclass
from slashed import SlashedCommand, CommandStore, CommandContext
from slashed.completers import ChoiceCompleter


# Define app state that will be available to commands
@dataclass
class AppState:
    greeting_count: int = 0


# Define a command with explicit parameters and typed context
class GreetCommand(SlashedCommand):
    """Greet someone with a custom greeting."""

    name = "greet"
    category = "demo"

    async def execute_command(
        self,
        ctx: CommandContext[AppState],
        name: str = "World",
        greeting: str = "Hello",
    ):
        """Greet someone.

        Args:
            ctx: Command context
            name: Who to greet
            greeting: Custom greeting to use
        """
        state = ctx.get_data()  # Type-safe access to app state
        state.greeting_count += 1
        await ctx.output.print(
            f"{greeting}, {name}! "
            f"(Greeted {state.greeting_count} times)"
        )

    def get_completer(self) -> ChoiceCompleter:
        """Provide name suggestions."""
        return ChoiceCompleter({
            "World": "Default greeting target",
            "Everyone": "Greet all users",
            "Team": "Greet the team"
        })

# Create store and register the command
store = CommandStore()
store.register_command(GreetCommand)

# Create context with app state
ctx = store.create_context(data=AppState())

# Execute a command
await store.execute_command("greet Phil --greeting Hi", ctx)
```

## Command Definition Styles

Slashed offers two different styles for defining commands, each with its own advantages:

### Traditional Style (using Command class)

```python
from slashed import Command, CommandContext

async def add_worker(ctx: CommandContext, args: list[str], kwargs: dict[str, str]):
    """Add a worker to the pool."""
    worker_id = args[0]
    host = kwargs.get("host", "localhost")
    port = kwargs.get("port", "8080")
    await ctx.output.print(f"Adding worker {worker_id} at {host}:{port}")

cmd = Command(
    name="add-worker",
    description="Add a worker to the pool",
    execute_func=add_worker,
    usage="<worker_id> --host <host> --port <port>",
    category="workers",
)
```

#### Advantages:
- Quick to create without inheritance
- All configuration in one place
- Easier to create commands dynamically
- More flexible for simple commands
- Familiar to users of other command frameworks

### Declarative Style (using SlashedCommand)

```python
from slashed import SlashedCommand, CommandContext

class AddWorkerCommand(SlashedCommand):
    """Add a worker to the pool."""

    name = "add-worker"
    category = "workers"

    async def execute_command(
        self,
        ctx: CommandContext,
        worker_id: str,          # required parameter
        host: str = "localhost", # optional with default
        port: int = 8080,       # optional with default
    ):
        """Add a new worker to the pool.

        Args:
            ctx: Command context
            worker_id: Unique worker identifier
            host: Worker hostname
            port: Worker port number
        """
        await ctx.output.print(f"Adding worker {worker_id} at {host}:{port}")
```

#### Advantages:
- Type-safe parameter handling
- Automatic usage generation from parameters
- Help text generated from docstrings
- Better IDE support with explicit parameters
- More maintainable for complex commands
- Validates required parameters automatically
- Natural Python class structure
- Parameters are self-documenting

### When to Use Which?

Use the **traditional style** when:
- Creating simple commands with few parameters
- Generating commands dynamically
- Wanting to avoid class boilerplate
- Need maximum flexibility

Use the **declarative style** when:
- Building complex commands with many parameters
- Need type safety and parameter validation
- Want IDE support for parameters
- Documentation is important
- Working in a larger codebase

### Alternative Registration Methods

#### Using the Command Decorator

```python
@store.command(
    category="tools",
    usage="<pattern> [--type type]",
    completer=PathCompleter(files=True),
    condition=lambda: find_spec("sqlalchemy") is not None,
)
async def search(ctx: CommandContext, pattern: str, *, type: str = "any"):
    """Search for files in current directory."""
    await ctx.output.print(f"Searching for {pattern}")
```

#### Using add_command

```python
# Direct function
store.add_command(
    "search",
    search_func,
    category="tools",
    completer=PathCompleter(files=True),
)

# Import path
store.add_command(
    "query",
    "myapp.commands.database.execute_query",
    category="database",
    condition=lambda: find_spec("sqlalchemy") is not None,
)
```

#### Using CommandRegistry

For cases where you need to define commands before initializing the store (e.g., in module-level code),
you can use `CommandRegistry` to collect commands and register them later:

```python
# commands.py
from slashed import CommandRegistry
from slashed.completers import PathCompleter

registry = CommandRegistry()

@registry.command(
    category="tools",
    completer=PathCompleter(files=True)
)
async def search(ctx: CommandContext, pattern: str):
    """Search for files in current directory."""
    await ctx.output.print(f"Searching for {pattern}")

@registry.command(
    category="tools",
    condition=lambda: find_spec("sqlalchemy") is not None
)
async def query(ctx: CommandContext, sql: str):
    """Execute database query."""
    await ctx.output.print(f"Running query: {sql}")

# app.py
from slashed import CommandStore
from .commands import registry

store = CommandStore()
registry.register_to(store)  # Register all collected commands
```


## Generic Context Example

```python
from dataclasses import dataclass
from slashed import Command, CommandStore, CommandContext


# Define your custom context data
@dataclass
class AppContext:
    user_name: str
    is_admin: bool


# Command that uses the typed context
async def admin_cmd(
    ctx: CommandContext[AppContext],
    args: list[str],
    kwargs: dict[str, str],
):
    """Admin-only command."""
    state = ctx.get_data()  # Type-safe access to context data
    if not state.is_admin:
        await ctx.output.print("Sorry, admin access required!")
        return
    await ctx.output.print(f"Welcome admin {state.user_name}!")


# Create and register the command
admin_command = Command(
    name="admin",
    description="Admin-only command",
    execute_func=admin_cmd,
    category="admin",
)

# Setup the store with typed context
store = CommandStore()
store.register_command(admin_command)

# Create context with your custom data
ctx = store.create_context(
    data=AppContext(user_name="Alice", is_admin=True)
)

# Execute command with typed context
await store.execute_command("admin", ctx)
```

## Signal-Based Event System

Slashed uses Psygnal to provide a robust event system for monitoring command execution and output. This makes it easy to track command usage, handle errors, and integrate with UIs.

```python
from slashed import CommandStore

store = CommandStore()

# Monitor command execution
@store.command_executed.connect
def on_command_executed(event):
    """Handle command execution results."""
    if event.success:
        print(f"Command '{event.command}' succeeded")
    else:
        print(f"Command '{event.command}' failed: {event.error}")

# Monitor command output
@store.output.connect
def on_output(message: str):
    """Handle command output."""
    print(f"Output: {message}")

# Monitor command registry changes
@store.command_events.adding.connect
def on_command_added(name: str, command):
    print(f"New command registered: {name}")

# Monitor context registry changes
@store.context_events.adding.connect
def on_context_added(type_: type, context):
    print(f"New context registered: {type_.__name__}")
```

### Available Signals

- `command_executed`: Emitted after command execution (success/failure)
- `output`: Emitted for all command output
- `command_events`: EventedDict signals for command registry changes
- `context_events`: EventedDict signals for context registry changes

The signal system provides a clean way to handle events without tight coupling, making it ideal for UI integration and logging.


## UI Integration Examples

Slashed provides integrations for both prompt_toolkit and Textual:

### Prompt Toolkit REPL

```python
from prompt_toolkit import PromptSession
from slashed import CommandStore
from slashed.prompt_toolkit_completer import PromptToolkitCompleter


async def main():
    """Run a simple REPL with command completion."""
    # Initialize command store
    store = CommandStore()
    await store.initialize()

    # Create session with command completion
    completer = PromptToolkitCompleter(store=store)
    session = PromptSession(completer=completer, complete_while_typing=True)

    print("Type /help to list commands. Press Ctrl+D to exit.")

    while True:
        try:
            text = await session.prompt_async(">>> ")
            if text.startswith("/"):
                await store.execute_command_with_context(text[1:])
        except EOFError:  # Ctrl+D
            break

if __name__ == "__main__":
    import asyncio
    asyncio.run(main())
```

## Type-Safe Context System

Slashed provides a powerful context system that automatically matches commands with their required context data based on type hints. This allows for type-safe access to application state while keeping commands decoupled from specific implementations.

### Basic Usage

```python
from dataclasses import dataclass
from slashed import SlashedCommand, CommandStore, CommandContext

# Define your contexts
@dataclass
class DatabaseContext:
    """Database connection context."""
    connection: str
    timeout: int = 30

@dataclass
class UIContext:
    """UI context."""
    theme: str = "dark"

# Commands specify their required context type
class QueryCommand(SlashedCommand):
    """Execute a database query."""
    name = "query"

    async def execute_command(
        self,
        ctx: CommandContext[DatabaseContext],  # Type hint determines required context
        query: str,
    ):
        db = ctx.get_data()  # Properly typed as DatabaseContext
        await ctx.output.print(f"Executing {query} with timeout {db.timeout}")

# Register contexts and commands
store = CommandStore()
store.register_context(DatabaseContext("mysql://localhost"))
store.register_context(UIContext("light"))

# Commands automatically get their matching context
await store.execute_command_auto("/query select * from users")
```



### Textual App

```python
from dataclasses import dataclass

from slashed import ChoiceCompleter, SlashedCommand
from slashed.textual_adapter import SlashedApp
from textual.containers import Container, VerticalScroll
from textual.widgets import Input, Label


@dataclass
class AppState:
    """Application state available to commands."""
    user_name: str


class GreetCommand(SlashedCommand):
    """Greet someone."""
    name = "greet"
    category = "demo"

    async def execute_command(self, ctx: CommandContext[AppState], name: str = "World"):
        state = ctx.get_data()
        await ctx.output.print(f"Hello, {name}! (from {state.user_name})")

    def get_completer(self) -> ChoiceCompleter:
        return ChoiceCompleter({"World": "Everyone", "Team": "The Team"})


class DemoApp(SlashedApp[AppState, None]):
    """App with slash commands and completion."""

    def compose(self) -> ComposeResult:
        # Command input with completion
        suggester = self.get_suggester()
        yield Container(Input(id="command-input", suggester=suggester))
        # Output areas
        yield VerticalScroll(id="main-output")
        yield Label(id="status")

        # Connect outputs to widgets
        self.bind_output("main", "#main-output", default=True)
        self.bind_output("status", "#status")


if __name__ == "__main__":
    state = AppState(user_name="Admin")
    app = DemoApp(data=state, commands=[GreetCommand])
    app.run()
```

Both integrations support:
- Command completion
- Command history
- Typed context data
- Rich output formatting


## Command Routing System

Slashed provides a flexible routing system that allows organizing commands into different contexts with explicit permissions:

```python
from dataclasses import dataclass
from slashed import CommandRouter, CommandStore, SlashedCommand

# Define contexts for different subsystems
@dataclass
class GlobalContext:
    """Global application context."""
    env: str = "production"

@dataclass
class DatabaseContext:
    """Database connection context."""
    connection: str
    timeout: int = 30

# Create store and router
store = CommandStore()
router = CommandRouter[GlobalContext, DatabaseContext](
    global_context=GlobalContext(),
    commands=store,
)

# Add route with restricted commands
router.add_route(
    "db",
    DatabaseContext("mysql://localhost"),
    description="Database operations",
    allowed_commands={"query", "migrate"},  # Only allow specific commands
)

# Execute commands with proper routing
await router.execute("help", output)  # Uses global context
await router.execute("@db query 'SELECT 1'", output)  # Uses DB context

# Temporary context switching
with router.temporary_context(db_context):
    await router.execute("query 'SELECT 1'", output)  # No prefix needed
```

The routing system provides:
- Route-specific command permissions
- Automatic context switching
- Command prefix completion (@db, @fs, etc.)
- Type-safe context handling
- Temporary context overrides
- Clear separation of subsystems

This makes it easy to organize commands into logical groups while maintaining type safety and proper access control.


## Documentation

For full documentation including advanced usage and API reference, visit [phil65.github.io/slashed](https://phil65.github.io/slashed).

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request. Make sure to read our contributing guidelines first.

## License

This project is licensed under the MIT License - see the LICENSE file for details.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "slashed",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.12",
    "maintainer_email": null,
    "keywords": null,
    "author": "Philipp Temminghoff",
    "author_email": "Philipp Temminghoff <philipptemminghoff@googlemail.com>",
    "download_url": "https://files.pythonhosted.org/packages/7e/1a/1b00c40116f299f28c053eed5bd3a53844a93ecb2027406e16e9d22e6081/slashed-0.12.0.tar.gz",
    "platform": null,
    "description": "# Slashed\n\n[![PyPI License](https://img.shields.io/pypi/l/slashed.svg)](https://pypi.org/project/slashed/)\n[![Package status](https://img.shields.io/pypi/status/slashed.svg)](https://pypi.org/project/slashed/)\n[![Monthly downloads](https://img.shields.io/pypi/dm/slashed.svg)](https://pypi.org/project/slashed/)\n[![Distribution format](https://img.shields.io/pypi/format/slashed.svg)](https://pypi.org/project/slashed/)\n[![Wheel availability](https://img.shields.io/pypi/wheel/slashed.svg)](https://pypi.org/project/slashed/)\n[![Python version](https://img.shields.io/pypi/pyversions/slashed.svg)](https://pypi.org/project/slashed/)\n[![Implementation](https://img.shields.io/pypi/implementation/slashed.svg)](https://pypi.org/project/slashed/)\n[![Releases](https://img.shields.io/github/downloads/phil65/slashed/total.svg)](https://github.com/phil65/slashed/releases)\n[![Github Contributors](https://img.shields.io/github/contributors/phil65/slashed)](https://github.com/phil65/slashed/graphs/contributors)\n[![Github Discussions](https://img.shields.io/github/discussions/phil65/slashed)](https://github.com/phil65/slashed/discussions)\n[![Github Forks](https://img.shields.io/github/forks/phil65/slashed)](https://github.com/phil65/slashed/forks)\n[![Github Issues](https://img.shields.io/github/issues/phil65/slashed)](https://github.com/phil65/slashed/issues)\n[![Github Issues](https://img.shields.io/github/issues-pr/phil65/slashed)](https://github.com/phil65/slashed/pulls)\n[![Github Watchers](https://img.shields.io/github/watchers/phil65/slashed)](https://github.com/phil65/slashed/watchers)\n[![Github Stars](https://img.shields.io/github/stars/phil65/slashed)](https://github.com/phil65/slashed/stars)\n[![Github Repository size](https://img.shields.io/github/repo-size/phil65/slashed)](https://github.com/phil65/slashed)\n[![Github last commit](https://img.shields.io/github/last-commit/phil65/slashed)](https://github.com/phil65/slashed/commits)\n[![Github release date](https://img.shields.io/github/release-date/phil65/slashed)](https://github.com/phil65/slashed/releases)\n[![Github language count](https://img.shields.io/github/languages/count/phil65/slashed)](https://github.com/phil65/slashed)\n[![Github commits this month](https://img.shields.io/github/commit-activity/m/phil65/slashed)](https://github.com/phil65/slashed)\n[![Package status](https://codecov.io/gh/phil65/slashed/branch/main/graph/badge.svg)](https://codecov.io/gh/phil65/slashed/)\n[![PyUp](https://pyup.io/repos/github/phil65/slashed/shield.svg)](https://pyup.io/repos/github/phil65/slashed/)\n\n[Read the documentation!](https://phil65.github.io/slashed/)\n\nA Python library for implementing slash commands with rich autocompletion support.\n\n## Features\n\n- Simple command registration system\n- Rich autocompletion support with multiple providers\n- Type-safe command and context handling:\n  - Generic typing for context data\n  - Type-checked command parameters\n  - Safe data access patterns\n- Built-in completers for:\n  - File paths\n  - Choice lists\n  - Keyword arguments\n  - Multi-value inputs\n  - Callback based lists\n  - Environment variables\n- Extensible completion provider system\n- Modern Python features (requires Python 3.12+)\n- UI framework integration:\n  - Textual support\n  - prompt_toolkit support\n- Built-in help system\n\n\n**Slashed** could be compared to cmd2, both providing interactive command systems with completion and history support,\nbut **Slashed** offers a modern async-first design with rich (generic) type hints, improved autocompletion,\nand flexible UI framework integration for both terminal (prompt-toolkit) and TUI (Textual) applications.\nUnlike cmd2's tight coupling to its own REPL, **Slashed** is framework-agnostic and provides multiple ways to define commands,\nmaking it more adaptable to different application needs while maintaining a clean, type-safe API.\n\n## Installation\n\n```bash\npip install slashed\n```\n\n## Quick Example\n\n```python\nfrom dataclasses import dataclass\nfrom slashed import SlashedCommand, CommandStore, CommandContext\nfrom slashed.completers import ChoiceCompleter\n\n\n# Define app state that will be available to commands\n@dataclass\nclass AppState:\n    greeting_count: int = 0\n\n\n# Define a command with explicit parameters and typed context\nclass GreetCommand(SlashedCommand):\n    \"\"\"Greet someone with a custom greeting.\"\"\"\n\n    name = \"greet\"\n    category = \"demo\"\n\n    async def execute_command(\n        self,\n        ctx: CommandContext[AppState],\n        name: str = \"World\",\n        greeting: str = \"Hello\",\n    ):\n        \"\"\"Greet someone.\n\n        Args:\n            ctx: Command context\n            name: Who to greet\n            greeting: Custom greeting to use\n        \"\"\"\n        state = ctx.get_data()  # Type-safe access to app state\n        state.greeting_count += 1\n        await ctx.output.print(\n            f\"{greeting}, {name}! \"\n            f\"(Greeted {state.greeting_count} times)\"\n        )\n\n    def get_completer(self) -> ChoiceCompleter:\n        \"\"\"Provide name suggestions.\"\"\"\n        return ChoiceCompleter({\n            \"World\": \"Default greeting target\",\n            \"Everyone\": \"Greet all users\",\n            \"Team\": \"Greet the team\"\n        })\n\n# Create store and register the command\nstore = CommandStore()\nstore.register_command(GreetCommand)\n\n# Create context with app state\nctx = store.create_context(data=AppState())\n\n# Execute a command\nawait store.execute_command(\"greet Phil --greeting Hi\", ctx)\n```\n\n## Command Definition Styles\n\nSlashed offers two different styles for defining commands, each with its own advantages:\n\n### Traditional Style (using Command class)\n\n```python\nfrom slashed import Command, CommandContext\n\nasync def add_worker(ctx: CommandContext, args: list[str], kwargs: dict[str, str]):\n    \"\"\"Add a worker to the pool.\"\"\"\n    worker_id = args[0]\n    host = kwargs.get(\"host\", \"localhost\")\n    port = kwargs.get(\"port\", \"8080\")\n    await ctx.output.print(f\"Adding worker {worker_id} at {host}:{port}\")\n\ncmd = Command(\n    name=\"add-worker\",\n    description=\"Add a worker to the pool\",\n    execute_func=add_worker,\n    usage=\"<worker_id> --host <host> --port <port>\",\n    category=\"workers\",\n)\n```\n\n#### Advantages:\n- Quick to create without inheritance\n- All configuration in one place\n- Easier to create commands dynamically\n- More flexible for simple commands\n- Familiar to users of other command frameworks\n\n### Declarative Style (using SlashedCommand)\n\n```python\nfrom slashed import SlashedCommand, CommandContext\n\nclass AddWorkerCommand(SlashedCommand):\n    \"\"\"Add a worker to the pool.\"\"\"\n\n    name = \"add-worker\"\n    category = \"workers\"\n\n    async def execute_command(\n        self,\n        ctx: CommandContext,\n        worker_id: str,          # required parameter\n        host: str = \"localhost\", # optional with default\n        port: int = 8080,       # optional with default\n    ):\n        \"\"\"Add a new worker to the pool.\n\n        Args:\n            ctx: Command context\n            worker_id: Unique worker identifier\n            host: Worker hostname\n            port: Worker port number\n        \"\"\"\n        await ctx.output.print(f\"Adding worker {worker_id} at {host}:{port}\")\n```\n\n#### Advantages:\n- Type-safe parameter handling\n- Automatic usage generation from parameters\n- Help text generated from docstrings\n- Better IDE support with explicit parameters\n- More maintainable for complex commands\n- Validates required parameters automatically\n- Natural Python class structure\n- Parameters are self-documenting\n\n### When to Use Which?\n\nUse the **traditional style** when:\n- Creating simple commands with few parameters\n- Generating commands dynamically\n- Wanting to avoid class boilerplate\n- Need maximum flexibility\n\nUse the **declarative style** when:\n- Building complex commands with many parameters\n- Need type safety and parameter validation\n- Want IDE support for parameters\n- Documentation is important\n- Working in a larger codebase\n\n### Alternative Registration Methods\n\n#### Using the Command Decorator\n\n```python\n@store.command(\n    category=\"tools\",\n    usage=\"<pattern> [--type type]\",\n    completer=PathCompleter(files=True),\n    condition=lambda: find_spec(\"sqlalchemy\") is not None,\n)\nasync def search(ctx: CommandContext, pattern: str, *, type: str = \"any\"):\n    \"\"\"Search for files in current directory.\"\"\"\n    await ctx.output.print(f\"Searching for {pattern}\")\n```\n\n#### Using add_command\n\n```python\n# Direct function\nstore.add_command(\n    \"search\",\n    search_func,\n    category=\"tools\",\n    completer=PathCompleter(files=True),\n)\n\n# Import path\nstore.add_command(\n    \"query\",\n    \"myapp.commands.database.execute_query\",\n    category=\"database\",\n    condition=lambda: find_spec(\"sqlalchemy\") is not None,\n)\n```\n\n#### Using CommandRegistry\n\nFor cases where you need to define commands before initializing the store (e.g., in module-level code),\nyou can use `CommandRegistry` to collect commands and register them later:\n\n```python\n# commands.py\nfrom slashed import CommandRegistry\nfrom slashed.completers import PathCompleter\n\nregistry = CommandRegistry()\n\n@registry.command(\n    category=\"tools\",\n    completer=PathCompleter(files=True)\n)\nasync def search(ctx: CommandContext, pattern: str):\n    \"\"\"Search for files in current directory.\"\"\"\n    await ctx.output.print(f\"Searching for {pattern}\")\n\n@registry.command(\n    category=\"tools\",\n    condition=lambda: find_spec(\"sqlalchemy\") is not None\n)\nasync def query(ctx: CommandContext, sql: str):\n    \"\"\"Execute database query.\"\"\"\n    await ctx.output.print(f\"Running query: {sql}\")\n\n# app.py\nfrom slashed import CommandStore\nfrom .commands import registry\n\nstore = CommandStore()\nregistry.register_to(store)  # Register all collected commands\n```\n\n\n## Generic Context Example\n\n```python\nfrom dataclasses import dataclass\nfrom slashed import Command, CommandStore, CommandContext\n\n\n# Define your custom context data\n@dataclass\nclass AppContext:\n    user_name: str\n    is_admin: bool\n\n\n# Command that uses the typed context\nasync def admin_cmd(\n    ctx: CommandContext[AppContext],\n    args: list[str],\n    kwargs: dict[str, str],\n):\n    \"\"\"Admin-only command.\"\"\"\n    state = ctx.get_data()  # Type-safe access to context data\n    if not state.is_admin:\n        await ctx.output.print(\"Sorry, admin access required!\")\n        return\n    await ctx.output.print(f\"Welcome admin {state.user_name}!\")\n\n\n# Create and register the command\nadmin_command = Command(\n    name=\"admin\",\n    description=\"Admin-only command\",\n    execute_func=admin_cmd,\n    category=\"admin\",\n)\n\n# Setup the store with typed context\nstore = CommandStore()\nstore.register_command(admin_command)\n\n# Create context with your custom data\nctx = store.create_context(\n    data=AppContext(user_name=\"Alice\", is_admin=True)\n)\n\n# Execute command with typed context\nawait store.execute_command(\"admin\", ctx)\n```\n\n## Signal-Based Event System\n\nSlashed uses Psygnal to provide a robust event system for monitoring command execution and output. This makes it easy to track command usage, handle errors, and integrate with UIs.\n\n```python\nfrom slashed import CommandStore\n\nstore = CommandStore()\n\n# Monitor command execution\n@store.command_executed.connect\ndef on_command_executed(event):\n    \"\"\"Handle command execution results.\"\"\"\n    if event.success:\n        print(f\"Command '{event.command}' succeeded\")\n    else:\n        print(f\"Command '{event.command}' failed: {event.error}\")\n\n# Monitor command output\n@store.output.connect\ndef on_output(message: str):\n    \"\"\"Handle command output.\"\"\"\n    print(f\"Output: {message}\")\n\n# Monitor command registry changes\n@store.command_events.adding.connect\ndef on_command_added(name: str, command):\n    print(f\"New command registered: {name}\")\n\n# Monitor context registry changes\n@store.context_events.adding.connect\ndef on_context_added(type_: type, context):\n    print(f\"New context registered: {type_.__name__}\")\n```\n\n### Available Signals\n\n- `command_executed`: Emitted after command execution (success/failure)\n- `output`: Emitted for all command output\n- `command_events`: EventedDict signals for command registry changes\n- `context_events`: EventedDict signals for context registry changes\n\nThe signal system provides a clean way to handle events without tight coupling, making it ideal for UI integration and logging.\n\n\n## UI Integration Examples\n\nSlashed provides integrations for both prompt_toolkit and Textual:\n\n### Prompt Toolkit REPL\n\n```python\nfrom prompt_toolkit import PromptSession\nfrom slashed import CommandStore\nfrom slashed.prompt_toolkit_completer import PromptToolkitCompleter\n\n\nasync def main():\n    \"\"\"Run a simple REPL with command completion.\"\"\"\n    # Initialize command store\n    store = CommandStore()\n    await store.initialize()\n\n    # Create session with command completion\n    completer = PromptToolkitCompleter(store=store)\n    session = PromptSession(completer=completer, complete_while_typing=True)\n\n    print(\"Type /help to list commands. Press Ctrl+D to exit.\")\n\n    while True:\n        try:\n            text = await session.prompt_async(\">>> \")\n            if text.startswith(\"/\"):\n                await store.execute_command_with_context(text[1:])\n        except EOFError:  # Ctrl+D\n            break\n\nif __name__ == \"__main__\":\n    import asyncio\n    asyncio.run(main())\n```\n\n## Type-Safe Context System\n\nSlashed provides a powerful context system that automatically matches commands with their required context data based on type hints. This allows for type-safe access to application state while keeping commands decoupled from specific implementations.\n\n### Basic Usage\n\n```python\nfrom dataclasses import dataclass\nfrom slashed import SlashedCommand, CommandStore, CommandContext\n\n# Define your contexts\n@dataclass\nclass DatabaseContext:\n    \"\"\"Database connection context.\"\"\"\n    connection: str\n    timeout: int = 30\n\n@dataclass\nclass UIContext:\n    \"\"\"UI context.\"\"\"\n    theme: str = \"dark\"\n\n# Commands specify their required context type\nclass QueryCommand(SlashedCommand):\n    \"\"\"Execute a database query.\"\"\"\n    name = \"query\"\n\n    async def execute_command(\n        self,\n        ctx: CommandContext[DatabaseContext],  # Type hint determines required context\n        query: str,\n    ):\n        db = ctx.get_data()  # Properly typed as DatabaseContext\n        await ctx.output.print(f\"Executing {query} with timeout {db.timeout}\")\n\n# Register contexts and commands\nstore = CommandStore()\nstore.register_context(DatabaseContext(\"mysql://localhost\"))\nstore.register_context(UIContext(\"light\"))\n\n# Commands automatically get their matching context\nawait store.execute_command_auto(\"/query select * from users\")\n```\n\n\n\n### Textual App\n\n```python\nfrom dataclasses import dataclass\n\nfrom slashed import ChoiceCompleter, SlashedCommand\nfrom slashed.textual_adapter import SlashedApp\nfrom textual.containers import Container, VerticalScroll\nfrom textual.widgets import Input, Label\n\n\n@dataclass\nclass AppState:\n    \"\"\"Application state available to commands.\"\"\"\n    user_name: str\n\n\nclass GreetCommand(SlashedCommand):\n    \"\"\"Greet someone.\"\"\"\n    name = \"greet\"\n    category = \"demo\"\n\n    async def execute_command(self, ctx: CommandContext[AppState], name: str = \"World\"):\n        state = ctx.get_data()\n        await ctx.output.print(f\"Hello, {name}! (from {state.user_name})\")\n\n    def get_completer(self) -> ChoiceCompleter:\n        return ChoiceCompleter({\"World\": \"Everyone\", \"Team\": \"The Team\"})\n\n\nclass DemoApp(SlashedApp[AppState, None]):\n    \"\"\"App with slash commands and completion.\"\"\"\n\n    def compose(self) -> ComposeResult:\n        # Command input with completion\n        suggester = self.get_suggester()\n        yield Container(Input(id=\"command-input\", suggester=suggester))\n        # Output areas\n        yield VerticalScroll(id=\"main-output\")\n        yield Label(id=\"status\")\n\n        # Connect outputs to widgets\n        self.bind_output(\"main\", \"#main-output\", default=True)\n        self.bind_output(\"status\", \"#status\")\n\n\nif __name__ == \"__main__\":\n    state = AppState(user_name=\"Admin\")\n    app = DemoApp(data=state, commands=[GreetCommand])\n    app.run()\n```\n\nBoth integrations support:\n- Command completion\n- Command history\n- Typed context data\n- Rich output formatting\n\n\n## Command Routing System\n\nSlashed provides a flexible routing system that allows organizing commands into different contexts with explicit permissions:\n\n```python\nfrom dataclasses import dataclass\nfrom slashed import CommandRouter, CommandStore, SlashedCommand\n\n# Define contexts for different subsystems\n@dataclass\nclass GlobalContext:\n    \"\"\"Global application context.\"\"\"\n    env: str = \"production\"\n\n@dataclass\nclass DatabaseContext:\n    \"\"\"Database connection context.\"\"\"\n    connection: str\n    timeout: int = 30\n\n# Create store and router\nstore = CommandStore()\nrouter = CommandRouter[GlobalContext, DatabaseContext](\n    global_context=GlobalContext(),\n    commands=store,\n)\n\n# Add route with restricted commands\nrouter.add_route(\n    \"db\",\n    DatabaseContext(\"mysql://localhost\"),\n    description=\"Database operations\",\n    allowed_commands={\"query\", \"migrate\"},  # Only allow specific commands\n)\n\n# Execute commands with proper routing\nawait router.execute(\"help\", output)  # Uses global context\nawait router.execute(\"@db query 'SELECT 1'\", output)  # Uses DB context\n\n# Temporary context switching\nwith router.temporary_context(db_context):\n    await router.execute(\"query 'SELECT 1'\", output)  # No prefix needed\n```\n\nThe routing system provides:\n- Route-specific command permissions\n- Automatic context switching\n- Command prefix completion (@db, @fs, etc.)\n- Type-safe context handling\n- Temporary context overrides\n- Clear separation of subsystems\n\nThis makes it easy to organize commands into logical groups while maintaining type safety and proper access control.\n\n\n## Documentation\n\nFor full documentation including advanced usage and API reference, visit [phil65.github.io/slashed](https://phil65.github.io/slashed).\n\n## Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request. Make sure to read our contributing guidelines first.\n\n## License\n\nThis project is licensed under the MIT License - see the LICENSE file for details.\n",
    "bugtrack_url": null,
    "license": "MIT License\n         \n         Copyright (c) 2024, Philipp Temminghoff\n         \n         Permission is hereby granted, free of charge, to any person obtaining a copy\n         of this software and associated documentation files (the \"Software\"), to deal\n         in the Software without restriction, including without limitation the rights\n         to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n         copies of the Software, and to permit persons to whom the Software is\n         furnished to do so, subject to the following conditions:\n         \n         The above copyright notice and this permission notice shall be included in all\n         copies or substantial portions of the Software.\n         \n         THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n         IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n         FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n         AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n         LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n         OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n         SOFTWARE.\n         ",
    "summary": "Slash commands and autocompletions",
    "version": "0.12.0",
    "project_urls": {
        "Code coverage": "https://app.codecov.io/gh/phil65/slashed",
        "Discussions": "https://github.com/phil65/slashed/discussions",
        "Documentation": "https://phil65.github.io/slashed/",
        "Issues": "https://github.com/phil65/slashed/issues",
        "Source": "https://github.com/phil65/slashed"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "994b922848eba1ac84e6c4c84eabec3a33c83f6ff7bf83226907f3c9c80bdc98",
                "md5": "30634d278624e7db6c68585947e749f0",
                "sha256": "80cdcb9c39ebc63eec868f5a0096e78768529ba11a3c20e5ec8d4bdc9d9dea00"
            },
            "downloads": -1,
            "filename": "slashed-0.12.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "30634d278624e7db6c68585947e749f0",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.12",
            "size": 51741,
            "upload_time": "2025-10-06T20:33:10",
            "upload_time_iso_8601": "2025-10-06T20:33:10.687030Z",
            "url": "https://files.pythonhosted.org/packages/99/4b/922848eba1ac84e6c4c84eabec3a33c83f6ff7bf83226907f3c9c80bdc98/slashed-0.12.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "7e1a1b00c40116f299f28c053eed5bd3a53844a93ecb2027406e16e9d22e6081",
                "md5": "2bd7541dda0a519e4f0ee4e7e28140f0",
                "sha256": "45a1adcfd7820f8dadb122e7ea82e0bfdc3dd938451274c99f2340c64af462c0"
            },
            "downloads": -1,
            "filename": "slashed-0.12.0.tar.gz",
            "has_sig": false,
            "md5_digest": "2bd7541dda0a519e4f0ee4e7e28140f0",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.12",
            "size": 39620,
            "upload_time": "2025-10-06T20:33:11",
            "upload_time_iso_8601": "2025-10-06T20:33:11.998946Z",
            "url": "https://files.pythonhosted.org/packages/7e/1a/1b00c40116f299f28c053eed5bd3a53844a93ecb2027406e16e9d22e6081/slashed-0.12.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-10-06 20:33:11",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "phil65",
    "github_project": "slashed",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "slashed"
}
        
Elapsed time: 1.30701s