Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 14 additions & 13 deletions bundled/tool/_debug_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,23 +15,24 @@ def update_sys_path(path_to_add: str) -> None:


# Ensure debugger is loaded before we load anything else, to debug initialization.
debugger_path = os.getenv("DEBUGPY_PATH", None)
if debugger_path:
if debugger_path.endswith("debugpy"):
debugger_path = os.fspath(pathlib.Path(debugger_path).parent)
if os.getenv("USE_DEBUGPY", "").strip().lower() in ["true", "1", "t", "yes"]:
debugger_path = os.getenv("DEBUGPY_PATH", None)
if debugger_path:
if debugger_path.endswith("debugpy"):
debugger_path = os.fspath(pathlib.Path(debugger_path).parent)

update_sys_path(debugger_path)
update_sys_path(debugger_path)

import debugpy
import debugpy

# 5678 is the default port, If you need to change it update it here
# and in launch.json.
debugpy.connect(5678)
# 5678 is the default port, If you need to change it update it here
# and in launch.json.
debugpy.connect(5678)

# This will ensure that execution is paused as soon as the debugger
# connects to VS Code. If you don't want to pause here comment this
# line and set breakpoints as appropriate.
debugpy.breakpoint()
# This will ensure that execution is paused as soon as the debugger
# connects to VS Code. If you don't want to pause here comment this
# line and set breakpoints as appropriate.
debugpy.breakpoint()

SERVER_PATH = os.fspath(pathlib.Path(__file__).parent / "lsp_server.py")
# NOTE: Set breakpoint in `server.py` before continuing.
Expand Down
15 changes: 13 additions & 2 deletions bundled/tool/lsp_jsonrpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import contextlib
import io
import json
import os
import pathlib
import subprocess
import threading
Expand Down Expand Up @@ -135,13 +136,23 @@ def stop_all_processes(self):
i.send_data({"id": str(uuid.uuid4()), "method": "exit"})
self._thread_pool.shutdown(wait=False)

def start_process(self, workspace: str, args: Sequence[str], cwd: str) -> None:
def start_process(
self,
workspace: str,
args: Sequence[str],
cwd: str,
env: Optional[Dict[str, str]] = None,
) -> None:
"""Starts a process and establishes JSON-RPC communication over stdio."""
_env = os.environ.copy()
if env is not None:
_env.update(env)
proc = subprocess.Popen(
args,
cwd=cwd,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
env=_env,
)
self._processes[workspace] = proc
self._rpc[workspace] = create_json_rpc(proc.stdout, proc.stdin)
Expand Down Expand Up @@ -212,7 +223,7 @@ def run_over_json_rpc(
"""Uses JSON-RPC to execute a command."""
rpc: Union[JsonRpc, None] = get_or_start_json_rpc(workspace, interpreter, cwd)
if not rpc:
raise Exception("Failed to run over JSON-RPC.")
raise ConnectionError("Failed to run over JSON-RPC.")

msg_id = str(uuid.uuid4())
msg = {
Expand Down
13 changes: 13 additions & 0 deletions bundled/tool/lsp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -697,6 +697,19 @@ def _get_settings_by_document(document: TextDocument | None):
}


def _get_settings_by_path(file_path: pathlib.Path):
workspaces = {s["workspaceFS"] for s in WORKSPACE_SETTINGS.values()}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot generated:
-706

Key/value mismatch causes KeyError on happy path. workspaces is a set of workspaceFS field values, but WORKSPACE_SETTINGS[str_file_path] indexes the dict by key. If the dict is keyed by URI (as is standard in LSP servers and consistent with sibling _get_settings_by_document), this crashes on every successful match.

Fix: iterate items and match on value directly:

for _key, settings in WORKSPACE_SETTINGS.items():
    if settings["workspaceFS"] == str_file_path:
        return settings

Or build a reverse mapping {s["workspaceFS"]: s for s in WORKSPACE_SETTINGS.values()}.


while file_path != file_path.parent:
str_file_path = utils.normalize_path(file_path)
if str_file_path in workspaces:
return WORKSPACE_SETTINGS[str_file_path]
file_path = file_path.parent

setting_values = list(WORKSPACE_SETTINGS.values())
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot generated:
-710

Unguarded [0] index crashes on empty WORKSPACE_SETTINGS. If no workspaces are registered (e.g., during initialization or edge-case startup), list(WORKSPACE_SETTINGS.values()) is [] and this raises IndexError. While the Advocate notes this mirrors _get_settings_by_document, new code should not replicate latent bugs. Add a guard:

if not setting_values:
    return {}  # or raise a descriptive error

return setting_values[0]


# *****************************************************
# Internal execution APIs.
# *****************************************************
Expand Down
5 changes: 3 additions & 2 deletions src/common/envFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@
import { traceInfo, traceWarn } from './logging';
import { getConfiguration } from './vscodeapi';

function expandTilde(value: string): string {
const home = process.env.HOME || process.env.USERPROFILE || '';
export function expandTilde(value: string): string {
const home = process.env.HOME || process.env.USERPROFILE;
if (!home) return value;

Check warning on line 13 in src/common/envFile.ts

View workflow job for this annotation

GitHub Actions / Lint

Expected { after 'if' condition

Check warning on line 13 in src/common/envFile.ts

View workflow job for this annotation

GitHub Actions / Lint

Expected { after 'if' condition

Check warning on line 13 in src/common/envFile.ts

View workflow job for this annotation

GitHub Actions / TypeScript Tests (ubuntu-latest)

Expected { after 'if' condition

Check warning on line 13 in src/common/envFile.ts

View workflow job for this annotation

GitHub Actions / TypeScript Tests (ubuntu-latest)

Expected { after 'if' condition

Check warning on line 13 in src/common/envFile.ts

View workflow job for this annotation

GitHub Actions / TypeScript Tests (windows-latest)

Expected { after 'if' condition

Check warning on line 13 in src/common/envFile.ts

View workflow job for this annotation

GitHub Actions / TypeScript Tests (windows-latest)

Expected { after 'if' condition
if (value === '~') {
return home;
}
Expand Down
8 changes: 1 addition & 7 deletions src/common/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { traceLog, traceWarn } from './logging';
import { getInterpreterDetails } from './python';
import { getConfiguration, getWorkspaceFolders } from './vscodeapi';
import { getInterpreterFromSetting } from './utilities';
import { expandTilde } from './envFile';

/* eslint-disable @typescript-eslint/naming-convention */
const DEFAULT_SEVERITY: Record<string, string> = {
Expand Down Expand Up @@ -149,13 +150,6 @@ export async function getWorkspaceSettings(
return workspaceSetting;
}

function expandTilde(value: string): string {
const home = process.env.HOME || process.env.USERPROFILE || '';
if (value === '~') return home;
if (value.startsWith('~/') || value.startsWith('~\\')) return home + value.slice(1);
return value;
}

function getGlobalValue<T>(config: WorkspaceConfiguration, key: string, defaultValue: T): T {
const inspect = config.inspect<T>(key);
return inspect?.globalValue ?? inspect?.defaultValue ?? defaultValue;
Expand Down
Loading