|
| 1 | +from typing import Dict, List |
| 2 | + |
| 3 | +import typer |
| 4 | + |
| 5 | +app = typer.Typer( |
| 6 | + help=("Search available commands by keyword " "(name or description).") |
| 7 | +) |
| 8 | + |
| 9 | + |
| 10 | +def _get_available_commands() -> List[Dict[str, str]]: |
| 11 | + """ |
| 12 | + Mocked list of available commands. |
| 13 | + Replace with real registry/source when available. |
| 14 | + """ |
| 15 | + return [ |
| 16 | + {"name": "ls", "description": "List directory contents"}, |
| 17 | + {"name": "grep", "description": "Search for PATTERN in files"}, |
| 18 | + { |
| 19 | + "name": "find", |
| 20 | + "description": "Search for files in a directory hierarchy", |
| 21 | + }, |
| 22 | + { |
| 23 | + "name": "awk", |
| 24 | + "description": "Pattern scanning and processing language", |
| 25 | + }, |
| 26 | + { |
| 27 | + "name": "cat", |
| 28 | + "description": ("Concatenate files and print on the standard " "output"), |
| 29 | + }, |
| 30 | + {"name": "head", "description": "Output the first part of files"}, |
| 31 | + {"name": "tail", "description": "Output the last part of files"}, |
| 32 | + { |
| 33 | + "name": "sed", |
| 34 | + "description": ("Stream editor for filtering and transforming " "text"), |
| 35 | + }, |
| 36 | + ] |
| 37 | + |
| 38 | + |
| 39 | +def _search_commands( |
| 40 | + keyword: str, |
| 41 | + commands: List[Dict[str, str]], |
| 42 | +) -> List[Dict[str, str]]: |
| 43 | + k = (keyword or "").strip().lower() |
| 44 | + if not k: |
| 45 | + return [] |
| 46 | + return [ |
| 47 | + cmd |
| 48 | + for cmd in commands |
| 49 | + if (k in cmd.get("name", "").lower()) |
| 50 | + or (k in cmd.get("description", "").lower()) |
| 51 | + ] |
| 52 | + |
| 53 | + |
| 54 | +@app.callback(invoke_without_command=True) |
| 55 | +def search( |
| 56 | + keyword: str = typer.Argument( |
| 57 | + ..., |
| 58 | + help="Keyword to search for, e.g. 'grep'", |
| 59 | + ), |
| 60 | +) -> None: |
| 61 | + """ |
| 62 | + Search available commands by keyword (matches command name or description). |
| 63 | + Example: python cli.py search grep |
| 64 | + """ |
| 65 | + results = _search_commands(keyword, _get_available_commands()) |
| 66 | + if not results: |
| 67 | + typer.echo("No commands found.") |
| 68 | + raise typer.Exit(code=1) |
| 69 | + |
| 70 | + for cmd in results: |
| 71 | + name = cmd.get("name", "").strip() |
| 72 | + desc = cmd.get("description", "").strip() |
| 73 | + typer.echo(f"{name}: {desc}") |
0 commit comments