дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-26 03:14:38 +02:00
Порівняти коміти
12
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
9944d13314 | ||
|
|
7aad01b035 | ||
|
|
2613e61ebf | ||
|
|
971760f858 | ||
|
|
ad5f827673 | ||
|
|
dd8c8b8993 | ||
|
|
35ba957893 | ||
|
|
e272131823 | ||
|
|
d5fe771eed | ||
|
|
14c7821cf4 | ||
|
|
73dd9fdf65 | ||
|
|
091c25351b |
No files matched your search
@@ -4,10 +4,11 @@ use crate::rpc::Dispatcher;
|
||||
|
||||
use super::build::load;
|
||||
use ide_build::compile;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, RequestId};
|
||||
use ide_lsp::jdtls::JavaLaunchInfo;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Cancellable with `cancel_request(request)`.
|
||||
/// Builds the workspace (when `build`), then resolves the runtime (or test)
|
||||
/// classpath and the JDK of the module at `module` (absolute, or relative to the project root).
|
||||
/// A module with Kotlin / Groovy / Scala sources is built by its build system, whose class directories come first.
|
||||
@@ -17,17 +18,33 @@ pub async fn java_resolve_launch(
|
||||
module: PathBuf,
|
||||
test: bool,
|
||||
build: bool,
|
||||
request: RequestId,
|
||||
) -> IdeResult<JavaLaunchInfo> {
|
||||
let cancel = host.begin_request(request);
|
||||
let result = resolve_launch(host, window, module, test, build, &cancel).await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
async fn resolve_launch(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
module: PathBuf,
|
||||
test: bool,
|
||||
build: bool,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<JavaLaunchInfo> {
|
||||
let project = host.project(window)?;
|
||||
let module = project.root.join(module);
|
||||
let settings = project.settings.effective();
|
||||
// Let jdtls finish its build before the external compiler writes Kotlin/Scala classes.
|
||||
let mut info = project.lsp.java_launch(&module, test, build).await?;
|
||||
let mut info = project.lsp.java_launch(&module, test, build, cancel).await?;
|
||||
let built = if build && compile::has_non_java_sources(&module) {
|
||||
let (root, cache, module, settings) =
|
||||
(project.root.clone(), project.build_cache_dir(), module.clone(), settings.clone());
|
||||
let cancel = cancel.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
compile::build_for_launch(&root, &load(&root, &cache, &settings), &module, test, &CancellationToken::new())
|
||||
compile::build_for_launch(&root, &load(&root, &cache, &settings), &module, test, &cancel)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))??
|
||||
@@ -65,6 +82,9 @@ pub async fn java_resolve_launch(
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
info.hints.extend(lombok.problem());
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
@@ -83,13 +103,14 @@ pub async fn java_build_workspace(
|
||||
) -> IdeResult<ide_lsp::jdtls::JavaBuildStatus> {
|
||||
let project = host.project(window)?;
|
||||
let module = project.root.join(module);
|
||||
project.lsp.java_build(&module).await
|
||||
project.lsp.java_build(&module, &CancellationToken::new()).await
|
||||
}
|
||||
|
||||
/// Commands of this module the remote server answers.
|
||||
pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("java_resolve_launch", |c| async move {
|
||||
java_resolve_launch(&c.host, &c.window, c.arg("module")?, c.arg("test")?, c.arg("build")?).await
|
||||
java_resolve_launch(&c.host, &c.window, c.arg("module")?, c.arg("test")?, c.arg("build")?, c.arg("request")?)
|
||||
.await
|
||||
});
|
||||
d.add("java_debug_server", |c| async move { java_debug_server(&c.host, &c.window, c.arg("module")?).await });
|
||||
d.add("java_build_workspace", |c| async move { java_build_workspace(&c.host, &c.window, c.arg("module")?).await });
|
||||
|
||||
@@ -8,8 +8,7 @@
|
||||
use crate::LspManager;
|
||||
use crate::server::{Running, Server};
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::{IdeError, IdeResult, LanguageId};
|
||||
use ide_jsonrpc::RpcError;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use specta::Type;
|
||||
@@ -20,7 +19,9 @@ use std::time::{Duration, Instant};
|
||||
const SERVER: &str = "jdtls";
|
||||
/// First start imports the Maven / Gradle model, which can take minutes.
|
||||
const READY_TIMEOUT: Duration = Duration::from_secs(240);
|
||||
const BUILD_TIMEOUT: Duration = Duration::from_secs(300);
|
||||
/// A workspace build of a large multi-module project can take far longer than
|
||||
/// an editor request; the user can always cancel the launch waiting on it.
|
||||
const BUILD_TIMEOUT: Duration = Duration::from_secs(20 * 60);
|
||||
const COMMAND_TIMEOUT: Duration = Duration::from_secs(120);
|
||||
/// How long to retry while the project is still being imported.
|
||||
const IMPORT_WAIT: Duration = Duration::from_secs(90);
|
||||
@@ -70,6 +71,8 @@ pub struct JavaLaunchInfo {
|
||||
pub project_root: Option<ide_core::IpcPath>,
|
||||
pub class_paths: Vec<String>,
|
||||
pub module_paths: Vec<String>,
|
||||
/// Path list separator of the host that runs the JVM.
|
||||
pub path_list_separator: String,
|
||||
/// JDK home jdtls compiles the project against.
|
||||
pub java_home: Option<ide_core::IpcPath>,
|
||||
/// The `java` launcher to use (filled in by the caller from the installed JDKs).
|
||||
@@ -163,10 +166,19 @@ fn missing_bundle(e: &IdeError) -> bool {
|
||||
m.contains("no delegatecommandhandler") || m.contains("unsupported command") || m.contains("not supported")
|
||||
}
|
||||
|
||||
/// Cancel local waits without interrupting a shared server's startup or import.
|
||||
async fn cancellable_wait<T>(cancel: &CancellationToken, wait: impl std::future::Future<Output = T>) -> IdeResult<T> {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => Err(IdeError::cancelled()),
|
||||
result = wait => Ok(result),
|
||||
}
|
||||
}
|
||||
|
||||
impl LspManager {
|
||||
/// The jdtls instance serving `path` (a module directory or source file),
|
||||
/// started if needed and waited for.
|
||||
async fn jdtls(&self, path: &Path) -> IdeResult<(Arc<Server>, Running)> {
|
||||
async fn jdtls(&self, path: &Path, cancel: &CancellationToken) -> IdeResult<(Arc<Server>, Running)> {
|
||||
let java = LanguageId::new("java");
|
||||
let server = self
|
||||
.servers_for(&java, path)
|
||||
@@ -174,7 +186,7 @@ impl LspManager {
|
||||
.find(|s| s.name == SERVER)
|
||||
.ok_or_else(|| IdeError::unavailable("no Java language server (jdtls) is configured"))?;
|
||||
self.ensure_started(&server);
|
||||
match server.wait_ready(READY_TIMEOUT).await {
|
||||
match cancellable_wait(cancel, server.wait_ready(READY_TIMEOUT)).await? {
|
||||
Some(run) => Ok((server, run)),
|
||||
None => {
|
||||
let status = server.status();
|
||||
@@ -191,34 +203,64 @@ impl LspManager {
|
||||
}
|
||||
}
|
||||
|
||||
async fn jdtls_request(&self, path: &Path, method: &str, params: Value, timeout: Duration) -> IdeResult<Value> {
|
||||
let (server, run) = self.jdtls(path).await?;
|
||||
let fut = run.peer.request::<Value, Value>(method, params, None);
|
||||
async fn jdtls_request(
|
||||
&self,
|
||||
path: &Path,
|
||||
method: &str,
|
||||
params: Value,
|
||||
timeout: Duration,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Value> {
|
||||
let (server, run) = self.jdtls(path, cancel).await?;
|
||||
let fut = run.peer.request::<Value, Value>(method, params, Some(cancel.clone()));
|
||||
match tokio::time::timeout(timeout, fut).await {
|
||||
Ok(r) => r.map_err(|e| crate::rpc_err(&server.name, method, e)),
|
||||
Err(_) => Err(crate::rpc_err(&server.name, method, RpcError::Timeout)),
|
||||
Err(_) => Err(IdeError::new(
|
||||
ErrorKind::Protocol,
|
||||
format!(
|
||||
"{SERVER}: {method} timed out after {} s; retry, or check that jdtls is not stuck",
|
||||
timeout.as_secs()
|
||||
),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// `workspace/executeCommand` on the jdtls serving `path`.
|
||||
pub async fn jdtls_command(&self, path: &Path, command: &str, arguments: Vec<Value>) -> IdeResult<Value> {
|
||||
self.jdtls_command_cancellable(path, command, arguments, &CancellationToken::new()).await
|
||||
}
|
||||
|
||||
async fn jdtls_command_cancellable(
|
||||
&self,
|
||||
path: &Path,
|
||||
command: &str,
|
||||
arguments: Vec<Value>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Value> {
|
||||
self.jdtls_request(
|
||||
path,
|
||||
"workspace/executeCommand",
|
||||
json!({ "command": command, "arguments": arguments }),
|
||||
COMMAND_TIMEOUT,
|
||||
cancel,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Like [`jdtls_command`](Self::jdtls_command), retried while the project is still importing.
|
||||
async fn jdtls_project_command(&self, path: &Path, command: &str, arguments: Vec<Value>) -> IdeResult<Value> {
|
||||
async fn jdtls_project_command(
|
||||
&self,
|
||||
path: &Path,
|
||||
command: &str,
|
||||
arguments: Vec<Value>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Value> {
|
||||
let deadline = Instant::now() + IMPORT_WAIT;
|
||||
loop {
|
||||
match self.jdtls_command(path, command, arguments.clone()).await {
|
||||
match self.jdtls_command_cancellable(path, command, arguments.clone(), cancel).await {
|
||||
Err(e) if not_imported(&e) && Instant::now() < deadline => {
|
||||
tracing::debug!("{command}: {e}; waiting for the project import");
|
||||
tokio::time::sleep(Duration::from_millis(1500)).await;
|
||||
cancellable_wait(cancel, tokio::time::sleep(Duration::from_millis(1500))).await?;
|
||||
}
|
||||
r => return r,
|
||||
}
|
||||
@@ -245,43 +287,62 @@ impl LspManager {
|
||||
|
||||
/// Incremental build of the jdtls workspace (`java/buildWorkspace`), so
|
||||
/// class files are up to date before a launch.
|
||||
pub async fn java_build(&self, path: &Path) -> IdeResult<JavaBuildStatus> {
|
||||
let v = self.jdtls_request(path, "java/buildWorkspace", json!(false), BUILD_TIMEOUT).await?;
|
||||
pub async fn java_build(&self, path: &Path, cancel: &CancellationToken) -> IdeResult<JavaBuildStatus> {
|
||||
let v = self.jdtls_request(path, "java/buildWorkspace", json!(false), BUILD_TIMEOUT, cancel).await?;
|
||||
Ok(JavaBuildStatus::from_code(v.as_i64().unwrap_or(0)))
|
||||
}
|
||||
|
||||
/// Runtime (`test == false`) or test classpath of the project containing `path`.
|
||||
pub async fn java_classpath(&self, path: &Path, test: bool) -> IdeResult<JavaClasspath> {
|
||||
pub async fn java_classpath(
|
||||
&self,
|
||||
path: &Path,
|
||||
test: bool,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<JavaClasspath> {
|
||||
let uri = crate::uri::path_to_uri_string(path);
|
||||
let options = json!({ "scope": if test { "test" } else { "runtime" } }).to_string();
|
||||
let v =
|
||||
self.jdtls_project_command(path, "java.project.getClasspaths", vec![json!(uri), json!(options)]).await?;
|
||||
let v = self
|
||||
.jdtls_project_command(path, "java.project.getClasspaths", vec![json!(uri), json!(options)], cancel)
|
||||
.await?;
|
||||
Ok(parse_classpaths(&v))
|
||||
}
|
||||
|
||||
/// The JDK home jdtls uses for the project containing `path`.
|
||||
pub async fn java_vm_location(&self, path: &Path) -> IdeResult<Option<PathBuf>> {
|
||||
pub async fn java_vm_location(&self, path: &Path, cancel: &CancellationToken) -> IdeResult<Option<PathBuf>> {
|
||||
let uri = crate::uri::path_to_uri_string(path);
|
||||
let v = self
|
||||
.jdtls_project_command(
|
||||
path,
|
||||
"java.project.getSettings",
|
||||
vec![json!(uri), json!(["org.eclipse.jdt.ls.core.vm.location"])],
|
||||
cancel,
|
||||
)
|
||||
.await?;
|
||||
Ok(parse_vm_location(&v))
|
||||
}
|
||||
|
||||
/// Builds (when asked), then resolves the classpath and JDK of the module at `module`.
|
||||
pub async fn java_launch(&self, module: &Path, test: bool, build: bool) -> IdeResult<JavaLaunchInfo> {
|
||||
let build = if build { Some(self.java_build(module).await?) } else { None };
|
||||
pub async fn java_launch(
|
||||
&self,
|
||||
module: &Path,
|
||||
test: bool,
|
||||
build: bool,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<JavaLaunchInfo> {
|
||||
let build = if build { Some(self.java_build(module, cancel).await?) } else { None };
|
||||
if build == Some(JavaBuildStatus::Cancelled) {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let (errors, error_count) = match build {
|
||||
Some(JavaBuildStatus::WithErrors | JavaBuildStatus::Failed) => self.java_compile_errors(module).await,
|
||||
Some(JavaBuildStatus::WithErrors | JavaBuildStatus::Failed) => {
|
||||
cancellable_wait(cancel, self.java_compile_errors(module)).await?
|
||||
}
|
||||
_ => (Vec::new(), 0),
|
||||
};
|
||||
let cp = self.java_classpath(module, test).await?;
|
||||
let java_home = match self.java_vm_location(module).await {
|
||||
let cp = self.java_classpath(module, test, cancel).await?;
|
||||
let java_home = match self.java_vm_location(module, cancel).await {
|
||||
Ok(home) => home,
|
||||
Err(e) if e.kind == ErrorKind::Cancelled => return Err(e),
|
||||
Err(e) => {
|
||||
tracing::debug!("java.project.getSettings: {e}");
|
||||
None
|
||||
@@ -292,6 +353,7 @@ impl LspManager {
|
||||
project_root: cp.project_root,
|
||||
class_paths: cp.class_paths,
|
||||
module_paths: cp.module_paths,
|
||||
path_list_separator: if cfg!(windows) { ";" } else { ":" }.into(),
|
||||
java_home: java_home.map(Into::into),
|
||||
java_exec: None,
|
||||
shorten_command_line: None,
|
||||
@@ -303,7 +365,7 @@ impl LspManager {
|
||||
|
||||
/// Compile errors jdtls reports for its workspace (all modules it imported).
|
||||
async fn java_compile_errors(&self, module: &Path) -> (Vec<JavaCompileError>, u32) {
|
||||
let Ok((server, _)) = self.jdtls(module).await else { return (Vec::new(), 0) };
|
||||
let Ok((server, _)) = self.jdtls(module, &CancellationToken::new()).await else { return (Vec::new(), 0) };
|
||||
let collect = || compile_errors(server.diagnostics_snapshot(), MAX_LAUNCH_ERRORS);
|
||||
let found = collect();
|
||||
if found.1 > 0 {
|
||||
@@ -341,6 +403,20 @@ impl LspManager {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancellation_ends_a_pending_wait() {
|
||||
let cancel = CancellationToken::new();
|
||||
let waiting = cancellable_wait(&cancel, std::future::pending::<()>());
|
||||
let cancelling = async {
|
||||
tokio::task::yield_now().await;
|
||||
cancel.cancel();
|
||||
};
|
||||
let (result, ()) = tokio::time::timeout(Duration::from_secs(1), async { tokio::join!(waiting, cancelling) })
|
||||
.await
|
||||
.expect("cancelled wait must finish");
|
||||
assert_eq!(result.unwrap_err().kind, ErrorKind::Cancelled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn launch_errors_are_sorted_and_capped() {
|
||||
let diag = |line: u32, severity, message: &str| lsp_types::Diagnostic {
|
||||
|
||||
@@ -6,7 +6,7 @@ use std::path::{Path, PathBuf};
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Explicit git executable from Settings › Version Control › Git (`None` = auto-detect).
|
||||
static CONFIGURED: std::sync::RwLock<Option<PathBuf>> = std::sync::RwLock::new(None);
|
||||
@@ -128,6 +128,78 @@ pub fn git_version(executable: Option<&Path>) -> IdeResult<String> {
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
/// `CreateProcessW` takes at most 32767 chars including the NUL; leave slack for quoting.
|
||||
/// (The same limits as `ide_run::java_cmdline`'s shortened java command lines.)
|
||||
pub(crate) const WINDOWS_LIMIT: usize = 32_000;
|
||||
/// Linux caps one argument at 128 KiB (`MAX_ARG_STRLEN`); macOS the whole `ARG_MAX` (1 MiB, env included).
|
||||
pub(crate) const UNIX_LIMIT: usize = 120_000;
|
||||
|
||||
/// The longest command line this platform's process spawning accepts.
|
||||
pub(crate) fn command_line_limit() -> usize {
|
||||
if cfg!(windows) { WINDOWS_LIMIT } else { UNIX_LIMIT }
|
||||
}
|
||||
|
||||
/// Slack for the program path and the `-c` options [`command`] adds.
|
||||
const COMMAND_LINE_SLACK: usize = 512;
|
||||
|
||||
/// Budget for `base` (two quotes and one separator per argument) plus [`COMMAND_LINE_SLACK`].
|
||||
pub(crate) fn base_command_line_len(base: &[&str]) -> usize {
|
||||
base.iter().map(|a| a.len() + 3).sum::<usize>() + COMMAND_LINE_SLACK
|
||||
}
|
||||
|
||||
/// Splits `paths` into runs whose length (`base_len` plus each path, two quotes, and a separator)
|
||||
/// stays within `limit`. A path that alone exceeds the remaining room still gets a batch
|
||||
/// of its own, so every call makes progress; an empty list yields no batches.
|
||||
pub(crate) fn batch_paths(base_len: usize, paths: &[String], limit: usize) -> Vec<&[String]> {
|
||||
let mut batches = Vec::new();
|
||||
let mut start = 0;
|
||||
while start < paths.len() {
|
||||
let mut len = base_len;
|
||||
let mut end = start;
|
||||
while end < paths.len() {
|
||||
// Windows quotes arguments containing spaces or tabs; reserve both quotes on every platform.
|
||||
let next = len + paths[end].len() + 3;
|
||||
if next > limit && end > start {
|
||||
break;
|
||||
}
|
||||
len = next;
|
||||
end += 1;
|
||||
}
|
||||
batches.push(&paths[start..end]);
|
||||
start = end;
|
||||
}
|
||||
batches
|
||||
}
|
||||
|
||||
/// [`run`] with a list of paths appended after `--`, split into as many invocations as
|
||||
/// the platform's command-line limit needs (a large rollback would otherwise fail with
|
||||
/// `os error 206` on Windows). `args` must already carry `--literal-pathspecs` and
|
||||
/// end with `--`; the first error stops the remaining batches.
|
||||
pub(crate) fn run_paths_env(
|
||||
root: &Path,
|
||||
args: &[&str],
|
||||
paths: &[String],
|
||||
stdin: Option<&[u8]>,
|
||||
env: &[(&str, &std::ffi::OsStr)],
|
||||
) -> IdeResult<Output> {
|
||||
let mut out = Output { stdout: Vec::new(), stderr: Vec::new(), code: Some(0) };
|
||||
if paths.is_empty() {
|
||||
return Ok(out);
|
||||
}
|
||||
let base_len = base_command_line_len(args);
|
||||
for batch in batch_paths(base_len, paths, command_line_limit()) {
|
||||
let mut full: Vec<&str> = args.to_vec();
|
||||
full.extend(batch.iter().map(String::as_str));
|
||||
out = run_env(root, &full, stdin, env)?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// [`run_paths_env`] without extra environment variables.
|
||||
pub(crate) fn run_paths(root: &Path, args: &[&str], paths: &[String]) -> IdeResult<Output> {
|
||||
run_paths_env(root, args, paths, None, &[])
|
||||
}
|
||||
|
||||
/// Builds a `git` command with the environment every invocation needs.
|
||||
pub(crate) fn command(root: &Path) -> IdeResult<Command> {
|
||||
let mut cmd = Command::new(git_binary()?);
|
||||
@@ -175,6 +247,59 @@ pub(crate) fn run_raw_env(
|
||||
args: &[&str],
|
||||
stdin: Option<&[u8]>,
|
||||
env: &[(&str, &std::ffi::OsStr)],
|
||||
) -> IdeResult<Output> {
|
||||
let first = run_raw_env_once(root, args, stdin, env)?;
|
||||
if !retryable_index_lock(args, &first) {
|
||||
return Ok(first);
|
||||
}
|
||||
let deadline = Instant::now() + Duration::from_secs(2);
|
||||
loop {
|
||||
let remaining = deadline.saturating_duration_since(Instant::now());
|
||||
if remaining.is_zero() {
|
||||
return Ok(first);
|
||||
}
|
||||
std::thread::sleep(remaining.min(Duration::from_millis(50)));
|
||||
if Instant::now() >= deadline {
|
||||
return Ok(first);
|
||||
}
|
||||
let out = run_raw_env_once(root, args, stdin, env)?;
|
||||
if !retryable_index_lock(args, &out) {
|
||||
return Ok(out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn retryable_index_lock(args: &[&str], out: &Output) -> bool {
|
||||
// These builtins take the index lock before changing the index, worktree or refs.
|
||||
// switch folds post-checkout hook failures to exit 1, unlike checkout/restore
|
||||
// path operations, whose hooks can return 128 after files have already changed.
|
||||
// Keep commit, update-index, merge, rebase, stash and streaming operations out:
|
||||
// a lock error there can follow partial work. Interactive modes are excluded too.
|
||||
let args = args.strip_prefix(&["--literal-pathspecs"]).unwrap_or(args);
|
||||
let Some((sub, options)) = args.split_first() else { return false };
|
||||
if !matches!(*sub, "switch" | "add" | "rm" | "reset")
|
||||
|| options
|
||||
.iter()
|
||||
.take_while(|arg| **arg != "--")
|
||||
.any(|arg| matches!(*arg, "-p" | "--patch" | "-i" | "--interactive" | "-e" | "--edit" | "--soft"))
|
||||
|| out.code != Some(128)
|
||||
|| !out.stdout.is_empty()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
let Some(path) = stderr.lines().next().and_then(|line| line.strip_prefix("fatal: Unable to create '")) else {
|
||||
return false;
|
||||
};
|
||||
path.strip_suffix("': File exists.")
|
||||
.is_some_and(|path| path.ends_with("/index.lock") || path.ends_with("\\index.lock"))
|
||||
}
|
||||
|
||||
fn run_raw_env_once(
|
||||
root: &Path,
|
||||
args: &[&str],
|
||||
stdin: Option<&[u8]>,
|
||||
env: &[(&str, &std::ffi::OsStr)],
|
||||
) -> IdeResult<Output> {
|
||||
let mut cmd = command(root)?;
|
||||
for (k, v) in env {
|
||||
@@ -500,3 +625,170 @@ mod command_session_tests {
|
||||
assert_eq!(ours, vec![(second_id, false, String::new()), (first_id, true, "done".into())]);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod batching_tests {
|
||||
use super::{WINDOWS_LIMIT, base_command_line_len, batch_paths, command_line_limit};
|
||||
|
||||
fn paths(n: usize, len: usize) -> Vec<String> {
|
||||
(0..n).map(|i| format!("src/file-{i}.rs").chars().cycle().take(len).collect()).collect()
|
||||
}
|
||||
|
||||
fn len_of(base_len: usize, batch: &[String]) -> usize {
|
||||
base_len + batch.iter().map(|p| p.len() + 3).sum::<usize>()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_input_yields_no_batches() {
|
||||
let empty: Vec<String> = Vec::new();
|
||||
assert!(batch_paths(10, &empty, 100).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_path_is_batched_exactly_once_and_in_order() {
|
||||
let all = paths(100, 12);
|
||||
let batches = batch_paths(50, &all, 200);
|
||||
let joined: Vec<&String> = batches.iter().flat_map(|b| b.iter()).collect();
|
||||
assert_eq!(joined, all.iter().collect::<Vec<_>>());
|
||||
assert!(batches.len() > 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batches_stay_within_the_limit() {
|
||||
let all = paths(5_000, 40);
|
||||
let base = 40;
|
||||
let limit = 1_000;
|
||||
for batch in batch_paths(base, &all, limit) {
|
||||
assert!(len_of(base, batch) <= limit || batch.len() == 1);
|
||||
}
|
||||
// The whole list would not have fit one invocation.
|
||||
assert!(len_of(base, &all) > limit);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paths_with_spaces_fit_the_windows_limit_including_quotes() {
|
||||
let all = vec![format!("directory with spaces/{}.rs", "x".repeat(15)); 5_000];
|
||||
assert_eq!(all[0].len(), 40);
|
||||
let base = base_command_line_len(&["--literal-pathspecs", "add", "-A", "--"]);
|
||||
let batches = batch_paths(base, &all, WINDOWS_LIMIT);
|
||||
assert!(batches.len() > 1);
|
||||
for batch in batches {
|
||||
assert!(len_of(base, batch) <= WINDOWS_LIMIT);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_oversized_path_gets_its_own_batch() {
|
||||
let all = vec!["a".to_string(), "x".repeat(10_000), "b".to_string()];
|
||||
let batches = batch_paths(0, &all, 100);
|
||||
assert_eq!(batches.len(), 3);
|
||||
assert_eq!(batches[0].to_vec(), vec!["a".to_string()]);
|
||||
assert_eq!(batches[1].to_vec(), vec!["x".repeat(10_000)]);
|
||||
assert_eq!(batches[2].to_vec(), vec!["b".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_platform_limit_is_a_positive_budget() {
|
||||
assert!(command_line_limit() > 1_000);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod index_lock_tests {
|
||||
use super::*;
|
||||
|
||||
fn repo() -> tempfile::TempDir {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
run(dir.path(), &["init", "-q", "-b", "main"], None).unwrap();
|
||||
std::fs::write(dir.path().join("file"), "main\n").unwrap();
|
||||
run(dir.path(), &["add", "file"], None).unwrap();
|
||||
run(
|
||||
dir.path(),
|
||||
&["-c", "user.name=Test", "-c", "[email protected]", "commit", "-qm", "initial"],
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
run(dir.path(), &["branch", "other"], None).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn switch_retries_until_index_lock_is_released() {
|
||||
let dir = repo();
|
||||
let lock = dir.path().join(".git/index.lock");
|
||||
std::fs::write(&lock, "held").unwrap();
|
||||
let release = std::thread::spawn(move || {
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
std::fs::remove_file(lock).unwrap();
|
||||
});
|
||||
let start = Instant::now();
|
||||
let result = run(dir.path(), &["switch", "other"], None);
|
||||
release.join().unwrap();
|
||||
result.unwrap();
|
||||
assert!(start.elapsed() >= Duration::from_millis(300));
|
||||
assert_eq!(run(dir.path(), &["branch", "--show-current"], None).unwrap().stdout_str().trim(), "other");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persistent_index_lock_returns_original_error_without_removing_lock() {
|
||||
let dir = repo();
|
||||
let lock = dir.path().join(".git/index.lock");
|
||||
std::fs::write(&lock, "held by someone else").unwrap();
|
||||
let args = ["switch", "other"];
|
||||
let original = run_raw_env_once(dir.path(), &args, None, &[]).unwrap();
|
||||
let start = Instant::now();
|
||||
let error = run(dir.path(), &args, None).err().unwrap();
|
||||
assert!(start.elapsed() >= Duration::from_secs(2));
|
||||
assert!(start.elapsed() < Duration::from_secs(4));
|
||||
assert_eq!(error.to_string(), failure(&args, &original.stderr, &original.stdout, original.code).to_string());
|
||||
assert_eq!(std::fs::read_to_string(lock).unwrap(), "held by someone else");
|
||||
assert_eq!(run(dir.path(), &["branch", "--show-current"], None).unwrap().stdout_str().trim(), "main");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn switch_does_not_repeat_a_failed_post_checkout_hook() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = repo();
|
||||
let hook = dir.path().join(".git/hooks/post-checkout");
|
||||
std::fs::write(
|
||||
&hook,
|
||||
"#!/bin/sh\necho ran >> hook-runs\necho \"fatal: Unable to create '$PWD/.git/index.lock': File exists.\" >&2\nexit 128\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let out = run_raw(dir.path(), &["switch", "-q", "other"], None).unwrap();
|
||||
assert_eq!(out.code, Some(1));
|
||||
assert_eq!(std::fs::read_to_string(dir.path().join("hook-runs")).unwrap(), "ran\n");
|
||||
assert_eq!(run(dir.path(), &["branch", "--show-current"], None).unwrap().stdout_str().trim(), "other");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_requires_a_safe_command_and_the_exact_lock_failure() {
|
||||
let mut out = Output {
|
||||
stdout: Vec::new(),
|
||||
stderr: b"fatal: Unable to create '/repo/.git/index.lock': File exists.\n\nAnother git process".to_vec(),
|
||||
code: Some(128),
|
||||
};
|
||||
for args in [&["switch", "other"][..], &["--literal-pathspecs", "add", "-A", "--"], &["rm"], &["reset"]] {
|
||||
assert!(retryable_index_lock(args, &out));
|
||||
}
|
||||
for sub in ["merge", "rebase", "stash", "commit", "update-index", "checkout", "restore", "pull", "status"] {
|
||||
assert!(!retryable_index_lock(&[sub], &out));
|
||||
}
|
||||
assert!(!retryable_index_lock(&["add", "--patch"], &out));
|
||||
assert!(!retryable_index_lock(&["reset", "--soft"], &out));
|
||||
out.code = Some(1); // switch's post-checkout hook can fail after the switch succeeded.
|
||||
assert!(!retryable_index_lock(&["switch"], &out));
|
||||
out.code = Some(128);
|
||||
for message in [
|
||||
"fatal: Unable to create '/repo/.git/HEAD.lock': File exists.",
|
||||
"fatal: Unable to create '/repo/.git/index.lock': Permission denied",
|
||||
"error: index.lock: File exists",
|
||||
"warning: partial work\nfatal: Unable to create '/repo/.git/index.lock': File exists.",
|
||||
] {
|
||||
out.stderr = message.as_bytes().to_vec();
|
||||
assert!(!retryable_index_lock(&["switch"], &out));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ use std::path::{Path, PathBuf};
|
||||
use std::sync::{Mutex, MutexGuard, OnceLock};
|
||||
use std::time::SystemTime;
|
||||
|
||||
#[derive(PartialEq, Eq)]
|
||||
#[derive(PartialEq, Eq, Clone)]
|
||||
struct Identity {
|
||||
len: u64,
|
||||
modified: SystemTime,
|
||||
@@ -16,6 +16,22 @@ fn identity(path: &Path) -> Option<Identity> {
|
||||
Some(Identity { len: metadata.len(), modified: metadata.modified().ok()? })
|
||||
}
|
||||
|
||||
/// The index as it was when a status run opened it, so the run can tell whether
|
||||
/// something else rewrote it before its stat-refresh write-back lands.
|
||||
#[derive(PartialEq, Eq, Clone)]
|
||||
pub(crate) struct Stamp(Option<Identity>);
|
||||
|
||||
pub(crate) fn stamp(path: &Path) -> Stamp {
|
||||
Stamp(identity(path))
|
||||
}
|
||||
|
||||
impl Stamp {
|
||||
/// Whether the index still has the identity it had when the stamp was taken.
|
||||
pub(crate) fn still_holds(&self, path: &Path) -> bool {
|
||||
identity(path) == self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct IndexWrites(HashMap<PathBuf, Identity>);
|
||||
|
||||
@@ -74,4 +90,19 @@ mod tests {
|
||||
std::fs::remove_file(&first).unwrap();
|
||||
assert!(!is_own_index_write(&first));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stamp_detects_an_external_rewrite_of_the_index() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let index = tmp.path().join("index");
|
||||
std::fs::write(&index, "ours").unwrap();
|
||||
let opened = stamp(&index);
|
||||
assert!(opened.still_holds(&index));
|
||||
// Another process (a `git switch`) replaces the index mid-status.
|
||||
std::fs::write(&index, "theirs").unwrap();
|
||||
assert!(!opened.still_holds(&index));
|
||||
// A missing index is a change too: git writes a fresh one on the next run.
|
||||
std::fs::remove_file(&index).unwrap();
|
||||
assert!(!opened.still_holds(&index));
|
||||
}
|
||||
}
|
||||
@@ -47,9 +47,7 @@ pub(crate) fn working_patch(r: &Repo, rel_paths: &[String], reverse: bool) -> Id
|
||||
} else {
|
||||
run_env(r.root(), &["read-tree", "--empty"], None, &env)?;
|
||||
}
|
||||
let mut add: Vec<&str> = vec!["--literal-pathspecs", "add", "-A", "--"];
|
||||
add.extend(rel_paths.iter().map(String::as_str));
|
||||
run_env(r.root(), &add, None, &env)?;
|
||||
cli::run_paths_env(r.root(), &["--literal-pathspecs", "add", "-A", "--"], rel_paths, None, &env)?;
|
||||
let mut diff =
|
||||
vec!["diff", "--cached", "--binary", "--full-index", "-M", "--no-color", "--no-ext-diff", "--no-textconv"];
|
||||
if reverse {
|
||||
@@ -155,9 +153,7 @@ pub(crate) fn apply(r: &Repo, patch: &str) -> IdeResult<ApplyOutcome> {
|
||||
// `--3way` stages what it applied; keep the index as it was for the clean files.
|
||||
let clean: Vec<String> = paths.iter().filter(|p| !conflicts.contains(p)).cloned().collect();
|
||||
if !clean.is_empty() && r.has_head()? {
|
||||
let mut args = vec!["--literal-pathspecs", "reset", "-q", "--"];
|
||||
args.extend(clean.iter().map(String::as_str));
|
||||
run(r.root(), &args, None)?;
|
||||
cli::run_paths(r.root(), &["--literal-pathspecs", "reset", "-q", "--"], &clean)?;
|
||||
}
|
||||
Ok(ApplyOutcome { applied: clean, conflicts })
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! `.idea/shelf`. Each shelved change list is `<shelf>/<id>/shelved.patch` plus
|
||||
//! `<shelf>/<id>/shelf.json` with its name, date and files.
|
||||
|
||||
use crate::cli::run;
|
||||
use crate::cli::run_paths;
|
||||
use crate::{ApplyOutcome, ChangeKind, Repo, ShelvedChangeList};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -152,15 +152,14 @@ pub(crate) fn shelve(r: &Repo, shelf: &Path, name: &str, rel_paths: &[String]) -
|
||||
fn revert_files(r: &Repo, files: &[crate::ChangedFile]) -> IdeResult<()> {
|
||||
let has_head = r.has_head()?;
|
||||
let (in_head, new): (Vec<_>, Vec<_>) = files.iter().partition(|f| has_head && f.kind != ChangeKind::Added);
|
||||
let paths = |files: &[&crate::ChangedFile]| -> Vec<String> { files.iter().map(|f| f.path.clone()).collect() };
|
||||
if !in_head.is_empty() {
|
||||
let mut args = vec!["--literal-pathspecs", "restore", "--source=HEAD", "--staged", "--worktree", "--"];
|
||||
args.extend(in_head.iter().map(|f| f.path.as_str()));
|
||||
run(r.root(), &args, None)?;
|
||||
let args = ["--literal-pathspecs", "restore", "--source=HEAD", "--staged", "--worktree", "--"];
|
||||
run_paths(r.root(), &args, &paths(&in_head))?;
|
||||
}
|
||||
if !new.is_empty() {
|
||||
let mut args = vec!["--literal-pathspecs", "rm", "--cached", "-q", "-r", "--ignore-unmatch", "--"];
|
||||
args.extend(new.iter().map(|f| f.path.as_str()));
|
||||
run(r.root(), &args, None)?;
|
||||
let args = ["--literal-pathspecs", "rm", "--cached", "-q", "-r", "--ignore-unmatch", "--"];
|
||||
run_paths(r.root(), &args, &paths(&new))?;
|
||||
for f in new {
|
||||
let abs = r.abs_path(&f.path);
|
||||
if abs.is_file() || abs.is_symlink() {
|
||||
|
||||
@@ -20,6 +20,12 @@ pub(crate) fn status(r: &Repo) -> IdeResult<Vec<FileStatus>> {
|
||||
let mut conflicts: HashSet<String> = HashSet::new();
|
||||
let ignored = r.ignored.read().unwrap_or_else(|p| p.into_inner()).clone();
|
||||
|
||||
// Stamp before status can read the index: stamping after the load could capture
|
||||
// an external `git switch`, `add` or commit's new index and allow the stale
|
||||
// snapshot to overwrite it. A change between the stamp and the read only skips
|
||||
// one stat refresh, which is safe.
|
||||
let index_path = repo.index_path();
|
||||
let opened = crate::index_writes::stamp(&index_path);
|
||||
let platform = repo
|
||||
.status(gix::progress::Discard)
|
||||
.map_err(gx)?
|
||||
@@ -95,10 +101,20 @@ pub(crate) fn status(r: &Repo) -> IdeResult<Vec<FileStatus>> {
|
||||
&& outcome.has_changes()
|
||||
{
|
||||
let mut writes = crate::index_writes::lock();
|
||||
match outcome.write_changes() {
|
||||
Some(Ok(_)) => writes.record(&repo.index_path()),
|
||||
Some(Err(e)) => tracing::debug!("could not write refreshed index: {e}"),
|
||||
None => {}
|
||||
// Another process rewrote the index while this status run was reading it
|
||||
// (a branch switch rewriting thousands of worktree files is the usual case).
|
||||
// Writing the stale snapshot back would restore the previous branch's tree,
|
||||
// so drop the refresh and let the next status re-read the current index.
|
||||
#[cfg(test)]
|
||||
run_between_read_and_write();
|
||||
if opened.still_holds(&index_path) {
|
||||
match outcome.write_changes() {
|
||||
Some(Ok(_)) => writes.record(&index_path),
|
||||
Some(Err(e)) => tracing::debug!("could not write refreshed index: {e}"),
|
||||
None => {}
|
||||
}
|
||||
} else {
|
||||
tracing::debug!("index changed during status; skipping the stat refresh write-back");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,3 +141,90 @@ pub(crate) fn status(r: &Repo) -> IdeResult<Vec<FileStatus>> {
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Lets a test land an external index write in the window between the status run
|
||||
/// reading the index and its write-back — the interleaving issue #471 describes.
|
||||
#[cfg(test)]
|
||||
fn run_between_read_and_write() {
|
||||
let mut hook = BETWEEN_READ_AND_WRITE.with(|h| h.borrow_mut().take());
|
||||
if let Some(hook) = hook.take() {
|
||||
hook();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
static BETWEEN_READ_AND_WRITE: std::cell::RefCell<Option<Box<dyn FnOnce()>>> =
|
||||
std::cell::RefCell::new(None);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
fn git(dir: &Path, args: &[&str]) {
|
||||
let out = Command::new("git")
|
||||
.current_dir(dir)
|
||||
.args(["-c", "init.defaultBranch=main", "-c", "core.autocrlf=false"])
|
||||
.args(args)
|
||||
.env("GIT_TERMINAL_PROMPT", "0")
|
||||
.output()
|
||||
.expect("git runs");
|
||||
assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
}
|
||||
|
||||
fn commit_all(dir: &Path, msg: &str) {
|
||||
git(dir, &["add", "-A"]);
|
||||
git(dir, &["commit", "-q", "-m", msg]);
|
||||
}
|
||||
|
||||
/// #471: a status run that read the index before an external `git switch`
|
||||
/// finished must not write its stale snapshot back over the new index.
|
||||
#[test]
|
||||
fn an_external_index_write_during_status_is_not_overwritten() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
git(dir, &["init", "-q"]);
|
||||
git(dir, &["config", "user.name", "Test User"]);
|
||||
git(dir, &["config", "user.email", "[email protected]"]);
|
||||
git(dir, &["config", "commit.gpgsign", "false"]);
|
||||
std::fs::write(dir.join("base.txt"), "base\n").unwrap();
|
||||
commit_all(dir, "base");
|
||||
// A branch that differs by a file and a deletion, so a switch rewrites the index.
|
||||
git(dir, &["checkout", "-q", "-b", "other"]);
|
||||
std::fs::write(dir.join("other.txt"), "other\n").unwrap();
|
||||
std::fs::remove_file(dir.join("base.txt")).unwrap();
|
||||
commit_all(dir, "other");
|
||||
git(dir, &["checkout", "-q", "main"]);
|
||||
// Rewrite a file with identical content: its stat info no longer matches the
|
||||
// index, so the status run refreshes it and has an index write-back to make.
|
||||
std::fs::write(dir.join("base.txt"), "base\n").unwrap();
|
||||
|
||||
let repo = Repo::discover(dir).unwrap().expect("repository found");
|
||||
let switched = dir.to_path_buf();
|
||||
let hook_ran = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let ran = hook_ran.clone();
|
||||
BETWEEN_READ_AND_WRITE.with(|h| {
|
||||
*h.borrow_mut() = Some(Box::new(move || {
|
||||
ran.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
git(&switched, &["switch", "-q", "--force", "other"]);
|
||||
}));
|
||||
});
|
||||
// The status result itself describes the tree as it was when it read the index
|
||||
// (base.txt still modified there); what matters is that it does not write that
|
||||
// snapshot back over the index `git switch` produced.
|
||||
repo.status().expect("status runs");
|
||||
assert!(hook_ran.load(std::sync::atomic::Ordering::SeqCst), "the external write landed mid-status");
|
||||
|
||||
// The index on disk is the one `git switch` wrote: its entries match the new branch.
|
||||
let listed = Command::new("git").current_dir(dir).args(["ls-files"]).output().unwrap();
|
||||
let files = String::from_utf8_lossy(&listed.stdout);
|
||||
assert!(files.contains("other.txt"), "{files}");
|
||||
assert!(!files.contains("base.txt"), "{files}");
|
||||
// Nothing staged: HEAD and index agree.
|
||||
let staged = Command::new("git").current_dir(dir).args(["diff", "--cached", "--stat"]).output().unwrap();
|
||||
assert!(staged.stdout.is_empty(), "{}", String::from_utf8_lossy(&staged.stdout));
|
||||
}
|
||||
}
|
||||
@@ -31,16 +31,14 @@ impl Repo {
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs a path-taking git command with literal pathspecs.
|
||||
/// Runs a path-taking git command with literal pathspecs, in as many invocations as
|
||||
/// the platform's command-line limit needs (a large rollback would otherwise fail with
|
||||
/// `os error 206` on Windows).
|
||||
fn run_paths(r: &Repo, args: &[&str], paths: &[String]) -> IdeResult<()> {
|
||||
if paths.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut full: Vec<&str> = vec!["--literal-pathspecs"];
|
||||
full.extend_from_slice(args);
|
||||
full.push("--");
|
||||
full.extend(paths.iter().map(String::as_str));
|
||||
run(r.root(), &full, None).map(|_| ())
|
||||
let mut base: Vec<&str> = vec!["--literal-pathspecs"];
|
||||
base.extend_from_slice(args);
|
||||
base.push("--");
|
||||
cli::run_paths(r.root(), &base, paths).map(|_| ())
|
||||
}
|
||||
|
||||
pub(crate) fn blame(
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
//! IPC commands of `ide_host::ops::java` (the shared implementation).
|
||||
|
||||
use crate::state::AppState;
|
||||
use ide_core::IdeResult;
|
||||
use ide_core::{IdeResult, RequestId};
|
||||
#[allow(unused_imports)]
|
||||
pub use ide_host::ops::java::*;
|
||||
use ide_lsp::jdtls::JavaLaunchInfo;
|
||||
use std::path::PathBuf;
|
||||
use tauri::{State, Window};
|
||||
|
||||
/// Cancellable with `cancel_request(request)`.
|
||||
/// Builds the workspace (when `build`), then resolves the runtime (or test)
|
||||
/// classpath and the JDK of the module at `module` (absolute, or relative to the project root).
|
||||
/// A module with Kotlin / Groovy / Scala sources is built by its build system, whose class directories come first.
|
||||
@@ -19,8 +20,9 @@ pub async fn java_resolve_launch(
|
||||
module: PathBuf,
|
||||
test: bool,
|
||||
build: bool,
|
||||
request: RequestId,
|
||||
) -> IdeResult<JavaLaunchInfo> {
|
||||
ide_host::ops::java::java_resolve_launch(&state.host, window.label(), module, test, build).await
|
||||
ide_host::ops::java::java_resolve_launch(&state.host, window.label(), module, test, build, request).await
|
||||
}
|
||||
|
||||
/// Port of java-debug's DAP server inside the jdtls serving `module` (started on demand).
|
||||
|
||||
@@ -606,11 +606,12 @@ export const commands = {
|
||||
*/
|
||||
buildRun: (kind: BuildKind, file: string | null, request: RequestId, clear: string[], onEvent: Channel<BuildEvent>) => typedError<BuildResult, IdeError>(__TAURI_INVOKE("build_run", { kind, file, request, clear, onEvent })),
|
||||
/**
|
||||
* Cancellable with `cancel_request(request)`.
|
||||
* Builds the workspace (when `build`), then resolves the runtime (or test)
|
||||
* classpath and the JDK of the module at `module` (absolute, or relative to the project root).
|
||||
* A module with Kotlin / Groovy / Scala sources is built by its build system, whose class directories come first.
|
||||
*/
|
||||
javaResolveLaunch: (module: string, test: boolean, build: boolean) => typedError<JavaLaunchInfo, IdeError>(__TAURI_INVOKE("java_resolve_launch", { module, test, build })),
|
||||
javaResolveLaunch: (module: string, test: boolean, build: boolean, request: RequestId) => typedError<JavaLaunchInfo, IdeError>(__TAURI_INVOKE("java_resolve_launch", { module, test, build, request })),
|
||||
/** Port of java-debug's DAP server inside the jdtls serving `module` (started on demand). */
|
||||
javaDebugServer: (module: string) => typedError<number, IdeError>(__TAURI_INVOKE("java_debug_server", { module })),
|
||||
/** Incremental build of the jdtls workspace serving `module` (e.g. before HotSwap). */
|
||||
@@ -3642,6 +3643,8 @@ export type JavaLaunchInfo = {
|
||||
projectRoot: IpcPath | null,
|
||||
classPaths: string[],
|
||||
modulePaths: string[],
|
||||
/** Path list separator of the host that runs the JVM. */
|
||||
pathListSeparator: string,
|
||||
/** JDK home jdtls compiles the project against. */
|
||||
javaHome: IpcPath | null,
|
||||
/** The `java` launcher to use (filled in by the caller from the installed JDKs). */
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
// From @codemirror/lang-angular 0.1.4 (MIT, see LICENSE). Changed by OpenIDEA:
|
||||
// control-flow blocks (`@if`, `@for`, `@switch`, `@defer`, ...) and `@let`
|
||||
// declarations in text, key and animation event names (`(keydown.enter)`,
|
||||
// `(@fade.done)`) and animation bindings (`[@fade]`). Regenerate with
|
||||
// `(@fade.done)`), animation bindings (`[@fade]`) and structural directives'
|
||||
// microsyntax (`*ngFor="let item of items; index as i"`). Regenerate with
|
||||
// `pnpm gen:angular-grammar`.
|
||||
|
||||
@top Content {
|
||||
@@ -22,12 +23,29 @@
|
||||
// `class.active`, `keydown.enter`, and animations' `@fade`, `@fade.done`.
|
||||
bindingName { "@"? Identifier ("." Identifier)* }
|
||||
|
||||
// A structural directive's value: an expression, then `let` declarations,
|
||||
// `as` aliases and keyed expressions (`of items`, `trackBy: byId`). A key's
|
||||
// expression is optional, like Angular's at the end and before `let`.
|
||||
@top Microsyntax {
|
||||
(BindingExpression alias?)? (binding | ";" | ",")*
|
||||
}
|
||||
|
||||
binding {
|
||||
reserved<"let"> VariableDefinition (Is VariableName)? |
|
||||
VariableName alias |
|
||||
BindingKey (":"? BindingExpression alias?)?
|
||||
}
|
||||
|
||||
alias { reserved<"as"> VariableDefinition }
|
||||
|
||||
BindingKey { jsIdentifier }
|
||||
|
||||
// The header of a block, up to its `{`: its body and `}` are content and
|
||||
// HTML elements around it. Both braces are a `Brace`, which CodeMirror
|
||||
// matches like plain text.
|
||||
Block {
|
||||
"@if" BlockParameters<Expression (";" kw<"as"> VariableDefinition)?> Brace |
|
||||
"@else" (kw<"if"> BlockParameters<Expression (";" kw<"as"> VariableDefinition)?>)? Brace |
|
||||
"@if" BlockParameters<Expression (";" alias)?> Brace |
|
||||
"@else" (kw<"if"> BlockParameters<Expression (";" alias)?>)? Brace |
|
||||
"@for" BlockParameters<VariableDefinition kw<"of"> Expression (";" forOption?)*> Brace |
|
||||
("@switch" | "@case") BlockParameters<Expression> Brace |
|
||||
("@default" | "@empty" | "@error") Brace |
|
||||
@@ -41,7 +59,7 @@
|
||||
|
||||
forOption {
|
||||
kw<"track"> Expression |
|
||||
kw<"let"> ForAlias ("," ForAlias)*
|
||||
reserved<"let"> ForAlias ("," ForAlias)*
|
||||
}
|
||||
|
||||
ForAlias { VariableDefinition Is VariableName }
|
||||
@@ -63,7 +81,12 @@
|
||||
|
||||
TriggerName { jsIdentifier }
|
||||
|
||||
kw<term> { @specialize[@name={term}]<jsIdentifier, term> }
|
||||
// Keywords that are also names where a keyword can't be (`@if (x; as
|
||||
// after)`). `let` and `as` never are: in microsyntax, `let x` and `as x`
|
||||
// would also read as a key and its expression.
|
||||
kw<term> { @extend[@name={term}]<jsIdentifier, term> }
|
||||
|
||||
reserved<term> { @specialize[@name={term}]<jsIdentifier, term> }
|
||||
}
|
||||
|
||||
AttributeValue[isolate] {
|
||||
@@ -86,7 +109,7 @@ Interpolation[isolate] {
|
||||
|
||||
@external tokens time from "./tokens" { Time }
|
||||
|
||||
@external tokens expression from "./tokens" { Expression }
|
||||
@external tokens expression from "./tokens" { Expression, BindingExpression }
|
||||
|
||||
@external tokens attrSingle from "./tokens" { attributeContentSingle }
|
||||
@external tokens attrDouble from "./tokens" { attributeContentDouble }
|
||||
@@ -101,7 +124,8 @@ Interpolation[isolate] {
|
||||
|
||||
InterpolationContent { (![}] | "}" ![}]) InterpolationContent? }
|
||||
|
||||
Identifier { (":" | "-" | @asciiLetter | @digit | "_" | $[À-\u{EFFFF}])+ }
|
||||
// `%` for unit bindings: `[style.width.%]`.
|
||||
Identifier { (":" | "-" | "%" | @asciiLetter | @digit | "_" | $[À-\u{EFFFF}])+ }
|
||||
|
||||
jsIdentifier {
|
||||
(@asciiLetter | "_" | "$" | $[À-\u{EFFFF}]) (@asciiLetter | @digit | "_" | "$" | $[À-\u{EFFFF}])*
|
||||
@@ -112,7 +136,7 @@ Interpolation[isolate] {
|
||||
Is { "=" }
|
||||
|
||||
"{{" "}}" "[" "]" "(" ")"
|
||||
"*" "#" "@" ";" ","
|
||||
"*" "#" "@" ";" "," ":"
|
||||
|
||||
"@if" "@else" "@for" "@empty" "@switch" "@case" "@default"
|
||||
"@defer" "@placeholder" "@loading" "@error" "@let"
|
||||
|
||||
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { ensureSyntaxTree, matchBrackets } from "@codemirror/language";
|
||||
import { ensureSyntaxTree, foldable, matchBrackets } from "@codemirror/language";
|
||||
import { NodeProp, type Tree } from "@lezer/common";
|
||||
import { buildParserFile } from "@lezer/generator";
|
||||
import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight";
|
||||
@@ -200,12 +200,57 @@ describe("Angular templates", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("highlights key and animation binding names", () => {
|
||||
const doc = `<input (keydown.enter)="save()" (window:resize)="fit()" [@fade]="s" (@fade.done)="end()">`;
|
||||
it("folds a block from its `{` to its `}`", () => {
|
||||
const doc = [
|
||||
"@if (a && b) {",
|
||||
" <p>{{ x }}</p>",
|
||||
"} @else if (c) {",
|
||||
" <ul>",
|
||||
" @for (i of is; track i) {",
|
||||
" <li>{ i }</li>",
|
||||
" }",
|
||||
" </ul>",
|
||||
"} @else {",
|
||||
" none",
|
||||
"}",
|
||||
"@switch (m) {",
|
||||
" @case (1) { one }",
|
||||
" @default {",
|
||||
" other",
|
||||
" }",
|
||||
"}",
|
||||
].join("\n");
|
||||
const state = EditorState.create({ doc, extensions: angular() });
|
||||
stateTree(state);
|
||||
const folds = [];
|
||||
for (let n = 1; n <= state.doc.lines; n++) {
|
||||
const line = state.doc.line(n);
|
||||
const fold = foldable(state, line.from, line.to);
|
||||
if (fold)
|
||||
folds.push([
|
||||
n,
|
||||
state.doc.lineAt(fold.to).number,
|
||||
state.sliceDoc(fold.from - 1, fold.from),
|
||||
state.sliceDoc(fold.to, fold.to + 1),
|
||||
]);
|
||||
}
|
||||
expect(folds).toEqual([
|
||||
[1, 3, "{", "}"],
|
||||
[3, 9, "{", "}"],
|
||||
// The element's own fold.
|
||||
[4, 8, ">", "<"],
|
||||
[5, 7, "{", "}"],
|
||||
[9, 11, "{", "}"],
|
||||
[12, 17, "{", "}"],
|
||||
[14, 16, "{", "}"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("highlights key, unit and animation binding names", () => {
|
||||
const doc = `<input (keydown.enter)="save()" (window:resize)="fit()" [style.width.%]="w" [@fade]="s" (@fade.done)="end()">`;
|
||||
expect(tokens(doc)).toEqual([
|
||||
"input:tag",
|
||||
"keydown:event",
|
||||
"enter:event",
|
||||
"keydown.enter:event",
|
||||
"=:op",
|
||||
'":value',
|
||||
"save:call",
|
||||
@@ -215,15 +260,17 @@ describe("Angular templates", () => {
|
||||
'":value',
|
||||
"fit:call",
|
||||
'":value',
|
||||
"@:attr",
|
||||
"fade:attr",
|
||||
"style.width.%:attr",
|
||||
"=:op",
|
||||
'":value',
|
||||
"w:var",
|
||||
'":value',
|
||||
"@fade:attr",
|
||||
"=:op",
|
||||
'":value',
|
||||
"s:var",
|
||||
'":value',
|
||||
"@:event",
|
||||
"fade:event",
|
||||
"done:event",
|
||||
"@fade.done:event",
|
||||
"=:op",
|
||||
'":value',
|
||||
"end:call",
|
||||
@@ -231,6 +278,168 @@ describe("Angular templates", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("highlights structural directives' microsyntax", () => {
|
||||
expect(tokens(`<li *ngFor="let item of items(); index as i; trackBy: byId"></li>`)).toEqual([
|
||||
"li:tag",
|
||||
"*ngFor:keyword",
|
||||
"=:op",
|
||||
'":value',
|
||||
"let:let",
|
||||
"item:def",
|
||||
"of:keyword",
|
||||
"items:call",
|
||||
"index:var",
|
||||
"as:keyword",
|
||||
"i:def",
|
||||
"trackBy:keyword",
|
||||
"byId:var",
|
||||
'":value',
|
||||
"li:tag",
|
||||
]);
|
||||
expect(
|
||||
tokens(
|
||||
`<p *ngIf="user$ | async as user, else loading"></p><b *ngTemplateOutlet="tpl; context: { $implicit: x }"></b>`,
|
||||
),
|
||||
).toEqual([
|
||||
"p:tag",
|
||||
"*ngIf:keyword",
|
||||
"=:op",
|
||||
'":value',
|
||||
"user$:var",
|
||||
"|:op",
|
||||
"async:var",
|
||||
"as:keyword",
|
||||
"user:def",
|
||||
"else:keyword",
|
||||
"loading:var",
|
||||
'":value',
|
||||
"p:tag",
|
||||
"b:tag",
|
||||
"*ngTemplateOutlet:keyword",
|
||||
"=:op",
|
||||
'":value',
|
||||
"tpl:var",
|
||||
"context:keyword",
|
||||
"{:brace",
|
||||
"$implicit:prop",
|
||||
"x:var",
|
||||
"}:brace",
|
||||
'":value',
|
||||
"b:tag",
|
||||
]);
|
||||
expect(tokens(`<i *cdkVirtualFor="let row of rows | slice: 0 : 5; let n = count"></i>`)).toEqual([
|
||||
"i:tag",
|
||||
"*cdkVirtualFor:keyword",
|
||||
"=:op",
|
||||
'":value',
|
||||
"let:let",
|
||||
"row:def",
|
||||
"of:keyword",
|
||||
"rows:var",
|
||||
"|:op",
|
||||
"slice:var",
|
||||
"0:num",
|
||||
"5:num",
|
||||
"let:let",
|
||||
"n:def",
|
||||
"=:op",
|
||||
"count:var",
|
||||
'":value',
|
||||
"i:tag",
|
||||
]);
|
||||
});
|
||||
|
||||
it("ends a directive's expressions at keys without separators", () => {
|
||||
expect(tokens(`<p *ngIf="ok; then yes else no"></p>`)).toEqual([
|
||||
"p:tag",
|
||||
"*ngIf:keyword",
|
||||
"=:op",
|
||||
'":value',
|
||||
"ok:var",
|
||||
"then:keyword",
|
||||
"yes:var",
|
||||
"else:keyword",
|
||||
"no:var",
|
||||
'":value',
|
||||
"p:tag",
|
||||
]);
|
||||
expect(tokens(`<p *ngFor="let a of xs, let i = index"></p>`).slice(4, -2)).toEqual([
|
||||
"let:let",
|
||||
"a:def",
|
||||
"of:keyword",
|
||||
"xs:var",
|
||||
"let:let",
|
||||
"i:def",
|
||||
"=:op",
|
||||
"index:var",
|
||||
]);
|
||||
expect(tokens(`<p *ngFor="let a of xs index as i"></p>`).slice(4, -2)).toEqual([
|
||||
"let:let",
|
||||
"a:def",
|
||||
"of:keyword",
|
||||
"xs:var",
|
||||
"index:var",
|
||||
"as:keyword",
|
||||
"i:def",
|
||||
]);
|
||||
});
|
||||
|
||||
it("parses directive values Angular accepts without errors", () => {
|
||||
const values = [
|
||||
"let a of xs; let i = index; trackBy: byId",
|
||||
"ok; then yes else no",
|
||||
"'a' in obj && x?.y as z; else no",
|
||||
"x, foo",
|
||||
"x; foo let y = z",
|
||||
"tpl; context: { a: [1, 2], b: f(c, d) }",
|
||||
];
|
||||
for (const value of values) {
|
||||
const errors: string[] = [];
|
||||
angularLanguage.parser.parse(`<p *dir="${value}"></p>`).iterate({
|
||||
enter: (node) => void (node.type.isError && errors.push(node.name)),
|
||||
});
|
||||
expect(errors, value).toEqual([]);
|
||||
}
|
||||
});
|
||||
|
||||
it("styles all of a binding's name and value", () => {
|
||||
const doc = `<p *ngIf="a?.b as c" [class.on]="d?.e()" (keydown.shift.enter)="f?.(1)" #ref></p>`;
|
||||
const tree = angularLanguage.parser.parse(doc);
|
||||
const styled = new Uint8Array(doc.length);
|
||||
highlightTree(tree, { style: (tags) => (tags.length ? "styled" : null) }, (from, to) => styled.fill(1, from, to));
|
||||
expect([...doc].filter((ch, i) => !styled[i] && ch != " ").join("")).toBe("");
|
||||
});
|
||||
|
||||
it("parses block keywords as the names they can also be", () => {
|
||||
expect(tokens(`@if (change.after; as after) {} @loading (after 100ms; minimum 1s) {}`)).toEqual([
|
||||
"@if:control",
|
||||
"change:var",
|
||||
".:op",
|
||||
"after:prop",
|
||||
"as:keyword",
|
||||
"after:def",
|
||||
"{:brace",
|
||||
"}:brace",
|
||||
"@loading:keyword",
|
||||
"after:keyword",
|
||||
"100ms:num",
|
||||
"minimum:keyword",
|
||||
"1s:num",
|
||||
"{:brace",
|
||||
"}:brace",
|
||||
]);
|
||||
expect(tokens(`@for (on of track; track on) {}`)).toEqual([
|
||||
"@for:control",
|
||||
"on:def",
|
||||
"of:keyword",
|
||||
"track:var",
|
||||
"track:keyword",
|
||||
"on:var",
|
||||
"{:brace",
|
||||
"}:brace",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps HTML's script, style and event handler attribute languages", () => {
|
||||
expect(tokens(`<script>let a = 1;</script><style>p { color: red }</style><b onclick="go(1)">x</b>`)).toEqual([
|
||||
"script:tag",
|
||||
|
||||
@@ -2,17 +2,20 @@
|
||||
* Angular template language: HTML whose text and binding attributes are
|
||||
* Angular syntax (`angular.grammar`), expressions parsed as JavaScript. From
|
||||
* @codemirror/lang-angular 0.1.4 (MIT, see LICENSE); changed by OpenIDEA:
|
||||
* control-flow blocks, `@let`, key and animation binding names, and runs of
|
||||
* text that entities split (`a && b`) parsed as one.
|
||||
* control-flow blocks, `@let`, key and animation binding names, structural
|
||||
* directives' microsyntax, runs of text that entities split (`a && b`)
|
||||
* parsed as one, and folding blocks.
|
||||
*/
|
||||
import { LRLanguage, LanguageSupport } from "@codemirror/language";
|
||||
import { LRLanguage, LanguageSupport, foldService, matchBrackets, syntaxTree } from "@codemirror/language";
|
||||
import { html } from "@codemirror/lang-html";
|
||||
import { javascriptLanguage } from "@codemirror/lang-javascript";
|
||||
import { styleTags, tags as t } from "@lezer/highlight";
|
||||
import { IterMode, parseMixed, type Input, type NestedParse, type SyntaxNode, type SyntaxNodeRef } from "@lezer/common";
|
||||
import { parser } from "./parser";
|
||||
|
||||
const exprParser = javascriptLanguage.parser.configure({ top: "SingleExpression" });
|
||||
// @lezer/javascript styles `.` as a deref operator, but not `?.`.
|
||||
const jsParser = javascriptLanguage.parser.configure({ props: [styleTags({ "?.": t.derefOperator })] });
|
||||
const exprParser = jsParser.configure({ top: "SingleExpression" });
|
||||
|
||||
const baseParser = parser.configure({
|
||||
props: [
|
||||
@@ -23,16 +26,17 @@ const baseParser = parser.configure({
|
||||
"AttributeValue ExpressionAttributeValue StatementAttributeValue": t.attributeValue,
|
||||
Entity: t.character,
|
||||
InvalidEntity: t.invalid,
|
||||
"BoundAttributeName/Identifier BoundAttributeName/@": t.attributeName,
|
||||
"EventName/Identifier EventName/@": t.special(t.attributeName),
|
||||
// A name's own style covers the `.`s between its parts.
|
||||
"BoundAttributeName BoundAttributeName/Identifier BoundAttributeName/@": t.attributeName,
|
||||
"EventName EventName/Identifier EventName/@": t.special(t.attributeName),
|
||||
"ReferenceName/Identifier": t.variableName,
|
||||
"DirectiveName/Identifier": t.keyword,
|
||||
'DirectiveName DirectiveName/Identifier DirectiveName/"*"': t.keyword,
|
||||
"{{ }}": t.special(t.brace),
|
||||
"( )": t.paren,
|
||||
"[ ]": t.bracket,
|
||||
"# '*'": t.punctuation,
|
||||
"# :": t.punctuation,
|
||||
"@if @else @for @empty @switch @case @default if": t.controlKeyword,
|
||||
"@defer @placeholder @loading @error of as track on when prefetch hydrate never minimum after TriggerName":
|
||||
"@defer @placeholder @loading @error of as track on when prefetch hydrate never minimum after TriggerName BindingKey":
|
||||
t.keyword,
|
||||
"@let let": t.definitionKeyword,
|
||||
Brace: t.brace,
|
||||
@@ -45,12 +49,16 @@ const baseParser = parser.configure({
|
||||
});
|
||||
|
||||
const exprMixed = { parser: exprParser },
|
||||
statementMixed = { parser: javascriptLanguage.parser };
|
||||
statementMixed = { parser: jsParser };
|
||||
|
||||
const EXPRESSIONS = new Set(["InterpolationContent", "Expression", "BindingExpression"]);
|
||||
|
||||
const textParser = baseParser.configure({
|
||||
wrap: parseMixed((node) => (node.name == "InterpolationContent" || node.name == "Expression" ? exprMixed : null)),
|
||||
wrap: parseMixed((node) => (EXPRESSIONS.has(node.name) ? exprMixed : null)),
|
||||
});
|
||||
|
||||
const microsyntaxMixed = { parser: textParser.configure({ top: "Microsyntax" }) };
|
||||
|
||||
// To reuse old inner trees, parseMixed takes those that the node at a mount's
|
||||
// start and its ancestors had with the same parser. So each kind of mount has
|
||||
// its own instance: the document's runs would take those of an element at its
|
||||
@@ -58,15 +66,20 @@ const textParser = baseParser.configure({
|
||||
const runsParser = textParser.configure({}),
|
||||
documentRunsParser = textParser.configure({});
|
||||
|
||||
/** The parser of an attribute's interpolation or bound value (`node`). */
|
||||
function attrValueMixed(node: SyntaxNode) {
|
||||
const value = node.parent;
|
||||
if (value?.name != "StatementAttributeValue") return exprMixed;
|
||||
return value.parent?.firstChild?.name == "DirectiveName" ? microsyntaxMixed : statementMixed;
|
||||
}
|
||||
|
||||
const attrParser = baseParser.configure({
|
||||
wrap: parseMixed((node) =>
|
||||
node.name == "InterpolationContent"
|
||||
? exprMixed
|
||||
: node.name != "AttributeInterpolation"
|
||||
? null
|
||||
: node.node.parent?.name == "StatementAttributeValue"
|
||||
? statementMixed
|
||||
: exprMixed,
|
||||
: node.name == "AttributeInterpolation"
|
||||
? attrValueMixed(node.node)
|
||||
: null,
|
||||
),
|
||||
top: "Attribute",
|
||||
});
|
||||
@@ -124,9 +137,27 @@ function mixAngular(node: SyntaxNodeRef, input: Input): NestedParse | null {
|
||||
|
||||
export const angularLanguage = (baseHTML.language as LRLanguage).configure({ wrap: parseMixed(mixAngular) }, "angular");
|
||||
|
||||
/**
|
||||
* The body of the first block opened on a line and closed on a later one, up
|
||||
* to its `}`, which stays visible: `@if (a) {…}`, `} @else {…}`. Its braces
|
||||
* pair like plain text, across elements.
|
||||
*/
|
||||
const blockFolding = foldService.of((state, lineStart, lineEnd) => {
|
||||
const text = state.sliceDoc(lineStart, lineEnd);
|
||||
const tree = syntaxTree(state);
|
||||
for (let i = text.indexOf("{"); i >= 0; i = text.indexOf("{", i + 1)) {
|
||||
const open = tree.resolveInner(lineStart + i, 1);
|
||||
if (open.name != "Brace" || open.parent?.name != "Block") continue;
|
||||
const match = matchBrackets(state, open.from, 1, { brackets: "{}", maxScanDistance: state.doc.length });
|
||||
if (match?.matched && match.end && match.end.from > lineEnd) return { from: open.to, to: match.end.from };
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
export function angular(): LanguageSupport {
|
||||
return new LanguageSupport(angularLanguage, [
|
||||
baseHTML.support,
|
||||
blockFolding,
|
||||
baseHTML.language.data.of({
|
||||
closeBrackets: { brackets: ["[", "{", '"'] },
|
||||
indentOnInput: /^\s*[}\]]$/,
|
||||
|
||||
@@ -4,35 +4,38 @@ export const
|
||||
Brace = 2,
|
||||
Time = 3,
|
||||
Expression = 4,
|
||||
attributeContentSingle = 80,
|
||||
attributeContentDouble = 81,
|
||||
scriptAttributeContentSingle = 82,
|
||||
scriptAttributeContentDouble = 83,
|
||||
Content = 5,
|
||||
Interpolation = 8,
|
||||
InterpolationContent = 9,
|
||||
Entity = 10,
|
||||
InvalidEntity = 11,
|
||||
Block = 12,
|
||||
as = 18,
|
||||
VariableDefinition = 19,
|
||||
_if = 21,
|
||||
of = 24,
|
||||
track = 25,
|
||||
_let = 26,
|
||||
ForAlias = 27,
|
||||
Is = 28,
|
||||
VariableName = 29,
|
||||
prefetch = 39,
|
||||
hydrate = 40,
|
||||
on = 41,
|
||||
DeferTrigger = 42,
|
||||
TriggerName = 43,
|
||||
when = 44,
|
||||
never = 45,
|
||||
minimum = 49,
|
||||
after = 50,
|
||||
LetDeclaration = 51,
|
||||
Attribute = 53,
|
||||
Identifier = 57,
|
||||
AttributeValue = 69
|
||||
BindingExpression = 5,
|
||||
attributeContentSingle = 85,
|
||||
attributeContentDouble = 86,
|
||||
scriptAttributeContentSingle = 87,
|
||||
scriptAttributeContentDouble = 88,
|
||||
Content = 6,
|
||||
Interpolation = 9,
|
||||
InterpolationContent = 10,
|
||||
Entity = 11,
|
||||
InvalidEntity = 12,
|
||||
Block = 13,
|
||||
as = 19,
|
||||
VariableDefinition = 20,
|
||||
_if = 22,
|
||||
of = 25,
|
||||
track = 26,
|
||||
_let = 27,
|
||||
ForAlias = 28,
|
||||
Is = 29,
|
||||
VariableName = 30,
|
||||
prefetch = 40,
|
||||
hydrate = 41,
|
||||
on = 42,
|
||||
DeferTrigger = 43,
|
||||
TriggerName = 44,
|
||||
when = 45,
|
||||
never = 46,
|
||||
minimum = 50,
|
||||
after = 51,
|
||||
LetDeclaration = 52,
|
||||
Attribute = 54,
|
||||
Identifier = 58,
|
||||
AttributeValue = 70,
|
||||
Microsyntax = 71,
|
||||
BindingKey = 72
|
||||
@@ -1,24 +1,24 @@
|
||||
// This file was generated by lezer-generator. You probably shouldn't edit it.
|
||||
import {LRParser} from "@lezer/lr"
|
||||
import {text, brace, time, expression, attrSingle, attrDouble, scriptAttrSingle, scriptAttrDouble} from "./tokens"
|
||||
const spec_jsIdentifier = {__proto__:null,as:36, if:42, of:48, track:50, let:52, prefetch:78, hydrate:80, on:82, when:88, never:90, minimum:98, after:100}
|
||||
const spec_jsIdentifier = {__proto__:null,as:38, if:45, of:51, track:53, let:54, prefetch:81, hydrate:83, on:85, when:91, never:93, minimum:101, after:103}
|
||||
export const parser = LRParser.deserialize({
|
||||
version: 14,
|
||||
states: "4jOVO&mOOO!^Q&jOOO!oO,UO'#CdO!wQ&jO'#ChO!|Q7^O'#ChO#UQ&jO'#ChO#ZQ&jO'#ChO#`Q&lO'#ChO#eQ&lO'#ChO#mQ&lO'#ChO#uQ7[O'#DaOOOR'#Dt'#DtQVO&mOOO#zQMhO'#DdO$VQ&jO'#DiO#}QMhO'#DnO$[Q&jO'#DoOOQO'#Dr'#Dr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#P#YO~OVQOY#ZOZ#ZO!r#ZO#Q#YO~Ob#]O~OS#^O~O^!lXa!lX~P%UO^#aOa!pO~O_#bO^zXazXnzX~On#cO^!zaa!za~OS#fO~O!R![O!S![O^!mXa!mX~O^#iOa!yO~Oa#jO~O!}!^O![!|i^!|i~O![#kO~O#P#lO~O#Q#lO~OVQOY#WOZ#WO!s#WO#P#nO~OVQOY#ZOZ#ZO!r#ZO#Q#nO~O^#sOa#qO~OR#uOS#uO^#tO~On#cO^!zia!zi~O^#yO~Oi#{Oj#|O^!iXa!iX~O^$OOa#qO~O^$PO~On#cO^!zqa!zq~OS$QO~Ol$TO~On$UO^!yaa!ya~O!x$WO~On$UO^!yia!yi~O",
|
||||
goto: "'S#PPPPPPPPP#QPPP#^PPP#bPP#hPPP#uPPP#xP$OPPP$RPPPP$UPPP$X$bPPPP$gPP#^PP$jPPPP$jP$m$p$s$v$vP$y$|%P%S%Y%`%f%p%v%|&W&^PPPPPPPP&d&g&m&sP&|SZO[S#W!i#XT#Z!j#[TZO[QhRR!PjQpYQ!QkQ#p#]T$R#|$URhTQ$S#|R$Y$UR$X$TRhURhWQ!u!UQ#e!wR#v#cV!t!U!w#cRhXRbPR!gyR#T!dR#V!eRcPR!gzRdPR!g{Q[ORq[Q#r#^R#}#rQ$V$SR$Z$VQ#d!uS#w#d#xR#x#eQ!q!TR#`!qQ!z!ZR#h!zQ!_rS#P!_#QR#Q!`Q#X!iR#m#XQ#[!jR#o#[R#z#qQ!TmR#_!pQ!ZnR#g!yQt]Qw_R!buQ!fyR!hz",
|
||||
nodeNames: "⚠ Text Brace Time Expression Content }} {{ Interpolation InterpolationContent Entity InvalidEntity Block @if ) ( BlockParameters ; as VariableDefinition @else if @for BlockParameters of track let ForAlias Is VariableName , @switch @case BlockParameters @default @empty @error @defer BlockParameters prefetch hydrate on DeferTrigger TriggerName when never @placeholder @loading BlockParameters minimum after LetDeclaration @let Attribute BoundAttributeName [ @ Identifier ] ReferenceName # ExpressionAttributeValue A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mXb!mX~O_$gOb$YO~O_$hO~Oo#yO_#Pqb#Pq~OS$iO~Om$lO~Oo$mO_#Oab#Oa~Oo$mO_#Oib#Oi~O",
|
||||
goto: "(Y#XPPPPPPPPP#YPPP#fPPP#jPP#pPPP$^PPP$aP$gPPP$sPPPP$vPPP$y%SPPPP%XPP#fPP%[PPPP%[P%_%b%e%h%hP%k%n%qP%tP%z&Q&W&^&h&n&t'O'U'[PPPPPPPP'd'g'm'sP'|PP(SS[O]S#k!w#lT#n!x#oT[O]QpSR!_rQxZQ!YkQ!`sQ!{!XQ!}!ZQ#p!yQ$W#qQ$X#sT$j$e$mRpUQ$k$eR$p$mWlQij!{Q#p!|R$o$lRpVRpXQ#Y!dQ#{#[R$_#yV#X!d#[#yRpYRcPR!u!RR#h!rR#j!sRdPR!u!SRePR!u!TXgQij!{Q]ORy]Q$Z#tR$f$ZQ$n$kR$q$nQ#z#YS$`#z$aR$a#{Q#U!cR#v#UQ#_!iR$O#_Q!mzS#d!m#eR#e!nQ#l!wR$T#lQ#o!xR$V#oUiQj!{R!WiR$c$YQ!cuR#u#TQ!ivR#}#^Q|^Q!P`R!p}Q!t!RR!v!SXhQij!{",
|
||||
nodeNames: "⚠ Text Brace Time Expression BindingExpression Content }} {{ Interpolation InterpolationContent Entity InvalidEntity Block @if ) ( BlockParameters ; as VariableDefinition @else if @for BlockParameters of track let ForAlias Is VariableName , @switch @case BlockParameters @default @empty @error @defer BlockParameters prefetch hydrate on DeferTrigger TriggerName when never @placeholder @loading BlockParameters minimum after LetDeclaration @let Attribute BoundAttributeName [ @ Identifier ] ReferenceName # ExpressionAttributeValue AttributeInterpolation AttributeInterpolation EventName DirectiveName * StatementAttributeValue AttributeName AttributeValue Microsyntax BindingKey :",
|
||||
maxTerm: 100,
|
||||
nodeProps: [
|
||||
["openedBy", 6,"{{",14,"("],
|
||||
["closedBy", 7,"}}",15,")"],
|
||||
["isolate", -4,8,61,67,69,""]
|
||||
["openedBy", 7,"{{",15,"("],
|
||||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$s<%lO$OTNRVYSO#X$O#X#YNh#Y#q$O#q#r$d#r;'S$O;'S;=`$s<%lO$OTNmVYSO#f$O#f#g! S#g#q$O#q#r$d#r;'S$O;'S;=`$s<%lO$OT! ZT!PPYSO#q$O#q#r$d#r;'S$O;'S;=`$s<%lO$OT! oVYSO#k$O#k#l!!U#l#q$O#q#r$d#r;'S$O;'S;=`$s<%lO$OT!!ZVYSO#]$O#]#^!!p#^#q$O#q#r$d#r;'S$O;'S;=`$s<%lO$OT!!uVYSO#h$O#h#i!#[#i#q$O#q#r$d#r;'S$O;'S;=`$s<%lO$OT!#aVYSO#V$O#V#W!#v#W#q$O#q#r$d#r;'S$O;'S;=`$s<%lO$OT!#{VYSO#[$O#[#]!$b#]#q$O#q#r$d#r;'S$O;'S;=`$s<%lO$OT!$iTpPYSO#q$O#q#r$d#r;'S$O;'S;=`$s<%lO$O_!%ReROV~",
|
||||
tokenizers: [text, brace, time, expression, attrSingle, attrDouble, scriptAttrSingle, scriptAttrDouble, 0, 1, 2, 3],
|
||||
topRules: {"Content":[0,5],"Attribute":[1,53]},
|
||||
specialized: [{term: 86, get: (value: keyof typeof spec_jsIdentifier) => spec_jsIdentifier[value] || -1}],
|
||||
topRules: {"Content":[0,6],"Attribute":[1,54],"Microsyntax":[2,71]},
|
||||
specialized: [{term: 91, get: (value: keyof typeof spec_jsIdentifier) => spec_jsIdentifier[value] || -1}],
|
||||
tokenPrec: 0
|
||||
})
|
||||
@@ -1,10 +1,11 @@
|
||||
/**
|
||||
* External tokens of `angular.grammar`. From @codemirror/lang-angular 0.1.4
|
||||
* (MIT, see LICENSE); text stopping at blocks, and the block tokens, added by
|
||||
* OpenIDEA.
|
||||
* (MIT, see LICENSE); text stopping at blocks, the block tokens and
|
||||
* microsyntax expressions added by OpenIDEA.
|
||||
*/
|
||||
import { ExternalTokenizer, type InputStream } from "@lezer/lr";
|
||||
import {
|
||||
BindingExpression,
|
||||
Brace,
|
||||
Expression,
|
||||
Text,
|
||||
@@ -22,7 +23,9 @@ const NEWLINE = 10,
|
||||
SINGLE_QUOTE = 39,
|
||||
PAREN_L = 40,
|
||||
PAREN_R = 41,
|
||||
COMMA = 44,
|
||||
DOT = 46,
|
||||
COLON = 58,
|
||||
SEMICOLON = 59,
|
||||
AT = 64,
|
||||
BRACKET_L = 91,
|
||||
@@ -33,6 +36,12 @@ const NEWLINE = 10,
|
||||
BRACE_L = 123,
|
||||
BRACE_R = 125;
|
||||
|
||||
/** Characters ending an operand outside an identifier: brackets and quotes. */
|
||||
const CLOSERS = new Set([PAREN_R, BRACKET_R, BRACE_R, SINGLE_QUOTE, DOUBLE_QUOTE, BACKTICK]);
|
||||
|
||||
/** Words that are operators rather than operands, unless after a `.`. */
|
||||
const OPERATORS = new Set(["in", "instanceof", "new", "typeof", "void"]);
|
||||
|
||||
const BLOCKS = new Set([
|
||||
"if",
|
||||
"else",
|
||||
@@ -130,44 +139,75 @@ function blockOnNextLine(input: InputStream): boolean {
|
||||
return input.peek(i) == AT && blockAt(input, i);
|
||||
}
|
||||
|
||||
/** The word at offset `i`: `as` in `index as i`, `let` in `let x`. */
|
||||
function wordAt(input: InputStream, i: number): string {
|
||||
let word = "";
|
||||
for (let ch = input.peek(i); isIdentifierChar(ch); ch = input.peek(++i)) word += String.fromCharCode(ch);
|
||||
return word;
|
||||
}
|
||||
|
||||
/**
|
||||
* A block parameter's or `@let`'s expression: up to a `;` or a closing bracket
|
||||
* outside brackets and strings, without the spaces around it. An unterminated
|
||||
* one (being typed) also ends before a child element or comment and before a
|
||||
* line starting with a block, so the blocks after it keep their highlighting.
|
||||
* A structural directive's (`BindingExpression`) also ends at a `,`, an `as`
|
||||
* alias or a word after an operand, the next key (`cond; then a else b`), and
|
||||
* is not one starting with `let`, `as` or a key's `:`.
|
||||
*/
|
||||
export const expression = new ExternalTokenizer((input) => {
|
||||
if (isSpace(input.next)) return;
|
||||
const start = input.pos;
|
||||
let depth = 0,
|
||||
quote = 0,
|
||||
escaped = false,
|
||||
end = start;
|
||||
for (;;) {
|
||||
const ch = input.next;
|
||||
if (ch < 0 || (ch == NEWLINE && blockOnNextLine(input))) break;
|
||||
if (escaped) {
|
||||
escaped = false;
|
||||
} else if (quote) {
|
||||
// Strings but template literals end with their line, like in JavaScript.
|
||||
if (ch == quote || (ch == NEWLINE && quote != BACKTICK)) quote = 0;
|
||||
else escaped = ch == BACKSLASH;
|
||||
} else if (ch == SINGLE_QUOTE || ch == DOUBLE_QUOTE || ch == BACKTICK) {
|
||||
quote = ch;
|
||||
} else if (ch == PAREN_L || ch == BRACKET_L || ch == BRACE_L) {
|
||||
depth++;
|
||||
} else if (ch == PAREN_R || ch == BRACKET_R || ch == BRACE_R) {
|
||||
if (depth == 0) break;
|
||||
depth--;
|
||||
} else if (ch == SEMICOLON && depth == 0) {
|
||||
break;
|
||||
export const expression = new ExternalTokenizer(
|
||||
(input, stack) => {
|
||||
if (isSpace(input.next)) return;
|
||||
const binding = stack.canShift(BindingExpression);
|
||||
if (binding && (input.next == COLON || /^(let|as)$/.test(wordAt(input, 0)))) return;
|
||||
const start = input.pos;
|
||||
let depth = 0,
|
||||
quote = 0,
|
||||
escaped = false,
|
||||
end = start,
|
||||
prev = -1,
|
||||
// In a word of `OPERATORS`.
|
||||
operator = false,
|
||||
// The last character outside spaces ends an operand: `a`, `)`, `'`.
|
||||
operand = false;
|
||||
for (;;) {
|
||||
const ch = input.next;
|
||||
if (ch < 0 || (ch == NEWLINE && blockOnNextLine(input))) break;
|
||||
if (escaped) {
|
||||
escaped = false;
|
||||
} else if (quote) {
|
||||
// Strings but template literals end with their line, like in JavaScript.
|
||||
if (ch == quote || (ch == NEWLINE && quote != BACKTICK)) quote = 0;
|
||||
else escaped = ch == BACKSLASH;
|
||||
} else if (ch == SINGLE_QUOTE || ch == DOUBLE_QUOTE || ch == BACKTICK) {
|
||||
quote = ch;
|
||||
} else if (ch == PAREN_L || ch == BRACKET_L || ch == BRACE_L) {
|
||||
depth++;
|
||||
} else if (ch == PAREN_R || ch == BRACKET_R || ch == BRACE_R) {
|
||||
if (depth == 0) break;
|
||||
depth--;
|
||||
} else if (depth == 0 && (ch == SEMICOLON || (binding && ch == COMMA))) {
|
||||
break;
|
||||
} else if (binding && isIdentifierStart(ch) && !isIdentifierChar(prev)) {
|
||||
const word = wordAt(input, 0);
|
||||
// After a space, an alias or, after an operand, the next binding's
|
||||
// key: `user$ | async as user`, `items index as i`.
|
||||
if (depth == 0 && end < input.pos && (word == "as" || (operand && !OPERATORS.has(word)))) break;
|
||||
operator = prev != DOT && OPERATORS.has(word);
|
||||
}
|
||||
if (!isSpace(ch)) {
|
||||
end = input.pos + 1;
|
||||
operand = !quote && (CLOSERS.has(ch) || (isIdentifierChar(ch) && !operator));
|
||||
}
|
||||
if (!isIdentifierChar(ch)) operator = false;
|
||||
prev = ch;
|
||||
if (!step(input)) break;
|
||||
}
|
||||
if (!isSpace(ch)) end = input.pos + 1;
|
||||
if (!step(input)) break;
|
||||
}
|
||||
// `end` is a document position: the stream skips the ranges' gaps.
|
||||
if (end > start) input.acceptTokenTo(Expression, end);
|
||||
});
|
||||
// `end` is a document position: the stream skips the ranges' gaps.
|
||||
if (end > start) input.acceptTokenTo(binding ? BindingExpression : Expression, end);
|
||||
},
|
||||
{ contextual: true },
|
||||
);
|
||||
|
||||
function attrContent(quote: number, token: number, script: boolean) {
|
||||
return new ExternalTokenizer((input) => {
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight";
|
||||
import { findLanguageDescription, loadSupport } from "./languages";
|
||||
|
||||
describe("language modes", () => {
|
||||
it("styles `?.` like `.` in JavaScript and TypeScript", async () => {
|
||||
const highlighter = tagHighlighter([{ tag: t.derefOperator, class: "deref" }]);
|
||||
for (const [mode, path] of [
|
||||
["JavaScript", "/p/a.js"],
|
||||
["TypeScript", "/p/a.ts"],
|
||||
["JSX", "/p/a.jsx"],
|
||||
["TSX", "/p/a.tsx"],
|
||||
] as const) {
|
||||
const support = await loadSupport(findLanguageDescription(mode, path)!);
|
||||
const doc = "a?.b.c?.();";
|
||||
const derefs: string[] = [];
|
||||
highlightTree(support!.language.parser.parse(doc), highlighter, (from, to) => derefs.push(doc.slice(from, to)));
|
||||
expect(derefs, mode).toEqual(["?.", ".", "?."]);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -200,8 +200,15 @@ const CSS_TAGS: Parameters<typeof styleTags>[0] = {
|
||||
"ClassName IdName PseudoClassName ColorLiteral CallTag": t.tagName,
|
||||
};
|
||||
|
||||
// @lezer/javascript styles `.` as a deref operator, but not `?.`.
|
||||
const JS_TAGS: Parameters<typeof styleTags>[0] = { "?.": t.derefOperator };
|
||||
|
||||
/** Highlighting the stock grammars lack or colour unlike IntelliJ. */
|
||||
const EXTRA_TAGS: Record<string, Parameters<typeof styleTags>[0]> = {
|
||||
JavaScript: JS_TAGS,
|
||||
TypeScript: JS_TAGS,
|
||||
JSX: JS_TAGS,
|
||||
TSX: JS_TAGS,
|
||||
// @lezer/java tags annotations as plain identifiers.
|
||||
Java: { "MarkerAnnotation/Identifier Annotation/Identifier MarkerAnnotation Annotation": t.annotation },
|
||||
CSS: CSS_TAGS,
|
||||
|
||||
@@ -115,6 +115,14 @@ describe("mouse navigation", () => {
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["windows", "linux"] as const)("opens the implementation with Ctrl+Alt+click on %s", async (os) => {
|
||||
usePlatform.setState({ os });
|
||||
useKeymap.setState({ preset: "intellij-windows", overrides: {} });
|
||||
click({ ctrlKey: true, altKey: true });
|
||||
await vi.waitFor(() => expect(openFile).toHaveBeenCalledOnce());
|
||||
expect(lspGoto).toHaveBeenCalledExactlyOnceWith(1, { line: 0, col: 9 }, "implementation");
|
||||
});
|
||||
|
||||
it("does not navigate with Option+Command when the binding is removed", async () => {
|
||||
useKeymap.setState({ overrides: { "navigate.implementation": ["Meta+Alt+B"] } });
|
||||
click({ metaKey: true, altKey: true });
|
||||
|
||||
@@ -24,6 +24,7 @@ vi.mock("@/platform/ipc", async (orig) => {
|
||||
projectRoot: "/p",
|
||||
classPaths: ["/p/target/classes", "/m2/a.jar"],
|
||||
modulePaths: [],
|
||||
pathListSeparator: ":",
|
||||
javaHome: "/jdk21",
|
||||
javaExec: "/jdk21/bin/java",
|
||||
shortenCommandLine,
|
||||
@@ -67,7 +68,7 @@ describe("Java debugging (java-debug through jdtls)", () => {
|
||||
expect(isJavaDebuggable({ ...app, kind: "maven" })).toBe(false);
|
||||
const l = await javaLaunchConfig(app, "/p");
|
||||
expect(invoked).toEqual([
|
||||
["javaResolveLaunch", ["api", false, true]],
|
||||
["javaResolveLaunch", ["api", false, true, expect.any(Number)]],
|
||||
["javaDebugServer", ["api"]],
|
||||
]);
|
||||
expect(l).toMatchObject({ adapter: "java-debug", request: "launch", cwd: "/p/api", args: [], env: { A: "1" } });
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { provideNotificationService } from "@/workbench/contributions";
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
import { registerDebugActions } from "../actions";
|
||||
import { useDebug } from "../state";
|
||||
|
||||
const ipc = vi.hoisted(() => ({
|
||||
javaResolveLaunch: vi.fn(),
|
||||
cancelRequest: vi.fn(async () => undefined),
|
||||
javaDebugServer: vi.fn(async () => ({ status: "ok", data: 5005 })),
|
||||
debugStart: vi.fn(async () => ({ status: "ok", data: 42 })),
|
||||
fsReadDir: vi.fn(async () => ({ status: "ok", data: [] })),
|
||||
}));
|
||||
vi.mock("@/platform/ipc", async (original) => {
|
||||
const real = await original<typeof import("@/platform/ipc")>();
|
||||
return { ...real, isTauri: () => true, commands: { ...real.commands, ...ipc } };
|
||||
});
|
||||
const notify = vi.fn();
|
||||
const expire = vi.fn();
|
||||
const config: RunConfig = {
|
||||
id: "application:Main",
|
||||
name: "Main",
|
||||
kind: "application",
|
||||
command: "java",
|
||||
args: ["-cp", "${classpath}", "Main"],
|
||||
cwd: null,
|
||||
env: {},
|
||||
detected: true,
|
||||
isTest: false,
|
||||
debugAdapter: "java-debug",
|
||||
};
|
||||
let dispose: () => void;
|
||||
let respond: (result: unknown) => void;
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
useDebug.setState({ sessions: {}, active: null, console: {} });
|
||||
useProject.setState({ project: { root: "/p" } as never });
|
||||
provideNotificationService({ notify, expire });
|
||||
ipc.javaResolveLaunch.mockImplementation(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
respond = resolve;
|
||||
}),
|
||||
);
|
||||
dispose = registerDebugActions();
|
||||
});
|
||||
afterEach(() => dispose());
|
||||
|
||||
async function startAndStop() {
|
||||
const starting = executeAction("debug.startConfig", config);
|
||||
await vi.waitFor(() => expect(ipc.javaResolveLaunch).toHaveBeenCalledOnce());
|
||||
const notification = notify.mock.calls[0]![0];
|
||||
expect(notification).toMatchObject({ sticky: true, title: "Starting debugger for Main…" });
|
||||
expect(notification.actions[0].label).toBe("Stop");
|
||||
notification.actions[0].run();
|
||||
expect(ipc.cancelRequest).toHaveBeenCalledWith(ipc.javaResolveLaunch.mock.calls[0]![3]);
|
||||
expect(expire).toHaveBeenCalledWith(notification.key);
|
||||
return { starting };
|
||||
}
|
||||
|
||||
function expectNoLaunch() {
|
||||
expect(ipc.javaDebugServer).not.toHaveBeenCalled();
|
||||
expect(ipc.debugStart).not.toHaveBeenCalled();
|
||||
expect(useDebug.getState().sessions).toEqual({});
|
||||
expect(notify).toHaveBeenCalledTimes(1);
|
||||
}
|
||||
|
||||
it("Stop cancels the resolve request and ends silently without starting a session", async () => {
|
||||
const { starting } = await startAndStop();
|
||||
respond({ status: "error", error: { kind: "cancelled", message: "Cancelled" } });
|
||||
await starting;
|
||||
expectNoLaunch();
|
||||
});
|
||||
|
||||
it("ignores a successful resolve arriving after Stop, including compile warnings", async () => {
|
||||
const { starting } = await startAndStop();
|
||||
respond({ status: "ok", data: { errorCount: 1 } });
|
||||
await starting;
|
||||
expectNoLaunch();
|
||||
});
|
||||
|
||||
it("ignores a failed resolve arriving after Stop", async () => {
|
||||
const { starting } = await startAndStop();
|
||||
respond({ status: "error", error: { kind: "internal", message: "Build failed" } });
|
||||
await starting;
|
||||
expectNoLaunch();
|
||||
});
|
||||
|
||||
it("still reports a real resolve failure and removes the starting notification", async () => {
|
||||
const starting = executeAction("debug.startConfig", config);
|
||||
await vi.waitFor(() => expect(ipc.javaResolveLaunch).toHaveBeenCalledOnce());
|
||||
respond({ status: "error", error: { kind: "internal", message: "Build failed" } });
|
||||
await starting;
|
||||
expect(notify).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({
|
||||
level: "error",
|
||||
title: "Cannot start debugging",
|
||||
body: "Build failed",
|
||||
}),
|
||||
);
|
||||
expect(expire).toHaveBeenCalledWith(notify.mock.calls[0]![0].key);
|
||||
expect(ipc.debugStart).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { JavaLaunchInfo, RunConfig } from "@/platform/ipc";
|
||||
import { resolveJavaCommand } from "@/platform/javaLaunch";
|
||||
|
||||
const ipc = vi.hoisted(() => ({
|
||||
javaResolveLaunch: vi.fn(),
|
||||
javaDebugServer: vi.fn(async () => ({ status: "ok", data: 5005 })),
|
||||
fsReadDir: vi.fn(async () => ({ status: "ok", data: [] })),
|
||||
}));
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/platform/ipc")>()),
|
||||
commands: ipc,
|
||||
}));
|
||||
|
||||
import { javaLaunchConfig } from "../java";
|
||||
|
||||
const config: RunConfig = {
|
||||
id: "main",
|
||||
name: "Main",
|
||||
kind: "application",
|
||||
command: "java",
|
||||
args: ["-cp", "${classpath}", "Main"],
|
||||
cwd: null,
|
||||
env: {},
|
||||
detected: false,
|
||||
isTest: false,
|
||||
debugAdapter: null,
|
||||
};
|
||||
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
const hosts = [
|
||||
{ client: "Win32", host: "Linux", separator: ":", paths: ["/p/classes", "/lib/a;b.jar"] },
|
||||
{ client: "MacIntel", host: "Windows", separator: ";", paths: ["C:\\p\\classes", "D:\\lib\\a.jar"] },
|
||||
{ client: "MacIntel", host: "Mac", separator: ":", paths: ["/p/classes", "/lib/a.jar"] },
|
||||
{ client: "Win32", host: "Windows", separator: ";", paths: ["C:\\p\\classes", "D:\\lib\\a.jar"] },
|
||||
{ client: "Linux x86_64", host: "Linux", separator: ":", paths: ["/p/classes", "/lib/a.jar"] },
|
||||
];
|
||||
|
||||
describe.each(hosts)("Java launch on $host from $client", ({ client, separator, paths }) => {
|
||||
const info: JavaLaunchInfo = {
|
||||
build: "succeeded",
|
||||
projectRoot: null,
|
||||
classPaths: paths,
|
||||
modulePaths: paths,
|
||||
pathListSeparator: separator,
|
||||
javaHome: null,
|
||||
javaExec: "java",
|
||||
shortenCommandLine: null,
|
||||
errors: [],
|
||||
errorCount: 0,
|
||||
hints: [],
|
||||
};
|
||||
|
||||
it.each(["${classpath}", "${testClasspath}"])("joins %s and module paths using the host separator", (placeholder) => {
|
||||
vi.spyOn(navigator, "platform", "get").mockReturnValue(client);
|
||||
const result = resolveJavaCommand({ ...config, args: ["-cp", placeholder, "Main"] }, info);
|
||||
expect(result.args).toEqual(["--module-path", paths.join(separator), "-cp", paths.join(separator), "Main"]);
|
||||
});
|
||||
|
||||
it.each(["java-debug", "kotlin-debug-adapter"])(
|
||||
"splits explicit classpaths for %s without damaging paths",
|
||||
async (adapter) => {
|
||||
vi.spyOn(navigator, "platform", "get").mockReturnValue(client);
|
||||
ipc.javaResolveLaunch.mockResolvedValue({ status: "ok", data: info });
|
||||
const result = await javaLaunchConfig(
|
||||
{ ...config, debugAdapter: adapter, args: ["-cp", paths.join(separator), "Main"] },
|
||||
"/p",
|
||||
);
|
||||
expect(JSON.parse(result.extraJson!).classPaths).toEqual(paths);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -218,6 +218,48 @@ async function startRemote(config: RunConfig, root: string) {
|
||||
if (launch) await startSession(launch, { runConfig: config });
|
||||
}
|
||||
|
||||
/** Java preparation has no backend session id yet; expose Stop like remote JVM listening. */
|
||||
async function startJavaConfig(config: RunConfig, root: string, origin: RunConfig) {
|
||||
const request = nextRequestId();
|
||||
const controller = new AbortController();
|
||||
const key = `debug.prepare.${request}`;
|
||||
let preparing = true;
|
||||
notifications().notify({
|
||||
group: "run",
|
||||
level: "info",
|
||||
key,
|
||||
sticky: true,
|
||||
title: tx`Starting debugger for ${config.name}…`,
|
||||
actions: [
|
||||
{
|
||||
label: "Stop",
|
||||
run: () => {
|
||||
if (!preparing || controller.signal.aborted) return;
|
||||
controller.abort();
|
||||
notifications().expire?.(key);
|
||||
void commands.cancelRequest(request).catch(() => undefined);
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
let launch;
|
||||
try {
|
||||
await maybeEditorService()
|
||||
?.saveAll()
|
||||
.catch(() => undefined);
|
||||
controller.signal.throwIfAborted();
|
||||
launch = await javaLaunchConfig(config, root, { request, signal: controller.signal });
|
||||
controller.signal.throwIfAborted();
|
||||
} catch (e) {
|
||||
if (controller.signal.aborted || isCancelled(e)) return;
|
||||
throw e;
|
||||
} finally {
|
||||
preparing = false;
|
||||
notifications().expire?.(key);
|
||||
}
|
||||
await startSession(launch, { runConfig: origin });
|
||||
}
|
||||
|
||||
async function startConfig(arg: unknown) {
|
||||
const root = useProject.getState().project?.root;
|
||||
if (!root) return;
|
||||
@@ -255,10 +297,7 @@ async function startConfig(arg: unknown) {
|
||||
return;
|
||||
}
|
||||
if (isJavaDebuggable(config)) {
|
||||
await maybeEditorService()
|
||||
?.saveAll()
|
||||
.catch(() => undefined);
|
||||
await startSession(await javaLaunchConfig(config, root), { runConfig: origin ?? config });
|
||||
await startJavaConfig(config, root, origin ?? config);
|
||||
return;
|
||||
}
|
||||
const launch = launchConfigFor(config, root);
|
||||
|
||||
@@ -5,7 +5,15 @@
|
||||
* JVMs started by Maven / Gradle with a JDWP agent are attached to.
|
||||
*/
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { call, commands, IpcError, type LaunchConfig, type RunConfig } from "@/platform/ipc";
|
||||
import {
|
||||
call,
|
||||
commands,
|
||||
IpcError,
|
||||
nextRequestId,
|
||||
type LaunchConfig,
|
||||
type RequestId,
|
||||
type RunConfig,
|
||||
} from "@/platform/ipc";
|
||||
import {
|
||||
formatCompileErrors,
|
||||
isJvmApplication,
|
||||
@@ -62,21 +70,30 @@ function offerInstall(e: unknown): never {
|
||||
throw e;
|
||||
}
|
||||
|
||||
async function debugServer(module: string): Promise<number> {
|
||||
async function debugServer(module: string, signal?: AbortSignal): Promise<number> {
|
||||
try {
|
||||
return await call(commands.javaDebugServer(module));
|
||||
} catch (e) {
|
||||
signal?.throwIfAborted();
|
||||
offerInstall(e);
|
||||
}
|
||||
}
|
||||
|
||||
/** Launch request for an Application configuration (`java … -cp ${classpath} Main args`). */
|
||||
export async function javaLaunchConfig(rc: RunConfig, root: string): Promise<LaunchConfig> {
|
||||
export async function javaLaunchConfig(
|
||||
rc: RunConfig,
|
||||
root: string,
|
||||
preparation?: { request: RequestId; signal: AbortSignal },
|
||||
): Promise<LaunchConfig> {
|
||||
const module = rc.cwd ?? "";
|
||||
const cwd = rc.cwd ? join(root, rc.cwd) : root;
|
||||
const parsed = parseJavaArgs(rc.args);
|
||||
if (!parsed.mainClass) throw new Error(`No main class in '${rc.name}'`);
|
||||
const info = await call(commands.javaResolveLaunch(module, parsed.classpath === "test", true));
|
||||
preparation?.signal.throwIfAborted();
|
||||
const info = await call(
|
||||
commands.javaResolveLaunch(module, parsed.classpath === "test", true, preparation?.request ?? nextRequestId()),
|
||||
);
|
||||
preparation?.signal.throwIfAborted();
|
||||
if (info.errorCount > 0)
|
||||
notifications().notify({
|
||||
group: "run",
|
||||
@@ -87,7 +104,10 @@ export async function javaLaunchConfig(rc: RunConfig, root: string): Promise<Lau
|
||||
});
|
||||
const resolved = resolveJavaCommand(rc, info);
|
||||
const kotlin = rc.debugAdapter === KOTLIN_ADAPTER || (await moduleHasKotlinSources(cwd));
|
||||
const classPaths = parsed.explicitClasspath ? parsed.explicitClasspath.split(/[:;]/) : info.classPaths;
|
||||
preparation?.signal.throwIfAborted();
|
||||
const classPaths = parsed.explicitClasspath
|
||||
? parsed.explicitClasspath.split(info.pathListSeparator)
|
||||
: info.classPaths;
|
||||
if (kotlin) {
|
||||
return {
|
||||
name: rc.name,
|
||||
@@ -108,7 +128,8 @@ export async function javaLaunchConfig(rc: RunConfig, root: string): Promise<Lau
|
||||
}),
|
||||
};
|
||||
}
|
||||
const port = await debugServer(module);
|
||||
const port = await debugServer(module, preparation?.signal);
|
||||
preparation?.signal.throwIfAborted();
|
||||
return {
|
||||
name: rc.name,
|
||||
adapter: JAVA_ADAPTER,
|
||||
|
||||
@@ -3,12 +3,29 @@
|
||||
* common ones, the options added through "Modify options" (⌥M) and the
|
||||
* Before launch list.
|
||||
*/
|
||||
import { useRef, useState, type ReactNode } from "react";
|
||||
import { useMemo, useRef, useState, type KeyboardEvent, type ReactNode, type RefObject } from "react";
|
||||
import clsx from "clsx";
|
||||
import type { BeforeLaunchTask, RunConfig } from "@/platform/ipc";
|
||||
import { useWorkflowSettings } from "@/platform/workflowSettings";
|
||||
import { useTx, useTxTemplate } from "@/platform/i18n";
|
||||
import { Button, Checkbox, Icon, IconButton, Input, Menu, Select, T, type MenuItem, type SelectOption } from "@/ui";
|
||||
import {
|
||||
Button,
|
||||
Checkbox,
|
||||
HighlightedText,
|
||||
Icon,
|
||||
IconButton,
|
||||
Input,
|
||||
List,
|
||||
listNavigate,
|
||||
Menu,
|
||||
Popup,
|
||||
SearchField,
|
||||
Select,
|
||||
T,
|
||||
fuzzyMatch,
|
||||
type MenuItem,
|
||||
type SelectOption,
|
||||
} from "@/ui";
|
||||
import { useContributions, type RunConfigTypeContribution } from "@/workbench/contributions";
|
||||
import { TASK_LABELS, taskLabel, type BeforeLaunchKind } from "./beforeLaunch";
|
||||
import {
|
||||
@@ -712,6 +729,26 @@ function OutputField({ label, text }: { label: string; text: string }) {
|
||||
);
|
||||
}
|
||||
|
||||
/** Candidate rows for a compound's member picker: every config except itself and ones already added. */
|
||||
export function memberRows(
|
||||
config: RunConfig,
|
||||
all: readonly RunConfig[],
|
||||
members: readonly string[],
|
||||
query: string,
|
||||
): Array<{ config: RunConfig; indices: number[] | null }> {
|
||||
const q = query.trim();
|
||||
return all
|
||||
.filter(
|
||||
(c) =>
|
||||
c.id !== config.id &&
|
||||
!members.includes(c.id) &&
|
||||
!compoundCycle({ ...config, compound: [...members, c.id] }, all),
|
||||
)
|
||||
.map((c) => ({ c, indices: q ? fuzzyMatch(c.name, q) : null }))
|
||||
.filter((x) => !q || x.indices)
|
||||
.map(({ c, indices }) => ({ config: c, indices }));
|
||||
}
|
||||
|
||||
function CompoundMembers({
|
||||
config,
|
||||
all,
|
||||
@@ -725,10 +762,9 @@ function CompoundMembers({
|
||||
}) {
|
||||
const tx = useTx();
|
||||
const members = config.compound ?? [];
|
||||
const candidates = all.filter(
|
||||
(c) =>
|
||||
c.id !== config.id && !members.includes(c.id) && !compoundCycle({ ...config, compound: [...members, c.id] }, all),
|
||||
);
|
||||
const addRef = useRef<HTMLButtonElement>(null);
|
||||
const [addOpen, setAddOpen] = useState(false);
|
||||
const hasCandidates = memberRows(config, all, members, "").length > 0;
|
||||
return (
|
||||
<Field label="Configurations" error={error} top>
|
||||
<div className={styles.taskList} role="list" aria-label={tx("Configurations of the compound")}>
|
||||
@@ -748,19 +784,131 @@ function CompoundMembers({
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<Select
|
||||
value={null}
|
||||
placeholder="Add configuration…"
|
||||
options={candidates.map((c) => ({ value: c.id, label: c.name }))}
|
||||
onChange={(id) => onChange([...members, id])}
|
||||
disabled={!candidates.length}
|
||||
aria-label="Add configuration"
|
||||
/>
|
||||
<Button
|
||||
ref={addRef}
|
||||
size="small"
|
||||
variant="ghost"
|
||||
icon="plus"
|
||||
aria-haspopup="listbox"
|
||||
aria-expanded={addOpen}
|
||||
disabled={!hasCandidates}
|
||||
onClick={() => setAddOpen(true)}
|
||||
>
|
||||
<T>Add configuration…</T>
|
||||
</Button>
|
||||
{addOpen && (
|
||||
<MemberPicker
|
||||
anchor={addRef}
|
||||
config={config}
|
||||
all={all}
|
||||
members={members}
|
||||
onAdd={(id) => onChange([...members, id])}
|
||||
onClose={() => setAddOpen(false)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</Field>
|
||||
);
|
||||
}
|
||||
|
||||
const MEMBER_ROW = 24;
|
||||
|
||||
/** "Add configuration" picker for a compound: stays open while configs are picked, so several can be added. */
|
||||
function MemberPicker({
|
||||
anchor,
|
||||
config,
|
||||
all,
|
||||
members,
|
||||
onAdd,
|
||||
onClose,
|
||||
}: {
|
||||
anchor: RefObject<HTMLButtonElement | null>;
|
||||
config: RunConfig;
|
||||
all: readonly RunConfig[];
|
||||
members: readonly string[];
|
||||
onAdd: (id: string) => void;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const [query, setQuery] = useState("");
|
||||
const rows = useMemo(() => memberRows(config, all, members, query), [config, all, members, query]);
|
||||
const [active, setActive] = useState(0);
|
||||
const clamped = Math.min(active, rows.length - 1);
|
||||
|
||||
const pick = (row: { config: RunConfig } | undefined) => {
|
||||
if (!row) return;
|
||||
onAdd(row.config.id);
|
||||
setQuery("");
|
||||
setActive(0);
|
||||
};
|
||||
|
||||
const onKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
pick(rows[clamped]);
|
||||
return;
|
||||
}
|
||||
const next = listNavigate(e.key, { items: rows, active: clamped, wrap: true });
|
||||
if (next !== null) {
|
||||
e.preventDefault();
|
||||
setActive(next);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Popup
|
||||
open
|
||||
anchor={anchor}
|
||||
onClose={onClose}
|
||||
placement="bottom-start"
|
||||
aria-label="Add configuration"
|
||||
className={styles.chooser}
|
||||
trapFocus
|
||||
>
|
||||
<div className={styles.chooserSearch}>
|
||||
<SearchField
|
||||
value={query}
|
||||
onChange={(v) => {
|
||||
setQuery(v);
|
||||
setActive(0);
|
||||
}}
|
||||
placeholder="Search configurations"
|
||||
aria-label="Search configurations"
|
||||
data-autofocus=""
|
||||
onKeyDown={onKeyDown}
|
||||
variant="bare"
|
||||
/>
|
||||
</div>
|
||||
<div style={{ height: Math.max(MEMBER_ROW, Math.min(rows.length * MEMBER_ROW, 10 * MEMBER_ROW)) }}>
|
||||
<List
|
||||
aria-label="Configurations"
|
||||
className={styles.chooserList}
|
||||
items={rows}
|
||||
getKey={(r) => r.config.id}
|
||||
activeIndex={clamped}
|
||||
onActiveChange={setActive}
|
||||
focusable={false}
|
||||
hoverSelects
|
||||
rowHeight={MEMBER_ROW}
|
||||
onActivate={(r) => pick(r)}
|
||||
empty={
|
||||
<span className={styles.chooserMuted}>
|
||||
<T>Nothing found</T>
|
||||
</span>
|
||||
}
|
||||
renderItem={(r) => (
|
||||
<span className={styles.chooserRow}>
|
||||
<Icon name={configIcon(r.config)} size={13} className={styles.chooserIcon} />
|
||||
<span className={styles.chooserName}>
|
||||
{r.indices?.length ? <HighlightedText text={r.config.name} indices={r.indices} /> : r.config.name}
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</Popup>
|
||||
);
|
||||
}
|
||||
|
||||
export function Field({
|
||||
label,
|
||||
error,
|
||||
|
||||
@@ -563,9 +563,12 @@
|
||||
min-height: var(--h-row);
|
||||
}
|
||||
.taskRow > :first-child {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.taskRow > .taskLabel,
|
||||
.taskRow > input {
|
||||
flex: 1;
|
||||
}
|
||||
.taskLabel {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
|
||||
@@ -194,6 +194,7 @@ describe("java compile errors", () => {
|
||||
projectRoot: "/p",
|
||||
classPaths: [],
|
||||
modulePaths: [],
|
||||
pathListSeparator: ":",
|
||||
javaHome: null,
|
||||
javaExec: null,
|
||||
shortenCommandLine: null,
|
||||
@@ -220,6 +221,7 @@ describe("java command lines", () => {
|
||||
projectRoot: "/p",
|
||||
classPaths: ["/p/target/classes", "/m2/a.jar"],
|
||||
modulePaths: [],
|
||||
pathListSeparator: ":",
|
||||
javaHome: "/jdk21",
|
||||
javaExec: "/jdk21/bin/java",
|
||||
shortenCommandLine: "none",
|
||||
@@ -245,10 +247,9 @@ describe("java command lines", () => {
|
||||
const r = resolveJavaCommand({ ...c, args: ["-Dx=1", ...c.args, "arg"] }, info);
|
||||
expect(r.command).toBe("/jdk21/bin/java");
|
||||
expect(r.args).toEqual(["-Dx=1", "-cp", "/p/target/classes:/m2/a.jar", "a.Main", "arg"]);
|
||||
expect(resolveJavaCommand(c, { ...info, modulePaths: ["/m/x.jar"] }, ";").args.slice(0, 2)).toEqual([
|
||||
"--module-path",
|
||||
"/m/x.jar",
|
||||
]);
|
||||
expect(
|
||||
resolveJavaCommand(c, { ...info, modulePaths: ["/m/x.jar"], pathListSeparator: ";" }).args.slice(0, 2),
|
||||
).toEqual(["--module-path", "/m/x.jar"]);
|
||||
});
|
||||
|
||||
it("joins arguments for java-debug and reads JDWP's port", () => {
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { JavaLaunchInfo, RunConfig } from "@/platform/ipc";
|
||||
|
||||
const ipc = vi.hoisted(() => ({
|
||||
javaResolveLaunch: vi.fn(),
|
||||
cancelRequest: vi.fn(async () => undefined),
|
||||
runStart: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return { ...real, isTauri: () => true, commands: { ...real.commands, ...ipc } };
|
||||
});
|
||||
vi.mock("@tauri-apps/api/core", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@tauri-apps/api/core")>()),
|
||||
Channel: class {
|
||||
onmessage: ((m: unknown) => void) | null = null;
|
||||
},
|
||||
}));
|
||||
|
||||
import { provideNotificationService } from "@/workbench/contributions";
|
||||
import { resetRuns, runtime, startRun, stopSession, useRun } from "./store";
|
||||
|
||||
const config: RunConfig = {
|
||||
id: "application:Main",
|
||||
name: "Main",
|
||||
kind: "application",
|
||||
command: "java",
|
||||
args: ["-cp", "${classpath}", "Main"],
|
||||
cwd: null,
|
||||
env: {},
|
||||
detected: false,
|
||||
isTest: false,
|
||||
debugAdapter: null,
|
||||
};
|
||||
const info: JavaLaunchInfo = {
|
||||
build: "succeeded",
|
||||
projectRoot: "/p",
|
||||
classPaths: ["/p/target/classes"],
|
||||
modulePaths: [],
|
||||
pathListSeparator: ":",
|
||||
javaHome: null,
|
||||
javaExec: "java",
|
||||
shortenCommandLine: null,
|
||||
errors: [],
|
||||
errorCount: 0,
|
||||
hints: [],
|
||||
};
|
||||
const notify = vi.fn();
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
provideNotificationService({ notify });
|
||||
});
|
||||
afterEach(() => {
|
||||
resetRuns();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("Stop during Java launch resolution", () => {
|
||||
it.each(["cancelled", "success"])("cancels the request and ignores a late %s response", async (response) => {
|
||||
type Result = Awaited<ReturnType<typeof import("@/platform/ipc").commands.javaResolveLaunch>>;
|
||||
let resolve!: (result: Result) => void;
|
||||
const pending = new Promise<Result>((done) => {
|
||||
resolve = done;
|
||||
});
|
||||
ipc.javaResolveLaunch.mockReturnValue(pending);
|
||||
const launch = startRun(config);
|
||||
await vi.waitFor(() => expect(ipc.javaResolveLaunch).toHaveBeenCalledOnce());
|
||||
const session = useRun.getState().sessions[0]!;
|
||||
expect(session.status).toBe("starting");
|
||||
const request = ipc.javaResolveLaunch.mock.calls[0]![3];
|
||||
expect(request).toEqual(expect.any(Number));
|
||||
await stopSession(session.id);
|
||||
expect(ipc.cancelRequest).toHaveBeenCalledExactlyOnceWith(request);
|
||||
resolve(
|
||||
response === "cancelled"
|
||||
? { status: "error", error: { kind: "cancelled", message: "request cancelled" } }
|
||||
: { status: "ok", data: info },
|
||||
);
|
||||
await launch;
|
||||
expect(ipc.runStart).not.toHaveBeenCalled();
|
||||
expect(notify).not.toHaveBeenCalled();
|
||||
expect(runtime(session.id)!.console.lines.some((line) => line.kind === "stderr")).toBe(false);
|
||||
expect(useRun.getState().sessions[0]).toMatchObject({ stopped: true, status: "finished", runId: null });
|
||||
expect(runtime(session.id)!.resolveRequest).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Java run host separator", () => {
|
||||
it.each([
|
||||
{ client: "Win32", separator: ":", paths: ["/p/classes", "/lib/a.jar"] },
|
||||
{ client: "MacIntel", separator: ";", paths: ["C:\\p\\classes", "D:\\lib\\a.jar"] },
|
||||
{ client: "MacIntel", separator: ":", paths: ["/p/classes", "/lib/a.jar"] },
|
||||
])("uses $separator from the host on $client", async ({ client, separator, paths }) => {
|
||||
vi.spyOn(navigator, "platform", "get").mockReturnValue(client);
|
||||
ipc.javaResolveLaunch.mockResolvedValue({
|
||||
status: "ok",
|
||||
data: { ...info, classPaths: paths, modulePaths: paths, pathListSeparator: separator },
|
||||
});
|
||||
ipc.runStart.mockResolvedValue({ status: "ok", data: 42 });
|
||||
await startRun(config);
|
||||
expect(ipc.runStart.mock.calls[0]![0].args).toEqual([
|
||||
"--module-path",
|
||||
paths.join(separator),
|
||||
"-cp",
|
||||
paths.join(separator),
|
||||
"Main",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
import { typeRows } from "./AddConfigPopup";
|
||||
import { runBeforeLaunch } from "./beforeLaunch";
|
||||
import { buildRows } from "./ConfigChooser";
|
||||
import { memberRows } from "./ConfigForm";
|
||||
import { compoundChildren, compoundCycle, formatEnv, parseEnv, validateConfig } from "./configs";
|
||||
import { contextConfig } from "./context";
|
||||
import { EditConfigsOverlay, moveConfig, treeRows } from "./EditConfigsDialog";
|
||||
@@ -347,6 +348,17 @@ describe("compound configurations", () => {
|
||||
.sort(),
|
||||
).toEqual(["a", "b"]);
|
||||
});
|
||||
|
||||
it("member picker lists candidates and filters them by name", () => {
|
||||
// `outer` contains `inner`, so adding it to `inner` would close a cycle.
|
||||
const rows = memberRows(inner, [a, b, inner, outer], [], "");
|
||||
expect(rows.map((r) => r.config.id)).toEqual(["a", "b"]);
|
||||
// Already-added members and the compound itself are excluded.
|
||||
expect(memberRows(inner, [a, b, inner, outer], ["a"], "").map((r) => r.config.id)).toEqual(["b"]);
|
||||
const named = cfg("named", { name: "Deploy App" });
|
||||
expect(memberRows(outer, [a, b, inner, outer, named], ["a"], "deploy").map((r) => r.config.id)).toEqual(["named"]);
|
||||
expect(memberRows(outer, [a, b, inner, outer, named], ["a"], "zzz")).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("before launch tasks", () => {
|
||||
|
||||
@@ -9,6 +9,9 @@ import {
|
||||
call,
|
||||
commands,
|
||||
isTauri,
|
||||
isCancelled,
|
||||
nextRequestId,
|
||||
type RequestId,
|
||||
type OutputChunk,
|
||||
type RunConfig,
|
||||
type RunId,
|
||||
@@ -68,6 +71,7 @@ export interface RunSession {
|
||||
}
|
||||
|
||||
interface SessionRuntime {
|
||||
resolveRequest?: { id: RequestId; cancelled: boolean };
|
||||
console: ConsoleModel;
|
||||
tests: TestResults | null;
|
||||
parser: TestOutputParser | null;
|
||||
@@ -620,7 +624,10 @@ export async function startRun(
|
||||
const resolved = await resolveJvmApplication(sessionId, launch);
|
||||
if (runtimes.get(sessionId)?.generation !== generation) return getSession(sessionId) ?? null;
|
||||
if (!resolved) {
|
||||
patchSession(sessionId, { status: "failed", endedAt: Date.now() });
|
||||
patchSession(sessionId, {
|
||||
status: getSession(sessionId)?.stopped ? "finished" : "failed",
|
||||
endedAt: Date.now(),
|
||||
});
|
||||
return getSession(sessionId) ?? null;
|
||||
}
|
||||
launch = resolved;
|
||||
@@ -672,8 +679,6 @@ function revealSession(sessionId: string) {
|
||||
}
|
||||
}
|
||||
|
||||
const pathSeparator = () => (typeof navigator !== "undefined" && /win/i.test(navigator.platform) ? ";" : ":");
|
||||
|
||||
/**
|
||||
* Builds the module (jdtls workspace build) and resolves `${classpath}` and the
|
||||
* project JDK of a Java application configuration. Null (and a console message) on failure.
|
||||
@@ -690,8 +695,14 @@ async function resolveJvmApplication(sessionId: string, config: RunConfig): Prom
|
||||
}
|
||||
if (!parsed.classpath) return config;
|
||||
say(`Building and resolving the classpath of ${parsed.mainClass}…\n`);
|
||||
const rt = runtime(sessionId)!;
|
||||
const request = { id: nextRequestId(), cancelled: false };
|
||||
rt.resolveRequest = request;
|
||||
try {
|
||||
const info = await call(commands.javaResolveLaunch(config.cwd ?? "", parsed.classpath === "test", true));
|
||||
const info = await call(
|
||||
commands.javaResolveLaunch(config.cwd ?? "", parsed.classpath === "test", true, request.id),
|
||||
);
|
||||
if (request.cancelled) return null;
|
||||
if (info.build === "withErrors")
|
||||
say("Build completed with errors; launching with the last compiled classes.\n", "stderr");
|
||||
if (info.build === "failed") say("Build failed; launching with the last compiled classes.\n", "stderr");
|
||||
@@ -712,9 +723,13 @@ async function resolveJvmApplication(sessionId: string, config: RunConfig): Prom
|
||||
say("The classpath is empty: is the module imported by the Java language server?\n", "stderr");
|
||||
return null;
|
||||
}
|
||||
return resolveJavaCommand(config, info, pathSeparator());
|
||||
return resolveJavaCommand(config, info);
|
||||
} catch (e) {
|
||||
const message = e instanceof Error ? e.message : String(e);
|
||||
if (request.cancelled || isCancelled(e)) {
|
||||
if (runtimes.get(sessionId) === rt && rt.resolveRequest === request) patchSession(sessionId, { stopped: true });
|
||||
return null;
|
||||
}
|
||||
say(`Cannot resolve the classpath: ${message}\n`, "stderr");
|
||||
// jdtls can't start without a newer JDK: "Download JDK 25".
|
||||
const actions = downloadJdkActions(message);
|
||||
@@ -726,6 +741,8 @@ async function resolveJvmApplication(sessionId: string, config: RunConfig): Prom
|
||||
actions,
|
||||
});
|
||||
return null;
|
||||
} finally {
|
||||
if (rt.resolveRequest === request) delete rt.resolveRequest;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -835,7 +852,15 @@ export function onRunExited(runId: RunId, code: number | null) {
|
||||
|
||||
export async function stopSession(sessionId: string): Promise<void> {
|
||||
const session = getSession(sessionId);
|
||||
if (!session || session.runId === null || session.status !== "running") return;
|
||||
if (!session) return;
|
||||
const request = runtimes.get(sessionId)?.resolveRequest;
|
||||
if (session.status === "starting" && request) {
|
||||
request.cancelled = true;
|
||||
patchSession(sessionId, { stopped: true });
|
||||
await commands.cancelRequest(request.id);
|
||||
return;
|
||||
}
|
||||
if (session.runId === null || session.status !== "running") return;
|
||||
patchSession(sessionId, { stopped: true });
|
||||
try {
|
||||
await call(commands.runStop(session.runId));
|
||||
@@ -995,7 +1020,7 @@ export async function closeSessionTab(sessionId: string): Promise<boolean> {
|
||||
export function closeSession(sessionId: string) {
|
||||
const session = getSession(sessionId);
|
||||
if (!session) return;
|
||||
if (session.status === "running") void stopSession(sessionId);
|
||||
if (session.status === "running" || session.status === "starting") void stopSession(sessionId);
|
||||
const rt = runtimes.get(sessionId);
|
||||
if (rt) cancelFlush(rt);
|
||||
runtimes.delete(sessionId);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { create } from "zustand";
|
||||
import { executeAction, registerActions } from "@/platform/actions";
|
||||
import { call, commands, isTauri, onIdeEvent } from "@/platform/ipc";
|
||||
@@ -10,8 +10,28 @@ 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 }));
|
||||
/** What the widget last resolved for a project, so the popup action can read it without a render. */
|
||||
interface Status {
|
||||
root: string;
|
||||
configured: string;
|
||||
visible: boolean;
|
||||
python: string | null;
|
||||
sdks: Sdk[];
|
||||
}
|
||||
|
||||
const usePopup = create<{ open: boolean; status: Status | null }>(() => ({ open: false, status: null }));
|
||||
const close = () => usePopup.setState({ open: false });
|
||||
const reset = () => usePopup.setState({ open: false, status: null });
|
||||
|
||||
/** Whether the widget is on screen, read straight from the stores (the action runs outside a render). */
|
||||
function popupShown(): boolean {
|
||||
const project = useProject.getState();
|
||||
const root = project.project?.root;
|
||||
const configured = project.settings?.languages?.python?.interpreter ?? "";
|
||||
const status = usePopup.getState().status;
|
||||
if (!root || !status || status.root !== root || status.configured !== configured) return false;
|
||||
return status.visible || !!configured;
|
||||
}
|
||||
const markers = [
|
||||
"pyproject.toml",
|
||||
"setup.py",
|
||||
@@ -48,17 +68,11 @@ async function hasPythonFiles(): Promise<boolean> {
|
||||
function PythonStatus() {
|
||||
const root = useProject((s) => s.project?.root);
|
||||
const configured = useProject((s) => s.settings?.languages?.python?.interpreter ?? "");
|
||||
const status = usePopup((s) => s.status);
|
||||
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();
|
||||
reset();
|
||||
if (!root || !isTauri()) return;
|
||||
let live = true;
|
||||
let sequence = 0;
|
||||
@@ -73,7 +87,7 @@ function PythonStatus() {
|
||||
visible || configured
|
||||
? await Promise.all([effectivePython(), (detected ??= call(commands.sdkDetect("python")))])
|
||||
: [null, [] as Sdk[]];
|
||||
if (live && sequence === request) setState({ root, configured, visible, python, sdks });
|
||||
if (live && sequence === request) usePopup.setState({ status: { root, configured, visible, python, sdks } });
|
||||
} catch (e) {
|
||||
console.warn("Cannot refresh Python interpreter status", e);
|
||||
}
|
||||
@@ -105,16 +119,13 @@ function PythonStatus() {
|
||||
live = false;
|
||||
clearTimeout(timer);
|
||||
off.forEach((dispose) => dispose());
|
||||
close();
|
||||
reset();
|
||||
};
|
||||
}, [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;
|
||||
// The widget only renders once its project's status is in the store, so the popup action
|
||||
// sees the same state as the button without waiting for an effect to publish a flag.
|
||||
if (!popupShown() || !status) return null;
|
||||
const current = status;
|
||||
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>();
|
||||
@@ -174,7 +185,7 @@ export function activatePythonStatus(): () => void {
|
||||
category: "Settings",
|
||||
when: "projectOpen",
|
||||
run: () =>
|
||||
usePopup.getState().shown
|
||||
popupShown()
|
||||
? usePopup.setState((s) => ({ open: !s.open }))
|
||||
: void executeAction("file.settings", "python.interpreter"),
|
||||
},
|
||||
@@ -213,7 +224,7 @@ export function activatePythonStatus(): () => void {
|
||||
]),
|
||||
];
|
||||
return () => {
|
||||
close();
|
||||
reset();
|
||||
dispose.reverse().forEach((d) => d());
|
||||
};
|
||||
}
|
||||
@@ -52,6 +52,7 @@ import { stashTabOf, stashTabs, type ContentTab } from "./gitTabs";
|
||||
import { openDiff, withChain, workingDiffData } from "./diffInput";
|
||||
import { KIND_COLOR, KIND_LABEL, fileCount, formatTime, stashLabel, stripSlash } from "./model";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import type { FileStatus } from "@/bindings";
|
||||
import { OperationBanner } from "./operations";
|
||||
import { ShelfPanel, loadShelves, useShelf } from "./shelf";
|
||||
import { refreshNow, repoName, selectRepo, useVcs } from "./store";
|
||||
@@ -172,7 +173,9 @@ function openNode(n: ChangeNode, roots: readonly ChangeNode[]) {
|
||||
void openDiff(withChain(items, Math.max(0, paths.indexOf(n.path))), { preview: true });
|
||||
}
|
||||
|
||||
function listMenu(id: string, active: boolean, paths: string[]): MenuItem[] {
|
||||
/** Context menu of a change list's header: the list's own actions, then the bulk ones on its files. */
|
||||
export function listMenu(id: string, active: boolean, files: readonly FileStatus[]): MenuItem[] {
|
||||
const paths = files.map((f) => stripSlash(f.path));
|
||||
const count = paths.length;
|
||||
return [
|
||||
...(count ? [{ kind: "action" as const, action: "vcs.changelist.commit", arg: id, label: "Commit…" }] : []),
|
||||
@@ -186,6 +189,22 @@ function listMenu(id: string, active: boolean, paths: string[]): MenuItem[] {
|
||||
{ kind: "action" as const, action: "vcs.changelist.delete", arg: id },
|
||||
]),
|
||||
{ kind: "separator" },
|
||||
// The whole list's files, as IDEA offers on a change list's header and as file
|
||||
// and directory nodes below it already offer (issue #473).
|
||||
{ kind: "action", action: "vcs.rollback", arg: paths, label: "Rollback…", disabled: !count },
|
||||
{
|
||||
label: "Stage",
|
||||
icon: "plus",
|
||||
disabled: !files.some((f) => f.unstaged),
|
||||
run: () => void call(commands.vcsStage(paths)).finally(() => void refreshNow()),
|
||||
},
|
||||
{
|
||||
label: "Unstage",
|
||||
icon: "minus",
|
||||
disabled: !files.some((f) => f.staged),
|
||||
run: () => void call(commands.vcsUnstage(paths)).finally(() => void refreshNow()),
|
||||
},
|
||||
{ kind: "separator" },
|
||||
...(count
|
||||
? [
|
||||
{ kind: "action" as const, action: "vcs.shelve", arg: paths },
|
||||
@@ -486,8 +505,7 @@ export function ChangesTree({ mode }: { mode: "commit" | "local" | "dialog" }) {
|
||||
onContextMenu={(node, sel, e: MouseEvent) => {
|
||||
if (!node) return;
|
||||
if (node.type === "group" && node.changelist) {
|
||||
const paths = node.files.map((f) => stripSlash(f.path));
|
||||
showContextMenu(e, listMenu(node.changelist, !!node.active, paths));
|
||||
showContextMenu(e, listMenu(node.changelist, !!node.active, node.files));
|
||||
return;
|
||||
}
|
||||
const nodes = [...sel].map((k) => byKey.get(k)).filter((n): n is ChangeNode => !!n);
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { FileStatus } from "@/bindings";
|
||||
import type { MenuItem } from "@/ui";
|
||||
|
||||
vi.mock("@/platform/ipc", async (original) => {
|
||||
const real = await original<typeof import("@/platform/ipc")>();
|
||||
return { ...real, call: vi.fn(), commands: { ...real.commands, vcsStage: "vcsStage", vcsUnstage: "vcsUnstage" } };
|
||||
});
|
||||
|
||||
const { listMenu } = await import("../CommitView");
|
||||
|
||||
const fs = (rel: string, staged: FileStatus["staged"], unstaged: FileStatus["unstaged"]): FileStatus => ({
|
||||
path: `/p/${rel}`,
|
||||
relPath: rel,
|
||||
staged,
|
||||
unstaged,
|
||||
renamedFrom: null,
|
||||
});
|
||||
|
||||
type Action = Extract<MenuItem, { kind: "action" }>;
|
||||
type Item = Extract<MenuItem, { kind?: "item" }>;
|
||||
|
||||
/** Actions in the menu, by action id. */
|
||||
const actions = (items: MenuItem[]) => items.filter((i): i is Action => i.kind === "action");
|
||||
/** Labelled items in the menu, by label. */
|
||||
const item = (items: MenuItem[], label: string) =>
|
||||
items.find((i): i is Item => i.kind !== "separator" && i.kind !== "action" && i.label === label);
|
||||
|
||||
const files = [fs("a.txt", null, "modified"), fs("b.txt", "modified", null)];
|
||||
|
||||
describe("change list header menu", () => {
|
||||
it("rolls back, stages and unstages the whole list", () => {
|
||||
const menu = listMenu("list-1", false, files);
|
||||
const rollback = actions(menu).find((a) => a.action === "vcs.rollback");
|
||||
expect(rollback?.arg).toEqual(["/p/a.txt", "/p/b.txt"]);
|
||||
// Both operations apply to the list's files, as on a file or directory node.
|
||||
expect(item(menu, "Stage")?.disabled).toBe(false);
|
||||
expect(item(menu, "Unstage")?.disabled).toBe(false);
|
||||
expect(actions(menu).find((a) => a.action === "vcs.shelve")?.arg).toEqual(["/p/a.txt", "/p/b.txt"]);
|
||||
});
|
||||
|
||||
it("keeps the change list's own actions", () => {
|
||||
const menu = listMenu("list-1", false, files);
|
||||
const actionsOf = (menu: MenuItem[]) => actions(menu).map((a) => a.action);
|
||||
expect(actionsOf(menu)).toContain("vcs.changelist.commit");
|
||||
expect(actionsOf(menu)).toContain("vcs.changelist.delete");
|
||||
// An active list is not offered Set Active / Delete.
|
||||
expect(actionsOf(listMenu("list-1", true, files))).not.toContain("vcs.changelist.delete");
|
||||
});
|
||||
|
||||
it("disables the operations nothing applies to in an empty list", () => {
|
||||
const menu = listMenu("list-1", true, []);
|
||||
expect(actions(menu).find((a) => a.action === "vcs.rollback")?.disabled).toBe(true);
|
||||
expect(item(menu, "Stage")?.disabled).toBe(true);
|
||||
expect(item(menu, "Unstage")?.disabled).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -71,11 +71,11 @@ export function parseJavaArgs(args: readonly string[]): JavaCommandLine {
|
||||
}
|
||||
|
||||
/** The configuration with its placeholders and launcher resolved. */
|
||||
export function resolveJavaCommand(config: RunConfig, info: JavaLaunchInfo, pathSeparator = ":"): RunConfig {
|
||||
const cp = info.classPaths.join(pathSeparator);
|
||||
export function resolveJavaCommand(config: RunConfig, info: JavaLaunchInfo): RunConfig {
|
||||
const cp = info.classPaths.join(info.pathListSeparator);
|
||||
const args: string[] = [];
|
||||
if (info.modulePaths.length && !config.args.some((a) => a === "-p" || a === "--module-path"))
|
||||
args.push("--module-path", info.modulePaths.join(pathSeparator));
|
||||
args.push("--module-path", info.modulePaths.join(info.pathListSeparator));
|
||||
args.push(...config.args.map((a) => (a === CLASSPATH || a === TEST_CLASSPATH ? cp : a)));
|
||||
const command = config.command === "java" && info.javaExec ? info.javaExec : config.command;
|
||||
return { ...config, command, args };
|
||||
|
||||
@@ -36,7 +36,7 @@ describe("IDEA keymap parity", () => {
|
||||
["window.previous", ["Meta+Alt+Shift+`"], ["Ctrl+Alt+["]],
|
||||
["code.commentBlock", ["Meta+Alt+/", "Ctrl+Shift+/"], ["Ctrl+Shift+/"]],
|
||||
["navigate.typeDeclaration", ["Meta+Shift+B", "Ctrl+Shift+B"], ["Ctrl+Shift+B"]],
|
||||
["navigate.implementation", ["Meta+Alt+B", "Meta+Alt+Button1"], ["Ctrl+Alt+B"]],
|
||||
["navigate.implementation", ["Meta+Alt+B", "Meta+Alt+Button1"], ["Ctrl+Alt+B", "Ctrl+Alt+Button1"]],
|
||||
["find.next", ["Meta+G"], ["F3", "Ctrl+L"]],
|
||||
["find.previous", ["Meta+Shift+G"], ["Shift+F3", "Ctrl+Shift+L"]],
|
||||
["project.copy", ["Meta+C"], ["Ctrl+C", "Ctrl+Insert"]],
|
||||
|
||||
@@ -20,7 +20,7 @@ export const intellijWindows: Record<string, string[]> = {
|
||||
"navigate.forward": ["Ctrl+Alt+Right", "Button5"],
|
||||
"navigate.gotoLine": ["Ctrl+G"],
|
||||
"navigate.declaration": ["Ctrl+B"],
|
||||
"navigate.implementation": ["Ctrl+Alt+B"],
|
||||
"navigate.implementation": ["Ctrl+Alt+B", "Ctrl+Alt+Button1"],
|
||||
"navigate.typeDeclaration": ["Ctrl+Shift+B"],
|
||||
"navigate.fileStructure": ["Ctrl+F12"],
|
||||
"navigate.nextError": ["F2"],
|
||||
|
||||
@@ -188,6 +188,9 @@ export const vscodeMacos: Record<string, string[]> = {
|
||||
"editor.splitRight": ["Meta+\\"],
|
||||
"editor.toggleZen": ["Meta+K Z"],
|
||||
"window.toggleFullScreen": ["Meta+Ctrl+F"],
|
||||
// Project window groups are an IntelliJ concept; VS Code has no counterpart.
|
||||
"window.nextTab": [],
|
||||
"window.previousTab": [],
|
||||
"window.next": [],
|
||||
"window.previous": [],
|
||||
"file.reloadFromDisk": [],
|
||||
|
||||
@@ -3345,6 +3345,7 @@
|
||||
"No changes yet": "还没有改动",
|
||||
"What should the agent do?": "让 agent 做点什么?",
|
||||
"New worktree": "新 worktree",
|
||||
"Starting debugger for {name}…": "正在启动 {name} 的调试器…",
|
||||
"Starting…": "正在启动…",
|
||||
"Waiting for your answer": "等待你的回答",
|
||||
"Waiting for your answer…": "等待你的回答…",
|
||||
|
||||
Reference in new issue
Заблокувати користувача