Skip to content

DiagnosticRunner

🛈 DocStrings

Run diagnostics using CLI tools.

Works with any command executor (local subprocess, Docker, SSH, etc.) to run CLI diagnostic tools and parse their output.

Source code in src/anyenv/lsp_servers/_runner.py
class DiagnosticRunner:
    """Run diagnostics using CLI tools.

    Works with any command executor (local subprocess, Docker, SSH, etc.) to run
    CLI diagnostic tools and parse their output.
    """

    def __init__(self, executor: CommandExecutor | None = None) -> None:
        """Initialize with an optional command executor.

        Args:
            executor: Callable to execute commands. Defaults to local subprocess.
        """
        self._executor = executor or _default_executor
        self._servers: list[LSPServerInfo] = []

    def register(self, server: LSPServerInfo) -> None:
        """Register an LSP server for diagnostics."""
        if server.has_cli_diagnostics:
            self._servers.append(server)

    def register_defaults(self) -> None:
        """Register all default servers with CLI diagnostic support."""
        from anyenv.lsp_servers._servers import ALL_SERVERS

        for server in ALL_SERVERS:
            if server.has_cli_diagnostics:
                self.register(server)

    def get_server(self, server_id: str) -> LSPServerInfo | None:
        """Get a server by ID."""
        return next((s for s in self._servers if s.id == server_id), None)

    def get_servers_for_file(self, path: str) -> list[LSPServerInfo]:
        """Get all servers that can handle a file."""
        ext = posixpath.splitext(path)[1]
        return [s for s in self._servers if s.can_handle(ext)]

    async def run(self, server: LSPServerInfo | str, files: list[str]) -> DiagnosticsResult:
        """Run diagnostics using a specific server.

        Args:
            server: Server instance or server ID
            files: File paths to check

        Returns:
            DiagnosticsResult with parsed diagnostics
        """
        if isinstance(server, str):
            srv = self.get_server(server)
            if srv is None:
                msg = f"Server {server!r} not found"
                return DiagnosticsResult(diagnostics=[], success=False, duration=0.0, error=msg)
            server = srv

        if not server.has_cli_diagnostics:
            msg = f"Server {server.id!r} has no CLI diagnostic support"
            return DiagnosticsResult(diagnostics=[], success=False, duration=0.0, error=msg)

        command = server.build_diagnostic_command(files)
        result = await self._executor(command)
        diagnostics = server.parse_diagnostics(result.stdout or "", result.stderr or "")
        # Parsing succeeded, even if there are errors
        return DiagnosticsResult(diagnostics=diagnostics, success=True, duration=result.duration)

    async def run_all(
        self, files: list[str], *, concurrency: int = 1
    ) -> dict[str, DiagnosticsResult]:
        """Run all applicable servers on the given files.

        Args:
            files: File paths to check
            concurrency: How many servers may run at once. The default runs them one
                after another (safe for remote executors and slow machines).

        Returns:
            Dict mapping server ID to DiagnosticsResult, in registration order
        """
        if concurrency < 1:
            msg = f"concurrency must be at least 1, got {concurrency}"
            raise ValueError(msg)
        # Each applicable server gets all the files it handles, whatever the extension.
        files_by_server: dict[str, tuple[LSPServerInfo, list[str]]] = {}
        for server in self._servers:
            server_files = [f for f in files if server.can_handle(posixpath.splitext(f)[1])]
            if server_files and server.id not in files_by_server:
                files_by_server[server.id] = (server, server_files)

        semaphore = asyncio.Semaphore(concurrency)

        async def run_one(server: LSPServerInfo, server_files: list[str]) -> DiagnosticsResult:
            async with semaphore:
                return await self.run(server, server_files)

        results = await asyncio.gather(*(run_one(s, f) for s, f in files_by_server.values()))
        return dict(zip(files_by_server, results, strict=True))

    async def run_for_file(self, path: str) -> list[Diagnostic]:
        """Run all applicable servers on a single file.

        Args:
            path: File path to check

        Returns:
            Combined list of diagnostics from all applicable servers
        """
        all_diagnostics: list[Diagnostic] = []
        for server in self.get_servers_for_file(path):
            result = await self.run(server, [path])
            all_diagnostics.extend(result.diagnostics)

        return all_diagnostics

__init__

__init__(executor: CommandExecutor | None = None) -> None

Initialize with an optional command executor.

Parameters:

Name Type Description Default
executor CommandExecutor | None

Callable to execute commands. Defaults to local subprocess.

None
Source code in src/anyenv/lsp_servers/_runner.py
def __init__(self, executor: CommandExecutor | None = None) -> None:
    """Initialize with an optional command executor.

    Args:
        executor: Callable to execute commands. Defaults to local subprocess.
    """
    self._executor = executor or _default_executor
    self._servers: list[LSPServerInfo] = []

get_server

get_server(server_id: str) -> LSPServerInfo | None

Get a server by ID.

Source code in src/anyenv/lsp_servers/_runner.py
def get_server(self, server_id: str) -> LSPServerInfo | None:
    """Get a server by ID."""
    return next((s for s in self._servers if s.id == server_id), None)

get_servers_for_file

get_servers_for_file(path: str) -> list[LSPServerInfo]

Get all servers that can handle a file.

Source code in src/anyenv/lsp_servers/_runner.py
def get_servers_for_file(self, path: str) -> list[LSPServerInfo]:
    """Get all servers that can handle a file."""
    ext = posixpath.splitext(path)[1]
    return [s for s in self._servers if s.can_handle(ext)]

register

register(server: LSPServerInfo) -> None

Register an LSP server for diagnostics.

Source code in src/anyenv/lsp_servers/_runner.py
def register(self, server: LSPServerInfo) -> None:
    """Register an LSP server for diagnostics."""
    if server.has_cli_diagnostics:
        self._servers.append(server)

register_defaults

register_defaults() -> None

Register all default servers with CLI diagnostic support.

Source code in src/anyenv/lsp_servers/_runner.py
def register_defaults(self) -> None:
    """Register all default servers with CLI diagnostic support."""
    from anyenv.lsp_servers._servers import ALL_SERVERS

    for server in ALL_SERVERS:
        if server.has_cli_diagnostics:
            self.register(server)

run async

run(server: LSPServerInfo | str, files: list[str]) -> DiagnosticsResult

Run diagnostics using a specific server.

Parameters:

Name Type Description Default
server LSPServerInfo | str

Server instance or server ID

required
files list[str]

File paths to check

required

Returns:

Type Description
DiagnosticsResult

DiagnosticsResult with parsed diagnostics

Source code in src/anyenv/lsp_servers/_runner.py
async def run(self, server: LSPServerInfo | str, files: list[str]) -> DiagnosticsResult:
    """Run diagnostics using a specific server.

    Args:
        server: Server instance or server ID
        files: File paths to check

    Returns:
        DiagnosticsResult with parsed diagnostics
    """
    if isinstance(server, str):
        srv = self.get_server(server)
        if srv is None:
            msg = f"Server {server!r} not found"
            return DiagnosticsResult(diagnostics=[], success=False, duration=0.0, error=msg)
        server = srv

    if not server.has_cli_diagnostics:
        msg = f"Server {server.id!r} has no CLI diagnostic support"
        return DiagnosticsResult(diagnostics=[], success=False, duration=0.0, error=msg)

    command = server.build_diagnostic_command(files)
    result = await self._executor(command)
    diagnostics = server.parse_diagnostics(result.stdout or "", result.stderr or "")
    # Parsing succeeded, even if there are errors
    return DiagnosticsResult(diagnostics=diagnostics, success=True, duration=result.duration)

run_all async

run_all(files: list[str], *, concurrency: int = 1) -> dict[str, DiagnosticsResult]

Run all applicable servers on the given files.

Parameters:

Name Type Description Default
files list[str]

File paths to check

required
concurrency int

How many servers may run at once. The default runs them one after another (safe for remote executors and slow machines).

1

Returns:

Type Description
dict[str, DiagnosticsResult]

Dict mapping server ID to DiagnosticsResult, in registration order

Source code in src/anyenv/lsp_servers/_runner.py
async def run_all(
    self, files: list[str], *, concurrency: int = 1
) -> dict[str, DiagnosticsResult]:
    """Run all applicable servers on the given files.

    Args:
        files: File paths to check
        concurrency: How many servers may run at once. The default runs them one
            after another (safe for remote executors and slow machines).

    Returns:
        Dict mapping server ID to DiagnosticsResult, in registration order
    """
    if concurrency < 1:
        msg = f"concurrency must be at least 1, got {concurrency}"
        raise ValueError(msg)
    # Each applicable server gets all the files it handles, whatever the extension.
    files_by_server: dict[str, tuple[LSPServerInfo, list[str]]] = {}
    for server in self._servers:
        server_files = [f for f in files if server.can_handle(posixpath.splitext(f)[1])]
        if server_files and server.id not in files_by_server:
            files_by_server[server.id] = (server, server_files)

    semaphore = asyncio.Semaphore(concurrency)

    async def run_one(server: LSPServerInfo, server_files: list[str]) -> DiagnosticsResult:
        async with semaphore:
            return await self.run(server, server_files)

    results = await asyncio.gather(*(run_one(s, f) for s, f in files_by_server.values()))
    return dict(zip(files_by_server, results, strict=True))

run_for_file async

run_for_file(path: str) -> list[Diagnostic]

Run all applicable servers on a single file.

Parameters:

Name Type Description Default
path str

File path to check

required

Returns:

Type Description
list[Diagnostic]

Combined list of diagnostics from all applicable servers

Source code in src/anyenv/lsp_servers/_runner.py
async def run_for_file(self, path: str) -> list[Diagnostic]:
    """Run all applicable servers on a single file.

    Args:
        path: File path to check

    Returns:
        Combined list of diagnostics from all applicable servers
    """
    all_diagnostics: list[Diagnostic] = []
    for server in self.get_servers_for_file(path):
        result = await self.run(server, [path])
        all_diagnostics.extend(result.diagnostics)

    return all_diagnostics

:fa-brands-github: Show source on GitHub