From 9a3b97a5fa09b764f4074cb785c3cd339df0fd49 Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Sun, 22 Nov 2026 15:43:09 +0900 Subject: [PATCH] feat(python): flag requirements the interpreter does not satisfy and offer to install them (#5168) `requirements*.txt` and `pyproject.toml` (`[project]` dependencies, optional dependencies, `[dependency-groups]`) now mark each requirement the project's interpreter doesn't have installed, or whose installed version misses the specifier. A banner offers Install requirements, and the quick fixes are Install requirement and Install all missing requirements; installs use the same pip/uv path as the interpreter settings page, run as a background task, report failures in one notification and re-check the file. The interpreter judges the requirements itself (with `packaging` or pip's vendored copy), so PEP 440 specifiers, PEP 503 names and markers behave as pip does; Rust only parses the files for spans, skipping `-r`, `-e`, options, URLs and paths. Nothing is checked without a local interpreter, for a container interpreter, or in Restricted Mode. It is a new inspection, "Unsatisfied package requirements", and the Cargo version check now shares the same editor plugin (`manifestCheck.ts`). Closes #5147 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- crates/ide-host/src/ops/dependencies.rs | 101 +++++++- crates/ide-host/src/ops/sdk.rs | 55 +++-- crates/ide-sdk/src/python.rs | 78 ++++++- crates/ide-sdk/src/tests.rs | 44 ++++ crates/ide-workspace/src/dependencies/mod.rs | 18 ++ .../ide-workspace/src/dependencies/python.rs | 193 +++++++++++++++ src-tauri/tests/commands.snap | 1 + src/bindings.ts | 22 ++ src/features/dependencies/index.ts | 139 +++-------- src/features/dependencies/manifestCheck.ts | 112 +++++++++ src/features/dependencies/python.test.ts | 143 ++++++++++++ src/features/dependencies/python.ts | 221 ++++++++++++++++++ .../settings/__tests__/inspections.test.ts | 3 +- src/platform/inspections.ts | 11 + src/platform/locales/text/en.json | 10 + src/platform/locales/text/zh.json | 10 + 16 files changed, 1030 insertions(+), 131 deletions(-) create mode 100644 crates/ide-workspace/src/dependencies/python.rs create mode 100644 src/features/dependencies/manifestCheck.ts create mode 100644 src/features/dependencies/python.test.ts create mode 100644 src/features/dependencies/python.ts diff --git a/crates/ide-host/src/ops/dependencies.rs b/crates/ide-host/src/ops/dependencies.rs index 469cc8a90..a97e0344e 100644 --- a/crates/ide-host/src/ops/dependencies.rs +++ b/crates/ide-host/src/ops/dependencies.rs @@ -2,7 +2,10 @@ use crate::Host; use ide_command::command; use ide_core::{CancellationToken, DocId, IdeError, IdeResult, RequestId}; -use ide_workspace::dependencies::{DependencyVersionSource, DependencyVersions, cargo, go, maven, npm}; +use ide_workspace::dependencies::{ + DependencyVersionSource, DependencyVersions, PythonRequirements, UnsatisfiedRequirement, cargo, go, maven, npm, + python, +}; use std::collections::BTreeMap; use std::hash::{DefaultHasher, Hash, Hasher}; use std::path::{Path, PathBuf}; @@ -254,6 +257,50 @@ pub async fn dependency_versions( result } +/// The requirements of a `requirements*.txt` / `pyproject.toml` the project's interpreter +/// doesn't satisfy; `None` for other files, or with no local interpreter to ask. +#[command(trust = trusted)] +pub async fn python_requirements( + host: &Host, + window: &str, + doc: DocId, + request: RequestId, +) -> IdeResult> { + let project = host.project(window)?; + let config_dir = host.config_dir.clone(); + let cancel = host.begin_project_read_request(window, request); + let result = host + .blocking(move || { + let snap = project.documents.snapshot(doc)?; + let name = snap.path.file_name().and_then(|n| n.to_str()).unwrap_or_default(); + if snap.large || snap.read_only { + return Ok(None); + } + let dependencies = python::requirements(name, &snap.text); + if dependencies.is_empty() { + return Ok(None); + } + // Running the interpreter runs project code (sitecustomize, .pth files). + project.require_trust()?; + let Some(python) = crate::ops::sdk::effective_python(&config_dir, &project, snap.path.parent()) else { + return Ok(None); + }; + let requirements: Vec<&str> = dependencies.iter().map(|d| d.requirement.as_str()).collect(); + let states = ide_sdk::python::unsatisfied_requirements(&python, &requirements, &cancel)?; + let unsatisfied = dependencies + .into_iter() + .zip(states) + .filter_map(|(dependency, state)| { + state.map(|s| UnsatisfiedRequirement { dependency, installed: s.installed }) + }) + .collect(); + Ok(Some(PythonRequirements { python: python.into(), unsatisfied })) + }) + .await; + host.end_request(request); + result +} + #[cfg(test)] mod tests { use super::*; @@ -313,6 +360,56 @@ mod tests { host.close_project("main"); } + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn requirements_are_checked_against_the_project_virtualenv() { + let Some(base) = ide_core::tool_path::find_command( + "python3", + &ide_core::tool_path::search_path_in(&std::env::temp_dir()), + &std::env::temp_dir(), + ) else { + return; + }; + let temp = tempfile::tempdir().unwrap(); + let base_dir = dunce::canonicalize(temp.path()).unwrap(); + let root = base_dir.join("project"); + std::fs::create_dir(&root).unwrap(); + let status = std::process::Command::new(base) + .args(["-I", "-m", "venv", "--without-pip"]) + .arg(root.join(".venv")) + .status() + .unwrap(); + assert!(status.success()); + let text = "# 中文\nopenidea-missing-xyz>=1\n-r other.txt\n"; + let path = root.join("requirements.txt"); + std::fs::write(&path, text).unwrap(); + let host = Host::new(HostConfig { + config_dir: base_dir.join("config"), + data_dir: base_dir.join("data"), + local_data_dir: base_dir.join("local"), + languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()), + syntax: Arc::default(), + sink_for: Box::new(|_| Arc::new(|_| {})), + owner: |w| w, + runtime: tokio::runtime::Handle::current(), + project_environment: false, + }); + let project = host.open_project("main", &root).unwrap(); + let info = project.documents.open(&path).unwrap(); + // Restricted Mode never runs the interpreter. + assert!(python_requirements(&host, "main", info.id, RequestId(429)).await.is_err()); + project.trusted.store(true, std::sync::atomic::Ordering::Release); + let found = python_requirements(&host, "main", info.id, RequestId(430)).await.unwrap().unwrap(); + assert!(found.python.0.starts_with(root.join(".venv"))); + assert_eq!(found.unsatisfied.len(), 1); + assert_eq!(found.unsatisfied[0].dependency.package, "openidea-missing-xyz"); + assert_eq!(found.unsatisfied[0].installed, None); + let other = root.join("notes.txt"); + std::fs::write(&other, text).unwrap(); + let info = project.documents.open(&other).unwrap(); + assert!(python_requirements(&host, "main", info.id, RequestId(431)).await.unwrap().is_none()); + host.close_project("main"); + } + struct CachedNpm; impl DependencyVersionSource for CachedNpm { fn id(&self) -> &'static str { @@ -361,4 +458,4 @@ mod tests { } } -ide_command::domain!(dependencies: dependency_versions); +ide_command::domain!(dependencies: dependency_versions, python_requirements); diff --git a/crates/ide-host/src/ops/sdk.rs b/crates/ide-host/src/ops/sdk.rs index 71845a61c..54a7f8231 100644 --- a/crates/ide-host/src/ops/sdk.rs +++ b/crates/ide-host/src/ops/sdk.rs @@ -120,6 +120,33 @@ pub async fn sdk_python_interpreter(host: &Host, window: &str, path: PathBuf) -> .map_err(join_err)? } +/// The interpreter of the workspace member `near` belongs to, else the project's. +pub(crate) fn effective_python( + config_dir: &std::path::Path, + project: &crate::Project, + near: Option<&std::path::Path>, +) -> Option { + let project_root = &project.root; + let member = ide_workspace::workspace::Workspace::load(project_root).ok().flatten().and_then(|w| { + let near = near?; + w.projects.into_iter().filter(|root| near.starts_with(root)).max_by_key(|root| root.components().count()) + }); + let (root, settings) = match member { + Some(root) => { + let settings = ide_workspace::SettingsStore::load(config_dir, Some(&root)).effective(); + (root, settings) + } + None => (project_root.clone(), project.settings.effective()), + }; + // A member with no Python of its own falls back to the primary project's + // (the same chain run configurations use), so every answer names one interpreter. + ide_sdk::apply::python_interpreter_near(&root, near, &settings).or_else(|| { + (&root != project_root) + .then(|| ide_sdk::apply::python_interpreter(project_root, &project.settings.effective())) + .flatten() + }) +} + /// The interpreter the project uses: the configured one, else its virtualenv. #[command(trust = trusted)] pub async fn sdk_python_effective( @@ -129,31 +156,11 @@ pub async fn sdk_python_effective( ) -> IdeResult> { host.require_trust(window)?; let project = host.project(window)?; - let (config_dir, project_root) = (host.config_dir.clone(), project.root.clone()); + let config_dir = host.config_dir.clone(); // Loading a member's settings needs more stack than a sync command's main thread has left. - tokio::task::spawn_blocking(move || { - let member = ide_workspace::workspace::Workspace::load(&project_root).ok().flatten().and_then(|w| { - let near = near.as_deref()?; - w.projects.into_iter().filter(|root| near.starts_with(root)).max_by_key(|root| root.components().count()) - }); - let (root, settings) = match member { - Some(root) => { - let settings = ide_workspace::SettingsStore::load(&config_dir, Some(&root)).effective(); - (root, settings) - } - None => (project_root.clone(), project.settings.effective()), - }; - // A member with no Python of its own falls back to the primary project's - // (the same chain run configurations use), so every answer names one interpreter. - let interpreter = ide_sdk::apply::python_interpreter_near(&root, near.as_deref(), &settings).or_else(|| { - (root != project_root) - .then(|| ide_sdk::apply::python_interpreter(&project_root, &project.settings.effective())) - .flatten() - }); - Ok(interpreter.map(Into::into)) - }) - .await - .map_err(join_err)? + tokio::task::spawn_blocking(move || Ok(effective_python(&config_dir, &project, near.as_deref()).map(Into::into))) + .await + .map_err(join_err)? } /// The PHP interpreter chosen in Settings › Languages & Frameworks › PHP; `None`: the `php` on `PATH`. diff --git a/crates/ide-sdk/src/python.rs b/crates/ide-sdk/src/python.rs index 98466971b..66a55048a 100644 --- a/crates/ide-sdk/src/python.rs +++ b/crates/ide-sdk/src/python.rs @@ -1,7 +1,7 @@ //! Python environments: creating virtualenvs and managing packages with pip //! (or `uv pip` for environments created by uv, which ship without pip). -use crate::exec::{query_in, stream, which}; +use crate::exec::{query_in, query_in_cancellable, stream, which}; use crate::{Sdk, bin_dir, exe, venv_of}; use ide_core::{CancellationToken, IdeError, IdeResult}; use serde::{Deserialize, Serialize}; @@ -320,6 +320,82 @@ pub fn install_package( stream(&program, &args, dir.as_ref().map(|d| d.path()), &pip_env(python), cancel, on_line).map(|_| ()) } +/// Run by the interpreter itself, so markers and PEP 440 specifiers are judged as pip would: +/// prints, per requirement of `argv[1]` (a JSON list), `null` when satisfied or not applicable +/// there, else `{"installed": }`. +const CHECK_REQUIREMENTS: &str = r#" +import json, re, sys +try: + from packaging.requirements import Requirement +except Exception: + try: + from pip._vendor.packaging.requirements import Requirement + except Exception: + Requirement = None +from importlib import metadata +norm = lambda n: re.sub(r"[-_.]+", "-", n).lower() +installed = {} +for d in metadata.distributions(): + name = d.metadata["Name"] + if name: + installed.setdefault(norm(name), d.version) +out = [] +for line in json.loads(sys.argv[1]): + try: + if Requirement: + r = Requirement(line) + name, spec, applies = r.name, r.specifier, r.marker is None or r.marker.evaluate({"extra": ""}) + else: + # Without packaging only names are compared; a marker can't be judged. + name, spec, applies = re.match(r"[A-Za-z0-9._-]+", line).group(0), None, ";" not in line + version = installed.get(norm(name)) + if not applies or (version is not None and (spec is None or spec.contains(version, prereleases=True))): + out.append(None) + else: + out.append({"installed": version}) + except Exception: + out.append(None) +print(json.dumps(out)) +"#; + +#[derive(Debug, Deserialize, PartialEq)] +pub struct Unsatisfied { + /// The version installed that misses the specifier; `None` when not installed. + pub installed: Option, +} + +/// Which of `requirements` (PEP 508 strings) `python` doesn't satisfy, in order; +/// `None` for satisfied ones, for ones whose marker excludes this interpreter, and +/// for ones it can't parse. +pub fn unsatisfied_requirements( + python: &Path, + requirements: &[&str], + cancel: &CancellationToken, +) -> IdeResult>> { + let list = serde_json::to_string(requirements).map_err(|e| IdeError::internal(e.to_string()))?; + let dir = neutral_dir().ok_or_else(|| IdeError::internal("no temporary directory"))?; + let out = query_in_cancellable( + python, + &["-c", CHECK_REQUIREMENTS, &list], + dir.path(), + &[], + Duration::from_secs(20), + cancel, + ); + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + let out = + out.ok_or_else(|| IdeError::unavailable(format!("cannot check requirements with {}", python.display())))?; + let json = out.lines().rev().find(|l| l.starts_with('[')).unwrap_or(""); + let result: Vec> = + serde_json::from_str(json).map_err(|e| IdeError::internal(format!("unexpected output: {e}")))?; + if result.len() != requirements.len() { + return Err(IdeError::internal("unexpected output: wrong number of results")); + } + Ok(result) +} + pub fn uninstall_package( python: &Path, name: &str, diff --git a/crates/ide-sdk/src/tests.rs b/crates/ide-sdk/src/tests.rs index 28786cc04..6c061a69a 100644 --- a/crates/ide-sdk/src/tests.rs +++ b/crates/ide-sdk/src/tests.rs @@ -6,6 +6,7 @@ use crate::apply::{ }; use crate::python::parse_pip_list; use crate::{bin_dir, exe, venv_of}; +use ide_core::CancellationToken; use ide_core::settings::Settings; use ide_language::LanguageServerConfig; use ide_run::RunConfig; @@ -3184,3 +3185,46 @@ fn server_command_paths_report_executables_set_for_built_in_servers() { ] ); } + +#[test] +fn unsatisfied_requirements_are_judged_by_the_interpreter() { + let Some(base) = crate::exec::which("python3").or_else(|| crate::exec::which("python")) else { return }; + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("env"); + // System site packages: pip's vendored `packaging` when the base has pip. + let status = std::process::Command::new(base) + .args(["-I", "-m", "venv", "--without-pip", "--system-site-packages"]) + .arg(&home) + .status() + .unwrap(); + assert!(status.success()); + let python = home.join(bin_dir()).join(exe("python")); + let site = std::process::Command::new(&python) + .args(["-c", "import sysconfig; print(sysconfig.get_paths()['purelib'])"]) + .output() + .unwrap(); + let site = std::path::PathBuf::from(String::from_utf8(site.stdout).unwrap().trim()); + let info = site.join("Fake.Dist_Pkg-1.0.dist-info"); + std::fs::create_dir_all(&info).unwrap(); + std::fs::write(info.join("METADATA"), "Metadata-Version: 2.1\nName: Fake.Dist_Pkg\nVersion: 1.0\n").unwrap(); + let packaging = std::process::Command::new(&python) + .args(["-c", "import pip._vendor.packaging.requirements"]) + .status() + .is_ok_and(|s| s.success()); + let cancel = CancellationToken::new(); + let found = crate::python::unsatisfied_requirements( + &python, + &[ + "fake-dist-pkg", + "FAKE_dist.pkg>=0.5", + "fake-dist-pkg>=2", + "openidea-not-installed-xyz[extra]==1", + "openidea-not-installed-xyz; sys_platform == 'nowhere'", + ], + &cancel, + ) + .unwrap(); + let missing = || Some(crate::python::Unsatisfied { installed: None }); + let old = packaging.then(|| crate::python::Unsatisfied { installed: Some("1.0".into()) }); + assert_eq!(found, [None, None, old, missing(), None]); +} diff --git a/crates/ide-workspace/src/dependencies/mod.rs b/crates/ide-workspace/src/dependencies/mod.rs index 9560c408c..f5449a85a 100644 --- a/crates/ide-workspace/src/dependencies/mod.rs +++ b/crates/ide-workspace/src/dependencies/mod.rs @@ -4,6 +4,7 @@ pub mod cargo; pub mod go; pub mod maven; pub mod npm; +pub mod python; pub use cache::VersionCache; use ide_core::{CancellationToken, IdeResult}; @@ -48,3 +49,20 @@ pub struct DependencyVersions { pub versions: Vec, pub update: Option, } + +/// A requirement the project's interpreter does not satisfy. +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct UnsatisfiedRequirement { + pub dependency: ManifestDependency, + /// The installed version that misses the specifier; `None` when not installed. + pub installed: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct PythonRequirements { + /// The interpreter checked, which installs go to. + pub python: ide_core::IpcPath, + pub unsatisfied: Vec, +} diff --git a/crates/ide-workspace/src/dependencies/python.rs b/crates/ide-workspace/src/dependencies/python.rs new file mode 100644 index 000000000..5a725d69e --- /dev/null +++ b/crates/ide-workspace/src/dependencies/python.rs @@ -0,0 +1,193 @@ +//! Python requirements in `requirements*.txt` and `pyproject.toml`. Whether one is +//! satisfied is up to the interpreter (`ide-sdk`): markers and PEP 440 depend on it. +use super::ManifestDependency; +use toml_edit::{Document, Item}; + +/// `requirements.txt`, `requirements-dev.txt`, `requirements/base.txt`'s siblings named alike. +pub fn is_requirements_file(name: &str) -> bool { + name.starts_with("requirements") && name.ends_with(".txt") +} + +/// The requirements of a manifest, by file name; `requirement` is the PEP 508 string +/// and `from..to` its UTF-16 span. +pub fn requirements(file_name: &str, text: &str) -> Vec { + if file_name == "pyproject.toml" { + pyproject(text) + } else if is_requirements_file(file_name) { + requirements_txt(text) + } else { + Vec::new() + } +} + +/// The distribution name a requirement starts with, if it names one (not a URL, path or archive). +fn named(requirement: &str) -> Option { + let end = requirement + .find(|c: char| !(c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))) + .unwrap_or(requirement.len()); + let name = requirement[..end].trim_end_matches(['.', '-', '_']); + let rest = requirement[end..].trim_start(); + if name.is_empty() + || !name.as_bytes()[0].is_ascii_alphanumeric() + || rest.starts_with([':', '/', '\\']) + || !rest.starts_with('@') && [".whl", ".zip", ".tar.gz", ".tgz"].iter().any(|ext| requirement.ends_with(ext)) + || requirement.contains("://") && !rest.starts_with(['@', '[']) + { + return None; + } + Some(ManifestDependency { package: name.to_owned(), requirement: requirement.to_owned(), from: 0, to: 0 }) +} + +fn utf16(text: &str, byte: usize) -> u32 { + text[..byte].encode_utf16().count() as u32 +} + +fn requirements_txt(text: &str) -> Vec { + let mut out = Vec::new(); + let mut start = 0; + for line in text.split_inclusive('\n') { + let line_start = start; + start += line.len(); + let body = line.trim_end_matches(['\n', '\r']); + // A comment starts the line or follows whitespace; per-requirement options (`--hash`) follow ` -`. + let cut = [" #", "\t#", " --", "\t--", " \\"].iter().filter_map(|m| body.find(m)).min().unwrap_or(body.len()); + let content = body[..cut].trim_end(); + let lead = content.len() - content.trim_start().len(); + let requirement = content.trim_start(); + if requirement.is_empty() || requirement.starts_with(['#', '-']) || is_continuation(text, line_start) { + continue; + } + if let Some(mut dep) = named(requirement) { + dep.from = utf16(text, line_start + lead); + dep.to = utf16(text, line_start + lead + requirement.len()); + out.push(dep); + } + } + out +} + +/// The previous physical line ends with `\`: this one continues it (its options). +fn is_continuation(text: &str, line_start: usize) -> bool { + text[..line_start].trim_end_matches(['\n', '\r']).ends_with('\\') +} + +fn pyproject(text: &str) -> Vec { + let Ok(doc) = text.parse::>() else { return Vec::new() }; + let mut arrays = Vec::new(); + if let Some(project) = doc.get("project").and_then(Item::as_table_like) { + arrays.extend(project.get("dependencies")); + if let Some(extras) = project.get("optional-dependencies").and_then(Item::as_table_like) { + arrays.extend(extras.iter().map(|(_, item)| item)); + } + } + // PEP 735 groups; `{ include-group = "…" }` entries aren't strings and are skipped. + if let Some(groups) = doc.get("dependency-groups").and_then(Item::as_table_like) { + arrays.extend(groups.iter().map(|(_, item)| item)); + } + let mut out = Vec::new(); + for value in arrays.into_iter().filter_map(Item::as_array).flat_map(|a| a.iter()) { + let (Some(requirement), Some(span)) = (value.as_str(), value.span()) else { continue }; + let Some(raw) = text.get(span.clone()) else { continue }; + let delimiter = if raw.starts_with("\"\"\"") || raw.starts_with("'''") { 3 } else { 1 }; + if let Some(mut dep) = named(requirement.trim()) { + dep.from = utf16(text, span.start + delimiter); + dep.to = utf16(text, span.end - delimiter); + out.push(dep); + } + } + out.sort_unstable_by_key(|d| d.from); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn names(deps: &[ManifestDependency], text: &str) -> Vec<(String, String)> { + let units: Vec = text.encode_utf16().collect(); + deps.iter() + .map(|d| { + let span = String::from_utf16(&units[d.from as usize..d.to as usize]).unwrap(); + assert_eq!(span, d.requirement, "span matches the requirement"); + (d.package.clone(), d.requirement.clone()) + }) + .collect() + } + + #[test] + fn requirements_txt_keeps_named_requirements_only() { + let text = "# 中文 😀 comment\n\ + Django>=4.2,<5 # web\n\ + typing_extensions\n\ + requests[socks]==2.31.0 ; python_version >= \"3.8\"\n\ + -r base.txt\n\ + --index-url https://pypi.org/simple\n\ + -e ./local\n\ + ./pkg\n\ + /abs/path\n\ + https://example.com/x.tar.gz\n\ + foo-1.0-py3-none-any.whl\n\ + pkg @ https://example.com/pkg.zip\n\ + numpy==1.26.4 \\\n --hash=sha256:abc \\\n --hash=sha256:def\n\ + \n \n\ + black --config-settings=x=y\n"; + let deps = requirements("requirements.txt", text); + assert_eq!( + names(&deps, text), + [ + ("Django", "Django>=4.2,<5"), + ("typing_extensions", "typing_extensions"), + ("requests", "requests[socks]==2.31.0 ; python_version >= \"3.8\""), + ("pkg", "pkg @ https://example.com/pkg.zip"), + ("numpy", "numpy==1.26.4"), + ("black", "black"), + ] + .map(|(a, b)| (a.to_owned(), b.to_owned())) + ); + } + + #[test] + fn requirements_files_by_name() { + assert!(is_requirements_file("requirements.txt")); + assert!(is_requirements_file("requirements-dev.txt")); + assert!(!is_requirements_file("constraints.txt")); + assert!(requirements("notes.txt", "django\n").is_empty()); + } + + #[test] + fn pyproject_project_extras_and_groups() { + let text = r#"[build-system] +requires = ["setuptools"] + +[project] +name = "demo" +dependencies = [ + "flask>=3", # 注释 + 'PyYAML', + "local @ file:///tmp/x", +] + +[project.optional-dependencies] +test = ["pytest>=8; python_version>='3.9'"] + +[dependency-groups] +dev = ["ruff", { include-group = "test" }] + +[tool.poetry.dependencies] +ignored = "^1" +"#; + let deps = requirements("pyproject.toml", text); + assert_eq!( + names(&deps, text), + [ + ("flask", "flask>=3"), + ("PyYAML", "PyYAML"), + ("local", "local @ file:///tmp/x"), + ("pytest", "pytest>=8; python_version>='3.9'"), + ("ruff", "ruff"), + ] + .map(|(a, b)| (a.to_owned(), b.to_owned())) + ); + assert!(requirements("pyproject.toml", "[project\n").is_empty()); + } +} diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 6431b344c..8d25b7ad7 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -510,6 +510,7 @@ project_trust_status always project_host bin project_workspace_member_set always project_host bindings sync project_workspace_members always project_host bindings sync proxy_check_connection always desktop bindings async +python_requirements trusted project_host bindings async recent_files always project_host bindings sync recent_project_groups always desktop bindings sync recent_projects always desktop bindings async diff --git a/src/bindings.ts b/src/bindings.ts index 5953c313c..d2dcfb447 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -1348,6 +1348,15 @@ export const commands = { * edited (not yet applied); the response status, or why there was none. */ proxyCheckConnection: (proxy: ProxySettings, url: string) => typedError(__TAURI_INVOKE("proxy_check_connection", { proxy, url })), + /** + * The requirements of a `requirements*.txt` / `pyproject.toml` the project's interpreter + * doesn't satisfy; `None` for other files, or with no local interpreter to ask. + */ + pythonRequirements: (doc: DocId, request: RequestId) => typedError<{ + /** The interpreter checked, which installs go to. */ + python: IpcPath, + unsatisfied: UnsatisfiedRequirement[], +} | null, IdeError>(__TAURI_INVOKE("python_requirements", { doc, request })), /** Recently opened files, most recent first (⌘E). */ recentFiles: () => typedError(__TAURI_INVOKE("recent_files")), /** The welcome screen's project groups. */ @@ -10639,6 +10648,12 @@ export type PythonPackage = { version: string, }; +export type PythonRequirements = { + /** The interpreter checked, which installs go to. */ + python: IpcPath, + unsatisfied: UnsatisfiedRequirement[], +}; + export type PythonSettings = { /** * Project interpreter executable; empty = auto-detect (project venv, else `python3`); @@ -12713,6 +12728,13 @@ export type UnityProjectInfo = { projects: string[], }; +/** A requirement the project's interpreter does not satisfy. */ +export type UnsatisfiedRequirement = { + dependency: ManifestDependency, + /** The installed version that misses the specifier; `None` when not installed. */ + installed: string | null, +}; + export type UpdateCheck = { enabled: boolean, update: UpdateInfo | null, diff --git a/src/features/dependencies/index.ts b/src/features/dependencies/index.ts index 0da4cd9b7..09ddf41dc 100644 --- a/src/features/dependencies/index.ts +++ b/src/features/dependencies/index.ts @@ -1,5 +1,5 @@ import { EditorState, StateEffect, StateField, type Extension } from "@codemirror/state"; -import { ViewPlugin, type EditorView } from "@codemirror/view"; +import type { EditorView } from "@codemirror/view"; import type { CompletionContext, CompletionResult } from "@codemirror/autocomplete"; import { intentionProviders, @@ -11,16 +11,12 @@ import { type ContributedIntention, type EditorDocContext, } from "@/editor/api"; -import { setFileDiagnostics } from "@/editor/lsp/diagnostics"; -import { call, commands, isTauri, nextRequestId, type DependencyVersions, type RequestId } from "@/platform/ipc"; -import { - DEPENDENCY_INSPECTION, - DEPENDENCY_PRODUCER, - inspectionProfile, - subscribeInspectionProfile, -} from "@/platform/inspections"; +import { call, commands, isTauri, nextRequestId, type DependencyVersions } from "@/platform/ipc"; +import { DEPENDENCY_INSPECTION, DEPENDENCY_PRODUCER } from "@/platform/inspections"; import { useProject } from "@/platform/project"; import { tx } from "@/platform/i18n"; +import { checkEnabled, manifestCheck, type ManifestCheck } from "./manifestCheck"; +import { isPythonManifest, pythonRequirements, registerPythonRequirements } from "./python"; const setVersions = StateEffect.define(); const versionsField = StateField.define({ @@ -32,12 +28,8 @@ const versionsField = StateField.define({ }, }); -const viewers = new Map(); - -const enabled = () => inspectionProfile()[DEPENDENCY_INSPECTION]?.enabled !== false; - export function dependencyFixes(view: EditorView, from: number, to: number): ContributedIntention[] { - if (!enabled() || view.state.readOnly) return []; + if (!checkEnabled(DEPENDENCY_INSPECTION) || view.state.readOnly) return []; const text = view.state.doc; return (view.state.field(versionsField, false) ?? []).flatMap(({ dependency, update }) => { if (!update || from > dependency.to || to < dependency.from) return []; @@ -79,95 +71,30 @@ export function versionCompletions(item: DependencyVersions, ctx: CompletionCont }; } +const cargoCheck: ManifestCheck = { + inspection: DEPENDENCY_INSPECTION, + producer: DEPENDENCY_PRODUCER, + fetch: (doc, id) => call(commands.dependencyVersions(doc.doc, null, id)), + apply(view, items, text) { + view.dispatch({ effects: [setVersions.of(items), intentionsChanged.of(null)] }); + return items.flatMap(({ dependency, update }) => { + if (!update) return []; + const { latest } = update; + return [ + { + range: offsetsToRange(text, dependency.from, dependency.to), + severity: "info" as const, + message: tx`A newer version is available: ${latest}`, + source: "Cargo", + code: null, + }, + ]; + }); + }, +}; + function extension(doc: EditorDocContext): Extension { - const plugin = ViewPlugin.define((view) => { - if (!isTauri()) return {}; - viewers.set(doc.path, (viewers.get(doc.path) ?? 0) + 1); - let timer: ReturnType | undefined; - let request: RequestId | null = null; - let sequence = 0; - let disposed = false; - const clear = () => setFileDiagnostics(doc.path, DEPENDENCY_PRODUCER, []); - const cancel = () => { - sequence++; - if (request !== null) void commands.cancelRequest(request); - request = null; - }; - const run = async () => { - if (disposed || !enabled()) return; - const mine = sequence; - const text = view.state.doc; - const root = useProject.getState().project?.root; - const id = nextRequestId(); - request = id; - try { - await whenSynced(view); - if (mine !== sequence || disposed) return; - const items = await call(commands.dependencyVersions(doc.doc, null, id)); - if (mine !== sequence || disposed || view.state.doc !== text || useProject.getState().project?.root !== root) - return; - view.dispatch({ effects: [setVersions.of(items), intentionsChanged.of(null)] }); - setFileDiagnostics( - doc.path, - DEPENDENCY_PRODUCER, - items.flatMap(({ dependency, update }) => { - if (!update) return []; - const { latest } = update; - return [ - { - range: offsetsToRange(text, dependency.from, dependency.to), - severity: "info", - message: tx`A newer version is available: ${latest}`, - source: "Cargo", - code: null, - }, - ]; - }), - ); - } catch { - // Offline registries and cancelled checks never interrupt editing. - } finally { - if (request === id) request = null; - } - }; - const schedule = () => { - cancel(); - clear(); - clearTimeout(timer); - timer = setTimeout(() => void run(), 500); - }; - schedule(); - const offProfile = subscribeInspectionProfile(() => { - schedule(); - view.dispatch({ effects: intentionsChanged.of(null) }); - }); - const offProject = useProject.subscribe((state, previous) => { - if (state.project?.root !== previous.project?.root) { - disposed = true; - cancel(); - clearTimeout(timer); - clear(); - } - }); - return { - update: (u) => { - if (u.docChanged) schedule(); - }, - destroy: () => { - disposed = true; - cancel(); - clearTimeout(timer); - offProfile(); - offProject(); - const remaining = (viewers.get(doc.path) ?? 1) - 1; - if (remaining) viewers.set(doc.path, remaining); - else { - viewers.delete(doc.path); - clear(); - } - }, - }; - }); + const plugin = manifestCheck(doc, cargoCheck); return [ versionsField, plugin, @@ -205,13 +132,19 @@ function versionCompletion(doc: EditorDocContext): Extension { } export function activate(): () => void { - return registerEditorContribution({ + const offPython = registerPythonRequirements(); + const offEditor = registerEditorContribution({ id: "dependency-versions", extensions: (doc) => { if (doc.virtual || doc.readOnly) return []; if (/(?:^|\/)Cargo\.toml$/.test(doc.path)) return extension(doc); if (/(?:^|\/)(?:go\.mod|package\.json)$/.test(doc.path)) return versionCompletion(doc); + if (isPythonManifest(doc.path)) return pythonRequirements(doc); return []; }, }); + return () => { + offEditor(); + offPython(); + }; } diff --git a/src/features/dependencies/manifestCheck.ts b/src/features/dependencies/manifestCheck.ts new file mode 100644 index 000000000..5e1192d10 --- /dev/null +++ b/src/features/dependencies/manifestCheck.ts @@ -0,0 +1,112 @@ +import type { Extension, Text } from "@codemirror/state"; +import { ViewPlugin, type EditorView } from "@codemirror/view"; +import { intentionsChanged, whenSynced, type EditorDocContext } from "@/editor/api"; +import { setFileDiagnostics } from "@/editor/lsp/diagnostics"; +import { commands, isTauri, nextRequestId, type Diagnostic, type RequestId } from "@/platform/ipc"; +import { inspectionProfile, subscribeInspectionProfile } from "@/platform/inspections"; +import { useProject } from "@/platform/project"; + +/** A backend check of a manifest file, published as one inspection's diagnostics. */ +export interface ManifestCheck { + inspection: string; + producer: string; + fetch(doc: EditorDocContext, request: RequestId): Promise; + /** Shows a result computed for `text` (the view's current text); returns the file's diagnostics. */ + apply(view: EditorView, result: T, text: Text): Diagnostic[]; + /** The file's result went stale or its last editor closed. */ + reset?(path: string): void; + /** Other reasons to check again (an install finished); returns the unsubscribe. */ + watch?(recheck: () => void): () => void; + /** Check again when the editor gains focus (the environment may have changed meanwhile). */ + onFocus?: boolean; +} + +export const checkEnabled = (inspection: string) => inspectionProfile()[inspection]?.enabled !== false; + +const viewers = new Map(); + +/** Runs `check` 500 ms after the file opens or changes, while its inspection is on. */ +export function manifestCheck(doc: EditorDocContext, check: ManifestCheck): Extension { + return ViewPlugin.define((view) => { + if (!isTauri()) return {}; + const key = `${check.producer}\n${doc.path}`; + viewers.set(key, (viewers.get(key) ?? 0) + 1); + let timer: ReturnType | undefined; + let request: RequestId | null = null; + let sequence = 0; + let disposed = false; + const clear = () => { + setFileDiagnostics(doc.path, check.producer, []); + check.reset?.(doc.path); + }; + const cancel = () => { + sequence++; + if (request !== null) void commands.cancelRequest(request); + request = null; + }; + const run = async () => { + if (disposed || !checkEnabled(check.inspection)) return; + const mine = sequence; + const text = view.state.doc; + const root = useProject.getState().project?.root; + const id = nextRequestId(); + request = id; + try { + await whenSynced(view); + if (mine !== sequence || disposed) return; + const result = await check.fetch(doc, id); + if (mine !== sequence || disposed || view.state.doc !== text || useProject.getState().project?.root !== root) + return; + setFileDiagnostics(doc.path, check.producer, check.apply(view, result, text)); + } catch { + // Offline registries, missing interpreters and cancelled checks never interrupt editing. + } finally { + if (request === id) request = null; + } + }; + // Keeps the current diagnostics until the new result arrives. + const recheck = () => { + cancel(); + clearTimeout(timer); + timer = setTimeout(() => void run(), 500); + }; + const schedule = () => { + clear(); + recheck(); + }; + schedule(); + const offProfile = subscribeInspectionProfile(() => { + schedule(); + view.dispatch({ effects: intentionsChanged.of(null) }); + }); + const offWatch = check.watch?.(recheck); + const offProject = useProject.subscribe((state, previous) => { + if (state.project?.root !== previous.project?.root) { + disposed = true; + cancel(); + clearTimeout(timer); + clear(); + } + }); + return { + update: (u) => { + if (u.docChanged) schedule(); + else if (check.onFocus && u.focusChanged && view.hasFocus) recheck(); + }, + destroy: () => { + disposed = true; + cancel(); + clearTimeout(timer); + offProfile(); + offWatch?.(); + offProject(); + const remaining = (viewers.get(key) ?? 1) - 1; + if (remaining) viewers.set(key, remaining); + else { + viewers.delete(key); + clear(); + } + }, + }; + }); +} diff --git a/src/features/dependencies/python.test.ts b/src/features/dependencies/python.test.ts new file mode 100644 index 000000000..6ca38247a --- /dev/null +++ b/src/features/dependencies/python.test.ts @@ -0,0 +1,143 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { EditorState } from "@codemirror/state"; +import { EditorView } from "@codemirror/view"; +import { act, renderHook } from "@testing-library/react"; +import type { PythonRequirements } from "@/bindings"; + +const pythonRequirements = vi.fn(); +const sdkPythonPip = vi.fn(); +const cancelRequest = vi.fn(async () => {}); +const notify = vi.fn(); +vi.mock("@tauri-apps/api/core", async (orig) => ({ + ...(await orig()), + Channel: class { + onmessage = (_: string) => {}; + }, +})); +vi.mock("@/platform/ipc", async (orig) => { + const actual = await orig(); + return { + ...actual, + isTauri: () => true, + commands: { ...actual.commands, pythonRequirements, sdkPythonPip, cancelRequest }, + }; +}); +vi.mock("@/workbench/contributions", async (orig) => ({ + ...(await orig()), + notifications: () => ({ notify }), +})); +const { activate } = await import("./index"); +const { useRequirements } = await import("./python"); +const { editorContributions, contributedIntentions } = await import("@/editor/api"); +const { diagnosticsFor } = await import("@/editor/lsp/diagnostics"); +const { lspDoc } = await import("@/editor/lsp/lsp"); +const { useProject } = await import("@/platform/project"); +const { useEditorBanners } = await import("@/workbench/contributions"); + +const text = "# 中文 😀\nDjango>=5\nrequests\nnumpy\n"; +const span = (s: string) => ({ from: text.indexOf(s), to: text.indexOf(s) + s.length }); +const result: PythonRequirements = { + python: "/p/.venv/bin/python", + unsatisfied: [ + { dependency: { package: "Django", requirement: "Django>=5", ...span("Django>=5") }, installed: "4.2" }, + { dependency: { package: "requests", requirement: "requests", ...span("requests") }, installed: null }, + ], +}; +let deactivate: () => void; +const views: EditorView[] = []; +beforeEach(() => { + vi.useFakeTimers(); + pythonRequirements.mockResolvedValue({ status: "ok", data: result }); + sdkPythonPip.mockResolvedValue({ status: "ok", data: null }); + useProject.setState({ project: { root: "/p" } as never, settings: {} as never }); + deactivate = activate(); +}); +afterEach(() => { + views.splice(0).forEach((view) => view.destroy()); + deactivate(); + useProject.setState({ project: null, settings: null }); + vi.clearAllMocks(); + vi.useRealTimers(); +}); +function editor(path = "/p/requirements.txt") { + const ctx = { doc: 3, path, language: "text", uiMode: "Text", readOnly: false }; + const contribution = editorContributions().find((c) => c.id === "dependency-versions")!; + const view = new EditorView({ + parent: document.body, + state: EditorState.create({ + doc: text, + selection: { anchor: span("requests").from }, + extensions: [lspDoc.of(ctx), contribution.extensions(ctx)], + }), + }); + views.push(view); + return view; +} +const settle = () => vi.advanceTimersByTimeAsync(550); +const banner = (path: string) => + renderHook(() => useEditorBanners.getState().banners.get("python.requirements")!.useBanner(path)).result.current; + +describe("Python requirements", () => { + it.each(["/p/requirements.txt", "/p/requirements-dev.txt", "/p/pyproject.toml"])("checks %s", async (path) => { + editor(path); + await settle(); + expect(pythonRequirements).toHaveBeenCalledWith(3, expect.any(Number)); + expect(diagnosticsFor(path)).toMatchObject([ + { + severity: "warning", + message: "Requirement Django>=5 is not satisfied: 4.2 is installed", + range: { start: { line: 1, col: 0 }, end: { line: 1, col: 9 } }, + }, + { severity: "warning", message: "Package requests is not installed", range: { start: { line: 2, col: 0 } } }, + ]); + }); + + it("leaves other files alone", async () => { + editor("/p/constraints.txt"); + await settle(); + expect(pythonRequirements).not.toHaveBeenCalled(); + }); + + it("installs one or all requirements, then checks again", async () => { + const view = editor(); + await settle(); + const fixes = contributedIntentions(view); + expect(fixes.map((f) => f.label)).toEqual(["Install requirement", "Install all missing requirements"]); + pythonRequirements.mockResolvedValue({ status: "ok", data: { ...result, unsatisfied: [] } }); + await fixes[1]!.run(); + await vi.waitFor(() => expect(useRequirements.getState().installs).toBe(1)); + expect(sdkPythonPip.mock.calls.map((c) => c.slice(0, 4))).toEqual([ + ["/p/.venv/bin/python", "Django>=5", false, false], + ["/p/.venv/bin/python", "requests", false, false], + ]); + await settle(); + expect(pythonRequirements).toHaveBeenCalledTimes(2); + expect(diagnosticsFor("/p/requirements.txt")).toEqual([]); + expect(notify).not.toHaveBeenCalled(); + }); + + it("reports failed installs in one notification", async () => { + sdkPythonPip.mockResolvedValue({ status: "error", error: { kind: "failed", message: "no matching distribution" } }); + const view = editor(); + await settle(); + await contributedIntentions(view)[0]!.run(); + await vi.waitFor(() => expect(notify).toHaveBeenCalledOnce()); + expect(notify.mock.calls[0]![0]).toMatchObject({ + level: "error", + body: expect.stringContaining("requests: no matching distribution"), + }); + }); + + it("shows a banner until ignored, and none without unsatisfied requirements", async () => { + editor(); + await settle(); + expect(useRequirements.getState().byPath.get("/p/requirements.txt")).toEqual(result); + expect(banner("/p/requirements.txt")).toMatchObject({ + text: "Package requirements are not satisfied", + actions: [{ label: "Install requirements" }, { label: "Ignore" }], + }); + act(() => useRequirements.setState({ ignored: true })); + expect(banner("/p/requirements.txt")).toBeNull(); + expect(banner("/p/other.txt")).toBeNull(); + }); +}); diff --git a/src/features/dependencies/python.ts b/src/features/dependencies/python.ts new file mode 100644 index 000000000..3e06d4152 --- /dev/null +++ b/src/features/dependencies/python.ts @@ -0,0 +1,221 @@ +/** + * Requirements of `requirements*.txt` / `pyproject.toml` that the project's interpreter doesn't + * satisfy (PyCharm's "Package requirements are not satisfied"): a warning on each, quick fixes + * and a banner that install them with pip / uv as Settings › Python Interpreter does. + */ +import { StateEffect, StateField, type Extension } from "@codemirror/state"; +import type { EditorView } from "@codemirror/view"; +import { Channel } from "@tauri-apps/api/core"; +import { create } from "zustand"; +import { + intentionProviders, + intentionsChanged, + offsetsToRange, + quickFixProviders, + type ContributedIntention, + type EditorDocContext, +} from "@/editor/api"; +import { call, commands, nextRequestId, onIdeEvent, type PythonRequirements, type RequestId } from "@/platform/ipc"; +import { PYTHON_REQUIREMENTS_INSPECTION, PYTHON_REQUIREMENTS_PRODUCER } from "@/platform/inspections"; +import { useProject } from "@/platform/project"; +import { tx } from "@/platform/i18n"; +import { notifications, registerEditorBanner } from "@/workbench/contributions"; +import { upsertTask } from "@/workbench/tasks"; +import { checkEnabled, manifestCheck, type ManifestCheck } from "./manifestCheck"; + +interface State { + /** By file: its last check, when something was unsatisfied. */ + byPath: Map; + /** Interpreters an install is running for. */ + installing: Set; + /** Banner dismissed until the project is reopened. */ + ignored: boolean; + /** Bumped when an install ends: open manifests check again. */ + installs: number; +} + +const initial = (): State => ({ byPath: new Map(), installing: new Set(), ignored: false, installs: 0 }); +export const useRequirements = create(initial); + +export const isPythonManifest = (path: string) => /(?:^|\/)(?:requirements[^/]*\.txt|pyproject\.toml)$/.test(path); + +function setResult(path: string, result: PythonRequirements | null) { + useRequirements.setState((s) => { + if (!result?.unsatisfied.length && !s.byPath.has(path)) return s; + const byPath = new Map(s.byPath); + if (result?.unsatisfied.length) byPath.set(path, result); + else byPath.delete(path); + return { byPath }; + }); +} + +function setInstalling(python: string, on: boolean) { + useRequirements.setState((s) => { + const installing = new Set(s.installing); + if (on) installing.add(python); + else installing.delete(python); + return on ? { installing } : { installing, installs: s.installs + 1 }; + }); +} + +/** Installs `requirements` one by one into `python`, as a background task; failures end in one notification. */ +export async function installRequirements(python: string, requirements: readonly string[]): Promise { + if (!requirements.length || useRequirements.getState().installing.has(python)) return; + setInstalling(python, true); + const id = `python-requirements:${python}`; + const title = tx("Installing package requirements"); + let current: RequestId | null = null; + let cancelled = false; + const cancel = () => { + cancelled = true; + if (current !== null) void commands.cancelRequest(current); + }; + const failures: string[] = []; + try { + for (const [i, requirement] of requirements.entries()) { + if (cancelled) break; + const progress = (message: string) => + upsertTask({ id, title, message, fraction: i / requirements.length, done: false, cancel }); + progress(requirement); + const channel = new Channel(); + channel.onmessage = (line) => line.trim() && progress(line.trim()); + current = nextRequestId(); + try { + await call(commands.sdkPythonPip(python, requirement, false, false, current, channel)); + } catch (e) { + if (!cancelled) failures.push(`${requirement}: ${e instanceof Error ? e.message : String(e)}`); + } + } + } finally { + upsertTask({ id, title, message: null, fraction: 1, done: true }); + setInstalling(python, false); + } + if (failures.length) + notifications().notify({ + level: "error", + title: "Cannot install package requirements", + body: failures.join("\n"), + }); +} + +const setFound = StateEffect.define(); +const foundField = StateField.define({ + create: () => null, + update(value, tr) { + if (tr.docChanged) return null; + for (const effect of tr.effects) if (effect.is(setFound)) return effect.value; + return value; + }, +}); + +export function requirementFixes(view: EditorView, from: number, to: number): ContributedIntention[] { + if (!checkEnabled(PYTHON_REQUIREMENTS_INSPECTION)) return []; + const found = view.state.field(foundField, false); + if (!found) return []; + const { python, unsatisfied } = found; + const at = unsatisfied.filter(({ dependency }) => from <= dependency.to && to >= dependency.from); + if (!at.length) return []; + const fixes: ContributedIntention[] = at.map(({ dependency }) => ({ + id: `python.installRequirement:${dependency.from}`, + label: tx("Install requirement"), + quickFix: true, + run: () => void installRequirements(python, [dependency.requirement]), + })); + if (unsatisfied.length > 1) + fixes.push({ + id: "python.installRequirements", + label: tx("Install all missing requirements"), + quickFix: true, + run: () => + void installRequirements( + python, + unsatisfied.map(({ dependency }) => dependency.requirement), + ), + }); + return fixes; +} + +const requirementsCheck = (path: string): ManifestCheck => ({ + inspection: PYTHON_REQUIREMENTS_INSPECTION, + producer: PYTHON_REQUIREMENTS_PRODUCER, + onFocus: true, + fetch: (doc, id) => call(commands.pythonRequirements(doc.doc, id)), + apply(view, result, text) { + view.dispatch({ effects: [setFound.of(result), intentionsChanged.of(null)] }); + setResult(path, result); + return (result?.unsatisfied ?? []).map(({ dependency: { package: name, requirement, from, to }, installed }) => ({ + range: offsetsToRange(text, from, to), + severity: "warning" as const, + message: + installed === null + ? tx`Package ${name} is not installed` + : tx`Requirement ${requirement} is not satisfied: ${installed} is installed`, + source: "Python", + code: null, + })); + }, + reset: () => setResult(path, null), + watch: (recheck) => { + const offInstalls = useRequirements.subscribe((s, prev) => { + if (s.installs !== prev.installs) recheck(); + }); + // Another interpreter chosen. + const offSettings = useProject.subscribe((s, prev) => { + if (s.settings !== prev.settings) recheck(); + }); + // Restricted Mode never runs the interpreter: check once the project is trusted. + const offTrust = onIdeEvent("projectTrustChanged", (e) => { + if (e.trusted) recheck(); + }); + return () => { + offInstalls(); + offSettings(); + offTrust(); + }; + }, +}); + +export function pythonRequirements(doc: EditorDocContext): Extension { + return [ + foundField, + manifestCheck(doc, requirementsCheck(doc.path)), + intentionProviders.of((view) => { + const selection = view.state.selection.main; + return requirementFixes(view, selection.from, selection.to); + }), + quickFixProviders.of(requirementFixes), + ]; +} + +function useRequirementsBanner(path: string) { + const found = useRequirements((s) => (s.ignored ? undefined : s.byPath.get(path))); + const installing = useRequirements((s) => !!found && s.installing.has(found.python)); + if (!found || installing) return null; + return { + text: "Package requirements are not satisfied", + level: "warning" as const, + actions: [ + { + label: "Install requirements", + run: () => + void installRequirements( + found.python, + found.unsatisfied.map((u) => u.dependency.requirement), + ), + }, + { label: "Ignore", run: () => useRequirements.setState({ ignored: true }) }, + ], + }; +} + +export function registerPythonRequirements(): () => void { + useRequirements.setState(initial()); + const offBanner = registerEditorBanner({ id: "python.requirements", order: 10, useBanner: useRequirementsBanner }); + const offProject = useProject.subscribe((s, prev) => { + if (s.project?.root !== prev.project?.root) useRequirements.setState(initial()); + }); + return () => { + offBanner(); + offProject(); + }; +} diff --git a/src/features/settings/__tests__/inspections.test.ts b/src/features/settings/__tests__/inspections.test.ts index ca39575e4..45f6f3b63 100644 --- a/src/features/settings/__tests__/inspections.test.ts +++ b/src/features/settings/__tests__/inspections.test.ts @@ -120,7 +120,8 @@ describe("inspections tree", () => { expect(python.children.map((n) => n.id)).toEqual([ "lsp:basedpyright", "lsp:ruff", - // The Python built-ins the IDE decides itself (no server checks class rules). + // The Python built-ins the IDE decides itself (no server checks class rules or installs). + "builtin:python-requirements", "builtin:python-circular-bases", "builtin:python-override", "builtin:python-abstract-method", diff --git a/src/platform/inspections.ts b/src/platform/inspections.ts index 3c62aec01..08ca2ef7d 100644 --- a/src/platform/inspections.ts +++ b/src/platform/inspections.ts @@ -235,6 +235,8 @@ export const SYNTAX_ERRORS_PRODUCER = "syntax"; export const DEPENDENCY_PRODUCER = "dependency-versions"; export const DEPENDENCY_INSPECTION = "builtin:dependency-versions"; +export const PYTHON_REQUIREMENTS_PRODUCER = "python-requirements"; +export const PYTHON_REQUIREMENTS_INSPECTION = "builtin:python-requirements"; /** Conflict markers left in a file by a merge, rebase, cherry-pick or stash that stopped on conflicts. */ export const CONFLICT_MARKERS_PRODUCER = "merge-conflict-markers"; @@ -280,6 +282,15 @@ export const BUILTIN_INSPECTIONS: readonly BuiltinInspection[] = [ description: "Reports newer crate versions that Cargo.toml requirements do not already allow.", defaultLevel: "weakWarning", }, + { + id: PYTHON_REQUIREMENTS_INSPECTION, + producer: PYTHON_REQUIREMENTS_PRODUCER, + name: "Unsatisfied package requirements", + group: "Python", + description: + "Reports requirements in requirements.txt and pyproject.toml that the project's Python interpreter does not have installed, or whose installed version does not match.", + defaultLevel: "warning", + }, { id: "builtin:syntax", producer: SYNTAX_ERRORS_PRODUCER, diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 6f4fee547..bf42de18a 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -3041,6 +3041,16 @@ "A folder with this name already exists and is not empty": "A folder with this name already exists and is not empty", "Show Only Affected Changes": "Show Only Affected Changes", "Layout": "Layout", + "Installing package requirements": "Installing package requirements", + "Cannot install package requirements": "Cannot install package requirements", + "Install requirement": "Install requirement", + "Install all missing requirements": "Install all missing requirements", + "Package {name} is not installed": "Package {name} is not installed", + "Requirement {requirement} is not satisfied: {installed} is installed": "Requirement {requirement} is not satisfied: {installed} is installed", + "Package requirements are not satisfied": "Package requirements are not satisfied", + "Install requirements": "Install requirements", + "Unsatisfied package requirements": "Unsatisfied package requirements", + "Reports requirements in requirements.txt and pyproject.toml that the project's Python interpreter does not have installed, or whose installed version does not match.": "Reports requirements in requirements.txt and pyproject.toml that the project's Python interpreter does not have installed, or whose installed version does not match.", "Python Console": "Python Console", "Execute Selection in Python Console": "Execute Selection in Python Console", "No Python interpreter": "No Python interpreter", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index c6e4fbba5..fe8768af3 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -9359,6 +9359,16 @@ "Mail:": "邮件:", "Show Only Affected Changes": "仅显示受影响的变更", "Layout": "布局", + "Installing package requirements": "正在安装依赖包", + "Cannot install package requirements": "无法安装依赖包", + "Install requirement": "安装此依赖", + "Install all missing requirements": "安装所有缺失的依赖", + "Package {name} is not installed": "未安装软件包 {name}", + "Requirement {requirement} is not satisfied: {installed} is installed": "未满足依赖 {requirement}:已安装 {installed}", + "Package requirements are not satisfied": "未满足依赖包要求", + "Install requirements": "安装依赖", + "Unsatisfied package requirements": "未满足的依赖包要求", + "Reports requirements in requirements.txt and pyproject.toml that the project's Python interpreter does not have installed, or whose installed version does not match.": "报告 requirements.txt 和 pyproject.toml 中项目 Python 解释器未安装、或已安装版本不符合要求的依赖。", "Python Console": "Python 控制台", "Execute Selection in Python Console": "在 Python 控制台中执行选中内容", "No Python interpreter": "没有 Python 解释器",