дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-27 13:06:07 +02:00
Порівняти коміти
19
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
8dea5904f2 | ||
|
|
c7d32f9e23 | ||
|
|
3f9512056d | ||
|
|
1283af8a41 | ||
|
|
d37b96002b | ||
|
|
364bb5ef50 | ||
|
|
4d503ef976 | ||
|
|
75b1704f78 | ||
|
|
06d78cf524 | ||
|
|
fff2c7110c | ||
|
|
9fbd57ed15 | ||
|
|
aea0b33585 | ||
|
|
e537dd43a0 | ||
|
|
c821ab144c | ||
|
|
6767a5ff8c | ||
|
|
a233d85fcc | ||
|
|
4e675c1171 | ||
|
|
8ebeaa2663 | ||
|
|
ed7b0f88ef |
No files matched your search
Створено
+46
-33
@@ -3974,7 +3974,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-agent"
|
||||
version = "0.1.23"
|
||||
version = "0.1.24"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"ide-core",
|
||||
@@ -3995,7 +3995,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.23"
|
||||
version = "0.1.24"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -4009,7 +4009,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.23"
|
||||
version = "0.1.24"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
@@ -4024,24 +4024,25 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-clipboard"
|
||||
version = "0.1.23"
|
||||
version = "0.1.24"
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.23"
|
||||
version = "0.1.24"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
"specta-typescript",
|
||||
"tempfile",
|
||||
"thiserror 2.0.21",
|
||||
"tokio-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.23"
|
||||
version = "0.1.24"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4055,7 +4056,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.23"
|
||||
version = "0.1.24"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jsonrpc",
|
||||
@@ -4072,7 +4073,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.23"
|
||||
version = "0.1.24"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"futures",
|
||||
@@ -4091,7 +4092,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.23"
|
||||
version = "0.1.24"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4103,9 +4104,20 @@ dependencies = [
|
||||
"which",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-fonts"
|
||||
version = "0.1.24"
|
||||
dependencies = [
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
"serde",
|
||||
"specta",
|
||||
"windows",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.23"
|
||||
version = "0.1.24"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4119,7 +4131,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-host"
|
||||
version = "0.1.23"
|
||||
version = "0.1.24"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
@@ -4160,7 +4172,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.23"
|
||||
version = "0.1.24"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4178,7 +4190,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.23"
|
||||
version = "0.1.24"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4200,7 +4212,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.23"
|
||||
version = "0.1.24"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"futures",
|
||||
@@ -4216,7 +4228,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.23"
|
||||
version = "0.1.24"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4270,7 +4282,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.23"
|
||||
version = "0.1.24"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"globset",
|
||||
@@ -4293,7 +4305,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.23"
|
||||
version = "0.1.24"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4311,7 +4323,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.23"
|
||||
version = "0.1.24"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4324,7 +4336,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.23"
|
||||
version = "0.1.24"
|
||||
dependencies = [
|
||||
"globset",
|
||||
"ide-core",
|
||||
@@ -4341,7 +4353,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.23"
|
||||
version = "0.1.24"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"ide-core",
|
||||
@@ -4361,7 +4373,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.23"
|
||||
version = "0.1.24"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"ide-core",
|
||||
@@ -4381,7 +4393,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.23"
|
||||
version = "0.1.24"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"globset",
|
||||
@@ -4401,7 +4413,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.23"
|
||||
version = "0.1.24"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4414,7 +4426,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.23"
|
||||
version = "0.1.24"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4433,7 +4445,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.23"
|
||||
version = "0.1.24"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4448,7 +4460,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.23"
|
||||
version = "0.1.24"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4461,7 +4473,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.23"
|
||||
version = "0.1.24"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4473,7 +4485,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.23"
|
||||
version = "0.1.24"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hex",
|
||||
@@ -4494,7 +4506,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.23"
|
||||
version = "0.1.24"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"gix",
|
||||
@@ -4511,7 +4523,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.23"
|
||||
version = "0.1.24"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -4532,7 +4544,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.23"
|
||||
version = "0.1.24"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"open",
|
||||
@@ -4548,7 +4560,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.23"
|
||||
version = "0.1.24"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -5973,7 +5985,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.23"
|
||||
version = "0.1.24"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dirs 6.0.0",
|
||||
@@ -5987,6 +5999,7 @@ dependencies = [
|
||||
"ide-dap",
|
||||
"ide-db",
|
||||
"ide-docker",
|
||||
"ide-fonts",
|
||||
"ide-github",
|
||||
"ide-host",
|
||||
"ide-http",
|
||||
|
||||
+2
-1
@@ -3,7 +3,7 @@ resolver = "3"
|
||||
members = ["crates/*", "src-tauri"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.23"
|
||||
version = "0.1.24"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
@@ -36,6 +36,7 @@ ide-web = { path = "crates/ide-web" }
|
||||
ide-spell = { path = "crates/ide-spell" }
|
||||
ide-agent = { path = "crates/ide-agent" }
|
||||
ide-clipboard = { path = "crates/ide-clipboard" }
|
||||
ide-fonts = { path = "crates/ide-fonts" }
|
||||
ide-ssh = { path = "crates/ide-ssh" }
|
||||
ide-remote = { path = "crates/ide-remote" }
|
||||
ide-host = { path = "crates/ide-host" }
|
||||
|
||||
@@ -45,8 +45,12 @@ pub(crate) fn run(
|
||||
mut on_line: impl FnMut(Stream, &str),
|
||||
) -> IdeResult<Output> {
|
||||
tracing::info!("build: {program} {} (in {})", args.join(" "), cwd.display());
|
||||
// Output is read as UTF-8: JVMs on Windows are told to write it (see `ide_core::output_encoding`).
|
||||
let encoding =
|
||||
ide_core::output_encoding::fix(program, args, env, |k| std::env::var(k).ok(), "UTF-8", cfg!(windows));
|
||||
let mut command = Command::new(program);
|
||||
command.args(args).current_dir(cwd).envs(env).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
command.args(args).current_dir(cwd).envs(env).envs(encoding.env).stdin(Stdio::null());
|
||||
command.stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
@@ -86,6 +90,7 @@ pub(crate) fn run(
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
match rx.recv_timeout(Duration::from_millis(100)) {
|
||||
Ok((_, line)) if encoding.notice.as_ref() == Some(&line) => {}
|
||||
Ok((stream, line)) => {
|
||||
on_line(stream, &line);
|
||||
text.push_str(&line);
|
||||
|
||||
@@ -13,3 +13,6 @@ specta.workspace = true
|
||||
specta-typescript.workspace = true
|
||||
thiserror.workspace = true
|
||||
tokio-util.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
@@ -12,6 +12,7 @@ pub mod ignored;
|
||||
pub mod inspection_settings;
|
||||
pub mod ipc_path;
|
||||
pub mod jsonc;
|
||||
pub mod output_encoding;
|
||||
pub mod process;
|
||||
pub mod project_dir;
|
||||
pub mod proxy_settings;
|
||||
@@ -19,6 +20,7 @@ pub mod remote_settings;
|
||||
pub mod settings;
|
||||
pub mod task;
|
||||
pub mod text;
|
||||
pub mod version_managers;
|
||||
pub mod workflow_settings;
|
||||
|
||||
pub use error::{IdeError, IdeResult};
|
||||
|
||||
@@ -0,0 +1,412 @@
|
||||
//! Makes the output of JVM and Python processes match the encoding the IDE decodes.
|
||||
//!
|
||||
//! On Windows both write piped output in the ANSI code page (GBK on a Chinese
|
||||
//! system: `System.out.println`, `javac` errors, Maven / Gradle logs, `print`), while
|
||||
//! the console decodes the configured encoding (UTF-8 by default). They are told
|
||||
//! which one to use:
|
||||
//! - `java`: `stdout.encoding` / `stderr.encoding` (JDK 19+) and their `sun.*`
|
||||
//! forerunners (JDK 8–18) on the command line, plus `file.encoding=UTF-8` for a
|
||||
//! UTF-8 console, the default charset of JDK 18+, which logging frameworks' console
|
||||
//! appenders write in on older JDKs too.
|
||||
//! - Build tools and launcher scripts (Maven, Gradle, sbt, …): the same `std*.encoding`
|
||||
//! properties in `JAVA_TOOL_OPTIONS`, the one variable every JVM reads, so the JVMs
|
||||
//! they fork get them too (`spring-boot:run`, Surefire, `bootRun`, test workers).
|
||||
//! Each JVM then reports "Picked up JAVA_TOOL_OPTIONS: …" on stderr (which a build tool
|
||||
//! may copy to its stdout); that line is hidden again ([`NoticeFilter`]). `file.encoding` is left alone there: it would change
|
||||
//! how a build reads sources that declare no encoding.
|
||||
//! - Python: `PYTHONIOENCODING`.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
const STD_PROPERTIES: &[&str] = &["stdout.encoding", "stderr.encoding", "sun.stdout.encoding", "sun.stderr.encoding"];
|
||||
const FILE_ENCODING: &str = "file.encoding";
|
||||
const TOOL_OPTIONS: &str = "JAVA_TOOL_OPTIONS";
|
||||
|
||||
/// Build tools and launcher scripts that run on (and may fork) JVMs.
|
||||
const JVM_TOOLS: &[&str] =
|
||||
&["mvn", "mvnw", "mvnd", "gradle", "gradlew", "sbt", "ant", "kotlin", "kotlinc", "groovy", "scala", "jbang"];
|
||||
|
||||
/// What a launch needs: `-D` options to put first on a `java` command line,
|
||||
/// environment variables to set, and the notice line its JVMs print because of them.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct EncodingFix {
|
||||
pub java_args: Vec<String>,
|
||||
pub env: Vec<(String, String)>,
|
||||
/// "Picked up JAVA_TOOL_OPTIONS: …" for a variable set here alone, to drop from the output.
|
||||
pub notice: Option<String>,
|
||||
}
|
||||
|
||||
pub fn is_utf8(encoding: &str) -> bool {
|
||||
matches!(encoding.trim().to_ascii_lowercase().replace('_', "-").as_str(), "utf-8" | "utf8")
|
||||
}
|
||||
|
||||
/// File name of `command` without a Windows executable extension: `C:\jdk\bin\java.exe` → `java`.
|
||||
fn program_name(command: &str) -> String {
|
||||
let name = command.rsplit(['/', '\\']).next().unwrap_or(command).to_ascii_lowercase();
|
||||
for ext in [".exe", ".cmd", ".bat"] {
|
||||
if let Some(stem) = name.strip_suffix(ext) {
|
||||
return stem.to_owned();
|
||||
}
|
||||
}
|
||||
name
|
||||
}
|
||||
|
||||
fn sets(text: &str, properties: &[&str]) -> bool {
|
||||
properties.iter().any(|p| text.contains(&format!("-D{p}=")))
|
||||
}
|
||||
|
||||
fn options(properties: &[&str], encoding: &str) -> Vec<String> {
|
||||
properties.iter().map(|p| format!("-D{p}={encoding}")).collect()
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Kind {
|
||||
Java,
|
||||
JvmTool,
|
||||
Python,
|
||||
Other,
|
||||
}
|
||||
|
||||
fn kind(program: &str) -> Kind {
|
||||
let name = program_name(program);
|
||||
if name == "java" || name == "javaw" {
|
||||
Kind::Java
|
||||
} else if JVM_TOOLS.contains(&name.as_str()) {
|
||||
Kind::JvmTool
|
||||
} else if is_python(&name) {
|
||||
Kind::Python
|
||||
} else {
|
||||
Kind::Other
|
||||
}
|
||||
}
|
||||
|
||||
/// The options for a launch of `program` (`args`, environment `vars` over the
|
||||
/// `inherited` one) whose output is decoded as `encoding`; nothing when the
|
||||
/// process already writes it (UTF-8 off Windows) or the user chose the options.
|
||||
pub fn fix(
|
||||
program: &str,
|
||||
args: &[String],
|
||||
vars: &BTreeMap<String, String>,
|
||||
inherited: impl Fn(&str) -> Option<String>,
|
||||
encoding: &str,
|
||||
windows: bool,
|
||||
) -> EncodingFix {
|
||||
fix_kind(kind(program), Some(args), vars, inherited, encoding, windows)
|
||||
}
|
||||
|
||||
/// [`fix`] for a command line run by the shell (`cmd /C "mvn spring-boot:run"`), whose
|
||||
/// arguments cannot be changed: its first word decides, and only variables are set.
|
||||
pub fn fix_command_line(
|
||||
line: &str,
|
||||
vars: &BTreeMap<String, String>,
|
||||
inherited: impl Fn(&str) -> Option<String>,
|
||||
encoding: &str,
|
||||
windows: bool,
|
||||
) -> EncodingFix {
|
||||
let line = line.trim_start();
|
||||
let first = match line.chars().next() {
|
||||
Some(q @ ('"' | '\'')) => line[1..].split(q).next(),
|
||||
_ => line.split(char::is_whitespace).next(),
|
||||
}
|
||||
.unwrap_or_default();
|
||||
fix_kind(kind(first), None, vars, inherited, encoding, windows)
|
||||
}
|
||||
|
||||
fn fix_kind(
|
||||
kind: Kind,
|
||||
args: Option<&[String]>,
|
||||
vars: &BTreeMap<String, String>,
|
||||
inherited: impl Fn(&str) -> Option<String>,
|
||||
encoding: &str,
|
||||
windows: bool,
|
||||
) -> EncodingFix {
|
||||
let encoding = encoding.trim();
|
||||
let mut out = EncodingFix::default();
|
||||
if encoding.is_empty() || (!windows && is_utf8(encoding)) {
|
||||
return out;
|
||||
}
|
||||
let current = |key: &str| vars.get(key).cloned().or_else(|| inherited(key)).unwrap_or_default();
|
||||
let tool_options = current(TOOL_OPTIONS);
|
||||
match (kind, args) {
|
||||
(Kind::Java, Some(args)) => {
|
||||
let java_options = format!("{} {tool_options}", current("JDK_JAVA_OPTIONS"));
|
||||
let chosen =
|
||||
|properties: &[&str]| args.iter().any(|a| sets(a, properties)) || sets(&java_options, properties);
|
||||
if !chosen(STD_PROPERTIES) {
|
||||
out.java_args = options(STD_PROPERTIES, encoding);
|
||||
}
|
||||
if is_utf8(encoding) && !chosen(&[FILE_ENCODING]) {
|
||||
out.java_args.push(format!("-D{FILE_ENCODING}=UTF-8"));
|
||||
}
|
||||
}
|
||||
(Kind::Java | Kind::JvmTool, _) => {
|
||||
if !sets(&tool_options, STD_PROPERTIES) {
|
||||
let added = options(STD_PROPERTIES, encoding).join(" ");
|
||||
let value = match tool_options.trim() {
|
||||
"" => {
|
||||
out.notice = Some(format!("Picked up {TOOL_OPTIONS}: {added}"));
|
||||
added
|
||||
}
|
||||
own => format!("{own} {added}"),
|
||||
};
|
||||
out.env.push((TOOL_OPTIONS.to_owned(), value));
|
||||
}
|
||||
}
|
||||
(Kind::Python, _) if current("PYTHONIOENCODING").trim().is_empty() => {
|
||||
out.env.push(("PYTHONIOENCODING".to_owned(), encoding.to_owned()));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `vmArgs` of a launch by java-debug, which decodes the JVM's output as `encoding`
|
||||
/// (its launch attribute, UTF-8 when unset) and sets `file.encoding` itself.
|
||||
pub fn java_debug_vm_args(vm_args: &str, encoding: Option<&str>, windows: bool) -> Option<String> {
|
||||
let encoding = encoding.map(str::trim).filter(|e| !e.is_empty()).unwrap_or("UTF-8");
|
||||
if (!windows && is_utf8(encoding)) || sets(vm_args, STD_PROPERTIES) {
|
||||
return None;
|
||||
}
|
||||
let added = options(STD_PROPERTIES, encoding).join(" ");
|
||||
Some(match vm_args.trim() {
|
||||
"" => added,
|
||||
own => format!("{own} {added}"),
|
||||
})
|
||||
}
|
||||
|
||||
/// `python`, `python3`, `python3.12`, `py`, and the runners that start one.
|
||||
fn is_python(name: &str) -> bool {
|
||||
name == "python"
|
||||
|| name == "py"
|
||||
|| name.strip_prefix("python").is_some_and(|v| v.chars().all(|c| c.is_ascii_digit() || c == '.'))
|
||||
|| matches!(name, "uv" | "poetry" | "pdm" | "pytest" | "pipenv")
|
||||
}
|
||||
|
||||
/// Drops whole lines equal to `notice` from a stream of decoded text (the
|
||||
/// [`EncodingFix::notice`] each JVM prints), passing everything else through.
|
||||
/// The start of a line is held back only while it can still become the notice.
|
||||
#[derive(Debug)]
|
||||
pub struct NoticeFilter {
|
||||
notice: String,
|
||||
held: String,
|
||||
at_line_start: bool,
|
||||
}
|
||||
|
||||
impl NoticeFilter {
|
||||
pub fn new(notice: String) -> Self {
|
||||
Self { notice, held: String::new(), at_line_start: true }
|
||||
}
|
||||
|
||||
pub fn filter(&mut self, text: &str, out: &mut String) {
|
||||
for piece in text.split_inclusive('\n') {
|
||||
if !self.at_line_start && self.held.is_empty() {
|
||||
out.push_str(piece);
|
||||
self.at_line_start = piece.ends_with('\n');
|
||||
continue;
|
||||
}
|
||||
self.held.push_str(piece);
|
||||
if self.held.ends_with('\n') {
|
||||
if self.held.trim_end_matches(['\n', '\r']) != self.notice {
|
||||
out.push_str(&self.held);
|
||||
}
|
||||
self.held.clear();
|
||||
self.at_line_start = true;
|
||||
} else if !self.could_be_notice() {
|
||||
out.push_str(&self.held);
|
||||
self.held.clear();
|
||||
self.at_line_start = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The held text is the start of the notice, or all of it before a `\r\n`.
|
||||
fn could_be_notice(&self) -> bool {
|
||||
match self.held.strip_suffix('\r') {
|
||||
Some(line) => line == self.notice,
|
||||
None => self.notice.starts_with(self.held.as_str()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The held-back start of a line, at the end of the stream.
|
||||
pub fn finish(&mut self) -> String {
|
||||
std::mem::take(&mut self.held)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const STD_UTF8: [&str; 4] = [
|
||||
"-Dstdout.encoding=UTF-8",
|
||||
"-Dstderr.encoding=UTF-8",
|
||||
"-Dsun.stdout.encoding=UTF-8",
|
||||
"-Dsun.stderr.encoding=UTF-8",
|
||||
];
|
||||
const TOOL_UTF8: &str =
|
||||
"-Dstdout.encoding=UTF-8 -Dstderr.encoding=UTF-8 -Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8";
|
||||
|
||||
fn vars(vars: &[(&str, &str)]) -> BTreeMap<String, String> {
|
||||
vars.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect()
|
||||
}
|
||||
|
||||
fn run(program: &str, args: &[&str], env: &[(&str, &str)], encoding: &str, windows: bool) -> EncodingFix {
|
||||
let args: Vec<String> = args.iter().map(|a| (*a).to_owned()).collect();
|
||||
fix(program, &args, &vars(env), |_| None, encoding, windows)
|
||||
}
|
||||
|
||||
fn tool_env(f: &EncodingFix) -> Option<&str> {
|
||||
f.env.iter().find(|(k, _)| k == TOOL_OPTIONS).map(|(_, v)| v.as_str())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_launches_write_the_console_encoding_on_windows() {
|
||||
let mut expected: Vec<&str> = STD_UTF8.to_vec();
|
||||
expected.push("-Dfile.encoding=UTF-8");
|
||||
// A source-file launch through the Oracle `javapath` shim, and an Application / Spring Boot launch.
|
||||
let java = "C:/Program Files/Common Files/Oracle/Java/javapath/java.exe";
|
||||
for program in [java, "java", "javaw.exe", r"C:\jdk\bin\java.exe", "JAVA.EXE"] {
|
||||
for args in [&["Main.java"][..], &["-cp", "a;b", "org.dromara.DromaraApplication"]] {
|
||||
let f = run(program, args, &[], "UTF-8", true);
|
||||
assert_eq!(f.java_args, expected, "{program}");
|
||||
assert!(f.env.is_empty() && f.notice.is_none());
|
||||
}
|
||||
}
|
||||
// Another console encoding: the streams follow it, the default charset stays the platform's.
|
||||
assert_eq!(
|
||||
run("java", &["-cp", "x", "a.Main"], &[], "GBK", true).java_args,
|
||||
[
|
||||
"-Dstdout.encoding=GBK",
|
||||
"-Dstderr.encoding=GBK",
|
||||
"-Dsun.stdout.encoding=GBK",
|
||||
"-Dsun.stderr.encoding=GBK"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_changes_where_output_already_matches() {
|
||||
for (program, args) in [("java", vec!["Main.java"]), ("mvn", vec!["package"]), ("python3", vec!["a.py"])] {
|
||||
assert_eq!(run(program, &args, &[], "UTF-8", false), EncodingFix::default(), "{program}");
|
||||
assert_eq!(run(program, &args, &[], "utf8", false), EncodingFix::default(), "{program}");
|
||||
assert_eq!(run(program, &args, &[], "", true), EncodingFix::default(), "{program}");
|
||||
}
|
||||
for program in ["node", "cargo", "go", "npm.cmd", "cmd.exe", "javac-wrapper"] {
|
||||
assert_eq!(run(program, &[], &[], "UTF-8", true), EncodingFix::default(), "{program}");
|
||||
}
|
||||
// A console set to another encoding elsewhere still gets it.
|
||||
assert_eq!(run("java", &["Main"], &[], "GBK", false).java_args.len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_chosen_by_the_user_win() {
|
||||
let f = run("java", &["-Dstdout.encoding=GBK", "Main"], &[], "UTF-8", true);
|
||||
assert_eq!(f.java_args, ["-Dfile.encoding=UTF-8"]);
|
||||
let f = run("java", &["-Dfile.encoding=GBK", "Main"], &[], "UTF-8", true);
|
||||
assert_eq!(f.java_args, STD_UTF8);
|
||||
for key in ["JDK_JAVA_OPTIONS", TOOL_OPTIONS] {
|
||||
let f = run("java", &["Main"], &[(key, "-Dsun.stdout.encoding=GBK -Dfile.encoding=GBK")], "UTF-8", true);
|
||||
assert!(f.java_args.is_empty(), "{key}");
|
||||
}
|
||||
assert!(run("mvn.cmd", &[], &[(TOOL_OPTIONS, "-Dstdout.encoding=GBK")], "UTF-8", true).env.is_empty());
|
||||
assert!(run("python.exe", &[], &[("PYTHONIOENCODING", "gbk")], "UTF-8", true).env.is_empty());
|
||||
}
|
||||
|
||||
/// Maven's `spring-boot:run` and Surefire, Gradle's `bootRun` and test workers fork JVMs
|
||||
/// that never see `MAVEN_OPTS` / `GRADLE_OPTS`: the options go where every JVM reads them.
|
||||
#[test]
|
||||
fn build_tools_reach_the_jvms_they_fork() {
|
||||
for program in [
|
||||
"mvn.cmd",
|
||||
"mvnw.cmd",
|
||||
r"C:\maven\bin\mvn.cmd",
|
||||
"mvnd.cmd",
|
||||
"gradlew.bat",
|
||||
"gradle.bat",
|
||||
"sbt.bat",
|
||||
"kotlinc.bat",
|
||||
] {
|
||||
let f = run(program, &["spring-boot:run"], &[], "UTF-8", true);
|
||||
assert_eq!(tool_env(&f), Some(TOOL_UTF8), "{program}");
|
||||
assert_eq!(f.notice.as_deref(), Some(format!("Picked up JAVA_TOOL_OPTIONS: {TOOL_UTF8}").as_str()));
|
||||
assert!(f.java_args.is_empty());
|
||||
assert!(!tool_env(&f).unwrap().contains("file.encoding"), "a build's source encoding is left alone");
|
||||
}
|
||||
// Existing options are kept, from the configuration or the inherited environment; the
|
||||
// JVMs then print the user's own variable, which stays visible.
|
||||
let f = run("mvn.cmd", &[], &[(TOOL_OPTIONS, "-javaagent:a.jar")], "UTF-8", true);
|
||||
assert_eq!(tool_env(&f), Some(format!("-javaagent:a.jar {TOOL_UTF8}").as_str()));
|
||||
assert!(f.notice.is_none());
|
||||
let inherited =
|
||||
fix("gradlew.bat", &[], &BTreeMap::new(), |k| (k == TOOL_OPTIONS).then(|| "-Xss4m".into()), "UTF-8", true);
|
||||
assert_eq!(tool_env(&inherited), Some(format!("-Xss4m {TOOL_UTF8}").as_str()));
|
||||
for program in ["python.exe", "python3", "python3.12", "py.exe", "uv.exe", "poetry"] {
|
||||
assert_eq!(
|
||||
run(program, &[], &[], "UTF-8", true).env,
|
||||
[("PYTHONIOENCODING".to_owned(), "UTF-8".to_owned())],
|
||||
"{program}"
|
||||
);
|
||||
}
|
||||
assert_eq!(run("python3", &[], &[], "GBK", false).env, [("PYTHONIOENCODING".to_owned(), "GBK".to_owned())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shell_command_lines_get_variables_from_their_first_word() {
|
||||
let line = |l: &str| fix_command_line(l, &BTreeMap::new(), |_| None, "UTF-8", true);
|
||||
for l in [
|
||||
"mvn spring-boot:run -pl ruoyi-admin",
|
||||
"\"C:\\Program Files\\Maven\\bin\\mvn.cmd\" test",
|
||||
"java -jar app.jar",
|
||||
] {
|
||||
let f = line(l);
|
||||
assert_eq!(tool_env(&f), Some(TOOL_UTF8), "{l}");
|
||||
assert!(f.java_args.is_empty());
|
||||
}
|
||||
assert_eq!(line("python manage.py runserver").env[0].0, "PYTHONIOENCODING");
|
||||
assert_eq!(line("npm run dev && echo done"), EncodingFix::default());
|
||||
assert_eq!(fix_command_line("mvn test", &BTreeMap::new(), |_| None, "UTF-8", false), EncodingFix::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_debug_launches_write_what_java_debug_decodes() {
|
||||
assert_eq!(java_debug_vm_args("", None, true).as_deref(), Some(TOOL_UTF8));
|
||||
assert_eq!(java_debug_vm_args("-Xmx1g", Some(""), true), Some(format!("-Xmx1g {TOOL_UTF8}")));
|
||||
assert_eq!(java_debug_vm_args("", Some("GBK"), true).unwrap().split(' ').next(), Some("-Dstdout.encoding=GBK"));
|
||||
assert_eq!(java_debug_vm_args("-Dstdout.encoding=GBK", None, true), None);
|
||||
assert_eq!(java_debug_vm_args("-Xmx1g", None, false), None);
|
||||
assert!(java_debug_vm_args("", Some("GBK"), false).is_some());
|
||||
}
|
||||
|
||||
fn filtered(chunks: &[&str]) -> String {
|
||||
let mut f = NoticeFilter::new(format!("Picked up JAVA_TOOL_OPTIONS: {TOOL_UTF8}"));
|
||||
let mut out = String::new();
|
||||
for c in chunks {
|
||||
f.filter(c, &mut out);
|
||||
}
|
||||
out.push_str(&f.finish());
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn notice_lines_are_dropped_wherever_the_chunks_split() {
|
||||
let notice = format!("Picked up JAVA_TOOL_OPTIONS: {TOOL_UTF8}");
|
||||
let text =
|
||||
format!("{notice}\r\nerror: one\n{notice}\nPicked up nothing\nPicked up JAVA_TOOL_OPTIONS: -Dx\nlast");
|
||||
let expected = "error: one\nPicked up nothing\nPicked up JAVA_TOOL_OPTIONS: -Dx\nlast";
|
||||
assert_eq!(filtered(&[&text]), expected);
|
||||
// Every split point, also inside the notice and between `\r` and `\n`.
|
||||
for i in 1..text.len() {
|
||||
let (a, b) = text.split_at(i);
|
||||
assert_eq!(filtered(&[a, b]), expected, "split at {i}");
|
||||
}
|
||||
// A line that only starts like it is not held: text mid-line passes through at once.
|
||||
let mut f = NoticeFilter::new(notice.clone());
|
||||
let mut out = String::new();
|
||||
f.filter("Pick a number: ", &mut out);
|
||||
assert_eq!(out, "Pick a number: ");
|
||||
f.filter("Picked", &mut out);
|
||||
assert_eq!(out, "Pick a number: Picked");
|
||||
// A prefix at the end of the stream comes out on finish.
|
||||
assert_eq!(filtered(&["Picked up"]), "Picked up");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
//! Version managers that keep one install per tool version (mise, asdf): where their
|
||||
//! installs and shims live. SDK detection lists the installs; child processes get the
|
||||
//! shims on `PATH` when the manager's shell hook didn't run (an app started from the Dock,
|
||||
//! `mise activate` only in an interactive rc file).
|
||||
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub const MISE: &str = "mise";
|
||||
pub const ASDF: &str = "asdf";
|
||||
|
||||
/// A toolchain the version managers install.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Tool {
|
||||
Java,
|
||||
Node,
|
||||
Python,
|
||||
Go,
|
||||
Maven,
|
||||
Gradle,
|
||||
}
|
||||
|
||||
impl Tool {
|
||||
/// The tool's names in mise and asdf plugins (`nodejs`, `golang` are asdf's).
|
||||
pub fn names(self) -> &'static [&'static str] {
|
||||
match self {
|
||||
Tool::Java => &["java"],
|
||||
Tool::Node => &["node", "nodejs"],
|
||||
Tool::Python => &["python"],
|
||||
Tool::Go => &["go", "golang"],
|
||||
Tool::Maven => &["maven"],
|
||||
Tool::Gradle => &["gradle"],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One version manager's data directory (`installs/`, `shims/`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Manager {
|
||||
pub name: &'static str,
|
||||
pub dir: PathBuf,
|
||||
}
|
||||
|
||||
impl Manager {
|
||||
pub fn shims(&self) -> PathBuf {
|
||||
self.dir.join("shims")
|
||||
}
|
||||
|
||||
/// `installs/<tool>/<version>` directories of `tool`, sorted. The alias links mise
|
||||
/// adds next to an install (`21 -> ./21.0.2`, `latest`) are left out; a link to an
|
||||
/// install elsewhere (`mise link`) is kept.
|
||||
pub fn installs(&self, tool: Tool) -> Vec<PathBuf> {
|
||||
let mut out = Vec::new();
|
||||
for name in tool.names() {
|
||||
let Ok(entries) = std::fs::read_dir(self.dir.join("installs").join(name)) else { continue };
|
||||
for e in entries.flatten() {
|
||||
let path = e.path();
|
||||
let alias = e.file_type().is_ok_and(|t| t.is_symlink())
|
||||
&& std::fs::read_link(&path).is_ok_and(|t| t.is_relative() && t.components().count() <= 2);
|
||||
if !alias && path.is_dir() {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
/// The install of `tool` named `version` exactly (alias links included).
|
||||
pub fn install_named(&self, tool: Tool, version: &str) -> Option<PathBuf> {
|
||||
if version.is_empty() || version.contains(['/', '\\']) || version.starts_with('.') {
|
||||
return None;
|
||||
}
|
||||
tool.names().iter().map(|n| self.dir.join("installs").join(n).join(version)).find(|p| p.is_dir())
|
||||
}
|
||||
}
|
||||
|
||||
/// mise's and asdf's data directories that exist, as this process's environment (and the
|
||||
/// login shell's) set them.
|
||||
pub fn managers() -> Vec<Manager> {
|
||||
let lookup = |k: &str| {
|
||||
crate::process::host_var_os(k)
|
||||
.or_else(|| crate::process::login_env()?.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone()))
|
||||
};
|
||||
let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from);
|
||||
managers_with(&lookup, home.as_deref()).into_iter().filter(|m| m.dir.is_dir()).collect()
|
||||
}
|
||||
|
||||
/// mise: `MISE_DATA_DIR`, else `$XDG_DATA_HOME/mise`, else `~/.local/share/mise`
|
||||
/// (`%LOCALAPPDATA%\mise` on Windows). asdf: `ASDF_DATA_DIR`, else `~/.asdf`.
|
||||
pub fn managers_with(env: &dyn Fn(&str) -> Option<OsString>, home: Option<&Path>) -> Vec<Manager> {
|
||||
let var = |k: &str| env(k).filter(|v| !v.is_empty()).map(PathBuf::from);
|
||||
let mise = var("MISE_DATA_DIR")
|
||||
.or_else(|| var("XDG_DATA_HOME").map(|d| d.join("mise")))
|
||||
.or_else(|| if cfg!(windows) { var("LOCALAPPDATA").map(|d| d.join("mise")) } else { None })
|
||||
.or_else(|| home.map(|h| h.join(".local/share/mise")));
|
||||
let asdf = var("ASDF_DATA_DIR").or_else(|| home.map(|h| h.join(".asdf")));
|
||||
let mut out = Vec::new();
|
||||
out.extend(mise.map(|dir| Manager { name: MISE, dir }));
|
||||
out.extend(asdf.map(|dir| Manager { name: ASDF, dir }));
|
||||
out
|
||||
}
|
||||
|
||||
/// Every install of `tool` with the manager it came from, mise's first.
|
||||
pub fn installs(tool: Tool) -> Vec<(PathBuf, &'static str)> {
|
||||
managers().iter().flat_map(|m| m.installs(tool).into_iter().map(|p| (p, m.name))).collect()
|
||||
}
|
||||
|
||||
/// The manager whose installs `path` lies in.
|
||||
pub fn manager_of(path: &Path) -> Option<&'static str> {
|
||||
manager_in(&managers(), path)
|
||||
}
|
||||
|
||||
pub fn manager_in(managers: &[Manager], path: &Path) -> Option<&'static str> {
|
||||
managers.iter().find_map(|m| {
|
||||
let installs = m.dir.join("installs");
|
||||
let real = dunce::canonicalize(&installs).ok();
|
||||
(path.starts_with(&installs) || real.is_some_and(|r| path.starts_with(r))).then_some(m.name)
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `path` is a version manager's shim (it picks the version by the working directory).
|
||||
pub fn is_shim(path: &Path) -> bool {
|
||||
path.parent().is_some_and(is_shims_dir)
|
||||
}
|
||||
|
||||
/// Whether `dir` is a version manager's `shims` folder.
|
||||
pub fn is_shims_dir(dir: &Path) -> bool {
|
||||
managers().iter().any(|m| m.shims() == dir)
|
||||
}
|
||||
|
||||
/// `path` (a `PATH` value) with the shims of a manager it doesn't reach yet: mise's in
|
||||
/// front (a mise shim runs the next tool on `PATH` when no version is set), asdf's at the
|
||||
/// end (an asdf shim fails then). A `PATH` that has a manager's shims or installs already
|
||||
/// (its shell hook ran) is left as it is for that manager.
|
||||
pub fn path_with_shims(managers: &[Manager], path: &OsStr) -> OsString {
|
||||
let mut dirs: Vec<PathBuf> = if path.is_empty() { Vec::new() } else { std::env::split_paths(path).collect() };
|
||||
let before = dirs.len();
|
||||
for m in managers {
|
||||
let shims = m.shims();
|
||||
let installs = m.dir.join("installs");
|
||||
if !shims.is_dir() || dirs.iter().any(|d| d == &shims || d.starts_with(&installs)) {
|
||||
continue;
|
||||
}
|
||||
if m.name == MISE {
|
||||
dirs.insert(0, shims);
|
||||
} else {
|
||||
dirs.push(shims);
|
||||
}
|
||||
}
|
||||
if dirs.len() == before {
|
||||
return path.to_owned();
|
||||
}
|
||||
std::env::join_paths(dirs).unwrap_or_else(|_| path.to_owned())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(unix)]
|
||||
fn mkdir(p: &Path) {
|
||||
std::fs::create_dir_all(p).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_dirs_follow_the_environment() {
|
||||
let home = Path::new("/home/me");
|
||||
let none = |_: &str| None;
|
||||
let dirs: Vec<_> = managers_with(&none, Some(home)).into_iter().map(|m| (m.name, m.dir)).collect();
|
||||
if !cfg!(windows) {
|
||||
assert_eq!(dirs[0], (MISE, home.join(".local/share/mise")));
|
||||
}
|
||||
assert_eq!(dirs[1], (ASDF, home.join(".asdf")));
|
||||
|
||||
let xdg = |k: &str| (k == "XDG_DATA_HOME").then(|| OsString::from("/xdg"));
|
||||
assert_eq!(managers_with(&xdg, Some(home))[0].dir, Path::new("/xdg/mise"));
|
||||
|
||||
let custom = |k: &str| match k {
|
||||
"MISE_DATA_DIR" => Some(OsString::from("/opt/mise")),
|
||||
"XDG_DATA_HOME" => Some(OsString::from("/xdg")),
|
||||
"ASDF_DATA_DIR" => Some(OsString::from("/opt/asdf")),
|
||||
_ => None,
|
||||
};
|
||||
let dirs: Vec<_> = managers_with(&custom, Some(home)).into_iter().map(|m| m.dir).collect();
|
||||
assert_eq!(dirs, [PathBuf::from("/opt/mise"), PathBuf::from("/opt/asdf")]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn installs_skip_alias_links() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mise = Manager { name: MISE, dir: tmp.path().join("mise") };
|
||||
let node = mise.dir.join("installs/node");
|
||||
mkdir(&node.join("20.11.0"));
|
||||
mkdir(&node.join("22.1.0"));
|
||||
std::os::unix::fs::symlink("./22.1.0", node.join("22")).unwrap();
|
||||
std::os::unix::fs::symlink("./22.1.0", node.join("latest")).unwrap();
|
||||
let elsewhere = tmp.path().join("opt-node");
|
||||
mkdir(&elsewhere);
|
||||
std::os::unix::fs::symlink(&elsewhere, node.join("linked")).unwrap();
|
||||
std::fs::write(node.join(".mise.backend.toml"), "").unwrap();
|
||||
|
||||
let names: Vec<_> =
|
||||
mise.installs(Tool::Node).iter().map(|p| p.file_name().unwrap().to_string_lossy().into_owned()).collect();
|
||||
assert_eq!(names, ["20.11.0", "22.1.0", "linked"]);
|
||||
assert_eq!(mise.install_named(Tool::Node, "22"), Some(node.join("22")));
|
||||
assert_eq!(mise.install_named(Tool::Node, "18"), None);
|
||||
assert_eq!(mise.install_named(Tool::Node, "../node"), None);
|
||||
|
||||
// asdf's plugin names.
|
||||
let asdf = Manager { name: ASDF, dir: tmp.path().join("asdf") };
|
||||
mkdir(&asdf.dir.join("installs/golang/1.22.1"));
|
||||
assert_eq!(asdf.installs(Tool::Go), [asdf.dir.join("installs/golang/1.22.1")]);
|
||||
assert_eq!(manager_in(&[mise.clone(), asdf.clone()], &node.join("20.11.0/bin/node")), Some(MISE));
|
||||
assert_eq!(manager_in(&[mise, asdf], tmp.path()), None);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn shims_join_a_path_the_hook_did_not_set() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mise = Manager { name: MISE, dir: tmp.path().join("mise") };
|
||||
let asdf = Manager { name: ASDF, dir: tmp.path().join("asdf") };
|
||||
let managers = [mise.clone(), asdf.clone()];
|
||||
let path = OsString::from("/usr/bin:/bin");
|
||||
assert_eq!(path_with_shims(&managers, &path), path, "no shims installed");
|
||||
|
||||
mkdir(&mise.shims());
|
||||
mkdir(&asdf.shims());
|
||||
let got = path_with_shims(&managers, &path);
|
||||
let want = format!("{}:/usr/bin:/bin:{}", mise.shims().display(), asdf.shims().display());
|
||||
assert_eq!(got, OsString::from(want));
|
||||
assert_eq!(path_with_shims(&managers, &got), got, "applied once");
|
||||
|
||||
// `mise activate` put an install on PATH: mise is active, only asdf's shims join.
|
||||
let active = format!("{}:/usr/bin", mise.dir.join("installs/node/22.1.0/bin").display());
|
||||
let got = path_with_shims(&managers, OsStr::new(&active));
|
||||
assert_eq!(got, OsString::from(format!("{active}:{}", asdf.shims().display())));
|
||||
}
|
||||
}
|
||||
@@ -88,10 +88,46 @@ fn hex(bytes: &[u8]) -> String {
|
||||
s
|
||||
}
|
||||
|
||||
/// How [`cell`] shows a value whose bytes are not text.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum Cells {
|
||||
/// Result grids: binary values as `0x…` hex.
|
||||
Display,
|
||||
/// Catalog queries: names and definitions, so bytes are read as UTF-8 whatever the
|
||||
/// column's type (MySQL flags `utf8mb3_bin` catalog columns BINARY, and sends every
|
||||
/// column as binary under `character_set_results = binary`).
|
||||
Text,
|
||||
}
|
||||
|
||||
/// Whether a value of type `ty` is binary data (see [`binary_type`]).
|
||||
fn is_binary<DB: sqlx::Database>(ty: &DB::TypeInfo) -> bool
|
||||
where
|
||||
String: sqlx::Type<DB>,
|
||||
{
|
||||
binary_type(ty.name(), <String as sqlx::Type<DB>>::compatible(ty))
|
||||
}
|
||||
|
||||
/// A BLOB / BINARY type that the driver does not read as text: MySQL flags text in a
|
||||
/// binary collation (`utf8mb4_bin`) BINARY too, and only the `binary` collation is bytes.
|
||||
fn binary_type(name: &str, text: bool) -> bool {
|
||||
let name = name.to_ascii_uppercase();
|
||||
(name.contains("BLOB") || name.contains("BINARY")) && !text
|
||||
}
|
||||
|
||||
/// Bytes as text: UTF-8, else hex (grids) or with invalid sequences replaced (catalog names).
|
||||
fn bytes_text(bytes: Vec<u8>, mode: Cells) -> String {
|
||||
match (String::from_utf8(bytes), mode) {
|
||||
(Ok(s), _) => s,
|
||||
(Err(e), Cells::Display) => hex(e.as_bytes()),
|
||||
(Err(e), Cells::Text) => String::from_utf8_lossy(e.as_bytes()).into_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The text of column `i` of `row`.
|
||||
fn cell<R: Row>(row: &R, i: usize) -> Option<String>
|
||||
fn cell<R: Row>(row: &R, i: usize, mode: Cells) -> Option<String>
|
||||
where
|
||||
usize: ColumnIndex<R>,
|
||||
String: sqlx::Type<R::Database>,
|
||||
for<'r> String: Decode<'r, R::Database>,
|
||||
for<'r> Vec<u8>: Decode<'r, R::Database>,
|
||||
{
|
||||
@@ -99,18 +135,14 @@ where
|
||||
if raw.is_null() {
|
||||
return None;
|
||||
}
|
||||
let ty = raw.type_info().name().to_ascii_uppercase();
|
||||
if ty.contains("BLOB") || ty.contains("BINARY") {
|
||||
let raw = row.try_get_raw(i).ok()?;
|
||||
if mode == Cells::Display && is_binary::<R::Database>(&raw.type_info()) {
|
||||
return <Vec<u8> as Decode<R::Database>>::decode(raw).ok().map(|b| hex(&b));
|
||||
}
|
||||
match <String as Decode<R::Database>>::decode(raw) {
|
||||
Ok(s) => Some(s),
|
||||
Err(_) => {
|
||||
let raw = row.try_get_raw(i).ok()?;
|
||||
<Vec<u8> as Decode<R::Database>>::decode(raw)
|
||||
.ok()
|
||||
.map(|b| String::from_utf8(b).unwrap_or_else(|e| hex(e.as_bytes())))
|
||||
<Vec<u8> as Decode<R::Database>>::decode(raw).ok().map(|b| bytes_text(b, mode))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -122,9 +154,10 @@ fn result_columns<R: Row>(row: &R) -> Vec<ResultColumn> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Streams the results of `$sql` on executor `$exec`, keeping at most `$max` rows.
|
||||
/// Streams the results of `$sql` on executor `$exec`, keeping at most `$max` rows
|
||||
/// with their cells read as `$mode`.
|
||||
macro_rules! fetch {
|
||||
($exec:expr, $sql:expr, $max:expr) => {{
|
||||
($exec:expr, $sql:expr, $max:expr, $mode:expr) => {{
|
||||
use futures::StreamExt;
|
||||
let mut stream = sqlx::raw_sql(sqlx::AssertSqlSafe($sql.to_owned())).fetch_many($exec);
|
||||
let mut columns: Vec<ResultColumn> = Vec::new();
|
||||
@@ -145,7 +178,7 @@ macro_rules! fetch {
|
||||
has_more = true;
|
||||
break;
|
||||
}
|
||||
rows.push((0..row.len()).map(|i| cell(&row, i)).collect());
|
||||
rows.push((0..row.len()).map(|i| cell(&row, i, $mode)).collect());
|
||||
}
|
||||
Err(e) => {
|
||||
failure = Some(db_err(e));
|
||||
@@ -167,7 +200,7 @@ type Fetched = (Vec<ResultColumn>, Vec<Vec<Option<String>>>, Option<u64>, bool,
|
||||
/// The server-side id of a connection (to cancel its statement from another one).
|
||||
macro_rules! backend_id {
|
||||
($conn:expr, $sql:expr) => {{
|
||||
let fetched: IdeResult<Fetched> = fetch!($conn, $sql, 1);
|
||||
let fetched: IdeResult<Fetched> = fetch!($conn, $sql, 1, Cells::Text);
|
||||
fetched
|
||||
.ok()
|
||||
.and_then(|f| f.1.into_iter().next())
|
||||
@@ -431,9 +464,9 @@ impl Pool {
|
||||
with_pool!(self, p => p.is_closed())
|
||||
}
|
||||
|
||||
/// Runs `sql` (no row limit beyond `max`), for introspection.
|
||||
/// Runs `sql` (no row limit beyond `max`), for introspection: cells are text (see [`Cells::Text`]).
|
||||
pub async fn rows(&self, sql: &str, max: usize) -> IdeResult<Vec<Vec<Option<String>>>> {
|
||||
let fetched: IdeResult<Fetched> = with_pool!(self, p => fetch!(p, sql, max));
|
||||
let fetched: IdeResult<Fetched> = with_pool!(self, p => fetch!(p, sql, max, Cells::Text));
|
||||
Ok(fetched?.1)
|
||||
}
|
||||
|
||||
@@ -530,7 +563,7 @@ impl Held {
|
||||
None => None,
|
||||
};
|
||||
let r = tokio::select! {
|
||||
r = async { fetch!(&mut **$conn, sql, max_rows) } => r,
|
||||
r = async { fetch!(&mut **$conn, sql, max_rows, Cells::Display) } => r,
|
||||
() = cancel.cancelled() => Err(IdeError::cancelled()),
|
||||
};
|
||||
if cancel.is_cancelled() {
|
||||
@@ -649,4 +682,35 @@ mod tests {
|
||||
let s = DataSource { properties: vec![prop("cache_size", "-2000")], ..Default::default() };
|
||||
assert_eq!(Setup::of(&s).unwrap().params, [("cache_size".to_owned(), "-2000".to_owned())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_bytes_typed_values_are_binary() {
|
||||
// (type name as the driver reports it, the driver reads it as text, binary)
|
||||
let cases = [
|
||||
("VARBINARY", false, true),
|
||||
("BLOB", false, true),
|
||||
("LONGBLOB", false, true),
|
||||
("BINARY", false, true),
|
||||
// MySQL catalog columns (`utf8mb3_bin`) and `utf8mb4_bin` text: flagged BINARY.
|
||||
("VARBINARY", true, false),
|
||||
("BLOB", true, false),
|
||||
("VARCHAR", true, false),
|
||||
("TEXT", true, false),
|
||||
("BYTEA", false, false),
|
||||
("INT", false, false),
|
||||
];
|
||||
for (name, text, binary) in cases {
|
||||
assert_eq!(binary_type(name, text), binary, "{name} text={text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_bytes_are_names_and_grid_bytes_are_hex() {
|
||||
// `oi_数据` as MySQL sends it under `character_set_results = binary`.
|
||||
let name = "oi_数据".as_bytes().to_vec();
|
||||
assert_eq!(bytes_text(name.clone(), Cells::Text), "oi_数据");
|
||||
assert_eq!(bytes_text(name, Cells::Display), "oi_数据");
|
||||
assert_eq!(bytes_text(vec![0xCA, 0xFE], Cells::Display), "0xCAFE");
|
||||
assert_eq!(bytes_text(vec![b'a', 0xFF], Cells::Text), "a\u{FFFD}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
//! Introspection against a real MySQL / MariaDB server, skipped unless
|
||||
//! `OPENIDEA_TEST_MYSQL=host:port:user:password` names a throwaway server.
|
||||
|
||||
use ide_core::{CancellationToken, IdeResult};
|
||||
use ide_db::{DataSource, DbDriver, DbManager, DbOptions};
|
||||
|
||||
const SCHEMAS: [&str; 2] = ["oi_bin_meta", "oi_数据"];
|
||||
|
||||
fn server() -> Option<(String, u16, String, String)> {
|
||||
let v = std::env::var("OPENIDEA_TEST_MYSQL").ok()?;
|
||||
let mut it = v.splitn(4, ':');
|
||||
Some((it.next()?.into(), it.next()?.parse().ok()?, it.next()?.into(), it.next().unwrap_or("").into()))
|
||||
}
|
||||
|
||||
async fn manager(tmp: &tempfile::TempDir, startup_script: &str) -> Option<DbManager> {
|
||||
let (host, port, user, password) = server()?;
|
||||
let root = tmp.path().to_path_buf();
|
||||
let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
|
||||
let db = DbManager::new(root.clone(), root.join("passwords.json"), root.join("history.json"), ssh);
|
||||
db.save_sources(vec![DataSource {
|
||||
id: "m".into(),
|
||||
name: "mysql".into(),
|
||||
driver: DbDriver::Mysql,
|
||||
host,
|
||||
port: Some(port),
|
||||
user,
|
||||
options: DbOptions { startup_script: startup_script.into(), ..Default::default() },
|
||||
..Default::default()
|
||||
}])
|
||||
.await
|
||||
.unwrap();
|
||||
db.set_password("m", Some(password), false).await.unwrap();
|
||||
Some(db)
|
||||
}
|
||||
|
||||
async fn create_schemas(db: &DbManager) {
|
||||
let c = CancellationToken::new();
|
||||
for s in SCHEMAS {
|
||||
for stmt in [
|
||||
format!("DROP DATABASE IF EXISTS `{s}`"),
|
||||
format!("CREATE DATABASE `{s}` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin"),
|
||||
format!(
|
||||
"CREATE TABLE `{s}`.`用户` (id INT PRIMARY KEY, name VARCHAR(20) COLLATE utf8mb4_bin, raw VARBINARY(4))"
|
||||
),
|
||||
format!("CREATE INDEX `名字` ON `{s}`.`用户` (name)"),
|
||||
format!("INSERT INTO `{s}`.`用户` VALUES (1, 'ann', 0xCAFE)"),
|
||||
] {
|
||||
db.execute("m", &stmt, 10, &c).await.unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn assert_metadata_is_text(db: &DbManager) -> IdeResult<()> {
|
||||
let schemas = db.schemas("m").await?;
|
||||
for s in SCHEMAS {
|
||||
assert!(schemas.iter().any(|n| n == s), "{s} missing from {schemas:?}");
|
||||
let tables = db.tables("m", s).await?;
|
||||
assert_eq!(tables.iter().map(|t| t.name.as_str()).collect::<Vec<_>>(), ["用户"], "tables of {s}");
|
||||
let d = db.table_details("m", s, "用户").await?;
|
||||
let cols: Vec<_> = d.columns.iter().map(|c| c.name.as_str()).collect();
|
||||
assert_eq!(cols, ["id", "name", "raw"]);
|
||||
assert!(d.indexes.iter().any(|i| i.name == "名字"), "{:?}", d.indexes);
|
||||
assert!(db.ddl("m", s, "用户").await?.contains("CREATE TABLE `用户`"));
|
||||
}
|
||||
let completion = db.completion("m").await?;
|
||||
let json = serde_json::to_string(&completion).unwrap();
|
||||
assert!(json.contains("oi_数据") && json.contains("用户"), "{json}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// One test: both phases share the schemas they create.
|
||||
#[tokio::test]
|
||||
async fn metadata_names_are_text_whatever_the_column_collation() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp, "").await else { return Ok(()) };
|
||||
create_schemas(&db).await;
|
||||
// MySQL 8 sends `utf8mb3_bin` catalog names flagged BINARY (lower_case_table_names = 0).
|
||||
assert_metadata_is_text(&db).await?;
|
||||
// `_bin` text is text in the grid; true binary stays hex.
|
||||
let r = db.execute("m", "SELECT name, raw FROM `oi_数据`.`用户`", 10, &CancellationToken::new()).await?;
|
||||
assert_eq!(r.rows, vec![vec![Some("ann".to_owned()), Some("0xCAFE".to_owned())]]);
|
||||
|
||||
// Every text column arrives with the `binary` collation.
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let raw = manager(&tmp, "SET character_set_results = binary").await.unwrap();
|
||||
assert_metadata_is_text(&raw).await
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "ide-fonts"
|
||||
description = "Font families installed on this machine, for the font pickers: CoreText, DirectWrite or fontconfig"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde.workspace = true
|
||||
specta.workspace = true
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
objc2-core-foundation = { version = "0.3", default-features = false, features = ["std", "CFArray", "CFDictionary", "CFNumber", "CFString"] }
|
||||
objc2-core-text = { version = "0.3", default-features = false, features = ["std", "CTFontCollection", "CTFontDescriptor", "CTFontTraits"] }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite"] }
|
||||
@@ -0,0 +1,264 @@
|
||||
//! The font families installed on this machine, for the font pickers in
|
||||
//! Settings (editor, typography fallback, terminal, UI font).
|
||||
//!
|
||||
//! Each platform asks the font system the WebView itself resolves CSS
|
||||
//! `font-family` names against, so every listed name renders: CoreText on
|
||||
//! macOS, DirectWrite on Windows, fontconfig (`fc-list`) on Linux and the BSDs.
|
||||
//! The list is read once per run and cached; the first read can take a few
|
||||
//! hundred milliseconds, so callers run it off the UI and command threads.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
/// One installed family. `monospaced` is the font system's own flag (fixed
|
||||
/// pitch; on Linux also fontconfig's dual-width CJK monospace).
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FontFamily {
|
||||
pub name: String,
|
||||
pub monospaced: bool,
|
||||
}
|
||||
|
||||
/// The installed families, sorted case-insensitively, read on first use.
|
||||
pub fn families() -> &'static [FontFamily] {
|
||||
static CACHE: OnceLock<Vec<FontFamily>> = OnceLock::new();
|
||||
CACHE.get_or_init(|| normalize(imp::list()))
|
||||
}
|
||||
|
||||
/// Merges the per-face records a font system reports into one entry per
|
||||
/// family: trimmed, without empty or hidden (`.`-prefixed system UI) names,
|
||||
/// monospaced when any face is, sorted case-insensitively.
|
||||
pub fn normalize(faces: impl IntoIterator<Item = (String, bool)>) -> Vec<FontFamily> {
|
||||
let mut by_key: BTreeMap<(String, String), bool> = BTreeMap::new();
|
||||
for (name, mono) in faces {
|
||||
let name = name.trim();
|
||||
if name.is_empty() || name.starts_with('.') {
|
||||
continue;
|
||||
}
|
||||
*by_key.entry((name.to_lowercase(), name.to_owned())).or_default() |= mono;
|
||||
}
|
||||
let mut out: Vec<FontFamily> = Vec::with_capacity(by_key.len());
|
||||
for ((key, name), monospaced) in by_key {
|
||||
// Same family under two casings (one font file each): keep the first.
|
||||
if let Some(last) = out.last_mut()
|
||||
&& last.name.to_lowercase() == key
|
||||
{
|
||||
last.monospaced |= monospaced;
|
||||
continue;
|
||||
}
|
||||
out.push(FontFamily { name, monospaced });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Parses `fc-list -f '%{family[0]}\t%{spacing}\n'`: one line per face, the
|
||||
/// spacing empty (proportional) or fontconfig's number or name for it.
|
||||
pub fn parse_fc_list(output: &str) -> Vec<(String, bool)> {
|
||||
output
|
||||
.lines()
|
||||
.filter_map(|line| {
|
||||
let (family, spacing) = line.split_once('\t').unwrap_or((line, ""));
|
||||
let family = family.replace("\\-", "-");
|
||||
let mono = match spacing.trim() {
|
||||
"dual" | "mono" | "charcell" => true,
|
||||
s => s.parse::<u32>().is_ok_and(|n| n >= 90),
|
||||
};
|
||||
(!family.trim().is_empty()).then_some((family, mono))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod imp {
|
||||
use objc2_core_foundation::{CFArray, CFDictionary, CFNumber, CFString, CFType};
|
||||
use objc2_core_text::{
|
||||
CTFontCollection, CTFontDescriptor, CTFontSymbolicTraits, kCTFontFamilyNameAttribute, kCTFontSymbolicTrait,
|
||||
kCTFontTraitsAttribute,
|
||||
};
|
||||
|
||||
/// Every face CoreText makes available to this process, as (family, fixed pitch).
|
||||
pub(crate) fn list() -> Vec<(String, bool)> {
|
||||
// SAFETY: CoreText's documented types: the matching descriptors array
|
||||
// holds CTFontDescriptors and the traits dictionary maps CFString keys.
|
||||
unsafe {
|
||||
let collection = CTFontCollection::from_available_fonts(None);
|
||||
let Some(descriptors) = collection.matching_font_descriptors() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let descriptors: &CFArray<CTFontDescriptor> = descriptors.cast_unchecked();
|
||||
descriptors
|
||||
.iter()
|
||||
.filter_map(|d| {
|
||||
let name = d.attribute(kCTFontFamilyNameAttribute)?.downcast::<CFString>().ok()?.to_string();
|
||||
let traits = d
|
||||
.attribute(kCTFontTraitsAttribute)
|
||||
.and_then(|t| t.downcast::<CFDictionary>().ok())
|
||||
.and_then(|t| t.cast_unchecked::<CFString, CFType>().get(kCTFontSymbolicTrait))
|
||||
.and_then(|n| n.downcast::<CFNumber>().ok())
|
||||
.and_then(|n| n.as_i64())
|
||||
.unwrap_or(0);
|
||||
Some((name, traits as u32 & CTFontSymbolicTraits::TraitMonoSpace.0 != 0))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod imp {
|
||||
use windows::Win32::Graphics::DirectWrite::{
|
||||
DWRITE_FACTORY_TYPE_SHARED, DWRITE_FONT_STRETCH_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_WEIGHT_NORMAL,
|
||||
DWriteCreateFactory, IDWriteFactory, IDWriteFont1, IDWriteLocalizedStrings,
|
||||
};
|
||||
use windows::core::{BOOL, Interface, w};
|
||||
|
||||
/// The system font collection's families, named in English when the
|
||||
/// family has an English name (what CSS matches), else its first name.
|
||||
pub(crate) fn list() -> Vec<(String, bool)> {
|
||||
// SAFETY: plain DirectWrite COM calls on interfaces we own.
|
||||
unsafe { read() }.unwrap_or_default()
|
||||
}
|
||||
|
||||
unsafe fn read() -> windows::core::Result<Vec<(String, bool)>> {
|
||||
let factory: IDWriteFactory = unsafe { DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED) }?;
|
||||
let mut collection = None;
|
||||
unsafe { factory.GetSystemFontCollection(&mut collection, false) }?;
|
||||
let Some(collection) = collection else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for i in 0..unsafe { collection.GetFontFamilyCount() } {
|
||||
let Ok(family) = (unsafe { collection.GetFontFamily(i) }) else {
|
||||
continue;
|
||||
};
|
||||
let Some(name) = unsafe { family.GetFamilyNames() }.ok().and_then(|n| unsafe { english(&n) }) else {
|
||||
continue;
|
||||
};
|
||||
let mono = unsafe {
|
||||
family.GetFirstMatchingFont(
|
||||
DWRITE_FONT_WEIGHT_NORMAL,
|
||||
DWRITE_FONT_STRETCH_NORMAL,
|
||||
DWRITE_FONT_STYLE_NORMAL,
|
||||
)
|
||||
}
|
||||
.ok()
|
||||
.and_then(|f| f.cast::<IDWriteFont1>().ok())
|
||||
.is_some_and(|f| unsafe { f.IsMonospacedFont() }.as_bool());
|
||||
out.push((name, mono));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
unsafe fn english(names: &IDWriteLocalizedStrings) -> Option<String> {
|
||||
let mut index = 0u32;
|
||||
let mut exists = BOOL(0);
|
||||
unsafe { names.FindLocaleName(w!("en-us"), &mut index, &mut exists) }.ok()?;
|
||||
if !exists.as_bool() {
|
||||
index = 0;
|
||||
}
|
||||
let len = unsafe { names.GetStringLength(index) }.ok()? as usize;
|
||||
let mut buf = vec![0u16; len + 1];
|
||||
unsafe { names.GetString(index, &mut buf) }.ok()?;
|
||||
Some(String::from_utf16_lossy(&buf[..len]))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
mod imp {
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
/// fontconfig's view, which WebKitGTK resolves names with. Empty when
|
||||
/// `fc-list` isn't installed.
|
||||
pub(crate) fn list() -> Vec<(String, bool)> {
|
||||
Command::new("fc-list")
|
||||
.args(["-f", "%{family[0]}\t%{spacing}\n"])
|
||||
.stdin(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.output()
|
||||
.ok()
|
||||
.filter(|o| o.status.success())
|
||||
.map(|o| super::parse_fc_list(&String::from_utf8_lossy(&o.stdout)))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
mod imp {
|
||||
pub(crate) fn list() -> Vec<(String, bool)> {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn fam(name: &str, monospaced: bool) -> FontFamily {
|
||||
FontFamily { name: name.into(), monospaced }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_merges_faces_sorts_and_drops_hidden() {
|
||||
let faces = [
|
||||
("Menlo", true),
|
||||
("Arial", false),
|
||||
("Menlo", true),
|
||||
(".SF NS Mono", true),
|
||||
(" ", false),
|
||||
("arial", false),
|
||||
("PingFang SC", false),
|
||||
("Courier New", false),
|
||||
("Courier New", true),
|
||||
("andale mono", true),
|
||||
]
|
||||
.map(|(n, m)| (n.to_owned(), m));
|
||||
assert_eq!(
|
||||
normalize(faces),
|
||||
vec![
|
||||
fam("andale mono", true),
|
||||
fam("Arial", false),
|
||||
fam("Courier New", true),
|
||||
fam("Menlo", true),
|
||||
fam("PingFang SC", false),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fc_list_spacing_marks_monospace() {
|
||||
let out = "DejaVu Sans Mono\t100\nDejaVu Sans\t\nNoto Sans Mono CJK SC\t90\nTerminus\t110\nCantarell\nFira\\-Code\tmono\n\t100\n";
|
||||
assert_eq!(
|
||||
parse_fc_list(out),
|
||||
[
|
||||
("DejaVu Sans Mono", true),
|
||||
("DejaVu Sans", false),
|
||||
("Noto Sans Mono CJK SC", true),
|
||||
("Terminus", true),
|
||||
("Cantarell", false),
|
||||
("Fira-Code", true),
|
||||
]
|
||||
.map(|(n, m)| (n.to_owned(), m))
|
||||
);
|
||||
}
|
||||
|
||||
/// The real font system: every desktop OS ships some fonts, at least one
|
||||
/// of them monospaced, and the list comes back sorted without duplicates.
|
||||
#[cfg(any(target_os = "macos", windows))]
|
||||
#[test]
|
||||
fn lists_installed_families() {
|
||||
let list = families();
|
||||
assert!(list.len() > 20, "only {} families", list.len());
|
||||
assert!(list.iter().any(|f| f.monospaced));
|
||||
assert!(list.iter().any(|f| !f.monospaced));
|
||||
let keys: Vec<String> = list.iter().map(|f| f.name.to_lowercase()).collect();
|
||||
assert!(keys.windows(2).all(|w| w[0] < w[1]));
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let menlo = list.iter().find(|f| f.name == "Menlo").expect("Menlo ships with macOS");
|
||||
assert!(menlo.monospaced);
|
||||
assert!(list.iter().any(|f| f.name == "Helvetica Neue" && !f.monospaced));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,13 @@ use std::path::PathBuf;
|
||||
|
||||
/// Starts a session owned by this window: its events (and those of child sessions) go here only.
|
||||
pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> IdeResult<DebugSessionId> {
|
||||
let mut config = match_java_debug_encoding(config, cfg!(windows));
|
||||
if config.adapter == "debugpy"
|
||||
&& config.request == "launch"
|
||||
&& let Ok(project) = host.project(window)
|
||||
{
|
||||
super::python::prepare_debug(&mut config, &super::python::paths(&project))?;
|
||||
}
|
||||
let label = window;
|
||||
let owner = SessionOwner::new(host.owner_window(label), host.window_sink(label));
|
||||
let settings = match host.project(label) {
|
||||
@@ -20,6 +27,26 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
host.debugger.start_with(config, owner, custom).await
|
||||
}
|
||||
|
||||
/// A JVM launched by java-debug writes what java-debug decodes its output as
|
||||
/// (see [`ide_core::output_encoding::java_debug_vm_args`]).
|
||||
fn match_java_debug_encoding(mut config: LaunchConfig, windows: bool) -> LaunchConfig {
|
||||
if config.adapter != "java-debug" || config.request != "launch" {
|
||||
return config;
|
||||
}
|
||||
let Some(serde_json::Value::Object(mut extra)) =
|
||||
config.extra_json.as_deref().and_then(|e| serde_json::from_str(e).ok())
|
||||
else {
|
||||
return config;
|
||||
};
|
||||
let vm_args = extra.get("vmArgs").and_then(|v| v.as_str()).unwrap_or_default();
|
||||
let encoding = extra.get("encoding").and_then(|v| v.as_str());
|
||||
if let Some(vm_args) = ide_core::output_encoding::java_debug_vm_args(vm_args, encoding, windows) {
|
||||
extra.insert("vmArgs".into(), vm_args.into());
|
||||
config.extra_json = Some(serde_json::Value::Object(extra).to_string());
|
||||
}
|
||||
config
|
||||
}
|
||||
|
||||
pub async fn debug_set_breakpoints(
|
||||
host: &Host,
|
||||
_window: &str,
|
||||
@@ -355,3 +382,46 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
|c| async move { debug_redefine_classes(&c.host, &c.window, c.arg("session")?).await },
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn launch(adapter: &str, request: &str, extra: serde_json::Value) -> LaunchConfig {
|
||||
LaunchConfig {
|
||||
name: "DromaraApplication".into(),
|
||||
adapter: adapter.into(),
|
||||
request: request.into(),
|
||||
program: None,
|
||||
args: vec![],
|
||||
cwd: None,
|
||||
env: Default::default(),
|
||||
extra_json: Some(extra.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn vm_args(config: &LaunchConfig) -> serde_json::Value {
|
||||
serde_json::from_str::<serde_json::Value>(config.extra_json.as_deref().unwrap()).unwrap()["vmArgs"].clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_debug_launches_on_windows_write_utf8() {
|
||||
let extra =
|
||||
serde_json::json!({"mainClass": "org.dromara.DromaraApplication", "vmArgs": "-Xmx1g", "debugServer": 1});
|
||||
let fixed = match_java_debug_encoding(launch("java-debug", "launch", extra.clone()), true);
|
||||
assert_eq!(
|
||||
vm_args(&fixed),
|
||||
"-Xmx1g -Dstdout.encoding=UTF-8 -Dstderr.encoding=UTF-8 -Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8"
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(fixed.extra_json.as_deref().unwrap()).unwrap()["mainClass"],
|
||||
"org.dromara.DromaraApplication"
|
||||
);
|
||||
// Attaching, other adapters and other platforms are left alone.
|
||||
for (adapter, request, windows) in
|
||||
[("java-debug", "attach", true), ("debugpy", "launch", true), ("java-debug", "launch", false)]
|
||||
{
|
||||
assert_eq!(vm_args(&match_java_debug_encoding(launch(adapter, request, extra.clone()), windows)), "-Xmx1g");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ pub mod java;
|
||||
pub mod lsp;
|
||||
pub mod nav;
|
||||
pub mod project;
|
||||
mod python;
|
||||
pub mod refactor;
|
||||
pub mod run;
|
||||
pub mod sdk;
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
use crate::project::Project;
|
||||
use ide_core::IdeResult;
|
||||
use ide_dap::LaunchConfig;
|
||||
use ide_workspace::roots::RootKind;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub(super) fn paths(project: &Project) -> Vec<PathBuf> {
|
||||
let mut paths = vec![project.root.clone()];
|
||||
paths.extend(project.content_roots());
|
||||
for root in project.roots().roots {
|
||||
if matches!(root.kind, RootKind::Source | RootKind::Test) {
|
||||
let path = project.root.join(root.path);
|
||||
if !paths.contains(&path) {
|
||||
paths.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
paths
|
||||
}
|
||||
|
||||
pub(super) fn prepare_debug(config: &mut LaunchConfig, paths: &[PathBuf]) -> IdeResult<()> {
|
||||
// Adapter-specific env takes precedence over the common launch fields in DAP.
|
||||
let mut extra: Option<serde_json::Value> = config.extra_json.as_deref().and_then(|s| serde_json::from_str(s).ok());
|
||||
// A custom adapter may run on another host; local paths are not portable.
|
||||
if extra.as_ref().is_some_and(|e| e.get("debugServer").is_some()) {
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(env) = extra.as_mut().and_then(|e| e.get_mut("env")) {
|
||||
if env.is_null() {
|
||||
*env = serde_json::json!({});
|
||||
}
|
||||
if !env.is_object() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut vars = BTreeMap::new();
|
||||
if let Some(value) = env.get("PYTHONPATH").and_then(|v| v.as_str()) {
|
||||
vars.insert("PYTHONPATH".into(), value.to_owned());
|
||||
}
|
||||
ide_run::python_path::extend(&mut vars, paths, env.get("PYTHONPATH").is_none())?;
|
||||
env["PYTHONPATH"] = serde_json::json!(vars["PYTHONPATH"]);
|
||||
config.extra_json = extra.map(|e| e.to_string());
|
||||
} else {
|
||||
ide_run::python_path::extend(&mut config.env, paths, true)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn debug_preserves_remote_paths_and_handles_null_env() {
|
||||
let root = std::env::temp_dir().join("project");
|
||||
let mut config = LaunchConfig {
|
||||
name: "Python".into(),
|
||||
adapter: "debugpy".into(),
|
||||
request: "launch".into(),
|
||||
program: None,
|
||||
args: vec![],
|
||||
cwd: None,
|
||||
env: BTreeMap::new(),
|
||||
extra_json: Some(serde_json::json!({"env": null, "debugServer": "remote:5678"}).to_string()),
|
||||
};
|
||||
let before = config.extra_json.clone();
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root)).unwrap();
|
||||
assert_eq!(config.extra_json, before);
|
||||
assert!(config.env.is_empty());
|
||||
config.extra_json = Some(serde_json::json!({"env": null}).to_string());
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root)).unwrap();
|
||||
let value: serde_json::Value = serde_json::from_str(config.extra_json.as_deref().unwrap()).unwrap();
|
||||
let paths = std::env::split_paths(value["env"]["PYTHONPATH"].as_str().unwrap()).collect::<Vec<_>>();
|
||||
assert_eq!(paths[0], root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debug_uses_the_effective_environment_field() {
|
||||
for extra in [false, true] {
|
||||
let root = std::env::temp_dir().join("project");
|
||||
let vendor = root.join("vendor");
|
||||
let vars = BTreeMap::from([("PYTHONPATH".into(), vendor.to_string_lossy().into_owned())]);
|
||||
let mut config = LaunchConfig {
|
||||
name: "Python".into(),
|
||||
adapter: "debugpy".into(),
|
||||
request: "launch".into(),
|
||||
program: Some("app/main.py".into()),
|
||||
args: vec![],
|
||||
cwd: None,
|
||||
env: vars.clone(),
|
||||
extra_json: extra.then(|| serde_json::json!({"env": vars}).to_string()),
|
||||
};
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root)).unwrap();
|
||||
let vars: BTreeMap<String, String> = if extra {
|
||||
let value: serde_json::Value = serde_json::from_str(config.extra_json.as_deref().unwrap()).unwrap();
|
||||
serde_json::from_value(value["env"].clone()).unwrap()
|
||||
} else {
|
||||
config.env
|
||||
};
|
||||
assert_eq!(std::env::split_paths(&vars["PYTHONPATH"]).collect::<Vec<_>>(), [root, vendor]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -43,7 +43,10 @@ pub async fn start(host: &Host, window: &str, config: RunConfig, on_output: Emit
|
||||
return Err(IdeError::unavailable(ide_sdk::godot::NOT_FOUND));
|
||||
}
|
||||
let encoding = settings.console.encoding;
|
||||
let options = StartOptions { encoding: Some(encoding).filter(|e| !e.trim().is_empty()) };
|
||||
let options = StartOptions {
|
||||
encoding: Some(encoding).filter(|e| !e.trim().is_empty()),
|
||||
python_paths: super::python::paths(&project),
|
||||
};
|
||||
host.processes.start(&project.root, &config, &options, project.sink.clone(), Box::new(move |c| on_output(c)))
|
||||
}
|
||||
|
||||
|
||||
@@ -21,6 +21,18 @@ pub fn run_system_env(_host: &Host, _window: &str) -> std::collections::BTreeMap
|
||||
ide_run::system_env()
|
||||
}
|
||||
|
||||
/// Writes the Gradle init script that adds `jvm_args` to the JVMs the build forks
|
||||
/// (`bootRun`, `run`, tests) and returns its path, for `--init-script`.
|
||||
pub async fn run_gradle_jvm_args_script(_host: &Host, _window: &str, jvm_args: Vec<String>) -> IdeResult<String> {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
ide_run::gradle_jvm::write_init_script(&ide_run::gradle_jvm::default_dir(), &jvm_args)
|
||||
.map(|p| p.to_string_lossy().into_owned())
|
||||
.map_err(|e| IdeError::internal(format!("cannot write the Gradle init script: {e}")))
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
/// Results from the JUnit XML reports (Surefire, Failsafe, Gradle) of the module at
|
||||
/// `module` (relative to the project root) written since `since_ms` (Unix epoch, ms).
|
||||
pub async fn run_test_reports(
|
||||
@@ -42,6 +54,9 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("run_templates", |c| async move { run_templates(&c.host, &c.window) });
|
||||
d.add("run_save_templates", |c| async move { run_save_templates(&c.host, &c.window, c.arg("templates")?) });
|
||||
d.add("run_system_env", |c| async move { Ok(run_system_env(&c.host, &c.window)) });
|
||||
d.add("run_gradle_jvm_args_script", |c| async move {
|
||||
run_gradle_jvm_args_script(&c.host, &c.window, c.arg("jvmArgs")?).await
|
||||
});
|
||||
d.add("run_test_reports", |c| async move {
|
||||
run_test_reports(&c.host, &c.window, c.arg("module")?, c.arg("sinceMs")?).await
|
||||
});
|
||||
|
||||
@@ -680,13 +680,17 @@ pub async fn vcs_diff_revisions(
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.diff_revisions(&from, &to))).await
|
||||
}
|
||||
|
||||
pub async fn vcs_create_patch(host: &Host, window: &str, source: PatchSource) -> IdeResult<String> {
|
||||
pub async fn vcs_create_patch(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
source: PatchSource,
|
||||
) -> IdeResult<String> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
project.with_repo(|r| match source {
|
||||
project.with_repo_at(repo.as_deref(), |r| match source {
|
||||
PatchSource::Changes { paths, reverse } => {
|
||||
let paths: Vec<PathBuf> = paths.into_iter().map(Into::into).collect();
|
||||
in_primary_repo(&project, &paths)?;
|
||||
r.create_patch(&paths, reverse)
|
||||
}
|
||||
PatchSource::Commits { commits, reverse } => r.create_commits_patch(&commits, reverse),
|
||||
@@ -695,14 +699,24 @@ pub async fn vcs_create_patch(host: &Host, window: &str, source: PatchSource) ->
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn vcs_patch_preview(host: &Host, window: &str, patch: String) -> IdeResult<Vec<PatchFile>> {
|
||||
pub async fn vcs_patch_preview(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
patch: String,
|
||||
) -> IdeResult<Vec<PatchFile>> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.with_repo(|r| r.patch_preview(&patch))).await
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.patch_preview(&patch))).await
|
||||
}
|
||||
|
||||
pub async fn vcs_apply_patch(host: &Host, window: &str, patch: String) -> IdeResult<ApplyOutcome> {
|
||||
pub async fn vcs_apply_patch(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
patch: String,
|
||||
) -> IdeResult<ApplyOutcome> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.with_repo(|r| r.apply_patch(&patch))).await
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.apply_patch(&patch))).await
|
||||
}
|
||||
|
||||
/// Shelve Changes: saves the changes of `paths` as a patch on the shelf and reverts them.
|
||||
@@ -901,9 +915,16 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("vcs_diff_revisions", |c| async move {
|
||||
vcs_diff_revisions(&c.host, &c.window, c.arg("repo")?, c.arg("from")?, c.arg("to")?).await
|
||||
});
|
||||
d.add("vcs_create_patch", |c| async move { vcs_create_patch(&c.host, &c.window, c.arg("source")?).await });
|
||||
d.add("vcs_patch_preview", |c| async move { vcs_patch_preview(&c.host, &c.window, c.arg("patch")?).await });
|
||||
d.add("vcs_apply_patch", |c| async move { vcs_apply_patch(&c.host, &c.window, c.arg("patch")?).await });
|
||||
d.add("vcs_create_patch", |c| async move {
|
||||
vcs_create_patch(&c.host, &c.window, c.arg("repo")?, c.arg("source")?).await
|
||||
});
|
||||
d.add("vcs_patch_preview", |c| async move {
|
||||
vcs_patch_preview(&c.host, &c.window, c.arg("repo")?, c.arg("patch")?).await
|
||||
});
|
||||
d.add(
|
||||
"vcs_apply_patch",
|
||||
|c| async move { vcs_apply_patch(&c.host, &c.window, c.arg("repo")?, c.arg("patch")?).await },
|
||||
);
|
||||
d.add("vcs_shelve", |c| async move { vcs_shelve(&c.host, &c.window, c.arg("name")?, c.arg("paths")?).await });
|
||||
d.add("vcs_shelves", |c| async move { vcs_shelves(&c.host, &c.window) });
|
||||
d.add("vcs_unshelve", |c| async move { vcs_unshelve(&c.host, &c.window, c.arg("id")?, c.arg("remove")?).await });
|
||||
|
||||
@@ -109,7 +109,13 @@ fn server_environment_from_login_shell_and_devcontainer() {
|
||||
let started = project.join("started.txt");
|
||||
wait_for("postStartCommand", || std::fs::read_to_string(&started).is_ok_and(|s| s.ends_with('\n')));
|
||||
assert_eq!(std::fs::read_to_string(&started).unwrap(), "two-demo\n");
|
||||
wait_for("the task to end", || events.0.lock().iter().any(|e| matches!(e, IdeEvent::Task { done: true, .. })));
|
||||
wait_for("postStartCommand to end", || {
|
||||
events
|
||||
.0
|
||||
.lock()
|
||||
.iter()
|
||||
.any(|e| matches!(e, IdeEvent::Task { title, done: true, .. } if title == "postStartCommand"))
|
||||
});
|
||||
assert!(events.0.lock().iter().any(
|
||||
|e| matches!(e, IdeEvent::Task { message: Some(m), title, .. } if m == "post-start-output" && title == "postStartCommand")
|
||||
));
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
//! Repository-scoped patch operations must never fall back to the primary root.
|
||||
use ide_core::NullSink;
|
||||
use ide_host::{Host, HostConfig, ops::vcs};
|
||||
use std::{path::Path, process::Command, sync::Arc, time::Duration};
|
||||
|
||||
fn git(root: &Path, args: &[&str]) -> String {
|
||||
let output = Command::new("git").current_dir(root).args(args).output().unwrap();
|
||||
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
|
||||
String::from_utf8(output.stdout).unwrap().trim().to_owned()
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn patches_read_and_write_the_requested_repository() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let project_root = base.join("project");
|
||||
let roots = [project_root.join("front"), project_root.join("back")];
|
||||
let mut revisions = Vec::new();
|
||||
for (i, root) in roots.iter().enumerate() {
|
||||
std::fs::create_dir_all(root).unwrap();
|
||||
git(root, &["init", "-b", "main"]);
|
||||
git(root, &["config", "user.name", "Test"]);
|
||||
git(root, &["config", "user.email", "[email protected]"]);
|
||||
std::fs::write(root.join("same.txt"), format!("root {i}\n")).unwrap();
|
||||
git(root, &["add", "."]);
|
||||
git(root, &["commit", "-m", "initial"]);
|
||||
std::fs::write(root.join("same.txt"), format!("changed {i}\n")).unwrap();
|
||||
git(root, &["commit", "-am", "change"]);
|
||||
revisions.push(git(root, &["rev-parse", "HEAD"]));
|
||||
}
|
||||
let host = Host::new(HostConfig {
|
||||
config_dir: base.join("config"),
|
||||
data_dir: base.join("data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(NullSink)),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
});
|
||||
let project = host.open_project("main", &project_root).unwrap();
|
||||
for _ in 0..500 {
|
||||
if project.repos().all().len() == 2 {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
assert_eq!(project.repos().all().len(), 2);
|
||||
for (i, root) in roots.iter().enumerate() {
|
||||
let patch = vcs::vcs_create_patch(
|
||||
&host,
|
||||
"main",
|
||||
Some(root.clone()),
|
||||
vcs::PatchSource::Commits { commits: vec![revisions[i].clone()], reverse: true },
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(patch.contains(&format!("-changed {i}")));
|
||||
assert_eq!(vcs::vcs_patch_preview(&host, "main", Some(root.clone()), patch.clone()).await.unwrap().len(), 1);
|
||||
vcs::vcs_apply_patch(&host, "main", Some(root.clone()), patch).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(root.join("same.txt")).unwrap(), format!("root {i}\n"));
|
||||
}
|
||||
assert!(vcs::vcs_apply_patch(&host, "main", Some(base.join("outside")), String::new()).await.is_err());
|
||||
host.close_project("main");
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
//! VM options for the JVMs a Gradle build forks (`bootRun`, `run`, `test`): Gradle has no
|
||||
//! command-line switch for them, so a launch passes an init script that adds them to every
|
||||
//! `JavaExec` and `Test` task (`--init-script <file>`). Gradle's own JVM is left alone.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Groovy string literal (single-quoted, `\` and `'` escaped).
|
||||
fn groovy_string(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len() + 2);
|
||||
out.push('\'');
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'\\' => out.push_str("\\\\"),
|
||||
'\'' => out.push_str("\\'"),
|
||||
'\n' => out.push_str("\\n"),
|
||||
'\r' => out.push_str("\\r"),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out.push('\'');
|
||||
out
|
||||
}
|
||||
|
||||
/// The init script adding `jvm_args` (one argument each) to the forked JVMs.
|
||||
pub fn init_script(jvm_args: &[String]) -> String {
|
||||
let list = jvm_args.iter().map(|a| groovy_string(a)).collect::<Vec<_>>().join(", ");
|
||||
format!(
|
||||
"// Written by OpenIDEA: VM options of the run configuration.\n\
|
||||
allprojects {{\n \
|
||||
tasks.withType(JavaExec).configureEach {{ jvmArgs([{list}]) }}\n \
|
||||
tasks.withType(Test).configureEach {{ jvmArgs([{list}]) }}\n\
|
||||
}}\n"
|
||||
)
|
||||
}
|
||||
|
||||
/// Where the scripts are written.
|
||||
pub fn default_dir() -> PathBuf {
|
||||
std::env::temp_dir().join("openidea-gradle")
|
||||
}
|
||||
|
||||
/// Writes the script for `jvm_args` under `dir` (named by its content, so launches share
|
||||
/// it and nothing needs deleting) and returns its path.
|
||||
pub fn write_init_script(dir: &Path, jvm_args: &[String]) -> std::io::Result<PathBuf> {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let text = init_script(jvm_args);
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
text.hash(&mut h);
|
||||
let file = dir.join(format!("jvm-args-{:016x}.init.gradle", h.finish()));
|
||||
if std::fs::read_to_string(&file).is_ok_and(|t| t == text) {
|
||||
return Ok(file);
|
||||
}
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let tmp = file.with_extension(format!("{}.tmp", std::process::id()));
|
||||
std::fs::write(&tmp, &text)?;
|
||||
std::fs::rename(&tmp, &file).inspect_err(|_| {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
})?;
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn args(a: &[&str]) -> Vec<String> {
|
||||
a.iter().map(|s| (*s).to_owned()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adds_each_argument_to_java_exec_and_test_tasks() {
|
||||
let script = init_script(&args(&["-Ddemo.flag=on", "--add-opens", "java.base/java.lang=ALL-UNNAMED"]));
|
||||
let list = "['-Ddemo.flag=on', '--add-opens', 'java.base/java.lang=ALL-UNNAMED']";
|
||||
assert!(script.contains(&format!("tasks.withType(JavaExec).configureEach {{ jvmArgs({list}) }}")), "{script}");
|
||||
assert!(script.contains(&format!("tasks.withType(Test).configureEach {{ jvmArgs({list}) }}")), "{script}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escapes_quotes_backslashes_and_keeps_spaces_and_dollars() {
|
||||
let script = init_script(&args(&[r"-Dpath=C:\Program Files\app", "-Dq=it's", "-Dv=${x}"]));
|
||||
assert!(script.contains(r"'-Dpath=C:\\Program Files\\app'"), "{script}");
|
||||
assert!(script.contains(r"'-Dq=it\'s'"), "{script}");
|
||||
// Single-quoted Groovy strings don't interpolate.
|
||||
assert!(script.contains("'-Dv=${x}'"), "{script}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writes_one_file_per_content() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let a = write_init_script(dir.path(), &args(&["-Xmx1g"])).unwrap();
|
||||
let again = write_init_script(dir.path(), &args(&["-Xmx1g"])).unwrap();
|
||||
let b = write_init_script(dir.path(), &args(&["-Xmx2g"])).unwrap();
|
||||
assert_eq!(a, again);
|
||||
assert_ne!(a, b);
|
||||
assert_eq!(std::fs::read_to_string(&a).unwrap(), init_script(&args(&["-Xmx1g"])));
|
||||
assert!(a.to_string_lossy().ends_with(".init.gradle"));
|
||||
}
|
||||
}
|
||||
@@ -3,10 +3,11 @@
|
||||
mod config;
|
||||
mod detect;
|
||||
pub mod envfile;
|
||||
pub mod gradle_jvm;
|
||||
pub mod java_cmdline;
|
||||
pub mod junit;
|
||||
mod output_encoding;
|
||||
mod process;
|
||||
pub mod python_path;
|
||||
mod utf8;
|
||||
pub mod which;
|
||||
pub mod wrap;
|
||||
|
||||
@@ -1,167 +0,0 @@
|
||||
//! Makes the output of JVM and Python processes match the console's encoding.
|
||||
//!
|
||||
//! On Windows both write piped output in the ANSI code page (GBK on a Chinese
|
||||
//! system: `javac` errors, Maven / Gradle logs, `print`), while the console decodes
|
||||
//! the configured encoding (UTF-8 by default). They are told which one to use:
|
||||
//! `java` through `stdout.encoding` / `stderr.encoding` (JDK 19+) and their
|
||||
//! `sun.*` forerunners (JDK 8–18), Maven and Gradle through `MAVEN_OPTS` /
|
||||
//! `GRADLE_OPTS`, Python through `PYTHONIOENCODING`.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
const JAVA_PROPERTIES: &[&str] = &["stdout.encoding", "stderr.encoding", "sun.stdout.encoding", "sun.stderr.encoding"];
|
||||
|
||||
/// What a launch needs: `-D` options to put first on a `java` command line, and
|
||||
/// environment variables to set.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct EncodingFix {
|
||||
pub java_args: Vec<String>,
|
||||
pub env: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
fn is_utf8(encoding: &str) -> bool {
|
||||
matches!(encoding.to_ascii_lowercase().replace('_', "-").as_str(), "utf-8" | "utf8")
|
||||
}
|
||||
|
||||
fn java_options(encoding: &str) -> Vec<String> {
|
||||
JAVA_PROPERTIES.iter().map(|p| format!("-D{p}={encoding}")).collect()
|
||||
}
|
||||
|
||||
fn sets_java_encoding(text: &str) -> bool {
|
||||
JAVA_PROPERTIES.iter().any(|p| text.contains(&format!("-D{p}=")))
|
||||
}
|
||||
|
||||
/// The options for a launch of `program` (`args`, environment `vars` over the
|
||||
/// `inherited` one) whose output is decoded as `encoding`; nothing when the
|
||||
/// process already writes it (UTF-8 off Windows) or the user chose the options.
|
||||
pub fn fix(
|
||||
program: &str,
|
||||
args: &[String],
|
||||
vars: &BTreeMap<String, String>,
|
||||
inherited: impl Fn(&str) -> Option<String>,
|
||||
encoding: &str,
|
||||
windows: bool,
|
||||
) -> EncodingFix {
|
||||
let encoding = encoding.trim();
|
||||
let mut out = EncodingFix::default();
|
||||
if encoding.is_empty() || (!windows && is_utf8(encoding)) {
|
||||
return out;
|
||||
}
|
||||
let current = |key: &str| vars.get(key).cloned().or_else(|| inherited(key));
|
||||
let name = crate::wrap::program_name(program).to_ascii_lowercase();
|
||||
match name.as_str() {
|
||||
"java" | "javaw" => {
|
||||
if !args.iter().any(|a| sets_java_encoding(a))
|
||||
&& !current("JDK_JAVA_OPTIONS").is_some_and(|o| sets_java_encoding(&o))
|
||||
{
|
||||
out.java_args = java_options(encoding);
|
||||
}
|
||||
}
|
||||
"mvn" | "mvnw" | "mvnd" | "gradle" | "gradlew" => {
|
||||
let key = if name.starts_with("gradle") { "GRADLE_OPTS" } else { "MAVEN_OPTS" };
|
||||
let opts = current(key).unwrap_or_default();
|
||||
if !sets_java_encoding(&opts) {
|
||||
let added = java_options(encoding).join(" ");
|
||||
let value = if opts.trim().is_empty() { added } else { format!("{} {added}", opts.trim()) };
|
||||
out.env.push((key.to_owned(), value));
|
||||
}
|
||||
}
|
||||
_ if is_python(&name) && current("PYTHONIOENCODING").is_none_or(|v| v.trim().is_empty()) => {
|
||||
out.env.push(("PYTHONIOENCODING".to_owned(), encoding.to_owned()));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `python`, `python3`, `python3.12`, `py`, and the runners that start one.
|
||||
fn is_python(name: &str) -> bool {
|
||||
name == "python"
|
||||
|| name == "py"
|
||||
|| name.strip_prefix("python").is_some_and(|v| v.chars().all(|c| c.is_ascii_digit() || c == '.'))
|
||||
|| matches!(name, "uv" | "poetry" | "pdm" | "pytest" | "pipenv")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn run(program: &str, args: &[&str], vars: &[(&str, &str)], encoding: &str, windows: bool) -> EncodingFix {
|
||||
let args: Vec<String> = args.iter().map(|a| (*a).to_owned()).collect();
|
||||
let vars: BTreeMap<String, String> = vars.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect();
|
||||
fix(program, &args, &vars, |_| None, encoding, windows)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_launches_write_the_console_encoding_on_windows() {
|
||||
let expected = [
|
||||
"-Dstdout.encoding=UTF-8",
|
||||
"-Dstderr.encoding=UTF-8",
|
||||
"-Dsun.stdout.encoding=UTF-8",
|
||||
"-Dsun.stderr.encoding=UTF-8",
|
||||
];
|
||||
// The reported case: a source-file launch through the Oracle `javapath` shim.
|
||||
let java = "C:/Program Files/Common Files/Oracle/Java/javapath/java.exe";
|
||||
for program in [java, "java", "javaw.exe", r"C:\jdk\bin\java.exe"] {
|
||||
let f = run(program, &["Main.java"], &[], "UTF-8", true);
|
||||
assert_eq!(f.java_args, expected, "{program}");
|
||||
assert!(f.env.is_empty());
|
||||
}
|
||||
assert_eq!(run("java", &["-cp", "x", "a.Main"], &[], "GBK", true).java_args[0], "-Dstdout.encoding=GBK");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_changes_where_output_already_matches() {
|
||||
for (program, args) in [("java", vec!["Main.java"]), ("mvn", vec!["package"]), ("python3", vec!["a.py"])] {
|
||||
assert_eq!(run(program, &args, &[], "UTF-8", false), EncodingFix::default(), "{program}");
|
||||
assert_eq!(run(program, &args, &[], "utf8", false), EncodingFix::default(), "{program}");
|
||||
assert_eq!(run(program, &args, &[], "", true), EncodingFix::default(), "{program}");
|
||||
}
|
||||
for program in ["node", "cargo", "go", "npm.cmd", "cmd.exe"] {
|
||||
assert_eq!(run(program, &[], &[], "UTF-8", true), EncodingFix::default(), "{program}");
|
||||
}
|
||||
// A console set to another encoding elsewhere still gets it.
|
||||
assert_eq!(run("java", &["Main"], &[], "GBK", false).java_args.len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_chosen_by_the_user_win() {
|
||||
assert!(run("java", &["-Dstdout.encoding=GBK", "Main"], &[], "UTF-8", true).java_args.is_empty());
|
||||
assert!(
|
||||
run("java", &["Main"], &[("JDK_JAVA_OPTIONS", "-Dsun.stdout.encoding=GBK")], "UTF-8", true)
|
||||
.java_args
|
||||
.is_empty()
|
||||
);
|
||||
assert!(run("mvn.cmd", &[], &[("MAVEN_OPTS", "-Dstdout.encoding=GBK")], "UTF-8", true).env.is_empty());
|
||||
assert!(run("python.exe", &[], &[("PYTHONIOENCODING", "gbk")], "UTF-8", true).env.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_tools_and_python_get_environment_variables() {
|
||||
let opts =
|
||||
"-Dstdout.encoding=UTF-8 -Dstderr.encoding=UTF-8 -Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8";
|
||||
for program in ["mvn.cmd", "mvnw.cmd", r"C:\maven\bin\mvn.cmd"] {
|
||||
assert_eq!(
|
||||
run(program, &["package"], &[], "UTF-8", true).env,
|
||||
[("MAVEN_OPTS".to_owned(), opts.to_owned())]
|
||||
);
|
||||
}
|
||||
for program in ["gradlew.bat", "gradle.bat"] {
|
||||
assert_eq!(run(program, &["build"], &[], "UTF-8", true).env, [("GRADLE_OPTS".to_owned(), opts.to_owned())]);
|
||||
}
|
||||
// Existing options are kept, from the configuration or the inherited environment.
|
||||
let f = run("mvn.cmd", &[], &[("MAVEN_OPTS", "-Xmx1g")], "UTF-8", true);
|
||||
assert_eq!(f.env, [("MAVEN_OPTS".to_owned(), format!("-Xmx1g {opts}"))]);
|
||||
let inherited =
|
||||
fix("gradlew.bat", &[], &BTreeMap::new(), |k| (k == "GRADLE_OPTS").then(|| "-Xmx2g".into()), "UTF-8", true);
|
||||
assert_eq!(inherited.env, [("GRADLE_OPTS".to_owned(), format!("-Xmx2g {opts}"))]);
|
||||
for program in ["python.exe", "python3", "python3.12", "py.exe", "uv.exe", "poetry"] {
|
||||
assert_eq!(
|
||||
run(program, &[], &[], "UTF-8", true).env,
|
||||
[("PYTHONIOENCODING".to_owned(), "UTF-8".to_owned())],
|
||||
"{program}"
|
||||
);
|
||||
}
|
||||
assert_eq!(run("python3", &[], &[], "GBK", false).env, [("PYTHONIOENCODING".to_owned(), "GBK".to_owned())]);
|
||||
}
|
||||
}
|
||||
@@ -77,6 +77,8 @@ impl Entry {
|
||||
pub struct StartOptions {
|
||||
/// Output encoding label (`UTF-8`, `GBK`, `windows-1252`…); `None` = UTF-8.
|
||||
pub encoding: Option<String>,
|
||||
/// Project content and source roots added to Python launch environments.
|
||||
pub python_paths: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -106,6 +108,8 @@ pub(crate) struct Invocation {
|
||||
pub args: Vec<String>,
|
||||
/// Passed verbatim (Windows `cmd /S /C "…"`: cmd does not parse C runtime quoting).
|
||||
pub raw_args: bool,
|
||||
/// A command line run by the platform shell (`display` is the line).
|
||||
pub shell: bool,
|
||||
pub display: String,
|
||||
}
|
||||
|
||||
@@ -141,7 +145,7 @@ pub(crate) fn invocation(config: &RunConfig, cwd: &Path) -> Invocation {
|
||||
display.push(' ');
|
||||
display.push_str("e(a));
|
||||
}
|
||||
Invocation { program, args: config.args.clone(), raw_args: false, display }
|
||||
Invocation { program, args: config.args.clone(), raw_args: false, shell: false, display }
|
||||
}
|
||||
|
||||
/// "Shorten command line" for a `java` launch too long for the platform (see
|
||||
@@ -172,22 +176,25 @@ fn shorten_java(inv: &mut Invocation, config: &RunConfig, cwd: &Path) -> IdeResu
|
||||
}
|
||||
|
||||
/// Tells JVM and Python processes to write the encoding the console decodes (see
|
||||
/// [`crate::output_encoding`]).
|
||||
fn match_console_encoding(inv: &mut Invocation, env: &mut LaunchEnv, config: &RunConfig, options: &StartOptions) {
|
||||
if inv.raw_args {
|
||||
return;
|
||||
}
|
||||
/// [`ide_core::output_encoding`]); returns the notice line to hide from the output.
|
||||
fn match_console_encoding(
|
||||
inv: &mut Invocation,
|
||||
env: &mut LaunchEnv,
|
||||
config: &RunConfig,
|
||||
options: &StartOptions,
|
||||
) -> Option<String> {
|
||||
use ide_core::output_encoding;
|
||||
let inherit = !env.clear;
|
||||
let fix = crate::output_encoding::fix(
|
||||
&inv.program.to_string_lossy(),
|
||||
&inv.args,
|
||||
&env.vars,
|
||||
|key| if inherit { std::env::var(key).ok() } else { None },
|
||||
options.encoding.as_deref().unwrap_or("UTF-8"),
|
||||
cfg!(windows),
|
||||
);
|
||||
let inherited = |key: &str| if inherit { std::env::var(key).ok() } else { None };
|
||||
let encoding = options.encoding.as_deref().unwrap_or("UTF-8");
|
||||
let fix = if inv.shell {
|
||||
output_encoding::fix_command_line(&inv.display, &env.vars, inherited, encoding, cfg!(windows))
|
||||
} else {
|
||||
let program = inv.program.to_string_lossy();
|
||||
output_encoding::fix(&program, &inv.args, &env.vars, inherited, encoding, cfg!(windows))
|
||||
};
|
||||
env.vars.extend(fix.env);
|
||||
if !fix.java_args.is_empty() {
|
||||
if !fix.java_args.is_empty() && !inv.raw_args {
|
||||
inv.args.splice(0..0, fix.java_args);
|
||||
let mut display = quote(config.command.trim());
|
||||
for a in &inv.args {
|
||||
@@ -196,6 +203,7 @@ fn match_console_encoding(inv: &mut Invocation, env: &mut LaunchEnv, config: &Ru
|
||||
}
|
||||
inv.display = display;
|
||||
}
|
||||
fix.notice
|
||||
}
|
||||
|
||||
/// A launch's pathing jar / argfile, deleted when dropped (the process exited, or never started).
|
||||
@@ -217,6 +225,7 @@ fn shell_invocation(command: &str, windows: bool, comspec: Option<String>) -> In
|
||||
program: comspec.filter(|c| !c.is_empty()).unwrap_or_else(|| "cmd.exe".into()).into(),
|
||||
args: vec!["/D".into(), "/S".into(), "/C".into(), format!("\"{command}\"")],
|
||||
raw_args: true,
|
||||
shell: true,
|
||||
display: command.into(),
|
||||
};
|
||||
}
|
||||
@@ -224,6 +233,7 @@ fn shell_invocation(command: &str, windows: bool, comspec: Option<String>) -> In
|
||||
program: "/bin/sh".into(),
|
||||
args: vec!["-c".into(), command.into()],
|
||||
raw_args: false,
|
||||
shell: true,
|
||||
display: command.into(),
|
||||
}
|
||||
}
|
||||
@@ -303,6 +313,9 @@ impl ProcessManager {
|
||||
return Err(IdeError::invalid("input cannot be redirected from a file when emulating a terminal"));
|
||||
}
|
||||
let mut env = launch_env(root, config)?;
|
||||
if matches!(config.kind.as_str(), "python" | "pytest") {
|
||||
crate::python_path::extend(&mut env.vars, &options.python_paths, !env.clear)?;
|
||||
}
|
||||
let on_output: OutputFn = Arc::from(on_output);
|
||||
let on_output = match extras.output_file.as_deref() {
|
||||
Some(file) => tee_output(&resolve_cwd(root, Some(Path::new(file))), on_output)?,
|
||||
@@ -313,10 +326,9 @@ impl ProcessManager {
|
||||
cwd: cwd.clone(),
|
||||
env: env.clone(),
|
||||
});
|
||||
if !extras.emulate_terminal {
|
||||
// A terminal re-encodes output itself; pipes carry the process's bytes as they are.
|
||||
match_console_encoding(&mut inv, &mut env, config, options);
|
||||
}
|
||||
// A terminal re-encodes output itself; pipes carry the process's bytes as they are.
|
||||
let notice =
|
||||
if extras.emulate_terminal { None } else { match_console_encoding(&mut inv, &mut env, config, options) };
|
||||
let temp = shorten_java(&mut inv, config, &cwd)?;
|
||||
if extras.emulate_terminal {
|
||||
return self.start_pty(config, &inv, &cwd, &env, stop, options, sink, on_output, temp);
|
||||
@@ -391,7 +403,7 @@ impl ProcessManager {
|
||||
if let Some(err) = stderr {
|
||||
spawn_reader(id, Stream::Stderr, err, tx.clone())?;
|
||||
}
|
||||
spawn_pump(rx, on_output, entry.clone(), sink, options.encoding.clone())?;
|
||||
spawn_pump(rx, on_output, entry.clone(), sink, options.encoding.clone(), notice)?;
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(e) = result {
|
||||
@@ -484,7 +496,7 @@ impl ProcessManager {
|
||||
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let result = spawn_reader(id, Stream::Stdout, reader, tx.clone())
|
||||
.and_then(|_| spawn_pump(rx, on_output, entry.clone(), sink, options.encoding.clone()));
|
||||
.and_then(|_| spawn_pump(rx, on_output, entry.clone(), sink, options.encoding.clone(), None));
|
||||
if let Err(e) = result {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
@@ -807,10 +819,16 @@ fn spawn_pump(
|
||||
entry: Arc<Entry>,
|
||||
sink: SharedSink,
|
||||
encoding: Option<String>,
|
||||
notice: Option<String>,
|
||||
) -> std::io::Result<()> {
|
||||
std::thread::Builder::new().name(format!("openidea-run-pump-{}", entry.id.0)).spawn(move || {
|
||||
let mut out_dec = OutputDecoder::for_label(encoding.as_deref());
|
||||
let mut err_dec = OutputDecoder::for_label(encoding.as_deref());
|
||||
// "Picked up JAVA_TOOL_OPTIONS: …" from every JVM given the console encoding, on
|
||||
// either stream (`spring-boot:run` copies its fork's stderr to Maven's stdout).
|
||||
let filter = || notice.clone().map(ide_core::output_encoding::NoticeFilter::new);
|
||||
let (mut out_notice, mut err_notice) = (filter(), filter());
|
||||
let mut decoded = String::new();
|
||||
let mut pending = String::new();
|
||||
let mut pending_stream = Stream::Stdout;
|
||||
let mut batch_started: Option<Instant> = None;
|
||||
@@ -840,8 +858,18 @@ fn spawn_pump(
|
||||
flush(&mut pending, pending_stream, &mut batch_started);
|
||||
pending_stream = stream;
|
||||
}
|
||||
let dec = if stream == Stream::Stdout { &mut out_dec } else { &mut err_dec };
|
||||
dec.decode_into(&bytes, &mut pending);
|
||||
let (dec, notice) = match stream {
|
||||
Stream::Stdout => (&mut out_dec, &mut out_notice),
|
||||
Stream::Stderr => (&mut err_dec, &mut err_notice),
|
||||
};
|
||||
match notice {
|
||||
Some(filter) => {
|
||||
dec.decode_into(&bytes, &mut decoded);
|
||||
filter.filter(&decoded, &mut pending);
|
||||
decoded.clear();
|
||||
}
|
||||
None => dec.decode_into(&bytes, &mut pending),
|
||||
}
|
||||
if !pending.is_empty() && batch_started.is_none() {
|
||||
batch_started = Some(Instant::now());
|
||||
}
|
||||
@@ -865,8 +893,15 @@ fn spawn_pump(
|
||||
}
|
||||
}
|
||||
flush(&mut pending, pending_stream, &mut batch_started);
|
||||
for (stream, dec) in [(Stream::Stdout, &mut out_dec), (Stream::Stderr, &mut err_dec)] {
|
||||
let rest = dec.finish();
|
||||
for (stream, dec, notice) in
|
||||
[(Stream::Stdout, &mut out_dec, &mut out_notice), (Stream::Stderr, &mut err_dec, &mut err_notice)]
|
||||
{
|
||||
let mut rest = dec.finish();
|
||||
if let Some(filter) = notice {
|
||||
let tail = std::mem::take(&mut rest);
|
||||
filter.filter(&tail, &mut rest);
|
||||
rest.push_str(&filter.finish());
|
||||
}
|
||||
if !rest.is_empty() {
|
||||
on_output(chunk(stream, rest));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
//! Python imports see the same content/source roots as the IDE.
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub fn extend(env: &mut BTreeMap<String, String>, roots: &[PathBuf], inherit: bool) -> IdeResult<()> {
|
||||
if roots.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let inherited = if inherit { crate::system_env().remove("PYTHONPATH") } else { None };
|
||||
let existing = env.get("PYTHONPATH").or(inherited.as_ref());
|
||||
let mut paths = Vec::new();
|
||||
for root in roots {
|
||||
if !paths.contains(root) {
|
||||
paths.push(root.clone());
|
||||
}
|
||||
}
|
||||
if let Some(existing) = existing {
|
||||
for path in std::env::split_paths(existing) {
|
||||
if !paths.contains(&path) {
|
||||
paths.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
let joined =
|
||||
std::env::join_paths(paths).map_err(|e| IdeError::invalid(format!("invalid Python import path: {e}")))?;
|
||||
env.insert("PYTHONPATH".into(), joined.to_string_lossy().into_owned());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn keeps_configured_paths_without_duplicates_or_system_leaks() {
|
||||
let root = std::env::temp_dir().join("python project");
|
||||
let other = root.join("vendor");
|
||||
let value = std::env::join_paths([&other, &root]).unwrap().to_string_lossy().into_owned();
|
||||
let mut env = BTreeMap::from([("PYTHONPATH".into(), value)]);
|
||||
extend(&mut env, std::slice::from_ref(&root), false).unwrap();
|
||||
assert_eq!(std::env::split_paths(&env["PYTHONPATH"]).collect::<Vec<_>>(), [root, other]);
|
||||
}
|
||||
}
|
||||
@@ -169,3 +169,45 @@ fn extras_round_trip_and_local_file() {
|
||||
assert_eq!(load_templates(dir.path()).unwrap(), vec![template]);
|
||||
assert_eq!(load_user_configs(dir.path()).unwrap(), moved);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jvm_options_persist_in_the_project_file() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let vm = "-Ddemo.flag=on --add-opens java.base/java.lang=ALL-UNNAMED '-Dname=a b'";
|
||||
let args =
|
||||
["-Ddemo.flag=on", "--add-opens", "java.base/java.lang=ALL-UNNAMED", "-Dname=a b", "-cp", "${classpath}"];
|
||||
let mut app = sample().remove(0);
|
||||
app.id = "user:demo".into();
|
||||
app.kind = "spring-boot".into();
|
||||
app.command = "java".into();
|
||||
app.args =
|
||||
args.into_iter().chain(["a.DemoApplication", "--spring.profiles.active=dev"]).map(String::from).collect();
|
||||
app.extras.params = BTreeMap::from([
|
||||
("mainClass".into(), "a.DemoApplication".into()),
|
||||
("vmOptions".into(), vm.into()),
|
||||
("activeProfiles".into(), "dev".into()),
|
||||
("classpath".into(), "${classpath}".into()),
|
||||
]);
|
||||
save_user_configs(dir.path(), std::slice::from_ref(&app)).unwrap();
|
||||
let text = fs::read_to_string(user_configs_path(dir.path())).unwrap();
|
||||
assert!(text.contains(&format!("vmOptions = \"{vm}\"")), "{text}");
|
||||
assert_eq!(load_user_configs(dir.path()).unwrap(), vec![app.clone()]);
|
||||
|
||||
// A file written before the form had these fields loads with its command line only.
|
||||
fs::write(
|
||||
user_configs_path(dir.path()),
|
||||
"[[configurations]]\nid = \"user:old\"\nname = \"Old\"\nkind = \"spring-boot\"\ncommand = \"java\"\n\
|
||||
args = [\"-Xmx1g\", \"-cp\", \"${classpath}\", \"a.App\"]\n",
|
||||
)
|
||||
.unwrap();
|
||||
let old = load_user_configs(dir.path()).unwrap();
|
||||
assert_eq!(old[0].args, ["-Xmx1g", "-cp", "${classpath}", "a.App"]);
|
||||
assert!(old[0].extras.params.is_empty());
|
||||
|
||||
// Templates keep default VM options for new configurations.
|
||||
let mut template = app;
|
||||
template.id = "template:spring-boot".into();
|
||||
template.extras.params = BTreeMap::from([("vmOptions".into(), "-Xmx512m".into())]);
|
||||
ide_run::save_templates(dir.path(), std::slice::from_ref(&template)).unwrap();
|
||||
assert_eq!(ide_run::load_templates(dir.path()).unwrap()[0].extras.params["vmOptions"], "-Xmx512m");
|
||||
}
|
||||
@@ -229,6 +229,39 @@ fn builds_nested_in_a_folder_of_repositories() {
|
||||
assert_eq!(c.iter().filter(|c| c.kind == "spring-boot").count(), 1);
|
||||
}
|
||||
|
||||
/// RuoYi-AI opened from the folder above it (`ites-agent/ruoyi-ai`), or two folders above:
|
||||
/// its application class builds the `SpringApplication` itself.
|
||||
#[test]
|
||||
fn spring_boot_application_of_a_repository_nested_one_or_two_levels_down() {
|
||||
const MAIN: &str = "package org.ruoyi;\n\nimport org.springframework.boot.SpringApplication;\n\
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;\n\n\
|
||||
/**\n * 启动程序\n *\n * @author Lion Li\n */\n@SpringBootApplication\n\
|
||||
public class RuoYiAIApplication {\n\n public static void main(String[] args) {\n\
|
||||
\x20 SpringApplication application = new SpringApplication(RuoYiAIApplication.class);\n\
|
||||
\x20 application.run(args);\n\
|
||||
\x20 System.out.println(\"(♥◠‿◠)ノ゙ RuoYi-AI启动成功 ლ(´ڡ`ლ)\");\n }\n}\n";
|
||||
for prefix in ["", "ites-agent/"] {
|
||||
let file = |p: &str| format!("{prefix}ruoyi-ai/{p}");
|
||||
let files = [
|
||||
(file("pom.xml"), PARENT_POM),
|
||||
(file("ruoyi-admin/pom.xml"), BOOT_POM),
|
||||
(file("ruoyi-admin/src/main/java/org/ruoyi/RuoYiAIApplication.java"), MAIN),
|
||||
(file("ruoyi-admin/src/main/java/org/ruoyi/RuoYiAIServletInitializer.java"), "package org.ruoyi;"),
|
||||
(file("ruoyi-common/pom.xml"), "<project><packaging>pom</packaging></project>"),
|
||||
(file("ruoyi-modules/ruoyi-chat/pom.xml"), "<project/>"),
|
||||
(file("docs/README.md"), "docs"),
|
||||
];
|
||||
let files: Vec<(&str, &str)> = files.iter().map(|(p, t)| (p.as_str(), *t)).collect();
|
||||
let dir = project(&files);
|
||||
let c = detect(dir.path());
|
||||
let module = format!("{prefix}ruoyi-ai/ruoyi-admin");
|
||||
let app = find(&c, &format!("application:{module}:org.ruoyi.RuoYiAIApplication"));
|
||||
assert_eq!((app.name.as_str(), app.kind.as_str()), ("RuoYiAIApplication", "spring-boot"), "{prefix}");
|
||||
assert_eq!(app.cwd.as_deref(), Some(Path::new(&module)));
|
||||
assert!(ids(&c).contains(&format!("maven:spring-boot:run:{prefix}ruoyi-ai").as_str()), "{prefix}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_builds_of_every_kind_and_depth() {
|
||||
let dir = project(&[
|
||||
|
||||
@@ -414,3 +414,57 @@ fn long_java_classpath_is_shortened() {
|
||||
.unwrap_or_else(|| panic!("no pathing jar / argfile in {first}"));
|
||||
assert!(!Path::new(file).exists(), "{file} not deleted");
|
||||
}
|
||||
|
||||
/// A build tool (here a fake `mvn` that forks like `spring-boot:run`) gets the console
|
||||
/// encoding in `JAVA_TOOL_OPTIONS`, and the notice its JVMs print about it is hidden.
|
||||
#[test]
|
||||
fn build_tools_get_the_console_encoding_for_every_jvm() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let h = harness();
|
||||
let mvn = h.root.path().join("mvn");
|
||||
let script = "#!/bin/sh\nnotice() { echo \"Picked up JAVA_TOOL_OPTIONS: $JAVA_TOOL_OPTIONS\" >&2; }\n\
|
||||
notice; echo \"maven $JAVA_TOOL_OPTIONS\"; notice 2>&1; printf 'Consume Time\\243\\272 1 ms\\n' >&2\n";
|
||||
std::fs::write(&mvn, script).unwrap();
|
||||
std::fs::set_permissions(&mvn, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let chunks: Chunks = Arc::default();
|
||||
let sink = chunks.clone();
|
||||
let options = StartOptions { encoding: Some("GBK".into()), ..Default::default() };
|
||||
let config = cfg("t:mvn", mvn.to_str().unwrap(), &["spring-boot:run"]);
|
||||
let info =
|
||||
h.pm.start(h.root.path(), &config, &options, h.sink.clone(), Box::new(move |c| sink.lock().push(c))).unwrap();
|
||||
wait_exit(&h, info.id, Duration::from_secs(10));
|
||||
assert_eq!(
|
||||
text(&chunks, stdout),
|
||||
"maven -Dstdout.encoding=GBK -Dstderr.encoding=GBK -Dsun.stdout.encoding=GBK -Dsun.stderr.encoding=GBK\n"
|
||||
);
|
||||
assert_eq!(text(&chunks, stderr), "Consume Time: 1 ms\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python_scripts_import_sibling_packages_and_preserve_env_file_paths() {
|
||||
for (kind, source_dir) in [("python", ""), ("pytest", "src")] {
|
||||
let h = harness();
|
||||
let root = h.root.path();
|
||||
let source = root.join(source_dir);
|
||||
for dir in [root.join("app"), source.join("helpers"), root.join("vendor")] {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
}
|
||||
std::fs::write(source.join("helpers/__init__.py"), "def hello(): return 'import OK'\n").unwrap();
|
||||
std::fs::write(root.join("vendor/custom.py"), "VALUE = 'vendor OK'\n").unwrap();
|
||||
std::fs::write(
|
||||
root.join("app/main.py"),
|
||||
"from helpers import hello\nfrom custom import VALUE\nprint(hello(), VALUE)\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(root.join(".env"), format!("PYTHONPATH={}\n", root.join("vendor").display())).unwrap();
|
||||
let mut config = cfg("python-imports", "python3", &["app/main.py"]);
|
||||
config.kind = kind.into();
|
||||
config.extras.env_files = vec![".env".into()];
|
||||
let options = StartOptions { python_paths: vec![root.to_owned(), source], ..Default::default() };
|
||||
let chunks: Chunks = Arc::default();
|
||||
let sink = chunks.clone();
|
||||
let info = h.pm.start(root, &config, &options, h.sink.clone(), Box::new(move |c| sink.lock().push(c))).unwrap();
|
||||
assert_eq!(wait_exit(&h, info.id, Duration::from_secs(10)), Some(0), "{}", text(&chunks, stderr));
|
||||
assert_eq!(text(&chunks, stdout), "import OK vendor OK\n");
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,10 @@
|
||||
|
||||
use crate::discover::{project_venv_python, workspace_tsdk};
|
||||
use crate::exec::{path_with, search_path};
|
||||
use crate::{angular, godot, vue};
|
||||
use crate::{angular, godot, pinned, vue};
|
||||
use crate::{bin_dir, exe, venv_of};
|
||||
use ide_core::settings::{LanguageServerSettings, Settings};
|
||||
use ide_core::version_managers::Tool;
|
||||
use ide_language::{LanguageConfig, LanguageServerConfig};
|
||||
use ide_run::RunConfig;
|
||||
use serde_json::{Value, json};
|
||||
@@ -28,14 +29,22 @@ pub fn setting_path(root: &Path, s: &str) -> Option<PathBuf> {
|
||||
}
|
||||
|
||||
/// The project interpreter: the configured one, else a project virtualenv
|
||||
/// (`.venv`, `venv`, …) in `dir` or the project root.
|
||||
/// (`.venv`, `venv`, …) in the project root, else the Python the project pins for mise / asdf.
|
||||
pub fn python_interpreter(root: &Path, s: &Settings) -> Option<PathBuf> {
|
||||
setting_path(root, &s.languages.python.interpreter).or_else(|| project_venv_python(root))
|
||||
setting_path(root, &s.languages.python.interpreter)
|
||||
.or_else(|| project_venv_python(root))
|
||||
.or_else(|| pinned::pinned_python(root))
|
||||
}
|
||||
|
||||
/// The configured `node` executable's directory.
|
||||
/// The configured `node` executable's directory, else the `bin` of the Node.js the
|
||||
/// project pins for mise / asdf.
|
||||
pub(crate) fn node_dir(root: &Path, s: &Settings) -> Option<PathBuf> {
|
||||
setting_path(root, &s.languages.node.interpreter).and_then(|p| p.parent().map(Path::to_path_buf))
|
||||
match setting_path(root, &s.languages.node.interpreter) {
|
||||
Some(p) => p.parent().map(Path::to_path_buf),
|
||||
None => pinned::pinned_install(root, Tool::Node)
|
||||
.map(|(dir, _)| dir.join("bin"))
|
||||
.filter(|bin| bin.join(exe("node")).is_file()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The configured Rust toolchain's `bin` directory and rustup toolchain name.
|
||||
@@ -54,8 +63,10 @@ pub(crate) fn rust_bin(root: &Path, s: &Settings) -> Option<(PathBuf, Option<Str
|
||||
Some((bin, toolchain))
|
||||
}
|
||||
|
||||
/// The configured GOROOT, else the Go the project pins for mise / asdf.
|
||||
pub(crate) fn goroot(root: &Path, s: &Settings) -> Option<PathBuf> {
|
||||
setting_path(root, &s.languages.go.goroot)
|
||||
.or_else(|| pinned::pinned_install(root, Tool::Go).and_then(|(dir, _)| pinned::goroot_in_install(&dir)))
|
||||
}
|
||||
|
||||
/// A JDK setting: a JDK home, its `bin` or its `bin/java`.
|
||||
@@ -64,11 +75,12 @@ fn jdk_setting(root: &Path, value: &str) -> Option<Result<crate::java::Jdk, Path
|
||||
Some(p.ancestors().take(3).find_map(crate::java::jdk_at).ok_or(p))
|
||||
}
|
||||
|
||||
/// The project JDK (`languages.java.jdk`).
|
||||
/// The project JDK (`languages.java.jdk`), else the JDK the project pins for mise / asdf.
|
||||
pub fn project_jdk(root: &Path, s: &Settings) -> Option<crate::java::Jdk> {
|
||||
jdk_setting(root, &s.languages.java.jdk)?
|
||||
.inspect_err(|p| tracing::warn!("project JDK {} is not a JDK home", p.display()))
|
||||
.ok()
|
||||
match jdk_setting(root, &s.languages.java.jdk) {
|
||||
Some(jdk) => jdk.inspect_err(|p| tracing::warn!("project JDK {} is not a JDK home", p.display())).ok(),
|
||||
None => pinned::pinned_install(root, Tool::Java).and_then(|(dir, _)| pinned::jdk_in_install(&dir)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The JDK chosen to run jdtls (`languages.java.jdtlsJdk`): `Ok(None)` when not
|
||||
@@ -85,10 +97,18 @@ pub fn jdtls_jdk(root: &Path, s: &Settings) -> Result<Option<crate::java::Jdk>,
|
||||
}
|
||||
|
||||
/// `mvn` of the configured Maven home (`languages.java.maven.home`): the
|
||||
/// executable itself, `<home>/bin/mvn` or `<bin>/mvn`.
|
||||
/// executable itself, `<home>/bin/mvn` or `<bin>/mvn`; else of the Maven the project
|
||||
/// pins for mise / asdf when it has no Maven wrapper.
|
||||
pub fn maven_command(root: &Path, s: &Settings) -> Option<PathBuf> {
|
||||
let p = setting_path(root, &s.languages.java.maven.home)?;
|
||||
let name = if cfg!(windows) { "mvn.cmd" } else { "mvn" };
|
||||
let Some(p) = setting_path(root, &s.languages.java.maven.home) else {
|
||||
if root.join("mvnw").is_file() || root.join("mvnw.cmd").is_file() {
|
||||
return None;
|
||||
}
|
||||
let (dir, _) = pinned::pinned_install(root, Tool::Maven)?;
|
||||
let homes = std::iter::once(dir.clone()).chain(std::fs::read_dir(&dir).ok()?.flatten().map(|e| e.path()));
|
||||
return homes.map(|h| h.join("bin").join(name)).find(|c| c.is_file());
|
||||
};
|
||||
let found = [p.clone(), p.join("bin").join(name), p.join(name)].into_iter().find(|c| c.is_file());
|
||||
if found.is_none() {
|
||||
tracing::warn!("Maven home {} has no {name}", p.display());
|
||||
@@ -458,6 +478,7 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
|
||||
let jdk = project_jdk(root, s);
|
||||
let mvn = maven_command(root, s);
|
||||
let mvn_options = maven_options(root, s);
|
||||
let gradle = pinned::pinned_install(root, Tool::Gradle).map(|(dir, _)| dir.join("bin"));
|
||||
|
||||
for c in configs.iter_mut() {
|
||||
resolve_run_command(c, root, s);
|
||||
@@ -529,6 +550,11 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
|
||||
if let Some(jdk) = &jdk {
|
||||
c.env.entry("JAVA_HOME".into()).or_insert_with(|| jdk.home.to_string_lossy().into_owned());
|
||||
}
|
||||
if c.kind == "gradle"
|
||||
&& let Some(bin) = gradle.as_ref().filter(|b| b.is_dir())
|
||||
{
|
||||
path_dirs.push(bin.clone());
|
||||
}
|
||||
if c.kind == "maven" && c.detected {
|
||||
if let Some(mvn) = &mvn {
|
||||
c.command = mvn.to_string_lossy().into_owned();
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Finding installed interpreters and toolchains.
|
||||
|
||||
use crate::exec::{query, search_path, which};
|
||||
use crate::{Sdk, SdkKind, bin_dir, exe, home_dir, venv_of};
|
||||
use crate::{Sdk, SdkKind, bin_dir, exe, home_dir, pinned, venv_of};
|
||||
use ide_core::version_managers::{self, Tool};
|
||||
use std::collections::HashSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
@@ -11,7 +12,7 @@ const VERSION_TIMEOUT: Duration = Duration::from_secs(4);
|
||||
/// Installed SDKs of `kind`, project-local ones (`root`) first. Blocking: runs
|
||||
/// `--version` queries in parallel.
|
||||
pub fn detect(kind: SdkKind, root: Option<&Path>) -> Vec<Sdk> {
|
||||
match kind {
|
||||
let mut out = match kind {
|
||||
SdkKind::Python => python(root),
|
||||
SdkKind::Node => node(),
|
||||
SdkKind::PackageManager => package_managers(),
|
||||
@@ -20,7 +21,32 @@ pub fn detect(kind: SdkKind, root: Option<&Path>) -> Vec<Sdk> {
|
||||
SdkKind::TypeScript => typescript(root),
|
||||
SdkKind::Jdk => jdk(),
|
||||
SdkKind::Maven => maven(),
|
||||
};
|
||||
if let Some(root) = root {
|
||||
pinned_first(&mut out, kind, root);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn tool_of(kind: SdkKind) -> Option<Tool> {
|
||||
match kind {
|
||||
SdkKind::Python => Some(Tool::Python),
|
||||
SdkKind::Node => Some(Tool::Node),
|
||||
SdkKind::Go => Some(Tool::Go),
|
||||
SdkKind::Jdk => Some(Tool::Java),
|
||||
SdkKind::Maven => Some(Tool::Maven),
|
||||
SdkKind::PackageManager | SdkKind::Rust | SdkKind::TypeScript => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves the install the project pins for mise / asdf after the project's own SDKs
|
||||
/// (virtualenvs), ahead of the rest.
|
||||
fn pinned_first(sdks: &mut Vec<Sdk>, kind: SdkKind, root: &Path) {
|
||||
let Some((dir, _)) = tool_of(kind).and_then(|t| pinned::pinned_install(root, t)) else { return };
|
||||
let Some(i) = sdks.iter().position(|s| s.path.starts_with(&dir)) else { return };
|
||||
let at = sdks.iter().take_while(|s| s.source == "venv").count().min(i);
|
||||
let sdk = sdks.remove(i);
|
||||
sdks.insert(at, sdk);
|
||||
}
|
||||
|
||||
/// Runs `f` over `items` on scoped threads (version queries spawn processes).
|
||||
@@ -99,6 +125,9 @@ fn python(root: Option<&Path>) -> Vec<Sdk> {
|
||||
for v in subdirs(&home.join(".local/share/uv/python")) {
|
||||
found.push((v.join(bin_dir()).join(exe("python3")), "uv"));
|
||||
}
|
||||
for (v, manager) in version_managers::installs(Tool::Python) {
|
||||
found.extend(pinned::python_in_install(&v).map(|p| (p, manager)));
|
||||
}
|
||||
let mut conda_roots: Vec<PathBuf> =
|
||||
["miniconda3", "anaconda3", "miniforge3", "mambaforge", "micromamba", "opt/miniconda3"]
|
||||
.iter()
|
||||
@@ -118,7 +147,7 @@ fn python(root: Option<&Path>) -> Vec<Sdk> {
|
||||
}
|
||||
}
|
||||
for dir in std::env::split_paths(&search_path()) {
|
||||
if dir.ends_with(".pyenv/shims") {
|
||||
if dir.ends_with(".pyenv/shims") || version_managers::is_shims_dir(&dir) {
|
||||
continue;
|
||||
}
|
||||
let mut names: Vec<String> = std::fs::read_dir(&dir)
|
||||
@@ -177,7 +206,7 @@ pub(crate) fn python_sdk(path: &Path, source: &str, root: Option<&Path>) -> Opti
|
||||
format!("Python {short} (conda: {})", env.unwrap_or_default())
|
||||
}
|
||||
(None, "pyenv") => format!("Python {short} (pyenv)"),
|
||||
(None, "uv") => format!("Python {short} (uv)"),
|
||||
(None, tool @ ("uv" | "mise" | "asdf")) => format!("Python {short} ({tool})"),
|
||||
_ => format!("Python {short}"),
|
||||
};
|
||||
Some(Sdk {
|
||||
@@ -209,8 +238,10 @@ fn subdirs(dir: &Path) -> Vec<PathBuf> {
|
||||
|
||||
fn node() -> Vec<Sdk> {
|
||||
let mut found: Vec<(PathBuf, &'static str)> = Vec::new();
|
||||
if let Some(p) = which("node") {
|
||||
found.push((p, "path"));
|
||||
// A mise / asdf shim picks the version by directory: its installs are listed instead.
|
||||
if let Some(p) = which("node").filter(|p| !version_managers::is_shim(p)) {
|
||||
let source = version_managers::manager_of(&p).unwrap_or("path");
|
||||
found.push((p, source));
|
||||
}
|
||||
if let Some(home) = home_dir() {
|
||||
for v in subdirs(&home.join(".nvm/versions/node")).into_iter().rev() {
|
||||
@@ -223,6 +254,9 @@ fn node() -> Vec<Sdk> {
|
||||
found.push((v.join("installation/bin").join(exe("node")), "fnm"));
|
||||
}
|
||||
}
|
||||
for (v, manager) in version_managers::installs(Tool::Node).into_iter().rev() {
|
||||
found.push((v.join("bin").join(exe("node")), manager));
|
||||
}
|
||||
for p in ["/opt/homebrew/bin/node", "/usr/local/bin/node", "/usr/bin/node"] {
|
||||
found.push((PathBuf::from(p), "system"));
|
||||
}
|
||||
@@ -323,7 +357,7 @@ fn go() -> Vec<Sdk> {
|
||||
let path_go = which("go");
|
||||
let default_gopath =
|
||||
path_go.as_ref().and_then(|go| query(go, &["env", "GOPATH"], VERSION_TIMEOUT)).map(PathBuf::from);
|
||||
if let Some(go) = &path_go
|
||||
if let Some(go) = path_go.as_ref().filter(|p| !version_managers::is_shim(p))
|
||||
&& let Some(root) = query(go, &["env", "GOROOT"], VERSION_TIMEOUT)
|
||||
{
|
||||
roots.push((PathBuf::from(root), "path"));
|
||||
@@ -341,6 +375,9 @@ fn go() -> Vec<Sdk> {
|
||||
}
|
||||
}
|
||||
}
|
||||
for (d, manager) in version_managers::installs(Tool::Go) {
|
||||
roots.extend(pinned::goroot_in_install(&d).map(|r| (r, manager)));
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
roots.retain(|(r, _)| {
|
||||
r.join("bin").join(exe("go")).is_file() && seen.insert(r.canonicalize().unwrap_or_else(|_| r.clone()))
|
||||
@@ -411,7 +448,7 @@ pub fn jdk_sdk(j: &crate::java::Jdk) -> Sdk {
|
||||
} else if crate::java::is_downloaded(&j.home) {
|
||||
"downloaded"
|
||||
} else {
|
||||
"system"
|
||||
version_managers::manager_of(&j.home).unwrap_or("system")
|
||||
};
|
||||
Sdk {
|
||||
path: j.home.clone().into(),
|
||||
@@ -466,6 +503,10 @@ fn maven() -> Vec<Sdk> {
|
||||
for d in subdirs(&home.join(".sdkman/candidates/maven")) {
|
||||
found.push((d, "sdkman"));
|
||||
}
|
||||
for (d, manager) in version_managers::installs(Tool::Maven) {
|
||||
found.extend(subdirs(&d).into_iter().map(|s| (s, manager)));
|
||||
found.push((d, manager));
|
||||
}
|
||||
// Distributions the Maven wrapper downloaded: `dists/apache-maven-3.9.6-bin/<hash>/apache-maven-3.9.6`,
|
||||
// or since wrapper 3.3 the home itself, `dists/apache-maven-3.9.6/<hash>`.
|
||||
for dist in subdirs(&home.join(".m2/wrapper/dists")) {
|
||||
|
||||
@@ -67,7 +67,7 @@ pub fn is_downloaded(home: &Path) -> bool {
|
||||
}
|
||||
|
||||
/// JDK homes in the usual install locations (macOS `JavaVirtualMachines`,
|
||||
/// `/usr/lib/jvm`, SDKMAN, IDEA's `~/.jdks`, Homebrew, Windows vendor
|
||||
/// `/usr/lib/jvm`, SDKMAN, mise, asdf, IDEA's `~/.jdks`, Homebrew, Windows vendor
|
||||
/// directories, the IDE's downloads), `JAVA_HOME` first, then the `java` on `PATH`.
|
||||
fn scan() -> Vec<Jdk> {
|
||||
let mut homes: Vec<PathBuf> = Vec::new();
|
||||
@@ -110,6 +110,10 @@ fn scan() -> Vec<Jdk> {
|
||||
homes.extend([dir.join("Contents/Home"), dir.join("libexec/openjdk.jdk/Contents/Home"), dir]);
|
||||
}
|
||||
}
|
||||
// mise keeps a macOS JDK as its bundle (`<version>/Contents/Home`), asdf flattens it.
|
||||
for (dir, _) in ide_core::version_managers::installs(ide_core::version_managers::Tool::Java) {
|
||||
homes.extend([dir.join("Contents/Home"), dir]);
|
||||
}
|
||||
let mut out: Vec<Jdk> = Vec::new();
|
||||
for h in homes {
|
||||
if let Some(jdk) = jdk_at(&h)
|
||||
@@ -336,6 +340,7 @@ pub fn configure_jdtls(
|
||||
{
|
||||
cfg.args.push(format!("--jvm-arg=-javaagent:{}", jar.to_string_lossy()));
|
||||
}
|
||||
crate::jdtls::add_default_vm_args(&mut cfg.args);
|
||||
let mut all: Vec<Jdk> = Vec::new();
|
||||
for j in project_jdk.into_iter().chain(jdks).chain(server_jdk) {
|
||||
if !all.contains(j) {
|
||||
@@ -529,9 +534,12 @@ mod tests {
|
||||
&bundles,
|
||||
None,
|
||||
);
|
||||
assert_eq!(cfg.args[0], "-data");
|
||||
assert!(cfg.args[1].starts_with("/data/lsp/jdtls/"), "{}", cfg.args[1]);
|
||||
assert_eq!(cfg.args[2], "--jvm-arg=-Djava.import.generatesMetadataFilesAtProjectRoot=false");
|
||||
let defaults: Vec<String> = crate::jdtls::DEFAULT_VM_ARGS.iter().map(|a| format!("--jvm-arg={a}")).collect();
|
||||
let n = defaults.len();
|
||||
assert_eq!(cfg.args[..n], defaults, "our JVM options come first");
|
||||
assert_eq!(cfg.args[n], "-data");
|
||||
assert!(cfg.args[n + 1].starts_with("/data/lsp/jdtls/"), "{}", cfg.args[n + 1]);
|
||||
assert_eq!(cfg.args[n + 2], "--jvm-arg=-Djava.import.generatesMetadataFilesAtProjectRoot=false");
|
||||
let opts = serde_json::to_value(cfg.initialization_options.clone().unwrap()).unwrap();
|
||||
let rt = &opts["settings"]["java"]["configuration"]["runtimes"];
|
||||
assert_eq!(rt[0], json!({ "name": "JavaSE-1.8", "path": "/jdk8" }));
|
||||
@@ -600,7 +608,8 @@ mod tests {
|
||||
assert!(cfg.args.contains(&agent), "{:?}", cfg.args);
|
||||
let mut plain = jdtls();
|
||||
configure_jdtls(&mut plain, Path::new("/p"), Path::new("/data"), &[], None, None, JDTLS_MIN_JAVA, &[], None);
|
||||
assert_ne!(cfg.args[1], plain.args[1], "a separate workspace, so everything is rebuilt with the agent");
|
||||
let data = |c: &LanguageServerConfig| c.args[c.args.iter().position(|a| a == "-data").unwrap() + 1].clone();
|
||||
assert_ne!(data(&cfg), data(&plain), "a separate workspace, so everything is rebuilt with the agent");
|
||||
let before = cfg.clone();
|
||||
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], None, None, JDTLS_MIN_JAVA, &[], Some(jar));
|
||||
assert_eq!(cfg, before, "idempotent");
|
||||
|
||||
@@ -105,6 +105,80 @@ fn split_script_args(args: &[String]) -> ScriptArgs {
|
||||
out
|
||||
}
|
||||
|
||||
/// JVM options jdtls runs with unless the user's set the same thing: a parallel collector
|
||||
/// tuned to give memory back to the OS (resident memory stays near what is live instead of
|
||||
/// growing to the maximum heap), a 2 GB heap limit (the JVM's own is a quarter of physical
|
||||
/// memory), no JVM logging on stdout (the LSP channel), and no scan for installed JDKs at
|
||||
/// start (they are passed as `java.configuration.runtimes`).
|
||||
pub const DEFAULT_VM_ARGS: &[&str] = &[
|
||||
"-XX:+UseParallelGC",
|
||||
"-XX:GCTimeRatio=4",
|
||||
"-XX:AdaptiveSizePolicyWeight=90",
|
||||
"-Dsun.zip.disableMemoryMapping=true",
|
||||
"-Xmx2G",
|
||||
"-Xms100m",
|
||||
"-Xlog:disable",
|
||||
"-DDetectVMInstallationsJob.disabled=true",
|
||||
"-Daether.dependencyCollector.impl=bf",
|
||||
];
|
||||
|
||||
/// What a JVM option sets, so two options setting the same thing can be told apart:
|
||||
/// `-Xmx2G` and `-XX:MaxRAMPercentage=50` both set the heap limit.
|
||||
fn option_key(arg: &str) -> Option<String> {
|
||||
let key = if let Some(name) = arg.strip_prefix("-XX:") {
|
||||
let name = name.trim_start_matches(['+', '-']);
|
||||
let name = name.split_once('=').map_or(name, |(n, _)| n);
|
||||
match name {
|
||||
"MaxHeapSize" | "MaxRAM" | "MaxRAMPercentage" | "MaxRAMFraction" => "Xmx".to_owned(),
|
||||
"InitialHeapSize" | "InitialRAMPercentage" | "InitialRAMFraction" => "Xms".to_owned(),
|
||||
_ if is_collector(name) => "collector".to_owned(),
|
||||
_ => format!("XX:{name}"),
|
||||
}
|
||||
} else if let Some(prop) = arg.strip_prefix("-D") {
|
||||
format!("D:{}", prop.split_once('=').map_or(prop, |(k, _)| k))
|
||||
} else if arg.starts_with("-Xlog") {
|
||||
"Xlog".to_owned()
|
||||
} else if arg.starts_with("-Xmx") {
|
||||
"Xmx".to_owned()
|
||||
} else if arg.starts_with("-Xms") {
|
||||
"Xms".to_owned()
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
Some(key)
|
||||
}
|
||||
|
||||
/// `UseParallelGC`, `UseG1GC`, `UseZGC`, `UseShenandoahGC`, `UseSerialGC`, `UseEpsilonGC`…
|
||||
fn is_collector(name: &str) -> bool {
|
||||
name.starts_with("Use") && name.ends_with("GC") && name.len() > "UseGC".len()
|
||||
}
|
||||
|
||||
/// Our tuning of the parallel collector, meaningless (or rejected) with another one.
|
||||
const COLLECTOR_TUNING: &[&str] = &["GCTimeRatio", "AdaptiveSizePolicyWeight"];
|
||||
|
||||
/// [`DEFAULT_VM_ARGS`] less what `user` (the JVM options already on the command line)
|
||||
/// sets itself. Choosing a collector drops our collector and its tuning altogether.
|
||||
pub fn default_vm_args(user: &[String]) -> Vec<String> {
|
||||
let user_keys: Vec<String> = user.iter().filter_map(|a| option_key(a)).collect();
|
||||
let own_collector = user_keys.iter().any(|k| k == "collector");
|
||||
DEFAULT_VM_ARGS
|
||||
.iter()
|
||||
.filter(|arg| {
|
||||
let key = option_key(arg).expect("default JVM options are keyed");
|
||||
let tuning = COLLECTOR_TUNING.iter().any(|t| key == format!("XX:{t}"));
|
||||
!user_keys.contains(&key) && !(own_collector && (key == "collector" || tuning))
|
||||
})
|
||||
.map(|a| a.to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Adds the [`DEFAULT_VM_ARGS`] the launch doesn't override to `args` (meant for the
|
||||
/// launcher script, so as `--jvm-arg=`), ahead of the user's own.
|
||||
pub fn add_default_vm_args(args: &mut Vec<String>) {
|
||||
let defaults = default_vm_args(&split_script_args(args).jvm);
|
||||
args.splice(0..0, defaults.into_iter().map(|a| format!("--jvm-arg={a}")));
|
||||
}
|
||||
|
||||
/// The JVM command line `bin/jdtls` builds: its system properties and module
|
||||
/// options, the user's `--jvm-arg`s, then the Equinox launcher with `-data`.
|
||||
pub fn java_args(install: &JdtlsInstall, java_major: u32, script_args: &[String]) -> Vec<String> {
|
||||
@@ -127,7 +201,6 @@ pub fn java_args(install: &JdtlsInstall, java_major: u32, script_args: &[String]
|
||||
[
|
||||
"-Dosgi.sharedConfiguration.area.readOnly=true",
|
||||
"-Dosgi.configuration.cascaded=true",
|
||||
"-Xms1G",
|
||||
"--add-modules=ALL-SYSTEM",
|
||||
"--add-opens",
|
||||
"java.base/java.util=ALL-UNNAMED",
|
||||
@@ -222,7 +295,6 @@ mod tests {
|
||||
&format!(r"-Dosgi.sharedConfiguration.area={tools}\config_win"),
|
||||
"-Dosgi.sharedConfiguration.area.readOnly=true",
|
||||
"-Dosgi.configuration.cascaded=true",
|
||||
"-Xms1G",
|
||||
"--add-modules=ALL-SYSTEM",
|
||||
"--add-opens",
|
||||
"java.base/java.util=ALL-UNNAMED",
|
||||
@@ -239,6 +311,81 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
fn keep(user: &[&str]) -> Vec<String> {
|
||||
default_vm_args(&strings(user))
|
||||
}
|
||||
|
||||
fn without(drop: &[&str]) -> Vec<String> {
|
||||
DEFAULT_VM_ARGS.iter().filter(|a| !drop.contains(a)).map(|a| a.to_string()).collect()
|
||||
}
|
||||
|
||||
const PARALLEL: &[&str] = &["-XX:+UseParallelGC", "-XX:GCTimeRatio=4", "-XX:AdaptiveSizePolicyWeight=90"];
|
||||
|
||||
#[test]
|
||||
fn user_options_override_the_defaults() {
|
||||
assert_eq!(keep(&[]), without(&[]));
|
||||
assert_eq!(keep(&["-javaagent:/opt/lombok.jar", "-Dlog.level=ALL"]), without(&[]), "unrelated options");
|
||||
let cases: &[(&[&str], &[&str])] = &[
|
||||
(&["-Xmx4G"], &["-Xmx2G"]),
|
||||
(&["-Xmx512m"], &["-Xmx2G"]),
|
||||
(&["-XX:MaxHeapSize=3g"], &["-Xmx2G"]),
|
||||
(&["-XX:MaxRAMPercentage=40"], &["-Xmx2G"]),
|
||||
(&["-Xms1G"], &["-Xms100m"]),
|
||||
(&["-XX:InitialHeapSize=256m"], &["-Xms100m"]),
|
||||
(&["-XX:+UseG1GC"], PARALLEL),
|
||||
(&["-XX:+UseZGC", "-XX:+ZGenerational"], PARALLEL),
|
||||
(&["-XX:+UseShenandoahGC"], PARALLEL),
|
||||
(&["-XX:+UseSerialGC"], PARALLEL),
|
||||
(&["-XX:-UseParallelGC"], PARALLEL),
|
||||
(&["-XX:+UseParallelGC"], PARALLEL),
|
||||
(&["-XX:GCTimeRatio=9"], &["-XX:GCTimeRatio=4"]),
|
||||
(&["-Xlog:gc*:file=gc.log"], &["-Xlog:disable"]),
|
||||
(&["-Dsun.zip.disableMemoryMapping=false"], &["-Dsun.zip.disableMemoryMapping=true"]),
|
||||
(&["-Daether.dependencyCollector.impl=df"], &["-Daether.dependencyCollector.impl=bf"]),
|
||||
];
|
||||
for (user, dropped) in cases {
|
||||
assert_eq!(keep(user), without(dropped), "{user:?}");
|
||||
}
|
||||
// Not collectors: they keep ours.
|
||||
assert_eq!(keep(&["-XX:+UseStringDeduplication", "-XX:+UseCompressedOops"]), without(&[]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn defaults_go_ahead_of_the_users_options_once() {
|
||||
let user = strings(&["--jvm-arg=-Xmx4G", "-data", "/ws", "--jvm-arg", "-XX:+UseG1GC"]);
|
||||
let mut args = user.clone();
|
||||
add_default_vm_args(&mut args);
|
||||
let dropped: Vec<&str> = PARALLEL.iter().copied().chain(["-Xmx2G"]).collect();
|
||||
let expected: Vec<String> =
|
||||
without(&dropped).into_iter().map(|a| format!("--jvm-arg={a}")).chain(user).collect();
|
||||
assert_eq!(args, expected);
|
||||
add_default_vm_args(&mut args);
|
||||
assert_eq!(args, expected, "idempotent");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_command_line_with_defaults() {
|
||||
// JDK 25 on Windows, "-Xmx3G" in the settings' JVM options.
|
||||
let tools = r"C:\Users\张 三\AppData\Roaming\ai.l0ng.openidea\tools\jdtls";
|
||||
let install = JdtlsInstall {
|
||||
launcher: PathBuf::from(format!(r"{tools}\plugins\org.eclipse.equinox.launcher_1.7.0.jar")),
|
||||
config: PathBuf::from(format!(r"{tools}\config_win")),
|
||||
};
|
||||
let mut script = strings(&["-data", r"C:\Users\张 三\ws", "--jvm-arg=-Xmx3G"]);
|
||||
add_default_vm_args(&mut script);
|
||||
let args = java_args(&install, 25, &script);
|
||||
let jar = args.iter().position(|a| a == "-jar").unwrap();
|
||||
let jvm = &args[..jar];
|
||||
for flag in ["-XX:+UseParallelGC", "-XX:GCTimeRatio=4", "-Xms100m", "-Xlog:disable", "-Xmx3G"] {
|
||||
assert!(jvm.contains(&flag.to_owned()), "{flag}: {jvm:?}");
|
||||
}
|
||||
let heap: Vec<&String> = jvm.iter().filter(|a| option_key(a).as_deref() == Some("Xmx")).collect();
|
||||
assert_eq!(heap, ["-Xmx3G"], "one heap limit, the user's");
|
||||
assert!(!jvm.iter().any(|a| a == "-Xms1G"), "{jvm:?}");
|
||||
assert_eq!(args[jar + 1], format!(r"{tools}\plugins\org.eclipse.equinox.launcher_1.7.0.jar"));
|
||||
assert_eq!(args[jar + 2..], strings(&["-data", r"C:\Users\张 三\ws"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unix_command_line() {
|
||||
let install = JdtlsInstall {
|
||||
|
||||
@@ -16,6 +16,7 @@ pub mod libraries;
|
||||
pub mod locate;
|
||||
pub mod lombok;
|
||||
mod npm;
|
||||
pub mod pinned;
|
||||
pub mod python;
|
||||
mod vue;
|
||||
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
//! Tool versions a project pins for mise / asdf (`mise.toml`, `.tool-versions`), and the
|
||||
//! installs that match them.
|
||||
|
||||
use ide_core::version_managers::{self, Manager, Tool};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// mise's config files in a directory, the one that wins first; `.tool-versions` (asdf's,
|
||||
/// read by mise too) last.
|
||||
const CONFIG_FILES: [&str; 9] = [
|
||||
"mise.local.toml",
|
||||
".mise.local.toml",
|
||||
"mise.toml",
|
||||
".mise.toml",
|
||||
"mise/config.toml",
|
||||
".mise/config.toml",
|
||||
".config/mise.toml",
|
||||
".config/mise/config.toml",
|
||||
".tool-versions",
|
||||
];
|
||||
|
||||
/// The version of `tool` pinned for `root`: the closest directory from `root` up that
|
||||
/// pins it, then the global config (`~/.config/mise/config.toml`).
|
||||
pub fn pinned_version(root: &Path, tool: Tool) -> Option<String> {
|
||||
pinned_version_in(root, &global_configs(), tool)
|
||||
}
|
||||
|
||||
fn pinned_version_in(root: &Path, global: &[PathBuf], tool: Tool) -> Option<String> {
|
||||
let files = root.ancestors().flat_map(|dir| CONFIG_FILES.iter().map(move |f| dir.join(f)));
|
||||
files.chain(global.iter().cloned()).find_map(|file| {
|
||||
let text = std::fs::read_to_string(&file).ok()?;
|
||||
if file.file_name().is_some_and(|n| n == ".tool-versions") {
|
||||
tool_versions_entry(&text, tool)
|
||||
} else {
|
||||
mise_toml_entry(&text, tool)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn global_configs() -> Vec<PathBuf> {
|
||||
let var = |k: &str| ide_core::process::host_var_os(k).filter(|v| !v.is_empty()).map(PathBuf::from);
|
||||
if let Some(file) = var("MISE_GLOBAL_CONFIG_FILE") {
|
||||
return vec![file];
|
||||
}
|
||||
let dir = var("MISE_CONFIG_DIR")
|
||||
.or_else(|| var("XDG_CONFIG_HOME").map(|d| d.join("mise")))
|
||||
.or_else(|| crate::home_dir().map(|h| h.join(".config/mise")));
|
||||
dir.map(|d| vec![d.join("config.toml")]).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The tool's key under `[tools]`: its name, or with a backend (`core:java`, `asdf:maven`).
|
||||
fn is_key_for(key: &str, tool: Tool) -> bool {
|
||||
let name = key.rsplit_once(':').map_or(key, |(_, n)| n);
|
||||
let name = name.rsplit_once('/').map_or(name, |(_, n)| n);
|
||||
tool.names().contains(&name)
|
||||
}
|
||||
|
||||
/// `node = "20"`, `python = ["3.12", "3.11"]` (the first) or `java = { version = "21" }`.
|
||||
fn mise_toml_entry(text: &str, tool: Tool) -> Option<String> {
|
||||
let doc: toml::Table = toml::from_str(text).ok()?;
|
||||
let tools = doc.get("tools")?.as_table()?;
|
||||
let value = tools.iter().find(|(k, _)| is_key_for(k, tool)).map(|(_, v)| v)?;
|
||||
let first = match value {
|
||||
toml::Value::Array(a) => a.first()?,
|
||||
v => v,
|
||||
};
|
||||
let version = match first {
|
||||
toml::Value::String(s) => s.as_str(),
|
||||
toml::Value::Table(t) => t.get("version")?.as_str()?,
|
||||
_ => return None,
|
||||
};
|
||||
Some(version.trim().to_owned()).filter(|v| !v.is_empty())
|
||||
}
|
||||
|
||||
/// `nodejs 20.11.0 18.19.0` (the first version).
|
||||
fn tool_versions_entry(text: &str, tool: Tool) -> Option<String> {
|
||||
text.lines().find_map(|line| {
|
||||
let line = line.split('#').next()?;
|
||||
let mut words = line.split_whitespace();
|
||||
let name = words.next()?;
|
||||
is_key_for(name, tool).then(|| words.next().map(str::to_owned))?
|
||||
})
|
||||
}
|
||||
|
||||
/// Numbers in a version, for ordering (`temurin-21.0.2+13` → 21, 0, 2, 13).
|
||||
fn version_key(v: &str) -> Vec<u64> {
|
||||
v.split(|c: char| !c.is_ascii_digit()).filter_map(|n| n.parse().ok()).collect()
|
||||
}
|
||||
|
||||
/// Whether the install `dir_name` is what mise resolves `version` to: the same name, or a
|
||||
/// longer one it is a prefix of (`21` → `21.0.2`, `temurin-21` → `temurin-21.0.2+13.0.LTS`).
|
||||
fn matches(dir_name: &str, version: &str) -> bool {
|
||||
dir_name == version || dir_name.strip_prefix(version).is_some_and(|rest| rest.starts_with(['.', '-', '+', '_']))
|
||||
}
|
||||
|
||||
/// The install of `tool` that `version` selects among `managers`' installs.
|
||||
fn install_for(managers: &[Manager], tool: Tool, version: &str) -> Option<(PathBuf, &'static str)> {
|
||||
if let Some(path) = version.strip_prefix("path:") {
|
||||
let path = PathBuf::from(path.trim());
|
||||
return path.is_dir().then_some((path, version_managers::MISE));
|
||||
}
|
||||
managers.iter().find_map(|m| {
|
||||
if let Some(exact) = m.install_named(tool, version) {
|
||||
return Some((dunce::canonicalize(&exact).unwrap_or(exact), m.name));
|
||||
}
|
||||
let installs = m.installs(tool);
|
||||
let name = |p: &PathBuf| p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let best = if version == "latest" {
|
||||
installs.into_iter().max_by_key(|p| version_key(&name(p)))
|
||||
} else {
|
||||
installs.into_iter().filter(|p| matches(&name(p), version)).max_by_key(|p| version_key(&name(p)))
|
||||
};
|
||||
best.map(|p| (p, m.name))
|
||||
})
|
||||
}
|
||||
|
||||
/// The mise / asdf install of `tool` that `root` pins, with the manager's name.
|
||||
pub fn pinned_install(root: &Path, tool: Tool) -> Option<(PathBuf, &'static str)> {
|
||||
let version = pinned_version(root, tool)?;
|
||||
install_for(&version_managers::managers(), tool, &version)
|
||||
}
|
||||
|
||||
/// The pinned Python's executable.
|
||||
pub(crate) fn pinned_python(root: &Path) -> Option<PathBuf> {
|
||||
let (dir, _) = pinned_install(root, Tool::Python)?;
|
||||
python_in_install(&dir)
|
||||
}
|
||||
|
||||
/// `bin/python3` of a Python install (`python.exe` at its root on Windows).
|
||||
pub(crate) fn python_in_install(dir: &Path) -> Option<PathBuf> {
|
||||
let candidates = if cfg!(windows) {
|
||||
vec![dir.join("python.exe")]
|
||||
} else {
|
||||
vec![dir.join("bin/python3"), dir.join("bin/python")]
|
||||
};
|
||||
candidates.into_iter().find(|p| p.is_file())
|
||||
}
|
||||
|
||||
/// A Go install's GOROOT: the install itself (mise) or its `go` folder (asdf).
|
||||
pub(crate) fn goroot_in_install(dir: &Path) -> Option<PathBuf> {
|
||||
[dir.to_path_buf(), dir.join("go")].into_iter().find(|d| d.join("bin").join(crate::exe("go")).is_file())
|
||||
}
|
||||
|
||||
/// A JDK install's home: the install itself, or `Contents/Home` of a macOS bundle.
|
||||
pub(crate) fn jdk_in_install(dir: &Path) -> Option<crate::java::Jdk> {
|
||||
[dir.join("Contents/Home"), dir.to_path_buf()].iter().find_map(|h| crate::java::jdk_at(h))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn write(path: &Path, text: &str) {
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, text).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_mise_toml_forms() {
|
||||
let toml = r#"
|
||||
[env]
|
||||
NODE_ENV = "dev"
|
||||
[tools]
|
||||
node = "20"
|
||||
python = ["3.12", "3.11"]
|
||||
"core:java" = { version = "temurin-21", os = ["macos"] }
|
||||
"asdf:mise-plugins/mise-maven" = "3.9.6"
|
||||
"#;
|
||||
assert_eq!(mise_toml_entry(toml, Tool::Node).as_deref(), Some("20"));
|
||||
assert_eq!(mise_toml_entry(toml, Tool::Python).as_deref(), Some("3.12"));
|
||||
assert_eq!(mise_toml_entry(toml, Tool::Java).as_deref(), Some("temurin-21"));
|
||||
assert_eq!(mise_toml_entry(toml, Tool::Maven).as_deref(), None, "the plugin is mise-maven, not maven");
|
||||
assert_eq!(mise_toml_entry("[tools]\nmaven = '3.9.6'\n", Tool::Maven).as_deref(), Some("3.9.6"));
|
||||
assert_eq!(mise_toml_entry(toml, Tool::Go), None);
|
||||
assert_eq!(mise_toml_entry("not toml [", Tool::Node), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_tool_versions() {
|
||||
let text = "# pinned\nnodejs 20.11.0 18.19.0\ngolang 1.22.1 # comment\njava\n";
|
||||
assert_eq!(tool_versions_entry(text, Tool::Node).as_deref(), Some("20.11.0"));
|
||||
assert_eq!(tool_versions_entry(text, Tool::Go).as_deref(), Some("1.22.1"));
|
||||
assert_eq!(tool_versions_entry(text, Tool::Java), None);
|
||||
assert_eq!(tool_versions_entry(text, Tool::Python), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_closest_config_wins_then_the_global_one() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = tmp.path().join("repo");
|
||||
let app = repo.join("apps/web");
|
||||
std::fs::create_dir_all(&app).unwrap();
|
||||
let global = tmp.path().join("global/config.toml");
|
||||
write(&global, "[tools]\nnode = 'lts'\npython = '3.13'\ngo = '1.23'\n");
|
||||
write(&repo.join("mise.toml"), "[tools]\nnode = '20'\njava = '21'\n");
|
||||
write(&repo.join(".tool-versions"), "nodejs 18.0.0\npython 3.11.9\n");
|
||||
write(&app.join(".mise.toml"), "[tools]\nnode = '22'\n");
|
||||
let g = [global];
|
||||
assert_eq!(pinned_version_in(&app, &g, Tool::Node).as_deref(), Some("22"));
|
||||
assert_eq!(pinned_version_in(&repo, &g, Tool::Node).as_deref(), Some("20"), "mise.toml over .tool-versions");
|
||||
assert_eq!(pinned_version_in(&app, &g, Tool::Python).as_deref(), Some("3.11.9"));
|
||||
assert_eq!(pinned_version_in(&app, &g, Tool::Java).as_deref(), Some("21"));
|
||||
assert_eq!(pinned_version_in(&app, &g, Tool::Go).as_deref(), Some("1.23"));
|
||||
assert_eq!(pinned_version_in(&app, &g, Tool::Gradle), None);
|
||||
write(&repo.join("mise.local.toml"), "[tools]\nnode = '21'\n");
|
||||
assert_eq!(pinned_version_in(&repo, &g, Tool::Node).as_deref(), Some("21"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefixes_resolve_to_the_newest_matching_install() {
|
||||
assert!(matches("21.0.2", "21"));
|
||||
assert!(matches("temurin-21.0.2+13.0.LTS", "temurin-21"));
|
||||
assert!(!matches("210.0", "21"));
|
||||
assert!(!matches("3.1.0", "3.12"));
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mise = Manager { name: version_managers::MISE, dir: tmp.path().join("mise") };
|
||||
let asdf = Manager { name: version_managers::ASDF, dir: tmp.path().join("asdf") };
|
||||
for v in ["20.9.0", "20.11.1", "22.1.0"] {
|
||||
std::fs::create_dir_all(mise.dir.join("installs/node").join(v)).unwrap();
|
||||
}
|
||||
std::fs::create_dir_all(asdf.dir.join("installs/nodejs/18.19.0")).unwrap();
|
||||
let managers = [mise.clone(), asdf.clone()];
|
||||
let pick = |v: &str| install_for(&managers, Tool::Node, v).map(|(p, m)| (p.file_name().unwrap().to_owned(), m));
|
||||
assert_eq!(pick("20"), Some(("20.11.1".into(), "mise")));
|
||||
assert_eq!(pick("22.1.0"), Some(("22.1.0".into(), "mise")));
|
||||
assert_eq!(pick("latest"), Some(("22.1.0".into(), "mise")));
|
||||
assert_eq!(pick("18"), Some(("18.19.0".into(), "asdf")));
|
||||
assert_eq!(pick("16"), None);
|
||||
let external = tmp.path().join("node-dev");
|
||||
std::fs::create_dir_all(&external).unwrap();
|
||||
let path = format!("path:{}", external.display());
|
||||
assert_eq!(install_for(&managers, Tool::Node, &path), Some((external, "mise")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
//! mise / asdf installs: detection and the project's pinned versions. One test in its
|
||||
//! own binary: it points `MISE_DATA_DIR` / `ASDF_DATA_DIR` at a fake layout.
|
||||
#![cfg(unix)]
|
||||
|
||||
use ide_core::settings::Settings;
|
||||
use ide_run::RunConfig;
|
||||
use ide_sdk::{Sdk, SdkKind, detect};
|
||||
use std::collections::BTreeMap;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
fn write(path: &Path, text: &str) {
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, text).unwrap();
|
||||
}
|
||||
|
||||
/// An executable that prints `out` (a `--version` answer).
|
||||
fn script(path: &Path, out: &str) {
|
||||
write(path, &format!("#!/bin/sh\necho '{out}'\n"));
|
||||
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
|
||||
fn jdk(home: &Path, version: &str) {
|
||||
write(&home.join("release"), &format!("IMPLEMENTOR=\"Eclipse Adoptium\"\nJAVA_VERSION=\"{version}\"\n"));
|
||||
script(&home.join("bin/java"), version);
|
||||
}
|
||||
|
||||
fn find<'a>(sdks: &'a [Sdk], dir: &Path) -> &'a Sdk {
|
||||
sdks.iter().find(|s| s.path.starts_with(dir)).unwrap_or_else(|| panic!("{} not in {sdks:#?}", dir.display()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mise_and_asdf_installs_are_detected_and_pinned_versions_used() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let tmp = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let mise = tmp.join("mise");
|
||||
let asdf = tmp.join("asdf");
|
||||
// SAFETY: the only test in this binary; nothing else reads the environment yet.
|
||||
unsafe {
|
||||
std::env::set_var("HOME", tmp.join("home"));
|
||||
std::env::set_var("MISE_DATA_DIR", &mise);
|
||||
std::env::set_var("ASDF_DATA_DIR", &asdf);
|
||||
std::env::set_var("MISE_GLOBAL_CONFIG_FILE", tmp.join("no-global.toml"));
|
||||
std::env::remove_var("JAVA_HOME");
|
||||
}
|
||||
|
||||
let installs = mise.join("installs");
|
||||
jdk(&installs.join("java/21.0.2/Contents/Home"), "21.0.2"); // macOS bundle
|
||||
jdk(&asdf.join("installs/java/temurin-17.0.10+7"), "17.0.10");
|
||||
for v in ["20.11.1", "22.1.0"] {
|
||||
script(&installs.join("node").join(v).join("bin/node"), &format!("v{v}"));
|
||||
}
|
||||
std::os::unix::fs::symlink("./22.1.0", installs.join("node/22")).unwrap();
|
||||
script(&installs.join("python/3.12.1/bin/python3"), "Python 3.12.1");
|
||||
let goroot = asdf.join("installs/golang/1.22.1/go");
|
||||
write(&goroot.join("VERSION"), "go1.22.1\n");
|
||||
script(&goroot.join("bin/go"), "go version go1.22.1");
|
||||
let maven = installs.join("maven/3.9.6");
|
||||
script(&maven.join("bin/mvn"), "Apache Maven 3.9.6");
|
||||
write(&maven.join("lib/maven-core-3.9.6.jar"), "");
|
||||
script(&installs.join("gradle/8.7/bin/gradle"), "Gradle 8.7");
|
||||
|
||||
let project = tmp.join("project");
|
||||
write(
|
||||
&project.join("mise.toml"),
|
||||
"[tools]\njava = '21'\nnode = '20'\npython = '3.12'\nmaven = '3.9'\ngradle = '8.7'\n",
|
||||
);
|
||||
write(&project.join(".tool-versions"), "golang 1.22.1\nnodejs 22.1.0\n");
|
||||
|
||||
let jdks = detect(SdkKind::Jdk, Some(&project));
|
||||
let mise_jdk = find(&jdks, &installs.join("java/21.0.2"));
|
||||
assert_eq!((mise_jdk.source.as_str(), mise_jdk.name.as_str()), ("mise", "Eclipse Adoptium 21.0.2"));
|
||||
assert_eq!(find(&jdks, &asdf.join("installs/java")).source, "asdf");
|
||||
assert_eq!(jdks[0].path, mise_jdk.path, "the pinned JDK first");
|
||||
|
||||
let nodes = detect(SdkKind::Node, Some(&project));
|
||||
assert_eq!(nodes[0].path, installs.join("node/20.11.1/bin/node"), "mise.toml over .tool-versions");
|
||||
assert_eq!(find(&nodes, &installs.join("node/22.1.0")).source, "mise");
|
||||
assert_eq!(nodes.iter().filter(|s| s.source == "mise").count(), 2, "the `22` alias is not listed again");
|
||||
|
||||
let pythons = detect(SdkKind::Python, Some(&project));
|
||||
assert_eq!(find(&pythons, &installs.join("python")).name, "Python 3.12 (mise)");
|
||||
|
||||
let gos = detect(SdkKind::Go, Some(&project));
|
||||
let go = find(&gos, &goroot);
|
||||
assert_eq!((go.source.as_str(), go.version.as_deref()), ("asdf", Some("1.22.1")));
|
||||
|
||||
let mavens = detect(SdkKind::Maven, Some(&project));
|
||||
let mvn = find(&mavens, &maven);
|
||||
assert_eq!((mvn.source.as_str(), mvn.version.as_deref()), ("mise", Some("3.9.6")));
|
||||
|
||||
// Nothing configured in Settings: the pinned versions apply.
|
||||
let s = Settings::default();
|
||||
let jdk = ide_sdk::apply::project_jdk(&project, &s).expect("pinned JDK");
|
||||
assert_eq!((jdk.major, jdk.home.clone()), (21, installs.join("java/21.0.2/Contents/Home")));
|
||||
assert_eq!(ide_sdk::apply::python_interpreter(&project, &s), Some(installs.join("python/3.12.1/bin/python3")));
|
||||
assert_eq!(ide_sdk::apply::maven_command(&project, &s), Some(maven.join("bin/mvn")));
|
||||
|
||||
let run = |kind: &str, command: &str| RunConfig {
|
||||
id: format!("{kind}:x"),
|
||||
name: "x".into(),
|
||||
kind: kind.into(),
|
||||
command: command.into(),
|
||||
args: vec![],
|
||||
cwd: None,
|
||||
env: BTreeMap::new(),
|
||||
detected: true,
|
||||
is_test: false,
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
};
|
||||
let mut configs = [run("npm", "npm"), run("go", "go"), run("gradle", "gradle"), run("maven", "mvn")];
|
||||
ide_sdk::apply::apply_to_run_configs(&mut configs, &project, &s);
|
||||
let path_of = |c: &RunConfig| -> Vec<PathBuf> { std::env::split_paths(&c.env["PATH"]).collect() };
|
||||
assert_eq!(path_of(&configs[0])[0], installs.join("node/20.11.1/bin"));
|
||||
assert_eq!(configs[1].command, goroot.join("bin/go").to_string_lossy());
|
||||
assert_eq!(configs[1].env["GOROOT"], goroot.to_string_lossy());
|
||||
assert_eq!(path_of(&configs[2])[0], installs.join("gradle/8.7/bin"));
|
||||
assert_eq!(configs[2].env["JAVA_HOME"], jdk.home.to_string_lossy());
|
||||
assert_eq!(configs[3].command, maven.join("bin/mvn").to_string_lossy());
|
||||
|
||||
// The project's Maven wrapper keeps precedence over a pinned Maven.
|
||||
script(&project.join("mvnw"), "");
|
||||
assert_eq!(ide_sdk::apply::maven_command(&project, &s), None);
|
||||
|
||||
// A version the project pins but that isn't installed: nothing is made up.
|
||||
write(&project.join("mise.toml"), "[tools]\njava = '25'\n");
|
||||
assert_eq!(ide_sdk::apply::project_jdk(&project, &s), None);
|
||||
}
|
||||
@@ -157,8 +157,10 @@ pub fn extend_process_path(app_data: &Path) {
|
||||
}
|
||||
}
|
||||
|
||||
/// `path` (a `PATH` value) with [`tools_bin_dirs`] in front, those it lacks.
|
||||
/// `path` (a `PATH` value) with [`tools_bin_dirs`] in front, those it lacks, and the
|
||||
/// mise / asdf shims when their shell hook didn't put them there.
|
||||
pub fn path_with_tools(app_data: &Path, path: &std::ffi::OsStr) -> OsString {
|
||||
let path = &ide_core::version_managers::path_with_shims(&ide_core::version_managers::managers(), path);
|
||||
let mut dirs = tools_bin_dirs(app_data);
|
||||
let current: Vec<PathBuf> = if path.is_empty() { Vec::new() } else { std::env::split_paths(path).collect() };
|
||||
dirs.retain(|d| !current.contains(d));
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"name": "openidea",
|
||||
"private": true,
|
||||
"description": "An open-source IDE inspired by IntelliJ IDEA",
|
||||
"version": "0.1.23",
|
||||
"version": "0.1.24",
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -36,6 +36,7 @@ dirs.workspace = true
|
||||
ide-core.workspace = true
|
||||
dunce.workspace = true
|
||||
ide-clipboard.workspace = true
|
||||
ide-fonts.workspace = true
|
||||
ide-text.workspace = true
|
||||
ide-vfs.workspace = true
|
||||
ide-workspace.workspace = true
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
//! Font families installed on this machine, for the font pickers in Settings.
|
||||
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_fonts::FontFamily;
|
||||
|
||||
/// Every installed family, sorted, each flagged monospaced or not. Read once
|
||||
/// per run (off the command threads) and cached.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn system_font_families() -> IdeResult<Vec<FontFamily>> {
|
||||
tauri::async_runtime::spawn_blocking(|| ide_fonts::families().to_vec())
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))
|
||||
}
|
||||
@@ -20,6 +20,7 @@ pub mod deploy;
|
||||
pub mod doc;
|
||||
pub mod docker;
|
||||
pub mod env;
|
||||
pub mod fonts;
|
||||
pub mod fs;
|
||||
pub mod github;
|
||||
pub mod history;
|
||||
@@ -109,6 +110,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
clipboard::clipboard_file_list,
|
||||
clipboard::clipboard_has_files,
|
||||
clipboard::clipboard_set_file_list,
|
||||
fonts::system_font_families,
|
||||
doc::doc_open,
|
||||
doc::doc_open_virtual,
|
||||
doc::doc_close,
|
||||
@@ -266,6 +268,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
run::run_list,
|
||||
run::run_close_stdin,
|
||||
run::run_resize,
|
||||
run::run_gradle_jvm_args_script,
|
||||
run::run_test_reports,
|
||||
build::build_model,
|
||||
build::build_sync,
|
||||
|
||||
@@ -89,6 +89,17 @@ pub fn run_system_env(state: State<'_, AppState>) -> std::collections::BTreeMap<
|
||||
ide_host::ops::run::run_system_env(&state.host, "")
|
||||
}
|
||||
|
||||
/// Writes the Gradle init script adding `jvm_args` to the JVMs the build forks; returns its path.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn run_gradle_jvm_args_script(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
jvm_args: Vec<String>,
|
||||
) -> IdeResult<String> {
|
||||
ide_host::ops::run::run_gradle_jvm_args_script(&state.host, window.label(), jvm_args).await
|
||||
}
|
||||
|
||||
/// Results from the JUnit XML reports (Surefire, Failsafe, Gradle) of the module at
|
||||
/// `module` (relative to the project root) written since `since_ms` (Unix epoch, ms).
|
||||
#[tauri::command]
|
||||
|
||||
@@ -520,20 +520,35 @@ pub async fn vcs_diff_revisions(
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn vcs_create_patch(window: Window, state: State<'_, AppState>, source: PatchSource) -> IdeResult<String> {
|
||||
ide_host::ops::vcs::vcs_create_patch(&state.host, window.label(), source).await
|
||||
pub async fn vcs_create_patch(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
repo: Option<PathBuf>,
|
||||
source: PatchSource,
|
||||
) -> IdeResult<String> {
|
||||
ide_host::ops::vcs::vcs_create_patch(&state.host, window.label(), repo, source).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn vcs_patch_preview(window: Window, state: State<'_, AppState>, patch: String) -> IdeResult<Vec<PatchFile>> {
|
||||
ide_host::ops::vcs::vcs_patch_preview(&state.host, window.label(), patch).await
|
||||
pub async fn vcs_patch_preview(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
repo: Option<PathBuf>,
|
||||
patch: String,
|
||||
) -> IdeResult<Vec<PatchFile>> {
|
||||
ide_host::ops::vcs::vcs_patch_preview(&state.host, window.label(), repo, patch).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn vcs_apply_patch(window: Window, state: State<'_, AppState>, patch: String) -> IdeResult<ApplyOutcome> {
|
||||
ide_host::ops::vcs::vcs_apply_patch(&state.host, window.label(), patch).await
|
||||
pub async fn vcs_apply_patch(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
repo: Option<PathBuf>,
|
||||
patch: String,
|
||||
) -> IdeResult<ApplyOutcome> {
|
||||
ide_host::ops::vcs::vcs_apply_patch(&state.host, window.label(), repo, patch).await
|
||||
}
|
||||
|
||||
/// Shelve Changes: saves the changes of `paths` as a patch on the shelf and reverts them.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "OpenIDEA",
|
||||
"version": "0.1.23",
|
||||
"version": "0.1.24",
|
||||
"identifier": "ai.l0ng.openidea",
|
||||
"build": {
|
||||
"beforeDevCommand": "pnpm dev",
|
||||
|
||||
+19
-3
@@ -152,6 +152,11 @@ export const commands = {
|
||||
* false when the clipboard stayed busy; the caller keeps working either way.
|
||||
*/
|
||||
clipboardSetFileList: (paths: string[]) => typedError<boolean, IdeError>(__TAURI_INVOKE("clipboard_set_file_list", { paths })),
|
||||
/**
|
||||
* Every installed family, sorted, each flagged monospaced or not. Read once
|
||||
* per run (off the command threads) and cached.
|
||||
*/
|
||||
systemFontFamilies: () => typedError<FontFamily[], IdeError>(__TAURI_INVOKE("system_font_families")),
|
||||
/**
|
||||
* Opens a document. Async: reading and decoding a large file must not block
|
||||
* the main thread (synchronous commands run on it).
|
||||
@@ -469,9 +474,9 @@ export const commands = {
|
||||
vcsDiffWithWorktree: (repo: string | null, rev: string) => typedError<ChangedFile[], IdeError>(__TAURI_INVOKE("vcs_diff_with_worktree", { repo, rev })),
|
||||
/** Files that differ between two revisions (the "N files updated" of Update Project). */
|
||||
vcsDiffRevisions: (repo: string | null, from: string, to: string) => typedError<ChangedFile[], IdeError>(__TAURI_INVOKE("vcs_diff_revisions", { repo, from, to })),
|
||||
vcsCreatePatch: (source: PatchSource) => typedError<string, IdeError>(__TAURI_INVOKE("vcs_create_patch", { source })),
|
||||
vcsPatchPreview: (patch: string) => typedError<PatchFile[], IdeError>(__TAURI_INVOKE("vcs_patch_preview", { patch })),
|
||||
vcsApplyPatch: (patch: string) => typedError<ApplyOutcome, IdeError>(__TAURI_INVOKE("vcs_apply_patch", { patch })),
|
||||
vcsCreatePatch: (repo: string | null, source: PatchSource) => typedError<string, IdeError>(__TAURI_INVOKE("vcs_create_patch", { repo, source })),
|
||||
vcsPatchPreview: (repo: string | null, patch: string) => typedError<PatchFile[], IdeError>(__TAURI_INVOKE("vcs_patch_preview", { repo, patch })),
|
||||
vcsApplyPatch: (repo: string | null, patch: string) => typedError<ApplyOutcome, IdeError>(__TAURI_INVOKE("vcs_apply_patch", { repo, patch })),
|
||||
/** Shelve Changes: saves the changes of `paths` as a patch on the shelf and reverts them. */
|
||||
vcsShelve: (name: string, paths: string[]) => typedError<ShelvedChangeList, IdeError>(__TAURI_INVOKE("vcs_shelve", { name, paths })),
|
||||
vcsShelves: () => typedError<ShelvedChangeList[], IdeError>(__TAURI_INVOKE("vcs_shelves")),
|
||||
@@ -515,6 +520,8 @@ export const commands = {
|
||||
runCloseStdin: (id: RunId) => typedError<null, IdeError>(__TAURI_INVOKE("run_close_stdin", { id })),
|
||||
/** Terminal size of a run started with "Emulate terminal in output console". */
|
||||
runResize: (id: RunId, cols: number, rows: number) => typedError<null, IdeError>(__TAURI_INVOKE("run_resize", { id, cols, rows })),
|
||||
/** Writes the Gradle init script adding `jvm_args` to the JVMs the build forks; returns its path. */
|
||||
runGradleJvmArgsScript: (jvmArgs: string[]) => typedError<string, IdeError>(__TAURI_INVOKE("run_gradle_jvm_args_script", { jvmArgs })),
|
||||
/**
|
||||
* Results from the JUnit XML reports (Surefire, Failsafe, Gradle) of the module at
|
||||
* `module` (relative to the project root) written since `since_ms` (Unix epoch, ms).
|
||||
@@ -2977,6 +2984,15 @@ export type FoldingSettings = {
|
||||
docComments?: boolean,
|
||||
};
|
||||
|
||||
/**
|
||||
* One installed family. `monospaced` is the font system's own flag (fixed
|
||||
* pitch; on Linux also fontconfig's dual-width CJK monospace).
|
||||
*/
|
||||
export type FontFamily = {
|
||||
name: string,
|
||||
monospaced: boolean,
|
||||
};
|
||||
|
||||
export type FormatOptions = {
|
||||
tabSize: number,
|
||||
insertSpaces: boolean,
|
||||
|
||||
@@ -102,6 +102,7 @@ const EXT_LANG: Record<string, string> = {
|
||||
kts: "kotlin",
|
||||
java: "java",
|
||||
py: "python",
|
||||
gd: "gdscript",
|
||||
go: "go",
|
||||
json: "json",
|
||||
md: "markdown",
|
||||
@@ -182,6 +183,15 @@ const MEM_LANGUAGES: LanguageInfo[] = [
|
||||
blockComment: null,
|
||||
indent: null,
|
||||
},
|
||||
{
|
||||
id: "gdscript",
|
||||
name: "GDScript",
|
||||
extensions: ["gd"],
|
||||
uiMode: null,
|
||||
lineComment: "#",
|
||||
blockComment: null,
|
||||
indent: { tabSize: 4, insertSpaces: false },
|
||||
},
|
||||
{
|
||||
id: "json",
|
||||
name: "JSON",
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { EditorSelection, EditorState, type Extension } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { insertNewlineAndIndent } from "@codemirror/commands";
|
||||
import { indentService, indentUnit } from "@codemirror/language";
|
||||
import {
|
||||
addCaretsToLineEnds,
|
||||
commentLine,
|
||||
completeStatement,
|
||||
joinLines,
|
||||
startNewLine,
|
||||
startNewLineBefore,
|
||||
toggleCase,
|
||||
unselectOccurrence,
|
||||
} from "./editing";
|
||||
import { commentTokens } from "./languages";
|
||||
import { toggleCaret } from "./multiCaret";
|
||||
import { enterInLineComment, lineCommentStyle } from "./comments";
|
||||
import { languages } from "@codemirror/language-data";
|
||||
@@ -42,7 +45,7 @@ function make(text: string, extensions: Extension = []) {
|
||||
state: EditorState.create({
|
||||
doc,
|
||||
selection: EditorSelection.create(ranges.length ? ranges : [EditorSelection.cursor(0)]),
|
||||
extensions: [EditorState.allowMultipleSelections.of(true), indentUnit.of(" "), extensions],
|
||||
extensions: [EditorState.allowMultipleSelections.of(true), extensions, indentUnit.of(" ")],
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
@@ -259,3 +262,79 @@ describe("enter in a line comment", async () => {
|
||||
expect(enterInLineComment(make("f(|x)", ext))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("fallback indentation for GDScript", () => {
|
||||
const gd = [
|
||||
EditorState.tabSize.of(4),
|
||||
indentUnit.of("\t"),
|
||||
commentTokens({
|
||||
id: "gdscript",
|
||||
name: "GDScript",
|
||||
extensions: ["gd"],
|
||||
uiMode: null,
|
||||
lineComment: "#",
|
||||
blockComment: null,
|
||||
indent: { tabSize: 4, insertSpaces: false },
|
||||
}),
|
||||
];
|
||||
|
||||
it("indents with a tab after a function header ending in a colon", () => {
|
||||
const v = make("func test() -> void:|", gd);
|
||||
insertNewlineAndIndent(v);
|
||||
expect(show(v)).toBe("func test() -> void:\n\t|");
|
||||
});
|
||||
|
||||
it("indents nested blocks and ignores trailing comments", () => {
|
||||
const v = make("func test() -> void:\n\tif x > 0: # check|", gd);
|
||||
insertNewlineAndIndent(v);
|
||||
expect(show(v)).toBe("func test() -> void:\n\tif x > 0: # check\n\t\t|");
|
||||
});
|
||||
|
||||
it("does not indent after a comment ending in a colon", () => {
|
||||
const v = make("\t# note:|", gd);
|
||||
insertNewlineAndIndent(v);
|
||||
expect(show(v)).toBe("\t# note:\n\t|");
|
||||
});
|
||||
|
||||
it("dedents after pass, return, break, and continue", () => {
|
||||
const v = make("func test() -> void:\n\tpass|", gd);
|
||||
insertNewlineAndIndent(v);
|
||||
expect(show(v)).toBe("func test() -> void:\n\tpass\n|");
|
||||
|
||||
const w = make("func test() -> int:\n\tif ready:\n\t\treturn 1|", gd);
|
||||
insertNewlineAndIndent(w);
|
||||
expect(show(w)).toBe("func test() -> int:\n\tif ready:\n\t\treturn 1\n\t|");
|
||||
});
|
||||
|
||||
it("completes a GDScript function header with a colon and indents the next line", () => {
|
||||
const v = make("func test() -> void|", gd);
|
||||
completeStatement("gdscript")(v);
|
||||
expect(show(v)).toBe("func test() -> void:\n\t|");
|
||||
});
|
||||
});
|
||||
|
||||
describe("fallback indentation boundaries", () => {
|
||||
const fallback = (id: string, lineComment = "#") =>
|
||||
commentTokens({
|
||||
id,
|
||||
name: id,
|
||||
extensions: [],
|
||||
uiMode: null,
|
||||
lineComment,
|
||||
blockComment: null,
|
||||
indent: null,
|
||||
});
|
||||
it.each([
|
||||
["gdscript", "var items = {|}", "var items = {\n |\n}"],
|
||||
["gdscript", 'var text = "unfinished:|', 'var text = "unfinished:\n|'],
|
||||
["gdscript", 'var text = "unfinished {|', 'var text = "unfinished {\n|'],
|
||||
["gdscript", 'var text = "#" # comment:|', 'var text = "#" # comment:\n|'],
|
||||
["gdscript", "if ready: # note|", "if ready: # note\n |"],
|
||||
["elixir", "if ready, do: value|", "if ready, do: value\n|"],
|
||||
["lua", "if ready then work() end|", "if ready then work() end\n|"],
|
||||
])("handles %s: %s", (id, input, expected) => {
|
||||
const v = make(input, fallback(id));
|
||||
insertNewlineAndIndent(v);
|
||||
expect(show(v)).toBe(expected);
|
||||
});
|
||||
});
|
||||
@@ -539,6 +539,7 @@ export const SEMICOLON_LANGS = new Set([
|
||||
/** Blocks close with a keyword (`end`) or by indentation: never complete them with braces. */
|
||||
export const KEYWORD_BLOCK_LANGS = new Set([
|
||||
"python",
|
||||
"gdscript",
|
||||
"ruby",
|
||||
"lua",
|
||||
"elixir",
|
||||
@@ -621,7 +622,11 @@ export function completeStatementSpec(state: EditorState, language: string): Tra
|
||||
}
|
||||
let insert = "";
|
||||
if (SEMICOLON_LANGS.has(language) && !comment && text.trim() && !/[;{},:]$/.test(text)) insert = ";";
|
||||
if (language === "python" && BLOCK_HEAD.test(text.replace(/^\s*(def|elif)\b/, "if")) && !text.endsWith(":"))
|
||||
if (
|
||||
(language === "python" || language === "gdscript") &&
|
||||
BLOCK_HEAD.test(text.replace(/^\s*(def|elif|static\s+func)\b/, "if")) &&
|
||||
!text.endsWith(":")
|
||||
)
|
||||
insert = ":";
|
||||
const opensBlock =
|
||||
text.endsWith("{") ||
|
||||
|
||||
@@ -5,7 +5,13 @@
|
||||
* and indentation fall back to the backend definition when the mode lacks them.
|
||||
*/
|
||||
import { EditorState, Prec, type Extension } from "@codemirror/state";
|
||||
import { LRLanguage, LanguageDescription, LanguageSupport } from "@codemirror/language";
|
||||
import {
|
||||
LRLanguage,
|
||||
LanguageDescription,
|
||||
LanguageSupport,
|
||||
indentService,
|
||||
language as languageFacet,
|
||||
} from "@codemirror/language";
|
||||
import { styleTags, tags as t } from "@lezer/highlight";
|
||||
import { languages as languageData } from "@codemirror/language-data";
|
||||
import type { DocBackend, LanguageInfo } from "../backend";
|
||||
@@ -118,11 +124,103 @@ export function loadedSupport(desc: LanguageDescription | null): LanguageSupport
|
||||
return desc?.support ?? null;
|
||||
}
|
||||
|
||||
/** Comment tokens from the backend definition, below the mode's own data. */
|
||||
export function commentTokens(info: LanguageInfo | undefined): Extension {
|
||||
if (!info || (!info.lineComment && !info.blockComment)) return [];
|
||||
const tokens: { line?: string; block?: { open: string; close: string } } = {};
|
||||
if (info.lineComment) tokens.line = info.lineComment;
|
||||
if (info.blockComment) tokens.block = { open: info.blockComment[0], close: info.blockComment[1] };
|
||||
return Prec.lowest(EditorState.languageData.of(() => [{ commentTokens: tokens }]));
|
||||
const COLON_INDENT_LANGS = new Set(["gdscript", "python"]);
|
||||
const DEDENT_STATEMENT = /^\s*(?:pass|break|continue|return)\b/;
|
||||
const KEYWORD_OPEN_LANGS = new Set(["elixir", "ruby", "lua"]);
|
||||
const KEYWORD_OPEN =
|
||||
/\b(?:do(?:\s*\|[^|]*\|)?|then|->)$|^\s*(?:def|defp|defmodule|class|module|function|local\s+function|if|unless|elsif|elseif|else|while|until|for|case|begin|cond|with|receive|try)\b/;
|
||||
const NO_INDENT_LANGS = new Set(["plaintext", "markdown", "log", "diff", "ignore", "gitattributes"]);
|
||||
|
||||
function opensBlock(code: string, language: string | undefined): boolean {
|
||||
if (!code) return false;
|
||||
if (/[{([]$/.test(code)) return true;
|
||||
if (COLON_INDENT_LANGS.has(language ?? "") && code.endsWith(":")) return true;
|
||||
if (language === "elixir") return /\bdo$|->$/.test(code);
|
||||
if (KEYWORD_OPEN_LANGS.has(language ?? "") && !/\bend$/.test(code) && KEYWORD_OPEN.test(code)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
function dedentsAfter(code: string, language: string | undefined): boolean {
|
||||
if (!COLON_INDENT_LANGS.has(language ?? "")) return false;
|
||||
return DEDENT_STATEMENT.test(code) && !/[,\\]$/.test(code);
|
||||
}
|
||||
|
||||
/** Hide literal contents before interpreting punctuation as block syntax. */
|
||||
function indentationCode(text: string, lineComment: string | undefined): string {
|
||||
let code = "";
|
||||
let quote: string | null = null;
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const ch = text[i]!;
|
||||
if (quote) {
|
||||
if (ch === "\\") i++;
|
||||
else if (ch === quote) quote = null;
|
||||
} else if (ch === '"' || ch === "'" || ch === "`") {
|
||||
quote = ch;
|
||||
code += "x";
|
||||
} else if (lineComment && text.startsWith(lineComment, i)) break;
|
||||
else code += ch;
|
||||
}
|
||||
return code.trimEnd();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fallback indentation for languages without a CodeMirror mode (GDScript, Zig,
|
||||
* Elixir, HCL, Terraform…): preserves the previous line's indentation and
|
||||
* indents one unit deeper after a block opener (`:`, `{`, `(`, `[` or keyword).
|
||||
*/
|
||||
export function fallbackIndent(language?: string): Extension {
|
||||
return indentService.of((cx, pos) => {
|
||||
if (cx.state.facet(languageFacet)) return undefined;
|
||||
const lineComment = cx.state.languageDataAt<{ line?: string }>("commentTokens", pos)[0]?.line;
|
||||
const stripComment = (text: string) => indentationCode(text, lineComment);
|
||||
|
||||
const after = cx.textAfterPos(pos);
|
||||
const closingBracket = /^\s*[}\])]/.test(after);
|
||||
|
||||
if (cx.simulatedBreak != null) {
|
||||
const line = cx.state.doc.lineAt(pos);
|
||||
const before = line.text.slice(0, pos - line.from);
|
||||
const base = cx.countColumn(before, before.search(/\S|$/));
|
||||
if (/\S/.test(before)) {
|
||||
const code = stripComment(before);
|
||||
if (closingBracket) return /[{([]$/.test(code) ? base : Math.max(0, base - cx.unit);
|
||||
if (opensBlock(code, language)) return base + cx.unit;
|
||||
if (dedentsAfter(code, language)) return Math.max(0, base - cx.unit);
|
||||
return base;
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
const curLine = cx.state.doc.lineAt(pos);
|
||||
for (let n = curLine.number - 1; n >= 1; n--) {
|
||||
const prev = cx.state.doc.line(n);
|
||||
if (!/\S/.test(prev.text)) continue;
|
||||
const base = cx.countColumn(prev.text, prev.text.search(/\S|$/));
|
||||
const code = stripComment(prev.text);
|
||||
if (closingBracket) return /[{([]$/.test(code) ? base : Math.max(0, base - cx.unit);
|
||||
if (opensBlock(code, language)) return base + cx.unit;
|
||||
if (dedentsAfter(code, language)) return Math.max(0, base - cx.unit);
|
||||
return base;
|
||||
}
|
||||
return 0;
|
||||
});
|
||||
}
|
||||
|
||||
/** Comment tokens and fallback indentation from the backend definition, below the mode's own data. */
|
||||
export function commentTokens(info: LanguageInfo | undefined, language = info?.id): Extension {
|
||||
const lang = language ?? info?.id;
|
||||
const hasComments = !!info && !!(info.lineComment || info.blockComment);
|
||||
const needsIndent = !!lang && !NO_INDENT_LANGS.has(lang);
|
||||
if (!hasComments && !needsIndent) return [];
|
||||
const data: Record<string, unknown> = {};
|
||||
if (hasComments) {
|
||||
const tokens: { line?: string; block?: { open: string; close: string } } = {};
|
||||
if (info!.lineComment) tokens.line = info!.lineComment;
|
||||
if (info!.blockComment) tokens.block = { open: info!.blockComment[0], close: info!.blockComment[1] };
|
||||
data.commentTokens = tokens;
|
||||
}
|
||||
if (needsIndent) data.indentOnInput = /^\s*[}\])]$/;
|
||||
const out: Extension[] = [Prec.lowest(EditorState.languageData.of(() => [data]))];
|
||||
if (needsIndent) out.push(Prec.lowest(fallbackIndent(lang)));
|
||||
return out;
|
||||
}
|
||||
@@ -355,7 +355,7 @@ export function baseExtensions(o: SetupOptions): Extension {
|
||||
tabKeymap,
|
||||
keymap.of([...closeBracketsKeymap, ...editorBaseKeymap, indentWithTab]),
|
||||
compartments.language.of(o.language ?? []),
|
||||
compartments.comments.of(commentTokens(o.info)),
|
||||
compartments.comments.of(commentTokens(o.info, o.ctx.language)),
|
||||
compartments.indent.of(indentExtension(o.indent ?? effectiveIndent(o.settings, o.info))),
|
||||
compartments.readOnly.of(readOnlyExtension(o.ctx.readOnly)),
|
||||
compartments.wrap.of(wrapExtension(o.settings, o.ctx.path, o.wrapOverride)),
|
||||
|
||||
@@ -101,6 +101,7 @@ describe("smart backspace", () => {
|
||||
it("applies in 'proper indent' mode except in indentation-based languages", () => {
|
||||
expect(smartBackspaceApplies("autoindent", "java")).toBe(true);
|
||||
expect(smartBackspaceApplies("autoindent", "python")).toBe(false);
|
||||
expect(smartBackspaceApplies("autoindent", "gdscript")).toBe(false);
|
||||
expect(smartBackspaceApplies("nearest", "java")).toBe(false);
|
||||
});
|
||||
|
||||
|
||||
@@ -47,7 +47,7 @@ export const tabKeymap: Extension = keymap.of([{ key: "Tab", run: insertTab }]);
|
||||
// --- Backspace -------------------------------------------------------------------------------
|
||||
|
||||
/** Languages whose layout is indentation: IDEA keeps "to nearest indent position" there. */
|
||||
const NEAREST_INDENT_LANGS = new Set(["python", "yaml", "shellscript"]);
|
||||
const NEAREST_INDENT_LANGS = new Set(["python", "gdscript", "yaml", "shellscript"]);
|
||||
|
||||
export function smartBackspaceApplies(mode: string, language: string | undefined): boolean {
|
||||
return mode === "autoindent" && !NEAREST_INDENT_LANGS.has(language ?? "");
|
||||
|
||||
@@ -422,7 +422,7 @@ export class DocModel {
|
||||
compartments.wrap.reconfigure(wrapExtension(editor, this.path, this.softWrapOverride)),
|
||||
compartments.sticky.reconfigure(stickyExtension(editor)),
|
||||
compartments.font.reconfigure(fontExtension(editor)),
|
||||
compartments.comments.reconfigure(commentTokens(this.info)),
|
||||
compartments.comments.reconfigure(commentTokens(this.info, this.meta.language)),
|
||||
compartments.lineNumbers.reconfigure(lineNumbersExtension(editor)),
|
||||
compartments.folding.reconfigure(foldingFor(editor)),
|
||||
compartments.caret.reconfigure(caretFor(editor)),
|
||||
|
||||
@@ -9,14 +9,15 @@
|
||||
import { ViewPlugin, type EditorView, type ViewUpdate } from "@codemirror/view";
|
||||
import { commands, type CodeAction, type Diagnostic } from "@/platform/ipc";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { docOf, lspRequest } from "./lsp";
|
||||
import { docOf, isUnavailable, lspRequest } from "./lsp";
|
||||
import { diagnosticsFor, subscribeDiagnostics } from "./diagnostics";
|
||||
import { applyCodeAction } from "./intentions";
|
||||
import { offsetsToRange, rangeToOffsets } from "./positions";
|
||||
import { serverBackoff } from "./availability";
|
||||
import { featureBackoff } from "./availability";
|
||||
|
||||
const IDLE_MS = 1500;
|
||||
const IMPORT_TITLE = /\bimport\b/i;
|
||||
const importBackoff = featureBackoff();
|
||||
|
||||
/** The single import fix among `actions`, if exactly one exists. */
|
||||
export function unambiguousImport(actions: readonly CodeAction[]): CodeAction | null {
|
||||
@@ -65,7 +66,7 @@ const autoImportPlugin = ViewPlugin.fromClass(
|
||||
const view = this.view;
|
||||
const doc = docOf(view);
|
||||
if ((!prefs.addUnambiguous && !prefs.optimizeOnTheFly) || this.running || !doc || doc.readOnly) return;
|
||||
if (!view.dom.isConnected || !view.hasFocus || serverBackoff.active(doc.doc)) return;
|
||||
if (!view.dom.isConnected || !view.hasFocus || importBackoff.active(doc.doc)) return;
|
||||
this.running = true;
|
||||
try {
|
||||
const caretLine = view.state.doc.lineAt(view.state.selection.main.head).number - 1;
|
||||
@@ -75,8 +76,9 @@ const autoImportPlugin = ViewPlugin.fromClass(
|
||||
this.dirty = false;
|
||||
await this.optimize(caretLine);
|
||||
}
|
||||
} catch {
|
||||
} catch (e) {
|
||||
// Servers without these code actions: nothing to do.
|
||||
if (isUnavailable(e)) importBackoff.mark(doc.doc);
|
||||
} finally {
|
||||
this.running = false;
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ vi.mock("@/platform/ipc", async (orig) => {
|
||||
};
|
||||
});
|
||||
|
||||
const { onServerSettled } = await import("./availability");
|
||||
const { onServerSettled, featureBackoff, installAvailabilityEvents } = await import("./availability");
|
||||
|
||||
const status = (s: string) => {
|
||||
for (const fn of listeners) fn({ type: "languageServer", server: 1, status: s } as unknown as IdeEvent);
|
||||
@@ -57,3 +57,43 @@ describe("onServerSettled", () => {
|
||||
expect(fn).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("featureBackoff", () => {
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
listeners.clear();
|
||||
});
|
||||
|
||||
it("leaves a document alone until the back-off expires", () => {
|
||||
vi.useFakeTimers();
|
||||
const backoff = featureBackoff(1000);
|
||||
expect(backoff.active(1)).toBe(false);
|
||||
backoff.mark(1);
|
||||
expect(backoff.active(1)).toBe(true);
|
||||
expect(backoff.active(2)).toBe(false);
|
||||
vi.advanceTimersByTime(1001);
|
||||
expect(backoff.active(1)).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps features independent: one feature backing off does not stop another", () => {
|
||||
const inlay = featureBackoff();
|
||||
const completion = featureBackoff();
|
||||
inlay.mark(1);
|
||||
expect(inlay.active(1)).toBe(true);
|
||||
expect(completion.active(1)).toBe(false);
|
||||
});
|
||||
|
||||
it("is cleared for every feature when a server becomes ready", () => {
|
||||
const a = featureBackoff();
|
||||
const b = featureBackoff();
|
||||
const off = installAvailabilityEvents();
|
||||
a.mark(1);
|
||||
b.mark(2);
|
||||
status("starting");
|
||||
expect(a.active(1)).toBe(true);
|
||||
status("ready");
|
||||
expect(a.active(1)).toBe(false);
|
||||
expect(b.active(2)).toBe(false);
|
||||
off();
|
||||
});
|
||||
});
|
||||
@@ -1,29 +1,45 @@
|
||||
/**
|
||||
* Per-document back-off after `unavailable` errors, so background features
|
||||
* (completion while typing, lightbulb, inlay hints…) don't hammer the backend
|
||||
* for files without a language server. Cleared when any server becomes ready.
|
||||
* Per-document, per-feature back-off after `unavailable` errors, so background
|
||||
* features (completion while typing, lightbulb, inlay hints…) don't hammer the
|
||||
* backend for files without a language server, or for a feature the server
|
||||
* doesn't offer. Each feature owns its back-off: a server lacking one
|
||||
* capability (Godot has no inlay hints, say) must not switch off the others.
|
||||
* All of them are cleared when any server becomes ready.
|
||||
*/
|
||||
import { isTauri, onIdeEvent } from "@/platform/ipc";
|
||||
import type { LspRefreshKind } from "@/bindings";
|
||||
|
||||
const BACKOFF_MS = 15_000;
|
||||
const until = new Map<number, number>();
|
||||
const DEFAULT_BACKOFF_MS = 15_000;
|
||||
const all = new Set<Map<number, number>>();
|
||||
|
||||
export const serverBackoff = {
|
||||
mark(doc: number) {
|
||||
until.set(doc, Date.now() + BACKOFF_MS);
|
||||
},
|
||||
active(doc: number): boolean {
|
||||
const t = until.get(doc);
|
||||
if (t === undefined) return false;
|
||||
if (t > Date.now()) return true;
|
||||
until.delete(doc);
|
||||
return false;
|
||||
},
|
||||
clear() {
|
||||
until.clear();
|
||||
},
|
||||
};
|
||||
export interface FeatureBackoff {
|
||||
/** Stop asking about `doc` for a while. */
|
||||
mark(doc: number): void;
|
||||
/** Whether `doc` is still being left alone. */
|
||||
active(doc: number): boolean;
|
||||
}
|
||||
|
||||
/** A back-off for one feature; give each feature its own. */
|
||||
export function featureBackoff(ms = DEFAULT_BACKOFF_MS): FeatureBackoff {
|
||||
const until = new Map<number, number>();
|
||||
all.add(until);
|
||||
return {
|
||||
mark(doc) {
|
||||
until.set(doc, Date.now() + ms);
|
||||
},
|
||||
active(doc) {
|
||||
const t = until.get(doc);
|
||||
if (t === undefined) return false;
|
||||
if (t > Date.now()) return true;
|
||||
until.delete(doc);
|
||||
return false;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function clearBackoffs() {
|
||||
for (const until of all) until.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls `fn` when data of `kind` fetched earlier may be stale: the server asked
|
||||
@@ -85,6 +101,6 @@ export function onServerSettled(fn: () => void): () => void {
|
||||
|
||||
export function installAvailabilityEvents(): () => void {
|
||||
return onIdeEvent("languageServer", (e) => {
|
||||
if (e.status === "ready") serverBackoff.clear();
|
||||
if (e.status === "ready") clearBackoffs();
|
||||
});
|
||||
}
|
||||
@@ -13,7 +13,7 @@ import { commands, nextRequestId, type OutlineItem, type SymbolKind } from "@/pl
|
||||
import { useProject } from "@/platform/project";
|
||||
import { debounce, docOf, isUnavailable, lspRequest } from "./lsp";
|
||||
import { posToOffset } from "./positions";
|
||||
import { onLspRefresh, serverBackoff } from "./availability";
|
||||
import { featureBackoff, onLspRefresh } from "./availability";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { authorLabel, authorSummary, authorTooltip, blameFor, onBlameInvalidated } from "./authorLens";
|
||||
import { tx } from "@/platform/i18n";
|
||||
@@ -35,6 +35,7 @@ const MAX_PER_PASS = 40;
|
||||
const CONCURRENCY = 4;
|
||||
/** Lines above/below the viewport that are counted too, so scrolling feels instant. */
|
||||
const MARGIN_LINES = 60;
|
||||
const usagesBackoff = featureBackoff();
|
||||
|
||||
export interface LensTarget {
|
||||
name: string;
|
||||
@@ -138,7 +139,7 @@ class UsagesLensPlugin {
|
||||
const doc = docOf(view);
|
||||
if (!doc) return;
|
||||
const gen = ++this.generation;
|
||||
const usages = usagesEnabled() && !serverBackoff.active(doc.doc);
|
||||
const usages = usagesEnabled() && !usagesBackoff.active(doc.doc);
|
||||
const authors = authorEnabled() && !doc.virtual;
|
||||
if (!usages && !authors) {
|
||||
if (view.state.field(lensField).length) view.dispatch({ effects: setLenses.of([]) });
|
||||
@@ -181,7 +182,7 @@ class UsagesLensPlugin {
|
||||
);
|
||||
if (gen !== this.generation || view.state.doc !== text) return;
|
||||
}
|
||||
if (unavailable) serverBackoff.mark(doc.doc);
|
||||
if (unavailable) usagesBackoff.mark(doc.doc);
|
||||
const lines = await blame;
|
||||
if (gen !== this.generation || view.state.doc !== text) return;
|
||||
const lenses: CodeLens[] = [];
|
||||
@@ -202,7 +203,7 @@ class UsagesLensPlugin {
|
||||
}
|
||||
if (!sameLenses(view.state.field(lensField), lenses)) view.dispatch({ effects: setLenses.of(lenses) });
|
||||
} catch (e) {
|
||||
if (isUnavailable(e)) serverBackoff.mark(doc.doc);
|
||||
if (isUnavailable(e)) usagesBackoff.mark(doc.doc);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@ import { isEmptyMarkup, renderCode, renderMarkup } from "./markdown";
|
||||
import { selectableText } from "@/ui/selectableText";
|
||||
import { iconNode } from "./iconMarkup";
|
||||
import { parameterInfoOrLeave, triggerSignatureHelp } from "./signature";
|
||||
import { serverBackoff } from "./availability";
|
||||
import { featureBackoff } from "./availability";
|
||||
import { pathCompletionSource } from "./fileReferences";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { tx } from "@/platform/i18n";
|
||||
@@ -410,6 +410,9 @@ interface RichCompletion extends Completion {
|
||||
typeText?: string;
|
||||
}
|
||||
|
||||
/** Documents the server could not complete in, so typing doesn't ask again until a server is ready. */
|
||||
const completionBackoff = featureBackoff();
|
||||
|
||||
async function lspCompletionSource(ctx: CompletionContext): Promise<CompletionResult | null> {
|
||||
const doc = ctx.state.facet(lspDoc);
|
||||
if (!doc || doc.readOnly) return null;
|
||||
@@ -417,8 +420,7 @@ async function lspCompletionSource(ctx: CompletionContext): Promise<CompletionRe
|
||||
const trigger = triggerCharacter(ctx.state.sliceDoc(Math.max(0, ctx.pos - 2), ctx.pos));
|
||||
if (!ctx.explicit && !word && !trigger) return null;
|
||||
if (!ctx.explicit && word && !trigger && /^\d/.test(word.text)) return null;
|
||||
if (serverBackoff.active(doc.doc)) return fallback(ctx);
|
||||
|
||||
if (completionBackoff.active(doc.doc)) return fallback(ctx);
|
||||
cancelInflight();
|
||||
const id = nextRequestId();
|
||||
inflight = id;
|
||||
@@ -433,7 +435,7 @@ async function lspCompletionSource(ctx: CompletionContext): Promise<CompletionRe
|
||||
);
|
||||
} catch (e) {
|
||||
if (isUnavailable(e)) {
|
||||
serverBackoff.mark(doc.doc);
|
||||
completionBackoff.mark(doc.doc);
|
||||
return fallback(ctx);
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -15,7 +15,7 @@ import { useProject } from "@/platform/project";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { debounce, docOf, isUnavailable, lspRequest } from "./lsp";
|
||||
import { offsetsToRange, posToOffset } from "./positions";
|
||||
import { onLspRefresh, serverBackoff } from "./availability";
|
||||
import { featureBackoff, onLspRefresh } from "./availability";
|
||||
import { gotoTargets } from "./navigation";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
@@ -30,6 +30,8 @@ async function setEditorSetting(key: string, value: unknown) {
|
||||
useProject.setState({ settings: await call(commands.settingsSet("global", `editor.${key}`, JSON.stringify(value))) });
|
||||
}
|
||||
|
||||
const inlayBackoff = featureBackoff();
|
||||
|
||||
/** A type hint after an identifier can resolve that identifier's inferred type. */
|
||||
function typeHintOffset(view: EditorView, at: number): number | null {
|
||||
if (at <= 0 || at > view.state.doc.length) return null;
|
||||
@@ -183,7 +185,7 @@ const inlayPlugin = ViewPlugin.fromClass(
|
||||
if (!view.dom.isConnected) return;
|
||||
const doc = docOf(view);
|
||||
if (!doc) return;
|
||||
if (!enabled(doc.language) || serverBackoff.active(doc.doc)) {
|
||||
if (!enabled(doc.language) || inlayBackoff.active(doc.doc)) {
|
||||
if (view.state.field(inlayField).size) view.dispatch({ effects: setInlays.of(Decoration.none) });
|
||||
return;
|
||||
}
|
||||
@@ -203,7 +205,7 @@ const inlayPlugin = ViewPlugin.fromClass(
|
||||
),
|
||||
});
|
||||
} catch (e) {
|
||||
if (isUnavailable(e)) serverBackoff.mark(doc.doc);
|
||||
if (isUnavailable(e)) inlayBackoff.mark(doc.doc);
|
||||
}
|
||||
}
|
||||
destroy() {
|
||||
|
||||
@@ -27,6 +27,7 @@ import { activeEditor } from "@/editor/api";
|
||||
import { docOf, isUnavailable, lspRequest } from "./lsp";
|
||||
import { offsetToPos, rangeToOffsets } from "./positions";
|
||||
import { showHint } from "./hint";
|
||||
import { featureBackoff } from "./availability";
|
||||
|
||||
/** A suggestion in document offsets: `text` replaces `[from, to)`. */
|
||||
export interface Suggestion {
|
||||
@@ -144,7 +145,7 @@ function enabledFor(language: string): boolean {
|
||||
return p.enabled && !p.disabledLanguages.includes(language);
|
||||
}
|
||||
|
||||
const backoff = new Map<number, number>();
|
||||
const backoff = featureBackoff(BACKOFF_MS);
|
||||
let focused: EditorView | null = null;
|
||||
let inflight: RequestId | null = null;
|
||||
|
||||
@@ -159,7 +160,7 @@ export async function requestInline(view: EditorView, automatic: boolean): Promi
|
||||
const state = view.state;
|
||||
const sel = state.selection;
|
||||
if (!doc || sel.ranges.length !== 1 || !sel.main.empty || view.state.readOnly) return false;
|
||||
if (automatic && (backoff.get(doc.doc) ?? 0) > Date.now()) return false;
|
||||
if (automatic && backoff.active(doc.doc)) return false;
|
||||
cancelInflight();
|
||||
const id = (inflight = nextRequestId());
|
||||
const caret = sel.main.head;
|
||||
@@ -173,7 +174,7 @@ export async function requestInline(view: EditorView, automatic: boolean): Promi
|
||||
view.dispatch({ effects: setGhost.of(suggestions.length ? { items: suggestions, index: 0, caret } : null) });
|
||||
return suggestions.length > 0;
|
||||
} catch (e) {
|
||||
if (isUnavailable(e)) backoff.set(doc.doc, Date.now() + BACKOFF_MS);
|
||||
if (isUnavailable(e)) backoff.mark(doc.doc);
|
||||
else if (!isCancelled(e)) console.debug("[lsp] inline completion", e);
|
||||
if (!automatic && !isCancelled(e)) throw e;
|
||||
return false;
|
||||
|
||||
@@ -18,7 +18,7 @@ import { formatLines } from "./format";
|
||||
import { pythonMemberIntentions } from "./pythonMembers";
|
||||
import { caretAnchor, openPopup, type ListPopupItem, type ListPreview } from "./popupStore";
|
||||
import { editPreviewLines } from "./workspaceEdit";
|
||||
import { serverBackoff } from "./availability";
|
||||
import { featureBackoff } from "./availability";
|
||||
import { iconNode } from "./iconMarkup";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { spellingIntentions } from "./spelling";
|
||||
@@ -27,6 +27,8 @@ import { SPELLING_INSPECTION } from "@/platform/inspections";
|
||||
import { editInspectionSettings, intentionControls } from "@/platform/inspectionControls";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
const codeActionBackoff = featureBackoff();
|
||||
|
||||
const isQuickFix = (a: CodeAction) => !!a.kind && (a.kind === "quickfix" || a.kind.startsWith("quickfix."));
|
||||
|
||||
/** IDEA ordering: quick fixes first, preferred before others, disabled last; stable otherwise. */
|
||||
@@ -512,14 +514,14 @@ const bulbPlugin = ViewPlugin.fromClass(
|
||||
const state = this.view.state;
|
||||
const typoFix = spellingIntentions(this.view).length > 0;
|
||||
const local = typoFix || contributedIntentions(this.view).length > 0;
|
||||
const backoff = serverBackoff.active(doc.doc);
|
||||
const backoff = codeActionBackoff.active(doc.doc);
|
||||
if (backoff && !local) return;
|
||||
let actions: CodeAction[] = [];
|
||||
if (!backoff) {
|
||||
try {
|
||||
actions = await fetchIntentions(this.view);
|
||||
} catch (e) {
|
||||
if (isUnavailable(e)) serverBackoff.mark(doc.doc);
|
||||
if (isUnavailable(e)) codeActionBackoff.mark(doc.doc);
|
||||
if (!local) return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ import { showHint } from "./hint";
|
||||
import { caretAnchor, openPopup, type ListPopupItem } from "./popupStore";
|
||||
import { identifierAt, readManyFileLines } from "./files";
|
||||
import { documentLinks, followReference, knownLinks, linkReference, referenceAt, textReference } from "./links";
|
||||
import { serverBackoff } from "./availability";
|
||||
import { featureBackoff } from "./availability";
|
||||
import { requestHover } from "./hover";
|
||||
import { declarationSummary, renderCode } from "./markdown";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
@@ -60,6 +60,8 @@ import { isNavigationGesture, onNavigationModifier } from "@/platform/navigation
|
||||
import { create } from "zustand";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
const highlightsBackoff = featureBackoff();
|
||||
|
||||
export async function navigateTo(loc: Location) {
|
||||
await editorService().openFile(loc.path, {
|
||||
selection: { line: loc.range.start.line, col: loc.range.start.col },
|
||||
@@ -573,7 +575,7 @@ async function fetchHighlights(view: EditorView, sticky: boolean) {
|
||||
);
|
||||
};
|
||||
let lspError: unknown = null;
|
||||
if (!serverBackoff.active(doc.doc)) {
|
||||
if (!highlightsBackoff.active(doc.doc)) {
|
||||
try {
|
||||
const items = await lspRequest(() => commands.lspDocumentHighlights(doc.doc, offsetToPos(state.doc, head)));
|
||||
if (stale()) return;
|
||||
@@ -582,7 +584,7 @@ async function fetchHighlights(view: EditorView, sticky: boolean) {
|
||||
return;
|
||||
} catch (e) {
|
||||
if (isCancelled(e)) return;
|
||||
if (isUnavailable(e)) serverBackoff.mark(doc.doc);
|
||||
if (isUnavailable(e)) highlightsBackoff.mark(doc.doc);
|
||||
lspError = e;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,9 @@ import { Decoration, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate
|
||||
import { commands, type SemanticTokens } from "@/platform/ipc";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { debounce, docOf, isUnavailable, lspRequest } from "./lsp";
|
||||
import { onLspRefresh, serverBackoff } from "./availability";
|
||||
import { featureBackoff, onLspRefresh } from "./availability";
|
||||
|
||||
const semanticBackoff = featureBackoff();
|
||||
|
||||
const TYPE_CLASS: Record<string, string> = {
|
||||
type: "type",
|
||||
@@ -180,14 +182,14 @@ const semanticPlugin = ViewPlugin.fromClass(
|
||||
async run() {
|
||||
const view = this.view;
|
||||
const doc = docOf(view);
|
||||
if (!doc || serverBackoff.active(doc.doc) || !view.dom.isConnected) return;
|
||||
if (!doc || semanticBackoff.active(doc.doc) || !view.dom.isConnected) return;
|
||||
const state = view.state;
|
||||
try {
|
||||
const tokens = await lspRequest(() => commands.lspSemanticTokens(doc.doc));
|
||||
if (view.state.doc !== state.doc) return this.refresh();
|
||||
this.decorate(state.doc, tokens);
|
||||
} catch (e) {
|
||||
if (isUnavailable(e)) serverBackoff.mark(doc.doc);
|
||||
if (isUnavailable(e)) semanticBackoff.mark(doc.doc);
|
||||
}
|
||||
}
|
||||
destroy() {
|
||||
|
||||
@@ -14,7 +14,7 @@ import { RangeSet, StateEffect, StateField, type Extension, type Text } from "@c
|
||||
import { EditorView, GutterMarker, ViewPlugin, gutter, type ViewUpdate } from "@codemirror/view";
|
||||
import type { EditorDocContext } from "@/editor/api";
|
||||
import { docOf, debounce, isUnavailable, lspRequest } from "@/editor/lsp/lsp";
|
||||
import { onServerSettled, serverBackoff } from "@/editor/lsp/availability";
|
||||
import { featureBackoff, onServerSettled } from "@/editor/lsp/availability";
|
||||
import { readManyFileLines, withDocument } from "@/editor/lsp/files";
|
||||
import { locationItems, navigateTo, pinToFind } from "@/editor/lsp/navigation";
|
||||
import { openPopup } from "@/editor/lsp/popupStore";
|
||||
@@ -49,6 +49,7 @@ import styles from "./LineMarkers.module.css";
|
||||
const MARGIN_LINES = 60;
|
||||
const MAX_PER_PASS = 60;
|
||||
const DEBOUNCE_MS = 500;
|
||||
const gutterBackoff = featureBackoff();
|
||||
|
||||
/** Settings › Editor › General › Gutter Icons groups that are on. */
|
||||
export function enabledGroups(prefs: Pick<EditorExtras, "showGutterIcons" | "gutterIconsDisabled">): Set<MarkerGroup> {
|
||||
@@ -279,7 +280,7 @@ class MarkersPlugin {
|
||||
const gen = ++this.generation;
|
||||
this.cancelRequest();
|
||||
const groups = enabledGroups(editorPrefs());
|
||||
if (!groups.size || serverBackoff.active(ctx.doc)) {
|
||||
if (!groups.size || gutterBackoff.active(ctx.doc)) {
|
||||
if (!groups.size) this.show([]);
|
||||
return;
|
||||
}
|
||||
@@ -310,7 +311,7 @@ class MarkersPlugin {
|
||||
if (stale()) return;
|
||||
this.show(place(text, cachedMarkers(candidates, groups, this.cache)));
|
||||
} catch (e) {
|
||||
if (isUnavailable(e)) serverBackoff.mark(ctx.doc);
|
||||
if (isUnavailable(e)) gutterBackoff.mark(ctx.doc);
|
||||
else if (!isCancelled(e)) console.debug("[lineMarkers]", e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { findTextOccurrences } from "./occurrences";
|
||||
|
||||
describe("text occurrence boundaries", () => {
|
||||
it("preserves whole-word matching, whitespace normalization and adjacent matches", () => {
|
||||
const text = "ab + c $b+c b + cd b+c b + c";
|
||||
expect(findTextOccurrences(text, 0, text.length, "b + c")).toEqual([
|
||||
{ from: 19, to: 22 },
|
||||
{ from: 23, to: 28 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("finds valid occurrences overlapping a rejected suffix match", () => {
|
||||
const text = "ab + b + b";
|
||||
expect(findTextOccurrences(text, 0, text.length, "b + b")).toEqual([{ from: 5, to: 10 }]);
|
||||
});
|
||||
|
||||
it("advances through zero-length matches", () => {
|
||||
expect(findTextOccurrences("ab", 0, 2, "")).toEqual([
|
||||
{ from: 0, to: 0 },
|
||||
{ from: 1, to: 1 },
|
||||
{ from: 2, to: 2 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps punctuation-led expressions and scope-relative boundaries", () => {
|
||||
expect(findTextOccurrences("x(a) x(a)", 0, 9, "(a)")).toEqual([
|
||||
{ from: 1, to: 4 },
|
||||
{ from: 6, to: 9 },
|
||||
]);
|
||||
expect(findTextOccurrences("ab", 1, 2, "b")).toEqual([{ from: 1, to: 2 }]);
|
||||
});
|
||||
});
|
||||
@@ -69,9 +69,8 @@ export function expressionPattern(expr: string): string {
|
||||
if (k > 0 && t !== "\\s+" && tokens[k - 1] !== "\\s+") src += "\\s*";
|
||||
src += t;
|
||||
});
|
||||
const head = WORD.test(norm[0] ?? "") ? "(?<![\\w$])" : "";
|
||||
const tail = WORD.test(norm[norm.length - 1] ?? "") ? "(?![\\w$])" : "";
|
||||
return head + src + tail;
|
||||
return src + tail;
|
||||
}
|
||||
|
||||
/** Spans in `text[from, to)` matching `expr` (absolute offsets), at most `limit`. */
|
||||
@@ -86,7 +85,12 @@ export function findTextOccurrences(
|
||||
const scope = text.slice(from, to);
|
||||
const want = normalizeExpression(expr.trim());
|
||||
const out: { from: number; to: number }[] = [];
|
||||
for (const m of scope.matchAll(re)) {
|
||||
for (let m = re.exec(scope); m; m = re.exec(scope)) {
|
||||
if (!m[0].length) re.lastIndex = m.index + 1;
|
||||
if (WORD.test(want[0] ?? "") && m.index > 0 && WORD.test(scope[m.index - 1]!)) {
|
||||
re.lastIndex = m.index + 1;
|
||||
continue;
|
||||
}
|
||||
if (normalizeExpression(m[0]) !== want) continue;
|
||||
out.push({ from: from + m.index!, to: from + m.index! + m[0].length });
|
||||
if (out.length >= limit) break;
|
||||
|
||||
@@ -231,6 +231,12 @@ describe("localDeclaration", () => {
|
||||
});
|
||||
|
||||
describe("textOccurrences", () => {
|
||||
it("checks Unicode identifier boundaries without shifting UTF-16 offsets", () => {
|
||||
const text = "𐐀foo αfoo $foo _foo foo 𐐀 foo foo𐐀";
|
||||
const hits = textOccurrences(text, "foo", [], { from: -1, to: -1 });
|
||||
expect(hits).toEqual([21, 28].map((from) => ({ from, to: from + 3 })));
|
||||
});
|
||||
|
||||
it("finds whole-word mentions that are not identifier tokens, outside the declaration", () => {
|
||||
const text = 'foo(); // foo and food\nlet s = "foo";\nfn foo() {}';
|
||||
const ids = [0, text.lastIndexOf("foo")].map((from) => ({ from, to: from + 3 }));
|
||||
|
||||
@@ -360,11 +360,12 @@ export function textOccurrences(
|
||||
exclude: { from: number; to: number },
|
||||
): { from: number; to: number }[] {
|
||||
const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
const re = new RegExp(`(?<![\\p{L}\\p{N}_$])${escaped}(?![\\p{L}\\p{N}_$])`, "gu");
|
||||
const re = new RegExp(`${escaped}(?![\\p{L}\\p{N}_$])`, "gu");
|
||||
const ids = new Set(identifiers.map((o) => o.from));
|
||||
const out: { from: number; to: number }[] = [];
|
||||
for (let m = re.exec(text); m; m = re.exec(text)) {
|
||||
const from = m.index;
|
||||
if (/[\p{L}\p{N}_$]$/u.test(text.slice(Math.max(0, from - 2), from))) continue;
|
||||
if (ids.has(from) || (from >= exclude.from && from < exclude.to)) continue;
|
||||
out.push({ from, to: from + name.length });
|
||||
}
|
||||
|
||||
@@ -49,7 +49,7 @@ export function activate(): () => void {
|
||||
id: TOOL_WINDOW,
|
||||
title: "Agents",
|
||||
icon: "toolwindow-agents",
|
||||
anchor: "left",
|
||||
anchor: "right",
|
||||
order: 0.5,
|
||||
component: lazyComponent(() => import("./AgentsView").then((m) => m.AgentsView)),
|
||||
headerActions: lazyComponent(() => import("./AgentsView").then((m) => m.AgentsHeaderActions)),
|
||||
|
||||
@@ -1202,3 +1202,60 @@
|
||||
color: var(--fg-strong);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.sqlCompletion {
|
||||
width: 300px;
|
||||
max-height: 240px;
|
||||
padding: 4px;
|
||||
}
|
||||
.sqlCompletionOption {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
align-items: center;
|
||||
width: 100%;
|
||||
padding: 4px 8px;
|
||||
text-align: left;
|
||||
}
|
||||
.sqlCompletionOption[aria-selected="true"],
|
||||
.sqlCompletionOption:hover {
|
||||
background: var(--bg-toolbar-selected);
|
||||
}
|
||||
.sqlCompletionOption span {
|
||||
flex: 1;
|
||||
}
|
||||
.sqlCompletionOption small {
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
.sqlInputWrap {
|
||||
position: relative;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
.sqlInputWrap > input {
|
||||
width: 100%;
|
||||
position: relative;
|
||||
}
|
||||
.sqlInputText {
|
||||
color: transparent !important;
|
||||
caret-color: var(--fg-strong);
|
||||
}
|
||||
.sqlHighlight {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
overflow: hidden;
|
||||
white-space: pre;
|
||||
pointer-events: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-ui);
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
/* The input's scroll width includes room for the caret; match it so both stop at the same scrollLeft. */
|
||||
.sqlHighlight::after {
|
||||
content: "";
|
||||
flex: none;
|
||||
width: 2px;
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { Grid } from "./Grid";
|
||||
|
||||
vi.mock("@tanstack/react-virtual", () => ({
|
||||
useVirtualizer: ({ count }: { count: number }) => ({
|
||||
getTotalSize: () => count * 24,
|
||||
getVirtualItems: () => Array.from({ length: count }, (_, index) => ({ index, start: index * 24, key: index })),
|
||||
scrollToIndex: () => {},
|
||||
}),
|
||||
}));
|
||||
|
||||
describe("database grid", () => {
|
||||
it("drags a rectangle and copies it as TSV", () => {
|
||||
const writeText = vi.fn();
|
||||
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText } });
|
||||
render(
|
||||
<Grid
|
||||
columns={[
|
||||
{ name: "a", type: "text" },
|
||||
{ name: "b", type: "text" },
|
||||
]}
|
||||
rowCount={2}
|
||||
value={(r, c) =>
|
||||
[
|
||||
["one", "two"],
|
||||
["three", "four"],
|
||||
][r]![c]!
|
||||
}
|
||||
/>,
|
||||
);
|
||||
const cells = screen.getAllByRole("gridcell");
|
||||
fireEvent.mouseDown(cells[0]!, { button: 0 });
|
||||
fireEvent.mouseEnter(cells[3]!);
|
||||
fireEvent.mouseUp(window);
|
||||
fireEvent.keyDown(screen.getByRole("grid"), { key: "c", metaKey: true });
|
||||
expect(writeText).toHaveBeenCalledWith("one\ttwo\nthree\tfour");
|
||||
});
|
||||
it("pastes a rectangle as pending edits and skips deleted rows", () => {
|
||||
const onEdit = vi.fn();
|
||||
render(
|
||||
<Grid
|
||||
columns={[
|
||||
{ name: "a", type: "text" },
|
||||
{ name: "b", type: "text" },
|
||||
]}
|
||||
rowCount={2}
|
||||
value={() => "old"}
|
||||
editable
|
||||
onEdit={onEdit}
|
||||
rowState={(r) => (r === 1 ? "deleted" : null)}
|
||||
/>,
|
||||
);
|
||||
fireEvent.mouseDown(screen.getAllByRole("gridcell")[0]!, { button: 0 });
|
||||
fireEvent.paste(screen.getByRole("grid"), { clipboardData: { getData: () => "new\tother\nignored\tignored" } });
|
||||
expect(onEdit.mock.calls).toEqual([
|
||||
[0, 0, "new"],
|
||||
[0, 1, "other"],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -3,11 +3,11 @@
|
||||
* cell selection (click, ⇧-click, arrows, ⌘A), copy as TSV / CSV, `<null>`
|
||||
* rendering, sortable headers and in-place editing (table editor).
|
||||
*/
|
||||
import { useEffect, useMemo, useRef, useState, type KeyboardEvent, type MouseEvent } from "react";
|
||||
import { useEffect, useMemo, useRef, useState, type ClipboardEvent, type KeyboardEvent, type MouseEvent } from "react";
|
||||
import { useVirtualizer } from "@tanstack/react-virtual";
|
||||
import clsx from "clsx";
|
||||
import { Icon, showContextMenu, type MenuItem } from "@/ui";
|
||||
import { toCsv, toTsv, type Cell } from "./model";
|
||||
import { parseDelimited, toCsv, toTsv, type Cell } from "./model";
|
||||
import styles from "./Database.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
@@ -95,6 +95,14 @@ export function Grid(props: GridProps) {
|
||||
const { columns, rowCount, value, editable, onEdit, sort, onSort, rowMenu, firstRowNumber = 1 } = props;
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const [sel, setSel] = useState<Sel | null>(null);
|
||||
const dragging = useRef(false);
|
||||
useEffect(() => {
|
||||
const stop = () => {
|
||||
dragging.current = false;
|
||||
};
|
||||
window.addEventListener("mouseup", stop);
|
||||
return () => window.removeEventListener("mouseup", stop);
|
||||
}, []);
|
||||
const [editing, setEditing] = useState<{ row: number; col: number; text: string } | null>(null);
|
||||
const columnKey = columns.map((c) => c.name).join("\u0000");
|
||||
const [widths, setWidths] = useState<number[]>([]);
|
||||
@@ -206,9 +214,34 @@ export function Grid(props: GridProps) {
|
||||
return;
|
||||
}
|
||||
if (editing) commit();
|
||||
e.preventDefault();
|
||||
scrollRef.current?.focus();
|
||||
dragging.current = true;
|
||||
setSel(e.shiftKey && sel ? { ...sel, r1: r, c1: c } : { r0: r, c0: c, r1: r, c1: c });
|
||||
};
|
||||
|
||||
const onPaste = (e: ClipboardEvent<HTMLDivElement>) => {
|
||||
if (editing || !editable || !onEdit || !sel) return;
|
||||
const text = e.clipboardData.getData("text/plain");
|
||||
if (!text) return;
|
||||
e.preventDefault();
|
||||
const rows = parseDelimited(text, "\t");
|
||||
const { top, left } = norm(sel);
|
||||
let bottom = top;
|
||||
let right = left;
|
||||
rows.forEach((cells, dr) =>
|
||||
cells.forEach((cell, dc) => {
|
||||
const row = top + dr,
|
||||
col = left + dc;
|
||||
if (row >= rowCount || col >= columns.length || props.rowState?.(row) === "deleted") return;
|
||||
onEdit(row, col, cell);
|
||||
bottom = Math.max(bottom, row);
|
||||
right = Math.max(right, col);
|
||||
}),
|
||||
);
|
||||
setSel({ r0: top, c0: left, r1: bottom, c1: right });
|
||||
};
|
||||
|
||||
const onRowNumberMouseDown = (e: MouseEvent, r: number) => {
|
||||
if (e.button !== 0 && sel && selected(r, 0)) return;
|
||||
const last = columns.length - 1;
|
||||
@@ -266,6 +299,7 @@ export function Grid(props: GridProps) {
|
||||
aria-label={props["aria-label"] ?? "Results"}
|
||||
aria-rowcount={rowCount}
|
||||
onKeyDown={onKeyDown}
|
||||
onPaste={onPaste}
|
||||
onContextMenu={onContextMenu}
|
||||
>
|
||||
<div className={styles.gridInner} style={{ width: totalWidth, height: virtualizer.getTotalSize() + ROW_H }}>
|
||||
@@ -367,6 +401,9 @@ export function Grid(props: GridProps) {
|
||||
props.isModified?.(r, c) && styles.cellModified,
|
||||
)}
|
||||
onMouseDown={(e) => onCellMouseDown(e, r, c)}
|
||||
onMouseEnter={() => {
|
||||
if (dragging.current) setSel((s) => (s ? { ...s, r1: r, c1: c } : s));
|
||||
}}
|
||||
onDoubleClick={() => startEdit(r, c)}
|
||||
title={val != null && val.length > 40 ? val.slice(0, 2000) : undefined}
|
||||
>
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { useState } from "react";
|
||||
import { SqlFilterInput } from "./SqlFilterInput";
|
||||
|
||||
describe("table SQL completion", () => {
|
||||
it.each(["where", "order"] as const)("suggests the current table columns in %s", (kind) => {
|
||||
function Example() {
|
||||
const [value, setValue] = useState("");
|
||||
return (
|
||||
<SqlFilterInput
|
||||
value={value}
|
||||
onChange={setValue}
|
||||
onKeyDown={vi.fn()}
|
||||
kind={kind}
|
||||
schema="main"
|
||||
table="users"
|
||||
columns={[
|
||||
{ name: "email", type: "text" },
|
||||
{ name: "id", type: "integer" },
|
||||
]}
|
||||
driver="sqlite"
|
||||
/>
|
||||
);
|
||||
}
|
||||
render(<Example />);
|
||||
const input = screen.getByRole("textbox");
|
||||
fireEvent.change(input, { target: { value: "ema", selectionStart: 3 } });
|
||||
expect(screen.getByRole("option", { name: /email/i })).toBeTruthy();
|
||||
expect(screen.queryByRole("option", { name: /^id /i })).toBeNull();
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
expect((input as HTMLInputElement).value).toBe("email");
|
||||
});
|
||||
});
|
||||
|
||||
describe("SQL filter typing", () => {
|
||||
function Example() {
|
||||
const [value, setValue] = useState("");
|
||||
return (
|
||||
<SqlFilterInput
|
||||
value={value}
|
||||
onChange={setValue}
|
||||
onKeyDown={vi.fn()}
|
||||
kind="where"
|
||||
schema="main"
|
||||
table="users"
|
||||
columns={[{ name: "email", type: "text" }]}
|
||||
driver="sqlite"
|
||||
/>
|
||||
);
|
||||
}
|
||||
it.each([
|
||||
["'", "''"],
|
||||
['"', '""'],
|
||||
["(", "()"],
|
||||
])("pairs %s without opening completion", (key, paired) => {
|
||||
render(<Example />);
|
||||
const input = screen.getByRole("textbox") as HTMLInputElement;
|
||||
fireEvent.keyDown(input, { key });
|
||||
expect(input.value).toBe(paired);
|
||||
expect(input.selectionStart).toBe(1);
|
||||
expect(screen.queryByRole("listbox")).toBeNull();
|
||||
});
|
||||
it.each([" ", "'", '"', "("])("does not automatically complete after %s", (character) => {
|
||||
render(<Example />);
|
||||
const input = screen.getByRole("textbox");
|
||||
fireEvent.change(input, { target: { value: character, selectionStart: 1 } });
|
||||
expect(screen.queryByRole("listbox")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,202 @@
|
||||
import { useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
|
||||
import type { DbCompletion, DbDriver } from "@/platform/ipc";
|
||||
import { Input, Popup } from "@/ui";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { analyze } from "./sql/analyze";
|
||||
import { quoteIdent, shouldAutoCompleteSql, sqlCandidates } from "./sql/complete";
|
||||
import { inLiteral, lex } from "./sql/lexer";
|
||||
import styles from "./Database.module.css";
|
||||
import { SqlHighlight } from "./SqlHighlight";
|
||||
|
||||
export function SqlFilterInput({
|
||||
value,
|
||||
onChange,
|
||||
onKeyDown,
|
||||
onBlur,
|
||||
kind,
|
||||
schema,
|
||||
table,
|
||||
columns,
|
||||
driver,
|
||||
invalid,
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
onKeyDown: (event: KeyboardEvent<HTMLInputElement>) => void;
|
||||
onBlur?: () => void;
|
||||
kind: "where" | "order";
|
||||
schema: string;
|
||||
table: string;
|
||||
columns: readonly { name: string; type: string }[];
|
||||
driver: DbDriver;
|
||||
invalid?: boolean;
|
||||
}) {
|
||||
const ref = useRef<HTMLInputElement>(null);
|
||||
const highlightRef = useRef<HTMLDivElement>(null);
|
||||
const pendingCaret = useRef<number | null>(null);
|
||||
useLayoutEffect(() => {
|
||||
if (pendingCaret.current !== null) {
|
||||
ref.current?.setSelectionRange(pendingCaret.current, pendingCaret.current);
|
||||
pendingCaret.current = null;
|
||||
}
|
||||
}, [value]);
|
||||
const [caret, setCaret] = useState(0);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [active, setActive] = useState(0);
|
||||
const prefix = `SELECT * FROM ${quoteIdent(schema, driver)}.${quoteIdent(table, driver)} ${kind === "where" ? "WHERE" : "ORDER BY"} `;
|
||||
const model = useMemo<DbCompletion>(
|
||||
() => ({
|
||||
defaultSchema: schema,
|
||||
foreignKeys: [],
|
||||
tables: [
|
||||
{
|
||||
schema,
|
||||
name: table,
|
||||
kind: "table",
|
||||
columns: columns.map((c) => ({
|
||||
name: c.name,
|
||||
dataType: c.type,
|
||||
nullable: true,
|
||||
primaryKey: false,
|
||||
hasDefault: false,
|
||||
})),
|
||||
},
|
||||
],
|
||||
}),
|
||||
[schema, table, columns],
|
||||
);
|
||||
const analysis = analyze(prefix + value, prefix.length + caret, driver);
|
||||
const from = Math.max(0, analysis.prefix.from - prefix.length);
|
||||
const typed = value.slice(from, caret).toLowerCase();
|
||||
const candidates = sqlCandidates({ model, analysis, driver }).filter(
|
||||
(c) => c.kind === "column" || (kind === "where" && ["keyword", "function"].includes(c.kind)),
|
||||
);
|
||||
if (kind === "order")
|
||||
candidates.push(...["ASC", "DESC"].map((label) => ({ label, kind: "keyword" as const, boost: 0 })));
|
||||
const options = candidates
|
||||
.filter((c, i, a) => c.label.toLowerCase().startsWith(typed) && a.findIndex((v) => v.label === c.label) === i)
|
||||
.slice(0, 30);
|
||||
const choose = (item: (typeof options)[number]) => {
|
||||
const replacement = kind === "order" && item.kind === "column" ? item.label : (item.insert ?? item.label);
|
||||
const next = value.slice(0, from) + replacement + value.slice(caret);
|
||||
onChange(next);
|
||||
setOpen(false);
|
||||
requestAnimationFrame(() => {
|
||||
ref.current?.focus();
|
||||
ref.current?.setSelectionRange(from + replacement.length, from + replacement.length);
|
||||
});
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<div className={styles.sqlInputWrap}>
|
||||
<div ref={highlightRef} className={styles.sqlHighlight} aria-hidden="true">
|
||||
<SqlHighlight text={value} />
|
||||
</div>
|
||||
<Input
|
||||
ref={ref}
|
||||
className={value ? styles.sqlInputText : undefined}
|
||||
onScroll={(e) => {
|
||||
if (highlightRef.current) highlightRef.current.scrollLeft = e.currentTarget.scrollLeft;
|
||||
}}
|
||||
variant="bare"
|
||||
mono
|
||||
aria-label={kind === "where" ? "WHERE filter" : "ORDER BY"}
|
||||
placeholder={kind === "where" ? "WHERE" : "ORDER BY"}
|
||||
invalid={invalid}
|
||||
value={value}
|
||||
onChange={(e) => {
|
||||
onChange(e.target.value);
|
||||
setCaret(e.target.selectionStart ?? e.target.value.length);
|
||||
setActive(0);
|
||||
const pos = e.target.selectionStart ?? e.target.value.length;
|
||||
setOpen(shouldAutoCompleteSql(analyze(prefix + e.target.value, prefix.length + pos, driver)));
|
||||
}}
|
||||
onClick={(e) => setCaret(e.currentTarget.selectionStart ?? value.length)}
|
||||
onBlur={onBlur}
|
||||
onKeyDown={(e) => {
|
||||
if (!e.metaKey && !e.ctrlKey && !e.altKey) {
|
||||
const start = e.currentTarget.selectionStart ?? value.length;
|
||||
const end = e.currentTarget.selectionEnd ?? start;
|
||||
const pairs: Record<string, string> = { "(": ")", "[": "]", "{": "}", "'": "'", '"': '"' };
|
||||
const closer = pairs[e.key];
|
||||
const quote = e.key === "'" || e.key === '"';
|
||||
const prefs = editorPrefs().smartKeys;
|
||||
const literal = inLiteral(lex(value, driver), start);
|
||||
if (start === end && value[start] === e.key && (quote || ")]}".includes(e.key))) {
|
||||
e.preventDefault();
|
||||
e.currentTarget.setSelectionRange(start + 1, start + 1);
|
||||
setCaret(start + 1);
|
||||
setOpen(false);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
closer &&
|
||||
start === end &&
|
||||
(quote ? prefs.pairQuotes : prefs.pairBrackets) &&
|
||||
!literal &&
|
||||
(!value[start] || /[\s)\]};,]/.test(value[start]!))
|
||||
) {
|
||||
e.preventDefault();
|
||||
pendingCaret.current = start + 1;
|
||||
onChange(value.slice(0, start) + e.key + closer + value.slice(end));
|
||||
setCaret(start + 1);
|
||||
setOpen(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (e.ctrlKey && e.key === " ") {
|
||||
e.preventDefault();
|
||||
setCaret(e.currentTarget.selectionStart ?? value.length);
|
||||
setOpen(true);
|
||||
setActive(0);
|
||||
return;
|
||||
}
|
||||
if (open && options.length && (e.key === "ArrowDown" || e.key === "ArrowUp")) {
|
||||
e.preventDefault();
|
||||
setActive((active + (e.key === "ArrowDown" ? 1 : -1) + options.length) % options.length);
|
||||
return;
|
||||
}
|
||||
if (open && options.length && (e.key === "Enter" || e.key === "Tab")) {
|
||||
e.preventDefault();
|
||||
choose(options[Math.min(active, options.length - 1)]!);
|
||||
return;
|
||||
}
|
||||
if (open && e.key === "Escape") {
|
||||
e.preventDefault();
|
||||
setOpen(false);
|
||||
return;
|
||||
}
|
||||
onKeyDown(e);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{open && options.length > 0 && (
|
||||
<Popup
|
||||
open
|
||||
anchor={ref}
|
||||
onClose={() => setOpen(false)}
|
||||
autoFocus={false}
|
||||
restoreFocus={false}
|
||||
role="listbox"
|
||||
aria-label="SQL completion"
|
||||
className={styles.sqlCompletion}
|
||||
>
|
||||
{options.map((c, i) => (
|
||||
<button
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={i === active}
|
||||
key={`${c.kind}:${c.label}`}
|
||||
className={styles.sqlCompletionOption}
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => choose(c)}
|
||||
>
|
||||
<span>{c.label}</span>
|
||||
<small>{c.type ?? c.kind}</small>
|
||||
</button>
|
||||
))}
|
||||
</Popup>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { render, waitFor } from "@testing-library/react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { SqlHighlight } from "./SqlHighlight";
|
||||
|
||||
describe("SQL filter highlighting", () => {
|
||||
it("uses the console SQL language and theme to highlight keywords, strings and numbers", async () => {
|
||||
const { container } = render(<SqlHighlight text="name = 'active' AND id > 12" />);
|
||||
await waitFor(() => expect(container.querySelectorAll("span[class]").length).toBeGreaterThanOrEqual(3));
|
||||
expect(container.textContent).toContain("name = 'active' AND id > 12");
|
||||
});
|
||||
it("wraps the gaps between tokens so flex layout keeps single spaces", async () => {
|
||||
const { container } = render(<SqlHighlight text="age > 20 AND id = 1" />);
|
||||
await waitFor(() => expect(container.querySelectorAll("span[class]").length).toBeGreaterThanOrEqual(3));
|
||||
const bare = [...container.childNodes].filter((n) => n.nodeType === Node.TEXT_NODE);
|
||||
expect(bare).toEqual([]);
|
||||
const spans = [...container.children].filter((n) => n.tagName === "SPAN");
|
||||
expect(spans.map((n) => n.textContent).join("")).toBe("age > 20 AND id = 1");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { ensureSyntaxTree, type LanguageSupport } from "@codemirror/language";
|
||||
import { highlightTree } from "@lezer/highlight";
|
||||
import { findLanguageDescription, loadSupport, loadedSupport } from "@/editor/core/cm/languages";
|
||||
import { openideaHighlightStyle } from "@/editor/core/cm/highlight";
|
||||
|
||||
const sql = findLanguageDescription("SQL", "console.sql");
|
||||
|
||||
/** Render with the same language mode and highlight style as a SQL console. */
|
||||
export function SqlHighlight({ text }: { text: string }) {
|
||||
const [support, setSupport] = useState<LanguageSupport | null>(() => loadedSupport(sql));
|
||||
useEffect(() => {
|
||||
if (!sql || support) return;
|
||||
let mounted = true;
|
||||
void loadSupport(sql).then((value) => {
|
||||
if (mounted) setSupport(value);
|
||||
});
|
||||
return () => {
|
||||
mounted = false;
|
||||
};
|
||||
}, [support]);
|
||||
const pieces = useMemo(() => {
|
||||
if (!support) return [<span key={0}>{text}</span>];
|
||||
const state = EditorState.create({ doc: text, extensions: [support] });
|
||||
const tree = ensureSyntaxTree(state, text.length, 100);
|
||||
if (!tree) return [<span key={0}>{text}</span>];
|
||||
const result: React.ReactNode[] = [];
|
||||
let offset = 0;
|
||||
highlightTree(tree, openideaHighlightStyle, (from, to, classes) => {
|
||||
// Every piece is an element: the overlay is a flex row, which drops bare whitespace-only text.
|
||||
if (from > offset) result.push(<span key={`t${offset}`}>{text.slice(offset, from)}</span>);
|
||||
result.push(
|
||||
<span key={from} className={classes}>
|
||||
{text.slice(from, to)}
|
||||
</span>,
|
||||
);
|
||||
offset = to;
|
||||
});
|
||||
if (offset < text.length) result.push(<span key={`t${offset}`}>{text.slice(offset)}</span>);
|
||||
return result;
|
||||
}, [support, text]);
|
||||
return (
|
||||
<>
|
||||
<style>{openideaHighlightStyle.module?.getRules()}</style>
|
||||
{pieces}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -13,8 +13,9 @@ import {
|
||||
type DbTablePage,
|
||||
type RequestId,
|
||||
} from "@/platform/ipc";
|
||||
import { Button, EmptyState, Icon, IconButton, Input, Select, Spinner, T, showContextMenu } from "@/ui";
|
||||
import { Button, EmptyState, Icon, IconButton, Select, Spinner, T, showContextMenu } from "@/ui";
|
||||
import { notifications, type EditorInput } from "@/workbench/contributions";
|
||||
import { SqlFilterInput } from "./SqlFilterInput";
|
||||
import { DataView, ExtractorSelect, PanelToggle, exportMenu, type DataPanel } from "./DataView";
|
||||
import type { ExportFormat } from "./export";
|
||||
import {
|
||||
@@ -257,13 +258,14 @@ export function TableEditor({ input }: { input: EditorInput }) {
|
||||
<div className={styles.filterBar}>
|
||||
<label className={styles.filterField}>
|
||||
<Icon name="filter" size={14} />
|
||||
<Input
|
||||
variant="bare"
|
||||
mono
|
||||
aria-label="WHERE filter"
|
||||
placeholder="WHERE"
|
||||
<SqlFilterInput
|
||||
kind="where"
|
||||
schema={ref.schema}
|
||||
table={ref.table}
|
||||
columns={gridColumns}
|
||||
driver={sourceById(ref.id)?.driver ?? "sqlite"}
|
||||
value={filterText}
|
||||
onChange={(e) => setFilterText(e.target.value)}
|
||||
onChange={setFilterText}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") {
|
||||
setOffset(0);
|
||||
@@ -274,14 +276,15 @@ export function TableEditor({ input }: { input: EditorInput }) {
|
||||
</label>
|
||||
<label className={styles.filterField}>
|
||||
<Icon name="db-sort" size={14} />
|
||||
<Input
|
||||
variant="bare"
|
||||
mono
|
||||
aria-label="ORDER BY"
|
||||
placeholder="ORDER BY"
|
||||
<SqlFilterInput
|
||||
kind="order"
|
||||
schema={ref.schema}
|
||||
table={ref.table}
|
||||
columns={gridColumns}
|
||||
driver={sourceById(ref.id)?.driver ?? "sqlite"}
|
||||
invalid={orderInvalid}
|
||||
value={orderDraft ?? formatOrderBy(sort)}
|
||||
onChange={(e) => setOrderDraft(e.target.value)}
|
||||
onChange={setOrderDraft}
|
||||
onBlur={() => !orderInvalid && setOrderDraft(null)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Escape") setOrderDraft(null);
|
||||
|
||||
@@ -38,7 +38,7 @@ import { shortcutLabel } from "@/platform/keymap";
|
||||
import { IconButton, Select } from "@/ui";
|
||||
import { sourceLabel, splitTarget, targetOf } from "./model";
|
||||
import { analyze, templateContexts, valuesSlot } from "./sql/analyze";
|
||||
import { sqlCandidates, type CandidateKind, type SqlCandidate } from "./sql/complete";
|
||||
import { shouldAutoCompleteSql, sqlCandidates, type CandidateKind, type SqlCandidate } from "./sql/complete";
|
||||
import { sqlSupport } from "./sqlSupport";
|
||||
import {
|
||||
bindConsole,
|
||||
@@ -427,9 +427,7 @@ function completionSource(path: string): CompletionSource {
|
||||
const analysis = placeholder
|
||||
? analyze(doc.slice(0, sel.from) + doc.slice(sel.to), sel.from, driver)
|
||||
: analyze(doc, ctx.pos, driver);
|
||||
const typed = analysis.prefix.text;
|
||||
const afterDot = !!analysis.qualifier && !typed;
|
||||
if (!ctx.explicit && ((!typed && !afterDot) || /^\d/.test(typed))) return null;
|
||||
if (!ctx.explicit && !shouldAutoCompleteSql(analysis)) return null;
|
||||
const candidates = sqlCandidates({ model, analysis, driver, sourceName: source?.name ?? undefined });
|
||||
if (!candidates.length) return null;
|
||||
return {
|
||||
|
||||
@@ -47,6 +47,12 @@ export interface SqlCandidate {
|
||||
doc?: string;
|
||||
}
|
||||
|
||||
/** Match the console's automatic trigger: a word or a qualifier followed by a dot. */
|
||||
export function shouldAutoCompleteSql(analysis: Analysis): boolean {
|
||||
const typed = analysis.prefix.text;
|
||||
return analysis.context.kind !== "none" && (!!typed || !!analysis.qualifier) && !/^\d/.test(typed);
|
||||
}
|
||||
|
||||
const MAX_ALL_COLUMNS = 3000;
|
||||
|
||||
const eq = (a: string | null | undefined, b: string | null | undefined) =>
|
||||
@@ -62,7 +68,10 @@ export function quoteIdent(name: string, driver: DbDriver): string {
|
||||
|
||||
/** A short alias for `table` not in `taken`: `order_items` → `oi`, `users` → `u`. */
|
||||
export function aliasFor(table: string, taken: ReadonlySet<string>): string {
|
||||
const words = table.split(/[_\s.$-]+|(?<=[a-z])(?=[A-Z])/).filter(Boolean);
|
||||
const words = table
|
||||
.replace(/([a-z])([A-Z])/g, "$1 $2")
|
||||
.split(/[_\s.$-]+/)
|
||||
.filter(Boolean);
|
||||
let base =
|
||||
words
|
||||
.map((w) => w[0]!)
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { appendConsole, clearConsole, useDebug } from "../state";
|
||||
|
||||
const lines = (session: number) => useDebug.getState().console[session] ?? [];
|
||||
|
||||
afterEach(() => useDebug.setState({ console: {} }));
|
||||
|
||||
describe("debug console", () => {
|
||||
it("renders ANSI colours instead of showing the escapes", () => {
|
||||
// A logback pattern whose colour spans the line break (`%boldMagenta(%logger{36}%n)`), with CRLF.
|
||||
appendConsole(
|
||||
5,
|
||||
"stdout",
|
||||
"\x1b[36m2026-10-29 09:13:55\x1b[0;39m \x1b[32m[main]\x1b[0;39m \x1b[1;35mo.d.c.p.l.MessageTopicListener\r\n",
|
||||
);
|
||||
appendConsole(5, "stdout", "\x1b[0;39m - 初始化消息主题订阅监听器成功\r\n");
|
||||
const [first, second] = lines(5);
|
||||
expect(first!.text).toBe("2026-10-29 09:13:55 [main] o.d.c.p.l.MessageTopicListener\n");
|
||||
expect(first!.spans[0]).toEqual({ text: "2026-10-29 09:13:55", fg: "var(--ansi-cyan)" });
|
||||
expect(first!.spans).toContainEqual({ text: "[main]", fg: "var(--ansi-green)" });
|
||||
expect(first!.spans.at(-1)).toEqual({
|
||||
text: "o.d.c.p.l.MessageTopicListener\n",
|
||||
fg: "var(--ansi-magenta)",
|
||||
bold: true,
|
||||
});
|
||||
expect(second!.text).toBe(" - 初始化消息主题订阅监听器成功\n");
|
||||
expect(second!.spans).toEqual([{ text: " - 初始化消息主题订阅监听器成功\n" }]);
|
||||
expect(lines(5).some((l) => l.text.includes("\x1b"))).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps a colour across output events and an escape split between them", () => {
|
||||
appendConsole(6, "stderr", "\x1b[3");
|
||||
appendConsole(6, "stderr", "1mred ");
|
||||
appendConsole(6, "stderr", "still\x1b[0m plain\n");
|
||||
const [line] = lines(6);
|
||||
expect(line!.text).toBe("red still plain\n");
|
||||
expect(line!.spans).toEqual([{ text: "red still", fg: "var(--ansi-red)" }, { text: " plain\n" }]);
|
||||
// Streams of other categories and sessions have their own state.
|
||||
appendConsole(6, "stdout", "\x1b[32mgreen");
|
||||
appendConsole(7, "stdout", "plain\n");
|
||||
expect(lines(7)[0]!.spans).toEqual([{ text: "plain\n" }]);
|
||||
clearConsole(6);
|
||||
appendConsole(6, "stdout", "after clear\n");
|
||||
expect(lines(6)[0]!.spans).toEqual([{ text: "after clear\n" }]);
|
||||
});
|
||||
});
|
||||
@@ -75,6 +75,23 @@ describe("Java debugging (java-debug through jdtls)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("passes the configuration's VM options to java-debug's vmArgs, before the main class", async () => {
|
||||
const args = [
|
||||
"-Ddemo.flag=on",
|
||||
"--add-opens",
|
||||
"java.base/java.lang=ALL-UNNAMED",
|
||||
"-Dname=a b",
|
||||
"-cp",
|
||||
"${classpath}",
|
||||
];
|
||||
const l = await javaLaunchConfig({ ...app, args: [...args, "a.App", "--spring.profiles.active=dev"] }, "/p");
|
||||
expect(JSON.parse(l.extraJson!)).toMatchObject({
|
||||
mainClass: "a.App",
|
||||
vmArgs: '-Ddemo.flag=on --add-opens java.base/java.lang=ALL-UNNAMED "-Dname=a b"',
|
||||
args: "--spring.profiles.active=dev",
|
||||
});
|
||||
});
|
||||
|
||||
it("lets java-debug shorten a classpath too long for the OS, as Run does", async () => {
|
||||
for (const how of ["jarmanifest", "argfile"]) {
|
||||
shortenCommandLine = how;
|
||||
|
||||
@@ -56,6 +56,16 @@ describe("locating Smart Step Into targets", () => {
|
||||
expect(locateStepTargets(line, 3, [target(1, "missing()")])).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects identifier suffixes, preserving UTF-16 offsets and nested calls", () => {
|
||||
const line = "𐐀foo() αfoo() $foo() _foo() foo(foo())";
|
||||
const from = line.indexOf("foo(foo");
|
||||
expect(locateStepTargets(line, 0, [target(1, "foo()"), target(2, "foo()")])).toEqual([
|
||||
{ id: 1, from, to: from + 3 },
|
||||
{ id: 2, from: from + 4, to: from + 7 },
|
||||
]);
|
||||
expect(targetsOnLine("𐐀foo() bar()", 0, [target(1, "foo()"), target(2, "bar()")]).map((t) => t.id)).toEqual([2]);
|
||||
});
|
||||
|
||||
it("keeps only the paused line's calls when the adapter lists the whole function", () => {
|
||||
const line = " total = add(total, square(i))";
|
||||
const all = [target(0, "square(i)"), target(1, "add(total, square(i))"), target(2, 'print("total", total)')];
|
||||
|
||||
@@ -25,7 +25,11 @@ export function calleeName(label: string): string | null {
|
||||
|
||||
/** A call of `name`: `name(` not preceded by an identifier character. */
|
||||
function callPattern(name: string, flags: string): RegExp {
|
||||
return new RegExp(`(?<![\\p{L}\\p{N}_$])${name.replace(/\$/g, "\\$")}\\s*\\(`, flags);
|
||||
return new RegExp(`${name.replace(/\$/g, "\\$")}\\s*\\(`, flags);
|
||||
}
|
||||
|
||||
function isCallBoundary(text: string, from: number): boolean {
|
||||
return !/[\p{L}\p{N}_$]$/u.test(text.slice(Math.max(0, from - 2), from));
|
||||
}
|
||||
|
||||
function identifierEnd(text: string, from: number): number {
|
||||
@@ -55,7 +59,7 @@ export function locateStepTargets(lineText: string, line: number, targets: StepI
|
||||
const name = calleeName(t.label);
|
||||
if (!name) return null;
|
||||
for (const m of lineText.matchAll(callPattern(name, "gu"))) {
|
||||
if (used.has(m.index!)) continue;
|
||||
if (used.has(m.index!) || !isCallBoundary(lineText, m.index!)) continue;
|
||||
from = m.index!;
|
||||
to = from + name.length;
|
||||
break;
|
||||
@@ -78,7 +82,7 @@ export function targetsOnLine(lineText: string, line: number, targets: StepInTar
|
||||
if (t.line != null) return t.line === line;
|
||||
if (t.column != null) return true;
|
||||
const name = calleeName(t.label);
|
||||
return !name || callPattern(name, "u").test(lineText);
|
||||
return !name || [...lineText.matchAll(callPattern(name, "gu"))].some((m) => isCallBoundary(lineText, m.index));
|
||||
});
|
||||
return kept.length ? kept : targets;
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
import { workflowSettings } from "@/platform/workflowSettings";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { create } from "zustand";
|
||||
import { AnsiStream, appendSpans, type Span } from "@/ui/ansi";
|
||||
import { setContext } from "@/platform/context";
|
||||
import {
|
||||
call,
|
||||
@@ -55,7 +56,10 @@ export interface DebugSession {
|
||||
export interface ConsoleLine {
|
||||
id: number;
|
||||
category: string;
|
||||
/** Plain text without escape sequences. */
|
||||
text: string;
|
||||
/** `text` styled by its ANSI colours. */
|
||||
spans: Span[];
|
||||
}
|
||||
|
||||
export interface WatchResult {
|
||||
@@ -95,6 +99,16 @@ export const useExecutionPoint = create<ExecutionPoint>(() => ({ path: null, lin
|
||||
|
||||
const MAX_CONSOLE_LINES = 5000;
|
||||
let lineSeq = 0;
|
||||
/** ANSI state per session and output category (a colour can span several output events). */
|
||||
const ansiStreams = new Map<DebugSessionId, Map<string, AnsiStream>>();
|
||||
|
||||
function ansiStream(session: DebugSessionId, category: string): AnsiStream {
|
||||
let streams = ansiStreams.get(session);
|
||||
if (!streams) ansiStreams.set(session, (streams = new Map()));
|
||||
let stream = streams.get(category);
|
||||
if (!stream) streams.set(category, (stream = new AnsiStream()));
|
||||
return stream;
|
||||
}
|
||||
|
||||
// --- accessors ---------------------------------------------------------------
|
||||
|
||||
@@ -215,7 +229,10 @@ export function publishContext() {
|
||||
|
||||
// --- console -----------------------------------------------------------------
|
||||
|
||||
export function appendConsole(session: DebugSessionId, category: string, text: string) {
|
||||
export function appendConsole(session: DebugSessionId, category: string, raw: string) {
|
||||
if (!raw) return;
|
||||
const spans = ansiStream(session, category).parse(raw);
|
||||
const text = spans.map((sp) => sp.text).join("");
|
||||
if (!text) return;
|
||||
useDebug.setState((s) => {
|
||||
const prev = s.console[session] ?? [];
|
||||
@@ -223,9 +240,9 @@ export function appendConsole(session: DebugSessionId, category: string, text: s
|
||||
const last = next[next.length - 1];
|
||||
// Merge partial lines of the same category.
|
||||
if (last && last.category === category && !last.text.endsWith("\n")) {
|
||||
next[next.length - 1] = { ...last, text: last.text + text };
|
||||
next[next.length - 1] = { ...last, text: last.text + text, spans: appendSpans(last.spans, spans) };
|
||||
} else {
|
||||
next.push({ id: ++lineSeq, category, text });
|
||||
next.push({ id: ++lineSeq, category, text, spans });
|
||||
}
|
||||
if (next.length > MAX_CONSOLE_LINES) next.splice(0, next.length - MAX_CONSOLE_LINES);
|
||||
return { console: { ...s.console, [session]: next } };
|
||||
@@ -233,6 +250,7 @@ export function appendConsole(session: DebugSessionId, category: string, text: s
|
||||
}
|
||||
|
||||
export function clearConsole(session: DebugSessionId) {
|
||||
ansiStreams.delete(session);
|
||||
useDebug.setState((s) => ({ console: { ...s.console, [session]: [] } }));
|
||||
}
|
||||
|
||||
@@ -255,6 +273,7 @@ export async function startSession(
|
||||
useDebug.setState((s) => {
|
||||
const sessions = Object.fromEntries(Object.entries(s.sessions).filter(([, v]) => isLive(v)));
|
||||
const consoleLines = Object.fromEntries(Object.entries(s.console).filter(([k]) => sessions[+k]));
|
||||
for (const id of ansiStreams.keys()) if (!sessions[id]) ansiStreams.delete(id);
|
||||
return { sessions, console: consoleLines, active: s.active != null && sessions[s.active] ? s.active : null };
|
||||
});
|
||||
try {
|
||||
@@ -657,6 +676,7 @@ export function handleDebugEvent(id: DebugSessionId, event: DebugEvent) {
|
||||
export function resetSessions() {
|
||||
const { sessions } = useDebug.getState();
|
||||
for (const s of Object.values(sessions)) if (s.parent == null && isLive(s)) void stopSession(s.id);
|
||||
ansiStreams.clear();
|
||||
useDebug.setState({ sessions: {}, active: null, console: {}, stopSeq: 0 });
|
||||
useExecutionPoint.setState({ path: null, line: 0, top: true, values: {} });
|
||||
publishContext();
|
||||
|
||||
@@ -42,6 +42,8 @@ import { VariablesView, type VarRoot } from "./VariablesView";
|
||||
import { pushHistory, readHistory, setConsoleHistoryBrowser } from "./expressionHistory";
|
||||
import { sortVariables } from "../values";
|
||||
import { workflowSettings } from "@/platform/workflowSettings";
|
||||
import { spanStyle } from "@/ui/ansi";
|
||||
import ansi from "@/ui/ansi.module.css";
|
||||
import styles from "./DebugToolWindow.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
@@ -609,7 +611,7 @@ function ConsoleView({ session }: { session: DebugSession }) {
|
||||
<div className={styles.console}>
|
||||
<div
|
||||
ref={scroller}
|
||||
className={styles.consoleOutput}
|
||||
className={clsx(styles.consoleOutput, ansi.palette)}
|
||||
onScroll={(e) => {
|
||||
const el = e.currentTarget;
|
||||
stick.current = el.scrollHeight - el.scrollTop - el.clientHeight < 24;
|
||||
@@ -624,7 +626,11 @@ function ConsoleView({ session }: { session: DebugSession }) {
|
||||
>
|
||||
{(lines ?? []).map((l) => (
|
||||
<span key={l.id} className={clsx(styles.out, styles[`cat-${l.category}`])}>
|
||||
{l.text}
|
||||
{l.spans.map((sp, i) => (
|
||||
<span key={i} style={spanStyle(sp)}>
|
||||
{sp.text}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -648,7 +648,7 @@ function TypeField({
|
||||
spellCheck={false}
|
||||
value={value}
|
||||
placeholder={tx(field.placeholder)}
|
||||
rows={4}
|
||||
rows={field.rows ?? 4}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
useRef,
|
||||
useState,
|
||||
type ClipboardEvent,
|
||||
type CSSProperties,
|
||||
type KeyboardEvent,
|
||||
type MouseEvent,
|
||||
} from "react";
|
||||
@@ -14,7 +13,9 @@ import clsx from "clsx";
|
||||
import { useVirtualizer } from "@tanstack/react-virtual";
|
||||
import { useWorkflowSettings } from "@/platform/workflowSettings";
|
||||
import { Icon, showContextMenu } from "@/ui";
|
||||
import type { ConsoleLine, ConsoleModel, SpanStyle } from "./console";
|
||||
import { spanStyle } from "@/ui/ansi";
|
||||
import ansi from "@/ui/ansi.module.css";
|
||||
import type { ConsoleLine, ConsoleModel } from "./console";
|
||||
import { findOutputLinks, type OutputLink } from "./links";
|
||||
import { openTarget, openUrl } from "./navigate";
|
||||
import { segmentLine } from "./segments";
|
||||
@@ -23,19 +24,6 @@ import { tx } from "@/platform/i18n";
|
||||
|
||||
const ROW = 20;
|
||||
|
||||
function spanStyle(s: SpanStyle): CSSProperties | undefined {
|
||||
if (!s.fg && !s.bg && !s.bold && !s.dim && !s.italic && !s.underline && !s.strike) return undefined;
|
||||
const deco = [s.underline && "underline", s.strike && "line-through"].filter(Boolean).join(" ");
|
||||
return {
|
||||
color: s.fg,
|
||||
background: s.bg,
|
||||
fontWeight: s.bold ? "var(--fw-code-bold, 700)" : undefined,
|
||||
opacity: s.dim ? 0.6 : undefined,
|
||||
fontStyle: s.italic ? "italic" : undefined,
|
||||
textDecoration: deco || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
const Line = memo(
|
||||
function Line({ line, cwd }: { line: ConsoleLine; length: number; cwd: string }) {
|
||||
// Not memoised: the open (last) line mutates in place; `memo` below re-renders on length changes only.
|
||||
@@ -289,7 +277,7 @@ export function ConsoleView({
|
||||
return (
|
||||
<div
|
||||
ref={scrollRef}
|
||||
className={clsx(styles.console, softWrap && styles.wrap)}
|
||||
className={clsx(styles.console, ansi.palette, softWrap && styles.wrap)}
|
||||
role="log"
|
||||
aria-live="off"
|
||||
aria-label={aria["aria-label"] ?? "Console"}
|
||||
|
||||
@@ -1,24 +1,3 @@
|
||||
/* ANSI palette derived from tokens (console spans reference these). */
|
||||
.root,
|
||||
.console {
|
||||
--ansi-black: var(--control-off);
|
||||
--ansi-red: var(--danger);
|
||||
--ansi-green: var(--success);
|
||||
--ansi-yellow: var(--warning);
|
||||
--ansi-blue: var(--syn-keyword);
|
||||
--ansi-magenta: var(--syn-annotation);
|
||||
--ansi-cyan: color-mix(in srgb, var(--syn-keyword) 50%, var(--syn-string));
|
||||
--ansi-white: var(--fg);
|
||||
--ansi-bright-black: var(--fg-subtle);
|
||||
--ansi-bright-red: color-mix(in srgb, var(--danger) 72%, var(--fg-strong));
|
||||
--ansi-bright-green: color-mix(in srgb, var(--success) 72%, var(--fg-strong));
|
||||
--ansi-bright-yellow: color-mix(in srgb, var(--warning) 72%, var(--fg-strong));
|
||||
--ansi-bright-blue: color-mix(in srgb, var(--syn-keyword) 72%, var(--fg-strong));
|
||||
--ansi-bright-magenta: color-mix(in srgb, var(--syn-annotation) 72%, var(--fg-strong));
|
||||
--ansi-bright-cyan: color-mix(in srgb, var(--ansi-cyan) 72%, var(--fg-strong));
|
||||
--ansi-bright-white: var(--fg-strong);
|
||||
}
|
||||
|
||||
.root {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
|
||||
@@ -258,8 +258,11 @@ export function validateConfig(config: RunConfig, all: readonly RunConfig[] = []
|
||||
|
||||
export const hasErrors = (e: ConfigErrors) => Object.keys(e).length > 0;
|
||||
|
||||
/** Splits a command line into arguments: whitespace, '…' and "…" quoting, backslash escapes. */
|
||||
export function parseArgs(input: string): string[] {
|
||||
/**
|
||||
* Splits a command line into arguments: whitespace, '…' and "…" quoting, backslash escapes.
|
||||
* `windowsPaths`: a backslash only escapes a quote, so `C:\dir\app.jar` stays as typed.
|
||||
*/
|
||||
export function parseArgs(input: string, windowsPaths = false): string[] {
|
||||
const out: string[] = [];
|
||||
let cur = "";
|
||||
let has = false;
|
||||
@@ -268,13 +271,18 @@ export function parseArgs(input: string): string[] {
|
||||
const ch = input[i]!;
|
||||
if (quote) {
|
||||
if (ch === quote) quote = null;
|
||||
else if (ch === "\\" && quote === '"' && i + 1 < input.length && '"\\$`'.includes(input[i + 1]!))
|
||||
else if (
|
||||
ch === "\\" &&
|
||||
quote === '"' &&
|
||||
i + 1 < input.length &&
|
||||
(windowsPaths ? '"' : '"\\$`').includes(input[i + 1]!)
|
||||
)
|
||||
cur += input[++i];
|
||||
else cur += ch;
|
||||
} else if (ch === "'" || ch === '"') {
|
||||
quote = ch;
|
||||
has = true;
|
||||
} else if (ch === "\\" && i + 1 < input.length) {
|
||||
} else if (ch === "\\" && i + 1 < input.length && (!windowsPaths || "\"'".includes(input[i + 1]!))) {
|
||||
cur += input[++i];
|
||||
has = true;
|
||||
} else if (/\s/.test(ch)) {
|
||||
|
||||
@@ -1,29 +1,15 @@
|
||||
/**
|
||||
* Console line model for run output: splits streamed chunks into lines,
|
||||
* parses ANSI SGR colours (via `anser`, one stateful parser per stream),
|
||||
* parses ANSI SGR colours (`ui/ansi`, one stateful parser per stream),
|
||||
* handles `\r` overwrites (progress bars) and caps the buffer.
|
||||
*/
|
||||
/* eslint-disable no-control-regex -- escape-sequence parsing matches control characters by design */
|
||||
import Anser from "anser";
|
||||
import type { OutputChunk } from "@/platform/ipc";
|
||||
import { AnsiStream, sameStyle, type Span } from "@/ui/ansi";
|
||||
|
||||
export { paletteColor, type Span, type SpanStyle } from "@/ui/ansi";
|
||||
|
||||
export type ChunkKind = OutputChunk["kind"];
|
||||
|
||||
export interface SpanStyle {
|
||||
/** CSS colour (`var(--ansi-red)`, `rgb(…)`). */
|
||||
fg?: string;
|
||||
bg?: string;
|
||||
bold?: boolean;
|
||||
dim?: boolean;
|
||||
italic?: boolean;
|
||||
underline?: boolean;
|
||||
strike?: boolean;
|
||||
}
|
||||
|
||||
export interface Span extends SpanStyle {
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface ConsoleLine {
|
||||
/** Monotonic id (stable across trimming). */
|
||||
id: number;
|
||||
@@ -37,111 +23,6 @@ export const MAX_LINES = 50_000;
|
||||
/** Very long lines are broken up so a single minified blob can't stall rendering. */
|
||||
export const MAX_LINE_LENGTH = 8_000;
|
||||
|
||||
const NAMED = ["black", "red", "green", "yellow", "blue", "magenta", "cyan", "white"];
|
||||
|
||||
/** xterm 256-colour palette entry (16–255) as `rgb(…)`. */
|
||||
export function paletteColor(n: number): string {
|
||||
if (n < 16) {
|
||||
const bright = n >= 8;
|
||||
return `var(--ansi-${bright ? "bright-" : ""}${NAMED[n % 8]})`;
|
||||
}
|
||||
if (n >= 232) {
|
||||
const v = 8 + (n - 232) * 10;
|
||||
return `rgb(${v}, ${v}, ${v})`;
|
||||
}
|
||||
const i = n - 16;
|
||||
const steps = [0, 95, 135, 175, 215, 255];
|
||||
return `rgb(${steps[Math.floor(i / 36)]}, ${steps[Math.floor(i / 6) % 6]}, ${steps[i % 6]})`;
|
||||
}
|
||||
|
||||
function cssColor(cls: string | null, truecolor: string | null): string | undefined {
|
||||
if (!cls) return undefined;
|
||||
if (cls === "ansi-truecolor") return truecolor ? `rgb(${truecolor})` : undefined;
|
||||
const palette = /^ansi-palette-(\d+)$/.exec(cls);
|
||||
if (palette) return paletteColor(Number(palette[1]));
|
||||
if (cls.startsWith("ansi-")) return `var(--${cls})`;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function sameStyle(a: SpanStyle, b: SpanStyle) {
|
||||
return (
|
||||
a.fg === b.fg &&
|
||||
a.bg === b.bg &&
|
||||
!!a.bold === !!b.bold &&
|
||||
!!a.dim === !!b.dim &&
|
||||
!!a.italic === !!b.italic &&
|
||||
!!a.underline === !!b.underline &&
|
||||
!!a.strike === !!b.strike
|
||||
);
|
||||
}
|
||||
|
||||
// OSC (…BEL or …ST), and escape sequences other than CSI.
|
||||
const OSC_RE = /\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g;
|
||||
const NON_CSI_ESC_RE = /\x1b(?:[()][0-9A-Za-z]|[=>78DEHMNOZc])/g;
|
||||
// CSI that isn't SGR: erase-line becomes a carriage return, everything else is dropped.
|
||||
const CSI_RE = /\x1b\[([0-9;?]*)([ -/]*)([@-~])/g;
|
||||
// An escape sequence cut off at the end of a chunk.
|
||||
const INCOMPLETE_RE = /\x1b(?:\[[0-9;?]*[ -/]*|\][^\x07\x1b]*\x1b?)?$/;
|
||||
|
||||
class StreamParser {
|
||||
private anser = new Anser();
|
||||
private carry = "";
|
||||
|
||||
/** Normalises escapes; returns text whose only escapes are SGR (`ESC[…m`). */
|
||||
clean(text: string): string {
|
||||
let s = this.carry + text;
|
||||
this.carry = "";
|
||||
const cut = INCOMPLETE_RE.exec(s);
|
||||
if (cut && cut[0].length > 0) {
|
||||
this.carry = cut[0];
|
||||
s = s.slice(0, cut.index);
|
||||
}
|
||||
return s
|
||||
.replace(OSC_RE, "")
|
||||
.replace(NON_CSI_ESC_RE, "")
|
||||
.replace(CSI_RE, (all, params: string, _i: string, final: string) => {
|
||||
if (final === "m") return all;
|
||||
if (final === "K" && (params === "2" || params === "1")) return "\r";
|
||||
if (final === "G" && (params === "" || params === "1" || params === "0")) return "\r";
|
||||
return "";
|
||||
})
|
||||
.replace(/[\x00-\x08\x0b\x0c\x0e-\x1a\x1c-\x1f\x7f]/g, "");
|
||||
}
|
||||
|
||||
/** Style in effect at the end of the previous call (anser only carries it into escaped chunks). */
|
||||
private carryStyle: SpanStyle = {};
|
||||
|
||||
spans(text: string): Span[] {
|
||||
const out: Span[] = [];
|
||||
const entries = this.anser.ansiToJson(text, { json: true, use_classes: true });
|
||||
entries.forEach((e, i) => {
|
||||
// Entry 0 is the text before the first escape: it continues the previous style.
|
||||
const style = i === 0 ? this.carryStyle : entryStyle(e);
|
||||
if (i === entries.length - 1) this.carryStyle = style;
|
||||
if (e.content) out.push({ text: e.content, ...style });
|
||||
});
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
function entryStyle(e: Anser.AnserJsonEntry): SpanStyle {
|
||||
const decorations = e.decorations ?? [];
|
||||
const style: SpanStyle = {};
|
||||
let fg = cssColor(e.fg, e.fg_truecolor);
|
||||
let bg = cssColor(e.bg, e.bg_truecolor);
|
||||
if ((e as { isInverted?: boolean }).isInverted) {
|
||||
[fg, bg] = [bg ?? "var(--bg-app)", fg ?? "var(--fg)"];
|
||||
}
|
||||
if (fg) style.fg = fg;
|
||||
if (bg) style.bg = bg;
|
||||
if (decorations.includes("bold")) style.bold = true;
|
||||
if (decorations.includes("dim")) style.dim = true;
|
||||
if (decorations.includes("italic")) style.italic = true;
|
||||
if (decorations.includes("underline")) style.underline = true;
|
||||
if (decorations.includes("strikethrough")) style.strike = true;
|
||||
return style;
|
||||
}
|
||||
|
||||
export interface ConsoleModelOptions {
|
||||
maxLines?: number;
|
||||
/** Cycle buffer: total characters kept (Settings › Console); unlimited when absent. */
|
||||
@@ -157,7 +38,7 @@ export class ConsoleModel {
|
||||
private nextId = 1;
|
||||
private open: ConsoleLine | null = null;
|
||||
private pendingCR = false;
|
||||
private readonly parsers = { stdout: new StreamParser(), stderr: new StreamParser(), system: new StreamParser() };
|
||||
private readonly parsers = { stdout: new AnsiStream(), stderr: new AnsiStream(), system: new AnsiStream() };
|
||||
private readonly maxLines: number;
|
||||
private maxChars: number | null;
|
||||
/** Characters currently buffered (line text + one per line break). */
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
|
||||
const scripts: string[][] = [];
|
||||
vi.mock("@/platform/ipc", async (orig) => {
|
||||
const real = await orig<typeof import("@/platform/ipc")>();
|
||||
return {
|
||||
...real,
|
||||
commands: {
|
||||
...real.commands,
|
||||
runGradleJvmArgsScript: (jvmArgs: string[]) => {
|
||||
scripts.push(jvmArgs);
|
||||
return Promise.resolve({ status: "ok", data: "/tmp/openidea-gradle/jvm-args-1.init.gradle" });
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const { parseJavaArgs, joinJavaArgs } = await import("@/platform/javaLaunch");
|
||||
const { parseArgs } = await import("./configs");
|
||||
const { jdwpLaunch } = await import("./javaDebug");
|
||||
const { applicationType, gradleJvmArgs, joinPropertyArgs, springBootType } = await import("./jvmTypes");
|
||||
const { formParams, newConfigOfType, registerBuiltinTypes, typeFor, withParams } = await import("./types");
|
||||
|
||||
const REPORTER_VM = "-Ddemo.flag=on --add-opens java.base/java.lang=ALL-UNNAMED";
|
||||
|
||||
const cfg = (over: Partial<RunConfig>): RunConfig => ({
|
||||
id: "c",
|
||||
name: "c",
|
||||
kind: "spring-boot",
|
||||
command: "java",
|
||||
args: [],
|
||||
cwd: null,
|
||||
env: {},
|
||||
detected: false,
|
||||
isTest: false,
|
||||
debugAdapter: "java-debug",
|
||||
...over,
|
||||
});
|
||||
|
||||
let dispose: () => void;
|
||||
beforeEach(() => {
|
||||
dispose = registerBuiltinTypes();
|
||||
scripts.length = 0;
|
||||
});
|
||||
afterEach(() => dispose());
|
||||
|
||||
describe("Application / Spring Boot command line", () => {
|
||||
it.each([
|
||||
["application", applicationType],
|
||||
["spring-boot", springBootType],
|
||||
] as const)("%s puts VM options before the main class and program arguments after it", (_, type) => {
|
||||
const line = type.commandLine({
|
||||
mainClass: "com.example.Application",
|
||||
vmOptions: REPORTER_VM,
|
||||
programArgs: "--server.port=8081 'two words'",
|
||||
classpath: "${classpath}",
|
||||
});
|
||||
expect(line).toEqual({
|
||||
command: "java",
|
||||
args: [
|
||||
"-Ddemo.flag=on",
|
||||
"--add-opens",
|
||||
"java.base/java.lang=ALL-UNNAMED",
|
||||
"-cp",
|
||||
"${classpath}",
|
||||
"com.example.Application",
|
||||
"--server.port=8081",
|
||||
"two words",
|
||||
],
|
||||
});
|
||||
const parsed = parseJavaArgs(line!.args);
|
||||
expect(parsed.vmArgs).toEqual(["-Ddemo.flag=on", "--add-opens", "java.base/java.lang=ALL-UNNAMED"]);
|
||||
expect(parsed.mainClass).toBe("com.example.Application");
|
||||
expect(parsed.programArgs).toEqual(["--server.port=8081", "two words"]);
|
||||
});
|
||||
|
||||
it("reads VM options over several lines and with quoted spaces", () => {
|
||||
const line = applicationType.commandLine({
|
||||
mainClass: "a.Main",
|
||||
vmOptions: '-Xmx1g\n-Dapp.name="My App"\n -Dempty=""',
|
||||
});
|
||||
expect(line!.args.slice(0, 3)).toEqual(["-Xmx1g", "-Dapp.name=My App", "-Dempty="]);
|
||||
expect(joinJavaArgs(parseJavaArgs(line!.args).vmArgs)).toBe('-Xmx1g "-Dapp.name=My App" -Dempty=');
|
||||
});
|
||||
|
||||
it("keeps Windows paths as typed on Windows", () => {
|
||||
expect(parseArgs(String.raw`-javaagent:C:\tools\agent.jar "-Dlog=C:\Program Files\x.log"`, true)).toEqual([
|
||||
String.raw`-javaagent:C:\tools\agent.jar`,
|
||||
String.raw`-Dlog=C:\Program Files\x.log`,
|
||||
]);
|
||||
expect(parseArgs(String.raw`-Dq=\"x\" "a \"b\""`, true)).toEqual(['-Dq="x"', 'a "b"']);
|
||||
// Elsewhere a backslash still escapes.
|
||||
expect(parseArgs(String.raw`a\ b`)).toEqual(["a b"]);
|
||||
});
|
||||
|
||||
it("passes Spring Boot's active profiles before the program arguments", () => {
|
||||
const line = springBootType.commandLine({ mainClass: "a.App", activeProfiles: "dev,local", programArgs: "--x" });
|
||||
expect(line!.args).toEqual(["-cp", "${classpath}", "a.App", "--spring.profiles.active=dev,local", "--x"]);
|
||||
// Application has no profiles field.
|
||||
expect(applicationType.commandLine({ mainClass: "a.App", activeProfiles: "dev" })!.args).toEqual([
|
||||
"-cp",
|
||||
"${classpath}",
|
||||
"a.App",
|
||||
]);
|
||||
});
|
||||
|
||||
it("uses the test classpath when chosen", () => {
|
||||
expect(applicationType.commandLine({ mainClass: "a.T", classpath: "${testClasspath}" })!.args).toEqual([
|
||||
"-cp",
|
||||
"${testClasspath}",
|
||||
"a.T",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("configurations saved or detected as a raw command line", () => {
|
||||
it("opens a detected Spring Boot configuration in the form", () => {
|
||||
const detected = cfg({ args: ["-cp", "${classpath}", "com.example.DemoApplication"], detected: true });
|
||||
expect(formParams(detected)).toEqual({
|
||||
mainClass: "com.example.DemoApplication",
|
||||
vmOptions: "",
|
||||
programArgs: "",
|
||||
classpath: "${classpath}",
|
||||
});
|
||||
});
|
||||
|
||||
it("splits an older configuration's arguments into VM options, main class, profiles and program arguments", () => {
|
||||
const old = cfg({
|
||||
args: ["-Xmx1g", "-Dname=a b", "-cp", "${classpath}", "a.App", "--spring.profiles.active=dev", "x y"],
|
||||
});
|
||||
const params = formParams(old);
|
||||
expect(params).toEqual({
|
||||
mainClass: "a.App",
|
||||
vmOptions: "-Xmx1g '-Dname=a b'",
|
||||
programArgs: "'x y'",
|
||||
classpath: "${classpath}",
|
||||
activeProfiles: "dev",
|
||||
});
|
||||
// Editing VM options keeps the rest of the command line.
|
||||
const next = withParams(old, { ...params!, vmOptions: REPORTER_VM });
|
||||
expect(next.args).toEqual([
|
||||
"-Ddemo.flag=on",
|
||||
"--add-opens",
|
||||
"java.base/java.lang=ALL-UNNAMED",
|
||||
"-cp",
|
||||
"${classpath}",
|
||||
"a.App",
|
||||
"--spring.profiles.active=dev",
|
||||
"x y",
|
||||
]);
|
||||
expect(next.params).toMatchObject({ vmOptions: REPORTER_VM });
|
||||
});
|
||||
|
||||
it("keeps an explicit classpath and edits other command lines as a command", () => {
|
||||
expect(formParams(cfg({ kind: "application", args: ["-cp", "lib/*", "a.Main"] }))).toMatchObject({
|
||||
classpath: "lib/*",
|
||||
});
|
||||
expect(formParams(cfg({ command: "./run.sh", args: ["a.Main"] }))).toBeNull();
|
||||
expect(formParams(cfg({ args: ["a.Main"] }))).toBeNull();
|
||||
});
|
||||
|
||||
it("prefers the stored params", () => {
|
||||
const c = cfg({
|
||||
params: { mainClass: "a.App", vmOptions: "-Xss2m" },
|
||||
args: ["-Xss2m", "-cp", "${classpath}", "a.App"],
|
||||
});
|
||||
expect(formParams(c)).toEqual({ mainClass: "a.App", vmOptions: "-Xss2m" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("templates", () => {
|
||||
it("applies the template's VM options to a new configuration", () => {
|
||||
const template = cfg({ id: "template:spring-boot", params: { classpath: "${classpath}", vmOptions: "-Xmx512m" } });
|
||||
const c = newConfigOfType(springBootType, [], template);
|
||||
expect(c.kind).toBe("spring-boot");
|
||||
expect(c.debugAdapter).toBe("java-debug");
|
||||
expect(c.params).toMatchObject({ vmOptions: "-Xmx512m" });
|
||||
expect(c.args).toEqual(["-Xmx512m", "-cp", "${classpath}"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Maven / Gradle: VM options of the forked JVM", () => {
|
||||
const maven = () => typeFor("maven")!;
|
||||
const gradle = () => typeFor("gradle")!;
|
||||
|
||||
it("passes spring-boot:run's VM options and profiles to the application, not to Maven", () => {
|
||||
const line = maven().commandLine({
|
||||
tasks: "spring-boot:run",
|
||||
vmOptions: REPORTER_VM + " '-Dname=a b'",
|
||||
activeProfiles: "dev",
|
||||
});
|
||||
expect(line!.args).toEqual([
|
||||
"spring-boot:run",
|
||||
`-Dspring-boot.run.jvmArguments=-Ddemo.flag=on --add-opens java.base/java.lang=ALL-UNNAMED "-Dname=a b"`,
|
||||
"-Dspring-boot.run.profiles=dev",
|
||||
]);
|
||||
// Debugging adds the JDWP agent to the same property.
|
||||
const debug = jdwpLaunch(cfg({ kind: "maven", command: "mvn", args: line!.args }));
|
||||
expect(debug!.args[1]).toMatch(/^-Dspring-boot\.run\.jvmArguments=-Ddemo\.flag=on .* -agentlib:jdwp=/);
|
||||
});
|
||||
|
||||
it("passes test goals' VM options to Surefire and nothing for other goals", () => {
|
||||
expect(maven().commandLine({ tasks: "test", vmOptions: "-Xmx1g" })!.args).toEqual(["test", "-DargLine=-Xmx1g"]);
|
||||
expect(maven().commandLine({ tasks: "package", vmOptions: "-Xmx1g" })!.args).toEqual(["package"]);
|
||||
const vm = maven().fields.find((f) => f.key === "vmOptions")!;
|
||||
expect(vm.visible!({ tasks: "clean spring-boot:run" })).toBe(true);
|
||||
expect(vm.visible!({ tasks: "package" })).toBe(false);
|
||||
});
|
||||
|
||||
it("quotes property values the plugins split", () => {
|
||||
expect(joinPropertyArgs(["-Xmx1g", "-Dp=C:\\Program Files\\x", 'say "hi"', ""])).toBe(
|
||||
`-Xmx1g "-Dp=C:\\Program Files\\x" 'say "hi"' ""`,
|
||||
);
|
||||
});
|
||||
|
||||
it("hands Gradle's VM options to an init script for the forked JVMs", async () => {
|
||||
const params = { tasks: "bootRun", vmOptions: REPORTER_VM, activeProfiles: "dev", wrapper: "true" };
|
||||
expect(gradleJvmArgs(params)).toEqual([
|
||||
"-Ddemo.flag=on",
|
||||
"--add-opens",
|
||||
"java.base/java.lang=ALL-UNNAMED",
|
||||
"-Dspring.profiles.active=dev",
|
||||
]);
|
||||
expect(gradleJvmArgs({ tasks: "build", vmOptions: "-Xmx1g" })).toEqual([]);
|
||||
const c = withParams(cfg({ kind: "gradle" }), params);
|
||||
// Gradle's own command line is unchanged.
|
||||
expect(c.args).toEqual(["bootRun"]);
|
||||
const launched = await gradle().prepareLaunch!(c);
|
||||
expect(scripts).toEqual([gradleJvmArgs(params)]);
|
||||
expect(launched.args).toEqual(["--init-script", "/tmp/openidea-gradle/jvm-args-1.init.gradle", "bootRun"]);
|
||||
// Debugging keeps them: `--debug-jvm` is added before the launch is prepared.
|
||||
const debug = await gradle().prepareLaunch!(jdwpLaunch(c)!);
|
||||
expect(debug.args).toEqual([
|
||||
"--init-script",
|
||||
"/tmp/openidea-gradle/jvm-args-1.init.gradle",
|
||||
"bootRun",
|
||||
"--debug-jvm",
|
||||
]);
|
||||
});
|
||||
|
||||
it("leaves Gradle configurations without VM options alone", async () => {
|
||||
const c = withParams(cfg({ kind: "gradle" }), { tasks: "bootRun" });
|
||||
expect(await gradle().prepareLaunch!(c)).toBe(c);
|
||||
expect(scripts).toEqual([]);
|
||||
const remote = withParams(cfg({ kind: "gradle", target: "ssh-1" }), { tasks: "bootRun", vmOptions: "-Xmx1g" });
|
||||
await expect(gradle().prepareLaunch!(remote)).rejects.toThrow(/run targets/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,206 @@
|
||||
/**
|
||||
* JVM run configuration types: Application and Spring Boot
|
||||
* (`java [VM options] -cp ${classpath} <main class> [program arguments]`), and the
|
||||
* VM options Maven / Gradle configurations hand to the JVM the build forks
|
||||
* (`spring-boot:run`, tests, `bootRun`) rather than to the build tool's own JVM.
|
||||
*/
|
||||
import { call, commands, type RunConfig } from "@/platform/ipc";
|
||||
import { CLASSPATH, parseJavaArgs, TEST_CLASSPATH } from "@/platform/javaLaunch";
|
||||
import type { RunConfigTypeContribution, RunConfigTypeField } from "@/workbench/contributions";
|
||||
import { formatArgs, parseArgs } from "./configs";
|
||||
|
||||
export const isWindows = () => typeof navigator !== "undefined" && /win/i.test(navigator.platform);
|
||||
|
||||
/** VM options / program arguments as typed; on Windows a backslash is a path separator. */
|
||||
export const splitJvmArgs = (text: string | undefined, windows = isWindows()) => parseArgs(text ?? "", windows);
|
||||
|
||||
export const PROFILES_ARG = "--spring.profiles.active=";
|
||||
|
||||
const VM_OPTIONS_PLACEHOLDER = "e.g. -Xmx1g -Dkey=value --add-opens java.base/java.lang=ALL-UNNAMED";
|
||||
|
||||
const vmOptionsField = (hint?: string, visible?: RunConfigTypeField["visible"]): RunConfigTypeField => ({
|
||||
key: "vmOptions",
|
||||
label: "VM options",
|
||||
control: "textarea",
|
||||
rows: 2,
|
||||
mono: true,
|
||||
placeholder: VM_OPTIONS_PLACEHOLDER,
|
||||
...(hint ? { hint } : {}),
|
||||
...(visible ? { visible } : {}),
|
||||
});
|
||||
|
||||
const profilesField = (hint: string, visible?: RunConfigTypeField["visible"]): RunConfigTypeField => ({
|
||||
key: "activeProfiles",
|
||||
label: "Active profiles",
|
||||
mono: true,
|
||||
placeholder: "e.g. dev,local",
|
||||
hint,
|
||||
...(visible ? { visible } : {}),
|
||||
});
|
||||
|
||||
const isJava = (command: string) => /^java(\.exe)?$/i.test(command.replace(/\\/g, "/").split("/").pop() ?? "");
|
||||
|
||||
/** Main classes of the JVM configurations, offered while typing. */
|
||||
function mainClasses(configs: readonly RunConfig[]): string[] {
|
||||
const out = new Set<string>();
|
||||
for (const c of configs) {
|
||||
if (c.kind !== "application" && c.kind !== "spring-boot") continue;
|
||||
const main = c.params?.mainClass || parseJavaArgs(c.args).mainClass;
|
||||
if (main) out.add(main);
|
||||
}
|
||||
return [...out];
|
||||
}
|
||||
|
||||
function jvmApplicationType(spring: boolean): RunConfigTypeContribution {
|
||||
return {
|
||||
id: spring ? "spring-boot" : "application",
|
||||
label: spring ? "Spring Boot" : "Application",
|
||||
icon: spring ? "spring-boot" : "class",
|
||||
description: spring ? "Run a Spring Boot application" : "Run a Java main class",
|
||||
defaults: { classpath: CLASSPATH },
|
||||
debugAdapter: "java-debug",
|
||||
fields: [
|
||||
{
|
||||
key: "mainClass",
|
||||
label: "Main class",
|
||||
mono: true,
|
||||
required: true,
|
||||
placeholder: "e.g. com.example.Application",
|
||||
suggestions: mainClasses,
|
||||
},
|
||||
vmOptionsField(),
|
||||
{ key: "programArgs", label: "Program arguments", mono: true },
|
||||
...(spring ? [profilesField("Comma separated; passed as --spring.profiles.active")] : []),
|
||||
{
|
||||
key: "classpath",
|
||||
label: "Classpath",
|
||||
control: "select",
|
||||
options: [
|
||||
{ value: CLASSPATH, label: "Runtime classpath of the module" },
|
||||
{ value: TEST_CLASSPATH, label: "Test classpath of the module" },
|
||||
],
|
||||
},
|
||||
],
|
||||
commandLine(p) {
|
||||
const main = p.mainClass?.trim() ?? "";
|
||||
const profiles = spring ? (p.activeProfiles?.trim() ?? "") : "";
|
||||
return {
|
||||
command: "java",
|
||||
args: [
|
||||
...splitJvmArgs(p.vmOptions),
|
||||
"-cp",
|
||||
p.classpath || CLASSPATH,
|
||||
...(main ? [main] : []),
|
||||
...(profiles ? [PROFILES_ARG + profiles] : []),
|
||||
...splitJvmArgs(p.programArgs),
|
||||
],
|
||||
};
|
||||
},
|
||||
// Configurations detected or saved before these fields existed: `java [vm] -cp <cp> Main [args]`.
|
||||
paramsFrom(c) {
|
||||
if (!isJava(c.command)) return null;
|
||||
const parsed = parseJavaArgs(c.args);
|
||||
const classpath =
|
||||
parsed.classpath === "runtime"
|
||||
? CLASSPATH
|
||||
: parsed.classpath === "test"
|
||||
? TEST_CLASSPATH
|
||||
: parsed.explicitClasspath;
|
||||
if (!parsed.mainClass || classpath === null) return null;
|
||||
let rest = parsed.programArgs;
|
||||
let activeProfiles = "";
|
||||
if (spring && rest[0]?.startsWith(PROFILES_ARG)) {
|
||||
activeProfiles = rest[0].slice(PROFILES_ARG.length);
|
||||
rest = rest.slice(1);
|
||||
}
|
||||
return {
|
||||
mainClass: parsed.mainClass,
|
||||
vmOptions: formatArgs(parsed.vmArgs),
|
||||
programArgs: formatArgs(rest),
|
||||
classpath,
|
||||
...(activeProfiles ? { activeProfiles } : {}),
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export const applicationType = jvmApplicationType(false);
|
||||
export const springBootType = jvmApplicationType(true);
|
||||
|
||||
/**
|
||||
* One value for a Maven property holding JVM arguments (`spring-boot.run.jvmArguments`,
|
||||
* `argLine`): the plugins split it on whitespace, honouring "…" and '…'.
|
||||
*/
|
||||
export function joinPropertyArgs(args: readonly string[]): string {
|
||||
return args
|
||||
.map((a) => {
|
||||
if (a && !/[\s"']/.test(a)) return a;
|
||||
return a.includes('"') ? `'${a}'` : `"${a}"`;
|
||||
})
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
const words = (tasks: string | undefined) => (tasks ?? "").split(/\s+/).filter(Boolean);
|
||||
|
||||
const isSpringBootRun = (goal: string) =>
|
||||
goal === "spring-boot:run" || /:spring-boot-maven-plugin:[^:]*:run$/.test(goal);
|
||||
const isMavenTestGoal = (goal: string) =>
|
||||
/^(test|verify|integration-test|surefire:test|failsafe:integration-test)$/.test(goal);
|
||||
const isBootRun = (task: string) => /(^|:)bootRun$/.test(task);
|
||||
const isGradleJvmTask = (task: string) => /(^|:)(test|bootRun|run|integrationTest|check)$/.test(task);
|
||||
|
||||
/** What a build tool configuration does with VM options and Spring Boot profiles. */
|
||||
export interface ForkedJvm {
|
||||
fields: readonly RunConfigTypeField[];
|
||||
/** Arguments appended to the build tool's command line. */
|
||||
args(params: Readonly<Record<string, string>>): string[];
|
||||
prepareLaunch?(config: RunConfig): Promise<RunConfig>;
|
||||
}
|
||||
|
||||
export const mavenForkedJvm: ForkedJvm = {
|
||||
fields: [
|
||||
vmOptionsField("Passed to the JVM that spring-boot:run or the tests start, not to Maven", (p) =>
|
||||
words(p.tasks).some((g) => isSpringBootRun(g) || isMavenTestGoal(g)),
|
||||
),
|
||||
profilesField("Comma separated; passed as -Dspring-boot.run.profiles", (p) => words(p.tasks).some(isSpringBootRun)),
|
||||
],
|
||||
args(p) {
|
||||
const goals = words(p.tasks);
|
||||
const vm = splitJvmArgs(p.vmOptions);
|
||||
const out: string[] = [];
|
||||
if (goals.some(isSpringBootRun)) {
|
||||
if (vm.length) out.push(`-Dspring-boot.run.jvmArguments=${joinPropertyArgs(vm)}`);
|
||||
const profiles = p.activeProfiles?.trim();
|
||||
if (profiles) out.push(`-Dspring-boot.run.profiles=${profiles}`);
|
||||
} else if (vm.length && goals.some(isMavenTestGoal)) {
|
||||
out.push(`-DargLine=${joinPropertyArgs(vm)}`);
|
||||
}
|
||||
return out;
|
||||
},
|
||||
};
|
||||
|
||||
/** VM options (and profiles, as `-Dspring.profiles.active`) of a Gradle configuration's forked JVMs. */
|
||||
export function gradleJvmArgs(p: Readonly<Record<string, string>>): string[] {
|
||||
const tasks = words(p.tasks);
|
||||
if (!tasks.some(isGradleJvmTask)) return [];
|
||||
const profiles = tasks.some(isBootRun) ? p.activeProfiles?.trim() : "";
|
||||
return [...splitJvmArgs(p.vmOptions), ...(profiles ? [`-Dspring.profiles.active=${profiles}`] : [])];
|
||||
}
|
||||
|
||||
export const gradleForkedJvm: ForkedJvm = {
|
||||
fields: [
|
||||
vmOptionsField("Passed to the JVMs the tasks start (bootRun, run, test), not to Gradle", (p) =>
|
||||
words(p.tasks).some(isGradleJvmTask),
|
||||
),
|
||||
profilesField("Comma separated; passed as -Dspring.profiles.active", (p) => words(p.tasks).some(isBootRun)),
|
||||
],
|
||||
// Gradle has no command-line switch for them: an init script adds them to the JavaExec / Test tasks.
|
||||
args: () => [],
|
||||
async prepareLaunch(config) {
|
||||
const jvmArgs = gradleJvmArgs(config.params ?? {});
|
||||
if (!jvmArgs.length) return config;
|
||||
if (config.target) throw new Error("VM options of Gradle configurations are not applied on run targets");
|
||||
const script = await call(commands.runGradleJvmArgsScript(jvmArgs));
|
||||
return { ...config, args: ["--init-script", script, ...config.args] };
|
||||
},
|
||||
};
|
||||
@@ -89,8 +89,9 @@ const PATTERNS: Pattern[] = [
|
||||
},
|
||||
// Generic `path:line` (Go `file.go:12`, Rust `--> src/main.rs:10`, gcc, eslint…) and `path(line,col)`.
|
||||
{
|
||||
re: new RegExp(String.raw`(?<![\w/.~\-])(${PATH})(?::(\d+)(?::(\d+))?|\((\d+)(?:,(\d+))?\))`, "dg"),
|
||||
re: new RegExp(String.raw`(${PATH})(?::(\d+)(?::(\d+))?|\((\d+)(?:,(\d+))?\))`, "dg"),
|
||||
build: (m) => {
|
||||
if (m.index! > 0 && /[\w/.~-]/.test(m.input![m.index! - 1]!)) return null;
|
||||
const [start, end] = [m.index!, m.index! + m[0].length];
|
||||
return {
|
||||
kind: "file",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Built-in run configuration types (Shell Script, Program, npm, Gradle, Maven,
|
||||
* Compound) and the helpers that turn a type's params into the launched
|
||||
* Application, Spring Boot, Compound) and the helpers that turn a type's params into the launched
|
||||
* command line. Other features contribute types with `registerRunConfigType`.
|
||||
*/
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
@@ -11,11 +11,18 @@ import {
|
||||
type RunConfigTypeContribution,
|
||||
} from "@/workbench/contributions";
|
||||
import { formatArgs, parseArgs, uid, uniqueName } from "./configs";
|
||||
import {
|
||||
applicationType,
|
||||
gradleForkedJvm,
|
||||
isWindows,
|
||||
mavenForkedJvm,
|
||||
springBootType,
|
||||
type ForkedJvm,
|
||||
} from "./jvmTypes";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
export const COMPOUND = "compound";
|
||||
|
||||
const isWindows = () => typeof navigator !== "undefined" && /win/i.test(navigator.platform);
|
||||
const on = (v: string | undefined) => v === "true";
|
||||
const baseName = (p: string) => p.replace(/\\/g, "/").split("/").pop() ?? p;
|
||||
const dirOf = (cwd: string | null | undefined) => cwd ?? "";
|
||||
@@ -213,6 +220,7 @@ function buildToolType(
|
||||
icon: string,
|
||||
tasks: { label: string; description: string },
|
||||
wrapper: { unix: string; windows: string; plain: string; label: string; byDefault: boolean },
|
||||
jvm: ForkedJvm,
|
||||
): RunConfigTypeContribution {
|
||||
return {
|
||||
id,
|
||||
@@ -231,13 +239,15 @@ function buildToolType(
|
||||
suggestions: (configs) => argsOf(configs, id, 0),
|
||||
},
|
||||
{ key: "arguments", label: "Arguments", mono: true },
|
||||
...jvm.fields,
|
||||
{ key: "wrapper", label: wrapper.label, control: "checkbox" },
|
||||
],
|
||||
commandLine: (p) => ({
|
||||
command: wrapperCommand(wrapper.unix, wrapper.windows, wrapper.plain, on(p.wrapper)),
|
||||
args: [...parseArgs(p.tasks ?? ""), ...parseArgs(p.arguments ?? "")],
|
||||
args: [...parseArgs(p.tasks ?? ""), ...parseArgs(p.arguments ?? ""), ...jvm.args(p)],
|
||||
cwd: p.projectDir?.trim() || null,
|
||||
}),
|
||||
...(jvm.prepareLaunch ? { prepareLaunch: jvm.prepareLaunch } : {}),
|
||||
paramsFrom(c) {
|
||||
const name = baseName(c.command);
|
||||
const usesWrapper = name === wrapper.unix || name === wrapper.windows;
|
||||
@@ -264,6 +274,7 @@ const gradle = buildToolType(
|
||||
label: "Use the Gradle wrapper",
|
||||
byDefault: true,
|
||||
},
|
||||
gradleForkedJvm,
|
||||
);
|
||||
|
||||
const maven = buildToolType(
|
||||
@@ -278,6 +289,7 @@ const maven = buildToolType(
|
||||
label: "Use the Maven wrapper",
|
||||
byDefault: false,
|
||||
},
|
||||
mavenForkedJvm,
|
||||
);
|
||||
|
||||
const compound: RunConfigTypeContribution = {
|
||||
@@ -296,6 +308,8 @@ export const BUILTIN_TYPES: readonly RunConfigTypeContribution[] = [
|
||||
gradle,
|
||||
maven,
|
||||
godot,
|
||||
applicationType,
|
||||
springBootType,
|
||||
compound,
|
||||
];
|
||||
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import type { FontFamily } from "@/platform/ipc";
|
||||
|
||||
const installed: FontFamily[] = [
|
||||
{ name: "Andale Mono", monospaced: true },
|
||||
{ name: "Arial", monospaced: false },
|
||||
{ name: "Courier New", monospaced: true },
|
||||
{ name: "Georgia", monospaced: false },
|
||||
{ name: "Helvetica Neue", monospaced: false },
|
||||
{ name: "Maple Mono NF CN", monospaced: true },
|
||||
{ name: "Menlo", monospaced: true },
|
||||
{ name: "Monaco", monospaced: true },
|
||||
{ name: "PingFang SC", monospaced: false },
|
||||
{ name: "Sarasa Term SC", monospaced: true },
|
||||
];
|
||||
const systemFontFamilies = vi.fn(async () => ({ status: "ok" as const, data: installed }));
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return { ...real, commands: { ...real.commands, systemFontFamilies: () => systemFontFamilies() } };
|
||||
});
|
||||
|
||||
import { resetSystemFontsForTests } from "@/platform/systemFonts";
|
||||
import { FontSelect } from "../components/FontSelect";
|
||||
|
||||
afterEach(() => resetSystemFontsForTests());
|
||||
|
||||
async function open(ui: React.ReactElement, label: string) {
|
||||
render(ui);
|
||||
await act(async () => {});
|
||||
fireEvent.click(screen.getByRole("button", { name: label }));
|
||||
return screen.getAllByRole("option").map((o) => o.textContent);
|
||||
}
|
||||
|
||||
describe("FontSelect", () => {
|
||||
it("lists every installed family plus the bundled one, sorted", async () => {
|
||||
const names = await open(<FontSelect value="Menlo" onChange={() => {}} aria-label="Font" />, "Font");
|
||||
expect(names).toEqual([
|
||||
"Andale Mono",
|
||||
"Arial",
|
||||
"Courier New",
|
||||
"Georgia",
|
||||
"Helvetica Neue",
|
||||
"JetBrains Mono",
|
||||
"Maple Mono NF CN",
|
||||
"Menlo",
|
||||
"Monaco",
|
||||
"PingFang SC",
|
||||
"Sarasa Term SC",
|
||||
]);
|
||||
});
|
||||
|
||||
it("filters to monospaced families when asked, keeping the current one", async () => {
|
||||
const names = await open(
|
||||
<FontSelect value="PingFang SC" onChange={() => {}} monospacedOnly aria-label="Font" />,
|
||||
"Font",
|
||||
);
|
||||
expect(names).toEqual([
|
||||
"Andale Mono",
|
||||
"Courier New",
|
||||
"JetBrains Mono",
|
||||
"Maple Mono NF CN",
|
||||
"Menlo",
|
||||
"Monaco",
|
||||
"PingFang SC",
|
||||
"Sarasa Term SC",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps a current family that isn't installed here", async () => {
|
||||
render(<FontSelect value="Fira Code" onChange={() => {}} monospacedOnly aria-label="Font" />);
|
||||
await act(async () => {});
|
||||
expect(screen.getByRole("button", { name: "Font" })).toHaveTextContent("Fira Code");
|
||||
});
|
||||
|
||||
it("offers None first for fallback fonts, without the bundled family", async () => {
|
||||
const names = await open(
|
||||
<FontSelect value="" onChange={() => {}} none aria-label="Fallback font" />,
|
||||
"Fallback font",
|
||||
);
|
||||
expect(names[0]).toBe("None");
|
||||
expect(names).not.toContain("JetBrains Mono");
|
||||
expect(names).toHaveLength(installed.length + 1);
|
||||
});
|
||||
|
||||
it("jumps to the family typed as a prefix", async () => {
|
||||
const onChange = vi.fn();
|
||||
await open(<FontSelect value="Arial" onChange={onChange} aria-label="Font" />, "Font");
|
||||
const popup = document.querySelector("[data-autofocus]")!;
|
||||
fireEvent.keyDown(popup, { key: "m", timeStamp: 1000 });
|
||||
fireEvent.keyDown(popup, { key: "e", timeStamp: 1100 });
|
||||
fireEvent.keyDown(popup, { key: "Enter", timeStamp: 1200 });
|
||||
expect(onChange).toHaveBeenCalledWith("Menlo");
|
||||
});
|
||||
|
||||
it("reads the font list once", async () => {
|
||||
systemFontFamilies.mockClear();
|
||||
render(
|
||||
<>
|
||||
<FontSelect value="Menlo" onChange={() => {}} aria-label="A" />
|
||||
<FontSelect value="Menlo" onChange={() => {}} aria-label="B" />
|
||||
</>,
|
||||
);
|
||||
await act(async () => {});
|
||||
expect(systemFontFamilies).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,155 @@
|
||||
import { act, render, screen, waitFor, cleanup } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { executeAction, registerAction } from "@/platform/actions";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { useProject } from "@/platform/project";
|
||||
import type { ProjectInfo, Sdk } from "@/bindings";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
notify: vi.fn(),
|
||||
files: vi.fn(),
|
||||
effective: vi.fn(),
|
||||
detect: vi.fn(),
|
||||
set: vi.fn(),
|
||||
component: null as React.ComponentType | null,
|
||||
}));
|
||||
vi.mock("@/platform/ipc", () => ({
|
||||
call: (p: unknown) => p,
|
||||
isTauri: () => true,
|
||||
onIdeEvent: () => () => {},
|
||||
commands: {
|
||||
findFiles: mocks.files,
|
||||
sdkPythonEffective: mocks.effective,
|
||||
sdkDetect: mocks.detect,
|
||||
settingsSet: mocks.set,
|
||||
},
|
||||
}));
|
||||
vi.mock("@/workbench/contributions", () => ({
|
||||
notifications: () => ({ notify: mocks.notify }),
|
||||
registerStatusItem: (item: { component: React.ComponentType }) => {
|
||||
mocks.component = item.component;
|
||||
return () => {};
|
||||
},
|
||||
}));
|
||||
import { activatePythonStatus, interpreterChoices, isPythonPath } from "../languages/PythonStatus";
|
||||
|
||||
let dispose: () => void;
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.files.mockResolvedValue([]);
|
||||
mocks.effective.mockResolvedValue(null);
|
||||
mocks.detect.mockResolvedValue([]);
|
||||
mocks.set.mockResolvedValue({ languages: { python: { interpreter: "/new/python" } } });
|
||||
useProject.setState({ project: { root: "/project" } as ProjectInfo, settings: null });
|
||||
setContext("projectOpen", true);
|
||||
dispose = activatePythonStatus();
|
||||
});
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
dispose();
|
||||
});
|
||||
|
||||
const mount = () => {
|
||||
const Component = mocks.component!;
|
||||
return render(<Component />);
|
||||
};
|
||||
|
||||
describe("Python interpreter status", () => {
|
||||
it.each([
|
||||
"src/main.py",
|
||||
"types/lib.pyi",
|
||||
"C:\\app\\main.pyw",
|
||||
"pyproject.toml",
|
||||
"requirements-dev.txt",
|
||||
"SConstruct",
|
||||
])("recognizes %s", (path) => expect(isPythonPath(path)).toBe(true));
|
||||
it.each(["main.ts", "python.md", "pyproject.toml.bak", "copy.py.json"])("rejects %s", (path) =>
|
||||
expect(isPythonPath(path)).toBe(false),
|
||||
);
|
||||
it("keeps custom interpreters and deduplicates detected paths", () => {
|
||||
const sdk = { path: "/python", name: "Python 3.12" } as Sdk;
|
||||
expect(interpreterChoices([sdk, sdk], "/custom")).toEqual([sdk, { path: "/custom", name: "/custom" }]);
|
||||
});
|
||||
it("hides for non-Python projects without probing SDKs", async () => {
|
||||
mount();
|
||||
await waitFor(() => expect(mocks.files).toHaveBeenCalled());
|
||||
expect(screen.queryByRole("button")).toBeNull();
|
||||
expect(mocks.detect).not.toHaveBeenCalled();
|
||||
});
|
||||
it("shows a warning for Python files without an interpreter", async () => {
|
||||
mocks.files.mockResolvedValue([{ path: "/project/src/main.py" }]);
|
||||
mount();
|
||||
expect(await screen.findByText("No interpreter")).toBeTruthy();
|
||||
const button = screen.getByRole("button", { name: "Python Interpreter: No interpreter" });
|
||||
expect(button.querySelector("svg")).toBeTruthy();
|
||||
});
|
||||
it("shows the paths of interpreters that share a name", async () => {
|
||||
mocks.files.mockResolvedValue([{ path: "/project/main.py" }]);
|
||||
mocks.effective.mockResolvedValue("/usr/local/bin/python3.11");
|
||||
mocks.detect.mockResolvedValue([
|
||||
{ path: "/usr/local/bin/python3.11", name: "Python 3.11" },
|
||||
{ path: "/opt/homebrew/bin/python3.11", name: "Python 3.11" },
|
||||
{ path: "/venv/bin/python", name: "Python 3.12 (.venv)" },
|
||||
]);
|
||||
mount();
|
||||
await screen.findByRole("button", { name: "Python Interpreter: Python 3.11" });
|
||||
await act(() => executeAction("python.interpreterPopup"));
|
||||
expect(await screen.findByText("/opt/homebrew/bin/python3.11")).toBeTruthy();
|
||||
expect(screen.getByText("/usr/local/bin/python3.11")).toBeTruthy();
|
||||
expect(screen.queryByText("/venv/bin/python")).toBeNull();
|
||||
});
|
||||
it("opens the Python page when the widget is hidden", async () => {
|
||||
const run = vi.fn();
|
||||
const off = registerAction({ id: "file.settings", title: "Settings…", run });
|
||||
mount();
|
||||
await waitFor(() => expect(mocks.files).toHaveBeenCalled());
|
||||
await executeAction("python.interpreterPopup");
|
||||
expect(run.mock.calls.map(([ctx]) => ctx.arg)).toEqual(["python.interpreter"]);
|
||||
off();
|
||||
});
|
||||
it("shows the effective SDK name and hides old state on project change", async () => {
|
||||
mocks.files.mockResolvedValue([{ path: "/project/pyproject.toml" }]);
|
||||
mocks.effective.mockResolvedValue("/venv/python");
|
||||
mocks.detect.mockResolvedValue([{ path: "/venv/python", name: "Python 3.12 (.venv)" }]);
|
||||
mount();
|
||||
expect(await screen.findByText("Python 3.12 (.venv)")).toBeTruthy();
|
||||
mocks.files.mockResolvedValue([]);
|
||||
act(() => useProject.setState({ project: { root: "/other" } as ProjectInfo }));
|
||||
expect(screen.queryByRole("button")).toBeNull();
|
||||
});
|
||||
it("writes the project setting through the same backend path as Settings", async () => {
|
||||
await executeAction("python.selectInterpreter", "/new/python");
|
||||
expect(mocks.set).toHaveBeenCalledWith("project", "languages.python.interpreter", '"/new/python"');
|
||||
expect(useProject.getState().settings?.languages?.python?.interpreter).toBe("/new/python");
|
||||
});
|
||||
it("reports write failures without changing the selected interpreter", async () => {
|
||||
mocks.set.mockRejectedValueOnce(new Error("write failed"));
|
||||
await executeAction("python.selectInterpreter", "/new/python");
|
||||
expect(mocks.notify).toHaveBeenCalledWith(expect.objectContaining({ level: "error" }));
|
||||
expect(useProject.getState().settings).toBeNull();
|
||||
});
|
||||
it("discards discovery completing after a project switch", async () => {
|
||||
mocks.files.mockResolvedValue([{ path: "/project/main.py" }]);
|
||||
let finish!: (sdks: Sdk[]) => void;
|
||||
mocks.detect.mockReturnValueOnce(
|
||||
new Promise<Sdk[]>((resolve) => {
|
||||
finish = resolve;
|
||||
}),
|
||||
);
|
||||
mocks.effective.mockResolvedValue("/old/python");
|
||||
mount();
|
||||
await waitFor(() => expect(mocks.detect).toHaveBeenCalled());
|
||||
mocks.files.mockResolvedValue([]);
|
||||
act(() => useProject.setState({ project: { root: "/other" } as ProjectInfo }));
|
||||
await act(async () => finish([{ path: "/old/python", name: "Python 3.12" } as Sdk]));
|
||||
expect(screen.queryByRole("button")).toBeNull();
|
||||
});
|
||||
it("opens the Python page for both settings entries", async () => {
|
||||
const run = vi.fn();
|
||||
const off = registerAction({ id: "file.settings", title: "Settings…", run });
|
||||
await executeAction("python.addInterpreter");
|
||||
await executeAction("python.interpreterSettings");
|
||||
expect(run.mock.calls.map(([ctx]) => ctx.arg)).toEqual(["python.interpreter", "python.interpreter"]);
|
||||
off();
|
||||
});
|
||||
});
|
||||
@@ -6,6 +6,7 @@
|
||||
* pressed only" and "Save files if the IDE is idle".
|
||||
*/
|
||||
import { executeAction, type Action } from "@/platform/actions";
|
||||
import { uiFontFamily } from "@/platform/fonts";
|
||||
import { call, commands, isTauri } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { setDragRequiresAlt } from "@/ui";
|
||||
@@ -32,8 +33,7 @@ export function applyAppearanceOptions(s: ValidSettings, root: HTMLElement = doc
|
||||
if (size === DEFAULT_SETTINGS.appearance.uiFontSize) root.style.removeProperty(name);
|
||||
else root.style.setProperty(name, `${size + delta}px`);
|
||||
}
|
||||
if (a.useCustomFont)
|
||||
root.style.setProperty("--font-ui", `"${a.uiFontFamily.replace(/"/g, "")}", system-ui, sans-serif`);
|
||||
if (a.useCustomFont) root.style.setProperty("--font-ui", uiFontFamily(a.uiFontFamily));
|
||||
else root.style.removeProperty("--font-ui");
|
||||
|
||||
flag(root, "compact", a.compactMode);
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* Font-family pickers over the families installed on this machine. The current
|
||||
* value always stays listed, so a family that isn't installed here (a synced
|
||||
* setting, an uninstalled font) still shows as selected.
|
||||
*/
|
||||
import { useMemo } from "react";
|
||||
import type { SelectOption } from "@/ui";
|
||||
import { BUNDLED_MONO_FAMILY } from "@/platform/fonts";
|
||||
import { fontNames, useSystemFonts } from "@/platform/systemFonts";
|
||||
import { Select } from "./Form";
|
||||
|
||||
const NO_BUNDLED: readonly string[] = [];
|
||||
const MONO_BUNDLED: readonly string[] = [BUNDLED_MONO_FAMILY];
|
||||
|
||||
export interface FontSelectProps {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
/** List only monospaced families (the current value stays). */
|
||||
monospacedOnly?: boolean;
|
||||
/** Offer "None" (empty value) first: fallback fonts. */
|
||||
none?: boolean;
|
||||
/** Families the app bundles, listed even when not installed. Default: the bundled monospace (none for fallbacks). */
|
||||
bundled?: readonly string[];
|
||||
disabled?: boolean;
|
||||
"aria-label": string;
|
||||
}
|
||||
|
||||
export function FontSelect({
|
||||
value,
|
||||
onChange,
|
||||
monospacedOnly,
|
||||
none,
|
||||
bundled = none ? NO_BUNDLED : MONO_BUNDLED,
|
||||
disabled,
|
||||
...aria
|
||||
}: FontSelectProps) {
|
||||
const fonts = useSystemFonts();
|
||||
const options = useMemo<SelectOption[]>(() => {
|
||||
const names = fontNames(fonts, { monospacedOnly, include: [...bundled, value] });
|
||||
const list = names.map((n) => ({ value: n, label: n }));
|
||||
return none ? [{ value: "", label: "None" }, ...list] : list;
|
||||
}, [fonts, monospacedOnly, none, bundled, value]);
|
||||
return (
|
||||
<Select value={value} options={options} onChange={onChange} disabled={disabled} aria-label={aria["aria-label"]} />
|
||||
);
|
||||
}
|
||||
@@ -35,6 +35,7 @@ import { trackRuntimeSettings } from "./runtime";
|
||||
import { installActionProxies, installSettingsHost } from "./window/bridge";
|
||||
import { AssignShortcutOverlay, showAssignShortcut } from "./keymap/AssignShortcut";
|
||||
import { settingsSearchEntries } from "./searchIndex";
|
||||
import { activatePythonStatus } from "./languages/PythonStatus";
|
||||
import { isImeKey } from "@/platform/ime";
|
||||
|
||||
export { settingsWindowParent } from "./window/bridge";
|
||||
@@ -100,6 +101,7 @@ async function showSettings(page?: string, newProjects = false) {
|
||||
export function activate(): () => void {
|
||||
const disposers = [
|
||||
trackRuntimeSettings(),
|
||||
activatePythonStatus(),
|
||||
unloadBuiltinPages,
|
||||
registerOverlay({ id: "settings.dialog", component: LazySettingsDialog }),
|
||||
registerActions(zoomActions()),
|
||||
|
||||
@@ -249,14 +249,14 @@ export function JavaPage() {
|
||||
<Row
|
||||
label="JVM options"
|
||||
htmlFor={id}
|
||||
hint="Passed to the JVM running jdtls (java.jdt.ls.vmargs), e.g. -Xmx2g. A Lombok agent is added automatically: the one installed in Language Servers, else, when the project uses Lombok (its build, an inherited parent POM or Gradle build, or its sources' imports), the newest from the Maven / Gradle caches."
|
||||
hint="Passed to the JVM running jdtls (java.jdt.ls.vmargs), e.g. -Xmx4g. jdtls runs with -XX:+UseParallelGC -XX:GCTimeRatio=4 -XX:AdaptiveSizePolicyWeight=90 -Xmx2G -Xms100m by default; an option set here replaces the default for the same setting, and another collector (e.g. -XX:+UseG1GC) replaces the default collector options. A Lombok agent is added automatically: the one installed in Language Servers, else, when the project uses Lombok (its build, an inherited parent POM or Gradle build, or its sources' imports), the newest from the Maven / Gradle caches."
|
||||
>
|
||||
<Input
|
||||
id={id}
|
||||
mono
|
||||
className={styles.pathInput}
|
||||
value={vmArgs}
|
||||
placeholder="-Xmx2g"
|
||||
placeholder="-Xmx4g"
|
||||
onChange={(e) => setVmArgs(e.target.value)}
|
||||
/>
|
||||
</Row>
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { create } from "zustand";
|
||||
import { executeAction, registerActions } from "@/platform/actions";
|
||||
import { call, commands, isTauri, onIdeEvent } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { notifications, registerStatusItem } from "@/workbench/contributions";
|
||||
import { BarButton, Menu, type MenuItem } from "@/ui";
|
||||
import { Icon } from "@/ui/icons";
|
||||
import { effectivePython, type Sdk } from "./api";
|
||||
import { tildify } from "./components";
|
||||
|
||||
const usePopup = create<{ open: boolean; shown: boolean }>(() => ({ open: false, shown: false }));
|
||||
const close = () => usePopup.setState({ open: false });
|
||||
const markers = [
|
||||
"pyproject.toml",
|
||||
"setup.py",
|
||||
"setup.cfg",
|
||||
"requirements.txt",
|
||||
"Pipfile",
|
||||
"pyrightconfig.json",
|
||||
"ty.toml",
|
||||
"uv.lock",
|
||||
"poetry.lock",
|
||||
"SConstruct",
|
||||
"SConscript",
|
||||
".python-version",
|
||||
];
|
||||
|
||||
export function isPythonPath(path: string): boolean {
|
||||
const name = path.replaceAll("\\", "/").split("/").at(-1)!;
|
||||
return /\.(py|pyi|pyw)$/.test(name) || markers.includes(name) || /^requirements[\w.-]*\.txt$/.test(name);
|
||||
}
|
||||
|
||||
export function interpreterChoices(sdks: Sdk[], current: string | null): { path: string; name: string }[] {
|
||||
const choices = [...new Map(sdks.map((sdk) => [sdk.path, sdk])).values()];
|
||||
if (!current || choices.some((sdk) => sdk.path === current)) return choices;
|
||||
return [...choices, { path: current, name: current }];
|
||||
}
|
||||
|
||||
async function hasPythonFiles(): Promise<boolean> {
|
||||
const matches = await Promise.all(
|
||||
[".py", "requirements", ...markers].map((query) => call(commands.findFiles(query, 10000))),
|
||||
);
|
||||
return matches.some((files) => files.some((file) => isPythonPath(file.path)));
|
||||
}
|
||||
|
||||
function PythonStatus() {
|
||||
const root = useProject((s) => s.project?.root);
|
||||
const configured = useProject((s) => s.settings?.languages?.python?.interpreter ?? "");
|
||||
const open = usePopup((s) => s.open);
|
||||
const anchor = useRef<HTMLButtonElement>(null);
|
||||
const [state, setState] = useState<{
|
||||
root: string;
|
||||
configured: string;
|
||||
visible: boolean;
|
||||
python: string | null;
|
||||
sdks: Sdk[];
|
||||
} | null>(null);
|
||||
useEffect(() => {
|
||||
close();
|
||||
if (!root || !isTauri()) return;
|
||||
let live = true;
|
||||
let sequence = 0;
|
||||
let detected: Promise<Sdk[]> | undefined;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const refresh = async () => {
|
||||
const request = ++sequence;
|
||||
try {
|
||||
const visible = await hasPythonFiles();
|
||||
if (!live || sequence !== request) return;
|
||||
const [python, sdks] =
|
||||
visible || configured
|
||||
? await Promise.all([effectivePython(), (detected ??= call(commands.sdkDetect("python")))])
|
||||
: [null, [] as Sdk[]];
|
||||
if (live && sequence === request) setState({ root, configured, visible, python, sdks });
|
||||
} catch (e) {
|
||||
console.warn("Cannot refresh Python interpreter status", e);
|
||||
}
|
||||
};
|
||||
const schedule = () => {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => void refresh(), 300);
|
||||
};
|
||||
void refresh();
|
||||
const off = [
|
||||
onIdeEvent("indexState", (e) => {
|
||||
if (!e.indexing) schedule();
|
||||
}),
|
||||
onIdeEvent("fsChanged", (e) => {
|
||||
if (e.created.length || e.removed.length) detected = undefined;
|
||||
if (
|
||||
e.created.length ||
|
||||
e.removed.length ||
|
||||
e.modified.some((path) => markers.includes(path.replaceAll("\\", "/").split("/").at(-1)!))
|
||||
)
|
||||
schedule();
|
||||
}),
|
||||
onIdeEvent("settingsChanged", () => {
|
||||
detected = undefined;
|
||||
schedule();
|
||||
}),
|
||||
];
|
||||
return () => {
|
||||
live = false;
|
||||
clearTimeout(timer);
|
||||
off.forEach((dispose) => dispose());
|
||||
close();
|
||||
};
|
||||
}, [root, configured]);
|
||||
const current = state && state.root === root && state.configured === configured ? state : null;
|
||||
const shown = !!root && !!current && (current.visible || !!configured);
|
||||
useEffect(() => {
|
||||
usePopup.setState({ shown });
|
||||
return () => usePopup.setState({ shown: false, open: false });
|
||||
}, [shown]);
|
||||
if (!shown || !current) return null;
|
||||
const choices = interpreterChoices(current.sdks, current.python);
|
||||
const label = choices.find((sdk) => sdk.path === current.python)?.name ?? tx("No interpreter");
|
||||
const names = new Map<string, number>();
|
||||
for (const sdk of choices) names.set(sdk.name, (names.get(sdk.name) ?? 0) + 1);
|
||||
const items: MenuItem[] = [
|
||||
{ kind: "header", label: "Python Interpreter" },
|
||||
...choices.map((sdk): MenuItem => ({
|
||||
label: sdk.name,
|
||||
verbatim: true,
|
||||
// Several system interpreters share a name ("Python 3.11"); their paths tell them apart.
|
||||
shortcut: (names.get(sdk.name) ?? 0) > 1 ? tildify(sdk.path) : undefined,
|
||||
checked: sdk.path === current.python,
|
||||
run: () => void executeAction("python.selectInterpreter", sdk.path),
|
||||
})),
|
||||
{ kind: "separator" },
|
||||
{ kind: "action", action: "python.addInterpreter" },
|
||||
{ kind: "action", action: "python.interpreterSettings" },
|
||||
];
|
||||
return (
|
||||
<>
|
||||
<BarButton
|
||||
ref={anchor}
|
||||
tooltip={current.python ?? tx("No interpreter")}
|
||||
aria-label={tx`Python Interpreter: ${label}`}
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={open}
|
||||
onClick={() => void executeAction("python.interpreterPopup")}
|
||||
>
|
||||
{!current.python && <Icon name="warning" size={14} />}
|
||||
{label}
|
||||
</BarButton>
|
||||
<Menu
|
||||
open={open}
|
||||
onClose={close}
|
||||
anchor={anchor}
|
||||
placement="top-end"
|
||||
items={items}
|
||||
aria-label="Python Interpreter"
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function activatePythonStatus(): () => void {
|
||||
const dispose = [
|
||||
registerStatusItem({
|
||||
id: "python.interpreter",
|
||||
title: "Python Interpreter",
|
||||
align: "right",
|
||||
priority: 90,
|
||||
component: PythonStatus,
|
||||
}),
|
||||
registerActions([
|
||||
{
|
||||
id: "python.interpreterPopup",
|
||||
title: "Python Interpreter",
|
||||
category: "Settings",
|
||||
when: "projectOpen",
|
||||
run: () =>
|
||||
usePopup.getState().shown
|
||||
? usePopup.setState((s) => ({ open: !s.open }))
|
||||
: void executeAction("file.settings", "python.interpreter"),
|
||||
},
|
||||
{
|
||||
id: "python.selectInterpreter",
|
||||
title: "Select Python Interpreter",
|
||||
category: "Settings",
|
||||
hidden: true,
|
||||
run: async ({ arg }) => {
|
||||
const project = useProject.getState().project;
|
||||
if (!project || typeof arg !== "string" || !arg) return;
|
||||
try {
|
||||
const settings = await call(
|
||||
commands.settingsSet("project", "languages.python.interpreter", JSON.stringify(arg)),
|
||||
);
|
||||
if (useProject.getState().project === project) useProject.setState({ settings });
|
||||
} catch (e) {
|
||||
notifications().notify({ level: "error", title: "Cannot select Python interpreter", body: String(e) });
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "python.addInterpreter",
|
||||
title: "Add New Interpreter…",
|
||||
category: "Settings",
|
||||
when: "projectOpen",
|
||||
run: () => void executeAction("file.settings", "python.interpreter"),
|
||||
},
|
||||
{
|
||||
id: "python.interpreterSettings",
|
||||
title: "Interpreter Settings…",
|
||||
category: "Settings",
|
||||
when: "projectOpen",
|
||||
run: () => void executeAction("file.settings", "python.interpreter"),
|
||||
},
|
||||
]),
|
||||
];
|
||||
return () => {
|
||||
close();
|
||||
dispose.reverse().forEach((d) => d());
|
||||
};
|
||||
}
|
||||
@@ -23,6 +23,11 @@
|
||||
}
|
||||
|
||||
/* "[x] Limit history to: [1000] rows" */
|
||||
.fontFamily {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.inlineRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
Loaded 100 of 147 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача