дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-30 22:32:35 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
1634cd8e84 | ||
|
|
81c95b2ab7 | ||
|
|
f7b5cc388c | ||
|
|
277d0e9d1e | ||
|
|
d6adb7aa40 | ||
|
|
6e5e482410 | ||
|
|
cc02c2fe40 | ||
|
|
74a3f6470a | ||
|
|
4c8c078666 | ||
|
|
e672b14d52 | ||
|
|
c0300f8959 | ||
|
|
11cf9864a1 |
No files matched your search
@@ -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"
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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).
|
||||
|
||||
@@ -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"] {
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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)? {
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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);
|
||||
@@ -760,6 +760,11 @@ impl PluginHost {
|
||||
.filter(|(_, p)| p.dev_root.as_deref() == Some(root))
|
||||
.map(|(id, _)| id.clone())
|
||||
.collect();
|
||||
// Nothing to unload, nothing to announce: `CommandsChanged` makes every window list the
|
||||
// plugins again, and listing restricts an untrusted project again, which looped while idle.
|
||||
if ids.is_empty() {
|
||||
return;
|
||||
}
|
||||
for id in ids {
|
||||
self.unload(&id);
|
||||
}
|
||||
|
||||
@@ -565,6 +565,21 @@ impl Host {
|
||||
.collect();
|
||||
matches!(rest.as_slice(), [first, ..] if first == "worktrees" && rest.len() <= 2)
|
||||
});
|
||||
// `git worktree add` writes the worktree's gitfile before its gitdir's
|
||||
// `HEAD`: a rescan in between finds no repository there yet, so that `HEAD`
|
||||
// rescans too while its worktree is unknown and one a rescan would find.
|
||||
git_dirs |= batch.vcs.iter().any(|p| {
|
||||
let Some(gitdir) = p.parent().filter(|_| p.ends_with("HEAD")) else { return false };
|
||||
if !gitdir.parent().is_some_and(|d| d.ends_with(".git/worktrees")) {
|
||||
return false;
|
||||
}
|
||||
// `gitdir` may be relative to itself (`git worktree add --relative-paths`).
|
||||
let worktree = std::fs::read_to_string(gitdir.join("gitdir"))
|
||||
.and_then(|gitfile| dunce::canonicalize(gitdir.join(gitfile.trim())));
|
||||
worktree.ok().as_deref().and_then(Path::parent).is_some_and(|dir| {
|
||||
!known.iter().any(|r| r == dir) && repository_searched(&root, dir, &settings.effective())
|
||||
})
|
||||
});
|
||||
// A repository folder moved or restored into the project: no `.git` event is
|
||||
// written inside it before the watcher sees the new directory, its creation is
|
||||
// the signal. A `git clone` / `git init` inside the project already arrives
|
||||
@@ -1186,18 +1201,34 @@ fn detect_repositories(
|
||||
build_cache: &Path,
|
||||
trusted: bool,
|
||||
) -> IdeResult<Repos> {
|
||||
let mut roots = vec![root.to_path_buf()];
|
||||
roots.extend(content_roots(settings, root, build_cache, trusted));
|
||||
Repos::discover_roots(&roots, &repository_scan_skips(settings))
|
||||
}
|
||||
|
||||
/// Folders the search for nested repositories leaves out, besides hidden and dependency ones.
|
||||
fn repository_scan_skips(settings: &ide_core::settings::Settings) -> impl Fn(&Path) -> bool {
|
||||
let ignored = settings.ignored_names();
|
||||
let skip = |p: &Path| {
|
||||
move |p: &Path| {
|
||||
p.file_name().is_some_and(|n| {
|
||||
let name = n.to_string_lossy();
|
||||
ignored.is_ignored_name(&name)
|
||||
|| (ide_workspace::unity::GENERATED_DIRS.contains(&name.as_ref())
|
||||
&& p.parent().is_some_and(ide_workspace::unity::is_project))
|
||||
})
|
||||
};
|
||||
let mut roots = vec![root.to_path_buf()];
|
||||
roots.extend(content_roots(settings, root, build_cache, trusted));
|
||||
Repos::discover_roots(&roots, &skip)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a scan of the project at `root` would look for a repository at `dir` and keep it.
|
||||
fn repository_searched(root: &Path, dir: &Path, settings: &ide_core::settings::Settings) -> bool {
|
||||
settings.vcs.git.enabled
|
||||
&& !settings
|
||||
.vcs
|
||||
.mappings
|
||||
.excluded
|
||||
.iter()
|
||||
.any(|p| dunce::canonicalize(VcsMappings::resolve(root, p)).is_ok_and(|e| e == dir))
|
||||
&& Repos::searched(root, dir, &repository_scan_skips(settings))
|
||||
}
|
||||
|
||||
impl Project {
|
||||
|
||||
@@ -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:?}");
|
||||
|
||||
@@ -8170,3 +8170,20 @@ fn contributes_skills_needs_api_1_15_and_warns_without_failing_plugin_on_bad_ent
|
||||
assert_eq!(dirs.len(), 1);
|
||||
assert!(dirs[0].ends_with("skills/good-skill"), "{dirs:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restricting_a_project_without_its_plugins_announces_nothing() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let events: Events = Arc::default();
|
||||
let sink = {
|
||||
let events = events.clone();
|
||||
move |client: Option<&str>, e: PluginEvent| events.lock().push((client.map(str::to_owned), e))
|
||||
};
|
||||
let host = PluginHost::new(tmp.path().join("plugins"), Arc::new(sink), Limits::default()).unwrap();
|
||||
host.load_all();
|
||||
events.lock().clear();
|
||||
// A restricted window lists the plugins, which restricts its project again each time.
|
||||
host.restrict_project(tmp.path());
|
||||
host.restrict_project(tmp.path());
|
||||
assert!(!events.lock().iter().any(|(_, e)| matches!(e, PluginEvent::CommandsChanged)));
|
||||
}
|
||||
@@ -28,6 +28,10 @@ struct Fixture {
|
||||
|
||||
impl Fixture {
|
||||
async fn new() -> Self {
|
||||
Self::with_sink(Arc::new(ide_core::NullSink)).await
|
||||
}
|
||||
|
||||
async fn with_sink(sink: ide_core::SharedSink) -> Self {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
@@ -40,7 +44,8 @@ impl Fixture {
|
||||
std::fs::write(root.join("file.txt"), "original\n").unwrap();
|
||||
git(&root, &["add", "."]);
|
||||
git(&root, &["commit", "-m", "original"]);
|
||||
let host = Host::new(common::host_config(&base));
|
||||
let host =
|
||||
Host::new(ide_host::HostConfig { sink_for: Box::new(move |_| sink.clone()), ..common::host_config(&base) });
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
let project = host.open_project("main", &root).unwrap();
|
||||
wait_for_repos(&project, 1).await;
|
||||
@@ -278,6 +283,50 @@ async fn watcher_picks_up_a_worktree_added_below_the_project() {
|
||||
assert!(roots.contains(&linked), "watcher did not discover the worktree added below the project: {roots:?}");
|
||||
}
|
||||
|
||||
/// `git worktree add` writes the worktree's gitfile before its gitdir's `commondir` and `HEAD`; a
|
||||
/// slow git lets the watcher rescan in between and find no repository there yet.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn watcher_picks_up_a_worktree_whose_head_is_written_after_a_rescan() {
|
||||
let changes = Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||
let counter = changes.clone();
|
||||
let sink: ide_core::SharedSink = Arc::new(move |event: ide_core::IdeEvent| {
|
||||
if matches!(event, ide_core::IdeEvent::VcsChanged { .. }) {
|
||||
counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
}
|
||||
});
|
||||
let f = Fixture::with_sink(sink).await;
|
||||
// The watcher reports a batch that rescans only once the rescan is done.
|
||||
let next_change = || {
|
||||
let (changes, seen) = (changes.clone(), changes.load(std::sync::atomic::Ordering::SeqCst));
|
||||
async move {
|
||||
for _ in 0..200 {
|
||||
if changes.load(std::sync::atomic::Ordering::SeqCst) > seen {
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
panic!("the watcher reported no change");
|
||||
}
|
||||
};
|
||||
let linked = f.root.join("watched");
|
||||
let gitdir = f.root.join(".git/worktrees/watched");
|
||||
let registered = next_change();
|
||||
std::fs::create_dir_all(&gitdir).unwrap();
|
||||
std::fs::write(gitdir.join("gitdir"), format!("{}\n", linked.join(".git").display())).unwrap();
|
||||
registered.await;
|
||||
let rescanned = next_change();
|
||||
std::fs::create_dir_all(&linked).unwrap();
|
||||
std::fs::write(linked.join(".git"), format!("gitdir: {}\n", gitdir.display())).unwrap();
|
||||
rescanned.await;
|
||||
assert_eq!(f.project.repos().all().len(), 1, "a gitfile without its gitdir's HEAD is no repository yet");
|
||||
std::fs::write(gitdir.join("commondir"), "../..\n").unwrap();
|
||||
// As git does: through a lock file.
|
||||
std::fs::write(gitdir.join("HEAD.lock"), "ref: refs/heads/main\n").unwrap();
|
||||
std::fs::rename(gitdir.join("HEAD.lock"), gitdir.join("HEAD")).unwrap();
|
||||
wait_for_repos(&f.project, 2).await;
|
||||
assert!(f.project.repos().roots().contains(&linked));
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
async fn open(&self, root: &std::path::Path) {
|
||||
self.host.trust.decide(root, true, false).unwrap();
|
||||
|
||||
@@ -227,6 +227,10 @@ pub struct LanguageServerConfig {
|
||||
/// it parses a document.
|
||||
#[serde(default)]
|
||||
pub resync_on_configuration: bool,
|
||||
/// Server-created work-done tokens to ignore, including slash-delimited suffixes.
|
||||
/// Client-created request tokens are handled independently.
|
||||
#[serde(default)]
|
||||
pub ignored_progress_token_prefixes: Vec<String>,
|
||||
/// Set by the settings hook: what the user sees as the server when another program serves
|
||||
/// in its place (TypeScript 7's own `tsc --lsp` for vtsls).
|
||||
#[serde(skip)]
|
||||
|
||||
@@ -909,7 +909,10 @@ mod tests {
|
||||
let cfg = reg.get(&LanguageId::new("php")).unwrap();
|
||||
let names: Vec<&str> = cfg.language_servers.iter().map(|s| s.name.as_str()).collect();
|
||||
// After the fallback: hover, rename and symbols stay with Intelephense.
|
||||
assert_eq!(names, ["intelephense", "phpactor", "phoxite", "devsense-php-ls", "laravel-lsp"]);
|
||||
assert_eq!(names, ["intelephense", "phpantom", "phpactor", "phoxite", "devsense-php-ls", "laravel-lsp"]);
|
||||
let phpantom = &cfg.language_servers[1];
|
||||
assert!(phpantom.fallback && phpantom.args.is_empty());
|
||||
assert_eq!(phpantom.command, "phpantom_lsp");
|
||||
// Phoxite answers the Laravel strings itself.
|
||||
let phoxite = cfg.language_servers.iter().find(|s| s.name == "phoxite").unwrap();
|
||||
assert!(phoxite.fallback && phoxite.replaces == ["laravel-lsp"]);
|
||||
|
||||
@@ -73,6 +73,7 @@ fn server_config() -> LanguageServerConfig {
|
||||
tsserver_project: false,
|
||||
tsserver_project_extras: Default::default(),
|
||||
resync_on_configuration: false,
|
||||
ignored_progress_token_prefixes: vec![],
|
||||
display_name: None,
|
||||
pinned: None,
|
||||
}
|
||||
|
||||
@@ -151,6 +151,23 @@ impl ClientHandler {
|
||||
}
|
||||
|
||||
fn progress(&self, mgr: &LspManager, params: Value) {
|
||||
if let Some(token) = params["token"].as_str() {
|
||||
if let Some(id) = token.strip_prefix(crate::server::REQUEST_PROGRESS_PREFIX) {
|
||||
if let (Ok(id), Ok(update)) = (id.parse::<u32>(), serde_json::from_value(params["value"].clone())) {
|
||||
self.server.request_progress(mgr.sink(), TaskId(id), update);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if self
|
||||
.server
|
||||
.config
|
||||
.ignored_progress_token_prefixes
|
||||
.iter()
|
||||
.any(|prefix| token.strip_prefix(prefix).is_some_and(|rest| rest.is_empty() || rest.starts_with('/')))
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
let token = progress_key(¶ms["token"]);
|
||||
let value = ¶ms["value"];
|
||||
let kind = value.get("kind").and_then(Value::as_str);
|
||||
|
||||
@@ -1598,10 +1598,20 @@ impl LspManager {
|
||||
cancel: Option<&CancellationToken>,
|
||||
timeout: Duration,
|
||||
) -> IdeResult<R> {
|
||||
let params = serde_json::to_value(params).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
let mut params = serde_json::to_value(params).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
// ImplementationParams accepts an optional client work-done token. Servers
|
||||
// may report on it even when implementationProvider is advertised as `true`.
|
||||
let progress = (method == "textDocument/implementation")
|
||||
.then(|| t.server.track_request_progress(t.run.generation, self.sink(), cancel));
|
||||
let cancel = if let Some(progress) = &progress {
|
||||
params["workDoneToken"] = json!(progress.wire_token());
|
||||
Some(progress.cancel.clone())
|
||||
} else {
|
||||
cancel.cloned()
|
||||
};
|
||||
let stamp = self.injected_request_stamp(¶ms);
|
||||
let fut = async {
|
||||
let mut value = t.run.peer.request::<Value, Value>(method, params, cancel.cloned()).await?;
|
||||
let mut value = t.run.peer.request::<Value, Value>(method, params, cancel).await?;
|
||||
virtual_doc::normalize_uris(&mut value);
|
||||
serde_json::from_value(value).map_err(|e| RpcError::Protocol(format!("{method}: {e}")))
|
||||
};
|
||||
|
||||
@@ -53,10 +53,58 @@ struct State {
|
||||
generation: u64,
|
||||
conn: Conn,
|
||||
restarting: bool,
|
||||
request_progress: HashMap<TaskId, RequestProgressState>,
|
||||
events: VecDeque<IdeEvent>,
|
||||
publishing: bool,
|
||||
}
|
||||
|
||||
pub(crate) const REQUEST_PROGRESS_PREFIX: &str = "openidea/request/";
|
||||
|
||||
struct RequestProgressState {
|
||||
title: Option<String>,
|
||||
message: Option<String>,
|
||||
fraction: Option<f32>,
|
||||
_cancel: ide_core::task::CancelHandle,
|
||||
}
|
||||
|
||||
impl RequestProgressState {
|
||||
fn event(&self, id: TaskId, done: bool) -> Option<IdeEvent> {
|
||||
Some(IdeEvent::Task {
|
||||
id,
|
||||
title: self.title.clone()?,
|
||||
message: self.message.clone(),
|
||||
fraction: self.fraction,
|
||||
done,
|
||||
cancellable: !done,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Progress provided to an LSP request. Dropping the request always retires its token.
|
||||
pub(crate) struct RequestProgress<'a> {
|
||||
id: TaskId,
|
||||
server: &'a Server,
|
||||
sink: &'a SharedSink,
|
||||
pub(crate) cancel: CancellationToken,
|
||||
}
|
||||
|
||||
impl RequestProgress<'_> {
|
||||
pub(crate) fn wire_token(&self) -> String {
|
||||
format!("{REQUEST_PROGRESS_PREFIX}{}", self.id.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for RequestProgress<'_> {
|
||||
fn drop(&mut self) {
|
||||
let mut st = self.server.state.lock();
|
||||
if let Some(progress) = st.request_progress.remove(&self.id) {
|
||||
st.events.extend(progress.event(self.id, true));
|
||||
}
|
||||
drop(st);
|
||||
self.server.publish(self.sink);
|
||||
}
|
||||
}
|
||||
|
||||
/// A file opened on the server by the client itself (not by the user) for the
|
||||
/// duration of a request, e.g. to widen a references search.
|
||||
struct Transient {
|
||||
@@ -172,6 +220,7 @@ impl Server {
|
||||
generation: 0,
|
||||
conn: Conn::Idle,
|
||||
restarting: false,
|
||||
request_progress: HashMap::new(),
|
||||
events: VecDeque::new(),
|
||||
publishing: false,
|
||||
}),
|
||||
@@ -552,6 +601,9 @@ impl Server {
|
||||
|
||||
fn queue_cleanup(&self, st: &mut State) {
|
||||
*self.initializing.lock() = None;
|
||||
for (id, progress) in st.request_progress.drain() {
|
||||
st.events.extend(progress.event(id, true));
|
||||
}
|
||||
for (id, title) in self.take_progress() {
|
||||
st.events.push_back(IdeEvent::Task {
|
||||
id,
|
||||
@@ -572,6 +624,61 @@ impl Server {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn track_request_progress<'a>(
|
||||
&'a self,
|
||||
generation: u64,
|
||||
sink: &'a SharedSink,
|
||||
parent_cancel: Option<&CancellationToken>,
|
||||
) -> RequestProgress<'a> {
|
||||
let id = TaskId::next();
|
||||
let cancel = parent_cancel.map(CancellationToken::child_token).unwrap_or_default();
|
||||
let mut st = self.state.lock();
|
||||
if st.generation == generation && matches!(st.conn, Conn::Ready(_)) {
|
||||
let token = cancel.clone();
|
||||
st.request_progress.insert(
|
||||
id,
|
||||
RequestProgressState {
|
||||
title: None,
|
||||
message: None,
|
||||
fraction: None,
|
||||
_cancel: ide_core::task::on_cancel(id, move || token.cancel()),
|
||||
},
|
||||
);
|
||||
}
|
||||
RequestProgress { id, server: self, sink, cancel }
|
||||
}
|
||||
|
||||
pub(crate) fn request_progress(&self, sink: &SharedSink, id: TaskId, update: lsp::WorkDoneProgress) {
|
||||
let mut st = self.state.lock();
|
||||
let Some(progress) = st.request_progress.get_mut(&id) else { return };
|
||||
let fraction = |p: u32| p.min(100) as f32 / 100.0;
|
||||
let event = match update {
|
||||
lsp::WorkDoneProgress::Begin(begin) => {
|
||||
progress.title = Some(begin.title);
|
||||
progress.message = begin.message;
|
||||
progress.fraction = begin.percentage.map(fraction);
|
||||
progress.event(id, false)
|
||||
}
|
||||
lsp::WorkDoneProgress::Report(report) => {
|
||||
progress.message = report.message.or_else(|| progress.message.take());
|
||||
progress.fraction = report.percentage.map(fraction).or(progress.fraction);
|
||||
progress.event(id, false)
|
||||
}
|
||||
lsp::WorkDoneProgress::End(end) => {
|
||||
progress.message = end.message.or_else(|| progress.message.take());
|
||||
progress.fraction = Some(1.0);
|
||||
let event = progress.event(id, true);
|
||||
st.request_progress.remove(&id);
|
||||
event
|
||||
}
|
||||
};
|
||||
// Queue under the state lock so a reply or cancellation can't publish `done`
|
||||
// before a concurrent progress update and leave a stale row.
|
||||
st.events.extend(event);
|
||||
drop(st);
|
||||
self.publish(sink);
|
||||
}
|
||||
|
||||
pub fn emit(&self, sink: &SharedSink, event: IdeEvent) {
|
||||
self.state.lock().events.push_back(event);
|
||||
self.publish(sink);
|
||||
|
||||
@@ -277,6 +277,7 @@ fn server_cfg(name: &str) -> LanguageServerConfig {
|
||||
tsserver_project: false,
|
||||
tsserver_project_extras: Default::default(),
|
||||
resync_on_configuration: false,
|
||||
ignored_progress_token_prefixes: vec![],
|
||||
display_name: None,
|
||||
pinned: None,
|
||||
}
|
||||
@@ -2225,6 +2226,54 @@ async fn a_progress_token_begun_again_ends_the_task_it_replaces() {
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn toml_progress_quirk_ignores_server_tokens_left_open_after_cancel() {
|
||||
let registry = LanguageRegistry::load(None).unwrap();
|
||||
let php = registry.get(&LanguageId::new("php")).unwrap();
|
||||
let quirk = &php.language_servers.iter().find(|s| s.name == "phpantom").unwrap().ignored_progress_token_prefixes;
|
||||
let h = harness_configured("php", "php", &[("mock", incremental_caps())], |cfg| {
|
||||
cfg.ignored_progress_token_prefixes = quirk.clone();
|
||||
});
|
||||
let (doc, path) = h.open("a.php", "<?php target();");
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
let server = h.launcher.state("mock");
|
||||
let peer = server.peer();
|
||||
let progress = |token, kind, title| {
|
||||
peer.notify("$/progress", json!({ "token": token, "value": { "kind": kind, "title": title } })).unwrap();
|
||||
};
|
||||
let method = "textDocument/references";
|
||||
let search = || h.mgr.references_streaming(doc, Pos::new(0, 7), true, false, true, Default::default(), None);
|
||||
|
||||
progress("find_references/1", "begin", "Find References");
|
||||
progress("find_references", "begin", "Find References");
|
||||
progress("goto_implementation/1", "begin", "Go to Implementation");
|
||||
progress("find_references_index/1", "begin", "Indexing");
|
||||
h.wait_status("mock", ServerStatus::Busy).await;
|
||||
server.errors.lock().insert(method.into(), (-32800, "Canceled".into()));
|
||||
assert_eq!(search().await.unwrap_err().kind, ide_core::error::ErrorKind::Cancelled);
|
||||
|
||||
server.errors.lock().remove(method);
|
||||
server.respond(
|
||||
method,
|
||||
json!([{
|
||||
"uri": uri_of(&path),
|
||||
"range": { "start": { "line": 0, "character": 6 }, "end": { "line": 0, "character": 12 } }
|
||||
}]),
|
||||
);
|
||||
progress("find_references/2", "begin", "Find References");
|
||||
assert_eq!(search().await.unwrap().locations.len(), 1);
|
||||
progress("find_references/2", "end", "Find References");
|
||||
progress("find_references_index/1", "end", "Indexing");
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
|
||||
let events = h.events.lock();
|
||||
assert!(!events.iter().any(
|
||||
|e| matches!(e, IdeEvent::Task { title, .. } if title == "Find References" || title == "Go to Implementation")
|
||||
));
|
||||
assert!(events.iter().any(|e| matches!(e, IdeEvent::Task { title, done: false, .. } if title == "Indexing")));
|
||||
assert!(events.iter().any(|e| matches!(e, IdeEvent::Task { title, done: true, .. } if title == "Indexing")));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn replacing_progress_keeps_cancellation_reports_and_indexing_on_the_new_task() {
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
@@ -4239,6 +4288,118 @@ async fn implementations_per_position() {
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn implementation_progress_ends_on_cancel_without_server_end() {
|
||||
implementation_progress_ends_with_request(false).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn implementation_progress_ends_on_timeout_without_server_end() {
|
||||
implementation_progress_ends_with_request(true).await;
|
||||
}
|
||||
|
||||
async fn implementation_progress_ends_with_request(timeout: bool) {
|
||||
let caps = json!({ "textDocumentSync": 1, "implementationProvider": true });
|
||||
let h = harness_for("php", "php", &[("mock", caps)], &[]);
|
||||
let (doc, path) = h.open("a.php", "<?php\ninterface A {}\nclass B implements A {}\n");
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
let server = h.launcher.state("mock");
|
||||
let method = "textDocument/implementation";
|
||||
let gate = Arc::new(Gate::default());
|
||||
let uri = uri_of(&path);
|
||||
*server.responder.lock() =
|
||||
Some(Arc::new({
|
||||
let gate = gate.clone();
|
||||
move |server, requested, params| {
|
||||
if requested != method {
|
||||
return None;
|
||||
}
|
||||
let token = ¶ms["workDoneToken"];
|
||||
let peer = server.peer();
|
||||
peer.notify("$/progress", json!({
|
||||
"token": token, "value": { "kind": "begin", "title": "Go to Implementation", "cancellable": false }
|
||||
})).unwrap();
|
||||
if params["position"]["character"] == 10 {
|
||||
peer.notify(
|
||||
"$/progress",
|
||||
json!({
|
||||
"token": token, "value": { "kind": "report", "percentage": 88 }
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
gate.hold();
|
||||
}
|
||||
// The mock answers without sending `end`.
|
||||
Some(json!([{
|
||||
"uri": uri,
|
||||
"range": { "start": { "line": 2, "character": 6 }, "end": { "line": 2, "character": 7 } }
|
||||
}]))
|
||||
}
|
||||
}));
|
||||
|
||||
let mgr = h.mgr.clone();
|
||||
let batch = tokio::spawn(async move {
|
||||
mgr.implementations(doc, &[Pos::new(1, 10), Pos::new(2, 6)], Default::default()).await.unwrap()
|
||||
});
|
||||
let task_events = || {
|
||||
h.events
|
||||
.lock()
|
||||
.iter()
|
||||
.filter_map(|e| match e {
|
||||
IdeEvent::Task { id, title, done, fraction, cancellable, .. } if title == "Go to Implementation" => {
|
||||
Some((*id, *done, *fraction, *cancellable))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
eventually(|| {
|
||||
let events = task_events();
|
||||
gate.entered() && events.iter().any(|e| e.2 == Some(0.88)) && events.iter().any(|(_, done, _, _)| *done)
|
||||
})
|
||||
.await;
|
||||
let scanning = task_events().into_iter().find(|e| e.2 == Some(0.88)).expect("scan reported 88%");
|
||||
let (task, _, _, cancellable) = scanning;
|
||||
assert!(cancellable);
|
||||
assert!(!task_events().iter().any(|(id, done, _, _)| *id == task && *done));
|
||||
let requests = server.requested(method);
|
||||
assert_eq!(requests.len(), 2);
|
||||
assert_ne!(requests[0]["workDoneToken"], requests[1]["workDoneToken"]);
|
||||
|
||||
if timeout {
|
||||
tokio::time::pause();
|
||||
tokio::time::advance(Duration::from_secs(31)).await;
|
||||
tokio::time::resume();
|
||||
} else {
|
||||
assert!(ide_core::task::cancel(task));
|
||||
}
|
||||
let found = batch.await.unwrap();
|
||||
gate.open();
|
||||
eventually(|| !server.notified("$/cancelRequest").is_empty()).await;
|
||||
assert!(found[0].is_empty());
|
||||
assert_eq!(found[1][0].range.start.line, 2);
|
||||
assert!(!ide_core::task::cancel(task));
|
||||
assert_eq!(task_events().iter().filter(|(id, done, _, _)| *id == task && *done).count(), 1);
|
||||
|
||||
// Late progress for either retired token must not bring back its task.
|
||||
let before = task_events();
|
||||
let peer = server.peer();
|
||||
for request in requests {
|
||||
peer.notify(
|
||||
"$/progress",
|
||||
json!({
|
||||
"token": request["workDoneToken"], "value": { "kind": "begin", "title": "Go to Implementation" }
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
peer.notify("$/progress", json!({ "token": "index", "value": { "kind": "begin", "title": "Indexing" } })).unwrap();
|
||||
h.wait_status("mock", ServerStatus::Busy).await;
|
||||
assert_eq!(task_events(), before);
|
||||
peer.notify("$/progress", json!({ "token": "index", "value": { "kind": "end" } })).unwrap();
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn java_implementations_come_from_sources_first() {
|
||||
let caps = json!({
|
||||
|
||||
@@ -428,6 +428,7 @@ async fn missing_binary_is_reported_with_install_hint() {
|
||||
tsserver_project: false,
|
||||
tsserver_project_extras: Default::default(),
|
||||
resync_on_configuration: false,
|
||||
ignored_progress_token_prefixes: vec![],
|
||||
display_name: None,
|
||||
pinned: None,
|
||||
};
|
||||
@@ -721,6 +722,7 @@ async fn typescript_language_server_end_to_end() {
|
||||
tsserver_project: false,
|
||||
tsserver_project_extras: Default::default(),
|
||||
resync_on_configuration: false,
|
||||
ignored_progress_token_prefixes: vec![],
|
||||
display_name: None,
|
||||
pinned: None,
|
||||
};
|
||||
@@ -775,6 +777,7 @@ fn npm_server(tools: &Path, name: &str, bin: &str, init: Option<serde_json::Valu
|
||||
tsserver_project: false,
|
||||
tsserver_project_extras: Default::default(),
|
||||
resync_on_configuration: false,
|
||||
ignored_progress_token_prefixes: vec![],
|
||||
display_name: None,
|
||||
pinned: None,
|
||||
}
|
||||
|
||||
@@ -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)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -1811,6 +1811,7 @@ fn custom_server(name: &str, ls: &LanguageServerSettings) -> LanguageServerConfi
|
||||
tsserver_project: false,
|
||||
tsserver_project_extras: Default::default(),
|
||||
resync_on_configuration: false,
|
||||
ignored_progress_token_prefixes: vec![],
|
||||
display_name: None,
|
||||
pinned: None,
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -46,6 +46,7 @@ pub(crate) fn server(name: &str) -> LanguageServerConfig {
|
||||
tsserver_project: false,
|
||||
tsserver_project_extras: Default::default(),
|
||||
resync_on_configuration: false,
|
||||
ignored_progress_token_prefixes: vec![],
|
||||
display_name: None,
|
||||
pinned: None,
|
||||
}
|
||||
|
||||
@@ -681,6 +681,28 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
homepage: "https://github.com/laravel/lsp",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "phpantom",
|
||||
display: "PHPantom",
|
||||
kind: LanguageServer,
|
||||
commands: &["phpantom_lsp"],
|
||||
method: Method::Release {
|
||||
source: ReleaseSource::GitHub { repo: "PHPantom-dev/phpantom_lsp" },
|
||||
assets: &[
|
||||
rule(Mac, Arm64, "phpantom_lsp-aarch64-apple-darwin.tar.gz"),
|
||||
rule(Mac, X64, "phpantom_lsp-x86_64-apple-darwin.tar.gz"),
|
||||
rule(Linux, Arm64, "phpantom_lsp-aarch64-unknown-linux-gnu.tar.gz"),
|
||||
rule(Linux, X64, "phpantom_lsp-x86_64-unknown-linux-gnu.tar.gz"),
|
||||
rule(Windows, Arm64, "phpantom_lsp-aarch64-pc-windows-msvc.zip"),
|
||||
rule(Windows, X64, "phpantom_lsp-x86_64-pc-windows-msvc.zip"),
|
||||
],
|
||||
locate: &["phpantom_lsp"],
|
||||
},
|
||||
fallback: None,
|
||||
version: ver("phpantom_lsp"),
|
||||
homepage: "https://github.com/PHPantom-dev/phpantom_lsp",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "phoxite",
|
||||
display: "Phoxite",
|
||||
|
||||
@@ -190,6 +190,7 @@ fn everything_missing_on_an_empty_system() {
|
||||
#[test]
|
||||
fn interchangeable_servers_list_their_alternatives() {
|
||||
let env = Env::new();
|
||||
env.script(&env.sys, "curl", "exit 1");
|
||||
let list = env.tools().list(&langs());
|
||||
let python = ["basedpyright", "pyright", "ty", "pyrefly"];
|
||||
for name in python {
|
||||
@@ -203,6 +204,13 @@ fn interchangeable_servers_list_their_alternatives() {
|
||||
for name in ["kotlin-lsp", "kotlin-language-server"] {
|
||||
assert_eq!(find(&list, name).alternatives, ["kotlin-lsp", "kotlin-language-server", "kmp-lsp"]);
|
||||
}
|
||||
let php = ["intelephense", "phpantom", "phpactor", "phoxite", "devsense-php-ls"];
|
||||
for name in php {
|
||||
assert_eq!(find(&list, name).alternatives, php);
|
||||
}
|
||||
let phpantom = find(&list, "phpantom");
|
||||
assert!(phpantom.can_install, "{:?}", phpantom.unavailable_reason);
|
||||
assert!(find(&list, "laravel-lsp").alternatives.is_empty());
|
||||
// A regular server after a fallback starts no group with it.
|
||||
assert!(find(&list, "angular-language-server").alternatives.is_empty());
|
||||
assert!(find(&list, "ruff").alternatives.is_empty());
|
||||
|
||||
@@ -15,6 +15,12 @@ const MAX_DEPTH: usize = 4;
|
||||
/// Folders never searched for nested repositories (dependencies, build output).
|
||||
const SKIPPED: &[&str] = &["node_modules", "target", "build", "dist", "out", "vendor", "venv", "__pycache__"];
|
||||
|
||||
/// A folder the nested-repository search neither looks at nor descends into.
|
||||
fn not_searched(path: &Path, skip: &dyn Fn(&Path) -> bool) -> bool {
|
||||
let name = path.file_name().map(|n| n.to_string_lossy()).unwrap_or_default();
|
||||
name.starts_with('.') || SKIPPED.contains(&name.as_ref()) || skip(path)
|
||||
}
|
||||
|
||||
/// The repositories of a project, sorted by root; lookups pick the innermost one.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct Repos {
|
||||
@@ -46,6 +52,18 @@ impl Repos {
|
||||
Ok(Self { repos, primary })
|
||||
}
|
||||
|
||||
/// Whether [`Self::discover`] from `project_root` looks for a repository at `dir`, below it.
|
||||
pub fn searched(project_root: &Path, dir: &Path, skip: &dyn Fn(&Path) -> bool) -> bool {
|
||||
let Ok(rel) = dir.strip_prefix(project_root) else { return false };
|
||||
let depth = rel.components().count();
|
||||
let mut path = project_root.to_path_buf();
|
||||
(1..=MAX_DEPTH).contains(&depth)
|
||||
&& rel.components().all(|c| {
|
||||
path.push(c);
|
||||
!not_searched(&path, skip)
|
||||
})
|
||||
}
|
||||
|
||||
/// The repository containing `project_root` and every repository whose worktree
|
||||
/// root lies below it (up to [`MAX_DEPTH`] levels; hidden and dependency folders and
|
||||
/// folders `skip` rejects are not searched).
|
||||
@@ -61,10 +79,8 @@ impl Repos {
|
||||
if !entry.file_type().is_ok_and(|t| t.is_dir()) {
|
||||
continue;
|
||||
}
|
||||
let name = entry.file_name();
|
||||
let name = name.to_string_lossy();
|
||||
let path = entry.path();
|
||||
if name.starts_with('.') || SKIPPED.contains(&name.as_ref()) || skip(&path) {
|
||||
if not_searched(&path, skip) {
|
||||
continue;
|
||||
}
|
||||
if path.join(".git").exists()
|
||||
@@ -350,6 +366,24 @@ mod tests {
|
||||
assert!(ok, "git {args:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn searched_matches_what_discover_finds() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
git_init(&root);
|
||||
let dirs = ["a", "a/b/c/d", "a/b/c/d/e", ".hidden/x", "vendor/x", "skipped/x", "a/skipped/x"];
|
||||
for dir in dirs {
|
||||
git_init(&root.join(dir));
|
||||
}
|
||||
let skip = |p: &Path| p.file_name().is_some_and(|n| n == "skipped");
|
||||
let found = Repos::discover(&root, &skip).unwrap().roots();
|
||||
for dir in dirs {
|
||||
let dir = root.join(dir);
|
||||
assert_eq!(Repos::searched(&root, &dir, &skip), found.contains(&dir), "{}", dir.display());
|
||||
}
|
||||
assert!(!Repos::searched(&root, &root, &skip), "the project root itself is no nested repository");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignored_files_use_git_rules_without_listing_other_repositories_twice() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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**:
|
||||
|
||||
@@ -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)。
|
||||
|
||||
@@ -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 解释器**,再选 **解释器类型**:
|
||||
|
||||
@@ -51,6 +51,60 @@ test("suggests and configures a project-scoped GitHub account in Settings › Ve
|
||||
expect(await ipcCalls(page, "gh_set_project_account")).toEqual([{ account: "alice-work" }]);
|
||||
});
|
||||
|
||||
test("Update failure offers project-scoped GitHub account selection", async ({ workbench: page }) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
let configuredAccount = "";
|
||||
const status = (): GhProjectAccountStatus => ({
|
||||
ghInstalled: true,
|
||||
accounts: [
|
||||
{ login: "alice", active: true },
|
||||
{ login: "alice-work", active: false },
|
||||
],
|
||||
configuredAccount,
|
||||
effectiveAccount: configuredAccount || "alice",
|
||||
suggestedAccount: configuredAccount ? null : "alice-work",
|
||||
});
|
||||
Object.assign(window.__ipc.handlers, {
|
||||
vcs_branch_info: () => ({ head: "main", upstream: "origin/main", headCommit: "c1", operation: null }),
|
||||
vcs_remote: () => {
|
||||
throw {
|
||||
kind: "invalid",
|
||||
message: "remote: Repository not found.\nfatal: repository 'https://github.com/acme/private.git/' not found",
|
||||
};
|
||||
},
|
||||
gh_project_account_status: () => status(),
|
||||
gh_set_project_account: ({ account }: { account: string }) => {
|
||||
configuredAccount = account;
|
||||
return status();
|
||||
},
|
||||
settings_get_global: () => ({}),
|
||||
window_open_settings: () => {
|
||||
throw { kind: "unavailable", message: "separate settings window disabled in browser test" };
|
||||
},
|
||||
});
|
||||
const opsModule = "/src/features/vcs/ops.ts";
|
||||
const { runRemote } = await import(/* @vite-ignore */ opsModule);
|
||||
await runRemote({ op: "updateProjectBranch", rebase: false }, undefined, ["/dev/acme-api"]);
|
||||
});
|
||||
|
||||
await expect(page.getByText("Update failed", { exact: true })).toBeVisible();
|
||||
await expect(page.getByText(/Repository not found/)).toBeVisible();
|
||||
await expect(page.getByText(/alice may not have access/)).toBeVisible();
|
||||
expect(await ipcCalls(page, "gh_set_project_account")).toEqual([]);
|
||||
const settingsLink = page.getByRole("button", { name: "GitHub Settings", exact: true });
|
||||
await expect(settingsLink).toBeVisible();
|
||||
if (process.env.CAPTURE_GH_AUTH_FAILURE) {
|
||||
await page.screenshot({ path: process.env.CAPTURE_GH_AUTH_FAILURE, animations: "disabled" });
|
||||
}
|
||||
await settingsLink.click();
|
||||
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
await expect(dialog.getByRole("button", { name: "GitHub account" })).toContainText("Automatic (alice)");
|
||||
await dialog.getByRole("button", { name: "Use alice-work for this project" }).click();
|
||||
await expect(dialog.getByRole("button", { name: "GitHub account" })).toContainText("alice-work");
|
||||
expect(await ipcCalls(page, "gh_set_project_account")).toEqual([{ account: "alice-work" }]);
|
||||
});
|
||||
|
||||
test("adds a GitHub account in Settings › Version Control › GitHub with OAuth device-code banner", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
|
||||
@@ -63,14 +63,13 @@ test("Shelf keeps patch and file selection available in a narrow dock", async ({
|
||||
const location = panel.getByText(directory, { exact: true });
|
||||
await expect.poll(() => location.evaluate((el) => el.clientWidth)).toBeGreaterThan(100);
|
||||
|
||||
const divider = panel.getByRole("separator", { name: "Resize shelf panes" });
|
||||
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
|
||||
const files = panel.getByRole("tree", { name: "Shelved files" });
|
||||
await expect(files.getByRole("treeitem")).toHaveCount(2);
|
||||
const pathBox = (await location.boundingBox())!;
|
||||
const filesBox = (await files.boundingBox())!;
|
||||
expect(pathBox.x).toBeLessThan(filesBox.x + filesBox.width - 50);
|
||||
const files = patches;
|
||||
await expect(patches.getByRole("treeitem").filter({ hasText: filename })).toHaveCount(1);
|
||||
const row = files.getByRole("treeitem").filter({ hasText: filename });
|
||||
const nameBox = (await row.getByText(filename, { exact: true }).boundingBox())!;
|
||||
const pathBox = (await location.boundingBox())!;
|
||||
expect(pathBox.x).toBeGreaterThan(nameBox.x + nameBox.width);
|
||||
expect(Math.abs(pathBox.y + pathBox.height - nameBox.y - nameBox.height)).toBeLessThan(3);
|
||||
await row.click({ position: { x: 90, y: 12 } });
|
||||
await expect(row).toHaveAttribute("aria-selected", "true");
|
||||
await panel.getByRole("button", { name: "Unshelve…", exact: true }).click();
|
||||
@@ -81,13 +80,9 @@ test("Shelf keeps patch and file selection available in a narrow dock", async ({
|
||||
await expect(dialog.getByText("README.md", { exact: true })).toHaveCount(0);
|
||||
await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
|
||||
await page.evaluate(async () => {
|
||||
const dock = "/src/workbench/toolwindows/store.ts";
|
||||
(await import(/* @vite-ignore */ dock)).setToolWindowSize("left", 640);
|
||||
});
|
||||
await expect(divider).toHaveAttribute("aria-orientation", "vertical");
|
||||
await expect(row).toHaveAttribute("aria-selected", "true");
|
||||
await patches.getByRole("treeitem").filter({ hasText: "Update release notes" }).click();
|
||||
await expect(files.getByRole("treeitem")).toHaveCount(1);
|
||||
const other = patches.getByRole("treeitem").filter({ hasText: "Update release notes" });
|
||||
await other.click();
|
||||
if ((await other.getAttribute("aria-expanded")) === "false") await page.keyboard.press("ArrowRight");
|
||||
await expect(files.getByText("CHANGELOG.md", { exact: true })).toBeVisible();
|
||||
});
|
||||
@@ -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",
|
||||
]
|
||||
|
||||
Бінарний файл не відображається.
@@ -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) {
|
||||
|
||||
@@ -17,6 +17,16 @@ install-hint = "npm i -g intelephense"
|
||||
# Intelephense applies the PHP version only to documents it parses after reading it.
|
||||
resync-on-configuration = true
|
||||
|
||||
[[language-servers]]
|
||||
name = "phpantom"
|
||||
# PHPantom 1.1.0 can cancel these operations without ending server-created progress.
|
||||
ignored-progress-token-prefixes = ["find_references", "goto_implementation"]
|
||||
fallback = true
|
||||
command = "phpantom_lsp"
|
||||
args = []
|
||||
root-markers = ["composer.json", "index.php"]
|
||||
install-hint = "Install PHPantom in Settings › Languages & Frameworks › Language Servers"
|
||||
|
||||
[[language-servers]]
|
||||
name = "phpactor"
|
||||
# Alternative: used only when the server above is not installed.
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -2,7 +2,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { Diagnostic, FileProblems } from "@/bindings";
|
||||
|
||||
const state = vi.hoisted(() => ({
|
||||
trusted: true as boolean | undefined,
|
||||
projectChanged: () => {},
|
||||
trustChanged: () => {},
|
||||
remoteChanged: () => {},
|
||||
report: vi.fn(),
|
||||
}));
|
||||
@@ -20,9 +22,11 @@ vi.mock("@/platform/ipc", async (importOriginal) => ({
|
||||
|
||||
vi.mock("@/platform/project", () => ({
|
||||
useProject: {
|
||||
getState: () => ({ project: { root: "/p" } }),
|
||||
getState: () => ({ project: { root: "/p", trusted: state.trusted } }),
|
||||
subscribe: (fn: (s: unknown, prev: unknown) => void) => {
|
||||
state.projectChanged = () => fn({ project: { root: "/p" } }, { project: null });
|
||||
state.trustChanged = () =>
|
||||
fn({ project: { root: "/p", trusted: true } }, { project: { root: "/p", trusted: false } });
|
||||
return () => {};
|
||||
},
|
||||
},
|
||||
@@ -58,6 +62,7 @@ describe("reportProblems", () => {
|
||||
clearProblems();
|
||||
reports.length = 0;
|
||||
state.report.mockReset();
|
||||
state.trusted = true;
|
||||
applyDiagnosticsEvent("/p/a.rs", "ra", [d(1), d(2)]);
|
||||
stop = reportProblems();
|
||||
});
|
||||
@@ -76,6 +81,20 @@ describe("reportProblems", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("reports nothing without a retry timer in a restricted project, then once when trusted", async () => {
|
||||
stop();
|
||||
state.trusted = false;
|
||||
reports.length = 0;
|
||||
stop = reportProblems();
|
||||
await vi.advanceTimersByTimeAsync(5000);
|
||||
expect(reports).toHaveLength(0);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
state.trusted = true;
|
||||
state.trustChanged();
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(summary()).toEqual([[true, [["/p/a.rs", 2]]]]);
|
||||
});
|
||||
|
||||
it("retries a failed delta with the full snapshot", async () => {
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
state.report.mockRejectedValueOnce(new Error("disconnected"));
|
||||
|
||||
@@ -13,7 +13,9 @@ export function reportProblems(): () => void {
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
const flush = () => {
|
||||
timer = null;
|
||||
if (!useProject.getState().project) return;
|
||||
const project = useProject.getState().project;
|
||||
// Restricted Mode refuses this command; the trust change below resets and reschedules.
|
||||
if (!project || project.trusted === false) return;
|
||||
const map = useProblems.getState().map;
|
||||
const files: FileProblems[] = [];
|
||||
for (const [path, sources] of map)
|
||||
@@ -37,7 +39,7 @@ export function reportProblems(): () => void {
|
||||
if (s.map !== prev.map) schedule();
|
||||
});
|
||||
const offProject = useProject.subscribe((s, prev) => {
|
||||
if (s.project?.root !== prev.project?.root) {
|
||||
if (s.project?.root !== prev.project?.root || s.project?.trusted !== prev.project?.trusted) {
|
||||
reset = true;
|
||||
reported = new Map();
|
||||
schedule();
|
||||
|
||||
@@ -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})`}
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
))}
|
||||
|
||||
@@ -42,7 +42,9 @@ export function activate(): () => void {
|
||||
const report = () => {
|
||||
if (timer) clearTimeout(timer);
|
||||
timer = null;
|
||||
if (!useProject.getState().project) return;
|
||||
const project = useProject.getState().project;
|
||||
// Restricted Mode refuses these commands; the trust change below reschedules the report.
|
||||
if (!project || project.trusted === false) return;
|
||||
const paths = openEditorPaths();
|
||||
const editor = activeEditor();
|
||||
const focused = document.hasFocus();
|
||||
|
||||
@@ -181,6 +181,27 @@ describe("MCP editor reports", () => {
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
expect(state.uiReady).toHaveBeenCalledWith(true);
|
||||
});
|
||||
it("sends no editor reports and runs no retry timer in a restricted project", async () => {
|
||||
stop();
|
||||
state.trusted = false;
|
||||
state.reportOpen.mockClear();
|
||||
state.reportFocused.mockClear();
|
||||
stop = activate();
|
||||
await vi.advanceTimersByTimeAsync(5000);
|
||||
expect(state.reportOpen).not.toHaveBeenCalled();
|
||||
expect(state.reportFocused).not.toHaveBeenCalled();
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
state.trusted = true;
|
||||
state.trustChanged();
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
expect(state.reportOpen).toHaveBeenCalledTimes(1);
|
||||
expect(state.reportFocused).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it("retries a failed editor report in a trusted project", async () => {
|
||||
state.reportOpen.mockRejectedValueOnce(new Error("disconnected"));
|
||||
await vi.advanceTimersByTimeAsync(600);
|
||||
expect(state.reportOpen).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
it("forwards remote editor reports and stops after disposal", async () => {
|
||||
state.remote = true;
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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)}']"
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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", () => {
|
||||
|
||||
@@ -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) },
|
||||
|
||||
@@ -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":
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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)) {
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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" }),
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -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" }));
|
||||
|
||||
@@ -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>,
|
||||
);
|
||||
|
||||
@@ -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>,
|
||||
);
|
||||
|
||||
@@ -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>,
|
||||
);
|
||||
|
||||
@@ -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",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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>,
|
||||
);
|
||||
|
||||
@@ -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" ? (
|
||||
<>
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -12,18 +12,9 @@
|
||||
|
||||
.fileText {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.filesHeader {
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
min-height: var(--h-compact-header);
|
||||
padding-inline: var(--space-2);
|
||||
border-bottom: 1px solid var(--border);
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
align-items: baseline;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.detail {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { BranchInfo, FetchReport, PushReport, RemoteOp } from "@/bindings";
|
||||
import type { BranchInfo, FetchReport, GhProjectAccountStatus, PushReport, RemoteOp } from "@/bindings";
|
||||
|
||||
let branch: Partial<BranchInfo> = {};
|
||||
/** What a pull brings in: the head moves to `c2`, with these changed files and commits. */
|
||||
@@ -10,6 +10,7 @@ let reports: Record<string, PushReport | FetchReport> = {};
|
||||
let partialReport: PushReport | null = null;
|
||||
let remoteGate: Promise<void> | null = null;
|
||||
let remoteRepos: Array<string | null> = [];
|
||||
const ghAccountStatus = vi.fn();
|
||||
|
||||
vi.mock("@tauri-apps/api/core", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@tauri-apps/api/core")>()),
|
||||
@@ -51,6 +52,7 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
vcsDiffRevisions: async () => ({ status: "ok", data: Array.from({ length: pulled.files }, (_, i) => ({ i })) }),
|
||||
vcsLog: async () => ({ status: "ok", data: Array.from({ length: pulled.commits }, (_, i) => ({ i })) }),
|
||||
vcsFinishShelfBatch: async () => ({ status: "ok", data: null }),
|
||||
ghProjectAccountStatus: () => ghAccountStatus(),
|
||||
cancelRequest: async () => ({ status: "ok", data: null }),
|
||||
},
|
||||
};
|
||||
@@ -73,11 +75,13 @@ import {
|
||||
import { pushTargets } from "../remoteUi";
|
||||
import { useVcs } from "../store";
|
||||
|
||||
type Note = { title: string; level: string; body?: string };
|
||||
type Note = { title: string; level: string; body?: string; actions?: Array<{ label: string; run: () => void }> };
|
||||
let notes: Note[] = [];
|
||||
|
||||
beforeEach(() => {
|
||||
notes = [];
|
||||
ghAccountStatus.mockReset();
|
||||
ghAccountStatus.mockResolvedValue({ status: "ok", data: null });
|
||||
provideNotificationService({ notify: (n) => void notes.push(n as Note), expire: () => {} });
|
||||
});
|
||||
|
||||
@@ -101,6 +105,108 @@ const pushTitle = async () => {
|
||||
return notes.at(-1)!.title;
|
||||
};
|
||||
|
||||
describe("GitHub HTTPS authentication failure", () => {
|
||||
const message =
|
||||
"remote: Repository not found.\nfatal: repository 'https://github.com/example/private.git/' not found";
|
||||
const multiAccount: GhProjectAccountStatus = {
|
||||
ghInstalled: true,
|
||||
accounts: [
|
||||
{ login: "personal", active: true },
|
||||
{ login: "work", active: false },
|
||||
],
|
||||
configuredAccount: "",
|
||||
effectiveAccount: "personal",
|
||||
suggestedAccount: "work",
|
||||
};
|
||||
|
||||
it("preserves the Git error and opens project GitHub settings without changing accounts", async () => {
|
||||
failure = { kind: "invalid", message };
|
||||
ghAccountStatus.mockResolvedValue({ status: "ok", data: multiAccount });
|
||||
const settings = vi.fn();
|
||||
const unregister = registerActions([{ id: "file.settings", title: "Settings", run: settings }]);
|
||||
try {
|
||||
expect(await runRemote({ op: "updateProjectBranch", rebase: false }, undefined, ["/p"])).toBe(false);
|
||||
const note = notes.at(-1)!;
|
||||
expect(note.title).toBe("Update failed");
|
||||
expect(note.body).toContain(message);
|
||||
expect(note.body).toContain("personal may not have access");
|
||||
expect(ghAccountStatus).toHaveBeenCalledTimes(1);
|
||||
expect(settings).not.toHaveBeenCalled();
|
||||
expect(remoteRepos).toEqual(["/p"]);
|
||||
note.actions?.find((action) => action.label === "GitHub Settings")?.run();
|
||||
await vi.waitFor(() => expect(settings).toHaveBeenCalledWith(expect.objectContaining({ arg: "vcs.github" })));
|
||||
} finally {
|
||||
unregister();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
"fatal: repository 'https://gitlab.com/example/private.git/' not found",
|
||||
"fatal: repository 'https://github.com.evil.example/private.git/' not found",
|
||||
"fatal: repository '[email protected]:example/private.git' not found",
|
||||
"remote: Repository not found.",
|
||||
"fatal: unable to access 'https://github.com/example/private.git/': Could not resolve host: github.com",
|
||||
])("does not check gh for unrelated errors: %s", async (message) => {
|
||||
failure = { kind: "invalid", message };
|
||||
expect(await runRemote({ op: "updateProjectBranch", rebase: false }, undefined, ["/p"])).toBe(false);
|
||||
expect(ghAccountStatus).not.toHaveBeenCalled();
|
||||
expect(notes.at(-1)).toMatchObject({ title: "Update failed", body: message });
|
||||
});
|
||||
|
||||
it("keeps the original failure when only one account is signed in", async () => {
|
||||
failure = { kind: "invalid", message };
|
||||
ghAccountStatus.mockResolvedValue({
|
||||
status: "ok",
|
||||
data: { ...multiAccount, accounts: multiAccount.accounts.slice(0, 1) },
|
||||
});
|
||||
expect(await runRemote({ op: "updateProjectBranch", rebase: false }, undefined, ["/p"])).toBe(false);
|
||||
expect(notes.at(-1)).toMatchObject({ title: "Update failed", body: message, actions: undefined });
|
||||
});
|
||||
|
||||
it("keeps the original failure when account detection is unavailable", async () => {
|
||||
failure = { kind: "invalid", message };
|
||||
ghAccountStatus.mockRejectedValue(new Error("gh unavailable"));
|
||||
expect(await runRemote({ op: "updateProjectBranch", rebase: false }, undefined, ["/p"])).toBe(false);
|
||||
expect(notes.at(-1)).toMatchObject({ title: "Update failed", body: message, actions: undefined });
|
||||
});
|
||||
|
||||
it("offers the same guidance for push failures without retrying", async () => {
|
||||
failure = { kind: "invalid", message };
|
||||
ghAccountStatus.mockResolvedValue({ status: "ok", data: multiAccount });
|
||||
expect(
|
||||
await pushTargets([
|
||||
{
|
||||
repo: "/p",
|
||||
op: {
|
||||
op: "pushSelected",
|
||||
selection: { branch: "main", revision: null, remote: "origin", target: "main" },
|
||||
force_with_lease: false,
|
||||
set_upstream: false,
|
||||
tags: null,
|
||||
no_verify: false,
|
||||
},
|
||||
},
|
||||
]),
|
||||
).toBe(false);
|
||||
expect(notes.at(-1)).toMatchObject({
|
||||
title: "Push failed",
|
||||
body: expect.stringContaining("personal may not have access"),
|
||||
actions: [expect.objectContaining({ label: "GitHub Settings" })],
|
||||
});
|
||||
expect(remoteRepos).toEqual(["/p"]);
|
||||
});
|
||||
|
||||
it("offers the same guidance for fetch authentication failures", async () => {
|
||||
failure = {
|
||||
kind: "invalid",
|
||||
message: "fatal: Authentication failed for 'https://github.com/example/private.git/'",
|
||||
};
|
||||
ghAccountStatus.mockResolvedValue({ status: "ok", data: multiAccount });
|
||||
expect(await runRemote({ op: "fetch" }, undefined, ["/p"])).toBe(false);
|
||||
expect(notes.at(-1)?.actions?.map(({ label }) => label)).toEqual(["Show Git Console", "GitHub Settings"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("fetch result notification", () => {
|
||||
it("keeps successful remotes and pruned refs visible when other remotes fail", async () => {
|
||||
const showConsole = vi.fn();
|
||||
|
||||
@@ -80,6 +80,8 @@ beforeEach(() => {
|
||||
mocks.patch.mockResolvedValue(null);
|
||||
useVcs.setState({ root: "/repo", roots: [], repo: null, available: false, status: [] });
|
||||
useCommit.setState({ selectedShelf: "work\u0000a.txt" });
|
||||
localStorage.removeItem("openidea.vcs.shelf.groupByDir");
|
||||
localStorage.removeItem("openidea.vcs.shelf.diffPreview");
|
||||
useShelf.setState({ shelves: [entry], loaded: true, diffs: { work: diffs } });
|
||||
mocks.ipc.mockResolvedValueOnce([entry]).mockResolvedValue(diffs);
|
||||
});
|
||||
@@ -287,6 +289,62 @@ describe("shelf scope and diffs", () => {
|
||||
fireEvent.click(screen.getByRole("menuitem", { name: "Copy as Patch to Clipboard" }));
|
||||
expect(mocks.execute).toHaveBeenCalledWith("vcs.shelf.copyPatch", { id: "work", path: "a.txt" });
|
||||
});
|
||||
it("deletes the selected shelf with the Delete key", async () => {
|
||||
useShelf.setState({ shelves: [entry] });
|
||||
useCommit.setState({ selectedShelf: "work" });
|
||||
render(<ShelfPanel />);
|
||||
await waitFor(() => expect(screen.getByText("Work")).toBeTruthy());
|
||||
fireEvent.keyDown(screen.getByRole("tree"), { key: "Delete" });
|
||||
expect(mocks.execute).toHaveBeenCalledWith("vcs.shelf.delete", { id: "work", path: undefined });
|
||||
});
|
||||
|
||||
it("groups shelved files by directory and exposes preview and tree controls", async () => {
|
||||
const grouped: ShelvedChangeList = {
|
||||
...entry,
|
||||
files: [
|
||||
{ path: "src/a.txt", kind: "modified", oldPath: null },
|
||||
{ path: "src/nested/b.txt", kind: "added", oldPath: null },
|
||||
],
|
||||
};
|
||||
const groupedDiff = [{ path: "src/a.txt", before: "base", after: "shelved", patch: "patch" }];
|
||||
mocks.ipc.mockReset().mockResolvedValueOnce([grouped]).mockResolvedValue(groupedDiff);
|
||||
localStorage.setItem("openidea.vcs.shelf.diffPreview", "false");
|
||||
act(() => useProject.setState({ settings: { vcs: { commit: { nonModal: false } } } as never }));
|
||||
useShelf.setState({
|
||||
shelves: [grouped],
|
||||
diffs: { work: groupedDiff },
|
||||
});
|
||||
useCommit.setState({ selectedShelf: "work\u0000src/a.txt" });
|
||||
render(
|
||||
<>
|
||||
<ShelfPanel />
|
||||
<ContextMenuHost />
|
||||
</>,
|
||||
);
|
||||
await waitFor(() => expect(screen.getByText("Work")).toBeTruthy());
|
||||
expect(useCommit.getState().selectedShelf).toBe("work\u0000src/a.txt");
|
||||
fireEvent.click(screen.getByRole("button", { name: "View Options" }));
|
||||
fireEvent.click(screen.getByText("Directory"));
|
||||
expect(localStorage.getItem("openidea.vcs.shelf.groupByDir")).toBe("true");
|
||||
expect(useCommit.getState().selectedShelf).toBe("work\u0000src/a.txt");
|
||||
expect(screen.getAllByText("src")).toHaveLength(1);
|
||||
fireEvent.mouseDown(screen.getByText("src"));
|
||||
expect(screen.getByRole("button", { name: "Unshelve…" }).hasAttribute("disabled")).toBe(true);
|
||||
fireEvent.keyDown(screen.getByRole("tree"), { key: "Delete" });
|
||||
expect(mocks.execute).not.toHaveBeenCalledWith("vcs.shelf.delete", expect.anything());
|
||||
fireEvent.click(screen.getByRole("button", { name: "Collapse All" }));
|
||||
expect(screen.queryByText("a.txt")).toBeNull();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Expand All" }));
|
||||
expect(screen.getByText("a.txt")).toBeTruthy();
|
||||
fireEvent.click(screen.getByRole("button", { name: "View Options" }));
|
||||
fireEvent.click(screen.getByText("Show Diff Preview"));
|
||||
expect(localStorage.getItem("openidea.vcs.shelf.diffPreview")).toBe("true");
|
||||
expect(screen.getByLabelText("Resize shelf preview")).toBeTruthy();
|
||||
act(() => useProject.setState({ settings: { vcs: { commit: { nonModal: true } } } as never }));
|
||||
expect(screen.queryByLabelText("Resize shelf preview")).toBeNull();
|
||||
fireEvent.click(screen.getByRole("button", { name: "View Options" }));
|
||||
expect(screen.queryByText("Show Diff Preview")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Shelve Silently / Unshelve Silently", () => {
|
||||
|
||||
@@ -9,6 +9,7 @@ const mocks = vi.hoisted(() => ({
|
||||
checkout: vi.fn(),
|
||||
notify: vi.fn(),
|
||||
openWorktree: vi.fn(),
|
||||
ghAccountStatus: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/platform/actions", async (original) => ({
|
||||
...(await original<typeof import("@/platform/actions")>()),
|
||||
@@ -23,7 +24,15 @@ vi.mock("../ops", async (original) => ({
|
||||
vi.mock("../openWorktree", () => ({ openWorktree: mocks.openWorktree }));
|
||||
vi.mock("@/platform/ipc", async (original) => {
|
||||
const real = await original<typeof import("@/platform/ipc")>();
|
||||
return { ...real, commands: { ...real.commands, vcsBranchInfo: mocks.head, vcsCheckout: mocks.checkout } };
|
||||
return {
|
||||
...real,
|
||||
commands: {
|
||||
...real.commands,
|
||||
vcsBranchInfo: mocks.head,
|
||||
vcsCheckout: mocks.checkout,
|
||||
ghProjectAccountStatus: mocks.ghAccountStatus,
|
||||
},
|
||||
};
|
||||
});
|
||||
vi.mock("@/workbench/contributions", async (original) => ({
|
||||
...(await original<typeof import("@/workbench/contributions")>()),
|
||||
@@ -123,6 +132,28 @@ describe("Update Selected", () => {
|
||||
expect(mocks.openWorktree).toHaveBeenCalledWith("/worktrees/topic", true);
|
||||
});
|
||||
|
||||
it("offers GitHub account settings for an unchecked branch's HTTPS failure", async () => {
|
||||
mocks.update.mockResolvedValue([
|
||||
result("topic", "failed", "/p", "fatal: repository 'https://github.com/acme/private.git/' not found"),
|
||||
]);
|
||||
mocks.ghAccountStatus.mockResolvedValue({
|
||||
status: "ok",
|
||||
data: {
|
||||
ghInstalled: true,
|
||||
accounts: [
|
||||
{ login: "personal", active: true },
|
||||
{ login: "work", active: false },
|
||||
],
|
||||
effectiveAccount: "personal",
|
||||
},
|
||||
});
|
||||
await updateBranches([target("topic", "/p")]);
|
||||
const [action] = mocks.notify.mock.lastCall![0].actions;
|
||||
expect(action.label).toBe("GitHub Settings");
|
||||
action.run();
|
||||
expect(mocks.execute).toHaveBeenCalledWith("file.settings", "vcs.github");
|
||||
});
|
||||
|
||||
it("offers Update Selected in the context menu of a multi-selection", () => {
|
||||
const selected = [target("a", "/p"), target("b", "/p")];
|
||||
const items = branchMenu(selected[0]!.branch, "main", () => {}, { selected });
|
||||
|
||||
@@ -17,6 +17,7 @@ import { executeAction } from "@/platform/actions";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { openWorktree } from "./openWorktree";
|
||||
import { githubHttpsFailureHelp } from "./githubHttpsFailure";
|
||||
import { activeRepository } from "./activeRepository";
|
||||
import { ask, confirmChecked } from "@/workbench/messages";
|
||||
import { branchNamePrefixes, isFavoriteBranch, isProtectedBranch, pushRecent, shortRemoteName } from "./branches";
|
||||
@@ -1446,6 +1447,11 @@ export async function updateBranches(targets: readonly BranchUpdateTarget[]) {
|
||||
const results = await runBranchUpdates(new Map([...byRepo].map(([repo, names]) => [repo, [...names]])));
|
||||
if (!results || useProject.getState().project !== project) return;
|
||||
const { lines, ...summary } = branchUpdateSummary(results, heads.length > 1);
|
||||
const help = await githubHttpsFailureHelp(
|
||||
results.flatMap((r) => (r.status === "failed" && r.message ? [r.message] : [])),
|
||||
);
|
||||
if (useProject.getState().project !== project) return;
|
||||
if (help) lines.push(help.message);
|
||||
const body = createElement(Fragment, null, ...lines.map((line) => createElement("div", { key: line }, line)));
|
||||
const worktrees = [...new Set(results.flatMap((r) => (r.status === "failed" && r.worktree ? [r.worktree] : [])))];
|
||||
notifications().notify({
|
||||
@@ -1454,10 +1460,13 @@ export async function updateBranches(targets: readonly BranchUpdateTarget[]) {
|
||||
userInitiated: true,
|
||||
...summary,
|
||||
body,
|
||||
actions: worktrees.map((path) => {
|
||||
const name = repoName(path);
|
||||
return { label: tx`Open Worktree ${name}`, run: () => void openWorktree(path, true) };
|
||||
}),
|
||||
actions: [
|
||||
...worktrees.map((path) => {
|
||||
const name = repoName(path);
|
||||
return { label: tx`Open Worktree ${name}`, run: () => void openWorktree(path, true) };
|
||||
}),
|
||||
...(help ? [help.action] : []),
|
||||
],
|
||||
});
|
||||
}
|
||||
if (current.length && useProject.getState().project === project) await runRemoteRound(current);
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
|
||||
/** GitHub deliberately uses "Repository not found" for inaccessible private repositories.
|
||||
* Require Git's actual failing HTTPS URL: the same error from another host or SSH is unrelated
|
||||
* to gh's HTTPS credential helper. Never infer a credential mismatch from the error alone.
|
||||
*/
|
||||
function isGithubHttpsFailure(message: string): boolean {
|
||||
return /^fatal: (?:repository 'https:\/\/github\.com\/[^'\r\n]+' not found|Authentication failed for 'https:\/\/github\.com\/[^'\r\n]+')\.?(?:\r?$)/im.test(
|
||||
message,
|
||||
);
|
||||
}
|
||||
|
||||
/** Diagnose only explicit failed remote operations. The existing project account settings
|
||||
* handle selection; do not switch gh's global account, edit remotes, or retry a Git write.
|
||||
*/
|
||||
export async function githubHttpsFailureHelp(messages: readonly string[]) {
|
||||
if (!messages.some(isGithubHttpsFailure)) return null;
|
||||
const project = useProject.getState().project;
|
||||
const status = await call(commands.ghProjectAccountStatus()).catch(() => null);
|
||||
if (!status?.ghInstalled || status.accounts.length < 2 || useProject.getState().project !== project) return null;
|
||||
return {
|
||||
message: status.effectiveAccount
|
||||
? tx`GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, ${status.effectiveAccount} may not have access. Check the remote URL or choose an account with access in GitHub settings, then retry.`
|
||||
: tx(
|
||||
"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.",
|
||||
),
|
||||
action: {
|
||||
label: "GitHub Settings",
|
||||
run: () => {
|
||||
if (useProject.getState().project === project) void executeAction("file.settings", "vcs.github");
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -24,6 +24,7 @@ import { flushChangelists } from "./changelists";
|
||||
import { pushHistoryRepo, rememberPushTarget } from "./pushHistory";
|
||||
import { describePush, formatPushOutcomes, partialPushReport, pushedCommits, type RepoPushOutcome } from "./pushReport";
|
||||
import { cancelIncomingCheck } from "./incomingRequest";
|
||||
import { githubHttpsFailureHelp } from "./githubHttpsFailure";
|
||||
import { beginGitWork, conflictedFiles, currentRepo, refreshNow, repoName, repoOf, useVcs } from "./store";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -551,6 +552,13 @@ export async function runRemoteRound<Op extends RemoteOp>(
|
||||
: first.op === "unshallow"
|
||||
? tx("Could not fetch full Git history")
|
||||
: `${doneTitle} failed`;
|
||||
const help = await githubHttpsFailureHelp(remaining.map(({ error }) => errorMessage(error)));
|
||||
if (cancelRequested || useProject.getState().project !== project)
|
||||
throw new IpcError({ kind: "cancelled", message: "cancelled" });
|
||||
const actions = [
|
||||
...(partial || isFetch ? [gitConsoleNotificationAction()] : []),
|
||||
...(help ? [help.action] : []),
|
||||
];
|
||||
notify({
|
||||
level: "error",
|
||||
key: "vcs.remote",
|
||||
@@ -561,9 +569,9 @@ export async function runRemoteRound<Op extends RemoteOp>(
|
||||
? tx(message)
|
||||
: message,
|
||||
)
|
||||
.concat(pruned)
|
||||
.concat(pruned, help ? [help.message] : [])
|
||||
.join("\n"),
|
||||
actions: partial || isFetch ? [gitConsoleNotificationAction()] : undefined,
|
||||
actions: actions.length ? actions : undefined,
|
||||
});
|
||||
}
|
||||
if (!reported && isUpdate(first) && updated.length) await notifyUpdated(updated, "vcs.remote.updated");
|
||||
|
||||
@@ -26,6 +26,7 @@ import { openDialog } from "./dialogs";
|
||||
import { useBranches } from "./gitMenuDialogs";
|
||||
import { saveVcsSetting } from "./settingsUi";
|
||||
import { formatTime } from "./model";
|
||||
import { githubHttpsFailureHelp } from "./githubHttpsFailure";
|
||||
import {
|
||||
allRepos,
|
||||
errorMessage,
|
||||
@@ -1493,12 +1494,13 @@ function pushReviewActions(review: readonly PushReviewTarget[]) {
|
||||
];
|
||||
}
|
||||
|
||||
function pushFailed(
|
||||
async function pushFailed(
|
||||
failures: RemoteFailure<PushOp>[],
|
||||
total: number,
|
||||
rejected: boolean,
|
||||
pushed: readonly RepoPushOutcome[],
|
||||
): false {
|
||||
): Promise<false> {
|
||||
const project = useProject.getState().project;
|
||||
const isPartial = ({ error }: RemoteFailure<PushOp>) => !!partialPushReport(error);
|
||||
const names = (items: RemoteFailure<PushOp>[]) =>
|
||||
items.flatMap(({ target }) => (target.repo ? [repoName(target.repo)] : [])).join(", ");
|
||||
@@ -1521,7 +1523,11 @@ function pushFailed(
|
||||
: tx(errorMessage(failures[0]!.error)),
|
||||
);
|
||||
}
|
||||
const actions = pushReviewActions(review);
|
||||
const help = await githubHttpsFailureHelp(failures.map(({ error }) => errorMessage(error)));
|
||||
if (useProject.getState().project !== project) return false;
|
||||
if (help) lines.push(help.message);
|
||||
const actions = [...(pushReviewActions(review) ?? []), ...(help ? [help.action] : [])];
|
||||
if (partiallyApplied.length) actions.push(gitConsoleNotificationAction());
|
||||
notifications().notify({
|
||||
group: "vcs",
|
||||
level: "error",
|
||||
@@ -1534,7 +1540,7 @@ function pushFailed(
|
||||
? "Push rejected"
|
||||
: "Push failed",
|
||||
body: lines.join("\n"),
|
||||
actions: partiallyApplied.length ? [...(actions ?? []), gitConsoleNotificationAction()] : actions,
|
||||
actions: actions.length ? actions : undefined,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -18,18 +18,20 @@ import type {
|
||||
} from "@/bindings";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
import { openDiff, openVcsDiff, withChain, workingDiffData, type DiffData } from "./diffInput";
|
||||
import { diffInput, openDiff, openVcsDiff, withChain, workingDiffData, type DiffData } from "./diffInput";
|
||||
import { useDiffSource } from "./diffSource";
|
||||
import { showCreatePatchForShelf } from "./patches";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { workflowSettings } from "@/platform/workflowSettings";
|
||||
import { useWorkflowSettings, workflowSettings } from "@/platform/workflowSettings";
|
||||
import {
|
||||
Checkbox,
|
||||
Dialog,
|
||||
EmptyState,
|
||||
Icon,
|
||||
IconButton,
|
||||
Input,
|
||||
lazyComponent,
|
||||
Select,
|
||||
SplitGroup,
|
||||
SplitHandle,
|
||||
@@ -40,7 +42,8 @@ import {
|
||||
T,
|
||||
} from "@/ui";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { groupOf } from "./changes";
|
||||
import { groupOf, moduleOf } from "./changes";
|
||||
import { useChangeModules } from "./changeModules";
|
||||
import { buildFileTree, dirKeys, type FileTreeNode } from "./fileTree";
|
||||
import { activeList, listOf, moveFiles, relOf, updateChangelists, useChangelists } from "./changelists";
|
||||
import { useCommit } from "./commitStore";
|
||||
@@ -65,6 +68,27 @@ import viewStyles from "./CommitView.module.css";
|
||||
import shelfStyles from "./Shelf.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
const DiffEditor = lazyComponent(() => import("./DiffEditor").then((m) => m.DiffEditor));
|
||||
|
||||
type ShelfViewOption = "groupByDir" | "groupByModule" | "diffPreview";
|
||||
|
||||
function readShelfViewOption(option: ShelfViewOption, fallback: boolean): boolean {
|
||||
try {
|
||||
const saved = localStorage.getItem(`openidea.vcs.shelf.${option}`);
|
||||
return saved === null ? fallback : saved === "true";
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
function saveShelfViewOption(option: ShelfViewOption, value: boolean) {
|
||||
try {
|
||||
localStorage.setItem(`openidea.vcs.shelf.${option}`, String(value));
|
||||
} catch {
|
||||
// The view remains usable if browser storage is unavailable.
|
||||
}
|
||||
}
|
||||
|
||||
interface ShelfState {
|
||||
shelves: ShelvedChangeList[];
|
||||
loaded: boolean;
|
||||
@@ -571,6 +595,19 @@ interface ShelfNode {
|
||||
key: string;
|
||||
entry: ShelvedChangeList;
|
||||
file?: ShelvedChangeList["files"][number];
|
||||
directory?: boolean;
|
||||
module?: boolean;
|
||||
label?: string;
|
||||
children?: ShelfNode[];
|
||||
}
|
||||
|
||||
function shelfDirKeys(nodes: readonly ShelfNode[], out: string[] = []): string[] {
|
||||
for (const node of nodes)
|
||||
if (node.children?.length) {
|
||||
out.push(node.key);
|
||||
shelfDirKeys(node.children, out);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export interface ShelfTarget {
|
||||
@@ -702,30 +739,35 @@ export function createShelfPatch(arg?: unknown) {
|
||||
|
||||
function ShelfTree({
|
||||
nodes,
|
||||
kind,
|
||||
selectedKey,
|
||||
empty,
|
||||
expanded,
|
||||
onExpandedChange,
|
||||
grouped,
|
||||
}: {
|
||||
nodes: ShelfNode[];
|
||||
kind: "changes" | "files";
|
||||
selectedKey: string | null;
|
||||
empty: string;
|
||||
expanded: ReadonlySet<string>;
|
||||
onExpandedChange: (expanded: Set<string>) => void;
|
||||
grouped: boolean;
|
||||
}) {
|
||||
const selected = useMemo(() => new Set(selectedKey ? [selectedKey] : []), [selectedKey]);
|
||||
const filePane = kind === "files";
|
||||
return (
|
||||
<Tree<ShelfNode>
|
||||
roots={nodes}
|
||||
getKey={(n) => n.key}
|
||||
getLabel={(n) => (n.file ? baseName(n.file.path) : n.entry.name)}
|
||||
getChildren={() => undefined}
|
||||
isExpandable={() => false}
|
||||
getLabel={(n) => (n.file ? baseName(n.file.path) : n.directory ? (n.label ?? "") : n.entry.name)}
|
||||
getChildren={(n) => n.children}
|
||||
isExpandable={(n) => !!n.children?.length}
|
||||
expanded={expanded}
|
||||
onExpandedChange={(next) => onExpandedChange(next)}
|
||||
selected={selected}
|
||||
onSelectionChange={(sel) => useCommit.setState({ selectedShelf: [...sel][0] ?? null })}
|
||||
horizontalScroll={filePane}
|
||||
rowHeight={filePane ? 40 : undefined}
|
||||
horizontalScroll
|
||||
multiSelect={false}
|
||||
onActivate={(n) => {
|
||||
if (n.directory) return;
|
||||
void executeAction(n.file ? "vcs.shelf.showDiff" : "vcs.unshelve", { id: n.entry.id, path: n.file?.path });
|
||||
}}
|
||||
onContextMenu={(node, _sel, e: MouseEvent) => {
|
||||
@@ -744,10 +786,18 @@ function ShelfTree({
|
||||
}),
|
||||
).then((supported) => showContextMenu(point, shelfMenu(node, supported.some(Boolean))));
|
||||
}}
|
||||
aria-label={filePane ? "Shelved files" : "Shelved changes"}
|
||||
aria-label="Shelved changes"
|
||||
empty={<span className={viewStyles.empty}>{tx(empty)}</span>}
|
||||
renderNode={(n) => {
|
||||
const file = n.file;
|
||||
if (n.directory) {
|
||||
return (
|
||||
<>
|
||||
<Icon name={n.module ? "module" : "folder"} size={16} className={viewStyles.icon} />
|
||||
<span className={shelfStyles.patchName}>{n.label}</span>
|
||||
</>
|
||||
);
|
||||
}
|
||||
if (file) {
|
||||
const directory = dirName(file.path);
|
||||
return (
|
||||
@@ -757,7 +807,7 @@ function ShelfTree({
|
||||
<span style={{ color: KIND_COLOR[file.kind === "untracked" ? "added" : file.kind] }}>
|
||||
{baseName(file.path)}
|
||||
</span>
|
||||
{directory && <span className={shelfStyles.detail}>{directory}</span>}
|
||||
{directory && !grouped && <span className={shelfStyles.detail}>{directory}</span>}
|
||||
</span>
|
||||
</>
|
||||
);
|
||||
@@ -765,11 +815,13 @@ function ShelfTree({
|
||||
const time = n.entry.timeMs ? formatTime(n.entry.timeMs) : null;
|
||||
return (
|
||||
<>
|
||||
<Icon name="shelve" size={16} className={viewStyles.icon} />
|
||||
<span className={shelfStyles.patchName} title={n.entry.name}>
|
||||
{n.entry.name}
|
||||
</span>
|
||||
<span className={shelfStyles.detail}>{fileCount(n.entry.files.length)}</span>
|
||||
<span className={shelfStyles.detail}>
|
||||
{fileCount(n.entry.files.length)}
|
||||
{time ? "," : ""}
|
||||
</span>
|
||||
{time && (
|
||||
<span className={shelfStyles.date} title={time}>
|
||||
{time}
|
||||
@@ -788,8 +840,17 @@ export function ShelfPanel() {
|
||||
const loaded = useShelf((s) => s.loaded);
|
||||
const root = useVcs((s) => s.root);
|
||||
const selectedShelf = useCommit((s) => s.selectedShelf);
|
||||
const shelfDiffFiles = useShelf((s) => s.diffs);
|
||||
const panelRef = useRef<HTMLDivElement>(null);
|
||||
const [stacked, setStacked] = useState(true);
|
||||
const viewRef = useRef<HTMLButtonElement>(null);
|
||||
const [stacked, setStacked] = useState(false);
|
||||
const [groupByDir, setGroupByDir] = useState(() => readShelfViewOption("groupByDir", false));
|
||||
const [groupByModule, setGroupByModule] = useState(() => readShelfViewOption("groupByModule", false));
|
||||
const changeModules = useChangeModules();
|
||||
const nonModal = useWorkflowSettings((s) => s.vcs.commit.nonModal);
|
||||
const [diffPreviewOption, setDiffPreview] = useState(() => readShelfViewOption("diffPreview", true));
|
||||
const diffPreview = diffPreviewOption && !nonModal;
|
||||
const [expanded, setExpanded] = useState<{ scope: string; keys: ReadonlySet<string> } | null>(null);
|
||||
useLayoutEffect(() => {
|
||||
const panel = panelRef.current;
|
||||
if (!panel) return;
|
||||
@@ -805,20 +866,68 @@ export function ShelfPanel() {
|
||||
return () => setContext("shelfFocus", false);
|
||||
}, [root]);
|
||||
useDiffSource(panelRef, { diff: () => shelfDiffData(), show: () => showShelfDiff() });
|
||||
const selectedId = selectedShelf?.split("\u0000", 1)[0];
|
||||
const entry = shelves.find((s) => s.id === selectedId);
|
||||
const patches = useMemo<ShelfNode[]>(() => shelves.map((s) => ({ key: s.id, entry: s })), [shelves]);
|
||||
const files = useMemo<ShelfNode[]>(
|
||||
() => entry?.files.map((file) => ({ key: `${entry.id}\u0000${file.path}`, entry, file })) ?? [],
|
||||
[entry],
|
||||
const nodes = useMemo<ShelfNode[]>(
|
||||
() =>
|
||||
shelves.map((entry) => {
|
||||
type F = (typeof entry.files)[number];
|
||||
const build = (files: F[]) =>
|
||||
groupByDir
|
||||
? buildFileTree(files, (file) => file.path.replaceAll("\\", "/"))
|
||||
: files.map((file) => ({
|
||||
key: `f:${file.path}`,
|
||||
name: baseName(file.path),
|
||||
file,
|
||||
children: [],
|
||||
count: 1,
|
||||
}));
|
||||
const convert = (node: FileTreeNode<F>): ShelfNode => ({
|
||||
key: `${entry.id}\u0000${node.file ? node.file.path : node.key}`,
|
||||
entry,
|
||||
file: node.file ?? undefined,
|
||||
directory: !node.file,
|
||||
label: node.name,
|
||||
children: node.file ? undefined : node.children.map(convert),
|
||||
});
|
||||
if (!groupByModule || !changeModules.length)
|
||||
return { key: entry.id, entry, children: build(entry.files).map(convert) };
|
||||
const byModule = new Map<string, { name: string; files: F[] }>();
|
||||
const loose: F[] = [];
|
||||
for (const file of entry.files) {
|
||||
const rel = file.path.replaceAll("\\", "/");
|
||||
const mod = moduleOf(rel.startsWith("/") || !root ? rel : `${stripSlash(root)}/${rel}`, changeModules);
|
||||
if (!mod) loose.push(file);
|
||||
else
|
||||
(byModule.get(mod.path) ?? byModule.set(mod.path, { name: mod.name, files: [] }).get(mod.path)!).files.push(
|
||||
file,
|
||||
);
|
||||
}
|
||||
const children: ShelfNode[] = [...byModule].map(([path, m]) => ({
|
||||
key: `${entry.id}\u0000m:${path}`,
|
||||
entry,
|
||||
directory: true,
|
||||
module: true,
|
||||
label: m.name,
|
||||
children: build(m.files).map(convert),
|
||||
}));
|
||||
return { key: entry.id, entry, children: [...children, ...build(loose).map(convert)] };
|
||||
}),
|
||||
[shelves, groupByDir, groupByModule, changeModules, root],
|
||||
);
|
||||
const allKeys = useMemo(() => shelfDirKeys(nodes), [nodes]);
|
||||
const expansionScope = `${groupByDir}:${groupByModule}`;
|
||||
const expandedKeys = expanded?.scope === expansionScope ? expanded.keys : new Set(allKeys);
|
||||
const updateExpanded = (keys: Set<string>) => setExpanded({ scope: expansionScope, keys });
|
||||
const current = selectedShelf ? shelfTarget(selectedShelf) : null;
|
||||
const patchTree = (
|
||||
const previewDiff = diffPreview && current?.path ? shelfDiffs({ id: current.entry.id, path: current.path })[0] : null;
|
||||
const previewInput = previewDiff ? diffInput(previewDiff) : null;
|
||||
const tree = (
|
||||
<ShelfTree
|
||||
nodes={patches}
|
||||
kind="changes"
|
||||
selectedKey={entry?.id ?? null}
|
||||
nodes={nodes}
|
||||
selectedKey={selectedShelf}
|
||||
empty={loaded ? "No shelved changes" : "Loading…"}
|
||||
expanded={expandedKeys}
|
||||
onExpandedChange={updateExpanded}
|
||||
grouped={groupByDir}
|
||||
/>
|
||||
);
|
||||
return (
|
||||
@@ -826,6 +935,12 @@ export function ShelfPanel() {
|
||||
className={viewStyles.changes}
|
||||
ref={panelRef}
|
||||
data-shelf-panel
|
||||
onKeyDown={(e) => {
|
||||
if (e.defaultPrevented || e.altKey || e.ctrlKey || !current) return;
|
||||
if (e.key !== "Delete" && !(e.key === "Backspace" && e.metaKey)) return;
|
||||
e.preventDefault();
|
||||
void executeAction("vcs.shelf.delete", { id: current.entry.id, path: current.path });
|
||||
}}
|
||||
onFocusCapture={() => setContext("shelfFocus", true)}
|
||||
onBlurCapture={(e) => {
|
||||
if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setContext("shelfFocus", false);
|
||||
@@ -833,7 +948,6 @@ export function ShelfPanel() {
|
||||
>
|
||||
<div className={viewStyles.toolbar} role="toolbar" aria-label={tx("Shelf")}>
|
||||
<IconButton icon="refresh" action="vcs.shelf.refresh" size="small" />
|
||||
<IconButton icon="shelve" action="vcs.shelve" size="small" />
|
||||
<span className={viewStyles.sep} />
|
||||
<IconButton
|
||||
icon="unshelve"
|
||||
@@ -842,6 +956,71 @@ export function ShelfPanel() {
|
||||
disabled={!current}
|
||||
onClick={() => current && void executeAction("vcs.unshelve", { id: current.entry.id, path: current.path })}
|
||||
/>
|
||||
<IconButton
|
||||
ref={viewRef}
|
||||
icon="eye"
|
||||
title="View Options"
|
||||
size="small"
|
||||
aria-haspopup="menu"
|
||||
onClick={() => {
|
||||
const rect = viewRef.current?.getBoundingClientRect();
|
||||
if (!rect) return;
|
||||
showContextMenu({ x: rect.left, y: rect.bottom + 2 }, [
|
||||
{ kind: "header", label: "Group By" },
|
||||
{
|
||||
label: "Directory",
|
||||
checked: groupByDir,
|
||||
run: () => {
|
||||
const value = !groupByDir;
|
||||
setGroupByDir(value);
|
||||
saveShelfViewOption("groupByDir", value);
|
||||
},
|
||||
},
|
||||
...(changeModules.length > 0
|
||||
? [
|
||||
{
|
||||
label: "Module",
|
||||
checked: groupByModule,
|
||||
run: () => {
|
||||
const value = !groupByModule;
|
||||
setGroupByModule(value);
|
||||
saveShelfViewOption("groupByModule", value);
|
||||
},
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(nonModal
|
||||
? []
|
||||
: [
|
||||
{ kind: "separator" as const },
|
||||
{
|
||||
label: "Show Diff Preview",
|
||||
checked: diffPreview,
|
||||
run: () => {
|
||||
const value = !diffPreview;
|
||||
setDiffPreview(value);
|
||||
saveShelfViewOption("diffPreview", value);
|
||||
},
|
||||
},
|
||||
]),
|
||||
]);
|
||||
}}
|
||||
/>
|
||||
<IconButton
|
||||
icon="expand-all"
|
||||
title="Expand All"
|
||||
size="small"
|
||||
disabled={!allKeys.length}
|
||||
onClick={() => updateExpanded(new Set(allKeys))}
|
||||
/>
|
||||
<IconButton
|
||||
icon="collapse-all"
|
||||
title="Collapse All"
|
||||
size="small"
|
||||
disabled={!allKeys.length}
|
||||
onClick={() => updateExpanded(new Set())}
|
||||
/>
|
||||
<span className={viewStyles.sep} />
|
||||
<IconButton
|
||||
icon="trash"
|
||||
title="Delete"
|
||||
@@ -852,31 +1031,35 @@ export function ShelfPanel() {
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
{patches.length ? (
|
||||
{nodes.length && diffPreview ? (
|
||||
<SplitGroup
|
||||
id="shelf-panes"
|
||||
className={shelfStyles.split}
|
||||
orientation={stacked ? "vertical" : "horizontal"}
|
||||
storageKey={`openidea.vcs.shelf.layout.${stacked ? "stacked" : "sideBySide"}`}
|
||||
>
|
||||
<SplitPanel id="shelf-changes" defaultSize="50%" minSize="25%">
|
||||
{patchTree}
|
||||
<SplitPanel id="shelf-tree" defaultSize="50%" minSize="25%">
|
||||
{tree}
|
||||
</SplitPanel>
|
||||
<SplitHandle aria-label={tx("Resize shelf panes")} />
|
||||
<SplitPanel id="shelf-files" defaultSize="50%" minSize="25%">
|
||||
<div className={shelfStyles.filesHeader}>
|
||||
<T>Shelved files</T>
|
||||
</div>
|
||||
<ShelfTree
|
||||
nodes={files}
|
||||
kind="files"
|
||||
selectedKey={current?.path ? selectedShelf : null}
|
||||
empty={entry ? "No files" : "Select a shelf to view its files"}
|
||||
/>
|
||||
<SplitHandle aria-label={tx("Resize shelf preview")} />
|
||||
<SplitPanel id="shelf-preview" defaultSize="50%" minSize="25%">
|
||||
{previewInput ? (
|
||||
<DiffEditor input={previewInput} />
|
||||
) : (
|
||||
<EmptyState>
|
||||
<T>
|
||||
{!current?.path
|
||||
? "Select a file to preview its changes"
|
||||
: shelfDiffFiles[current.entry.id]
|
||||
? "No diff available for this file"
|
||||
: "Loading…"}
|
||||
</T>
|
||||
</EmptyState>
|
||||
)}
|
||||
</SplitPanel>
|
||||
</SplitGroup>
|
||||
) : (
|
||||
<div className={viewStyles.treeWrap}>{patchTree}</div>
|
||||
<div className={viewStyles.treeWrap}>{tree}</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -3830,9 +3830,8 @@
|
||||
"Resize rebase panes": "Resize rebase panes",
|
||||
"New message for {id}": "New message for {id}",
|
||||
"Resize right merge pane": "Resize right merge pane",
|
||||
"Resize shelf panes": "Resize shelf panes",
|
||||
"Shelved files": "Shelved files",
|
||||
"Select a shelf to view its files": "Select a shelf to view its files",
|
||||
"Resize shelf preview": "Resize shelf preview",
|
||||
"No diff available for this file": "No diff available for this file",
|
||||
"No files": "No files",
|
||||
"Database and schema": "Database and schema",
|
||||
"Loading…": "Loading…",
|
||||
@@ -4816,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",
|
||||
@@ -4830,5 +4834,19 @@
|
||||
"Create Library": "Create Library",
|
||||
"Library name": "Library name",
|
||||
"Library name cannot be empty.": "Library name cannot be empty.",
|
||||
"A library with this name already exists.": "A library with this name already exists."
|
||||
"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",
|
||||
"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}"
|
||||
}
|
||||
@@ -3320,8 +3320,8 @@
|
||||
"Shelve Changes": "Отложить изменения",
|
||||
"Shelve Changes…": "Отложить изменения…",
|
||||
"Shelved changes": "Отложенные изменения",
|
||||
"Shelved files": "Отложенные файлы",
|
||||
"Select a shelf to view its files": "Выберите полку для просмотра её файлов",
|
||||
"Resize shelf preview": "Изменить размер предпросмотра отложенных изменений",
|
||||
"No diff available for this file": "Для этого файла нет diff",
|
||||
"No files": "Нет файлов",
|
||||
"Show": "Показать",
|
||||
"Show \"Today\", \"Yesterday\" and \"N min ago\" for recent dates": "Показывать «Сегодня», «Вчера» и «N мин назад» для недавних дат",
|
||||
@@ -9845,7 +9845,6 @@
|
||||
"Resize left merge pane": "Изменить размер левой панели слияния",
|
||||
"Resize rebase panes": "Изменить размер панелей перебазирования",
|
||||
"Resize right merge pane": "Изменить размер правой панели слияния",
|
||||
"Resize shelf panes": "Изменить размер панелей отложенных изменений",
|
||||
"Database and schema": "База данных и схема",
|
||||
"Shelve Silently": "Отложить без подтверждения",
|
||||
"Unshelve Silently": "Восстановить без подтверждения",
|
||||
|
||||
@@ -2748,9 +2748,8 @@
|
||||
"Resize rebase panes": "Rebase bölmelerini yeniden boyutlandır",
|
||||
"New message for {id}": "{id} için yeni mesaj",
|
||||
"Resize right merge pane": "Sağ birleştirme bölmesini yeniden boyutlandır",
|
||||
"Resize shelf panes": "Raf bölmelerini yeniden boyutlandır",
|
||||
"Shelved files": "Rafa alınmış dosyalar",
|
||||
"Select a shelf to view its files": "Dosyalarını görüntülemek için bir raf seçin",
|
||||
"Resize shelf preview": "Raf önizlemesini yeniden boyutlandır",
|
||||
"No diff available for this file": "Bu dosya için fark yok",
|
||||
"No files": "Yok dosyaları",
|
||||
"Database and schema": "Veritabanı ve şema",
|
||||
"Loading…": "Yükleniyor…",
|
||||
|
||||
@@ -2923,8 +2923,8 @@
|
||||
"Shelve Changes": "擱置更改",
|
||||
"Shelve Changes…": "擱置更改…",
|
||||
"Shelved changes": "已擱置的更改",
|
||||
"Shelved files": "已擱置的檔案",
|
||||
"Select a shelf to view its files": "選擇一條擱置記錄以檢視檔案",
|
||||
"Resize shelf preview": "調整擱置記錄預覽大小",
|
||||
"No diff available for this file": "此檔案沒有可用的差異",
|
||||
"No files": "沒有檔案",
|
||||
"Show": "顯示",
|
||||
"Show \"Today\", \"Yesterday\" and \"N min ago\" for recent dates": "對最近的日期顯示「今天」、「昨天」和「N 分鐘前」",
|
||||
@@ -9281,7 +9281,6 @@
|
||||
"Resize left merge pane": "調整左側合併窗格寬度",
|
||||
"Resize rebase panes": "調整重定基底計劃和詳細資訊窗格大小",
|
||||
"Resize right merge pane": "調整右側合併窗格寬度",
|
||||
"Resize shelf panes": "調整擱置記錄和檔案窗格大小",
|
||||
"Database and schema": "資料庫和 schema",
|
||||
"Shelve Silently": "靜默擱置",
|
||||
"Unshelve Silently": "靜默取消擱置",
|
||||
@@ -9539,5 +9538,8 @@
|
||||
"Create Library": "建立庫",
|
||||
"Library name": "庫名稱",
|
||||
"Library name cannot be empty.": "庫名稱不可為空。",
|
||||
"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 登入了多個帳號。如果 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 設定"
|
||||
}
|
||||
@@ -3587,8 +3587,8 @@
|
||||
"Shelve Changes": "搁置更改",
|
||||
"Shelve Changes…": "搁置更改…",
|
||||
"Shelved changes": "已搁置的更改",
|
||||
"Shelved files": "已搁置的文件",
|
||||
"Select a shelf to view its files": "选择一条搁置记录以查看文件",
|
||||
"Resize shelf preview": "调整搁置记录预览大小",
|
||||
"No diff available for this file": "此文件没有可用的差异",
|
||||
"No files": "没有文件",
|
||||
"Show": "显示",
|
||||
"Show \"Today\", \"Yesterday\" and \"N min ago\" for recent dates": "对最近的日期显示“今天”、“昨天”和“N 分钟前”",
|
||||
@@ -10422,7 +10422,6 @@
|
||||
"Resize left merge pane": "调整左侧合并窗格宽度",
|
||||
"Resize rebase panes": "调整变基计划和详细信息窗格大小",
|
||||
"Resize right merge pane": "调整右侧合并窗格宽度",
|
||||
"Resize shelf panes": "调整搁置记录和文件窗格大小",
|
||||
"Database and schema": "数据库和 schema",
|
||||
"Shelve Silently": "静默搁置",
|
||||
"Unshelve Silently": "静默取消搁置",
|
||||
@@ -11495,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": "转到源定义",
|
||||
@@ -11527,5 +11531,19 @@
|
||||
"Create Library": "创建库",
|
||||
"Library name": "库名称",
|
||||
"Library name cannot be empty.": "库名称不能为空。",
|
||||
"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 登录了多个账号。如果 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 设置",
|
||||
"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}"
|
||||
}
|
||||
@@ -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, ""),
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
gitRevisionOf,
|
||||
isVirtualUri,
|
||||
@@ -6,8 +6,10 @@ import {
|
||||
libraryEntryPaths,
|
||||
virtualContainer,
|
||||
virtualName,
|
||||
virtualDocument,
|
||||
virtualParent,
|
||||
} from "./virtualDocs";
|
||||
import { commands } from "./ipc";
|
||||
import { basename, dirname, relativeDir, relativePath } from "./project";
|
||||
|
||||
const JDT =
|
||||
@@ -151,3 +153,23 @@ describe("Git revision URIs", () => {
|
||||
expect(gitRevisionOf("jdt://contents/x.jar/a/B.class")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("virtualDocument cache", () => {
|
||||
it("keeps the most recently used documents and fetches an evicted one again", async () => {
|
||||
const fetch = vi
|
||||
.spyOn(commands, "lspVirtualDocument")
|
||||
.mockImplementation(async (uri) => ({ status: "ok", data: { uri, text: uri } }) as never);
|
||||
const uris = Array.from({ length: 33 }, (_, i) => `jdt://contents/a${i}.class`);
|
||||
await virtualDocument(uris[0]!);
|
||||
// oxlint-disable-next-line no-await-in-loop -- the order of use is what the test checks
|
||||
for (const uri of uris.slice(1, 32)) await virtualDocument(uri);
|
||||
await virtualDocument(uris[0]!);
|
||||
expect(fetch).toHaveBeenCalledTimes(32);
|
||||
await virtualDocument(uris[32]!);
|
||||
await virtualDocument(uris[0]!);
|
||||
expect(fetch).toHaveBeenCalledTimes(33);
|
||||
await virtualDocument(uris[1]!);
|
||||
expect(fetch).toHaveBeenCalledTimes(34);
|
||||
fetch.mockRestore();
|
||||
});
|
||||
});
|
||||
@@ -97,6 +97,8 @@ export function virtualContainer(uri: string): string {
|
||||
return segs.join(" › ");
|
||||
}
|
||||
|
||||
/** Cached documents beyond this many are dropped, least recently used first. */
|
||||
const MAX_CACHED = 32;
|
||||
const cache = new Map<string, Promise<VirtualDocument>>();
|
||||
|
||||
export function invalidateVirtualDocument(uri: string): void {
|
||||
@@ -111,11 +113,14 @@ export function invalidateVirtualDocuments(): void {
|
||||
/** Contents of a virtual document (cached; failures are retried on the next call). */
|
||||
export function virtualDocument(uri: string): Promise<VirtualDocument> {
|
||||
let p = cache.get(uri);
|
||||
if (!p) {
|
||||
p = call(commands.lspVirtualDocument(uri));
|
||||
p.catch(() => cache.delete(uri));
|
||||
cache.set(uri, p);
|
||||
if (p) {
|
||||
cache.delete(uri);
|
||||
} else {
|
||||
const fetched = (p = call(commands.lspVirtualDocument(uri)));
|
||||
p.catch(() => cache.get(uri) === fetched && cache.delete(uri));
|
||||
}
|
||||
cache.set(uri, p);
|
||||
if (cache.size > MAX_CACHED) cache.delete(cache.keys().next().value!);
|
||||
return p;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Заблокувати користувача