Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai 3d6ceed0df fix(vcs): reuse one diff tab with the preview tab turned off
Diffs opened from Commit / Local Changes, the Git Log, shelves and stashes
reused one tab only through the preview tab, so turning off Opening Policy ›
Enable preview tab also opened every diff in a new tab. Editor kinds can now
ask for their previews to be granted regardless of that setting
(`reusesPreviewTab`); the diff, combined diff and merge commit diff kinds do,
so stepping through a change set keeps one diff tab while project files still
open as regular tabs. Pinned and kept diff tabs stay, and the Git Log's
selection-following preview works with the setting off too.

Fixes #7096
2026-12-01 03:47:18 +08:00
l0ng-ai 8ac194cf50 fix(plugins): let capabilities.reasons explain capabilities a contribution brings (#7101)
A plugin with [[contributes.javaAgents]] gets java.agent without listing it under [capabilities], so the manifest check rejected a reason for it and the install dialog and Permissions showed only the IDE's description. Manifest::derived_capabilities names the capabilities contributions bring (java.agent from javaAgents, project.read from documentIndexers) and reasons may use those keys too; docs updated.

Fixes #7088
2026-12-01 03:26:09 +08:00
Ivan 3b488a7824 fix(macos): let background project tabs give their web content memory back (#7060)
A background project tab of a native tab group detaches its WKWebView from the window 30 s after it leaves the front, so WebKit frees the hidden page's graphics and caches. The view comes back when the tab is selected through our tab bar, when its window becomes key (Window menu, Close Project) or when AppKit makes it visible by itself; an inactive app's full-screen group waits for activation (#6937).

Every macOS with_webview caller goes through macos::with_web_view, which hands the retained view to a detached tab instead of panicking in wry; titlebar::set_height uses the NSWindow directly. clippy.toml disallows the raw with_webview calls. Covered by BackgroundTabs unit tests and an AppKit test of the synchronous re-attach on the key notification (it no longer asks a never-loaded web view for its process ids, which WebKit asserts on).

Fixes #6938

Co-authored-by: Pecnikas <[email protected]>

Co-authored-by: Pecnikas <[email protected]>
2026-12-01 03:20:08 +08:00
l0ng-ai b5e89aace0 feat(run): show each invocation of a parameterized test in the Run window (#7099)
The JUnit runner and the Gradle test init script report an invocation of a parameterized, repeated or dynamic test with its display name, and the JVM parser puts it under its method node with its own status, output and stack trace; the method shows the aggregate. Rerunning a failed invocation reruns its method.

Fixes #7046
2026-12-01 03:06:11 +08:00
Akbar Husain 81c95b2ab7 perf(lint): clear remaining non-e2e React perf violations (#7093)
Clears the remaining non-e2e React perf lint violations and turns the three rules on outside e2e/ so they can't come back: data-derived keys for diagram edges and deadlock cycles (index keys stay, with a documented suppression, where position is the identity), context values in tests hoisted to constants or memoized, and array/JSX default props replaced with module-level constants.

Co-authored-by: akbar1214 <[email protected]>
2026-12-01 02:59:24 +08:00
LU XIANGRUIтаwildcatDownstairs f7b5cc388c feat(run): debug Python on a WSL run target (#6777)
A Python run configuration on a WSL target can now be debugged: the program starts under the container debugger's bootstrap in the distribution, which waits for the IDE on the distribution's loopback (WSL forwards it), finding the IDE's debugpy and bootstrap through wslpath when the distro has none. Stop ends the debugged process in the distribution, with pkill or, where it is missing, a /proc scan. Other kinds say they can't be debugged in WSL.

Also carries the WSL run target review fixes that neither #6764 nor #6770 included: Maven options naming this machine's files are dropped from remote runs, a failed wsl.exe listing is reported in Run Targets and retried on focus, an unsafe distribution name is cleared and asked for again, a printed path whose .. climbs above its root is refused, and prepare_wsl is built only on Windows.

Verified by the contributor on Windows 11 with WSL 2 (Ubuntu 24.04): a breakpoint is hit and Stop leaves no debug process.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-01 02:54:14 +08:00
LU XIANGRUIтаwildcatDownstairs 277d0e9d1e feat(python): a Python in WSL as the project interpreter (#6770)
Python > Add Interpreter gets a WSL tab: pick a distribution and a Python in it (a bare python3 is looked up on the distribution's PATH; Windows paths are refused). The project interpreter then runs in the distribution: packages are listed from there, the project's virtualenv inside the distro is read, the language server resolves imports from the distro's site-packages through \\wsl.localhost, and runs go through the WSL run target. Verified by the contributor on Windows 11 with WSL 2 (Ubuntu 24.04).

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-01 02:38:34 +08:00
LU XIANGRUIтаwildcatDownstairs d6adb7aa40 feat(run): run configurations in a WSL distribution from a Windows project (#6764)
Settings > Run Targets gets a WSL target that lists the installed distributions. A run configuration on it starts locally as wsl.exe -d <distro> --cd <dir> --exec ..., with the project's Windows paths mapped to /mnt/<drive>/..., arguments passed unchanged, environment variables forwarded through WSLENV, and Stop ending the Linux process. Verified by the contributor on Windows 11 with WSL 2 (Ubuntu 24.04), including quoted arguments and Emulate terminal.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-01 02:21:28 +08:00
l0ng-ai 6e5e482410 test(memory): make the debounce test tolerate a loaded machine (#7098)
memory::tests::a_burst_of_calls_runs_once_after_the_delay failed on a loaded macOS runner: with a 100 ms delay and 20 ms gaps, oversleeping let the debounced call fire before the burst ended. The test now uses a 500 ms delay, checks "nothing ran yet" only when less than the delay has passed since the last call, waits for the run, and asserts exactly one run only when no gap in the burst reached the delay.
2026-12-01 02:20:22 +08:00
77 змінених файлів з 2143 додано та 161 видалено

No files matched your search

+4 -1
Переглянути файл
@@ -152,7 +152,10 @@
"files": ["**/*.ts", "**/*.tsx", "**/*.mts", "**/*.cts"],
"excludeFiles": ["e2e/**"],
"rules": {
"no-await-in-loop": "error"
"no-await-in-loop": "error",
"react/no-array-index-key": "error",
"react/jsx-no-constructed-context-values": "error",
"react/no-object-type-as-default-prop": "error"
}
}
]
+21 -4
Переглянути файл
@@ -63,13 +63,30 @@ mod tests {
#[test]
fn a_burst_of_calls_runs_once_after_the_delay() {
// Timing-based: a loaded CI machine can oversleep, so each check allows for that.
let delay = Duration::from_millis(500);
let (mut last, mut widest_gap) = (None::<Instant>, Duration::ZERO);
for _ in 0..5 {
debounce(&DUE, Duration::from_millis(100), count);
debounce(&DUE, delay, count);
let now = Instant::now();
widest_gap = widest_gap.max(last.map_or(Duration::ZERO, |l| now - l));
last = Some(now);
std::thread::sleep(Duration::from_millis(20));
}
assert_eq!(RUNS.load(SeqCst), 0);
std::thread::sleep(Duration::from_millis(400));
assert_eq!(RUNS.load(SeqCst), 1);
if last.unwrap().elapsed() < delay {
assert_eq!(RUNS.load(SeqCst), 0, "ran before the delay passed");
}
let deadline = Instant::now() + Duration::from_secs(10);
while RUNS.load(SeqCst) == 0 && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
// A second run would come within another delay.
std::thread::sleep(delay);
if widest_gap < delay {
assert_eq!(RUNS.load(SeqCst), 1);
} else {
assert!(RUNS.load(SeqCst) >= 1);
}
release_free_pages_soon();
}
}
+7 -1
Переглянути файл
@@ -203,6 +203,9 @@ pub enum RunTargetKind {
Docker,
/// A new container of a Compose service (`docker compose run --rm`).
Compose,
/// A WSL distribution on this Windows machine (`wsl.exe -d <distro>`), the project read
/// through `/mnt/<drive>`.
Wsl,
}
/// Build, Execution, Deployment › Run Targets: run configurations on another machine
@@ -215,7 +218,8 @@ pub struct RunTarget {
pub name: String,
/// [`SshConfiguration::id`] (SSH).
pub ssh_config: String,
/// Remote folder the project is synchronised to and run from (SSH).
/// Remote folder the project is synchronised to and run from (SSH); the project's Linux
/// path, empty = its `/mnt/<drive>` path (WSL).
pub project_root: String,
/// Upload changed project files before each run (SSH).
pub sync_before_run: bool,
@@ -241,6 +245,8 @@ pub struct RunTarget {
pub run_options: String,
/// Run as the image's user instead of the project folder's owner (Linux).
pub image_user: bool,
/// Distribution name, as `wsl.exe -l -q` lists it (WSL).
pub distro: String,
}
/// A plugin-owned argv wrapper for project runs (API 1.4).
+92
Переглянути файл
@@ -35,6 +35,24 @@ pub fn parse(path: &Path) -> Option<WslPath> {
Some(WslPath { distro: distro.to_owned(), path: format!("/{}", tail.trim_end_matches('/')) })
}
/// The Linux path of a Windows path seen from `distro`: `C:\a` → `/mnt/c/a` (WSL's default
/// automount root), `\\wsl.localhost\<distro>\a` → `/a`. `None` for another distro's share,
/// other network shares and relative paths.
pub fn linux_path(path: &Path, distro: &str) -> Option<String> {
if let Some(w) = parse(path) {
return w.distro.eq_ignore_ascii_case(distro).then_some(w.path);
}
let s = path.to_string_lossy().replace('\\', "/");
let s = s.strip_prefix("//?/").unwrap_or(&s);
let mut chars = s.chars();
let drive = chars.next().filter(char::is_ascii_alphabetic)?;
let rest = chars.as_str().strip_prefix(':')?;
if !(rest.is_empty() || rest.starts_with('/')) {
return None;
}
Some(format!("/mnt/{}{}", drive.to_ascii_lowercase(), rest.trim_end_matches('/')))
}
/// A distro name `wsl.exe -d` can be given safely: Windows creates them from letters, digits,
/// `.`, `_` and `-`. A leading `-` would be read as an option, so it is refused too.
pub fn is_valid_distro(name: &str) -> bool {
@@ -86,6 +104,57 @@ pub fn list_distros() -> Vec<String> {
Vec::new()
}
/// Where this machine reads `distro`'s file system.
pub fn share_root(distro: &str) -> std::path::PathBuf {
format!(r"\\wsl.localhost\{distro}").into()
}
/// The names of a Linux path, `.` dropped and `..` taking the name before it.
pub fn path_parts(linux: &str) -> Vec<&str> {
let mut parts: Vec<&str> = Vec::new();
for c in linux.split('/').filter(|c| !c.is_empty() && *c != ".") {
if c == ".." {
parts.pop();
} else {
parts.push(c);
}
}
parts
}
/// Where this machine reads the absolute path `linux` of `distro`: a drive mounted at
/// `/mnt/<drive>` is read directly, anything else through [`share_root`]. `..` goes up
/// within `linux`, never above the drive or the share.
pub fn windows_path(linux: &str, distro: &str) -> std::path::PathBuf {
let parts = path_parts(linux);
let base = match parts.as_slice() {
["mnt", drive, ..] if drive.len() == 1 && drive.chars().all(|c| c.is_ascii_alphabetic()) => {
let base = std::path::PathBuf::from(format!("{}:\\", drive.to_ascii_uppercase()));
return parts[2..].iter().fold(base, |p, c| p.join(c));
}
_ => share_root(distro),
};
parts.iter().fold(base, |p, c| p.join(c))
}
/// Runs `args` in `distro` without its shell and returns the standard output; a failed
/// run is an error with its output. `wsl.exe`'s own messages are UTF-16: their NULs go.
pub fn exec(distro: &str, args: &[&str], timeout: std::time::Duration) -> crate::IdeResult<String> {
use crate::cli_process::{CliTool, Decoding};
if !is_valid_distro(distro) {
return Err(crate::IdeError::invalid(format!("'{distro}' is not a WSL distribution name")));
}
let mut cmd = std::process::Command::new(EXE);
cmd.args(["-d", distro, "--exec"]).args(args);
let out = CliTool::new(EXE, Decoding::Utf8Lossy).run(cmd, timeout, None)?;
let (stdout, stderr) = (out.stdout.replace('\0', ""), out.stderr.replace('\0', ""));
if out.success {
return Ok(stdout);
}
let detail = if stderr.trim().is_empty() { stdout.trim() } else { stderr.trim() };
Err(crate::IdeError::internal(format!("{EXE} -d {distro} --exec {}: {detail}", args.first().unwrap_or(&""))))
}
#[cfg(test)]
mod tests {
use super::*;
@@ -103,6 +172,21 @@ mod tests {
assert_eq!(p(r"\\?\UNC\WSL.LOCALHOST\Ubuntu-24.04\home\me\app"), want);
}
#[test]
fn windows_paths_map_onto_the_distro() {
let l = |s: &str| linux_path(Path::new(s), "Ubuntu");
assert_eq!(l(r"C:\Users\me\app"), Some("/mnt/c/Users/me/app".into()));
assert_eq!(l(r"D:\"), Some("/mnt/d".into()));
assert_eq!(l("e:/work/x/"), Some("/mnt/e/work/x".into()));
assert_eq!(l(r"\\?\C:\proj"), Some("/mnt/c/proj".into()));
assert_eq!(l(r"\\wsl.localhost\ubuntu\home\me"), Some("/home/me".into()));
assert_eq!(l(r"\\wsl$\Debian\home\me"), None);
assert_eq!(l(r"\\server\share\a"), None);
assert_eq!(l(r"C:relative"), None);
assert_eq!(l("app"), None);
assert_eq!(l("/home/me"), None);
}
#[test]
fn distro_root_and_foreign_paths() {
assert_eq!(p(r"\\wsl.localhost\Debian"), Some(("Debian".to_owned(), "/".to_owned())));
@@ -127,6 +211,14 @@ mod tests {
assert!(parse_distro_list(b"").is_empty());
}
#[test]
fn linux_paths_are_read_on_their_drive_or_through_the_share() {
use std::path::PathBuf;
assert_eq!(windows_path("/mnt/d/lib/../x.py", "U"), PathBuf::from("D:\\").join("x.py"));
assert_eq!(windows_path("/usr/lib/a.py", "U"), share_root("U").join("usr").join("lib").join("a.py"));
assert_eq!(windows_path("/mnt/wsl/x", "U"), share_root("U").join("mnt").join("wsl").join("x"));
}
#[test]
fn distro_names_cannot_smuggle_options_or_paths() {
for bad in ["", "-d", "--exec", "a b", "a/b", r"a\b", "a;b", "a$(x)", "a\"b"] {
+27 -2
Переглянути файл
@@ -391,9 +391,12 @@ impl Manifest {
if !self.capabilities.reasons.is_empty() {
self.needs_api("`capabilities.reasons`", 19)?;
}
let derived = self.derived_capabilities();
for (key, text) in &self.capabilities.reasons {
if !self.capabilities.all().any(|c| c.to_string() == *key) {
return Err(format!("capabilities.reasons: {key:?} is not under `required` or `optional`"));
if !self.capabilities.all().chain(&derived).any(|c| c.to_string() == *key) {
return Err(format!(
"capabilities.reasons: {key:?} is not under `required` or `optional`, nor comes from a contribution"
));
}
if text.trim().is_empty() || text.chars().count() > MAX_CAPABILITY_REASON {
return Err(format!(
@@ -522,6 +525,17 @@ impl Manifest {
Ok(())
}
/// Capabilities the plugin's contributions bring without being listed under `[capabilities]`:
/// `java.agent` from `[[contributes.javaAgents]]`, `project.read` from
/// `[[contributes.documentIndexers]]` (the extension points in `ide-host` add them to the grant).
pub fn derived_capabilities(&self) -> Vec<Capability> {
[("javaAgents", Capability::JavaAgent), ("documentIndexers", Capability::ProjectRead)]
.into_iter()
.filter(|(point, _)| self.contributes.contains_key(*point))
.map(|(_, cap)| cap)
.collect()
}
/// The declarations of one extension point: `[[contributes.x]]` gives
/// several, `[contributes.x]` one.
pub fn declarations(&self, point: &str) -> Vec<toml::Value> {
@@ -843,6 +857,17 @@ required = [\"lsp:phoxite\"]
assert!(err(&src(&long)).contains("1 to 500 characters"));
}
#[test]
fn capability_reasons_explain_capabilities_that_contributions_bring() {
let src = |rest: &str| format!("{}{rest}", BASE.replace("^1.2", "^1.19"));
let reason = "[capabilities.reasons]\n\"java.agent\" = \"Captures the SQL MyBatis runs.\"\n";
let agent = "[[contributes.javaAgents]]\npath = \"agent.jar\"\n";
let m = Manifest::parse(&src(&format!("{reason}{agent}"))).unwrap();
assert_eq!(m.derived_capabilities(), [Capability::JavaAgent]);
assert_eq!(m.capabilities.reason(&Capability::JavaAgent), Some("Captures the SQL MyBatis runs."));
assert!(err(&src(reason)).contains("nor comes from a contribution"), "no javaAgents declaration");
}
#[test]
fn the_clipboard_read_capability_needs_api_1_11() {
let caps = "[capabilities]\noptional = [\"clipboard.read\"]\n";
+87 -11
Переглянути файл
@@ -448,13 +448,18 @@ async fn start_inner(
}
let target = ide_remote::service::run_target(&settings, id)?;
if target.kind != RunTargetKind::Ssh {
// A local run of the docker CLI: the command is resolved in the container, and
// this machine's toolchains and `PYTHONPATH` don't apply.
let mut config = config;
if ide_run::is_python_kind(&config.kind) {
container_python_path(&mut config.env, &super::python::paths(&project), &project.root);
}
let (config, note) = container::prepare(host, &project.root, target, config).await?;
// A local run of the docker CLI or `wsl.exe`: the command is resolved in the
// container or distribution, and this machine's toolchains and `PYTHONPATH` don't apply.
// The settings of the workspace member it belongs to derived its values.
let mut member = config.clone();
let (member_root, member_settings, fallback) = settings_for(host, &project, &mut member)?;
let derived = Derived { root: &member_root, fallback: fallback.as_deref(), settings: &member_settings };
let config = remote_config(&config, derived, &project.root, &super::python::paths(&project));
let (config, note) = if target.kind == RunTargetKind::Wsl {
(container::prepare_wsl(host, &project.root, target, config).await?, None)
} else {
container::prepare(host, &project.root, target, config).await?
};
if let Some(note) = note {
on_output(OutputChunk::System { text: format!("{note}\n") });
}
@@ -462,7 +467,7 @@ async fn start_inner(
let options = StartOptions {
encoding: Some(encoding).filter(|e| !e.trim().is_empty()),
python_paths: Vec::new(),
// A folder on this machine: not in the container.
// A folder on this machine: not in the container or distribution.
ruby_reporter: None,
plots: None,
capture_junit_reports: false,
@@ -864,6 +869,44 @@ pub use commands::*;
mod ownership_tests {
use super::*;
#[cfg(unix)]
#[test]
fn a_remote_run_gets_none_of_this_machines_derived_values() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let venv = root.join(".venv");
std::fs::create_dir_all(venv.join("bin")).unwrap();
std::fs::write(venv.join("pyvenv.cfg"), "home = /usr/bin\n").unwrap();
std::fs::write(venv.join("bin/python"), "").unwrap();
let mut settings = ide_core::settings::Settings::default();
settings.languages.python.interpreter = venv.join("bin/python").to_string_lossy().into_owned();
let mut config = RunConfig {
id: "app".into(),
name: "app".into(),
kind: "python".into(),
command: "python".into(),
args: vec!["main.py".into()],
cwd: None,
env: [("FOO".to_owned(), "bar".to_owned())].into(),
detected: false,
is_test: false,
debug_adapter: None,
allow_parallel: false,
extras: Default::default(),
};
config.extras.target = Some("wsl".into());
ide_sdk::apply::apply_to_run_configs(std::slice::from_mut(&mut config), root, &settings);
assert!(config.env.contains_key("VIRTUAL_ENV") && config.env.contains_key("PATH"), "{:?}", config.env);
config.env.insert("GOFLAGS".into(), "-mod=mod".into());
let derived = Derived { root, fallback: None, settings: &settings };
let out = remote_config(&config, derived, root, &[root.to_path_buf()]);
assert_eq!(out.env.keys().collect::<Vec<_>>(), ["FOO", "GOFLAGS", "PYTHONPATH"], "{:?}", out.env);
assert_eq!(out.command, "python", "the interpreter is the target's");
assert_eq!(out.extras.target.as_deref(), Some("wsl"));
assert!(has_local_path("/opt/go") && has_local_path("/a/bin:/b/bin"));
assert!(!has_local_path("-mod=mod") && !has_local_path("https://proxy.golang.org,direct"), "kept: not paths");
}
#[cfg(unix)]
#[test]
fn source_roots_go_on_the_container_pythonpath() {
@@ -1062,6 +1105,9 @@ pub async fn run_container_path(
if !path.starts_with('/') {
return Ok(None);
}
if run_target.kind == RunTargetKind::Wsl {
return Ok(ide_remote::wsl::local_file(&path, &run_target, &root).filter(|f| f.is_file()).map(Into::into));
}
let library = snapshots
.and_then(|dir| ide_sdk::container_python::current(&dir))
.and_then(|(dir, snapshot)| ide_sdk::container_python::snapshot_file(&dir, &snapshot, &path));
@@ -1074,9 +1120,39 @@ pub async fn run_container_path(
.await
}
/// The project's source roots on `PYTHONPATH` in a container, as a local run gets them:
/// they are mounted with the project, and `container::prepare` maps their paths. The
/// container's separator is `:`, whatever this machine's is.
/// `config` for a container or WSL distribution: without what settings derived from this
/// machine (its `PATH`, `VIRTUAL_ENV`, toolchain homes, resolved interpreter paths), which
/// would replace the values there, and with the project's source roots on `PYTHONPATH`.
/// Values that settings derive but that are not paths of this machine (`GOPROXY`, `GOFLAGS`)
/// still apply there and are kept.
fn remote_config(config: &RunConfig, derived: Derived<'_>, root: &Path, python_roots: &[PathBuf]) -> RunConfig {
let plain = ide_sdk::apply::without_derived_in(config, derived.root, derived.fallback, derived.settings);
let mut out = config.clone();
out.command = plain.command;
out.env.retain(|key, value| plain.env.contains_key(key) || !has_local_path(value));
if ide_run::is_python_kind(&out.kind) {
container_python_path(&mut out.env, python_roots, root);
}
out
}
/// The settings a configuration's derived values come from (see [`settings_for`]).
#[derive(Clone, Copy)]
struct Derived<'a> {
root: &'a Path,
fallback: Option<&'a Path>,
settings: &'a ide_core::settings::Settings,
}
/// `value` is an absolute path of this machine, alone or first in a path list (a URL such
/// as `GOPROXY`'s is not: its first part is `https`).
fn has_local_path(value: &str) -> bool {
std::env::split_paths(value).find(|p| !p.as_os_str().is_empty()).is_some_and(|p| p.is_absolute())
}
/// The project's source roots on `PYTHONPATH` in a container or WSL distribution, as a local
/// run gets them: they are mounted with the project, and `container::prepare` /
/// `prepare_wsl` map their paths. The separator there is `:`, whatever this machine's is.
fn container_python_path(env: &mut std::collections::BTreeMap<String, String>, roots: &[PathBuf], root: &Path) {
let mut paths: Vec<String> =
roots.iter().filter(|p| p.starts_with(root)).map(|p| p.to_string_lossy().into_owned()).collect();
+33 -2
Переглянути файл
@@ -1,5 +1,5 @@
//! Docker and Compose run targets: the configuration becomes a local run of the
//! docker CLI (see `ide_remote::docker`).
//! Docker, Compose and WSL run targets: the configuration becomes a local run of the
//! docker CLI (see `ide_remote::docker`) or of `wsl.exe` (see `ide_remote::wsl`).
use crate::Host;
use ide_core::remote_settings::{RunTarget, RunTargetKind};
@@ -73,6 +73,37 @@ pub(super) async fn prepare(
.await
}
/// `config` rewritten to run in `target`'s WSL distribution.
pub(super) async fn prepare_wsl(
host: &Host,
root: &Path,
target: RunTarget,
config: RunConfig,
) -> IdeResult<RunConfig> {
if !cfg!(windows) {
return Err(IdeError::invalid(format!(
"Run target '{}' is a WSL distribution: WSL needs Windows",
target.name
)));
}
let root = root.to_path_buf();
host.blocking(move || {
let linux_root = ide_remote::wsl::project_root(&target, &root)?;
let file_env = env_files(&root, &config)?;
let inherited = std::env::var("WSLENV").ok();
ide_remote::wsl::wsl_config(
&config,
&target,
&root,
&linux_root,
ide_core::wsl::EXE,
&file_env,
inherited.as_deref(),
)
})
.await
}
/// The project can only be bind-mounted from a daemon on this machine.
pub(crate) fn require_local(endpoint: &DockerEndpoint, target: &RunTarget) -> IdeResult<()> {
if !ide_docker::endpoint_is_local(endpoint)? {
+1 -1
Переглянути файл
@@ -12,7 +12,7 @@ use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
pub mod container_python;
pub use container_python::{ContainerPython, sdk_container_python, sdk_container_python_refresh};
pub use container_python::{ContainerPython, sdk_container_python, sdk_container_python_refresh, sdk_wsl_pythons};
/// Executables found for "run this file", and where single files are compiled to.
#[derive(Clone, Debug, serde::Serialize, specta::Type)]
+126 -12
Переглянути файл
@@ -4,6 +4,9 @@
//! A snapshot runs the target's Python once in a new container (the image's entrypoint
//! and the service's dependencies skipped), then copies its `sys.path` folders out of
//! the stopped container with `docker cp`. Nothing is installed in the container.
//!
//! A WSL run target's snapshot only records its Python's `sys.path`: the folders are read
//! in place through `\\wsl.localhost\<distro>`.
use crate::Host;
use crate::project::Project;
@@ -23,6 +26,8 @@ use std::time::Duration;
const PROBE_TIMEOUT: Duration = Duration::from_secs(15 * 60);
const COPY_TIMEOUT: Duration = Duration::from_secs(10 * 60);
const QUICK: Duration = Duration::from_secs(30);
/// Starting the distribution may come first.
const WSL_TIMEOUT: Duration = Duration::from_secs(2 * 60);
/// The project interpreter when it is a run target's.
#[derive(Clone, Debug, serde::Serialize, specta::Type)]
@@ -34,8 +39,10 @@ pub struct ContainerPython {
pub name: String,
/// The Python version of the snapshot in use; `None`: no snapshot yet.
pub version: Option<String>,
/// The image the snapshot was copied from.
/// The image the snapshot was copied from; `None` for WSL.
pub image: Option<String>,
/// The interpreter's path in the container or distribution.
pub executable: Option<String>,
/// The copied library folders on this machine.
pub folders: Vec<IpcPath>,
/// Packages of the snapshot (read-only).
@@ -108,22 +115,25 @@ pub(crate) fn library_group(host: &Host, root: &Path, settings: &Settings) -> Op
}
/// The project interpreter when it is a Docker or Compose run target's, with its snapshot.
/// Off the calling thread: a WSL interpreter's packages are read over `\\wsl.localhost`.
#[command(trust = trusted)]
pub fn sdk_container_python(host: &Host, window: &str) -> IdeResult<Option<ContainerPython>> {
pub async fn sdk_container_python(host: &Host, window: &str) -> IdeResult<Option<ContainerPython>> {
host.require_trust(window)?;
let project = host.project(window)?;
Ok(describe(host, &project.root, &project.settings.effective()))
let (dirs, root, settings) = (Dirs::of(host), project.root.clone(), project.settings.effective());
host.blocking(move || Ok(describe(&dirs, &root, &settings))).await
}
fn describe(host: &Host, root: &Path, settings: &Settings) -> Option<ContainerPython> {
fn describe(dirs: &Dirs, root: &Path, settings: &Settings) -> Option<ContainerPython> {
let target = settings.languages.python.run_target()?;
let name = settings.run_targets.iter().find(|t| t.id == target).map(|t| t.name.clone()).unwrap_or_default();
let dir = Dirs::of(host).target(root, target);
let dir = dirs.target(root, target);
let mut out = ContainerPython {
target: target.to_owned(),
name,
version: None,
image: None,
executable: None,
folders: Vec::new(),
packages: Vec::new(),
updating: updating(&dir),
@@ -132,7 +142,8 @@ fn describe(host: &Host, root: &Path, settings: &Settings) -> Option<ContainerPy
out.folders = snapshots::local_folders(&dir, &snapshot).into_iter().map(Into::into).collect();
out.packages = snapshots::packages(&dir, &snapshot);
out.version = Some(snapshot.probe.version);
out.image = Some(snapshot.image);
out.executable = Some(snapshot.probe.executable);
out.image = snapshot.distro.is_none().then_some(snapshot.image);
}
Some(out)
}
@@ -144,7 +155,8 @@ pub async fn sdk_container_python_refresh(host: &Host, window: &str) -> IdeResul
host.require_trust(window)?;
let project = host.project(window)?;
update(Dirs::of(host), &project, true).await?;
Ok(describe(host, &project.root, &project.settings.effective()))
let (dirs, root, settings) = (Dirs::of(host), project.root.clone(), project.settings.effective());
host.blocking(move || Ok(describe(&dirs, &root, &settings))).await
}
/// Takes a snapshot when the project interpreter is a run target's and the current image
@@ -154,13 +166,22 @@ pub(crate) fn ensure(host: &Host, project: &Arc<Project>) {
return;
}
let (dirs, project) = (Dirs::of(host), project.clone());
let settings = project.settings.effective();
let wsl = settings
.languages
.python
.run_target()
.and_then(|id| settings.run_targets.iter().find(|t| t.id == id))
.is_some_and(|t| t.kind == RunTargetKind::Wsl);
let title =
if wsl { "Cannot read the WSL Python's libraries" } else { "Cannot copy the container's Python libraries" };
host.runtime.spawn(async move {
if let Err(e) = update(dirs, &project, false).await
&& e.kind != ide_core::error::ErrorKind::Cancelled
{
project.sink.emit(IdeEvent::Notify {
level: NotifyLevel::Warning,
title: "Cannot copy the container's Python libraries".into(),
title: title.into(),
body: Some(e.message),
});
}
@@ -173,7 +194,7 @@ async fn update(dirs: Dirs, project: &Arc<Project>, force: bool) -> IdeResult<()
let target = ide_remote::service::run_target(&settings, id)?;
if target.kind == RunTargetKind::Ssh {
return Err(IdeError::invalid(format!(
"Run target '{}' runs over SSH: only a Docker or Compose run target can be the project interpreter",
"Run target '{}' is an SSH host: only a Docker, Compose or WSL run target can be the project interpreter",
target.name
)));
}
@@ -182,7 +203,10 @@ async fn update(dirs: Dirs, project: &Arc<Project>, force: bool) -> IdeResult<()
return Ok(());
}
let _done = Updating(dir.clone());
let endpoint = crate::ops::run::container::endpoint(&dirs.data, &target)?;
let endpoint = match target.kind {
RunTargetKind::Wsl => None,
_ => Some(crate::ops::run::container::endpoint(&dirs.data, &target)?),
};
let task = TaskId::next();
let title = format!("Python libraries of {}", target.name);
let (root, sink) = (project.root.clone(), project.sink.clone());
@@ -198,7 +222,11 @@ async fn update(dirs: Dirs, project: &Arc<Project>, force: bool) -> IdeResult<()
};
let report = progress.clone();
let result = tokio::task::spawn_blocking(move || {
take(&endpoint, &root, &target, &dir, &dirs.cache, force, &|message| report(message, false))
let report = |message: &str| report(message, false);
match endpoint {
Some(endpoint) => take(&endpoint, &root, &target, &dir, &dirs.cache, force, &report),
None => take_wsl(&root, &target, &dir, &dirs.cache, &report),
}
})
.await
.map_err(|e| IdeError::internal(e.to_string()))
@@ -288,6 +316,7 @@ fn take(
image: image.clone(),
probe,
folders,
distro: None,
};
snapshots::write(&partial, &snapshot)?;
if dir.exists() {
@@ -298,6 +327,72 @@ fn take(
Ok(true)
}
/// Records where the WSL target's Python finds its libraries and makes that the snapshot in
/// use; `false` when nothing changed. Nothing is copied, so packages installed later show up.
fn take_wsl(
root: &Path,
target: &RunTarget,
target_dir: &Path,
cache: &Path,
progress: &dyn Fn(&str),
) -> IdeResult<bool> {
if !cfg!(windows) {
return Err(IdeError::unavailable(format!(
"Run target '{}' is a WSL distribution: WSL needs Windows",
target.name
)));
}
let linux_root = ide_remote::wsl::project_root(target, root)?;
let distro = target.distro.trim();
progress("Starting the WSL Python");
let out = ide_core::wsl::exec(distro, &[ide_remote::wsl::python(target), "-c", snapshots::PROBE], WSL_TIMEOUT)?;
let probe = snapshots::parse_probe(&out)?;
let id = format!("wsl-{}-{}", probe.executable, probe.version);
let snapshot = Snapshot {
image: id.clone(),
folders: wsl_folders(&probe, &linux_root),
neutral_python: snapshots::neutral_python(cache, &probe.version),
distro: Some(distro.to_owned()),
probe,
};
// What the language server is given: the probe's other details (its raw `sys.path` order,
// say) are kept in the snapshot but don't restart it.
let libraries = |s: &Snapshot| (s.image.clone(), s.folders.clone(), s.neutral_python.clone(), s.distro.clone());
let changed = snapshots::current(target_dir).map(|(_, s)| libraries(&s)) != Some(libraries(&snapshot));
let dir = target_dir.join(snapshots::dir_name(&id));
std::fs::create_dir_all(&dir)?;
snapshots::write(&dir, &snapshot)?;
snapshots::make_current(target_dir, &id)?;
Ok(changed)
}
/// The library folders of a WSL Python: as a container's, plus a virtualenv's in the project
/// (`.venv/lib/python3.12/site-packages`), which a container mount would hold anyway.
fn wsl_folders(probe: &snapshots::Probe, linux_root: &str) -> Vec<String> {
let root = linux_root.trim_end_matches('/');
let in_project = |f: &str| root.is_empty() || f == root || f.starts_with(&format!("{root}/"));
let packages = |f: &str| f.split('/').any(|c| c == "site-packages" || c == "dist-packages");
snapshots::folders_to_copy(probe, "").into_iter().filter(|f| !in_project(f) || packages(f)).collect()
}
/// The Pythons found in a WSL distribution, for Add Python Interpreter: the ones on its
/// `PATH`, in `/usr/bin` and `/usr/local/bin`, pyenv's, and the project's virtualenv. Empty off Windows.
#[command(trust = trusted)]
pub async fn sdk_wsl_pythons(host: &Host, window: &str, distro: String) -> IdeResult<Vec<String>> {
host.require_trust(window)?;
if !cfg!(windows) {
return Ok(Vec::new());
}
let root = host.project(window)?.root.clone();
host.blocking(move || {
let distro = distro.trim();
let linux_root = ide_core::wsl::linux_path(&root, distro).unwrap_or_default();
let script = ["sh", "-c", ide_remote::wsl::FIND_PYTHONS, "sh", &linux_root];
Ok(ide_remote::wsl::parse_pythons(&ide_core::wsl::exec(distro, &script, WSL_TIMEOUT)?))
})
.await
}
/// Distinguishes probe containers.
fn unique() -> String {
use std::sync::atomic::{AtomicU32, Ordering};
@@ -306,4 +401,23 @@ fn unique() -> String {
format!("{:x}-{}-{}", secs & 0xff_ffff, std::process::id(), COUNT.fetch_add(1, Ordering::Relaxed))
}
ide_command::domain!(sdk_container_python: sdk_container_python, sdk_container_python_refresh);
#[cfg(test)]
mod wsl_tests {
#[test]
fn a_virtualenv_in_the_project_is_read_and_its_sources_are_not() {
let probe = super::snapshots::Probe {
version: "3.12.3".into(),
executable: "/mnt/c/p/.venv/bin/python".into(),
stdlib: vec![Some("/usr/lib/python3.12".into())],
path: ["/mnt/c/p/src", "/usr/lib/python3.12", "/mnt/c/p/.venv/lib/python3.12/site-packages", "/opt/extra"]
.map(String::from)
.to_vec(),
};
assert_eq!(
super::wsl_folders(&probe, "/mnt/c/p"),
["/mnt/c/p/.venv/lib/python3.12/site-packages", "/opt/extra"]
);
}
}
ide_command::domain!(sdk_container_python: sdk_container_python, sdk_container_python_refresh, sdk_wsl_pythons);
+1 -1
Переглянути файл
@@ -107,7 +107,7 @@ async fn compose_target_is_the_python_interpreter() {
eprintln!("run target interpreter: {after:?}");
assert!(after.iter().all(|m| !m.contains("could not be resolved")), "{after:?}");
let info = ops::sdk::sdk_container_python(&host, WINDOW).unwrap().expect("a run target interpreter");
let info = ops::sdk::sdk_container_python(&host, WINDOW).await.unwrap().expect("a run target interpreter");
eprintln!("snapshot: version {:?}, image {:?}, folders {:?}", info.version, info.image, info.folders);
assert_eq!(info.name, "Compose web");
assert!(info.version.as_deref().is_some_and(|v| v.starts_with("3.12.")), "{info:?}");
+4 -2
Переглянути файл
@@ -225,7 +225,9 @@ pub fn container_config(config: &RunConfig, run: &ContainerRun) -> IdeResult<Run
args.push("--no-TTY".into());
}
}
RunTargetKind::Ssh => return Err(IdeError::internal("an SSH target does not run in a container")),
RunTargetKind::Ssh | RunTargetKind::Wsl => {
return Err(IdeError::internal("this run target does not run in a container"));
}
}
args.extend(["--name".into(), run.name.to_owned(), "--label".into(), format!("openidea.run={}", config.id)]);
args.extend(["--workdir".into(), command.cwd.clone()]);
@@ -341,7 +343,7 @@ pub fn python_probe_args(target: &RunTarget, root: &Path, name: &str, code: &str
}
args.extend(["run", "--no-deps", "--no-TTY"].map(String::from));
}
RunTargetKind::Ssh => {
RunTargetKind::Ssh | RunTargetKind::Wsl => {
return Err(IdeError::invalid(format!("Run target '{}' is not a container", target.name)));
}
}
+3 -1
Переглянути файл
@@ -1,5 +1,6 @@
//! Remote work over SSH: SFTP deployment ([`deploy`], [`mapping`]) and run
//! configurations on run targets ([`target`]; Docker and Compose ones in [`docker`]).
//! configurations on run targets ([`target`]; Docker and Compose ones in [`docker`], WSL
//! ones in [`wsl`]).
pub mod container_tunnel;
pub mod deploy;
@@ -10,6 +11,7 @@ pub mod mapping;
pub mod service;
pub mod target;
pub mod upload;
pub mod wsl;
pub use deploy::{
Deployment, DeploymentCoverage, SyncAction, SyncEntry, SyncStatus, SyncStep, TransferReport, coverage,
+1 -1
Переглянути файл
@@ -438,7 +438,7 @@ impl RemoteService {
let target_id = config.extras.target.as_deref().unwrap_or_default();
let target = run_target(settings, target_id)?;
if target.kind != ide_core::remote_settings::RunTargetKind::Ssh {
return Err(IdeError::internal("container run targets start as local runs of the docker CLI"));
return Err(IdeError::internal("container and WSL run targets start as local runs"));
}
let session = self.ssh.session(&target.ssh_config).await?;
let fs = RemoteFs::new(session.sftp().await?).with_shell(session.clone());
+8 -2
Переглянути файл
@@ -72,7 +72,8 @@ fn replace_root(s: &str, root: &str, remote: &str) -> String {
out.push_str(remote);
if root.contains('\\') {
let end = after
.find(|c: char| c.is_whitespace() || matches!(c, ';' | ',' | '"' | '\''))
// `:` too: past the drive letter, it only separates a POSIX path list.
.find(|c: char| c.is_whitespace() || matches!(c, ';' | ':' | ',' | '"' | '\''))
.unwrap_or(after.len());
out.push_str(&after[..end].replace('\\', "/"));
after = &after[end..];
@@ -191,7 +192,7 @@ pub fn debugpy_probe(debug: &RemoteCommand, bootstrap: &str) -> String {
/// `java` flags whose value is a path list that may point outside the project
/// (`~/.m2` jars, `--module-path` entries): deployment sync only uploads the
/// project root, so these entries need their own sync + rewrite (#2641).
const PATH_LIST_FLAGS: [&str; 6] =
pub(crate) const PATH_LIST_FLAGS: [&str; 6] =
["-cp", "-classpath", "--class-path", "-p", "--module-path", "--upgrade-module-path"];
/// The separator of a `-cp` value on this (client) machine.
@@ -635,6 +636,11 @@ mod tests {
assert_eq!(replace_root("/work/proj2/x:/work/proj/y", "/work/proj", "/srv"), "/work/proj2/x:/srv/y");
assert_eq!(replace_root("/work/proj", "/work/proj", "/srv"), "/srv");
assert_eq!(replace_root(r"C:\p\src/a.py C:\p2", r"C:\p", "/srv"), r"/srv/src/a.py C:\p2");
assert_eq!(
replace_root(r"C:\work\proj:C:\work\proj\src", r"C:\work\proj", "/mnt/c/work/proj"),
"/mnt/c/work/proj:/mnt/c/work/proj/src",
"each root of a PYTHONPATH list"
);
}
/// Unix/Windows spellings of the same layout: one inside-root entry, one
+426
Переглянути файл
@@ -0,0 +1,426 @@
//! Run configurations on WSL run targets: rewritten into a local run of
//! `wsl.exe -d <distro> --cd <dir> --exec <program> <args>`, with the project's paths
//! and interpreters swapped for their Linux counterparts. The console, stdin, Stop and
//! test parsers then work as for any local run.
use crate::target::remote_command;
use ide_core::remote_settings::RunTarget;
use ide_core::{IdeError, IdeResult};
use ide_run::RunConfig;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
/// Where the project is inside the target's distribution.
pub fn project_root(target: &RunTarget, root: &Path) -> IdeResult<String> {
match target.project_root.trim().trim_end_matches('/') {
"" if target.project_root.trim().starts_with('/') => Ok("/".into()),
"" => ide_core::wsl::linux_path(root, target.distro.trim()).ok_or_else(|| {
IdeError::invalid(format!(
"Run target '{}' can't reach {} from WSL: set the project's Linux path in Settings › Run Targets",
target.name,
root.display()
))
}),
folder => Ok(folder.to_owned()),
}
}
/// The file on this machine of a path a run in the target's distribution printed (a
/// traceback line): in the project, on a drive under `/mnt/<drive>`, else in the
/// distribution's own file system (`\\wsl.localhost\<distro>`).
pub fn local_file(path: &str, target: &RunTarget, root: &Path) -> Option<PathBuf> {
if !path.starts_with('/') {
return None;
}
if let Ok(linux_root) = project_root(target, root) {
let linux_root = linux_root.trim_end_matches('/');
if let Some(rest) =
path.strip_prefix(linux_root).filter(|r| r.is_empty() || r.starts_with('/') || linux_root.is_empty())
{
return Some(ide_core::wsl::path_parts(rest).into_iter().fold(root.to_path_buf(), |p, c| p.join(c)));
}
}
Some(ide_core::wsl::windows_path(path, target.distro.trim()))
}
fn is_java(command: &str) -> bool {
let name = command.trim().rsplit(['/', '\\']).next().unwrap_or("");
name.to_ascii_lowercase().trim_end_matches(".exe") == "java"
}
/// The `-cp` / `--module-path` values of `java` arguments as the distribution reads them:
/// each absolute entry outside the project through its `/mnt` path, joined with `:`.
/// Entries in the project stay as they are: `remote_command` maps them onto its folder there.
fn linux_path_lists(args: &[String], root: &Path, distro: &str) -> Vec<String> {
let mut out = args.to_vec();
for i in 1..out.len() {
if !crate::target::PATH_LIST_FLAGS.contains(&out[i - 1].as_str()) || out[i].contains("${") {
continue;
}
let entries: Vec<String> = out[i]
.split(crate::target::classpath_separator())
.filter(|e| !e.is_empty())
.map(|e| {
let path = Path::new(e);
if path.starts_with(root) {
return e.to_owned();
}
match path.is_absolute().then(|| ide_core::wsl::linux_path(path, distro)).flatten() {
Some(linux) => linux,
None => e.replace('\\', "/"),
}
})
.collect();
out[i] = entries.join(":");
}
out
}
/// The target's Python: its own, or `python3` on the distribution's `PATH`.
pub fn python(target: &RunTarget) -> &str {
match target.python.trim() {
"" => "python3",
python => python,
}
}
/// Run with `sh -c` in a distribution, the project's Linux folder as `$1`: prints the
/// Pythons found there, one path a line.
pub const FIND_PYTHONS: &str = r#"for p in "$(command -v python3)" "$(command -v python)" /usr/bin/python3* /usr/local/bin/python3* "$HOME"/.pyenv/versions/*/bin/python "$1/.venv/bin/python" "$1/venv/bin/python"; do case "$p" in *-config) continue ;; esac; [ -f "$p" ] && [ -x "$p" ] && echo "$p"; done; true"#;
/// The paths [`FIND_PYTHONS`] printed, without repeats and without the tools named after
/// Python (`python3-pytest`, `python3.12-config`).
pub fn parse_pythons(out: &str) -> Vec<String> {
let interpreter = |path: &str| {
let name = path.rsplit('/').next().unwrap_or("");
let version = name.strip_prefix("python").unwrap_or("-");
version.chars().all(|c| c.is_ascii_digit() || c == '.')
};
let mut found: Vec<String> = Vec::new();
for line in out.lines().map(str::trim).filter(|l| l.starts_with('/') && interpreter(l)) {
if !found.iter().any(|f| f == line) {
found.push(line.to_owned());
}
}
found
}
/// `config` as a local run of `wsl_exe` that runs it in the target's distribution.
/// `file_env` holds the variables of the configuration's `.env` files, already read;
/// `inherited_wslenv` is this machine's `WSLENV`, kept for the distribution.
pub fn wsl_config(
config: &RunConfig,
target: &RunTarget,
root: &Path,
linux_root: &str,
wsl_exe: &str,
file_env: &BTreeMap<String, String>,
inherited_wslenv: Option<&str>,
) -> IdeResult<RunConfig> {
let distro = target.distro.trim();
if !ide_core::wsl::is_valid_distro(distro) {
return Err(IdeError::invalid(format!(
"Run target '{}' has no WSL distribution; choose one in Settings › Run Targets",
target.name
)));
}
let mut command = if is_java(&config.command) {
let mut java = config.clone();
java.args = linux_path_lists(&config.args, root, distro);
remote_command(&java, target, root, linux_root)
} else {
remote_command(config, target, root, linux_root)
};
// Outside the project `remote_command` falls back to the project folder: a folder of
// this machine is reached through its own `/mnt` path instead.
if let Some(dir) = config.cwd.as_ref().map(|d| d.to_path_buf()).filter(|d| d.is_absolute() && !d.starts_with(root))
{
command.cwd = ide_core::wsl::linux_path(&dir, distro).ok_or_else(|| {
IdeError::invalid(format!(
"Run target '{}' can't reach the working folder {} from WSL",
target.name,
dir.display()
))
})?;
}
let mut env = file_env.clone();
if ide_run::is_python_kind(&config.kind) && !command.env.contains_key("PYTHONUNBUFFERED") {
env.insert("PYTHONUNBUFFERED".into(), "1".into());
}
env.extend(command.env.clone());
// The distribution keeps its own `PATH`: a value here is this machine's, or a `.env`
// `PATH=$PATH:…` already expanded against it.
env.remove("PATH");
let mut args: Vec<String> = ["-d", distro, "--cd", &command.cwd, "--exec"].map(String::from).to_vec();
// A Python run finds the console scripts next to the target's interpreter (a virtualenv's
// `pytest`) first, as a local run with the project interpreter does.
let scripts = (ide_run::is_python_kind(&config.kind) && target.python.trim().starts_with('/'))
.then(|| target.python.trim().rsplit_once('/').map(|(dir, _)| dir.to_owned()))
.flatten()
.filter(|dir| !dir.is_empty());
match (command.shell_line, scripts) {
(Some(line), None) => args.extend(["sh".into(), "-c".into(), line]),
(Some(line), Some(dir)) => args.extend(["sh".into(), "-c".into(), format!("PATH=\"$0:$PATH\"; {line}"), dir]),
(None, None) => {
args.push(command.program);
args.extend(command.args);
}
(None, Some(dir)) => {
args.extend(["sh".into(), "-c".into(), r#"PATH="$0:$PATH" exec "$@""#.into(), dir, command.program]);
args.extend(command.args);
}
}
// Values cross into the distribution through the environment (`WSLENV` lists the
// names), so they stay out of the command line echoed in the console. The configuration's
// own `WSLENV` entries (`FOO/p`) are kept with their flags.
let own = env.remove("WSLENV");
let mut wslenv: Vec<&str> = inherited_wslenv
.into_iter()
.chain(own.as_deref())
.flat_map(|v| v.split(':'))
.filter(|n| !n.is_empty())
.collect();
let listed = |name: &str, list: &[&str]| list.iter().any(|n| n.split('/').next() == Some(name));
for name in env.keys() {
if !listed(name, &wslenv) {
wslenv.push(name);
}
}
let wslenv = wslenv.join(":");
if !wslenv.is_empty() {
env.insert("WSLENV".into(), wslenv);
}
let mut out = config.clone();
out.command = wsl_exe.to_owned();
out.args = args;
out.cwd = Some(root.to_path_buf().into());
out.env = env;
let extras = &mut out.extras;
extras.target = None;
extras.env_files.clear();
// `wsl.exe` needs this machine's environment; the distribution gets only `WSLENV`'s names.
extras.include_system_env = true;
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
use ide_core::remote_settings::RunTargetKind;
fn target() -> RunTarget {
RunTarget { kind: RunTargetKind::Wsl, name: "wsl".into(), distro: "Ubuntu-24.04".into(), ..Default::default() }
}
fn config(command: &str, args: &[&str]) -> RunConfig {
RunConfig {
id: "app".into(),
name: "app".into(),
kind: "python".into(),
command: command.into(),
args: args.iter().map(|a| (*a).to_owned()).collect(),
cwd: None,
env: BTreeMap::new(),
detected: false,
is_test: false,
debug_adapter: None,
allow_parallel: false,
extras: Default::default(),
}
}
#[test]
fn the_project_root_is_the_targets_or_its_mnt_path() {
let t = target();
assert_eq!(project_root(&t, Path::new(r"C:\work\proj")).unwrap(), "/mnt/c/work/proj");
assert_eq!(project_root(&t, Path::new(r"\\wsl.localhost\Ubuntu-24.04\home\me\p")).unwrap(), "/home/me/p");
let err = project_root(&t, Path::new(r"\\server\share\p")).unwrap_err();
assert!(err.message.contains("set the project's Linux path"), "{}", err.message);
let custom = RunTarget { project_root: " /c/work/proj/ ".into(), ..t.clone() };
assert_eq!(project_root(&custom, Path::new(r"\\server\share\p")).unwrap(), "/c/work/proj");
let slash = RunTarget { project_root: "/".into(), ..t };
assert_eq!(project_root(&slash, Path::new("x")).unwrap(), "/");
}
// Unix paths are not absolute on Windows; `windows_paths_are_mapped` covers Windows.
#[cfg(unix)]
#[test]
fn a_program_runs_through_wsl_exe_with_its_variables_by_name() {
let mut c = config("/work/proj/.venv/bin/python", &["-u", "/work/proj/main.py", "a b"]);
c.cwd = Some(Path::new("/work/proj/src").to_path_buf().into());
c.env.insert("DATA".into(), "/work/proj/data".into());
c.extras.target = Some("t".into());
c.extras.env_files = vec![".env".into()];
let files = BTreeMap::from([("SECRET".to_owned(), "s3".to_owned())]);
let out =
wsl_config(&c, &target(), Path::new("/work/proj"), "/mnt/c/proj", "wsl.exe", &files, Some("USERPROFILE/p"))
.unwrap();
assert_eq!(out.command, "wsl.exe");
assert_eq!(
out.args,
["-d", "Ubuntu-24.04", "--cd", "/mnt/c/proj/src", "--exec", "python3", "-u", "/mnt/c/proj/main.py", "a b"]
);
assert_eq!(out.env["DATA"], "/mnt/c/proj/data");
assert_eq!(out.env["SECRET"], "s3");
assert_eq!(out.env["PYTHONUNBUFFERED"], "1");
assert_eq!(out.env["WSLENV"], "USERPROFILE/p:DATA:PYTHONUNBUFFERED:SECRET");
assert_eq!(out.cwd.as_ref().map(|p| p.to_path_buf()), Some(Path::new("/work/proj").to_path_buf()));
assert_eq!(out.extras.target, None);
assert!(out.extras.env_files.is_empty());
assert!(out.extras.include_system_env);
}
#[test]
fn a_shell_line_runs_in_sh_and_the_targets_interpreter_is_used() {
let mut shell = config("npm run dev", &[]);
shell.kind = "shell".into();
let out =
wsl_config(&shell, &target(), Path::new("proj"), "/mnt/c/proj", "wsl.exe", &BTreeMap::new(), None).unwrap();
assert_eq!(out.args, ["-d", "Ubuntu-24.04", "--cd", "/mnt/c/proj", "--exec", "sh", "-c", "npm run dev"]);
assert!(!out.env.contains_key("WSLENV"));
let t = RunTarget { python: "/home/me/.venv/bin/python".into(), ..target() };
let out =
wsl_config(&config("python.exe", &["-V"]), &t, Path::new("proj"), "/p", "wsl.exe", &BTreeMap::new(), None)
.unwrap();
let path_first = r#"PATH="$0:$PATH" exec "$@""#;
assert_eq!(
&out.args[4..],
["--exec", "sh", "-c", path_first, "/home/me/.venv/bin", "/home/me/.venv/bin/python", "-V"],
"the virtualenv's scripts come first on PATH"
);
let mut pytest = config("pytest", &["tests"]);
pytest.kind = "pytest".into();
let out = wsl_config(&pytest, &t, Path::new("proj"), "/p", "wsl.exe", &BTreeMap::new(), None).unwrap();
assert_eq!(&out.args[9..], ["pytest", "tests"]);
}
#[test]
fn a_configurations_wslenv_keeps_its_flags_and_an_outside_folder_is_refused() {
let mut c = config("python", &[]);
c.env.insert("WSLENV".into(), "DATA/p".into());
c.env.insert("DATA".into(), "x".into());
let out = wsl_config(&c, &target(), Path::new("proj"), "/p", "wsl.exe", &BTreeMap::new(), Some("A/u")).unwrap();
assert_eq!(out.env["WSLENV"], "A/u:DATA/p:PYTHONUNBUFFERED");
c.env.insert("PATH".into(), "/here/bin:/usr/bin".into());
let out = wsl_config(&c, &target(), Path::new("proj"), "/p", "wsl.exe", &BTreeMap::new(), None).unwrap();
assert!(!out.env.contains_key("PATH") && !out.env["WSLENV"].contains("PATH"), "{:?}", out.env);
// An absolute folder of this machine outside the project (`/elsewhere` has no `/mnt` path).
let outside = if cfg!(windows) { r"\\server\share\x" } else { "/elsewhere" };
c.cwd = Some(Path::new(outside).to_path_buf().into());
let root = if cfg!(windows) { r"C:\proj" } else { "/proj" };
let err = wsl_config(&c, &target(), Path::new(root), "/p", "wsl.exe", &BTreeMap::new(), None).unwrap_err();
assert!(err.message.contains("can't reach the working folder"), "{}", err.message);
}
#[cfg(unix)]
#[test]
fn java_path_lists_are_joined_with_colons() {
let args: Vec<String> = ["-cp", "out:lib/*", "-p", "/opt/mods", "Main"].map(String::from).to_vec();
assert_eq!(linux_path_lists(&args, Path::new("/p"), "Ubuntu"), ["-cp", "out:lib/*", "-p", "/opt/mods", "Main"]);
assert!(is_java("/usr/lib/jvm/bin/java") && is_java(r"C:\jdk\bin\JAVA.EXE") && !is_java("javac"));
}
#[test]
fn printed_paths_lead_back_to_files_here() {
let t = RunTarget { project_root: "/mnt/c/work/proj".into(), ..target() };
let root = Path::new("proj-here");
assert_eq!(local_file("/mnt/c/work/proj/app/main.py", &t, root), Some(root.join("app").join("main.py")));
assert_eq!(
local_file("/mnt/d/lib/x.py", &t, root),
Some(PathBuf::from("D:\\").join("lib").join("x.py")),
"another drive"
);
assert_eq!(
local_file("/usr/lib/python3/dist-packages/a.py", &t, root),
Some(
ide_core::wsl::share_root("Ubuntu-24.04")
.join("usr")
.join("lib")
.join("python3")
.join("dist-packages")
.join("a.py")
)
);
assert_eq!(
local_file("/mnt/c/work/proj2/a.py", &t, root),
Some(PathBuf::from("C:\\").join("work").join("proj2").join("a.py"))
);
assert_eq!(local_file("main.py", &t, root), None);
assert_eq!(local_file("/mnt/c/work/proj/app/../lib/a.py", &t, root), Some(root.join("lib").join("a.py")));
}
#[test]
fn pythons_are_listed_once_and_python3_is_the_default() {
let out = "/usr/bin/python3\n\n/usr/bin/python3\n/usr/bin/python3.12\nsh: 1: bad\n/usr/bin/python3-pytest\n\
/usr/bin/python3.12-config\n/mnt/c/p/.venv/bin/python\r\n";
assert_eq!(parse_pythons(out), ["/usr/bin/python3", "/usr/bin/python3.12", "/mnt/c/p/.venv/bin/python"]);
assert_eq!(python(&target()), "python3");
assert_eq!(python(&RunTarget { python: " /opt/py/bin/python ".into(), ..target() }), "/opt/py/bin/python");
}
// The script itself, in this machine's `sh`.
#[cfg(unix)]
#[test]
fn the_python_finder_lists_a_venv_of_the_project() {
let dir = tempfile::tempdir().unwrap();
let bin = dir.path().join(".venv/bin");
std::fs::create_dir_all(&bin).unwrap();
let python = bin.join("python");
std::fs::write(&python, "#!/bin/sh\n").unwrap();
std::fs::set_permissions(&python, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap();
let out = std::process::Command::new("sh").args(["-c", FIND_PYTHONS, "sh"]).arg(dir.path()).output().unwrap();
assert!(out.status.success());
let found = parse_pythons(&String::from_utf8_lossy(&out.stdout));
assert!(found.contains(&python.to_string_lossy().into_owned()), "{found:?}");
assert!(found.iter().all(|p| !p.ends_with("-config")), "{found:?}");
}
#[test]
fn a_target_without_a_valid_distribution_is_refused() {
for distro in ["", " ", "-u root", "a;b"] {
let t = RunTarget { distro: distro.into(), ..target() };
let err = wsl_config(&config("python", &[]), &t, Path::new("p"), "/p", "wsl.exe", &BTreeMap::new(), None)
.unwrap_err();
assert!(err.message.contains("no WSL distribution"), "{distro}: {}", err.message);
}
}
#[cfg(windows)]
#[test]
fn windows_paths_are_mapped() {
let root = Path::new(r"C:\work\proj");
let linux = project_root(&target(), root).unwrap();
let mut c = config(r"C:\work\proj\.venv\Scripts\python.exe", &[r"C:\work\proj\app\main.py"]);
c.cwd = Some(Path::new(r"C:\work\proj\app").to_path_buf().into());
let out = wsl_config(&c, &target(), root, &linux, "wsl.exe", &BTreeMap::new(), None).unwrap();
assert_eq!(
out.args,
["-d", "Ubuntu-24.04", "--cd", "/mnt/c/work/proj/app", "--exec", "python3", "/mnt/c/work/proj/app/main.py"]
);
let java = config(
r"C:\jdk\bin\java.exe",
&["-cp", r"C:\work\proj\out;D:\m2\a.jar;lib\*", "--module-path", r"C:\work\proj\mods", "app.Main"],
);
let out = wsl_config(&java, &target(), root, &linux, "wsl.exe", &BTreeMap::new(), None).unwrap();
assert_eq!(
&out.args[4..],
[
"--exec",
"java",
"-cp",
"/mnt/c/work/proj/out:/mnt/d/m2/a.jar:lib/*",
"--module-path",
"/mnt/c/work/proj/mods",
"app.Main"
]
);
let custom = RunTarget { project_root: "/home/me/proj".into(), ..target() };
let java = config(r"C:\jdk\bin\java.exe", &["-cp", r"C:\work\proj\out;D:\m2\a.jar", "app.Main"]);
let out = wsl_config(&java, &custom, root, "/home/me/proj", "wsl.exe", &BTreeMap::new(), None).unwrap();
assert_eq!(out.args[7], "/home/me/proj/out:/mnt/d/m2/a.jar", "project entries go to its folder there");
c.cwd = Some(Path::new(r"D:\data").to_path_buf().into());
let out = wsl_config(&c, &target(), root, &linux, "wsl.exe", &BTreeMap::new(), None).unwrap();
assert_eq!(out.args[3], "/mnt/d/data", "a folder outside the project, through its /mnt path");
}
}
+39 -5
Переглянути файл
@@ -81,7 +81,11 @@ pub fn folders_to_copy(probe: &Probe, container_root: &str) -> Vec<String> {
/// Where a snapshot in `dir` keeps its copy of the container folder `container`.
pub fn local_folder(dir: &Path, container: &str) -> PathBuf {
container.split('/').filter(|c| !c.is_empty() && *c != "." && *c != "..").fold(dir.join("fs"), |p, c| p.join(c))
below(dir.join("fs"), container)
}
fn below(base: PathBuf, path: &str) -> PathBuf {
path.split('/').filter(|c| !c.is_empty() && *c != "." && *c != "..").fold(base, |p, c| p.join(c))
}
/// Where a snapshot in `dir` keeps the file `container_path` of its container (a
@@ -91,7 +95,7 @@ pub fn snapshot_file(dir: &Path, snapshot: &Snapshot, container_path: &str) -> O
.folders
.iter()
.any(|f| container_path.strip_prefix(f.trim_end_matches('/')).is_some_and(|rest| rest.starts_with('/')));
(copied && !container_path.split('/').any(|c| c == "..")).then(|| local_folder(dir, container_path))
(copied && !container_path.split('/').any(|c| c == "..")).then(|| snapshot.local(dir, container_path))
}
/// `snapshot.json` of a snapshot folder.
@@ -105,6 +109,21 @@ pub struct Snapshot {
pub folders: Vec<String>,
/// The neutral interpreter given to the language server; `None` without a local Python.
pub neutral_python: Option<PathBuf>,
/// A WSL interpreter's distribution. Its folders are read in place, not copied: on their
/// drive under `/mnt/<drive>`, the rest through `\\wsl.localhost\<distro>`.
#[serde(skip_serializing_if = "Option::is_none")]
pub distro: Option<String>,
}
impl Snapshot {
/// Where this machine reads the interpreter's folder or file `path`.
pub fn local(&self, dir: &Path, path: &str) -> PathBuf {
match &self.distro {
// `..` never climbs above the drive or the distribution's share.
Some(distro) => ide_core::wsl::windows_path(path, distro),
None => local_folder(dir, path),
}
}
}
const SNAPSHOT_FILE: &str = "snapshot.json";
@@ -160,8 +179,11 @@ pub fn make_current(target_dir: &Path, image: &str) -> IdeResult<()> {
}
/// The local folders of a snapshot that exist.
/// A WSL snapshot's folders are taken as they were probed: checking them would read the
/// distribution's file system, which may be slow or still starting.
pub fn local_folders(dir: &Path, snapshot: &Snapshot) -> Vec<PathBuf> {
snapshot.folders.iter().map(|f| local_folder(dir, f)).filter(|p| p.is_dir()).collect()
let folders = snapshot.folders.iter().map(|f| snapshot.local(dir, f));
if snapshot.distro.is_some() { folders.collect() } else { folders.filter(|p| p.is_dir()).collect() }
}
/// basedpyright / pyright: the neutral interpreter and the snapshot's folders as
@@ -189,8 +211,8 @@ pub fn library_group(target_name: &str, dir: &Path, snapshot: &Snapshot) -> Opti
let roots: Vec<LibraryRoot> = snapshot
.folders
.iter()
.map(|f| (f, local_folder(dir, f)))
.filter(|(_, p)| p.is_dir())
.map(|f| (f, snapshot.local(dir, f)))
.filter(|(_, p)| snapshot.distro.is_some() || p.is_dir())
.map(|(f, p)| LibraryRoot { name: f.rsplit('/').next().unwrap_or(f).to_owned(), path: p.into() })
.collect();
(!roots.is_empty()).then(|| LibraryGroup {
@@ -318,6 +340,17 @@ mod tests {
local_folder(dir, "/usr/local/lib/../site-packages"),
Path::new("snap").join("fs").join("usr").join("local").join("lib").join("site-packages")
);
let wsl = Snapshot { distro: Some("U".into()), ..Snapshot::default() };
assert_eq!(
wsl.local(dir, "/usr/lib/python3/dist-packages"),
ide_core::wsl::share_root("U").join("usr").join("lib").join("python3").join("dist-packages"),
"a WSL snapshot reads the distribution in place"
);
assert_eq!(
wsl.local(dir, "/mnt/c/p/.venv/lib"),
PathBuf::from("C:\\").join("p").join(".venv").join("lib"),
"a drive directly"
);
assert_eq!(dir_name("sha256:0123456789abcdef0123"), "0123456789abcdef");
assert_eq!(dir_name("target/../x y"), "target____x_y");
}
@@ -344,6 +377,7 @@ mod tests {
probe: probe(),
folders: vec!["/usr/local/lib/python3.12/site-packages".into(), "/gone".into()],
neutral_python: neutral,
distro: None,
};
let site = local_folder(dir, &snapshot.folders[0]);
std::fs::create_dir_all(site.join("Django-5.1.3.dist-info")).unwrap();
+11
Переглянути файл
@@ -145,6 +145,17 @@ The **Ports** tool window is available in a WSL window too. Because the distribu
`localhost`, a forwarded port is reachable here on the same port; the window lists, opens and remembers ports as it
does for SSH.
### Run a Windows project in WSL
A project on the Windows file system can keep its local window and run its configurations in a distribution: in
**Settings › Build, Execution, Deployment › Run Targets**, add a target of **Type** **WSL** (offered when a
distribution is installed) and pick the **WSL distribution**. A configuration with that target under **Run on** runs as
`wsl.exe -d <distribution> --cd <folder> --exec <program> <arguments>`. Project paths become their `/mnt/<drive>`
paths (`C:\work\app` is `/mnt/c/work/app`); set **Project folder in WSL** when the distribution mounts drives
elsewhere. Interpreters left empty are looked up on the distribution's `PATH` (`python3`, `node`, `java`). Environment
variables reach the distribution through `WSLENV`. Debugging, coverage and profiling are not available on a WSL
target.
## Other uses of SSH configurations
- **Run targets** (**Settings › Build, Execution, Deployment › Run Targets**) run a configuration on an SSH host. See
+8
Переглянути файл
@@ -68,6 +68,14 @@ When the project's dependencies are installed only in an image, choose a Docker
A `pyrightconfig.json` or a `[tool.basedpyright]` / `[tool.pyright]` section with its own `extraPaths` replaces the copied paths. The interpreter's Python version is the empty virtualenv's, from a local Python of the same version when there is one.
### A Python in WSL as the interpreter
On Windows with WSL, **Add Python Interpreter** has a **WSL** entry: pick the **Distribution** and the **Python interpreter** (the ones found on its `PATH`, in `/usr/bin` and `/usr/local/bin`, pyenv's, and the project's `.venv` / `venv`; another path can be typed). **OK** adds a WSL [run target](/en/guide/remote/ssh#run-a-windows-project-in-wsl) with that Python and makes it the project interpreter.
- **Editor.** The IDE runs that Python once in the distribution to read its `sys.path`. basedpyright and Pyright read those folders in place through `\\wsl.localhost\<distribution>` (nothing is copied), with an empty local virtualenv as their interpreter, as for a Docker target. They are shown under **External Libraries**.
- **Run.** Python run configurations without a run target of their own run in the distribution.
- **Packages.** The list is read-only: install packages in WSL, then reload it.
### Creating an environment
On **Settings › Languages & Frameworks › Python Interpreter**, choose **Add Python Interpreter** and pick the **Interpreter type**:
+1 -1
Переглянути файл
@@ -35,7 +35,7 @@ optional = ["net:127.0.0.1", "clipboard.read"]
"clipboard.read" = "Imports a log you copied, on the Log to SQL tab only."
```
The dialog and the plugin's details in **Settings › Plugins** show it below the IDE's description, marked as the plugin's own words; it never replaces that description. Keys must be capabilities listed under `required` or `optional`, and each reason is 1 to 500 characters. Translate it like the plugin's other strings, with the English text as the key in `locales/<tag>.json`.
The dialog and the plugin's details in **Settings › Plugins** show it below the IDE's description, marked as the plugin's own words; it never replaces that description. Keys must be capabilities listed under `required` or `optional`, or ones a contribution brings (`java.agent` from `[[contributes.javaAgents]]`, `project.read` from `[[contributes.documentIndexers]]`), and each reason is 1 to 500 characters. Translate it like the plugin's other strings, with the English text as the key in `locales/<tag>.json`.
When code finds an optional capability refused, `host::open_permissions()` opens **Settings › Plugins** at the plugin's permissions, so a notice can offer a button that goes straight there (from a command or event only).
+8
Переглянути файл
@@ -114,6 +114,14 @@ Shell。IDE 内置的 SSH 客户端会使用配置里保存的密码、密钥或
WSL 窗口中也可以使用**端口**工具窗口。由于发行版与本机的 `localhost` 相通,转发的端口在本机可用同一端口访问;端口的列表、在浏览器中打开和记忆方式与 SSH 相同。
### 在 WSL 中运行 Windows 项目
位于 Windows 文件系统上的项目可以保留本地窗口,把运行配置放到发行版中运行:在**设置 › 构建、执行、部署 › 运行目标**中添加
**类型**为 **WSL** 的目标(装有发行版时才会出现),并选择 **WSL 发行版**。在**运行于**中选了该目标的配置,会以
`wsl.exe -d <distribution> --cd <folder> --exec <program> <arguments>` 运行。项目路径换成对应的 `/mnt/<盘符>` 路径
(`C:\work\app` 对应 `/mnt/c/work/app`);发行版把磁盘挂载在别处时,请填写 **WSL 中的项目文件夹**。留空的解释器从发行版的
`PATH` 查找(`python3`、`node`、`java`)。环境变量通过 `WSLENV` 传入发行版。WSL 目标不支持调试、覆盖率和性能分析。
## SSH 配置的其他用途
- **运行目标**(**设置 › 构建、执行、部署 › 运行目标**)可以在 SSH 主机上执行运行配置,见[运行配置](/zh/guide/run)。
+8
Переглянути файл
@@ -68,6 +68,14 @@ Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml`
如果 `pyrightconfig.json` 或 `[tool.basedpyright]` / `[tool.pyright]` 设置了自己的 `extraPaths`,它们会取代复制的路径。解释器的 Python 版本取自空虚拟环境;本机有相同版本的 Python 时会用它来创建。
### 以 WSL 中的 Python 作为解释器
在装有 WSL 的 Windows 上,**添加 Python 解释器**中有 **WSL** 一项:选择**发行版**和 **Python 解释器**(列出其 `PATH` 上、`/usr/bin` 和 `/usr/local/bin` 中、pyenv 的,以及项目 `.venv` / `venv` 中的 Python;也可以输入其他路径)。点击**确定**后会添加一个使用该 Python 的 WSL [运行目标](/zh/guide/remote/ssh#在-wsl-中运行-windows-项目),并将其设为项目解释器。
- **编辑器。** IDE 在发行版中运行一次该 Python 来读取其 `sys.path`。basedpyright 和 Pyright 通过 `\\wsl.localhost\<发行版>` 直接读取这些文件夹(不复制),解释器与 Docker 目标一样是一个本地的空虚拟环境。这些文件夹显示在**外部库**下。
- **运行。** 没有设置自己运行目标的 Python 运行配置会在该发行版中运行。
- **软件包。** 列表只读:请在 WSL 中安装软件包,然后重新加载列表。
### 创建环境
在 **设置 › 语言和框架 › Python 解释器** 中选择 **添加 Python 解释器**,再选 **解释器类型**:
+1 -1
Переглянути файл
@@ -35,7 +35,7 @@ optional = ["net:127.0.0.1", "clipboard.read"]
"clipboard.read" = "Imports a log you copied, on the Log to SQL tab only."
```
授权对话框和 **设置 › 插件** 的插件详情会把这句话显示在 IDE 说明的下方,并标明是插件自己的说法;它不会替换 IDE 的说明。键必须是 `required` 或 `optional` 里列出的能力,每条 1 到 500 个字符。翻译方式与插件的其他字符串相同:在 `locales/<tag>.json` 里以英文原文为键。
授权对话框和 **设置 › 插件** 的插件详情会把这句话显示在 IDE 说明的下方,并标明是插件自己的说法;它不会替换 IDE 的说明。键必须是 `required` 或 `optional` 里列出的能力,或者由贡献点带来的能力(`[[contributes.javaAgents]]` 带来的 `java.agent`、`[[contributes.documentIndexers]]` 带来的 `project.read`),每条 1 到 500 个字符。翻译方式与插件的其他字符串相同:在 `locales/<tag>.json` 里以英文原文为键。
代码发现某个 optional 能力被拒绝时,可以调用 `host::open_permissions()` 打开 **设置 › 插件** 并定位到本插件的权限,这样通知里可以放一个直接跳过去的按钮(仅限命令或事件中调用)。
+2 -1
Переглянути файл
@@ -51,7 +51,8 @@ with tempfile.TemporaryDirectory() as scratch:
"##teamcity[testFailed name='fails' className='sample.SampleTest' message='org.opentest4j.AssertionFailedError: it|'s wrong ==> expected: <1> but was: <2>'",
"##teamcity[testIgnored name='disabled' className='sample.SampleTest'",
"##teamcity[testIgnored name='aborted' className='sample.SampleTest']",
"##teamcity[testFailed name='parameterized' className='sample.SampleTest'",
"##teamcity[testStarted name='parameterized' className='sample.SampleTest' invocation='|[1|] 1']",
"##teamcity[testFailed name='parameterized' className='sample.SampleTest' invocation='|[2|] 2'",
"##teamcity[testFinished name='nested' className='sample.SampleTest$Inner' duration=",
"7 tests completed, 2 failed, 2 skipped",
]
Бінарний файл не відображається.
+14 -7
Переглянути файл
@@ -153,18 +153,25 @@ final class PlatformRunner implements TestExecutionListener {
for (Output o : outputs) o.flushLines(true);
}
/** `name='method' className='a.B$Nested'`, the method and class of the test or its closest source. */
/**
* `name='method' className='a.B$Nested'`, the method and class of the test or its closest source;
* an invocation of a parameterized, repeated or dynamic test adds `invocation='[1] a'`, its display name.
*/
private String id(TestIdentifier id) {
// The outermost method of the chain: the test itself, or the method container of its invocations.
TestIdentifier method = null;
for (TestIdentifier at = id; at != null; at = plan.getParent(at).orElse(null)) {
TestSource source = at.getSource().orElse(null);
if (source instanceof MethodSource) {
MethodSource m = (MethodSource) source;
return Reporter.attr("name", m.getMethodName()) + Reporter.attr("className", m.getClassName());
}
if (source instanceof ClassSource)
if (source instanceof MethodSource) method = at;
else if (method != null) break;
else if (source instanceof ClassSource)
return Reporter.attr("name", id.getLegacyReportingName()) + Reporter.attr("className", ((ClassSource) source).getClassName());
}
return Reporter.attr("name", id.getLegacyReportingName()) + Reporter.attr("className", id.getDisplayName());
if (method == null)
return Reporter.attr("name", id.getLegacyReportingName()) + Reporter.attr("className", id.getDisplayName());
MethodSource m = (MethodSource) method.getSource().get();
String own = Reporter.attr("name", m.getMethodName()) + Reporter.attr("className", m.getClassName());
return method == id ? own : own + Reporter.attr("invocation", id.getDisplayName());
}
private Optional<String> className(TestIdentifier id) {
+4
Переглянути файл
@@ -72,6 +72,10 @@ ide-android = { path = "../crates/ide-android" }
[dev-dependencies]
tempfile.workspace = true
[[test]]
name = "background_tab_appkit"
harness = false
[target.'cfg(target_os = "macos")'.dependencies]
block2 = "0.6"
# Plugin secrets in the login keychain.
+4
Переглянути файл
@@ -0,0 +1,4 @@
disallowed-methods = [
{ path = "tauri::webview::WebviewWindow::with_webview", reason = "panics on a detached background tab on macOS; use macos::with_web_view" },
{ path = "tauri::webview::Webview::with_webview", reason = "panics on a detached background tab on macOS; use macos::with_web_view" },
]
+71
Переглянути файл
@@ -0,0 +1,71 @@
//! AppKit side of a background tab's detached web view; no tauri types, so a test can include it.
use objc2::{
Message,
rc::Retained,
runtime::{AnyClass, ProtocolObject},
};
use objc2_app_kit::{
NSView, NSWindow, NSWindowDidBecomeKeyNotification, NSWindowDidChangeOcclusionStateNotification,
NSWindowOcclusionState, NSWindowOrderingMode,
};
use objc2_foundation::{NSNotificationCenter, NSObjectProtocol};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Return {
Key,
Visible,
}
pub fn web_view(native: &NSWindow) -> Option<Retained<NSView>> {
let class = AnyClass::get(c"WKWebView")?;
native.contentView()?.subviews().iter().find(|v| v.isKindOfClass(class))
}
/// At the bottom so the title bar views stay above it.
pub fn put_back(native: &NSWindow, view: &NSView) {
let Some(content) = native.contentView() else { return };
view.setFrame(content.bounds());
content.addSubview_positioned_relativeTo(view, NSWindowOrderingMode::Below, None);
native.makeFirstResponder(Some(view));
}
/// Calls `f` when the window becomes key, or visible (AppKit can bring a window back by itself,
/// e.g. when a tab it closes next to leaves the group). The observers have no queue, so `f` runs
/// synchronously inside the post. For the key notification that is inside `makeKeyWindow`, before the
/// window's first display; occlusion arrives when the window is already on screen.
pub fn on_return(
native: &NSWindow,
f: impl Fn(Return) + 'static,
) -> Vec<Retained<ProtocolObject<dyn NSObjectProtocol>>> {
let f = std::rc::Rc::new(f);
let center = NSNotificationCenter::defaultCenter();
let key = {
let f = f.clone();
let block = block2::RcBlock::new(move |_| f(Return::Key));
unsafe {
center.addObserverForName_object_queue_usingBlock(
Some(NSWindowDidBecomeKeyNotification),
Some(native),
None,
&block,
)
}
};
let visible = {
let window: Retained<NSWindow> = native.retain();
let block = block2::RcBlock::new(move |_| {
if window.occlusionState().contains(NSWindowOcclusionState::Visible) {
f(Return::Visible);
}
});
unsafe {
center.addObserverForName_object_queue_usingBlock(
Some(NSWindowDidChangeOcclusionStateNotification),
Some(native),
None,
&block,
)
}
};
vec![key, visible]
}
+3 -3
Переглянути файл
@@ -170,9 +170,9 @@ async fn webview_processes(app: &AppHandle, state: &AppState) -> Vec<MemoryRoot>
let mut pending = Vec::new();
for (label, w) in app.webview_windows() {
let (tx, rx) = tokio::sync::oneshot::channel();
let sent = w.with_webview(move |pv| {
// SAFETY: `with_webview` runs on the main thread with the live WKWebView.
let _ = tx.send(unsafe { memory::webkit_process_ids(pv.inner()) });
let sent = crate::macos::with_web_view(&w, move |view| {
// SAFETY: runs on the main thread with the live WKWebView, detached or not.
let _ = tx.send(unsafe { memory::webkit_process_ids(view) });
});
if sent.is_ok() {
pending.push((label, rx));
+1
Переглянути файл
@@ -233,6 +233,7 @@ pub fn window_flash_taskbar(window: WebviewWindow, flash: bool) -> IdeResult<()>
#[specta::specta]
pub fn window_set_smooth_scrolling(window: WebviewWindow, enabled: bool) -> IdeResult<()> {
#[cfg(target_os = "linux")]
#[allow(clippy::disallowed_methods)]
window
.with_webview(move |platform| crate::linux_webkit::set_smooth_scrolling(&platform, enabled))
.map_err(|e| IdeError::internal(e.to_string()))?;
+3
Переглянути файл
@@ -7,6 +7,8 @@
#![recursion_limit = "512"]
mod application_focus;
#[cfg(target_os = "macos")]
mod background_tab;
mod cli;
mod commands;
#[cfg(debug_assertions)]
@@ -308,6 +310,7 @@ pub fn run() {
#[cfg(target_os = "macos")]
{
page_swipe::forget(window.label());
macos::forget_background(window.label());
titlebar::forget(window);
}
if windows::auxiliary_parent(window.label()).is_none() {
+1
Переглянути файл
@@ -91,6 +91,7 @@ pub fn smooth_scrolling_plugin() -> tauri::plugin::TauriPlugin<tauri::Wry> {
let enabled = webview
.try_state::<crate::state::AppState>()
.is_some_and(|s| s.global_settings.effective().appearance.smooth_scrolling);
#[allow(clippy::disallowed_methods)]
let _ = webview.with_webview(move |platform| set_smooth_scrolling(&platform, enabled));
})
.build()
+242 -3
Переглянути файл
@@ -1,15 +1,101 @@
//! macOS project tabs: native window tab groups behind the page's own tab bar.
use crate::background_tab::{self, Return};
use crate::windows::{Launch, WindowsState};
use ide_core::{IdeError, IdeResult};
use ide_workspace::window_groups::{TabbingPreference, should_group_new_project};
use objc2::{
MainThreadMarker,
rc::Retained,
runtime::{AnyClass, AnyObject, Imp, Sel},
runtime::{AnyClass, AnyObject, Imp, ProtocolObject, Sel},
};
use objc2_app_kit::{
NSApplication, NSView, NSWindow, NSWindowOcclusionState, NSWindowOrderingMode, NSWindowStyleMask,
NSWindowUserTabbingPreference,
};
use objc2_foundation::{NSNotificationCenter, NSObjectProtocol, NSOperationQueue};
use std::{
cell::{Cell, RefCell},
collections::HashMap,
ffi::c_void,
time::Duration,
};
use objc2_app_kit::{NSWindow, NSWindowUserTabbingPreference};
use tauri::{AppHandle, Manager, WebviewWindow};
/// WebKit frees a page's graphics 10 s and its caches 2 min after the page leaves its window.
const DETACH_BACKGROUND_TAB_AFTER: Duration = Duration::from_secs(30);
enum Background<V> {
Pending(u64),
Detached(V),
}
struct BackgroundTabs<V> {
next: u64,
tabs: HashMap<String, Background<V>>,
}
impl<V> Default for BackgroundTabs<V> {
fn default() -> Self {
Self { next: 0, tabs: HashMap::new() }
}
}
impl<V> BackgroundTabs<V> {
/// None when the label already has an entry: a repeated select must not restart the clock.
fn schedule(&mut self, label: &str) -> Option<u64> {
if self.tabs.contains_key(label) {
return None;
}
self.next += 1;
self.tabs.insert(label.to_string(), Background::Pending(self.next));
Some(self.next)
}
fn due(&self, label: &str, generation: u64) -> bool {
matches!(self.tabs.get(label), Some(Background::Pending(g)) if *g == generation)
}
fn detached(&mut self, label: &str, view: V) {
self.tabs.insert(label.to_string(), Background::Detached(view));
}
fn cancel(&mut self, label: &str) {
self.tabs.remove(label);
}
fn view(&self, label: &str) -> Option<&V> {
match self.tabs.get(label) {
Some(Background::Detached(view)) => Some(view),
_ => None,
}
}
/// Also cancels a pending detach.
fn attach(&mut self, label: &str) -> Option<V> {
match self.tabs.remove(label) {
Some(Background::Detached(view)) => Some(view),
_ => None,
}
}
}
struct DetachedView {
view: Retained<NSView>,
observers: Vec<Retained<ProtocolObject<dyn NSObjectProtocol>>>,
}
impl Drop for DetachedView {
fn drop(&mut self) {
for observer in &self.observers {
unsafe { NSNotificationCenter::defaultCenter().removeObserver(observer.as_ref()) };
}
}
}
thread_local! {
static BACKGROUND: RefCell<BackgroundTabs<DetachedView>> = RefCell::new(BackgroundTabs::default());
}
fn tabbing_preference(app: &AppHandle) -> IdeResult<TabbingPreference> {
fn read(mtm: MainThreadMarker) -> TabbingPreference {
match NSWindow::userTabbingPreference(mtm) {
@@ -83,6 +169,101 @@ fn same_group(a: &NSWindow, b: &NSWindow) -> bool {
}
}
fn schedule_detach(window: &WebviewWindow) {
// The debug-only MCP bridge calls `with_webview` directly, which panics on a detached view.
if cfg!(debug_assertions) {
return;
}
let Some(generation) = BACKGROUND.with_borrow_mut(|tabs| tabs.schedule(window.label())) else { return };
let target = window.clone();
tauri::async_runtime::spawn(async move {
tokio::time::sleep(DETACH_BACKGROUND_TAB_AFTER).await;
let window = target.clone();
let _ = window.run_on_main_thread(move || detach_if_background(&target, generation));
});
}
fn detach_if_background(window: &WebviewWindow, generation: u64) {
if !BACKGROUND.with_borrow(|tabs| tabs.due(window.label(), generation)) {
return;
}
let Some(native) = native(window) else { return };
// A visible window is never a background tab.
if native.occlusionState().contains(NSWindowOcclusionState::Visible) {
BACKGROUND.with_borrow_mut(|tabs| tabs.cancel(window.label()));
return;
}
// An inactive app's full-screen group can be mid-transition, where AppKit has crashed (#6937): wait for activation.
let inactive = MainThreadMarker::new().is_some_and(|mtm| !NSApplication::sharedApplication(mtm).isActive());
if inactive && native.styleMask().contains(NSWindowStyleMask::FullScreen) {
BACKGROUND.with_borrow_mut(|tabs| tabs.cancel(window.label()));
schedule_detach(window);
return;
}
let view = (|| {
let group = native.tabGroup()?;
let selected = group.selectedWindow()?;
let background = group.windows().count() > 1
&& !std::ptr::eq(Retained::as_ptr(&selected), native)
&& native.attachedSheet().is_none();
background.then(|| background_tab::web_view(native)).flatten()
})();
let Some(view) = view else {
BACKGROUND.with_borrow_mut(|tabs| tabs.cancel(window.label()));
return;
};
view.removeFromSuperview();
let target = window.clone();
let observers = background_tab::on_return(native, move |why| {
attach_for(&target, if why == Return::Key { "key" } else { "visible" }, true)
});
BACKGROUND.with_borrow_mut(|tabs| tabs.detached(window.label(), DetachedView { view, observers }));
}
/// Puts a detached web view back and cancels a pending detach.
pub fn attach(window: &WebviewWindow) {
attach_for(window, "select", false);
}
fn attach_for(window: &WebviewWindow, reason: &str, from_observer: bool) {
let Some(detached) = BACKGROUND.with_borrow_mut(|tabs| tabs.attach(window.label())) else {
return;
};
if let Some(native) = native(window) {
background_tab::put_back(native, &detached.view);
tracing::debug!(label = window.label(), reason, "re-attached background tab web view");
}
if from_observer {
// Dropping removes the observer whose block is running; wait until the post returns.
let detached = Cell::new(Some(detached));
let block = block2::RcBlock::new(move || drop(detached.take()));
unsafe { NSOperationQueue::mainQueue().addOperationWithBlock(&block) };
}
}
/// Calls `f` on the main thread with the window's `WKWebView`, attached or not.
/// tauri's webview size/position APIs (`core:webview:default` grants `webview_size`/`webview_position`) unwrap
/// `superview()` in wry and are not safe while a tab is detached.
pub fn with_web_view(window: &WebviewWindow, f: impl FnOnce(*mut c_void) + Send + 'static) -> tauri::Result<()> {
let target = window.clone();
window.run_on_main_thread(move || {
// On the main thread tauri handles with_webview synchronously, so the tab cannot be detached between
// the check and the call; wry's with_webview panics on a windowless view.
let detached = BACKGROUND.with_borrow(|tabs| tabs.view(target.label()).map(|d| Retained::as_ptr(&d.view)));
match detached {
Some(view) => f(view as *mut c_void),
None => {
#[allow(clippy::disallowed_methods)]
let _ = target.with_webview(move |w| f(w.inner()));
}
}
})
}
pub fn forget_background(label: &str) {
BACKGROUND.with_borrow_mut(|tabs| tabs.cancel(label));
}
/// Adds `members` to the existing anchor's native tab group and shows `selected`.
pub fn sync_tab_group(
members: Vec<WebviewWindow>,
@@ -99,14 +280,18 @@ pub fn sync_tab_group(
if let Some(window) = native(member)
&& !same_group(anchor_window, window)
{
anchor_window.addTabbedWindow_ordered(window, objc2_app_kit::NSWindowOrderingMode::Above);
anchor_window.addTabbedWindow_ordered(window, NSWindowOrderingMode::Above);
}
}
attach(&target);
if let Some(group) = shown.tabGroup() {
group.setSelectedWindow(Some(shown));
}
shown.makeKeyAndOrderFront(None);
for member in &members {
if member.label() != target.label() {
schedule_detach(member);
}
if let Some(window) = native(member) {
hide_tab_bar(window);
}
@@ -129,6 +314,7 @@ pub fn move_tab_to_new_window(window: &WebviewWindow) -> tauri::Result<()> {
let target = window.clone();
on_main(window, move || {
let Some(native) = native(&target) else { return };
attach(&target);
if native.tabbedWindows().is_some_and(|tabs| tabs.count() > 1) {
native.moveTabToNewWindow(None);
}
@@ -226,3 +412,56 @@ pub fn native_modal_open() -> bool {
let application = objc2_app_kit::NSApplication::sharedApplication(mtm);
application.modalWindow().is_some() || application.windows().iter().any(|window| window.attachedSheet().is_some())
}
#[cfg(test)]
mod tests {
use super::BackgroundTabs;
#[test]
fn repeated_schedule_keeps_the_first_generation() {
let mut tabs = BackgroundTabs::<u32>::default();
let first = tabs.schedule("a").unwrap();
assert_eq!(tabs.schedule("a"), None);
assert!(tabs.due("a", first));
}
#[test]
fn attach_cancels_a_pending_detach() {
let mut tabs = BackgroundTabs::<u32>::default();
let generation = tabs.schedule("a").unwrap();
assert_eq!(tabs.attach("a"), None);
assert!(!tabs.due("a", generation));
}
#[test]
fn stale_generation_is_not_due_after_reschedule() {
let mut tabs = BackgroundTabs::<u32>::default();
let stale = tabs.schedule("a").unwrap();
tabs.attach("a");
let fresh = tabs.schedule("a").unwrap();
assert_ne!(stale, fresh);
assert!(!tabs.due("a", stale));
assert!(tabs.due("a", fresh));
}
#[test]
fn view_is_only_there_while_detached() {
let mut tabs = BackgroundTabs::<&'static str>::default();
tabs.schedule("a").unwrap();
assert_eq!(tabs.view("a"), None);
tabs.detached("a", "view");
assert_eq!(tabs.view("a"), Some(&"view"));
tabs.attach("a");
assert_eq!(tabs.view("a"), None);
}
#[test]
fn attach_returns_the_detached_view_once() {
let mut tabs = BackgroundTabs::<&'static str>::default();
let generation = tabs.schedule("a").unwrap();
tabs.detached("a", "view");
assert!(!tabs.due("a", generation));
assert_eq!(tabs.attach("a"), Some("view"));
assert_eq!(tabs.attach("a"), None);
}
}
+4 -3
Переглянути файл
@@ -33,9 +33,10 @@ fn stroke(window: &WebviewWindow, right: bool) {
pub fn install(window: &WebviewWindow) {
let target = window.clone();
let _ = window.with_webview(move |webview| {
let view = unsafe { Retained::retain(webview.inner().cast::<NSView>()).unwrap() };
let native = webview.ns_window() as usize;
let _ = crate::macos::with_web_view(window, move |webview| {
let view = unsafe { Retained::retain(webview.cast::<NSView>()).unwrap() };
let Ok(native) = target.ns_window() else { return };
let native = native as usize;
let window = target.clone();
let block = block2::RcBlock::new(move |event: NonNull<NSEvent>| {
let event = unsafe { event.as_ref() };
+5 -3
Переглянути файл
@@ -458,10 +458,12 @@ fn track(window: &NSWindow, app: &tauri::AppHandle) -> Tracked {
pub fn set_height(window: &tauri::WebviewWindow, height: f64) -> tauri::Result<()> {
let label = window.label().to_owned();
let app = window.app_handle().clone();
// with_webview runs on the AppKit thread.
window.with_webview(move |webview| unsafe {
let target = window.clone();
// The window's own handle works while a background tab's web view is detached.
window.run_on_main_thread(move || unsafe {
let Some(mtm) = MainThreadMarker::new() else { return };
let native = &*webview.ns_window().cast::<NSWindow>();
let Ok(native) = target.ns_window() else { return };
let native = &*native.cast::<NSWindow>();
let (state, buttons, strip) = WINDOWS.with_borrow_mut(|windows| {
let tracked = windows.entry(label).or_insert_with(|| track(native, &app));
tracked.height.set(height);
+2 -2
Переглянути файл
@@ -2764,8 +2764,8 @@ fn disable_macos_text_input_selection_updates(preferences: &objc2_web_kit::WKPre
/// suppresses the affordance even if `NSTextInputContext` queries the view directly.
#[cfg(target_os = "macos")]
fn suppress_window_writing_tools_affordance(window: &WebviewWindow) {
let _ = window.with_webview(|webview| unsafe {
let ptr = webview.inner().cast::<objc2::runtime::AnyObject>();
let _ = crate::macos::with_web_view(window, |webview| unsafe {
let ptr = webview.cast::<objc2::runtime::AnyObject>();
if !ptr.is_null() {
let cls = (*ptr).class();
suppress_webview_class_writing_tools_affordance(cls);
+1
Переглянути файл
@@ -11,6 +11,7 @@ pub fn init() -> plugin::TauriPlugin<Wry> {
plugin::Builder::new("webview-keys").on_webview_ready(disable_browser_keys).build()
}
#[allow(clippy::disallowed_methods)]
fn disable_browser_keys(webview: Webview) {
let label = webview.label().to_owned();
if let Err(error) = webview.with_webview(move |platform| {
+1
Переглянути файл
@@ -50,6 +50,7 @@ pub fn init() -> plugin::TauriPlugin<Wry> {
.build()
}
#[allow(clippy::disallowed_methods)]
fn install(webview: Webview) {
let app = webview.app_handle().clone();
let label = webview.label().to_owned();
+70
Переглянути файл
@@ -0,0 +1,70 @@
#[cfg(not(target_os = "macos"))]
fn main() {}
#[cfg(target_os = "macos")]
#[path = "../src/background_tab.rs"]
mod background_tab;
#[cfg(target_os = "macos")]
#[link(name = "WebKit", kind = "framework")]
unsafe extern "C" {}
#[cfg(target_os = "macos")]
fn main() {
// nextest runs a harness-less binary as `--list --format terse [--ignored]`, then `<name> --exact --nocapture`.
let args: Vec<String> = std::env::args().collect();
if args.iter().any(|a| a == "--list") {
if !args.iter().any(|a| a == "--ignored") {
println!("background_tab_appkit: test");
}
return;
}
use background_tab::Return;
use objc2::{MainThreadMarker, msg_send, rc::Retained, runtime::AnyClass};
use objc2_app_kit::{
NSApplication, NSBackingStoreType, NSView, NSWindow, NSWindowDidBecomeKeyNotification, NSWindowStyleMask,
};
use objc2_foundation::{NSNotificationCenter, NSPoint, NSRect, NSSize};
use std::{cell::Cell, rc::Rc};
let mtm = MainThreadMarker::new().expect("main thread");
let _app = NSApplication::sharedApplication(mtm);
let rect = NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(400.0, 300.0));
let window = unsafe {
NSWindow::initWithContentRect_styleMask_backing_defer(
mtm.alloc(),
rect,
NSWindowStyleMask::Titled,
NSBackingStoreType::Buffered,
false,
)
};
let class = AnyClass::get(c"WKWebView").expect("WebKit is linked");
let web: Retained<NSView> = unsafe { msg_send![msg_send![class, alloc], initWithFrame: rect] };
window.contentView().unwrap().addSubview(&web);
let view = background_tab::web_view(&window).expect("web view in content view");
view.removeFromSuperview();
assert!(view.window().is_none());
// Not asked for its process ids: on a web view that never loaded a page, WebKit asserts in
// `_networkProcessIdentifier` (macOS 15), which a real tab never is.
let reason = Rc::new(Cell::new(None));
let observers = {
let (reason, window, view) = (reason.clone(), window.clone(), view.clone());
background_tab::on_return(&window.clone(), move |why| {
background_tab::put_back(&window, &view);
reason.set(Some(why));
})
};
unsafe {
NSNotificationCenter::defaultCenter()
.postNotificationName_object(NSWindowDidBecomeKeyNotification, Some(&window));
}
assert_eq!(reason.get(), Some(Return::Key));
assert!(view.window().is_some_and(|w| Retained::as_ptr(&w) == Retained::as_ptr(&window)));
for observer in &observers {
unsafe { NSNotificationCenter::defaultCenter().removeObserver(observer.as_ref()) };
}
println!("ok: re-attached synchronously inside the key notification");
}
+2 -1
Переглянути файл
@@ -693,7 +693,7 @@ scaffold_options always project_host bin
scaffold_requirements always project_host bindings async
scaffold_target_taken always project_host bindings async
scope_files always project_host bindings async
sdk_container_python trusted project_host bindings sync
sdk_container_python trusted project_host bindings async
sdk_container_python_refresh trusted project_host bindings async
sdk_detect outside_restricted project_host bindings async
sdk_flutter_at trusted project_host bindings async
@@ -714,6 +714,7 @@ sdk_python_pip outside_restricted project_host bin
sdk_python_project_interpreters outside_restricted project_host bindings async
sdk_python_sys_path outside_restricted project_host bindings async
sdk_python_user_path_problems outside_restricted project_host bindings async
sdk_wsl_pythons trusted project_host bindings async
search_start always project_host bindings async
search_validate always project_host bindings sync
set_recent_project_groups always desktop bindings sync
+30 -6
Переглянути файл
@@ -1981,7 +1981,10 @@ export const commands = {
*/
scaffoldTargetTaken: (location: string, name: string) => typedError<boolean, IdeError>(__TAURI_INVOKE("scaffold_target_taken", { location, name })),
scopeFiles: (pattern: string, limit: number) => typedError<ScopeFiles, IdeError>(__TAURI_INVOKE("scope_files", { pattern, limit })),
/** The project interpreter when it is a Docker or Compose run target's, with its snapshot. */
/**
* The project interpreter when it is a Docker or Compose run target's, with its snapshot.
* Off the calling thread: a WSL interpreter's packages are read over `\\wsl.localhost`.
*/
sdkContainerPython: () => typedError<{
/** The run target's id. */
target: string,
@@ -1989,8 +1992,10 @@ export const commands = {
name: string,
/** The Python version of the snapshot in use; `None`: no snapshot yet. */
version: string | null,
/** The image the snapshot was copied from. */
/** The image the snapshot was copied from; `None` for WSL. */
image: string | null,
/** The interpreter's path in the container or distribution. */
executable: string | null,
/** The copied library folders on this machine. */
folders: IpcPath[],
/** Packages of the snapshot (read-only). */
@@ -2006,8 +2011,10 @@ export const commands = {
name: string,
/** The Python version of the snapshot in use; `None`: no snapshot yet. */
version: string | null,
/** The image the snapshot was copied from. */
/** The image the snapshot was copied from; `None` for WSL. */
image: string | null,
/** The interpreter's path in the container or distribution. */
executable: string | null,
/** The copied library folders on this machine. */
folders: IpcPath[],
/** Packages of the snapshot (read-only). */
@@ -2116,6 +2123,11 @@ export const commands = {
* (`None`: it is used). The folders may not be saved yet.
*/
sdkPythonUserPathProblems: (paths: string[]) => typedError<(UserPathProblem | null)[], IdeError>(__TAURI_INVOKE("sdk_python_user_path_problems", { paths })),
/**
* The Pythons found in a WSL distribution, for Add Python Interpreter: the ones on its
* `PATH`, in `/usr/bin` and `/usr/local/bin`, pyenv's, and the project's virtualenv. Empty off Windows.
*/
sdkWslPythons: (distro: string) => typedError<string[], IdeError>(__TAURI_INVOKE("sdk_wsl_pythons", { distro })),
/**
* Find in Files. Results stream through `on_event`; ends with `Done`.
* Cancel with `cancel_request(request)`.
@@ -5782,8 +5794,10 @@ export type ContainerPython = {
name: string,
/** The Python version of the snapshot in use; `None`: no snapshot yet. */
version: string | null,
/** The image the snapshot was copied from. */
/** The image the snapshot was copied from; `None` for WSL. */
image: string | null,
/** The interpreter's path in the container or distribution. */
executable: string | null,
/** The copied library folders on this machine. */
folders: IpcPath[],
/** Packages of the snapshot (read-only). */
@@ -14406,7 +14420,10 @@ export type RunTarget = {
name?: string,
/** [`SshConfiguration::id`] (SSH). */
sshConfig?: string,
/** Remote folder the project is synchronised to and run from (SSH). */
/**
* Remote folder the project is synchronised to and run from (SSH); the project's Linux
* path, empty = its `/mnt/<drive>` path (WSL).
*/
projectRoot?: string,
/** Upload changed project files before each run (SSH). */
syncBeforeRun?: boolean,
@@ -14436,6 +14453,8 @@ export type RunTarget = {
runOptions?: string,
/** Run as the image's user instead of the project folder's owner (Linux). */
imageUser?: boolean,
/** Distribution name, as `wsl.exe -l -q` lists it (WSL). */
distro?: string,
};
/** Where a run target runs configurations. */
@@ -14445,7 +14464,12 @@ export type RunTargetKind =
/** A new container of an image (`docker run --rm`), the project bind-mounted. */
"docker" |
/** A new container of a Compose service (`docker compose run --rm`). */
"compose";
"compose" |
/**
* A WSL distribution on this Windows machine (`wsl.exe -d <distro>`), the project read
* through `/mnt/<drive>`.
*/
"wsl";
export type RustSettings = {
/** Directory holding `cargo` / `rustc`; empty = `PATH` / rustup default. */
+9 -2
Переглянути файл
@@ -43,6 +43,7 @@ import {
useTextEditorWrappers,
type EditorCloseSession,
type EditorInput,
type EditorKindContribution,
type OpenOptions,
type FileEditorResolution,
type OpenEditorTab,
@@ -310,6 +311,11 @@ function tabModified(tab: Tab): boolean {
);
}
/** Whether `input` opens in the preview tab when asked: always for kinds that reuse one, else per the setting. */
function previewTabsFor(input: EditorInput, kinds: ReadonlyMap<string, EditorKindContribution>): boolean {
return editorPrefs().tabs.previewTab || !!kinds.get(input.kind)?.reusesPreviewTab;
}
export class EditorController implements SlotHost {
manager: DocumentManager;
readonly slots = new Map<string, EditorSlot>();
@@ -1529,7 +1535,7 @@ export class EditorController implements SlotHost {
const kinds = useContributions.getState().editorKinds;
const lifecycle = documentLifecycle(input, kinds);
const canPreview = !lifecycle || (lifecycle.allowPreview && !documentDirty({ input, lifecycle }));
const preview = !!o.preview && editorPrefs().tabs.previewTab && canPreview;
const preview = !!o.preview && previewTabsFor(input, kinds) && canPreview;
if (!activate && preview) return;
const kind = kinds.get(input.kind);
let paneId = s.panes[generation.pane] ? generation.pane : activate ? s.activePane : null;
@@ -2447,7 +2453,8 @@ export class EditorController implements SlotHost {
activeInput(options?: { previewOnly?: boolean }): EditorInput | null {
const tab = this.activeTabOf();
if (options?.previewOnly && (!tab?.preview || !editorPrefs().tabs.previewTab)) return null;
const kinds = useContributions.getState().editorKinds;
if (options?.previewOnly && (!tab?.preview || !previewTabsFor(tab.input, kinds))) return null;
return tab?.input ?? null;
}
+30
Переглянути файл
@@ -151,6 +151,36 @@ describe("file open order", () => {
expect(activePath()).toBe("/p/b.ts");
});
it("reuses one tab for kinds that ask for it while the preview tab is off", async () => {
useProject.setState({ settings: { editor: { tabs: { previewTab: false } } } });
dispose = registerEditorKind({
kind: "test-diff",
reusesPreviewTab: true,
component: () => null,
title: (input) => input.key,
});
const controller = setup();
const diff = (key: string) => ({ kind: "test-diff", key });
await controller.openInput(diff("one"), { preview: true, focus: false });
await controller.openInput(diff("two"), { preview: true, focus: false });
const tabs = () => Object.values(useTabs.getState().panes).flatMap((pane) => pane.tabs);
expect(tabs().map((t) => [t.input.key, t.preview])).toEqual([["two", true]]);
expect(controller.activeInput({ previewOnly: true })?.key).toBe("two");
// Files still don't preview.
await controller.openFile("/p/a.ts", { preview: true, focus: false });
await controller.openFile("/p/b.ts", { preview: true, focus: false });
expect(openFilePaths(useTabs.getState()).sort()).toEqual(["/p/a.ts", "/p/b.ts"]);
// A kept diff tab stays.
const pane = useTabs.getState().activePane;
controller.keepTab(pane, tabs().find((t) => t.input.key == "two")!.id);
await controller.openInput(diff("three"), { preview: true, focus: false });
expect(
tabs()
.filter((t) => t.input.kind == "test-diff")
.map((t) => t.input.key),
).toEqual(["two", "three"]);
});
it("keeps an earlier regular file without removing the newer preview", async () => {
const { started, response } = delayProvider();
const controller = setup();
+2 -2
Переглянути файл
@@ -439,7 +439,7 @@ export function DiagramView({ data, onJump }: { data: DiagramData; onJump?: () =
</marker>
</defs>
{arrangement &&
edges.map((e, i) => {
edges.map((e) => {
const [from, to] = [nodes[e.from]!, nodes[e.to]!];
const [a, b] = [boxOf(from.key), boxOf(to.key)];
if (!a || !b || arrangement.hidden.has(from.key) || arrangement.hidden.has(to.key)) return null;
@@ -447,7 +447,7 @@ export function DiagramView({ data, onJump }: { data: DiagramData; onJump?: () =
const toY = rowCenter(to, b, arrangement.collapsed.has(to.key), e.toColumns[0]);
return (
<path
key={i}
key={`${from.key}:${e.fromColumns.join(",")}→${to.key}:${e.toColumns.join(",")}`}
className={clsx(styles.link, e.optional && styles.optional)}
d={linkPath(a, fromY, b, toY)}
markerEnd={`url(#${markerId})`}
+9 -1
Переглянути файл
@@ -1495,7 +1495,15 @@ function QuickDoc({ node, anchor }: { node: DbNode; anchor: { x: number; y: numb
);
}
function SourceFolderDialog({ folder, sources = [] }: { folder: DbSourceFolder | null; sources?: string[] }) {
const NO_SOURCES: readonly string[] = [];
function SourceFolderDialog({
folder,
sources = NO_SOURCES,
}: {
folder: DbSourceFolder | null;
sources?: readonly string[];
}) {
const [name, setName] = useState(folder?.name ?? "");
const [busy, setBusy] = useState(false);
const submit = async () => {
+5 -1
Переглянути файл
@@ -742,7 +742,11 @@ export function WorkspaceEditor({ input }: { input: EditorInput }) {
) : (
<div role="log" tabIndex={0} className={dbStyles.output} aria-label={t("Feedback")}>
{results.map(({ data }, index) => (
<div key={index} className={dbStyles.outputLine}>
<div
// oxlint-disable-next-line react/no-array-index-key -- results are append-only; the result number is the identity
key={index}
className={dbStyles.outputLine}
>
{resultLabel(index + 1)} · {t`${data.rows.length} rows`}
{data.elapsedMs !== null && ` · ${formatElapsed(data.elapsedMs)}`}
</div>
+10 -2
Переглянути файл
@@ -31,7 +31,11 @@ function Row({ row, width, target }: { row: MemoryRow; width: number; target: bi
{COLUMN_OFFSETS.map((_, i) => {
const byte = row.bytes[i];
return (
<span key={i} className={clsx(styles.byte, i === at && styles.target, byte === null && styles.unreadable)}>
<span
// oxlint-disable-next-line react/no-array-index-key -- byte column position is the cell's identity
key={i}
className={clsx(styles.byte, i === at && styles.target, byte === null && styles.unreadable)}
>
{byte === undefined ? " " : hexByte(byte)}
</span>
);
@@ -39,7 +43,11 @@ function Row({ row, width, target }: { row: MemoryRow; width: number; target: bi
</span>
<span role="gridcell" className={styles.ascii}>
{row.bytes.map((byte, i) => (
<span key={i} className={clsx(i === at && styles.target, byte === null && styles.unreadable)}>
<span
// oxlint-disable-next-line react/no-array-index-key -- an unreadable byte has no value; position is the identity
key={i}
className={clsx(i === at && styles.target, byte === null && styles.unreadable)}
>
{asciiChar(byte)}
</span>
))}
+1
Переглянути файл
@@ -685,6 +685,7 @@ export function TomcatSettings({ config, onChange }: { config: RunConfig; onChan
<div className={styles.appServersList} role="listbox" aria-label={tx("Deploy at the server startup")}>
{deployments.map((d, i) => (
<div
// oxlint-disable-next-line react/no-array-index-key -- deployments are reordered and selected by position; position is the identity
key={i}
role="option"
aria-selected={i === selectedIdx}
+18 -7
Переглянути файл
@@ -12,6 +12,17 @@ def tc = { String s ->
.replace('[', '|[').replace(']', '|]')
}
// `name='method(Type)[1]' className='a.B'`; an invocation of a parameterized, repeated or dynamic
// test (its parent is the method, not the class) adds `invocation='[1] a'`, its display name.
def id = { TestDescriptor test ->
def own = "name='${tc(test.name)}' className='${tc(test.className)}'"
def parent = test.parent
if (parent == null || parent.className != test.className || parent.name == test.className) return own
// `getDisplayName` is Gradle 4.10+.
def shown = test.hasProperty('displayName') ? test.displayName : test.name
"${own} invocation='${tc(shown)}'"
}
allprojects {
each(tasks.withType(Test)) { Test task ->
task.outputs.upToDateWhen { false }
@@ -21,29 +32,29 @@ allprojects {
void afterSuite(TestDescriptor suite, TestResult result) {}
void beforeTest(TestDescriptor test) {
println "##teamcity[testStarted name='${tc(test.name)}' className='${tc(test.className)}']"
println "##teamcity[testStarted ${id(test)}]"
}
void afterTest(TestDescriptor test, TestResult result) {
def id = "name='${tc(test.name)}' className='${tc(test.className)}'"
def own = id(test)
def type = result.resultType.toString()
if (type == 'FAILURE') {
def error = result.exception
def trace = new StringWriter()
error?.printStackTrace(new PrintWriter(trace))
println "##teamcity[testFailed ${id} message='${tc(error?.toString())}' details='${tc(trace.toString())}']"
println "##teamcity[testFailed ${own} message='${tc(error?.toString())}' details='${tc(trace.toString())}']"
} else if (type == 'SKIPPED') {
println "##teamcity[testIgnored ${id}]"
println "##teamcity[testIgnored ${own}]"
}
println "##teamcity[testFinished ${id} duration='${result.endTime - result.startTime}']"
println "##teamcity[testFinished ${own} duration='${result.endTime - result.startTime}']"
}
})
task.addTestOutputListener(new TestOutputListener() {
void onOutput(TestDescriptor test, TestOutputEvent output) {
if (test.className == null) return
// A class's own output (`@BeforeAll`, `@AfterAll`) carries no test name.
def name = test.composite ? '' : " name='${tc(test.name)}'"
println "##teamcity[testStdOut${name} className='${tc(test.className)}' out='${tc(output.message)}']"
def own = test.composite ? "className='${tc(test.className)}'" : id(test)
println "##teamcity[testStdOut ${own} out='${tc(output.message)}']"
}
})
}
+14
Переглянути файл
@@ -574,6 +574,14 @@ describe("coverage and profiling", () => {
);
});
it("are refused on WSL, with a notification", () => {
const wsl: RunTargetValid = { ...DEFAULT_RUN_TARGET, kind: "wsl", id: "w", name: "Ubuntu", distro: "Ubuntu" };
expect(containerExecutorBlocked(cfg("app", { target: "w" }), [box, wsl])).toBe(true);
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({ title: "Coverage and profiling are not supported on WSL", level: "warning" }),
);
});
it("are left alone locally and over SSH", () => {
expect(containerExecutorBlocked(cfg("app"), [box, container])).toBe(false);
expect(containerExecutorBlocked(cfg("app", { target: "box" }), [box, container])).toBe(false);
@@ -598,6 +606,12 @@ describe("the container a run is in", () => {
expect(containerTarget(cfg("a", { kind: "python" }), targets)).toBeNull();
expect(containerTarget(cfg("a", { target: "web" }), targets)).toBe("web");
});
it("is a WSL target too: its printed paths are looked up there", () => {
const wsl: RunTargetValid = { ...DEFAULT_RUN_TARGET, kind: "wsl", id: "w", name: "w", distro: "Ubuntu" };
settings(".venv/bin/python");
expect(containerTarget(cfg("a", { target: "w" }), [box, wsl])).toBe("w");
});
});
describe("SSH remedies when starting", () => {
+16 -10
Переглянути файл
@@ -1,6 +1,6 @@
/**
* Run targets (Settings › Run Targets): configurations with a `target` run over
* SSH or in a Docker / Compose container. Labels, the debug and executor guards,
* SSH, in a Docker / Compose container or in a WSL distribution. Labels, the debug and executor guards,
* and the connection remedies of `runStart`.
*/
import { withRunTarget } from "@/platform/runTargetSelection";
@@ -59,8 +59,9 @@ export function withTarget(config: RunConfig, target: string): RunConfig {
const PYTHON_KINDS = new Set(["python", "pytest", "unittest", "doctest", "django-test", "celery"]);
/**
* The id of the Docker / Compose run target `config` runs in: its own target, else, for a Python
* configuration, the project interpreter's (`target:<id>`, as ide-sdk's `run_target` picks it).
* The id of the Docker / Compose / WSL run target `config` runs in: its own target, else, for a
* Python configuration, the project interpreter's (`target:<id>`, as ide-sdk's `run_target` picks
* it). The paths such a run prints are looked up through `runContainerPath`.
*/
export function containerTarget(
config: RunConfig | null | undefined,
@@ -75,7 +76,7 @@ export function containerTarget(
(python && interpreter.startsWith("target:") ? interpreter.slice("target:".length).trim() : null) ??
withRunTarget(config).target;
const target = id ? targetOf({ target: id }, targets) : undefined;
return target && inContainer(target) ? target.id : null;
return target && (inContainer(target) || target.kind === "wsl") ? target.id : null;
}
/**
@@ -121,23 +122,28 @@ export function remoteDebugBlocked(config: RunConfig, targets: readonly RuntimeR
/**
* Coverage and profiling read their results on this machine: tells so (offering
* Run) and returns true when `config` runs in a container.
* Run) and returns true when `config` runs in a container or a WSL distribution.
*/
export function containerExecutorBlocked(
config: RunConfig,
targets: readonly RuntimeRunTarget[] = allRunTargets(),
): boolean {
const target = targetOf(config, targets);
if (!target || !inContainer(target)) return false;
if (!target || !(inContainer(target) || target.kind === "wsl")) return false;
const where = target.name.trim() || target.id;
const wsl = target.kind === "wsl";
notifications().notify({
group: "run",
level: "warning",
key: "run.containerExecutor",
title: "Coverage and profiling are not supported in containers",
body: txTemplate(
`'${config.name}' runs in a container on ${where}. Run it, or choose “Local machine” under “Run on”.`,
),
title: wsl
? "Coverage and profiling are not supported on WSL"
: "Coverage and profiling are not supported in containers",
body: wsl
? txTemplate(`'${config.name}' runs in WSL on ${where}. Run it, or choose “Local machine” under “Run on”.`)
: txTemplate(
`'${config.name}' runs in a container on ${where}. Run it, or choose “Local machine” under “Run on”.`,
),
actions: [
{ label: "Run", run: () => void executeAction("run.runConfig", config.id) },
{ label: "Edit Configuration…", run: () => void executeAction("run.editConfigs", config.id) },
+5 -2
Переглянути файл
@@ -32,7 +32,9 @@ function frameLocation(line: string): TestLocation | null {
/**
* Test events of the init script's messages. Tests are `[class, method]`, named as in the XML reports
* (`add(int, int)[1]` → `add`); `outcomes` keeps each test's failure or skip until it finishes.
* (`add(int, int)` → `add`), and an invocation of a parameterized, repeated or dynamic test is
* `[class, method, "[1] a"]` (its `invocation`, the display name); `outcomes` keeps each test's
* failure or skip until it finishes.
*/
function initScriptEvents({ kind, attrs }: ServiceMessage, outcomes: Map<string, "failed" | "skipped">): TestEvent[] {
if (!attrs.className) return [];
@@ -43,8 +45,9 @@ function initScriptEvents({ kind, attrs }: ServiceMessage, outcomes: Map<string,
// A class's own output (`@BeforeAll`, `@AfterAll`) belongs to the class.
if (!attrs.name) return kind === "testStdOut" || kind === "testStdErr" ? printed([attrs.className]) : [];
const path = [attrs.className, attrs.name.split("(")[0]!.trim() || attrs.name];
if (attrs.invocation) path.push(attrs.invocation);
const key = path.join("\0");
// A parameterized method's invocations share its node: one failure fails the method.
// Invocations without a name of their own share the method's node: one failure fails the method.
const failed = outcomes.get(key) === "failed";
switch (kind) {
case "testStarted":
+26
Переглянути файл
@@ -16,6 +16,7 @@ import {
type TestOutputParser,
} from "./index";
import { moveToReportedClasses } from "./jvm";
import { failedTestPaths } from "./rerun";
function results(parser: TestOutputParser, text: string) {
const r = new TestResults();
@@ -589,6 +590,31 @@ CalcTest > fails() FAILED
expect(r.hasResult(["demo.CalcTest", "other"])).toBe(false);
});
it("shows each invocation of a parameterized test under its method", () => {
const r = results(
jvmParser(),
`##teamcity[testStarted name='accepts' className='demo.ParamTest' invocation='|[1|] a']
##teamcity[testFinished name='accepts' className='demo.ParamTest' invocation='|[1|] a' duration='2']
##teamcity[testStarted name='accepts' className='demo.ParamTest' invocation='|[2|] bb']
##teamcity[testStdOut name='accepts' className='demo.ParamTest' invocation='|[2|] bb' out='checking bb|n']
##teamcity[testFailed name='accepts' className='demo.ParamTest' invocation='|[2|] bb' message='no' details='org.opentest4j.AssertionFailedError: no|n\tat app//demo.ParamTest.accepts(ParamTest.java:12)|n']
##teamcity[testFinished name='accepts' className='demo.ParamTest' invocation='|[2|] bb' duration='1']
##teamcity[testStarted name='accepts(String)|[3|]' className='demo.ParamTest' invocation='|[3|] c']
##teamcity[testFinished name='accepts(String)|[3|]' className='demo.ParamTest' invocation='|[3|] c' duration='1']
`,
);
const method = leaf(r, "demo.ParamTest", "accepts")!;
expect(method.children.map((n) => n.name)).toEqual(["[1] a", "[2] bb", "[3] c"]);
expect(nodeStatus(method)).toBe("failed");
expect(leaf(r, "demo.ParamTest", "accepts", "[1] a")).toMatchObject({ own: "passed", durationMs: 2, output: [] });
const failed = leaf(r, "demo.ParamTest", "accepts", "[2] bb")!;
expect(failed.own).toBe("failed");
expect(failed.output.slice(0, 2)).toEqual(["checking bb", "org.opentest4j.AssertionFailedError: no"]);
expect(failed.location).toMatchObject({ path: "demo/ParamTest.java", line: 12 });
expect(leaf(r, "demo.ParamTest", "accepts", "[3] c")?.own).toBe("passed");
expect(failedTestPaths(r)).toEqual([["demo.ParamTest", "accepts", "[2] bb"]]);
});
it("gives a class's own output from the gradle init script to the class", () => {
const r = results(
jvmParser(),
+9
Переглянути файл
@@ -244,6 +244,15 @@ describe("rerunFailedConfig", () => {
]);
});
it("jvm: a failed invocation of a parameterized test reruns its method", async () => {
expect(
(await rerunFailedConfig(cfg("gradle", "./gradlew", ["test"]), [
["com.a.FooTest", "add", "[2] b"],
["com.a.FooTest", "add", "[3] c"],
]))!.args,
).toEqual(["test", "--tests", "com.a.FooTest.add"]);
});
it("maven: a rerun replaces the previous selection and lets modules without the tests pass", async () => {
const narrowed = cfg("maven", "./mvnw", [
"test",
+2 -3
Переглянути файл
@@ -153,9 +153,8 @@ function goArgs(base: string[], paths: string[][], file?: string): string[] | nu
}
function jvmArgs(config: RunConfig, paths: string[][]): string[] | null {
const tests = paths
.filter((p) => p.length >= 2)
.map((p) => ({ cls: p[0]!, method: p[p.length - 1]!.replace(/\(\)$/, "") }));
// `[class, method]`, or `[class, method, invocation]`: an invocation reruns its method.
const tests = paths.filter((p) => p.length >= 2).map((p) => ({ cls: p[0]!, method: p[1]!.replace(/\(.*\)$/, "") }));
const classes = unique(paths.filter((p) => p.length === 1).map((p) => p[0]!));
if (!tests.length && !classes.length) return null;
if (isJunitRunner(config)) {
+2 -2
Переглянути файл
@@ -93,8 +93,8 @@ function DeadlockBanner({ dump, onSelect }: { dump: ThreadDump; onSelect: (name:
);
return (
<div role="alert" className={styles.banner}>
{dump.deadlocks.map((cycle, i) => (
<div key={i} className={styles.cycle}>
{dump.deadlocks.map((cycle) => (
<div key={cycle.map((link) => link.thread).join("\u0000")} className={styles.cycle}>
<span className={styles.cycleLabel}>
<T>Deadlock:</T>
</span>
+113
Переглянути файл
@@ -0,0 +1,113 @@
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({ distros: vi.fn(), pythons: vi.fn(), detect: vi.fn(), hatchEnvs: vi.fn() }));
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
return {
...real,
isTauri: () => true,
commands: {
...real.commands,
wslDistros: mocks.distros,
sdkWslPythons: mocks.pythons,
sdkDetect: mocks.detect,
sdkPythonHatchEnvs: mocks.hatchEnvs,
},
};
});
const { AddInterpreterDialog } = await import("../languages/AddInterpreterDialog");
const { targetChoices, useSdks } = await import("../languages/api");
const { DEFAULT_RUN_TARGET } = await import("@/platform/remoteSettings");
const ok = <T,>(data: T) => ({ status: "ok" as const, data });
beforeEach(() => {
Object.assign(window, { __TAURI_INTERNALS__: { transformCallback: () => 1 } });
mocks.detect.mockResolvedValue(ok([]));
mocks.hatchEnvs.mockResolvedValue(ok([]));
mocks.pythons.mockImplementation((distro: string) =>
Promise.resolve(ok(distro === "Debian" ? [] : ["/usr/bin/python3", "/mnt/c/p/.venv/bin/python"])),
);
useSdks.setState({ byKind: {}, loading: {}, errors: {} });
});
afterEach(() => {
cleanup();
vi.clearAllMocks();
});
const dialog = (onAddedTarget?: (t: unknown) => void) =>
render(<AddInterpreterDialog root="/p" onClose={() => {}} onAdded={() => {}} onAddedTarget={onAddedTarget} />);
describe("Add Python Interpreter › WSL", () => {
it("is offered only when WSL has distributions", async () => {
mocks.distros.mockResolvedValue(ok([]));
dialog(() => {});
await waitFor(() => expect(mocks.distros).toHaveBeenCalled());
expect(screen.queryByRole("button", { name: "WSL" })).toBeNull();
});
it("adds a WSL run target with the Python found in the distribution", async () => {
mocks.distros.mockResolvedValue(ok(["Ubuntu-24.04", "Debian"]));
const added = vi.fn();
dialog(added);
fireEvent.click(await screen.findByRole("button", { name: "WSL" }));
// The first one found is the default; the input stays empty so every choice is offered.
const input = await screen.findByPlaceholderText("/usr/bin/python3");
expect(mocks.pythons).toHaveBeenCalledWith("Ubuntu-24.04");
fireEvent.change(input, { target: { value: "~/venv/bin/python" } });
fireEvent.click(screen.getByRole("button", { name: "OK" }));
expect(await screen.findByRole("alert")).toHaveTextContent(/absolute path/);
for (const windows of [String.raw`C:\venv\Scripts\python.exe`, "c:/venv/python.exe", String.raw`venv\python`]) {
fireEvent.change(input, { target: { value: windows } });
fireEvent.click(screen.getByRole("button", { name: "OK" }));
expect(screen.getByRole("alert")).toHaveTextContent(/absolute path/);
}
expect(added).not.toHaveBeenCalled();
fireEvent.change(input, { target: { value: "/mnt/c/p/.venv/bin/python" } });
fireEvent.click(screen.getByRole("button", { name: "OK" }));
expect(added).toHaveBeenCalledWith(
expect.objectContaining({
kind: "wsl",
name: "WSL Ubuntu-24.04",
distro: "Ubuntu-24.04",
python: "/mnt/c/p/.venv/bin/python",
}),
);
});
it("says why it is not offered when the distributions could not be listed", async () => {
mocks.distros.mockRejectedValue(new Error("wsl.exe did not answer in time"));
dialog(() => {});
expect(await screen.findByRole("alert")).toHaveTextContent(
"WSL distributions could not be listed: wsl.exe did not answer in time",
);
expect(screen.queryByRole("button", { name: "WSL" })).toBeNull();
});
it("says when the distribution has no Python", async () => {
mocks.distros.mockResolvedValue(ok(["Debian"]));
dialog(() => {});
fireEvent.click(await screen.findByRole("button", { name: "WSL" }));
expect(await screen.findByText(/No Python found in this distribution/)).toBeTruthy();
expect(screen.getByRole("button", { name: "OK" })).toBeDisabled();
});
it("tells a project's own target list from the global one by content, not field order", async () => {
const { sameTargets } = await import("../languages/PythonInterpreterPage");
const a = { ...DEFAULT_RUN_TARGET, kind: "wsl" as const, id: "w", name: "W", distro: "Ubuntu" };
const reordered = Object.fromEntries(Object.entries(a).reverse()) as typeof a;
expect(sameTargets([a], [reordered])).toBe(true);
expect(sameTargets([a], [{ ...a, python: "/usr/bin/python3" }])).toBe(false);
expect(sameTargets([a], [])).toBe(false);
});
it("lists WSL targets as interpreters", () => {
const wsl = { ...DEFAULT_RUN_TARGET, kind: "wsl" as const, id: "w", name: "WSL Ubuntu", distro: "Ubuntu" };
const ssh = { ...DEFAULT_RUN_TARGET, kind: "ssh" as const, id: "s", name: "Box" };
expect(targetChoices([wsl, ssh])).toEqual([
expect.objectContaining({ value: "target:w", label: "WSL Ubuntu", detail: "python3 in WSL Ubuntu" }),
]);
});
});
+30 -2
Переглянути файл
@@ -8,6 +8,8 @@ const mocks = vi.hoisted(() => ({
packages: vi.fn(),
effective: vi.fn(),
cancel: vi.fn(),
distros: vi.fn(async () => ({ status: "ok", data: ["Ubuntu"] })),
pythons: vi.fn(async () => ({ status: "ok", data: ["/usr/bin/python3"] })),
}));
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
@@ -22,6 +24,9 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
sdkPythonPackages: mocks.packages,
sdkPythonEffective: mocks.effective,
cancelRequest: mocks.cancel,
wslDistros: mocks.distros,
sdkWslPythons: mocks.pythons,
sdkPythonHatchEnvs: vi.fn(async () => ({ status: "ok", data: [] })),
},
};
});
@@ -38,6 +43,7 @@ const SNAPSHOT: ContainerPython = {
target: "web",
name: "Compose web",
version: "3.12.7",
executable: "/usr/local/bin/python",
image: "sha256:0123456789abcdef",
folders: ["/cache/web/0123/fs/usr/local/lib/python3.12/site-packages"],
packages: [
@@ -52,11 +58,13 @@ const TARGETS = [
];
const PYTHON_INTERPRETER_CONTEXT = { pageId: "python.interpreter", scope: "project" } as const;
function mount(interpreter: string) {
function mount(interpreter: string, inherited = false) {
const settings = structuredClone(DEFAULT_SETTINGS) as typeof DEFAULT_SETTINGS & Record<string, unknown>;
settings.languages.python.interpreter = interpreter;
settings.runTargets = TARGETS;
useSettingsDialog.setState({ base: settings, globalBase: structuredClone(DEFAULT_SETTINGS), staged: {}, query: "" });
const global = structuredClone(DEFAULT_SETTINGS) as typeof DEFAULT_SETTINGS & Record<string, unknown>;
if (inherited) global.runTargets = TARGETS;
useSettingsDialog.setState({ base: settings, globalBase: global, staged: {}, query: "" });
render(
<PageContext.Provider value={PYTHON_INTERPRETER_CONTEXT}>
<PythonInterpreterPage />
@@ -99,6 +107,26 @@ describe("run target interpreter", () => {
await waitFor(() => expect(mocks.refresh).toHaveBeenCalledTimes(1));
});
it("adds a WSL interpreter's run target to the IDE-wide list only", async () => {
const { useProject } = await import("@/platform/project");
useProject.setState({ project: { root: "/p" } } as never);
mount("", true);
fireEvent.click(screen.getByRole("button", { name: "Add Interpreter…" }));
fireEvent.click(await screen.findByRole("button", { name: "WSL" }));
await screen.findByPlaceholderText("/usr/bin/python3");
fireEvent.click(screen.getByRole("button", { name: "OK" }));
const staged = Object.values(useSettingsDialog.getState().staged) as {
scope: string;
key: string;
value: unknown;
}[];
const targets = staged.filter((c) => c.key === "runTargets");
expect(targets.map((c) => c.scope)).toEqual(["global"]);
const added = (targets[0]?.value as { id: string }[] | undefined)?.at(-1);
expect(added).toMatchObject({ kind: "wsl", distro: "Ubuntu", python: "/usr/bin/python3" });
expect(staged.find((c) => c.key === "languages.python.interpreter")?.value).toBe(`target:${added?.id}`);
});
it("offers the container targets in the interpreter list", async () => {
mount("");
fireEvent.click(screen.getByRole("button", { name: "Python interpreter" }));
+3 -1
Переглянути файл
@@ -12,6 +12,8 @@ import type { PageSpec } from "../pages/spec";
afterEach(cleanup);
const APPEARANCE_CONTEXT = { pageId: "appearance", scope: "global" } as const;
const PAGE: PageSpec = {
id: "test.dependentOptions",
title: "Dependent options",
@@ -101,7 +103,7 @@ describe("dependent options of a checkbox", () => {
useProject.setState({ settings, project: null });
openSettings(appearance.id);
render(
<PageContext.Provider value={{ pageId: appearance.id, scope: "global" }}>
<PageContext.Provider value={APPEARANCE_CONTEXT}>
<OptionsPage spec={appearance} />
</PageContext.Provider>,
);
+2 -1
Переглянути файл
@@ -27,13 +27,14 @@ const PAGE: PageSpec = {
},
],
};
const PAGE_CONTEXT = { pageId: PAGE.id, scope: "project" } as const;
function renderPage(enabled: boolean) {
const settings = { ...structuredClone(DEFAULT_SETTINGS), vcs: { git: { enabled } } } as typeof DEFAULT_SETTINGS;
useProject.setState({ settings, project: null });
openSettings(PAGE.id);
render(
<PageContext.Provider value={{ pageId: PAGE.id, scope: "project" }}>
<PageContext.Provider value={PAGE_CONTEXT}>
<OptionsPage spec={PAGE} />
</PageContext.Provider>,
);
+2 -1
Переглянути файл
@@ -16,6 +16,7 @@ const TARGETS = [
{ ...DEFAULT_RUN_TARGET, kind: "compose" as const, id: "odoo110", name: "odoo110", ports: ["8069:8069"] },
{ ...DEFAULT_RUN_TARGET, kind: "compose" as const, id: "odoo170", name: "odoo170", ports: ["9000:9000"] },
];
const PAGE_CONTEXT = { pageId: "build.runTargets", scope: "global" } as const;
function mount() {
const settings = structuredClone(DEFAULT_SETTINGS) as typeof DEFAULT_SETTINGS & Record<string, unknown>;
@@ -27,7 +28,7 @@ function mount() {
query: "",
});
render(
<PageContext.Provider value={{ pageId: "build.runTargets", scope: "global" }}>
<PageContext.Provider value={PAGE_CONTEXT}>
<RunTargetsEditor />
</PageContext.Provider>,
);
+76
Переглянути файл
@@ -0,0 +1,76 @@
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const { distros } = vi.hoisted(() => ({ distros: vi.fn() }));
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
return { ...real, isTauri: () => true, commands: { ...real.commands, wslDistros: distros } };
});
const { PageContext } = await import("../components/context");
const { RunTargetsEditor } = await import("../pages/RunTargetsBody");
const { useSettingsDialog } = await import("../model/staging");
const { DEFAULT_SETTINGS } = await import("../model/schema");
const { DEFAULT_RUN_TARGET, validateRunTargets } = await import("@/platform/remoteSettings");
const PAGE_CONTEXT = { pageId: "build.runTargets", scope: "global" } as const;
function mount(targets: unknown[]) {
const settings = structuredClone(DEFAULT_SETTINGS) as typeof DEFAULT_SETTINGS & Record<string, unknown>;
settings.runTargets = targets as typeof settings.runTargets;
useSettingsDialog.setState({ base: structuredClone(settings), globalBase: settings, staged: {}, query: "" });
render(
<PageContext.Provider value={PAGE_CONTEXT}>
<RunTargetsEditor />
</PageContext.Provider>,
);
}
const typeOptions = () => {
fireEvent.click(screen.getByRole("button", { name: "Type" }));
return screen.getAllByRole("option").map((o) => o.textContent);
};
beforeEach(() => {
Object.assign(window, { __TAURI_INTERNALS__: { transformCallback: () => 1 } });
});
afterEach(() => {
cleanup();
distros.mockReset();
});
describe("WSL run targets", () => {
it("are offered only when WSL has distributions", async () => {
distros.mockResolvedValue({ status: "ok", data: [] });
mount([{ ...DEFAULT_RUN_TARGET, id: "box", name: "Box" }]);
await waitFor(() => expect(distros).toHaveBeenCalled());
expect(typeOptions()).not.toContain("WSL");
});
it("pick the first distribution and show its fields", async () => {
distros.mockResolvedValue({ status: "ok", data: ["Ubuntu-24.04", "Debian"] });
mount([{ ...DEFAULT_RUN_TARGET, id: "box", name: "Box" }]);
await waitFor(() => expect(typeOptions()).toContain("WSL"));
fireEvent.click(screen.getByRole("option", { name: "WSL" }));
expect(await screen.findByRole("button", { name: "WSL distribution" })).toHaveTextContent("Ubuntu-24.04");
expect(screen.getByRole("textbox", { name: "Project folder in WSL" })).toHaveValue("");
const staged = useSettingsDialog.getState().staged as Record<string, unknown>;
expect(JSON.stringify(staged)).toContain('"distro":"Ubuntu-24.04"');
});
it("keep a distribution that is no longer installed", async () => {
distros.mockResolvedValue({ status: "ok", data: [] });
mount([{ ...DEFAULT_RUN_TARGET, kind: "wsl", id: "w", name: "W", distro: "Old" }]);
expect(await screen.findByRole("button", { name: "WSL distribution" })).toHaveTextContent("Old (missing)");
expect(typeOptions()).toContain("WSL");
});
it("are read back from settings", () => {
expect(validateRunTargets([{ kind: "wsl", id: "w", distro: "Ubuntu", projectRoot: "/c/p" }])[0]).toMatchObject({
kind: "wsl",
distro: "Ubuntu",
projectRoot: "/c/p",
});
});
});
+3 -1
Переглянути файл
@@ -34,6 +34,8 @@ import { SwiftPage } from "../languages/LanguagePages";
import { DEFAULT_SETTINGS } from "../model/schema";
import { openSettings } from "../model/staging";
const PAGE_CONTEXT = { pageId: "languages.swift", scope: "project" } as const;
afterEach(() => {
cleanup();
vi.clearAllMocks();
@@ -46,7 +48,7 @@ describe("Swift settings page", () => {
useProject.setState({ settings, project: null });
openSettings("languages.swift");
render(
<PageContext.Provider value={{ pageId: "languages.swift", scope: "project" }}>
<PageContext.Provider value={PAGE_CONTEXT}>
<SwiftPage />
</PageContext.Provider>,
);
+144 -7
Переглянути файл
@@ -1,12 +1,23 @@
/**
* PyCharm's "Add Python Interpreter" (local): generate a new environment with a
* tool (virtualenv / conda / uv / Poetry / Pipenv / Hatch) or select an existing interpreter.
* On Windows with WSL, also a Python in a WSL distribution: it becomes a WSL run target.
*/
import { isCancelled } from "@/platform/ipc";
import { useEffect, useId, useMemo, useState } from "react";
import { Checkbox, Dialog, IconButton, Input, Select, Spinner, type SelectOption, T } from "@/ui";
import { Icon, type IconName } from "@/ui/icons";
import { createVenv, hatchEnvs, pythonInterpreter, rememberSdk, type Sdk, type VenvTool } from "./api";
import {
createVenv,
hatchEnvs,
pythonInterpreter,
rememberSdk,
wslDistros,
wslPythons,
type Sdk,
type VenvTool,
} from "./api";
import { DEFAULT_RUN_TARGET, type RunTargetValid } from "@/platform/remoteSettings";
import { choosePath } from "@/platform/choosePath";
import { tildify, useDetected } from "./components";
import styles from "./Sdk.module.css";
@@ -39,13 +50,22 @@ export function AddInterpreterDialog({
root,
onClose,
onAdded,
onAddedTarget,
}: {
root: string;
onClose: () => void;
onAdded: (python: string) => void;
/** A WSL Python was chosen: the run target to add (without an id) and make the interpreter. */
onAddedTarget?: (target: Omit<RunTargetValid, "id">) => void;
}) {
const { list, loading } = useDetected("python");
const [kind, setKind] = useState<VenvTool>("venv");
// The WSL entry is chosen instead of an environment tool.
const [wsl, setWsl] = useState(false);
const [distros, setDistros] = useState<string[]>([]);
const [distro, setDistro] = useState<string | null>(null);
const [wslFound, setWslFound] = useState<{ distro: string; pythons: string[] } | null>(null);
const [wslPython, setWslPython] = useState<string | null>(null);
const [mode, setMode] = useState<Mode>("new");
const bases = useMemo(() => list.filter((s) => !["venv", "pipenv", "hatch"].includes(s.source)), [list]);
const [base, setBase] = useState<string | null>(null);
@@ -61,7 +81,39 @@ export function AddInterpreterDialog({
const [busy, setBusy] = useState<{ cancel: () => void } | null>(null);
const [log, setLog] = useState<string[]>([]);
const [error, setError] = useState<string | null>(null);
const ids = { base: useId(), location: useId(), existing: useId() };
const ids = { base: useId(), location: useId(), existing: useId(), distro: useId(), wslPython: useId() };
const wslOffered = !!onAddedTarget;
useEffect(() => {
if (!wslOffered) return;
let live = true;
// Without distributions the WSL entry is hidden: say why when listing them failed.
wslDistros()
.then((found) => live && setDistros(found))
.catch(
(e: unknown) => live && setError(tx`WSL distributions could not be listed: ${(e as Error)?.message ?? e}`),
);
return () => {
live = false;
};
}, [wslOffered]);
const distroValue = distro ?? distros[0] ?? null;
useEffect(() => {
if (!wsl || !distroValue) return;
let live = true;
wslPythons(distroValue)
.then((pythons) => live && setWslFound({ distro: distroValue, pythons }))
.catch((e: unknown) => {
if (!live) return;
setWslFound({ distro: distroValue, pythons: [] });
setError(String((e as Error)?.message ?? e));
});
return () => {
live = false;
};
}, [wsl, distroValue]);
const wslPythonsFound = wslFound?.distro === distroValue ? wslFound.pythons : null;
const wslPythonValue = (wslPython ?? wslPythonsFound?.[0] ?? "").trim();
const toOption = (s: { path: string; name: string }): SelectOption => ({
value: s.path,
@@ -148,6 +200,25 @@ export function AddInterpreterDialog({
const ok = () => {
if (busy) return;
setError(null);
if (wsl) {
// Run with `wsl.exe --exec`: no shell expands `~`, and a relative path has no folder to start from.
// A Windows path (`C:\venv\python.exe`) is this machine's, not the distribution's. A bare
// name (`python3`) is looked up on the distribution's `PATH`.
const windowsPath = /^[A-Za-z]:|\\/.test(wslPythonValue);
if (windowsPath || (wslPythonValue.includes("/") && !wslPythonValue.startsWith("/"))) {
setError(tx("Type the absolute path of the Python in WSL, such as /home/me/.venv/bin/python."));
return;
}
if (distroValue && wslPythonValue && onAddedTarget)
onAddedTarget({
...DEFAULT_RUN_TARGET,
kind: "wsl",
name: `WSL ${distroValue}`,
distro: distroValue,
python: wslPythonValue,
});
return;
}
if (mode === "existing") {
if (existing)
checkExisting(existing, (sdk) => {
@@ -173,7 +244,8 @@ export function AddInterpreterDialog({
.finally(() => setBusy(null));
};
const canOk = !busy && (mode === "new" ? !!baseValue && !!target : !!existing?.trim());
const canOk =
!busy && (wsl ? !!distroValue && !!wslPythonValue : mode === "new" ? !!baseValue && !!target : !!existing?.trim());
const note = {
venv: inheritPackages
? tx(
@@ -197,6 +269,51 @@ export function AddInterpreterDialog({
hatch: tx("Runs “hatch env create <environment>” in the project. Hatch decides where to store the environment."),
}[kind];
const wslForm = (
<>
<label htmlFor={ids.distro}>
<T>Distribution:</T>
</label>
<Select
id={ids.distro}
value={distroValue}
options={distros.map((d) => ({ value: d, label: d, verbatim: true }))}
onChange={(d) => {
setDistro(d);
setWslPython(null);
setError(null);
}}
aria-label={tx("WSL distribution")}
/>
<label htmlFor={ids.wslPython}>
<T>Python interpreter:</T>
</label>
<Input
id={ids.wslPython}
list={`${ids.wslPython}-found`}
value={wslPython ?? ""}
placeholder={wslPythonsFound ? (wslPythonsFound[0] ?? "python3") : tx("Looking for Python…")}
onChange={(e) => setWslPython(e.target.value)}
/>
<datalist id={`${ids.wslPython}-found`}>
{wslPythonsFound?.map((p) => (
<option key={p} value={p} />
))}
</datalist>
{wslPythonsFound?.length === 0 && !formError && (
<div className={styles.note}>
<T>No Python found in this distribution. Install python3 there, or type the path of one.</T>
</div>
)}
<div className={styles.note}>
<T>
Adds a WSL run target with this Python and makes it the project interpreter. The language server reads its
libraries in place in the distribution; install packages there, in WSL.
</T>
</div>
</>
);
return (
<Dialog
open
@@ -221,9 +338,10 @@ export function AddInterpreterDialog({
<button
type="button"
disabled={!!busy}
className={`${styles.kind} ${kind === k.tool ? styles.kindOn : ""}`}
aria-current={kind === k.tool || undefined}
className={`${styles.kind} ${!wsl && kind === k.tool ? styles.kindOn : ""}`}
aria-current={(!wsl && kind === k.tool) || undefined}
onClick={() => {
setWsl(false);
setKind(k.tool);
setBase(null);
setError(null);
@@ -234,9 +352,26 @@ export function AddInterpreterDialog({
</button>
</li>
))}
{distros.length > 0 && (
<li>
<button
type="button"
disabled={!!busy}
className={`${styles.kind} ${wsl ? styles.kindOn : ""}`}
aria-current={wsl || undefined}
onClick={() => {
setWsl(true);
setError(null);
}}
>
<Icon name="toolwindow-terminal" size={16} />
<T>WSL</T>
</button>
</li>
)}
</ul>
<div className={styles.form}>
<div className={styles.radios} role="radiogroup" aria-label={tx("Environment")}>
<div className={styles.radios} role="radiogroup" aria-label={tx("Environment")} hidden={wsl}>
<label className={styles.radio}>
<input
type="radio"
@@ -258,7 +393,9 @@ export function AddInterpreterDialog({
<T>Existing environment</T>
</label>
</div>
{mode === "new" ? (
{wsl ? (
wslForm
) : mode === "new" ? (
<>
{kind === "conda" ? (
<>
+51 -8
Переглянути файл
@@ -2,8 +2,9 @@
* Settings › Python › Dependencies (PyCharm's "Python Interpreter" page): the
* project interpreter and its packages (pip / uv pip). The interpreter feeds
* run configurations, basedpyright / pyright (`python.pythonPath`) and the
* terminal's virtualenv activation. A Docker or Compose run target can be the
* interpreter (`target:<id>`): its libraries are a read-only snapshot of the image.
* terminal's virtualenv activation. A Docker, Compose or WSL run target can be the
* interpreter (`target:<id>`): its libraries are a read-only snapshot of the image, or
* read in place in the WSL distribution.
*/
import { isCancelled } from "@/platform/ipc";
import { useCallback, useEffect, useMemo, useState, type KeyboardEvent, type MouseEvent } from "react";
@@ -22,7 +23,7 @@ import {
type ContainerPython,
type PythonPackage,
} from "./api";
import { validateRunTargets, type RunTargetValid } from "@/platform/remoteSettings";
import { newRemoteId, validateRunTargets, type RunTargetValid } from "@/platform/remoteSettings";
import { AddInterpreterDialog } from "./AddInterpreterDialog";
import { useAppliedSetting, useSetting } from "../components/context";
import { SdkField, tildify } from "./components";
@@ -113,9 +114,13 @@ export function PythonInterpreterPage() {
})),
[rows, detected],
);
const [rawTargets] = useSetting<RunTargetValid[] | undefined>("runTargets");
const [rawTargets, setRawTargets] = useSetting<RunTargetValid[] | undefined>("runTargets");
// A new run target joins the IDE-wide list, where Settings › Run Targets opens; the project
// keeps inheriting it rather than a copy of the whole list.
const [globalTargets, setGlobalTargets] = useSetting<RunTargetValid[] | undefined>("runTargets", "global");
const targets = useMemo(() => targetChoices(validateRunTargets(rawTargets)), [rawTargets]);
const target = interpreterTarget(interpreter);
const onWsl = !!target && validateRunTargets(rawTargets).find((t) => t.id === target)?.kind === "wsl";
const container = useContainerPython(target);
useEffect(() => {
@@ -222,12 +227,16 @@ export function PythonInterpreterPage() {
const containerDetail = !target
? null
: container.info?.version
? `${container.info.name || target} — Python ${container.info.version}${container.info.image ? ` · ${container.info.image.replace(/^sha256:/, "").slice(0, 12)}` : ""}`
? `${container.info.name || target} — Python ${container.info.version}${container.info.image ? ` · ${container.info.image.replace(/^sha256:/, "").slice(0, 12)}` : onWsl && container.info.executable ? ` · ${container.info.executable}` : ""}`
: container.busy
? tx("Copying the libraries from the container…")
? onWsl
? tx("Reading the libraries in WSL…")
: tx("Copying the libraries from the container…")
: container.info && !container.info.name
? tx("No run target has this id: choose another interpreter.")
: tx("The container's libraries have not been copied yet.");
: onWsl
? tx("The WSL Python's libraries have not been read yet.")
: tx("The container's libraries have not been copied yet.");
return (
<div className={styles.page}>
@@ -408,7 +417,15 @@ export function PythonInterpreterPage() {
<T>Could not check for newer versions of the packages.</T>
</div>
)}
{target && (
{target && onWsl && (
<div className={styles.note}>
<T>
Packages come from the Python in WSL and are read-only here. To change them, install them there (for example
with pip in the distribution), then reload the list.
</T>
</div>
)}
{target && !onWsl && (
<div className={styles.note}>
<T>
Packages come from the container image and are read-only here. To change them, edit the image or its
@@ -466,6 +483,26 @@ export function PythonInterpreterPage() {
reload();
setAdding(false);
}}
onAddedTarget={(added) => {
const id = newRemoteId("target");
const project = validateRunTargets(rawTargets);
// The same Python chosen again: its run target already exists.
const same = project.find(
(t) => t.kind === "wsl" && t.distro === added.distro && t.python === added.python,
);
if (same) {
setInterpreter(`target:${same.id}`);
setAdding(false);
return;
}
const target = { ...added, id };
const global = validateRunTargets(globalTargets);
// A project with a list of its own (it doesn't inherit the global one) gets it too.
if (!sameTargets(project, global)) setRawTargets([...project, target]);
setGlobalTargets([...global, target]);
setInterpreter(`target:${id}`);
setAdding(false);
}}
/>
)}
</div>
@@ -484,6 +521,12 @@ function latestCell(pkg: PythonPackage, newer: Map<string, string> | null) {
);
}
/** The same run targets in the same order, whatever order their fields were written in. */
export function sameTargets(a: readonly RunTargetValid[], b: readonly RunTargetValid[]): boolean {
const canonical = (t: RunTargetValid) => JSON.stringify(t, Object.keys(t).sort());
return a.length === b.length && a.every((t, i) => canonical(t) === canonical(b[i]!));
}
/** Whether `resolved` (an absolute path from the backend) is the configured `interpreter` setting. */
function sameInterpreter(resolved: string | null, interpreter: string, root: string | null): boolean {
if (!resolved) return false;
+3
Переглянути файл
@@ -262,6 +262,9 @@
flex-wrap: wrap;
gap: var(--space-1-5) var(--space-4);
}
.radios[hidden] {
display: none;
}
.radio {
display: inline-flex;
align-items: center;
+31 -9
Переглянути файл
@@ -208,19 +208,41 @@ export function interpreterTarget(value: string | null | undefined): string | nu
return v.slice(TARGET_PREFIX.length).trim() || null;
}
/** Docker and Compose run targets as interpreter choices (`target:<id>`). */
/** The run target kinds whose Python can be the project interpreter (its libraries are read here). */
const INTERPRETER_TARGET_KINDS: ReadonlySet<string> = new Set(["docker", "compose", "wsl"]);
/** Docker, Compose and WSL run targets as interpreter choices (`target:<id>`). A new kind is
* added here once its libraries can be read; SSH targets have none on this machine. */
export function targetChoices(targets: readonly RunTargetValid[]): SelectOption[] {
return targets
.filter((t) => t.kind === "docker" || t.kind === "compose")
.map((t) => ({
value: `${TARGET_PREFIX}${t.id}`,
label: t.name || t.id,
verbatim: true,
detail: t.kind === "compose" ? tx`Docker Compose service ${t.service}` : tx`Docker image ${t.image}`,
}));
.filter((t) => INTERPRETER_TARGET_KINDS.has(t.kind))
.map((t) => {
const python = t.python || "python3";
return {
value: `${TARGET_PREFIX}${t.id}`,
label: t.name || t.id,
verbatim: true,
detail:
t.kind === "wsl"
? tx`${python} in WSL ${t.distro}`
: t.kind === "compose"
? tx`Docker Compose service ${t.service}`
: tx`Docker image ${t.image}`,
};
});
}
/** The project interpreter when it is a Docker or Compose run target's, with its library snapshot. */
/** Installed WSL distributions; empty off Windows. */
export function wslDistros(): Promise<string[]> {
return isTauri() ? call(commands.wslDistros()) : Promise.resolve([]);
}
/** The Pythons found in a WSL distribution (paths there). */
export function wslPythons(distro: string): Promise<string[]> {
return isTauri() ? call(commands.sdkWslPythons(distro)) : Promise.resolve([]);
}
/** The project interpreter when it is a run target's, with its library snapshot. */
export function containerPython(): Promise<ContainerPython | null> {
return isTauri() ? call(commands.sdkContainerPython()) : Promise.resolve(null);
}
+84 -5
Переглянути файл
@@ -1,6 +1,6 @@
/**
* Build, Execution, Deployment › Run Targets: SSH hosts and Docker / Compose
* containers run configurations can run on (`RunConfig.target`). Consumed by
* Build, Execution, Deployment › Run Targets: SSH hosts, Docker / Compose
* containers and WSL distributions run configurations can run on (`RunConfig.target`). Consumed by
* `ide-run`, `ide-remote` and the run feature.
*/
import { usePluginRunTargets } from "@/platform/pluginRunTargets";
@@ -317,14 +317,74 @@ const KIND_OPTIONS: SelectOption[] = [
{ value: "docker", label: "Docker" },
{ value: "compose", label: "Docker Compose" },
];
const WSL_OPTION: SelectOption = { value: "wsl", label: "WSL" };
/** Image or service of a container target, for the list. */
/** Installed WSL distributions; empty off Windows or without WSL, which hides the WSL type. */
function useWslDistros(): string[] {
const [distros, setDistros] = useState<string[]>([]);
useEffect(() => {
if (!isTauri()) return;
let live = true;
void call(commands.wslDistros())
.then((found) => live && setDistros(found))
.catch(() => {});
return () => {
live = false;
};
}, []);
return distros;
}
/** Image, service or distribution of a target that isn't SSH, for the list. */
function containerSummary(t: RunTargetValid): string {
if (t.kind === "docker") return t.image;
if (t.kind === "compose") return t.service ? `compose:${t.service}` : "compose";
if (t.kind === "wsl") return t.distro ? `wsl:${t.distro}` : "wsl";
return "";
}
function WslFields({
target,
distros,
update,
}: {
target: RunTargetValid;
distros: string[];
update: (p: Partial<RunTargetValid>) => void;
}) {
const id = useId();
const options: SelectOption[] = distros.map((d) => ({ value: d, label: d, verbatim: true }));
if (target.distro && !distros.includes(target.distro))
options.push({ value: target.distro, label: tx`${target.distro} (missing)` });
return (
<>
<Row label="WSL distribution" className={styles.alignedRow}>
<Select
value={target.distro}
options={options}
onChange={(distro) => update({ distro })}
aria-label="WSL distribution"
/>
</Row>
<Row
label="Project folder in WSL"
htmlFor={id}
className={styles.alignedRow}
hint="Empty: the project's path under /mnt, such as /mnt/c/work/app."
>
<Input
id={id}
mono
className={styles.wide}
value={target.projectRoot}
placeholder="/mnt/c/…"
onChange={(e) => update({ projectRoot: e.target.value })}
/>
</Row>
</>
);
}
function ContainerFields({ target, update }: { target: RunTargetValid; update: (p: Partial<RunTargetValid>) => void }) {
const projectName = useProject((s) => s.project?.name ?? "project");
const compose = target.kind === "compose";
@@ -411,6 +471,7 @@ export function RunTargetsEditor() {
if (defaultTarget && !allTargets.some((t) => t.id === defaultTarget))
defaultOptions.push({ value: defaultTarget, label: tx`${defaultTarget} (missing)` });
const sshConfigs = useSshConfigs();
const distros = useWslDistros();
const [selected, setSelected] = useState<string | null>(targets[0]?.id ?? null);
const current = targets.find((t) => t.id === selected) ?? null;
const index = current ? targets.indexOf(current) : -1;
@@ -524,8 +585,14 @@ export function RunTargetsEditor() {
<Row label="Type" className={styles.alignedRow}>
<Select
value={current.kind}
options={KIND_OPTIONS}
onChange={(kind) => update({ kind: kind as RunTargetKindValid })}
options={distros.length || current.kind === "wsl" ? [...KIND_OPTIONS, WSL_OPTION] : KIND_OPTIONS}
onChange={(kind) =>
update(
kind === "wsl" && !current.distro
? { kind, distro: distros[0] ?? "" }
: { kind: kind as RunTargetKindValid },
)
}
aria-label="Type"
/>
</Row>
@@ -541,6 +608,8 @@ export function RunTargetsEditor() {
label="Upload changed project files before each run"
/>
</>
) : current.kind === "wsl" ? (
<WslFields target={current} distros={distros} update={update} />
) : (
<ContainerFields target={current} update={update} />
)}
@@ -575,6 +644,16 @@ export function RunTargetsEditor() {
"Docker connections come from the Services tool window. Each run gets a new container, removed when it ends. Python and Node.js configurations can be debugged there; coverage and profiling stay on this machine."
}
</T>
{distros.length > 0 && (
<>
{" "}
<T>
{
"WSL targets run in the chosen distribution through wsl.exe, with the project read through /mnt. Debugging, coverage and profiling stay on this machine."
}
</T>
</>
)}
</div>
</div>
);
+13 -11
Переглянути файл
@@ -1,4 +1,5 @@
import { addContributedSnippets, SettingsPageFocusContext } from "@/workbench/contributions";
import { useMemo } from "react";
import { addContributedSnippets, SettingsPageFocusContext, type SettingsPageFocus } from "@/workbench/contributions";
import { describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { LiveTemplatesPage, groupTemplates } from "../settings/LiveTemplatesPage";
@@ -14,6 +15,15 @@ import { reloadFileTemplates, resetInclude, saveInclude, setTemplateScheme, useF
import { useProject } from "@/platform/project";
import type { ProjectInfo } from "@/platform/ipc";
function FocusedPage({ focus, consume }: SettingsPageFocus) {
const value = useMemo<SettingsPageFocus>(() => ({ focus, consume }), [focus, consume]);
return (
<SettingsPageFocusContext.Provider value={value}>
<LiveTemplatesPage />
</SettingsPageFocusContext.Provider>
);
}
describe("settings pages", () => {
it("groups and filters live templates", () => {
const groups = groupTemplates(BUILTIN_TEMPLATES, "psvm");
@@ -87,11 +97,7 @@ describe("settings pages", () => {
contexts: ["typescript"],
});
const consume = vi.fn();
const page = (focus: string | null) => (
<SettingsPageFocusContext.Provider value={{ focus, consume }}>
<LiveTemplatesPage />
</SettingsPageFocusContext.Provider>
);
const page = (focus: string | null) => <FocusedPage focus={focus} consume={consume} />;
const view = render(page(null));
try {
fireEvent.change(screen.getByLabelText("Filter templates"), { target: { value: "psvm" } });
@@ -109,11 +115,7 @@ describe("settings pages", () => {
it("shows nothing selected when opened on a template that is gone", async () => {
const consume = vi.fn();
const view = render(
<SettingsPageFocusContext.Provider value={{ focus: "user.missing", consume }}>
<LiveTemplatesPage />
</SettingsPageFocusContext.Provider>,
);
const view = render(<FocusedPage focus="user.missing" consume={consume} />);
await waitFor(() => expect(consume).toHaveBeenCalledOnce());
expect(screen.queryByRole("option", { selected: true })).toBeNull();
expect(screen.getByText("Select a template to edit it")).toBeInTheDocument();
+2 -1
Переглянути файл
@@ -79,11 +79,12 @@ function buildRows(
}
const isSection = (r: Row) => r.type === "section";
const NO_REPOS: readonly string[] = [];
export function BranchFilterPopup({
anchor,
branches,
repos = [],
repos = NO_REPOS,
selected,
onSelect,
onSelectMany,
+3 -1
Переглянути файл
@@ -37,6 +37,8 @@ import { KIND_COLOR, KIND_LABEL, baseName, fileCount } from "./model";
import { ownedStagedDocument } from "./stagedDocument";
import styles from "./CombinedDiff.module.css";
const NO_CHANGES = <T>No changes</T>;
type Kind = "added" | "deleted" | "modified";
/** What happened to the file: one side absent means added or deleted. */
@@ -228,7 +230,7 @@ export function CombinedDiffView({
tabKey,
reveal,
handle,
empty = <T>No changes</T>,
empty = NO_CHANGES,
onSeparateTabs,
toolbarStart,
toolbarEnd,
+2
Переглянути файл
@@ -16,6 +16,7 @@ export function activateDiffViewer(): () => void {
const single = registerEditorKind({
kind: DIFF_KIND,
standalone: true,
reusesPreviewTab: true,
// Switching back shows the diff where it was left (scroll, caret, expanded lines),
// without reloading the revisions.
keepAlive: true,
@@ -28,6 +29,7 @@ export function activateDiffViewer(): () => void {
const combined = registerEditorKind({
kind: COMBINED_DIFF_KIND,
standalone: true,
reusesPreviewTab: true,
keepAlive: true,
component: lazyComponent(() => import("./CombinedDiff").then((m) => m.CombinedDiffTab)),
title: (input) => (input.data as CombinedDiffData).title ?? tx("Combined Changes Diff"),
+1
Переглянути файл
@@ -426,6 +426,7 @@ export function activate(): () => void {
registerEditorKind({
kind: "git-merge-diff",
standalone: true,
reusesPreviewTab: true,
component: lazyComponent(() => import("./GitMergeDiff").then((m) => m.GitMergeDiff)),
title: (input) => (input.data as { path: string }).path,
icon: () => "diff",
+17 -1
Переглянути файл
@@ -4815,6 +4815,11 @@
"xcodebuild doesn't compile it until it's in a target of {name}. Add it in Xcode or convert the group to a folder.": "xcodebuild doesn't compile it until it's in a target of {name}. Add it in Xcode or convert the group to a folder.",
"xcodebuild doesn't compile {files} until they're in a target of {name}. Add them in Xcode or convert the group to a folder.": "xcodebuild doesn't compile {files} until they're in a target of {name}. Add them in Xcode or convert the group to a folder.",
"Open in Xcode": "Open in Xcode",
"Coverage and profiling are not supported on WSL": "Coverage and profiling are not supported on WSL",
"'{name}' runs in WSL on {where}. Run it, or choose “Local machine” under “Run on”.": "'{name}' runs in WSL on {where}. Run it, or choose “Local machine” under “Run on”.",
"Project folder in WSL": "Project folder in WSL",
"Empty: the project's path under /mnt, such as /mnt/c/work/app.": "Empty: the project's path under /mnt, such as /mnt/c/work/app.",
"WSL targets run in the chosen distribution through wsl.exe, with the project read through /mnt. Debugging, coverage and profiling stay on this machine.": "WSL targets run in the chosen distribution through wsl.exe, with the project read through /mnt. Debugging, coverage and profiling stay on this machine.",
"Import Recent Projects from JetBrains IDE": "Import Recent Projects from JetBrains IDE",
"Import Recent Projects from JetBrains IDE…": "Import Recent Projects from JetBrains IDE…",
"Recent projects imported": "Recent projects imported",
@@ -4832,5 +4837,16 @@
"A library with this name already exists.": "A library with this name already exists.",
"GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, {effectiveAccount} may not have access. Check the remote URL or choose an account with access in GitHub settings, then retry.": "GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, {effectiveAccount} may not have access. Check the remote URL or choose an account with access in GitHub settings, then retry.",
"GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, check the remote URL or choose an account with access in GitHub settings, then retry.": "GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, check the remote URL or choose an account with access in GitHub settings, then retry.",
"GitHub Settings": "GitHub Settings"
"GitHub Settings": "GitHub Settings",
"Distribution:": "Distribution:",
"Python interpreter:": "Python interpreter:",
"Looking for Python…": "Looking for Python…",
"No Python found in this distribution. Install python3 there, or type the path of one.": "No Python found in this distribution. Install python3 there, or type the path of one.",
"Adds a WSL run target with this Python and makes it the project interpreter. The language server reads its libraries in place in the distribution; install packages there, in WSL.": "Adds a WSL run target with this Python and makes it the project interpreter. The language server reads its libraries in place in the distribution; install packages there, in WSL.",
"Reading the libraries in WSL…": "Reading the libraries in WSL…",
"The WSL Python's libraries have not been read yet.": "The WSL Python's libraries have not been read yet.",
"Packages come from the Python in WSL and are read-only here. To change them, install them there (for example with pip in the distribution), then reload the list.": "Packages come from the Python in WSL and are read-only here. To change them, install them there (for example with pip in the distribution), then reload the list.",
"{python} in WSL {distro}": "{python} in WSL {distro}",
"Type the absolute path of the Python in WSL, such as /home/me/.venv/bin/python.": "Type the absolute path of the Python in WSL, such as /home/me/.venv/bin/python.",
"WSL distributions could not be listed: {e}": "WSL distributions could not be listed: {e}"
}
+17 -1
Переглянути файл
@@ -11494,6 +11494,11 @@
"xcodebuild doesn't compile it until it's in a target of {name}. Add it in Xcode or convert the group to a folder.": "在加入 {name} 的某个 target 之前,xcodebuild 不会编译它。请在 Xcode 中添加,或把该组转换为文件夹。",
"xcodebuild doesn't compile {files} until they're in a target of {name}. Add them in Xcode or convert the group to a folder.": "在加入 {name} 的某个 target 之前,xcodebuild 不会编译 {files}。请在 Xcode 中添加,或把该组转换为文件夹。",
"Open in Xcode": "在 Xcode 中打开",
"Coverage and profiling are not supported on WSL": "WSL 中不支持覆盖率和性能分析",
"'{name}' runs in WSL on {where}. Run it, or choose “Local machine” under “Run on”.": "'{name}' 在 {where} 的 WSL 中运行。请直接运行,或在“运行于”中选择“本地计算机”。",
"Project folder in WSL": "WSL 中的项目文件夹",
"Empty: the project's path under /mnt, such as /mnt/c/work/app.": "留空:使用项目在 /mnt 下的路径,例如 /mnt/c/work/app。",
"WSL targets run in the chosen distribution through wsl.exe, with the project read through /mnt. Debugging, coverage and profiling stay on this machine.": "WSL 目标通过 wsl.exe 在所选发行版中运行,项目通过 /mnt 读取。调试、覆盖率和性能分析仍在本机进行。",
"Plugin navigation covers {count} of {total} files in {project}; exclude folders to narrow it": "插件导航仅覆盖 {project} 中 {total} 个文件里的 {count} 个;可排除文件夹以缩小范围",
"Source Definition": "源定义",
"Go to Source Definition": "转到源定义",
@@ -11529,5 +11534,16 @@
"A library with this name already exists.": "已存在同名的库。",
"GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, {effectiveAccount} may not have access. Check the remote URL or choose an account with access in GitHub settings, then retry.": "GitHub CLI 登录了多个账号。如果 Git 通过 gh 获取 HTTPS 凭据,{effectiveAccount} 可能没有访问权限。请检查远程 URL,或在 GitHub 设置中选择有权限的账号后重试。",
"GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, check the remote URL or choose an account with access in GitHub settings, then retry.": "GitHub CLI 登录了多个账号。如果 Git 通过 gh 获取 HTTPS 凭据,请检查远程 URL,或在 GitHub 设置中选择有权限的账号后重试。",
"GitHub Settings": "GitHub 设置"
"GitHub Settings": "GitHub 设置",
"Distribution:": "发行版:",
"Python interpreter:": "Python 解释器:",
"Looking for Python…": "正在查找 Python…",
"No Python found in this distribution. Install python3 there, or type the path of one.": "此发行版中未找到 Python。请在其中安装 python3,或输入 Python 的路径。",
"Adds a WSL run target with this Python and makes it the project interpreter. The language server reads its libraries in place in the distribution; install packages there, in WSL.": "添加使用此 Python 的 WSL 运行目标,并将其设为项目解释器。语言服务器直接读取发行版中的库;请在 WSL 中安装软件包。",
"Reading the libraries in WSL…": "正在读取 WSL 中的库…",
"The WSL Python's libraries have not been read yet.": "尚未读取 WSL Python 的库。",
"Packages come from the Python in WSL and are read-only here. To change them, install them there (for example with pip in the distribution), then reload the list.": "软件包来自 WSL 中的 Python,此处只读。如需更改,请在 WSL 中安装(例如在发行版中使用 pip),然后重新加载列表。",
"{python} in WSL {distro}": "WSL {distro} 中的 {python}",
"Type the absolute path of the Python in WSL, such as /home/me/.venv/bin/python.": "请输入 WSL 中 Python 的绝对路径,例如 /home/me/.venv/bin/python。",
"WSL distributions could not be listed: {e}": "无法列出 WSL 发行版:{e}"
}
+6 -2
Переглянути файл
@@ -61,7 +61,7 @@ export interface DeploymentSettingsValid {
exclude: string[];
}
export type RunTargetKindValid = "ssh" | "docker" | "compose";
export type RunTargetKindValid = "ssh" | "docker" | "compose" | "wsl";
export interface RunTargetValid {
kind: RunTargetKindValid;
@@ -82,6 +82,8 @@ export interface RunTargetValid {
ports: string[];
runOptions: string;
imageUser: boolean;
/** WSL distribution, as `wsl.exe -l -q` lists it. */
distro: string;
}
export interface RemoteSettings {
@@ -141,6 +143,7 @@ export const DEFAULT_RUN_TARGET: RunTargetValid = {
ports: [],
runOptions: "",
imageUser: false,
distro: "",
};
export const DEFAULT_REMOTE: RemoteSettings = {
@@ -235,7 +238,7 @@ export function validateDeployment(raw: unknown): DeploymentSettingsValid {
export function validateRunTargets(raw: unknown): RunTargetValid[] {
const d = DEFAULT_RUN_TARGET;
return withIds(raw, "target", (o) => ({
kind: oneOf(o.kind, ["ssh", "docker", "compose"] as const, d.kind),
kind: oneOf(o.kind, ["ssh", "docker", "compose", "wsl"] as const, d.kind),
id: text(o.id, ""),
name: text(o.name, ""),
sshConfig: text(o.sshConfig, ""),
@@ -252,6 +255,7 @@ export function validateRunTargets(raw: unknown): RunTargetValid[] {
ports: strings(o.ports, []),
runOptions: text(o.runOptions, ""),
imageUser: bool(o.imageUser, d.imageUser),
distro: text(o.distro, ""),
}));
}
+5
Переглянути файл
@@ -169,6 +169,11 @@ export interface EditorKindContribution {
* `splitInput`, or moves the tab instead.
*/
singleton?: boolean;
/**
* A preview tab its opener asks for is granted even with Opening Policy › Enable preview tab
* off, so stepping through a change set's diffs reuses one tab. Pinned or kept tabs stay.
*/
reusesPreviewTab?: boolean;
/** Fresh input opened when splitting a `singleton` tab (e.g. a new shell in the same cwd). */
splitInput?(input: EditorInput): EditorInput | Promise<EditorInput | null> | null;
/** Last tab showing this input closed (including split tabs and tab-limit eviction). */