Skip to content

tldr_pages

Class info

Classes

Name Children Inherits
TldrExample
clinspector.help_providers.tldr_pages
Example collected during parsing.
    TldrProvider
    clinspector.help_providers.tldr_pages
    Provider for tldr-pages help.

      🛈 DocStrings

      tldr-pages provider implementation.

      TldrExample dataclass

      Example collected during parsing.

      Source code in src/clinspector/help_providers/tldr_pages.py
      @dataclass
      class TldrExample:
          """Example collected during parsing."""
      
          description: str
          command: str = ""
          placeholders: dict[str, str] = field(default_factory=dict)
      
          def to_example(self) -> Example:
              """Convert to CommandInfo Example."""
              return Example(
                  description=self.description,
                  command=self.command,
                  placeholders=self.placeholders,
              )
      

      to_example

      to_example() -> Example
      

      Convert to CommandInfo Example.

      Source code in src/clinspector/help_providers/tldr_pages.py
      def to_example(self) -> Example:
          """Convert to CommandInfo Example."""
          return Example(
              description=self.description,
              command=self.command,
              placeholders=self.placeholders,
          )
      

      TldrProvider

      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__

      __init__() -> None
      

      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_command_help(command: str) -> CommandHelp
      

      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()
          ]