TldrProvider
Base classes
| Name |
Children |
Inherits |
HelpProvider clinspector.help_providers.base Protocol for CLI help providers. |
|
|
⋔ Inheritance diagram
graph TD
4181891595["tldr_pages.TldrProvider"]
1550573299["base.HelpProvider"]
1073422405["typing.Protocol"]
3481597255["typing.Generic"]
2751680898["builtins.object"]
1550573299 --> 4181891595
1073422405 --> 1550573299
3481597255 --> 1073422405
2751680898 --> 3481597255
🛈 DocStrings
Bases: HelpProvider
Provider for tldr-pages help.
Source code in src/clinspector/help_providers/tldr_pages.py
| class TldrProvider(HelpProvider):
"""Provider for tldr-pages help."""
def __init__(self) -> None:
"""Initialize provider."""
self._cache_initialized = False
self._init_lock = asyncio.Lock()
async def _ensure_cache(self) -> None:
"""Initialize cache if needed."""
import tldr
if self._cache_initialized:
return
async with self._init_lock:
if not self._cache_initialized:
await asyncio.to_thread(tldr.update_cache)
self._cache_initialized = True
def _clean_command_name(self, cmd: str) -> str:
"""Remove language suffix from command name."""
return cmd.split(" (", maxsplit=1)[0] if " (" in cmd else cmd
def _parse_page(self, lines: list[bytes], platform: str = "") -> CommandHelp:
"""Parse a tldr page into CommandHelp."""
examples: list[Example] = []
name = ""
description_lines: list[str] = []
current: TldrExample | None = None
for line_bytes in lines:
line = line_bytes.decode(errors="replace").strip()
if line.startswith("# "):
name = line.removeprefix("# ")
elif line.startswith("> "):
text = line.removeprefix("> ")
if not text.startswith("More information:"):
description_lines.append(text)
elif line.startswith("- "):
if current:
examples.append(current.to_example())
current = TldrExample(description=line.removeprefix("- "))
elif line.startswith("`") and current:
cmd = line.strip("`")
placeholders: dict[str, str] = {}
for match in re.finditer(r"\{\{(.+?)\}\}", cmd):
placeholders[match.group(1)] = ""
current.command = cmd
current.placeholders = placeholders
if current:
examples.append(current.to_example())
description = " ".join(description_lines)
return CommandHelp(name=name, description=description, examples=examples, platform=platform)
async def get_command_help(self, command: str) -> CommandHelp:
"""Get help for a command from tldr."""
import tldr
await self._ensure_cache()
def get_page(platform: str) -> list[bytes]:
return cast(
list[bytes],
tldr.get_page_for_platform(command, platform, tldr.PAGES_SOURCE_LOCATION, "en"),
)
for platform_name in ["common", "windows", "linux", "osx"]:
try:
result = await asyncio.to_thread(get_page, platform_name)
if result:
return self._parse_page(result, platform_name)
except Exception as exc: # noqa: BLE001
logger.debug("Error fetching %s for %s: %s", command, platform_name, exc)
continue
msg = f"No help found for command: {command}"
raise ValueError(msg)
async def search_commands(self, query: str) -> list[str]:
"""Search for commands matching query."""
import tldr
await self._ensure_cache()
commands = await asyncio.to_thread(tldr.get_commands)
return [
self._clean_command_name(cmd)
for cmd in commands
if query.lower() in self._clean_command_name(cmd).lower()
]
async def list_commands(self) -> list[str]:
"""List all available commands."""
import tldr
await self._ensure_cache()
commands = await asyncio.to_thread(tldr.get_commands)
return [self._clean_command_name(cmd) for cmd in commands]
|
__init__
Initialize provider.
Source code in src/clinspector/help_providers/tldr_pages.py
| def __init__(self) -> None:
"""Initialize provider."""
self._cache_initialized = False
self._init_lock = asyncio.Lock()
|
get_command_help
async
Get help for a command from tldr.
Source code in src/clinspector/help_providers/tldr_pages.py
| async def get_command_help(self, command: str) -> CommandHelp:
"""Get help for a command from tldr."""
import tldr
await self._ensure_cache()
def get_page(platform: str) -> list[bytes]:
return cast(
list[bytes],
tldr.get_page_for_platform(command, platform, tldr.PAGES_SOURCE_LOCATION, "en"),
)
for platform_name in ["common", "windows", "linux", "osx"]:
try:
result = await asyncio.to_thread(get_page, platform_name)
if result:
return self._parse_page(result, platform_name)
except Exception as exc: # noqa: BLE001
logger.debug("Error fetching %s for %s: %s", command, platform_name, exc)
continue
msg = f"No help found for command: {command}"
raise ValueError(msg)
|
list_commands
async
list_commands() -> list[str]
List all available commands.
Source code in src/clinspector/help_providers/tldr_pages.py
| async def list_commands(self) -> list[str]:
"""List all available commands."""
import tldr
await self._ensure_cache()
commands = await asyncio.to_thread(tldr.get_commands)
return [self._clean_command_name(cmd) for cmd in commands]
|
search_commands
async
search_commands(query: str) -> list[str]
Search for commands matching query.
Source code in src/clinspector/help_providers/tldr_pages.py
| async def search_commands(self, query: str) -> list[str]:
"""Search for commands matching query."""
import tldr
await self._ensure_cache()
commands = await asyncio.to_thread(tldr.get_commands)
return [
self._clean_command_name(cmd)
for cmd in commands
if query.lower() in self._clean_command_name(cmd).lower()
]
|
:fa-brands-github: Show source on GitHub