дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-27 21:12:34 +02:00
Settings → Python → All Interpreters gets **Show Paths for Selected Interpreter** (toolbar and context menu). The dialog lists the interpreter's own `sys.path` (queried from the interpreter on a blocking thread, cancellable, with a reload button) and lets you add and remove folders outside the project. Until now there was no way to see `sys.path` or to put such a folder on the import path short of setting `PYTHONPATH` by hand in every run configuration. Added folders are saved per interpreter in the global settings layer (`languages.python.interpreterPaths`, keyed by the interpreter's executable, like the interpreter list itself), so they apply to every project that uses the interpreter, as in PyCharm. They follow the interpreter that is actually used: basedpyright / Pyright get them as `extraPaths` for the interpreter that server analyses with, and run, debug, tests and the Python Console get them on `PYTHONPATH` for the interpreter the launch names (else the one of the project or workspace member it runs in), so Run and Debug of the same file agree. They are listed under External Libraries unless they are inside or around the project's own folders, which stay editable. A folder that no longer exists is marked **Missing**, one `PYTHONPATH` cannot hold (not absolute, or with its separator in the name) is marked **Invalid**; neither is passed on. Duplicates and folders already on `sys.path` are not added. Removing an interpreter from the list drops its folders. Not in this PR: removing the interpreter's own entries (PyCharm's excluded paths); ty, pyrefly, pylsp and notebook kernels don't get the folders. Docker / Compose run targets are not rows of this list, so they have no paths dialog. Co-authored-by: wildcatDownstairs <[email protected]>
137 рядки
5.5 KiB
Rust
137 рядки
5.5 KiB
Rust
use crate::project::Project;
|
||
use ide_core::IdeResult;
|
||
use ide_dap::LaunchConfig;
|
||
use ide_workspace::roots::RootKind;
|
||
use std::collections::BTreeMap;
|
||
use std::path::{Path, PathBuf};
|
||
|
||
pub(super) fn paths(project: &Project) -> Vec<PathBuf> {
|
||
let mut paths = vec![project.root.clone()];
|
||
paths.extend(project.content_roots());
|
||
for root in project.roots().roots {
|
||
if matches!(root.kind, RootKind::Source | RootKind::Test) {
|
||
let path = project.root.join(root.path);
|
||
if !paths.contains(&path) {
|
||
paths.push(path);
|
||
}
|
||
}
|
||
}
|
||
paths
|
||
}
|
||
|
||
/// `paths` plus the folders added to the paths of the interpreter a launch uses (All
|
||
/// Interpreters › Show Paths): `command` when it names a Python executable, else the
|
||
/// interpreter of the project or workspace member at `near`. Run, Debug and the console
|
||
/// resolve it the same way, so the same file imports the same modules in each.
|
||
pub(super) fn with_user_paths(
|
||
mut paths: Vec<PathBuf>,
|
||
config_dir: &Path,
|
||
project: &Project,
|
||
command: Option<&str>,
|
||
near: Option<&Path>,
|
||
) -> Vec<PathBuf> {
|
||
let named = command
|
||
.filter(|c| ide_sdk::apply::is_python_command(c))
|
||
.map(PathBuf::from)
|
||
.filter(|p| p.is_absolute() && p.is_file())
|
||
.map(|p| ide_core::project_roots::resolve(&project.root, &p));
|
||
let python = named.or_else(|| super::sdk::effective_python(config_dir, project, near));
|
||
if let Some(python) = python {
|
||
for path in ide_sdk::apply::interpreter_user_paths(&python, &project.settings.effective()) {
|
||
if !paths.contains(&path) {
|
||
paths.push(path);
|
||
}
|
||
}
|
||
}
|
||
paths
|
||
}
|
||
|
||
/// The interpreter a debugpy launch names (`"python": "<executable>"`), if it names one.
|
||
pub(super) fn debug_python(config: &LaunchConfig) -> Option<String> {
|
||
let extra: serde_json::Value = serde_json::from_str(config.extra_json.as_deref()?).ok()?;
|
||
extra.get("python")?.as_str().map(str::to_owned)
|
||
}
|
||
|
||
pub(super) fn prepare_debug(config: &mut LaunchConfig, paths: &[PathBuf]) -> IdeResult<()> {
|
||
// Adapter-specific env takes precedence over the common launch fields in DAP.
|
||
let mut extra: Option<serde_json::Value> = config.extra_json.as_deref().and_then(|s| serde_json::from_str(s).ok());
|
||
// A custom adapter may run on another host; local paths are not portable.
|
||
if extra.as_ref().is_some_and(|e| e.get("debugServer").is_some()) {
|
||
return Ok(());
|
||
}
|
||
if let Some(env) = extra.as_mut().and_then(|e| e.get_mut("env")) {
|
||
if env.is_null() {
|
||
*env = serde_json::json!({});
|
||
}
|
||
if !env.is_object() {
|
||
return Ok(());
|
||
}
|
||
let mut vars = BTreeMap::new();
|
||
if let Some(value) = env.get("PYTHONPATH").and_then(|v| v.as_str()) {
|
||
vars.insert("PYTHONPATH".into(), value.to_owned());
|
||
}
|
||
ide_run::python_path::extend(&mut vars, paths, env.get("PYTHONPATH").is_none())?;
|
||
env["PYTHONPATH"] = serde_json::json!(vars["PYTHONPATH"]);
|
||
config.extra_json = extra.map(|e| e.to_string());
|
||
} else {
|
||
ide_run::python_path::extend(&mut config.env, paths, true)?;
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
#[test]
|
||
fn debug_preserves_remote_paths_and_handles_null_env() {
|
||
let root = std::env::temp_dir().join("project");
|
||
let mut config = LaunchConfig {
|
||
name: "Python".into(),
|
||
adapter: "debugpy".into(),
|
||
request: "launch".into(),
|
||
program: None,
|
||
args: vec![],
|
||
cwd: None,
|
||
env: BTreeMap::new(),
|
||
extra_json: Some(serde_json::json!({"env": null, "debugServer": "remote:5678"}).to_string()),
|
||
};
|
||
let before = config.extra_json.clone();
|
||
prepare_debug(&mut config, std::slice::from_ref(&root)).unwrap();
|
||
assert_eq!(config.extra_json, before);
|
||
assert!(config.env.is_empty());
|
||
config.extra_json = Some(serde_json::json!({"env": null}).to_string());
|
||
prepare_debug(&mut config, std::slice::from_ref(&root)).unwrap();
|
||
let value: serde_json::Value = serde_json::from_str(config.extra_json.as_deref().unwrap()).unwrap();
|
||
let paths = std::env::split_paths(value["env"]["PYTHONPATH"].as_str().unwrap()).collect::<Vec<_>>();
|
||
assert_eq!(paths[0], root);
|
||
}
|
||
|
||
#[test]
|
||
fn debug_uses_the_effective_environment_field() {
|
||
for extra in [false, true] {
|
||
let root = std::env::temp_dir().join("project");
|
||
let vendor = root.join("vendor");
|
||
let vars = BTreeMap::from([("PYTHONPATH".into(), vendor.to_string_lossy().into_owned())]);
|
||
let mut config = LaunchConfig {
|
||
name: "Python".into(),
|
||
adapter: "debugpy".into(),
|
||
request: "launch".into(),
|
||
program: Some("app/main.py".into()),
|
||
args: vec![],
|
||
cwd: None,
|
||
env: vars.clone(),
|
||
extra_json: extra.then(|| serde_json::json!({"env": vars}).to_string()),
|
||
};
|
||
prepare_debug(&mut config, std::slice::from_ref(&root)).unwrap();
|
||
let vars: BTreeMap<String, String> = if extra {
|
||
let value: serde_json::Value = serde_json::from_str(config.extra_json.as_deref().unwrap()).unwrap();
|
||
serde_json::from_value(value["env"].clone()).unwrap()
|
||
} else {
|
||
config.env
|
||
};
|
||
assert_eq!(std::env::split_paths(&vars["PYTHONPATH"]).collect::<Vec<_>>(), [root, vendor]);
|
||
}
|
||
}
|
||
}
|