дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-01 06:42:54 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
639adb6625 | ||
|
|
8ac194cf50 | ||
|
|
3b488a7824 | ||
|
|
b5e89aace0 | ||
|
|
81c95b2ab7 | ||
|
|
f7b5cc388c | ||
|
|
277d0e9d1e | ||
|
|
d6adb7aa40 | ||
|
|
6e5e482410 | ||
|
|
cc02c2fe40 | ||
|
|
74a3f6470a | ||
|
|
4c8c078666 | ||
|
|
e672b14d52 | ||
|
|
c0300f8959 | ||
|
|
11cf9864a1 |
No files matched your search
@@ -15,6 +15,7 @@
|
||||
"src/editor/core/cm/jsp/parser*.ts",
|
||||
"src/editor/core/cm/astro/parser*.ts",
|
||||
"src/editor/core/cm/django/parser*.ts",
|
||||
"src/editor/core/cm/freemarker/parser*.ts",
|
||||
"plugins/themes.md",
|
||||
"pnpm-lock.yaml",
|
||||
"**/*.toml",
|
||||
|
||||
@@ -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"] {
|
||||
|
||||
@@ -391,9 +391,12 @@ impl Manifest {
|
||||
if !self.capabilities.reasons.is_empty() {
|
||||
self.needs_api("`capabilities.reasons`", 19)?;
|
||||
}
|
||||
let derived = self.derived_capabilities();
|
||||
for (key, text) in &self.capabilities.reasons {
|
||||
if !self.capabilities.all().any(|c| c.to_string() == *key) {
|
||||
return Err(format!("capabilities.reasons: {key:?} is not under `required` or `optional`"));
|
||||
if !self.capabilities.all().chain(&derived).any(|c| c.to_string() == *key) {
|
||||
return Err(format!(
|
||||
"capabilities.reasons: {key:?} is not under `required` or `optional`, nor comes from a contribution"
|
||||
));
|
||||
}
|
||||
if text.trim().is_empty() || text.chars().count() > MAX_CAPABILITY_REASON {
|
||||
return Err(format!(
|
||||
@@ -522,6 +525,17 @@ impl Manifest {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Capabilities the plugin's contributions bring without being listed under `[capabilities]`:
|
||||
/// `java.agent` from `[[contributes.javaAgents]]`, `project.read` from
|
||||
/// `[[contributes.documentIndexers]]` (the extension points in `ide-host` add them to the grant).
|
||||
pub fn derived_capabilities(&self) -> Vec<Capability> {
|
||||
[("javaAgents", Capability::JavaAgent), ("documentIndexers", Capability::ProjectRead)]
|
||||
.into_iter()
|
||||
.filter(|(point, _)| self.contributes.contains_key(*point))
|
||||
.map(|(_, cap)| cap)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The declarations of one extension point: `[[contributes.x]]` gives
|
||||
/// several, `[contributes.x]` one.
|
||||
pub fn declarations(&self, point: &str) -> Vec<toml::Value> {
|
||||
@@ -843,6 +857,17 @@ required = [\"lsp:phoxite\"]
|
||||
assert!(err(&src(&long)).contains("1 to 500 characters"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capability_reasons_explain_capabilities_that_contributions_bring() {
|
||||
let src = |rest: &str| format!("{}{rest}", BASE.replace("^1.2", "^1.19"));
|
||||
let reason = "[capabilities.reasons]\n\"java.agent\" = \"Captures the SQL MyBatis runs.\"\n";
|
||||
let agent = "[[contributes.javaAgents]]\npath = \"agent.jar\"\n";
|
||||
let m = Manifest::parse(&src(&format!("{reason}{agent}"))).unwrap();
|
||||
assert_eq!(m.derived_capabilities(), [Capability::JavaAgent]);
|
||||
assert_eq!(m.capabilities.reason(&Capability::JavaAgent), Some("Captures the SQL MyBatis runs."));
|
||||
assert!(err(&src(reason)).contains("nor comes from a contribution"), "no javaAgents declaration");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_clipboard_read_capability_needs_api_1_11() {
|
||||
let caps = "[capabilities]\noptional = [\"clipboard.read\"]\n";
|
||||
|
||||
@@ -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**:
|
||||
|
||||
@@ -35,7 +35,7 @@ optional = ["net:127.0.0.1", "clipboard.read"]
|
||||
"clipboard.read" = "Imports a log you copied, on the Log to SQL tab only."
|
||||
```
|
||||
|
||||
The dialog and the plugin's details in **Settings › Plugins** show it below the IDE's description, marked as the plugin's own words; it never replaces that description. Keys must be capabilities listed under `required` or `optional`, and each reason is 1 to 500 characters. Translate it like the plugin's other strings, with the English text as the key in `locales/<tag>.json`.
|
||||
The dialog and the plugin's details in **Settings › Plugins** show it below the IDE's description, marked as the plugin's own words; it never replaces that description. Keys must be capabilities listed under `required` or `optional`, or ones a contribution brings (`java.agent` from `[[contributes.javaAgents]]`, `project.read` from `[[contributes.documentIndexers]]`), and each reason is 1 to 500 characters. Translate it like the plugin's other strings, with the English text as the key in `locales/<tag>.json`.
|
||||
|
||||
When code finds an optional capability refused, `host::open_permissions()` opens **Settings › Plugins** at the plugin's permissions, so a notice can offer a button that goes straight there (from a command or event only).
|
||||
|
||||
|
||||
@@ -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 解释器**,再选 **解释器类型**:
|
||||
|
||||
@@ -35,7 +35,7 @@ optional = ["net:127.0.0.1", "clipboard.read"]
|
||||
"clipboard.read" = "Imports a log you copied, on the Log to SQL tab only."
|
||||
```
|
||||
|
||||
授权对话框和 **设置 › 插件** 的插件详情会把这句话显示在 IDE 说明的下方,并标明是插件自己的说法;它不会替换 IDE 的说明。键必须是 `required` 或 `optional` 里列出的能力,每条 1 到 500 个字符。翻译方式与插件的其他字符串相同:在 `locales/<tag>.json` 里以英文原文为键。
|
||||
授权对话框和 **设置 › 插件** 的插件详情会把这句话显示在 IDE 说明的下方,并标明是插件自己的说法;它不会替换 IDE 的说明。键必须是 `required` 或 `optional` 里列出的能力,或者由贡献点带来的能力(`[[contributes.javaAgents]]` 带来的 `java.agent`、`[[contributes.documentIndexers]]` 带来的 `project.read`),每条 1 到 500 个字符。翻译方式与插件的其他字符串相同:在 `locales/<tag>.json` 里以英文原文为键。
|
||||
|
||||
代码发现某个 optional 能力被拒绝时,可以调用 `host::open_permissions()` 打开 **设置 › 插件** 并定位到本插件的权限,这样通知里可以放一个直接跳过去的按钮(仅限命令或事件中调用)。
|
||||
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -10,6 +10,7 @@ const config: KnipConfig = {
|
||||
"!src/editor/core/cm/jsp/parser.terms.ts",
|
||||
"!src/editor/core/cm/astro/parser.terms.ts",
|
||||
"!src/editor/core/cm/django/parser.terms.ts",
|
||||
"!src/editor/core/cm/freemarker/parser.terms.ts",
|
||||
"scripts/**/*.ts",
|
||||
"perf/**/*.ts",
|
||||
"evals/**/*.ts",
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
"gen:angular-grammar": "lezer-generator src/editor/core/cm/angular/angular.grammar --typeScript -o src/editor/core/cm/angular/parser.ts",
|
||||
"gen:jsp-grammar": "lezer-generator src/editor/core/cm/jsp/jsp.grammar --typeScript -o src/editor/core/cm/jsp/parser.ts",
|
||||
"gen:django-grammar": "lezer-generator src/editor/core/cm/django/django.grammar --typeScript -o src/editor/core/cm/django/parser.ts",
|
||||
"gen:freemarker-grammar": "lezer-generator src/editor/core/cm/freemarker/freemarker.grammar --typeScript -o src/editor/core/cm/freemarker/parser.ts",
|
||||
"gen:astro-grammar": "lezer-generator src/editor/core/cm/astro/astro.grammar --typeScript -o src/editor/core/cm/astro/parser.ts",
|
||||
"gen:theme-docs": "node scripts/theme/gen-docs.ts",
|
||||
"gen:plugin-catalog": "node scripts/gen-plugin-catalog.ts",
|
||||
|
||||
@@ -72,6 +72,10 @@ ide-android = { path = "../crates/ide-android" }
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
|
||||
[[test]]
|
||||
name = "background_tab_appkit"
|
||||
harness = false
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
block2 = "0.6"
|
||||
# Plugin secrets in the login keychain.
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
disallowed-methods = [
|
||||
{ path = "tauri::webview::WebviewWindow::with_webview", reason = "panics on a detached background tab on macOS; use macos::with_web_view" },
|
||||
{ path = "tauri::webview::Webview::with_webview", reason = "panics on a detached background tab on macOS; use macos::with_web_view" },
|
||||
]
|
||||
@@ -0,0 +1,71 @@
|
||||
//! AppKit side of a background tab's detached web view; no tauri types, so a test can include it.
|
||||
use objc2::{
|
||||
Message,
|
||||
rc::Retained,
|
||||
runtime::{AnyClass, ProtocolObject},
|
||||
};
|
||||
use objc2_app_kit::{
|
||||
NSView, NSWindow, NSWindowDidBecomeKeyNotification, NSWindowDidChangeOcclusionStateNotification,
|
||||
NSWindowOcclusionState, NSWindowOrderingMode,
|
||||
};
|
||||
use objc2_foundation::{NSNotificationCenter, NSObjectProtocol};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Return {
|
||||
Key,
|
||||
Visible,
|
||||
}
|
||||
|
||||
pub fn web_view(native: &NSWindow) -> Option<Retained<NSView>> {
|
||||
let class = AnyClass::get(c"WKWebView")?;
|
||||
native.contentView()?.subviews().iter().find(|v| v.isKindOfClass(class))
|
||||
}
|
||||
|
||||
/// At the bottom so the title bar views stay above it.
|
||||
pub fn put_back(native: &NSWindow, view: &NSView) {
|
||||
let Some(content) = native.contentView() else { return };
|
||||
view.setFrame(content.bounds());
|
||||
content.addSubview_positioned_relativeTo(view, NSWindowOrderingMode::Below, None);
|
||||
native.makeFirstResponder(Some(view));
|
||||
}
|
||||
|
||||
/// Calls `f` when the window becomes key, or visible (AppKit can bring a window back by itself,
|
||||
/// e.g. when a tab it closes next to leaves the group). The observers have no queue, so `f` runs
|
||||
/// synchronously inside the post. For the key notification that is inside `makeKeyWindow`, before the
|
||||
/// window's first display; occlusion arrives when the window is already on screen.
|
||||
pub fn on_return(
|
||||
native: &NSWindow,
|
||||
f: impl Fn(Return) + 'static,
|
||||
) -> Vec<Retained<ProtocolObject<dyn NSObjectProtocol>>> {
|
||||
let f = std::rc::Rc::new(f);
|
||||
let center = NSNotificationCenter::defaultCenter();
|
||||
let key = {
|
||||
let f = f.clone();
|
||||
let block = block2::RcBlock::new(move |_| f(Return::Key));
|
||||
unsafe {
|
||||
center.addObserverForName_object_queue_usingBlock(
|
||||
Some(NSWindowDidBecomeKeyNotification),
|
||||
Some(native),
|
||||
None,
|
||||
&block,
|
||||
)
|
||||
}
|
||||
};
|
||||
let visible = {
|
||||
let window: Retained<NSWindow> = native.retain();
|
||||
let block = block2::RcBlock::new(move |_| {
|
||||
if window.occlusionState().contains(NSWindowOcclusionState::Visible) {
|
||||
f(Return::Visible);
|
||||
}
|
||||
});
|
||||
unsafe {
|
||||
center.addObserverForName_object_queue_usingBlock(
|
||||
Some(NSWindowDidChangeOcclusionStateNotification),
|
||||
Some(native),
|
||||
None,
|
||||
&block,
|
||||
)
|
||||
}
|
||||
};
|
||||
vec![key, visible]
|
||||
}
|
||||
@@ -170,9 +170,9 @@ async fn webview_processes(app: &AppHandle, state: &AppState) -> Vec<MemoryRoot>
|
||||
let mut pending = Vec::new();
|
||||
for (label, w) in app.webview_windows() {
|
||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||
let sent = w.with_webview(move |pv| {
|
||||
// SAFETY: `with_webview` runs on the main thread with the live WKWebView.
|
||||
let _ = tx.send(unsafe { memory::webkit_process_ids(pv.inner()) });
|
||||
let sent = crate::macos::with_web_view(&w, move |view| {
|
||||
// SAFETY: runs on the main thread with the live WKWebView, detached or not.
|
||||
let _ = tx.send(unsafe { memory::webkit_process_ids(view) });
|
||||
});
|
||||
if sent.is_ok() {
|
||||
pending.push((label, rx));
|
||||
|
||||
@@ -233,6 +233,7 @@ pub fn window_flash_taskbar(window: WebviewWindow, flash: bool) -> IdeResult<()>
|
||||
#[specta::specta]
|
||||
pub fn window_set_smooth_scrolling(window: WebviewWindow, enabled: bool) -> IdeResult<()> {
|
||||
#[cfg(target_os = "linux")]
|
||||
#[allow(clippy::disallowed_methods)]
|
||||
window
|
||||
.with_webview(move |platform| crate::linux_webkit::set_smooth_scrolling(&platform, enabled))
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
#![recursion_limit = "512"]
|
||||
|
||||
mod application_focus;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod background_tab;
|
||||
mod cli;
|
||||
mod commands;
|
||||
#[cfg(debug_assertions)]
|
||||
@@ -308,6 +310,7 @@ pub fn run() {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
page_swipe::forget(window.label());
|
||||
macos::forget_background(window.label());
|
||||
titlebar::forget(window);
|
||||
}
|
||||
if windows::auxiliary_parent(window.label()).is_none() {
|
||||
|
||||
@@ -91,6 +91,7 @@ pub fn smooth_scrolling_plugin() -> tauri::plugin::TauriPlugin<tauri::Wry> {
|
||||
let enabled = webview
|
||||
.try_state::<crate::state::AppState>()
|
||||
.is_some_and(|s| s.global_settings.effective().appearance.smooth_scrolling);
|
||||
#[allow(clippy::disallowed_methods)]
|
||||
let _ = webview.with_webview(move |platform| set_smooth_scrolling(&platform, enabled));
|
||||
})
|
||||
.build()
|
||||
|
||||
@@ -1,15 +1,101 @@
|
||||
//! macOS project tabs: native window tab groups behind the page's own tab bar.
|
||||
use crate::background_tab::{self, Return};
|
||||
use crate::windows::{Launch, WindowsState};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_workspace::window_groups::{TabbingPreference, should_group_new_project};
|
||||
use objc2::{
|
||||
MainThreadMarker,
|
||||
rc::Retained,
|
||||
runtime::{AnyClass, AnyObject, Imp, Sel},
|
||||
runtime::{AnyClass, AnyObject, Imp, ProtocolObject, Sel},
|
||||
};
|
||||
use objc2_app_kit::{
|
||||
NSApplication, NSView, NSWindow, NSWindowOcclusionState, NSWindowOrderingMode, NSWindowStyleMask,
|
||||
NSWindowUserTabbingPreference,
|
||||
};
|
||||
use objc2_foundation::{NSNotificationCenter, NSObjectProtocol, NSOperationQueue};
|
||||
use std::{
|
||||
cell::{Cell, RefCell},
|
||||
collections::HashMap,
|
||||
ffi::c_void,
|
||||
time::Duration,
|
||||
};
|
||||
use objc2_app_kit::{NSWindow, NSWindowUserTabbingPreference};
|
||||
use tauri::{AppHandle, Manager, WebviewWindow};
|
||||
|
||||
/// WebKit frees a page's graphics 10 s and its caches 2 min after the page leaves its window.
|
||||
const DETACH_BACKGROUND_TAB_AFTER: Duration = Duration::from_secs(30);
|
||||
|
||||
enum Background<V> {
|
||||
Pending(u64),
|
||||
Detached(V),
|
||||
}
|
||||
|
||||
struct BackgroundTabs<V> {
|
||||
next: u64,
|
||||
tabs: HashMap<String, Background<V>>,
|
||||
}
|
||||
|
||||
impl<V> Default for BackgroundTabs<V> {
|
||||
fn default() -> Self {
|
||||
Self { next: 0, tabs: HashMap::new() }
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> BackgroundTabs<V> {
|
||||
/// None when the label already has an entry: a repeated select must not restart the clock.
|
||||
fn schedule(&mut self, label: &str) -> Option<u64> {
|
||||
if self.tabs.contains_key(label) {
|
||||
return None;
|
||||
}
|
||||
self.next += 1;
|
||||
self.tabs.insert(label.to_string(), Background::Pending(self.next));
|
||||
Some(self.next)
|
||||
}
|
||||
|
||||
fn due(&self, label: &str, generation: u64) -> bool {
|
||||
matches!(self.tabs.get(label), Some(Background::Pending(g)) if *g == generation)
|
||||
}
|
||||
|
||||
fn detached(&mut self, label: &str, view: V) {
|
||||
self.tabs.insert(label.to_string(), Background::Detached(view));
|
||||
}
|
||||
|
||||
fn cancel(&mut self, label: &str) {
|
||||
self.tabs.remove(label);
|
||||
}
|
||||
|
||||
fn view(&self, label: &str) -> Option<&V> {
|
||||
match self.tabs.get(label) {
|
||||
Some(Background::Detached(view)) => Some(view),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Also cancels a pending detach.
|
||||
fn attach(&mut self, label: &str) -> Option<V> {
|
||||
match self.tabs.remove(label) {
|
||||
Some(Background::Detached(view)) => Some(view),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct DetachedView {
|
||||
view: Retained<NSView>,
|
||||
observers: Vec<Retained<ProtocolObject<dyn NSObjectProtocol>>>,
|
||||
}
|
||||
|
||||
impl Drop for DetachedView {
|
||||
fn drop(&mut self) {
|
||||
for observer in &self.observers {
|
||||
unsafe { NSNotificationCenter::defaultCenter().removeObserver(observer.as_ref()) };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static BACKGROUND: RefCell<BackgroundTabs<DetachedView>> = RefCell::new(BackgroundTabs::default());
|
||||
}
|
||||
|
||||
fn tabbing_preference(app: &AppHandle) -> IdeResult<TabbingPreference> {
|
||||
fn read(mtm: MainThreadMarker) -> TabbingPreference {
|
||||
match NSWindow::userTabbingPreference(mtm) {
|
||||
@@ -83,6 +169,101 @@ fn same_group(a: &NSWindow, b: &NSWindow) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
fn schedule_detach(window: &WebviewWindow) {
|
||||
// The debug-only MCP bridge calls `with_webview` directly, which panics on a detached view.
|
||||
if cfg!(debug_assertions) {
|
||||
return;
|
||||
}
|
||||
let Some(generation) = BACKGROUND.with_borrow_mut(|tabs| tabs.schedule(window.label())) else { return };
|
||||
let target = window.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
tokio::time::sleep(DETACH_BACKGROUND_TAB_AFTER).await;
|
||||
let window = target.clone();
|
||||
let _ = window.run_on_main_thread(move || detach_if_background(&target, generation));
|
||||
});
|
||||
}
|
||||
|
||||
fn detach_if_background(window: &WebviewWindow, generation: u64) {
|
||||
if !BACKGROUND.with_borrow(|tabs| tabs.due(window.label(), generation)) {
|
||||
return;
|
||||
}
|
||||
let Some(native) = native(window) else { return };
|
||||
// A visible window is never a background tab.
|
||||
if native.occlusionState().contains(NSWindowOcclusionState::Visible) {
|
||||
BACKGROUND.with_borrow_mut(|tabs| tabs.cancel(window.label()));
|
||||
return;
|
||||
}
|
||||
// An inactive app's full-screen group can be mid-transition, where AppKit has crashed (#6937): wait for activation.
|
||||
let inactive = MainThreadMarker::new().is_some_and(|mtm| !NSApplication::sharedApplication(mtm).isActive());
|
||||
if inactive && native.styleMask().contains(NSWindowStyleMask::FullScreen) {
|
||||
BACKGROUND.with_borrow_mut(|tabs| tabs.cancel(window.label()));
|
||||
schedule_detach(window);
|
||||
return;
|
||||
}
|
||||
let view = (|| {
|
||||
let group = native.tabGroup()?;
|
||||
let selected = group.selectedWindow()?;
|
||||
let background = group.windows().count() > 1
|
||||
&& !std::ptr::eq(Retained::as_ptr(&selected), native)
|
||||
&& native.attachedSheet().is_none();
|
||||
background.then(|| background_tab::web_view(native)).flatten()
|
||||
})();
|
||||
let Some(view) = view else {
|
||||
BACKGROUND.with_borrow_mut(|tabs| tabs.cancel(window.label()));
|
||||
return;
|
||||
};
|
||||
view.removeFromSuperview();
|
||||
let target = window.clone();
|
||||
let observers = background_tab::on_return(native, move |why| {
|
||||
attach_for(&target, if why == Return::Key { "key" } else { "visible" }, true)
|
||||
});
|
||||
BACKGROUND.with_borrow_mut(|tabs| tabs.detached(window.label(), DetachedView { view, observers }));
|
||||
}
|
||||
|
||||
/// Puts a detached web view back and cancels a pending detach.
|
||||
pub fn attach(window: &WebviewWindow) {
|
||||
attach_for(window, "select", false);
|
||||
}
|
||||
|
||||
fn attach_for(window: &WebviewWindow, reason: &str, from_observer: bool) {
|
||||
let Some(detached) = BACKGROUND.with_borrow_mut(|tabs| tabs.attach(window.label())) else {
|
||||
return;
|
||||
};
|
||||
if let Some(native) = native(window) {
|
||||
background_tab::put_back(native, &detached.view);
|
||||
tracing::debug!(label = window.label(), reason, "re-attached background tab web view");
|
||||
}
|
||||
if from_observer {
|
||||
// Dropping removes the observer whose block is running; wait until the post returns.
|
||||
let detached = Cell::new(Some(detached));
|
||||
let block = block2::RcBlock::new(move || drop(detached.take()));
|
||||
unsafe { NSOperationQueue::mainQueue().addOperationWithBlock(&block) };
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls `f` on the main thread with the window's `WKWebView`, attached or not.
|
||||
/// tauri's webview size/position APIs (`core:webview:default` grants `webview_size`/`webview_position`) unwrap
|
||||
/// `superview()` in wry and are not safe while a tab is detached.
|
||||
pub fn with_web_view(window: &WebviewWindow, f: impl FnOnce(*mut c_void) + Send + 'static) -> tauri::Result<()> {
|
||||
let target = window.clone();
|
||||
window.run_on_main_thread(move || {
|
||||
// On the main thread tauri handles with_webview synchronously, so the tab cannot be detached between
|
||||
// the check and the call; wry's with_webview panics on a windowless view.
|
||||
let detached = BACKGROUND.with_borrow(|tabs| tabs.view(target.label()).map(|d| Retained::as_ptr(&d.view)));
|
||||
match detached {
|
||||
Some(view) => f(view as *mut c_void),
|
||||
None => {
|
||||
#[allow(clippy::disallowed_methods)]
|
||||
let _ = target.with_webview(move |w| f(w.inner()));
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn forget_background(label: &str) {
|
||||
BACKGROUND.with_borrow_mut(|tabs| tabs.cancel(label));
|
||||
}
|
||||
|
||||
/// Adds `members` to the existing anchor's native tab group and shows `selected`.
|
||||
pub fn sync_tab_group(
|
||||
members: Vec<WebviewWindow>,
|
||||
@@ -99,14 +280,18 @@ pub fn sync_tab_group(
|
||||
if let Some(window) = native(member)
|
||||
&& !same_group(anchor_window, window)
|
||||
{
|
||||
anchor_window.addTabbedWindow_ordered(window, objc2_app_kit::NSWindowOrderingMode::Above);
|
||||
anchor_window.addTabbedWindow_ordered(window, NSWindowOrderingMode::Above);
|
||||
}
|
||||
}
|
||||
attach(&target);
|
||||
if let Some(group) = shown.tabGroup() {
|
||||
group.setSelectedWindow(Some(shown));
|
||||
}
|
||||
shown.makeKeyAndOrderFront(None);
|
||||
for member in &members {
|
||||
if member.label() != target.label() {
|
||||
schedule_detach(member);
|
||||
}
|
||||
if let Some(window) = native(member) {
|
||||
hide_tab_bar(window);
|
||||
}
|
||||
@@ -129,6 +314,7 @@ pub fn move_tab_to_new_window(window: &WebviewWindow) -> tauri::Result<()> {
|
||||
let target = window.clone();
|
||||
on_main(window, move || {
|
||||
let Some(native) = native(&target) else { return };
|
||||
attach(&target);
|
||||
if native.tabbedWindows().is_some_and(|tabs| tabs.count() > 1) {
|
||||
native.moveTabToNewWindow(None);
|
||||
}
|
||||
@@ -226,3 +412,56 @@ pub fn native_modal_open() -> bool {
|
||||
let application = objc2_app_kit::NSApplication::sharedApplication(mtm);
|
||||
application.modalWindow().is_some() || application.windows().iter().any(|window| window.attachedSheet().is_some())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::BackgroundTabs;
|
||||
|
||||
#[test]
|
||||
fn repeated_schedule_keeps_the_first_generation() {
|
||||
let mut tabs = BackgroundTabs::<u32>::default();
|
||||
let first = tabs.schedule("a").unwrap();
|
||||
assert_eq!(tabs.schedule("a"), None);
|
||||
assert!(tabs.due("a", first));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attach_cancels_a_pending_detach() {
|
||||
let mut tabs = BackgroundTabs::<u32>::default();
|
||||
let generation = tabs.schedule("a").unwrap();
|
||||
assert_eq!(tabs.attach("a"), None);
|
||||
assert!(!tabs.due("a", generation));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_generation_is_not_due_after_reschedule() {
|
||||
let mut tabs = BackgroundTabs::<u32>::default();
|
||||
let stale = tabs.schedule("a").unwrap();
|
||||
tabs.attach("a");
|
||||
let fresh = tabs.schedule("a").unwrap();
|
||||
assert_ne!(stale, fresh);
|
||||
assert!(!tabs.due("a", stale));
|
||||
assert!(tabs.due("a", fresh));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn view_is_only_there_while_detached() {
|
||||
let mut tabs = BackgroundTabs::<&'static str>::default();
|
||||
tabs.schedule("a").unwrap();
|
||||
assert_eq!(tabs.view("a"), None);
|
||||
tabs.detached("a", "view");
|
||||
assert_eq!(tabs.view("a"), Some(&"view"));
|
||||
tabs.attach("a");
|
||||
assert_eq!(tabs.view("a"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attach_returns_the_detached_view_once() {
|
||||
let mut tabs = BackgroundTabs::<&'static str>::default();
|
||||
let generation = tabs.schedule("a").unwrap();
|
||||
tabs.detached("a", "view");
|
||||
assert!(!tabs.due("a", generation));
|
||||
assert_eq!(tabs.attach("a"), Some("view"));
|
||||
assert_eq!(tabs.attach("a"), None);
|
||||
}
|
||||
}
|
||||
@@ -33,9 +33,10 @@ fn stroke(window: &WebviewWindow, right: bool) {
|
||||
|
||||
pub fn install(window: &WebviewWindow) {
|
||||
let target = window.clone();
|
||||
let _ = window.with_webview(move |webview| {
|
||||
let view = unsafe { Retained::retain(webview.inner().cast::<NSView>()).unwrap() };
|
||||
let native = webview.ns_window() as usize;
|
||||
let _ = crate::macos::with_web_view(window, move |webview| {
|
||||
let view = unsafe { Retained::retain(webview.cast::<NSView>()).unwrap() };
|
||||
let Ok(native) = target.ns_window() else { return };
|
||||
let native = native as usize;
|
||||
let window = target.clone();
|
||||
let block = block2::RcBlock::new(move |event: NonNull<NSEvent>| {
|
||||
let event = unsafe { event.as_ref() };
|
||||
|
||||
@@ -458,10 +458,12 @@ fn track(window: &NSWindow, app: &tauri::AppHandle) -> Tracked {
|
||||
pub fn set_height(window: &tauri::WebviewWindow, height: f64) -> tauri::Result<()> {
|
||||
let label = window.label().to_owned();
|
||||
let app = window.app_handle().clone();
|
||||
// with_webview runs on the AppKit thread.
|
||||
window.with_webview(move |webview| unsafe {
|
||||
let target = window.clone();
|
||||
// The window's own handle works while a background tab's web view is detached.
|
||||
window.run_on_main_thread(move || unsafe {
|
||||
let Some(mtm) = MainThreadMarker::new() else { return };
|
||||
let native = &*webview.ns_window().cast::<NSWindow>();
|
||||
let Ok(native) = target.ns_window() else { return };
|
||||
let native = &*native.cast::<NSWindow>();
|
||||
let (state, buttons, strip) = WINDOWS.with_borrow_mut(|windows| {
|
||||
let tracked = windows.entry(label).or_insert_with(|| track(native, &app));
|
||||
tracked.height.set(height);
|
||||
|
||||
@@ -2764,8 +2764,8 @@ fn disable_macos_text_input_selection_updates(preferences: &objc2_web_kit::WKPre
|
||||
/// suppresses the affordance even if `NSTextInputContext` queries the view directly.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn suppress_window_writing_tools_affordance(window: &WebviewWindow) {
|
||||
let _ = window.with_webview(|webview| unsafe {
|
||||
let ptr = webview.inner().cast::<objc2::runtime::AnyObject>();
|
||||
let _ = crate::macos::with_web_view(window, |webview| unsafe {
|
||||
let ptr = webview.cast::<objc2::runtime::AnyObject>();
|
||||
if !ptr.is_null() {
|
||||
let cls = (*ptr).class();
|
||||
suppress_webview_class_writing_tools_affordance(cls);
|
||||
|
||||
@@ -11,6 +11,7 @@ pub fn init() -> plugin::TauriPlugin<Wry> {
|
||||
plugin::Builder::new("webview-keys").on_webview_ready(disable_browser_keys).build()
|
||||
}
|
||||
|
||||
#[allow(clippy::disallowed_methods)]
|
||||
fn disable_browser_keys(webview: Webview) {
|
||||
let label = webview.label().to_owned();
|
||||
if let Err(error) = webview.with_webview(move |platform| {
|
||||
|
||||
@@ -50,6 +50,7 @@ pub fn init() -> plugin::TauriPlugin<Wry> {
|
||||
.build()
|
||||
}
|
||||
|
||||
#[allow(clippy::disallowed_methods)]
|
||||
fn install(webview: Webview) {
|
||||
let app = webview.app_handle().clone();
|
||||
let label = webview.label().to_owned();
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn main() {}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[path = "../src/background_tab.rs"]
|
||||
mod background_tab;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[link(name = "WebKit", kind = "framework")]
|
||||
unsafe extern "C" {}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn main() {
|
||||
// nextest runs a harness-less binary as `--list --format terse [--ignored]`, then `<name> --exact --nocapture`.
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
if args.iter().any(|a| a == "--list") {
|
||||
if !args.iter().any(|a| a == "--ignored") {
|
||||
println!("background_tab_appkit: test");
|
||||
}
|
||||
return;
|
||||
}
|
||||
use background_tab::Return;
|
||||
use objc2::{MainThreadMarker, msg_send, rc::Retained, runtime::AnyClass};
|
||||
use objc2_app_kit::{
|
||||
NSApplication, NSBackingStoreType, NSView, NSWindow, NSWindowDidBecomeKeyNotification, NSWindowStyleMask,
|
||||
};
|
||||
use objc2_foundation::{NSNotificationCenter, NSPoint, NSRect, NSSize};
|
||||
use std::{cell::Cell, rc::Rc};
|
||||
|
||||
let mtm = MainThreadMarker::new().expect("main thread");
|
||||
let _app = NSApplication::sharedApplication(mtm);
|
||||
let rect = NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(400.0, 300.0));
|
||||
let window = unsafe {
|
||||
NSWindow::initWithContentRect_styleMask_backing_defer(
|
||||
mtm.alloc(),
|
||||
rect,
|
||||
NSWindowStyleMask::Titled,
|
||||
NSBackingStoreType::Buffered,
|
||||
false,
|
||||
)
|
||||
};
|
||||
let class = AnyClass::get(c"WKWebView").expect("WebKit is linked");
|
||||
let web: Retained<NSView> = unsafe { msg_send![msg_send![class, alloc], initWithFrame: rect] };
|
||||
window.contentView().unwrap().addSubview(&web);
|
||||
|
||||
let view = background_tab::web_view(&window).expect("web view in content view");
|
||||
view.removeFromSuperview();
|
||||
assert!(view.window().is_none());
|
||||
// Not asked for its process ids: on a web view that never loaded a page, WebKit asserts in
|
||||
// `_networkProcessIdentifier` (macOS 15), which a real tab never is.
|
||||
|
||||
let reason = Rc::new(Cell::new(None));
|
||||
let observers = {
|
||||
let (reason, window, view) = (reason.clone(), window.clone(), view.clone());
|
||||
background_tab::on_return(&window.clone(), move |why| {
|
||||
background_tab::put_back(&window, &view);
|
||||
reason.set(Some(why));
|
||||
})
|
||||
};
|
||||
unsafe {
|
||||
NSNotificationCenter::defaultCenter()
|
||||
.postNotificationName_object(NSWindowDidBecomeKeyNotification, Some(&window));
|
||||
}
|
||||
assert_eq!(reason.get(), Some(Return::Key));
|
||||
assert!(view.window().is_some_and(|w| Retained::as_ptr(&w) == Retained::as_ptr(&window)));
|
||||
for observer in &observers {
|
||||
unsafe { NSNotificationCenter::defaultCenter().removeObserver(observer.as_ref()) };
|
||||
}
|
||||
println!("ok: re-attached synchronously inside the key notification");
|
||||
}
|
||||
@@ -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. */
|
||||
|
||||
@@ -1,154 +0,0 @@
|
||||
/**
|
||||
* FreeMarker editor mode: HTML outside the template syntax, FreeMarker inside
|
||||
* directives (`<#if …>`, `<@macro …/>`), interpolations (`${…}`) and comments.
|
||||
* The first directive fixes the tag syntax, angle (`<#if>`) or square (`[#if]`),
|
||||
* as FreeMarker itself does; `[=…]` interpolations count only in square syntax.
|
||||
*/
|
||||
import { LanguageSupport, StreamLanguage, StringStream, type StreamParser } from "@codemirror/language";
|
||||
import { tags } from "@lezer/highlight";
|
||||
|
||||
type State<H> = {
|
||||
html: H;
|
||||
mode: "comment" | "directive" | "interpolation" | null;
|
||||
/** Tag syntax: `null` until the first directive, then square or not. */
|
||||
square: boolean | null;
|
||||
/** What ends the current comment, directive or interpolation. */
|
||||
close: string;
|
||||
/** Brackets open inside the expression; the closer counts only at 0. */
|
||||
depth: number;
|
||||
/** The directive's name comes next. */
|
||||
name: "#" | "@" | null;
|
||||
};
|
||||
|
||||
// `(?=…)` lookahead only: WebKit lacks lookbehind.
|
||||
const OPENER = /<#--|\[#--|<\/?[#@](?=[A-Za-z_])|\[\/?[#@](?=[A-Za-z_])|\$\{|\[=/g;
|
||||
const KEYWORDS = new Set(["as", "in", "using", "gt", "gte", "lt", "lte"]);
|
||||
|
||||
function nextOpener(line: string, from: number, square: boolean | null): RegExpExecArray | null {
|
||||
OPENER.lastIndex = from;
|
||||
for (let m = OPENER.exec(line); m; m = OPENER.exec(line)) {
|
||||
const text = m[0];
|
||||
if (text === "${") return m;
|
||||
if (text === "[=" ? square === true : square === null || square === (text[0] === "[")) return m;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function tokenComment<H>(stream: StringStream, state: State<H>): string {
|
||||
const end = stream.string.indexOf(state.close, stream.pos);
|
||||
stream.pos = end < 0 ? stream.string.length : end + state.close.length;
|
||||
if (end >= 0) state.mode = null;
|
||||
return "comment";
|
||||
}
|
||||
|
||||
function tokenExpression<H>(stream: StringStream, state: State<H>): string | null {
|
||||
if (stream.eatSpace()) return null;
|
||||
if (state.depth === 0 && stream.match(state.close)) {
|
||||
state.mode = null;
|
||||
return "ftlDelimiter";
|
||||
}
|
||||
if (state.depth === 0 && state.mode === "directive" && stream.match("/" + state.close)) {
|
||||
state.mode = null;
|
||||
return "ftlDelimiter";
|
||||
}
|
||||
if (stream.match(/^r?"(?:[^"\\]|\\.)*"?/) || stream.match(/^r?'(?:[^'\\]|\\.)*'?/)) return "string";
|
||||
if (stream.match(/^\d+(?:\.\d+)?/)) return "number";
|
||||
if (stream.match("??")) return "operator";
|
||||
if (stream.match(/^\?[A-Za-z_]\w*/)) return "ftlBuiltin";
|
||||
if (stream.match(/^\.[A-Za-z_]\w*/)) return "propertyName";
|
||||
if (stream.match(/^[A-Za-z_$][\w$]*/)) {
|
||||
const word = stream.current();
|
||||
if (word === "true" || word === "false") return "bool";
|
||||
return KEYWORDS.has(word) ? "keyword" : "variableName";
|
||||
}
|
||||
const ch = stream.next()!;
|
||||
if ("([{".includes(ch)) {
|
||||
state.depth++;
|
||||
return "bracket";
|
||||
}
|
||||
if (")]}".includes(ch)) {
|
||||
state.depth = Math.max(0, state.depth - 1);
|
||||
return "bracket";
|
||||
}
|
||||
if (ch === "." && stream.match(/^\.[<!*]?/)) return "operator";
|
||||
return "+-*/%!=<>&|:,;.".includes(ch) ? "operator" : null;
|
||||
}
|
||||
|
||||
function freemarkerParser<H>(html: StreamParser<H>): StreamParser<State<H>> {
|
||||
const copy = (state: H): H =>
|
||||
html.copyState
|
||||
? html.copyState(state)
|
||||
: (Object.fromEntries(
|
||||
Object.entries(state as object).map(([k, v]) => [k, Array.isArray(v) ? v.slice() : v]),
|
||||
) as H);
|
||||
|
||||
/** Runs the HTML mode on `stream` cut at `end`, then advances `stream` to where it stopped. */
|
||||
const tokenHtml = (stream: StringStream, end: number, state: H): string | null => {
|
||||
const sub = new StringStream(stream.string.slice(0, end), 4, stream.indentUnit);
|
||||
sub.pos = stream.pos;
|
||||
sub.start = stream.start;
|
||||
const style = html.token(sub, state);
|
||||
stream.pos = Math.max(sub.pos, stream.pos + (sub.pos === stream.pos ? 1 : 0));
|
||||
return style;
|
||||
};
|
||||
|
||||
return {
|
||||
name: "freemarker",
|
||||
languageData: { ...html.languageData, commentTokens: { block: { open: "<#--", close: "-->" } } },
|
||||
tokenTable: {
|
||||
...html.tokenTable,
|
||||
ftlDelimiter: tags.special(tags.brace),
|
||||
ftlBuiltin: tags.standard(tags.function(tags.variableName)),
|
||||
ftlMacro: tags.function(tags.variableName),
|
||||
},
|
||||
startState: (indentUnit) => ({
|
||||
html: html.startState!(indentUnit),
|
||||
mode: null,
|
||||
square: null,
|
||||
close: "",
|
||||
depth: 0,
|
||||
name: null,
|
||||
}),
|
||||
copyState: (s) => ({ ...s, html: copy(s.html) }),
|
||||
blankLine: (s, unit) => (s.mode ? undefined : html.blankLine?.(s.html, unit)),
|
||||
indent: (s, text, cx) => (s.mode ? null : (html.indent?.(s.html, text, cx) ?? null)),
|
||||
token(stream, state) {
|
||||
if (state.mode === "comment") return tokenComment(stream, state);
|
||||
if (state.name) {
|
||||
const sigil = state.name;
|
||||
state.name = null;
|
||||
if (stream.match(/^[A-Za-z_][\w.:-]*/)) return sigil === "#" ? "keyword" : "ftlMacro";
|
||||
}
|
||||
if (state.mode) return tokenExpression(stream, state);
|
||||
|
||||
const open = nextOpener(stream.string, stream.pos, state.square);
|
||||
if (open?.index !== stream.pos) {
|
||||
return tokenHtml(stream, open ? open.index : stream.string.length, state.html);
|
||||
}
|
||||
const text = open[0];
|
||||
stream.pos += text.length;
|
||||
const square = text[0] === "[";
|
||||
state.depth = 0;
|
||||
if (text.endsWith("--")) {
|
||||
state.mode = "comment";
|
||||
state.close = square ? "--]" : "-->";
|
||||
return tokenComment(stream, state);
|
||||
}
|
||||
if (text === "${" || text === "[=") {
|
||||
state.mode = "interpolation";
|
||||
state.close = text === "${" ? "}" : "]";
|
||||
return "ftlDelimiter";
|
||||
}
|
||||
state.square ??= square;
|
||||
state.mode = "directive";
|
||||
state.close = square ? "]" : ">";
|
||||
state.name = text.endsWith("@") ? "@" : "#";
|
||||
return "ftlDelimiter";
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function freemarker(): Promise<LanguageSupport> {
|
||||
const { html } = await import("@codemirror/legacy-modes/mode/xml");
|
||||
return new LanguageSupport(StreamLanguage.define(freemarkerParser(html)));
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
// FreeMarker templates: the template layer. Directives (`<#if …>`), user-defined
|
||||
// directive calls (`<@badge …/>`), interpolations (`${…}`) and comments are parsed
|
||||
// here; the text between them is HTML, mounted by `./index.ts`. The first directive
|
||||
// fixes the tag syntax, angle (`<#if>`) or square (`[#if]`), as FreeMarker does.
|
||||
// Block directives nest (`<#if>…<#elseif>…<#else>…</#if>`); others stand alone.
|
||||
// Regenerate with `pnpm gen:freemarker-grammar`.
|
||||
|
||||
@context blocks from "./tokens"
|
||||
|
||||
@top Template { node* }
|
||||
|
||||
node {
|
||||
Text |
|
||||
Comment |
|
||||
Interpolation |
|
||||
Tag |
|
||||
Element |
|
||||
RawElement |
|
||||
StrayEndTag
|
||||
}
|
||||
|
||||
// A block directive or user-defined directive call, its middle tags
|
||||
// (`elseif`, `else`, `recover`, `case`…) and its end tag.
|
||||
Element { OpenTag node* (MidTag node*)* EndTag }
|
||||
|
||||
// `<#noparse>…</#noparse>`, `<#comment>…</#comment>`: the content is not parsed.
|
||||
RawElement { RawTag RawBody? EndTag }
|
||||
|
||||
@skip { space } {
|
||||
OpenTag { OpenTagStart tagName argument* TagEnd }
|
||||
RawTag { RawTagStart tagName argument* TagEnd }
|
||||
MidTag { MidTagStart tagName argument* (TagEnd | SelfCloseEnd) }
|
||||
EndTag { EndTagStart tagName? TagEnd }
|
||||
// An end tag without its start tag, or of a directive that may or may not be a block (`</#sep>`).
|
||||
StrayEndTag { StrayEndTagStart tagName? TagEnd }
|
||||
Tag { TagStart tagName argument* (TagEnd | SelfCloseEnd) }
|
||||
|
||||
Interpolation { InterpolationStart argument* InterpolationEnd }
|
||||
|
||||
argument {
|
||||
VariableName |
|
||||
Member { "." PropertyName } |
|
||||
BuiltIn { "?" BuiltInName } |
|
||||
String |
|
||||
Number |
|
||||
Operator |
|
||||
CompareOp |
|
||||
kw<"as"> | kw<"in"> | kw<"using"> |
|
||||
kw<"gt"> | kw<"gte"> | kw<"lt"> | kw<"lte"> |
|
||||
@specialize[@name=BooleanLiteral]<identifier, "true" | "false"> |
|
||||
ParenGroup { "(" argument* ")" } |
|
||||
BracketGroup { "[" argument* "]" } |
|
||||
HashGroup { "{" argument* "}" }
|
||||
}
|
||||
}
|
||||
|
||||
tagName { DirectiveName | MacroName }
|
||||
|
||||
VariableName { identifier }
|
||||
|
||||
PropertyName { identifier }
|
||||
|
||||
BuiltInName { identifier }
|
||||
|
||||
kw<term> { @specialize[@name={term}]<identifier, term> }
|
||||
|
||||
// Tried in this order, before the tokens below.
|
||||
@external tokens comment from "./tokens" { Comment }
|
||||
@external tokens rawBody from "./tokens" { RawBody }
|
||||
@external tokens text from "./tokens" { Text }
|
||||
@external tokens tagStart from "./tokens" {
|
||||
OpenTagStart, RawTagStart, MidTagStart, EndTagStart, StrayEndTagStart, TagStart, InterpolationStart
|
||||
}
|
||||
@external tokens tagName from "./tokens" { DirectiveName, MacroName }
|
||||
@external tokens tagEnd from "./tokens" { TagEnd, SelfCloseEnd, InterpolationEnd }
|
||||
|
||||
@tokens {
|
||||
space { $[ \t\n\r]+ }
|
||||
|
||||
identifier { $[a-zA-Z_$\u{a1}-\u{10ffff}] $[a-zA-Z0-9_$\u{a1}-\u{10ffff}]* }
|
||||
|
||||
Number { @digit+ ("." @digit+)? }
|
||||
|
||||
String {
|
||||
"r"? '"' (!["\\] | "\\" _)* '"'? |
|
||||
"r"? "'" (!['\\] | "\\" _)* "'"?
|
||||
}
|
||||
|
||||
Operator {
|
||||
"+" | "-" | "*" | "/" | "%" | "!" | "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "++" | "--" |
|
||||
"&&" | "||" | "&" | "|" | "??" | ".." | "..<" | "..!" | "..*" | "," | ":" | ";" | "->"
|
||||
}
|
||||
|
||||
CompareOp { "==" | "!=" | "<" | "<=" | ">=" | ">" }
|
||||
|
||||
@precedence { String, identifier }
|
||||
|
||||
"." "?" "(" ")" "[" "]" "{" "}"
|
||||
}
|
||||
|
||||
@detectDelim
|
||||
@@ -0,0 +1,202 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { EditorSelection, EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { CompletionContext, type CompletionResult, type CompletionSource } from "@codemirror/autocomplete";
|
||||
import { foldable, getIndentation, indentUnit, matchBrackets } from "@codemirror/language";
|
||||
import { buildParserFile } from "@lezer/generator";
|
||||
import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight";
|
||||
import { completedSyntaxState, completedSyntaxTree } from "@/test/syntax";
|
||||
import { commentBlock } from "../comments";
|
||||
import { freemarker, freemarkerLanguage } from "./index";
|
||||
|
||||
const highlighter = tagHighlighter([
|
||||
{ tag: t.special(t.brace), class: "delim" },
|
||||
{ tag: t.blockComment, class: "comment" },
|
||||
{ tag: t.keyword, class: "keyword" },
|
||||
{ tag: t.variableName, class: "var" },
|
||||
{ tag: t.propertyName, class: "prop" },
|
||||
{ tag: t.attributeName, class: "attr" },
|
||||
{ tag: t.string, class: "str" },
|
||||
{ tag: t.tagName, class: "tag" },
|
||||
]);
|
||||
|
||||
function state(doc: string, selection?: number): EditorState {
|
||||
return completedSyntaxState(
|
||||
EditorState.create({
|
||||
doc,
|
||||
selection: selection == undefined ? undefined : EditorSelection.cursor(selection),
|
||||
extensions: [freemarker(), indentUnit.of(" ")],
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** `text:class` of the styled tokens of `doc`, HTML and embedded languages included. */
|
||||
function tokens(doc: string): string[] {
|
||||
const out: string[] = [];
|
||||
highlightTree(completedSyntaxTree(state(doc)), highlighter, (from, to, cls) =>
|
||||
out.push(`${doc.slice(from, to)}:${cls}`),
|
||||
);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The error nodes of `doc`'s template layer, with the text they start. */
|
||||
function errors(doc: string): string[] {
|
||||
const out: string[] = [];
|
||||
freemarkerLanguage.parser.parse(doc).iterate({
|
||||
enter: (node) => void (node.type.isError && out.push(doc.slice(node.from, node.from + 12))),
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
const outline = (doc: string) => freemarkerLanguage.parser.parse(doc).toString();
|
||||
|
||||
/** A view on `doc` with `|` marking the caret. */
|
||||
function view(marked: string): EditorView {
|
||||
const at = marked.indexOf("|");
|
||||
return new EditorView({ state: state(marked.slice(0, at) + marked.slice(at + 1), at) });
|
||||
}
|
||||
|
||||
/** Types `text` at the caret through the input handlers, like a keystroke. */
|
||||
function type(v: EditorView, text: string): string {
|
||||
const { from, to } = v.state.selection.main;
|
||||
const handled = v.state.facet(EditorView.inputHandler).some((h) => h(v, from, to, text, () => v.state.update({})));
|
||||
if (!handled)
|
||||
v.dispatch({ changes: { from, to, insert: text }, selection: EditorSelection.cursor(from + text.length) });
|
||||
const head = v.state.selection.main.head;
|
||||
return v.state.sliceDoc(0, head) + "|" + v.state.sliceDoc(head);
|
||||
}
|
||||
|
||||
/** The labels completion offers at the end of `doc`. */
|
||||
function complete(doc: string): string[] | undefined {
|
||||
const s = state(doc);
|
||||
const sources = s.languageDataAt<CompletionSource>("autocomplete", doc.length);
|
||||
const result = sources.map((src) => src(new CompletionContext(s, doc.length, true))).find(Boolean) as
|
||||
| CompletionResult
|
||||
| undefined;
|
||||
return result?.options.map((o) => o.label);
|
||||
}
|
||||
|
||||
describe("FreeMarker template layer", () => {
|
||||
it("nests block directives with their middle tags and leaves other directives alone", () => {
|
||||
expect(outline("<#if a>x<#elseif b>y<#else>z</#if><#assign n = 1>")).toBe(
|
||||
"Template(Element(OpenTag(OpenTagStart,DirectiveName,VariableName,TagEnd),Text," +
|
||||
"MidTag(MidTagStart,DirectiveName,VariableName,TagEnd),Text,MidTag(MidTagStart,DirectiveName,TagEnd),Text," +
|
||||
"EndTag(EndTagStart,DirectiveName,TagEnd)),Tag(TagStart,DirectiveName,VariableName,Operator,Number,TagEnd))",
|
||||
);
|
||||
// `assign` without `=` captures its content; a call with content is a block, one without isn't.
|
||||
expect(outline("<#assign x>v</#assign><@m/><@m>c</@m>")).toMatch(
|
||||
/^Template\(Element\(.*\),Tag\(.*SelfCloseEnd\),Element\(.*\)\)$/,
|
||||
);
|
||||
});
|
||||
|
||||
it("doesn't parse the content of noparse and comment", () => {
|
||||
expect(outline("<#noparse><#if>${x}</#noparse>")).toBe(
|
||||
"Template(RawElement(RawTag(RawTagStart,DirectiveName,TagEnd),RawBody,EndTag(EndTagStart,DirectiveName,TagEnd)))",
|
||||
);
|
||||
});
|
||||
|
||||
it("parses common templates without errors", () => {
|
||||
const doc = [
|
||||
'<#ftl output_format="HTML">',
|
||||
'<#import "/lib/ui.ftl" as ui>',
|
||||
"<#macro row item><tr><td>${item.name}</td></tr></#macro>",
|
||||
"<#function total xs><#local s = 0><#list xs as x><#local s += x.price></#list><#return s></#function>",
|
||||
"<#list orders?filter(o -> o.paid) as order><@row item=order/><#sep>, </#sep><#else>none</#list>",
|
||||
'<#switch kind><#case "a">A<#break><#default>B</#switch>',
|
||||
"<#attempt>${risky}<#recover>failed</#attempt>",
|
||||
"<#if (a > 1) && b?? && c?has_content>${a..<5}</#if>",
|
||||
'<@ui.card title="x" items=[1, 2] opts={"k": true}>c</@ui.card>',
|
||||
"<#list map as k, v>${k}=${v}</#list>",
|
||||
].join("\n");
|
||||
expect(errors(doc)).toEqual([]);
|
||||
});
|
||||
|
||||
it("highlights script and style content as JavaScript and CSS", () => {
|
||||
const out = tokens('<script>let a = "${x}";</script><style>p { color: red }</style>');
|
||||
expect(out).toContain("let:keyword");
|
||||
expect(out).toContain("x:var");
|
||||
expect(out).toContain("color:prop");
|
||||
});
|
||||
|
||||
it("nests markup across directives", () => {
|
||||
const out = tokens('<#if a><div class="x"></#if><#if a></div></#if>');
|
||||
expect(out.filter((t) => t == "div:tag")).toHaveLength(2);
|
||||
expect(out).toContain("class:attr");
|
||||
});
|
||||
|
||||
it("is generated from freemarker.grammar", () => {
|
||||
const dir = import.meta.dirname;
|
||||
const { parser, terms } = buildParserFile(readFileSync(resolve(dir, "freemarker.grammar"), "utf8"), {
|
||||
fileName: "src/editor/core/cm/freemarker/freemarker.grammar",
|
||||
moduleStyle: "es",
|
||||
typeScript: true,
|
||||
});
|
||||
const lf = (s: string) => s.replace(/\r\n/g, "\n");
|
||||
expect(lf(parser)).toBe(lf(readFileSync(resolve(dir, "parser.ts"), "utf8")));
|
||||
expect(lf(terms)).toBe(lf(readFileSync(resolve(dir, "parser.terms.ts"), "utf8")));
|
||||
});
|
||||
});
|
||||
|
||||
describe("FreeMarker template editing", () => {
|
||||
it("folds blocks", () => {
|
||||
const doc = "<#list xs as x>\n <p>${x}</p>\n</#list>\n";
|
||||
expect(foldable(state(doc), 0, doc.indexOf("\n"))).toEqual({ from: doc.indexOf(">") + 1, to: doc.indexOf("</#") });
|
||||
});
|
||||
|
||||
it("indents a block's content and puts its middle and end tags back", () => {
|
||||
const s = state("<#if a>\nx\n<#else>\ny\n</#if>");
|
||||
const lineStart = (n: number) => s.doc.line(n).from;
|
||||
expect(getIndentation(s, lineStart(2))).toBe(2);
|
||||
expect(getIndentation(s, lineStart(3))).toBe(0);
|
||||
expect(getIndentation(s, lineStart(4))).toBe(2);
|
||||
expect(getIndentation(s, lineStart(5))).toBe(0);
|
||||
});
|
||||
|
||||
it("matches a block directive with its end tag", () => {
|
||||
const doc = "<#list xs as x>${x}</#list>";
|
||||
const match = matchBrackets(state(doc), 3, 1);
|
||||
expect(match?.matched).toBe(true);
|
||||
expect(doc.slice(match!.end!.from, match!.end!.to)).toBe("list");
|
||||
});
|
||||
|
||||
it("adds the end tag of a block directive when its > is typed", () => {
|
||||
expect(type(view("<#if a|"), ">")).toBe("<#if a>|</#if>");
|
||||
expect(type(view("<@card title=t|"), ">")).toBe("<@card title=t>|</@card>");
|
||||
expect(type(view("[#ftl][#list xs as x|"), "]")).toBe("[#ftl][#list xs as x]|[/#list]");
|
||||
// It has one already.
|
||||
expect(type(view("<#if a|\n</#if>"), ">")).toBe("<#if a>|\n</#if>");
|
||||
// Not a block, or closed by `/>`.
|
||||
expect(type(view("<#include 'a.ftl'|"), ">")).toBe("<#include 'a.ftl'>|");
|
||||
expect(type(view("<@card /|"), ">")).toBe("<@card />|");
|
||||
// A capturing assign only without `=`.
|
||||
expect(type(view("<#assign x|"), ">")).toBe("<#assign x>|</#assign>");
|
||||
// Not in a script.
|
||||
expect(type(view("<script>if (a <#b|</script>"), ">")).toBe("<script>if (a <#b>|</script>");
|
||||
});
|
||||
|
||||
it("completes directives, the open blocks' end tags and built-ins", () => {
|
||||
expect(complete("<p><#")).toContain("list");
|
||||
expect(complete("<#list xs as x><@card><#if a></")).toEqual(["#if", "@card", "#list"]);
|
||||
expect(complete("<#list xs as x><@card><#if a></#")).toEqual(["#if", "@card", "#list"]);
|
||||
expect(complete("${name?")).toContain("upper_case");
|
||||
expect(complete("<p>Why?")).not.toContain("upper_case");
|
||||
});
|
||||
|
||||
it("comments with <#-- -->", () => {
|
||||
const v = view("|<p>a</p>");
|
||||
v.dispatch({ selection: EditorSelection.range(0, v.state.doc.length) });
|
||||
commentBlock(v);
|
||||
expect(v.state.doc.toString()).toBe("<#-- <p>a</p> -->");
|
||||
const square = view("[#ftl]\n|<p>a</p>");
|
||||
square.dispatch({ selection: EditorSelection.range(7, square.state.doc.length) });
|
||||
commentBlock(square);
|
||||
expect(square.state.doc.toString()).toBe("[#ftl]\n[#-- <p>a</p> --]");
|
||||
// JavaScript keeps its own.
|
||||
const script = view("<script>|a()</script>");
|
||||
script.dispatch({ selection: EditorSelection.range(8, 11) });
|
||||
commentBlock(script);
|
||||
expect(script.state.doc.toString()).toBe("<script>/* a() */</script>");
|
||||
});
|
||||
});
|
||||
+14
-4
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { completedSyntaxTree } from "@/test/syntax";
|
||||
import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight";
|
||||
import { findLanguageDescription, loadSupport } from "./languages";
|
||||
import { findLanguageDescription, loadSupport } from "../languages";
|
||||
|
||||
const highlighter = tagHighlighter([
|
||||
{ tag: t.keyword, class: "keyword" },
|
||||
@@ -25,9 +25,19 @@ async function tokens(source: string) {
|
||||
const support = await loadSupport(desc);
|
||||
const state = EditorState.create({ doc: source, extensions: [support!] });
|
||||
const result: { text: string; style: string }[] = [];
|
||||
highlightTree(completedSyntaxTree(state), highlighter, (from, to, style) =>
|
||||
result.push({ text: source.slice(from, to), style }),
|
||||
);
|
||||
let last = { to: -1, style: "" };
|
||||
// One span per run of a style on a line, as the editor draws it.
|
||||
highlightTree(completedSyntaxTree(state), highlighter, (from, to, style) => {
|
||||
source
|
||||
.slice(from, to)
|
||||
.split("\n")
|
||||
.forEach((text, i) => {
|
||||
const prev = result.at(-1);
|
||||
if (i == 0 && prev && last.to == from && last.style == style) prev.text += text;
|
||||
else result.push({ text, style });
|
||||
});
|
||||
last = { to, style };
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
/**
|
||||
* FreeMarker templates: `freemarker.grammar` parses the template layer (directives,
|
||||
* user-defined directive calls, interpolations, comments), and the text between its
|
||||
* elements is one HTML document, an overlay as in Django and JSP templates, so markup
|
||||
* split by a directive still nests, `href="${url}"` is an attribute with a hole, and
|
||||
* `<script>` / `<style>` get JavaScript and CSS. Block directives fold, indent their
|
||||
* content and match their end tags; finishing a block directive adds its end tag.
|
||||
* Completion offers directives after `<#`, the open blocks' end tags after `</` and
|
||||
* built-ins after `?`.
|
||||
*/
|
||||
import {
|
||||
LRLanguage,
|
||||
LanguageSupport,
|
||||
bracketMatchingHandle,
|
||||
foldNodeProp,
|
||||
indentNodeProp,
|
||||
syntaxTree,
|
||||
type TreeIndentContext,
|
||||
} from "@codemirror/language";
|
||||
import { html } from "@codemirror/lang-html";
|
||||
import type { Completion, CompletionContext, CompletionResult } from "@codemirror/autocomplete";
|
||||
import { EditorSelection, EditorState, Prec, type Text } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { styleTags, tags as t } from "@lezer/highlight";
|
||||
import { NodeProp, parseMixed, type SyntaxNode, type SyntaxNodeRef } from "@lezer/common";
|
||||
import { VERSIONED_SCRIPT_TYPES } from "../htmlScripts";
|
||||
import { parser } from "./parser";
|
||||
import { BLOCK_DIRECTIVES, CAPTURING, DIRECTIVES, RAW_DIRECTIVES } from "./tokens";
|
||||
|
||||
const baseHTML = html({ selfClosingTags: true, nestedLanguages: VERSIONED_SCRIPT_TYPES });
|
||||
|
||||
const FTL_COMMENT = { block: { open: "<#--", close: "-->" } };
|
||||
const SQUARE_COMMENT = { block: { open: "[#--", close: "--]" } };
|
||||
|
||||
const OPENERS = ["OpenTag", "RawTag"];
|
||||
|
||||
const startTagOf = (element: SyntaxNode) => element.firstChild;
|
||||
const endTagOf = (element: SyntaxNode) => (element.lastChild?.name == "EndTag" ? element.lastChild : null);
|
||||
const tagNameOf = (node: SyntaxNode) => node.getChild("DirectiveName") ?? node.getChild("MacroName");
|
||||
|
||||
/** The content of a block: from the end of its start tag to its end tag (or the end of the block). */
|
||||
function foldBlock(element: SyntaxNode, state: EditorState) {
|
||||
const start = startTagOf(element);
|
||||
const end = endTagOf(element);
|
||||
if (!start) return null;
|
||||
// An end tag the parser inserted to recover is empty.
|
||||
const to = end && end.to > end.from ? end.from : element.to;
|
||||
return start.to < to && state.doc.lineAt(start.to).number < state.doc.lineAt(to).number
|
||||
? { from: start.to, to }
|
||||
: null;
|
||||
}
|
||||
|
||||
const MIDDLE = new Set([...BLOCK_DIRECTIVES.values()].flat());
|
||||
const CLOSING_LINE = /^\s*(?:<|\[)(?:\/[#@]|#([A-Za-z]+))/;
|
||||
|
||||
/** A block's content one unit in from its start tag's line; its middle and end tags at that line's indent. */
|
||||
function indentBlock(cx: TreeIndentContext) {
|
||||
const start = startTagOf(cx.node);
|
||||
if (!start) return null;
|
||||
const base = cx.lineIndent(start.from);
|
||||
const m = CLOSING_LINE.exec(cx.textAfter);
|
||||
return m && (!m[1] || MIDDLE.has(m[1])) ? base : base + cx.unit;
|
||||
}
|
||||
|
||||
const templateParser = parser.configure({
|
||||
props: [
|
||||
styleTags({
|
||||
"TagStart OpenTagStart RawTagStart MidTagStart EndTagStart StrayEndTagStart TagEnd SelfCloseEnd InterpolationStart InterpolationEnd":
|
||||
t.special(t.brace),
|
||||
DirectiveName: t.keyword,
|
||||
MacroName: t.function(t.variableName),
|
||||
"Comment RawBody": t.blockComment,
|
||||
VariableName: t.variableName,
|
||||
"PropertyName Member/.": t.propertyName,
|
||||
"BuiltInName BuiltIn/?": t.standard(t.function(t.variableName)),
|
||||
String: t.string,
|
||||
Number: t.number,
|
||||
BooleanLiteral: t.bool,
|
||||
"Operator CompareOp": t.operator,
|
||||
"as in using gt gte lt lte": t.keyword,
|
||||
"( ) [ ] { }": t.bracket,
|
||||
}),
|
||||
foldNodeProp.add({ "Element RawElement": foldBlock }),
|
||||
indentNodeProp.add({
|
||||
Element: indentBlock,
|
||||
// The raw content keeps its own indentation.
|
||||
RawElement: () => null,
|
||||
}),
|
||||
NodeProp.closedBy.add({ "OpenTag RawTag": ["EndTag"] }),
|
||||
NodeProp.openedBy.add({ EndTag: OPENERS }),
|
||||
bracketMatchingHandle.add({ "OpenTag RawTag EndTag": tagNameOf }),
|
||||
],
|
||||
});
|
||||
|
||||
// HTML's document gives no indentation past its last text; there the block around it does.
|
||||
const htmlBase = (baseHTML.language as LRLanguage).parser;
|
||||
const htmlDocumentIndent = htmlBase.nodeSet.types.find((type) => type.name == "Document")?.prop(indentNodeProp);
|
||||
const htmlParser = htmlBase.configure({
|
||||
props: [indentNodeProp.add({ Document: (cx) => htmlDocumentIndent?.(cx) ?? cx.continue() })],
|
||||
});
|
||||
|
||||
// The template text is one HTML document.
|
||||
const htmlMixed = { parser: htmlParser, overlay: (node: SyntaxNodeRef) => node.name == "Text" };
|
||||
|
||||
export const freemarkerLanguage = LRLanguage.define({
|
||||
name: "freemarker",
|
||||
parser: templateParser.configure({ wrap: parseMixed((node) => (node.type.isTop ? htmlMixed : null)) }),
|
||||
});
|
||||
|
||||
/** Where the template layer reaches: FreeMarker's own nodes, or the HTML outside `<script>` and `<style>`. */
|
||||
function inTemplate(state: EditorState, pos: number): boolean {
|
||||
return freemarkerLanguage.isActiveAt(state, pos, -1) || baseHTML.language.isActiveAt(state, pos, -1);
|
||||
}
|
||||
|
||||
const squareSyntaxOf = new WeakMap<Text, boolean>();
|
||||
|
||||
/** The square tag syntax, when the template's first directive uses it. */
|
||||
function squareSyntax(state: EditorState): boolean {
|
||||
let square = squareSyntaxOf.get(state.doc);
|
||||
if (square == undefined) {
|
||||
const head = state.sliceDoc(0, Math.min(state.doc.length, 20_000));
|
||||
square = /<\/?[#@][A-Za-z]|\[\/?[#@][A-Za-z]/.exec(head)?.[0][0] == "[";
|
||||
squareSyntaxOf.set(state.doc, square);
|
||||
}
|
||||
return square;
|
||||
}
|
||||
|
||||
/** The blocks open at `pos`, innermost first, as `#if` / `@badge`. */
|
||||
function openBlocks(state: EditorState, pos: number): string[] {
|
||||
const names: string[] = [];
|
||||
for (let node: SyntaxNode | null = syntaxTree(state).resolve(pos, -1); node; node = node.parent) {
|
||||
if (node.name != "Element" && node.name != "RawElement") continue;
|
||||
const start = startTagOf(node);
|
||||
const name = start && tagNameOf(start);
|
||||
if (start && name && start.to <= pos) {
|
||||
names.push(state.sliceDoc(start.from, name.from).replace(/^[<[]/, "") + state.sliceDoc(name.from, name.to));
|
||||
}
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
/** Whether the block `name` opened before `pos` has no end tag after it, nested blocks counted. */
|
||||
function unclosed(state: EditorState, sigil: string, name: string, pos: number): boolean {
|
||||
const rest = state.sliceDoc(pos);
|
||||
const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
const re = new RegExp(`[<\\[](/)?${sigil}${escaped}(?![\\w.:-])`, "g");
|
||||
let depth = 0;
|
||||
for (let m; (m = re.exec(rest));) {
|
||||
if (!m[1]) depth++;
|
||||
else if (depth-- == 0) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
const TAG_BEFORE = /[<[]([#@])([A-Za-z_][\w.:-]*)(?:\s[^<>[\]]*)?$/;
|
||||
|
||||
/** Typing the `>` (`]`) of a block directive or a call with content adds its end tag after the caret. */
|
||||
const closeBlock = EditorView.inputHandler.of((view, from, to, text) => {
|
||||
const { state } = view;
|
||||
if ((text != ">" && text != "]") || from != to || state.selection.ranges.length > 1 || state.readOnly) return false;
|
||||
const square = squareSyntax(state);
|
||||
if ((text == "]") != square) return false;
|
||||
const line = state.doc.lineAt(from);
|
||||
const before = state.sliceDoc(line.from, from);
|
||||
const m = TAG_BEFORE.exec(before);
|
||||
if (!m || before.endsWith("/") || (m[0][0] == "[") != square) return false;
|
||||
const [, sigil, name] = m;
|
||||
// `<#assign x>…</#assign>` captures its content; `<#assign x = 1>` doesn't.
|
||||
const assigns = /(?:^|[^=!<>])=(?!=)/.test(before.slice(before.length - m[0].length + 2 + name!.length));
|
||||
const block = BLOCK_DIRECTIVES.has(name!) || RAW_DIRECTIVES.has(name!) || (CAPTURING.has(name!) && !assigns);
|
||||
if (sigil == "#" && !block) return false;
|
||||
if (!inTemplate(state, from - m[0].length)) return false;
|
||||
if (!unclosed(state, sigil!, name!, from)) return false;
|
||||
const close = square ? `[/${sigil}${name}]` : `</${sigil}${name}>`;
|
||||
view.dispatch({
|
||||
changes: { from, insert: text + close },
|
||||
selection: EditorSelection.cursor(from + 1),
|
||||
userEvent: "input.type",
|
||||
});
|
||||
return true;
|
||||
});
|
||||
|
||||
const DIRECTIVE_OPTIONS: Completion[] = DIRECTIVES.map((label) => ({ label, type: "keyword" }));
|
||||
|
||||
/** Built-ins most templates use, for completion after `?`. */
|
||||
const BUILT_INS = [
|
||||
"api",
|
||||
"boolean",
|
||||
"c",
|
||||
"c_lower_case",
|
||||
"cap_first",
|
||||
"capitalize",
|
||||
"chop_linebreaks",
|
||||
"chunk",
|
||||
"contains",
|
||||
"counter",
|
||||
"date",
|
||||
"datetime",
|
||||
"default",
|
||||
"drop_while",
|
||||
"ends_with",
|
||||
"ensure_ends_with",
|
||||
"ensure_starts_with",
|
||||
"eval",
|
||||
"eval_json",
|
||||
"filter",
|
||||
"first",
|
||||
"groups",
|
||||
"has_content",
|
||||
"has_next",
|
||||
"html",
|
||||
"if_exists",
|
||||
"index",
|
||||
"index_of",
|
||||
"interpret",
|
||||
"is_boolean",
|
||||
"is_date",
|
||||
"is_even_item",
|
||||
"is_first",
|
||||
"is_hash",
|
||||
"is_last",
|
||||
"is_number",
|
||||
"is_odd_item",
|
||||
"is_sequence",
|
||||
"is_string",
|
||||
"item_cycle",
|
||||
"item_parity",
|
||||
"j_string",
|
||||
"join",
|
||||
"js_string",
|
||||
"json_string",
|
||||
"keep_after",
|
||||
"keep_after_last",
|
||||
"keep_before",
|
||||
"keep_before_last",
|
||||
"keys",
|
||||
"last",
|
||||
"last_index_of",
|
||||
"left_pad",
|
||||
"length",
|
||||
"lower_case",
|
||||
"map",
|
||||
"matches",
|
||||
"max",
|
||||
"min",
|
||||
"no_esc",
|
||||
"number",
|
||||
"number_to_date",
|
||||
"number_to_datetime",
|
||||
"remove_beginning",
|
||||
"remove_ending",
|
||||
"replace",
|
||||
"reverse",
|
||||
"right_pad",
|
||||
"round",
|
||||
"seq_contains",
|
||||
"seq_index_of",
|
||||
"size",
|
||||
"sort",
|
||||
"sort_by",
|
||||
"split",
|
||||
"starts_with",
|
||||
"string",
|
||||
"substring",
|
||||
"switch",
|
||||
"take_while",
|
||||
"then",
|
||||
"time",
|
||||
"trim",
|
||||
"truncate",
|
||||
"uncap_first",
|
||||
"upper_case",
|
||||
"url",
|
||||
"values",
|
||||
"word_list",
|
||||
"xhtml",
|
||||
"xml",
|
||||
].map((label): Completion => ({ label, type: "function" }));
|
||||
|
||||
/** `<#…`, `</#…` and `?…` inside the template layer. */
|
||||
function templateCompletion(context: CompletionContext): CompletionResult | null {
|
||||
const { state } = context;
|
||||
const end = context.matchBefore(/[<[]\/(?:[#@][\w.:-]*)?$/);
|
||||
if (end) {
|
||||
const from = end.from + 2;
|
||||
const options = openBlocks(state, from).map((block, i) => ({ label: block, type: "keyword", boost: 99 - i }));
|
||||
return options.length ? { from, options, validFor: /^(?:[#@][\w.:-]*)?$/ } : null;
|
||||
}
|
||||
const directive = context.matchBefore(/[<[]#\w*$/);
|
||||
if (directive) {
|
||||
if ((directive.text[0] == "[") != squareSyntax(state)) return null;
|
||||
const name = /\w*$/.exec(directive.text)![0];
|
||||
return { from: directive.to - name.length, options: DIRECTIVE_OPTIONS, validFor: /^\w*$/ };
|
||||
}
|
||||
const builtIn = context.matchBefore(/\?\w*$/);
|
||||
// The `?` is a built-in's, not text or a string's.
|
||||
const mark = builtIn && syntaxTree(state).resolveInner(builtIn.from + 1, -1);
|
||||
if (builtIn && mark && (mark.name == "BuiltIn" || mark.parent?.name == "BuiltIn")) {
|
||||
return { from: builtIn.from + 1, options: BUILT_INS, validFor: /^\w*$/ };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function freemarker(): LanguageSupport {
|
||||
return new LanguageSupport(freemarkerLanguage, [
|
||||
// Before HTML's, so the template's completions come first.
|
||||
baseHTML.language.data.of({ autocomplete: templateCompletion }),
|
||||
baseHTML.support,
|
||||
// Markup is commented out with a template comment, which FreeMarker drops from the page.
|
||||
baseHTML.language.data.of({ commentTokens: FTL_COMMENT }),
|
||||
freemarkerLanguage.data.of({ autocomplete: templateCompletion, commentTokens: FTL_COMMENT }),
|
||||
// In the square syntax, `[#-- --]`.
|
||||
Prec.highest(
|
||||
EditorState.languageData.of((state, pos) =>
|
||||
squareSyntax(state) && inTemplate(state, pos) ? [{ commentTokens: SQUARE_COMMENT }] : [],
|
||||
),
|
||||
),
|
||||
Prec.high(closeBlock),
|
||||
]);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// This file was generated by lezer-generator. You probably shouldn't edit it.
|
||||
export const
|
||||
Comment = 1,
|
||||
RawBody = 2,
|
||||
Text = 3,
|
||||
OpenTagStart = 4,
|
||||
RawTagStart = 5,
|
||||
MidTagStart = 6,
|
||||
EndTagStart = 7,
|
||||
StrayEndTagStart = 8,
|
||||
TagStart = 9,
|
||||
InterpolationStart = 10,
|
||||
DirectiveName = 11,
|
||||
MacroName = 12,
|
||||
TagEnd = 13,
|
||||
SelfCloseEnd = 14,
|
||||
InterpolationEnd = 15,
|
||||
Template = 16,
|
||||
Interpolation = 17,
|
||||
VariableName = 18,
|
||||
PropertyName = 21,
|
||||
BuiltInName = 24,
|
||||
String = 25,
|
||||
Number = 26,
|
||||
Operator = 27,
|
||||
CompareOp = 28,
|
||||
as = 29,
|
||||
_in = 30,
|
||||
using = 31,
|
||||
gt = 32,
|
||||
gte = 33,
|
||||
lt = 34,
|
||||
lte = 35,
|
||||
BooleanLiteral = 36,
|
||||
Tag = 46,
|
||||
Element = 47,
|
||||
OpenTag = 48,
|
||||
MidTag = 49,
|
||||
EndTag = 50,
|
||||
RawElement = 51,
|
||||
RawTag = 52,
|
||||
StrayEndTag = 53
|
||||
@@ -0,0 +1,24 @@
|
||||
// This file was generated by lezer-generator. You probably shouldn't edit it.
|
||||
import {LRParser} from "@lezer/lr"
|
||||
import {comment, rawBody, text, tagStart, tagName, tagEnd, blocks} from "./tokens"
|
||||
const spec_identifier = {__proto__:null,as:58, in:60, using:62, gt:64, gte:66, lt:68, lte:70, true:72, false:72}
|
||||
export const parser = LRParser.deserialize({
|
||||
version: 14,
|
||||
states: "*nQVO]OOO!xQ#SO'#CmO#PQ!rO'#D[O#PQ!rO'#D^O#XO]O'#D]O#PQ!rO'#DbO#cOYO'#DaO#kQ#dO'#DcOOO]'#Dj'#DjOOO]'#Dd'#DdQVO]OOOOQp'#Cn'#CnO#vQ!bO'#CoO#{Q!bO'#CrO$QQ!bO'#DTO$XQ!bO'#DWO$`Q!bO'#DZOOQp'#Dk'#DkOOQp'#De'#DeO$gQ#SO,59XOOO],59X,59XOOQp'#Dm'#DmO$nQ#SO,59vO$xQ#SO,59xO#PQ!rO'#D_O%PO]O'#DfO%ZOWO,59wO%cQ#dO'#D`OOO],59w,59wO#XO]O,59wO%nQ#SO,59|OOO],59{,59{O#fOWO,59{OOO],59},59}O%uQ#SO,59}OOO]-E7b-E7bOOQp'#Cq'#CqOOQp,59Z,59ZOOQp'#Ct'#CtOOQp,59^,59^OOQp,59o,59oO%zQ!bO,59oOOQp,59r,59rO&RQ!bO,59rOOQp,59u,59uO&YQ!bO,59uOOQp-E7c-E7cOOO]1G.s1G.sO&aQ#SO1G/bOOO]1G/b1G/bO&kQ#SO1G/dOOO]1G/d1G/dO&rQ#SO,59yO&|O]O,5:QOOOW-E7d-E7dOOO]1G/c1G/cOOO],59z,59zO'WQ#SO,59zO%ZOWO1G/cO']Q#SO1G/hOOOY1G/h1G/hOOO]1G/g1G/gOOO]1G/i1G/iOOQp1G/Z1G/ZOOQp1G/^1G/^OOQp1G/a1G/aOOO]7+$|7+$|OOO]7+%O7+%OO'dQ#SO1G/eOOO]1G/e1G/eOOO]1G/f1G/fOOO]7+$}7+$}OOOY7+%S7+%SOOO]7+%P7+%P",
|
||||
stateData: "'q~O!]OS~OPWORWOSROTTOWVOXQOYPO~Od[Og]OiaOjaOkaOlaOmaOnaOoaOpaOqaOraOsaOtaOv^Oy_O|`O!`ZO~O_dO~PnOZeO[eO~OUhOVkO~PVOQpOVkO~OZeO[eO]qO~O!`tO~O!`vO~OuxO~PnOxzO~PnO{|O~PnO_!PO~PnO]!RO^!RO~PnO]!TO~PnOU!YXV!YX~PVOUhOVkO~OZeO[eO]!YO~O]!^O~PnO]!`O~Ou!aO~PnOx!bO~PnO{!cO~PnO]!dO^!dO~PnO]!eO~PnO]!gO^!gO~PnOU!YaV!Ya~PVO]!hO~O]!jO~PnO]!kO^!kO~PnOi!`~",
|
||||
goto: "&V!bPPPPPPPPPPPPPPPPP!c!k!kP!}!kP#QPPPPPPPPPPPPPP!kPP!kPP!k!c!c#T#]#c!c#s!c#{$Z$}PPP%X%aP%s]WOSYim!VqaP^_`cfgny{}!Q!S!U!]!fRu[Rw]]SOSYim!VXiSjm![QlSQoUS!XjmQ!_pR!i![]UOSYim!VQYOQmSUsYm!VR!ViQcPQy^Q{_Q}``!Ocy{}!Q!S!]!fQ!QfQ!SgQ!]nR!f!UQjSS!Wj![R![m]XOSYim!VqbP^_`cfgny{}!Q!S!U!]!fQfQQgRQnTQrVQ!UhR!Zk",
|
||||
nodeNames: "⚠ Comment RawBody Text OpenTagStart RawTagStart MidTagStart EndTagStart StrayEndTagStart TagStart InterpolationStart DirectiveName MacroName TagEnd SelfCloseEnd InterpolationEnd Template Interpolation VariableName Member . PropertyName BuiltIn ? BuiltInName String Number Operator CompareOp as in using gt gte lt lte BooleanLiteral ) ( ParenGroup ] [ BracketGroup } { HashGroup Tag Element OpenTag MidTag EndTag RawElement RawTag StrayEndTag",
|
||||
maxTerm: 63,
|
||||
context: blocks,
|
||||
nodeProps: [
|
||||
["openedBy", 37,"(",40,"[",43,"{"],
|
||||
["closedBy", 38,")",41,"]",44,"}"]
|
||||
],
|
||||
skippedNodes: [0],
|
||||
repeatNodeCount: 3,
|
||||
tokenData: ",X~RvXY#iYZ#i]^#ipq#iqr#zrs$Xtu%yuv&nvw&{wx'Txy(pyz(uz{&n{|(z|}&v}!O)V!O!P)e!P!Q&n!Q![){![!]&v!]!^&v!^!_*f!_!`#z!`!a*f!a!b*n!c!}%y!}#O*v#P#Q*{#R#S%y#T#f%y#f#g+Q#g#o%y#o#p+u#p#q+z#q#r,S$g;'S%y;'S;=`&h<%lO%y~#nS!]~XY#iYZ#i]^#ipq#i~$PPk~!_!`$S~$XOl~~$^Vi~Or$Xrs$ss#O$X#O#P$x#P;'S$X;'S;=`%s<%lO$X~$xOi~~${RO;'S$X;'S;=`%U;=`O$X~%ZWi~Or$Xrs$ss#O$X#O#P$x#P;'S$X;'S;=`%s;=`<%l$X<%lO$X~%vP;=`<%l$X~&OW!`~tu%y!Q![%y!c!}%y#R#S%y#T#o%y$g;'S%y;'S;=`&h<%lO%y~&kP;=`<%l%y~&sPk~!_!`&v~&{Ok~~'QPk~vw&v~'YVi~Ow'Twx$sx#O'T#O#P'o#P;'S'T;'S;=`(j<%lO'T~'rRO;'S'T;'S;=`'{;=`O'T~(QWi~Ow'Twx$sx#O'T#O#P'o#P;'S'T;'S;=`(j;=`<%l'T<%lO'T~(mP;=`<%l'T~(uOv~~(zOu~~)PQk~{|&v!_!`&v~)[Rk~}!O&v!_!`&v!`!a&v~)jPd~!O!P)m~)rRk~qr&vz{&v!^!_&v~*QQj~!O!P*W!Q![){~*ZP!Q![*^~*cPj~!Q![*^~*kPl~!_!`$S~*sPg~!a!b&v~*{Oy~~+QOx~~+VY!`~rs$Xtu%ywx'T!Q![%y!c!}%y#R#S%y#T#o%y$g;'S%y;'S;=`&h<%lO%y~+zO|~~,PPk~#p#q&v~,XO{~",
|
||||
tokenizers: [comment, rawBody, text, tagStart, tagName, tagEnd, 0],
|
||||
topRules: {"Template":[0,16]},
|
||||
specialized: [{term: 62, get: (value: keyof typeof spec_identifier) => spec_identifier[value] || -1}],
|
||||
tokenPrec: 306
|
||||
})
|
||||
@@ -0,0 +1,350 @@
|
||||
/**
|
||||
* External tokens of `freemarker.grammar`: the text between template elements, the
|
||||
* comments, the raw content of `noparse`, the start of each tag, classified by its name
|
||||
* against the blocks open around it, the tag's name and the delimiters that end tags
|
||||
* and interpolations, which depend on the tag syntax.
|
||||
*/
|
||||
import { ContextTracker, ExternalTokenizer, type InputStream, type Stack } from "@lezer/lr";
|
||||
import {
|
||||
Comment,
|
||||
DirectiveName,
|
||||
Element,
|
||||
EndTagStart,
|
||||
InterpolationEnd,
|
||||
InterpolationStart,
|
||||
MacroName,
|
||||
MidTagStart,
|
||||
OpenTagStart,
|
||||
RawBody,
|
||||
RawElement,
|
||||
RawTagStart,
|
||||
SelfCloseEnd,
|
||||
StrayEndTagStart,
|
||||
TagEnd,
|
||||
TagStart,
|
||||
Text,
|
||||
} from "./parser.terms";
|
||||
|
||||
const LT = 60,
|
||||
GT = 62,
|
||||
SLASH = 47,
|
||||
HASH = 35,
|
||||
AT = 64,
|
||||
DOLLAR = 36,
|
||||
EQ = 61,
|
||||
BRACE_L = 123,
|
||||
BRACE_R = 125,
|
||||
BRACKET_L = 91,
|
||||
BRACKET_R = 93,
|
||||
PAREN_L = 40,
|
||||
PAREN_R = 41,
|
||||
DASH = 45,
|
||||
QUOTE = 34,
|
||||
APOS = 39,
|
||||
BACKSLASH = 92,
|
||||
BANG = 33;
|
||||
|
||||
/** Block directives, with the middle tags each one allows. */
|
||||
export const BLOCK_DIRECTIVES: ReadonlyMap<string, readonly string[]> = new Map([
|
||||
["attempt", ["recover"]],
|
||||
["autoesc", []],
|
||||
["compress", []],
|
||||
["escape", []],
|
||||
["function", []],
|
||||
["if", ["elseif", "else"]],
|
||||
["items", []],
|
||||
["list", ["else"]],
|
||||
["macro", []],
|
||||
["noautoesc", []],
|
||||
["noescape", []],
|
||||
["outputformat", []],
|
||||
["switch", ["case", "default", "on"]],
|
||||
]);
|
||||
|
||||
/** `<#assign x>…</#assign>`: these capture their content when they have no `=`. */
|
||||
export const CAPTURING: ReadonlySet<string> = new Set(["assign", "global", "local"]);
|
||||
|
||||
/** Directives whose content FreeMarker doesn't parse. */
|
||||
export const RAW_DIRECTIVES: ReadonlySet<string> = new Set(["noparse", "comment"]);
|
||||
|
||||
/** Every built-in directive, for completion. */
|
||||
export const DIRECTIVES = [
|
||||
"assign",
|
||||
"attempt",
|
||||
"autoesc",
|
||||
"break",
|
||||
"case",
|
||||
"compress",
|
||||
"continue",
|
||||
"default",
|
||||
"else",
|
||||
"elseif",
|
||||
"escape",
|
||||
"fallback",
|
||||
"flush",
|
||||
"ftl",
|
||||
"function",
|
||||
"global",
|
||||
"if",
|
||||
"import",
|
||||
"include",
|
||||
"items",
|
||||
"list",
|
||||
"local",
|
||||
"lt",
|
||||
"macro",
|
||||
"nested",
|
||||
"noautoesc",
|
||||
"noescape",
|
||||
"noparse",
|
||||
"nt",
|
||||
"on",
|
||||
"outputformat",
|
||||
"recover",
|
||||
"recurse",
|
||||
"return",
|
||||
"rt",
|
||||
"sep",
|
||||
"setting",
|
||||
"stop",
|
||||
"switch",
|
||||
"t",
|
||||
"visit",
|
||||
];
|
||||
|
||||
/** The blocks open around a position, innermost first, and the tag syntax (`null`: not fixed yet). */
|
||||
class Context {
|
||||
readonly hash: number;
|
||||
constructor(
|
||||
/** `#if`, `@badge`. */
|
||||
readonly name: string | null,
|
||||
readonly parent: Context | null,
|
||||
readonly square: boolean | null,
|
||||
) {
|
||||
let hash = parent ? parent.hash : square === null ? 1 : square ? 2 : 3;
|
||||
for (let i = 0; name && i < name.length; i++) hash = ((hash << 5) - hash + name.charCodeAt(i)) | 0;
|
||||
this.hash = hash;
|
||||
}
|
||||
}
|
||||
|
||||
const TOP = new Context(null, null, null);
|
||||
|
||||
const isNameStart = (ch: number) => (ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122) || ch == 95;
|
||||
const isName = (ch: number) => isNameStart(ch) || (ch >= 48 && ch <= 57);
|
||||
/** User-defined directive names may be qualified (`lib.badge`) or carry `:` and `-`. */
|
||||
const isMacroName = (ch: number) => isName(ch) || ch == 46 || ch == 58 || ch == DASH;
|
||||
|
||||
/** A tag opening `offset` code units ahead: its kind, sigil and name. */
|
||||
interface TagHead {
|
||||
/** Code units up to the name. */
|
||||
length: number;
|
||||
end: boolean;
|
||||
sigil: "#" | "@";
|
||||
name: string;
|
||||
square: boolean;
|
||||
}
|
||||
|
||||
function tagHead(input: InputStream, offset: number, square: boolean | null): TagHead | null {
|
||||
const open = input.peek(offset);
|
||||
if (open == LT ? square === true : open == BRACKET_L ? square === false : true) return null;
|
||||
let i = offset + 1;
|
||||
const end = input.peek(i) == SLASH;
|
||||
if (end) i++;
|
||||
const sigil = input.peek(i);
|
||||
if (sigil != HASH && sigil != AT) return null;
|
||||
i++;
|
||||
let name = "";
|
||||
const accept = sigil == HASH ? isName : isMacroName;
|
||||
for (let ch; accept((ch = input.peek(i))); i++) {
|
||||
if (!name && !isNameStart(ch)) break;
|
||||
name += String.fromCharCode(ch);
|
||||
}
|
||||
// `<#--` is a comment, `</@>` ends the innermost call; anything else needs a name.
|
||||
if (!name && !(end && sigil == AT)) return null;
|
||||
return { length: i - offset - name.length, end, sigil: sigil == HASH ? "#" : "@", name, square: open == BRACKET_L };
|
||||
}
|
||||
|
||||
const commentAt = (input: InputStream, offset: number, square: boolean | null) => {
|
||||
const open = input.peek(offset);
|
||||
return (
|
||||
(open == LT ? square !== true : open == BRACKET_L && square !== false) &&
|
||||
input.peek(offset + 1) == HASH &&
|
||||
input.peek(offset + 2) == DASH &&
|
||||
input.peek(offset + 3) == DASH
|
||||
);
|
||||
};
|
||||
|
||||
const interpolationAt = (input: InputStream, offset: number, square: boolean | null) => {
|
||||
const ch = input.peek(offset);
|
||||
return (
|
||||
(ch == DOLLAR && input.peek(offset + 1) == BRACE_L) ||
|
||||
(square === true && ch == BRACKET_L && input.peek(offset + 1) == EQ)
|
||||
);
|
||||
};
|
||||
|
||||
/** Whether a comment, a tag or an interpolation starts `offset` code units ahead. */
|
||||
function elementStart(input: InputStream, offset: number, square: boolean | null): boolean {
|
||||
const ch = input.peek(offset);
|
||||
if (ch != LT && ch != BRACKET_L && ch != DOLLAR) return false;
|
||||
return interpolationAt(input, offset, square) || commentAt(input, offset, square) || !!tagHead(input, offset, square);
|
||||
}
|
||||
|
||||
/** How far a tag scan looks for the tag's end. */
|
||||
const MAX_TAG = 4000;
|
||||
|
||||
/**
|
||||
* The rest of a tag after its name: whether it ends with `/>` (`/]`) and whether it has an
|
||||
* assignment `=` outside brackets, skipping strings and brackets.
|
||||
*/
|
||||
function tagTail(input: InputStream, offset: number, square: boolean): { selfClosing: boolean; assigns: boolean } {
|
||||
const close = square ? BRACKET_R : GT;
|
||||
let depth = 0;
|
||||
let assigns = false;
|
||||
for (let i = offset; i < offset + MAX_TAG; i++) {
|
||||
const ch = input.peek(i);
|
||||
if (ch < 0) break;
|
||||
if (ch == QUOTE || ch == APOS) {
|
||||
for (i++; ; i++) {
|
||||
const c = input.peek(i);
|
||||
if (c < 0 || c == ch) break;
|
||||
if (c == BACKSLASH) i++;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (ch == PAREN_L || ch == BRACE_L || ch == BRACKET_L) {
|
||||
depth++;
|
||||
continue;
|
||||
}
|
||||
if (depth > 0 && (ch == PAREN_R || ch == BRACE_R || ch == BRACKET_R)) {
|
||||
depth--;
|
||||
continue;
|
||||
}
|
||||
if (depth == 0 && ch == close) return { selfClosing: input.peek(i - 1) == SLASH, assigns };
|
||||
if (depth == 0 && ch == EQ) {
|
||||
const before = input.peek(i - 1);
|
||||
const after = input.peek(i + 1);
|
||||
if (after != EQ && before != EQ && before != BANG && before != LT && before != GT) assigns = true;
|
||||
}
|
||||
}
|
||||
return { selfClosing: false, assigns };
|
||||
}
|
||||
|
||||
export const blocks = new ContextTracker<Context>({
|
||||
start: TOP,
|
||||
shift(context, term, _stack, input) {
|
||||
const opens = term == OpenTagStart || term == RawTagStart;
|
||||
const tag = opens || term == MidTagStart || term == EndTagStart || term == StrayEndTagStart || term == TagStart;
|
||||
if (!tag) return context;
|
||||
const square = context.square ?? input.next == BRACKET_L;
|
||||
if (!opens) return square === context.square ? context : fixSyntax(context, square);
|
||||
const head = tagHead(input, 0, square);
|
||||
const base = square === context.square ? context : fixSyntax(context, square);
|
||||
return new Context(head ? head.sigil + head.name : null, base, square);
|
||||
},
|
||||
reduce(context, term) {
|
||||
return (term == Element || term == RawElement) && context.parent ? context.parent : context;
|
||||
},
|
||||
hash: (context) => context.hash,
|
||||
strict: false,
|
||||
});
|
||||
|
||||
/** `context` with the tag syntax fixed, for the blocks around it too. */
|
||||
function fixSyntax(context: Context, square: boolean): Context {
|
||||
return context.parent
|
||||
? new Context(context.name, fixSyntax(context.parent, square), square)
|
||||
: new Context(null, null, square);
|
||||
}
|
||||
|
||||
/** `<#-- … -->` (`[#-- … --]`), to the end of the document when unterminated. */
|
||||
export const comment = new ExternalTokenizer((input, stack: Stack) => {
|
||||
const context: Context = stack.context;
|
||||
if (!commentAt(input, 0, context.square)) return;
|
||||
const close = input.next == BRACKET_L ? BRACKET_R : GT;
|
||||
input.advance(4);
|
||||
for (let ch; (ch = input.next) >= 0;) {
|
||||
if (ch == DASH && input.peek(1) == DASH && input.peek(2) == close) {
|
||||
input.advance(3);
|
||||
break;
|
||||
}
|
||||
input.advance();
|
||||
}
|
||||
input.acceptToken(Comment);
|
||||
});
|
||||
|
||||
/** Template text: up to a tag, an interpolation or a comment. */
|
||||
export const text = new ExternalTokenizer((input, stack: Stack) => {
|
||||
const square = (stack.context as Context).square;
|
||||
const start = input.pos;
|
||||
while (input.next >= 0 && !elementStart(input, 0, square)) input.advance();
|
||||
if (input.pos > start) input.acceptToken(Text);
|
||||
});
|
||||
|
||||
/** The opening delimiter of a tag or an interpolation, a token telling what it is in the blocks open around it. */
|
||||
export const tagStart = new ExternalTokenizer((input, stack: Stack) => {
|
||||
const context: Context = stack.context;
|
||||
if (interpolationAt(input, 0, context.square)) {
|
||||
if (stack.canShift(InterpolationStart)) input.acceptToken(InterpolationStart, 2);
|
||||
return;
|
||||
}
|
||||
const head = tagHead(input, 0, context.square);
|
||||
if (!head) return;
|
||||
const open = context.name;
|
||||
const name = head.sigil + head.name;
|
||||
let term = TagStart;
|
||||
if (head.end) {
|
||||
term =
|
||||
open && (name == open || (head.sigil == "@" && !head.name && open.startsWith("@")))
|
||||
? EndTagStart
|
||||
: StrayEndTagStart;
|
||||
} else if (head.sigil == "#" && RAW_DIRECTIVES.has(head.name)) {
|
||||
term = RawTagStart;
|
||||
} else if (open?.startsWith("#") && BLOCK_DIRECTIVES.get(open.slice(1))?.includes(head.name)) {
|
||||
term = MidTagStart;
|
||||
} else if (head.sigil == "@" || BLOCK_DIRECTIVES.has(head.name) || CAPTURING.has(head.name)) {
|
||||
const tail = tagTail(input, head.length + head.name.length, head.square);
|
||||
const block = !tail.selfClosing && (!CAPTURING.has(head.name) || !tail.assigns);
|
||||
if (block) term = OpenTagStart;
|
||||
}
|
||||
if (!stack.canShift(term)) term = term == EndTagStart ? StrayEndTagStart : TagStart;
|
||||
if (stack.canShift(term)) input.acceptToken(term, head.length);
|
||||
});
|
||||
|
||||
/** A tag's name: a directive's (`if`) or a user-defined directive's (`lib.badge`). */
|
||||
export const tagName = new ExternalTokenizer((input) => {
|
||||
const sigil = input.peek(-1);
|
||||
if (sigil != HASH && sigil != AT) return;
|
||||
const accept = sigil == HASH ? isName : isMacroName;
|
||||
if (!isNameStart(input.next)) return;
|
||||
while (accept(input.next)) input.advance();
|
||||
input.acceptToken(sigil == HASH ? DirectiveName : MacroName);
|
||||
});
|
||||
|
||||
/** `>` / `/>` (`]` / `/]`) ending a tag, `}` (`]`) ending an interpolation. */
|
||||
export const tagEnd = new ExternalTokenizer((input, stack: Stack) => {
|
||||
const square = (stack.context as Context).square === true;
|
||||
const close = square ? BRACKET_R : GT;
|
||||
if (input.next == SLASH && input.peek(1) == close) {
|
||||
if (stack.canShift(SelfCloseEnd)) input.acceptToken(SelfCloseEnd, 2);
|
||||
return;
|
||||
}
|
||||
if (input.next == close && stack.canShift(TagEnd)) {
|
||||
input.acceptToken(TagEnd, 1);
|
||||
return;
|
||||
}
|
||||
if ((input.next == BRACE_R || (square && input.next == BRACKET_R)) && stack.canShift(InterpolationEnd)) {
|
||||
input.acceptToken(InterpolationEnd, 1);
|
||||
}
|
||||
});
|
||||
|
||||
/** The content of `noparse` or `comment`: up to the end tag closing it. */
|
||||
export const rawBody = new ExternalTokenizer((input, stack: Stack) => {
|
||||
const context: Context = stack.context;
|
||||
const name = context.name;
|
||||
if (!name) return;
|
||||
const start = input.pos;
|
||||
for (; input.next >= 0; input.advance()) {
|
||||
const head = (input.next == LT || input.next == BRACKET_L) && tagHead(input, 0, context.square);
|
||||
if (head && head.end && head.sigil + head.name == name) break;
|
||||
}
|
||||
if (input.pos > start) input.acceptToken(RawBody);
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
Loaded 100 of 121 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача