дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 17:47:08 +02:00
Порівняти коміти
1
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
37735eab14 |
No files matched your search
Створено
+26
-26
@@ -3962,7 +3962,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.5"
|
||||
version = "0.1.3"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -3976,7 +3976,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.5"
|
||||
version = "0.1.3"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
@@ -3991,7 +3991,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.5"
|
||||
version = "0.1.3"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"serde",
|
||||
@@ -4003,7 +4003,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.5"
|
||||
version = "0.1.3"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4017,7 +4017,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.5"
|
||||
version = "0.1.3"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jsonrpc",
|
||||
@@ -4034,7 +4034,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.5"
|
||||
version = "0.1.3"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"futures",
|
||||
@@ -4054,7 +4054,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.5"
|
||||
version = "0.1.3"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4067,7 +4067,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.5"
|
||||
version = "0.1.3"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4081,7 +4081,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.5"
|
||||
version = "0.1.3"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4099,7 +4099,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.5"
|
||||
version = "0.1.3"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4121,7 +4121,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.5"
|
||||
version = "0.1.3"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"ide-core",
|
||||
@@ -4136,7 +4136,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.5"
|
||||
version = "0.1.3"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4188,7 +4188,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.5"
|
||||
version = "0.1.3"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"globset",
|
||||
@@ -4211,7 +4211,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.5"
|
||||
version = "0.1.3"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4229,7 +4229,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.5"
|
||||
version = "0.1.3"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4242,7 +4242,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.5"
|
||||
version = "0.1.3"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"ide-core",
|
||||
@@ -4260,7 +4260,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.5"
|
||||
version = "0.1.3"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"ide-core",
|
||||
@@ -4277,7 +4277,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.5"
|
||||
version = "0.1.3"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"globset",
|
||||
@@ -4296,7 +4296,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.5"
|
||||
version = "0.1.3"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4311,7 +4311,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.5"
|
||||
version = "0.1.3"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4324,7 +4324,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.5"
|
||||
version = "0.1.3"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4336,7 +4336,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.5"
|
||||
version = "0.1.3"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hex",
|
||||
@@ -4356,7 +4356,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.5"
|
||||
version = "0.1.3"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"gix",
|
||||
@@ -4373,7 +4373,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.5"
|
||||
version = "0.1.3"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -4393,7 +4393,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.5"
|
||||
version = "0.1.3"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -5817,7 +5817,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.5"
|
||||
version = "0.1.3"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ resolver = "3"
|
||||
members = ["crates/*", "src-tauri"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.5"
|
||||
version = "0.1.3"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
|
||||
@@ -19,7 +19,7 @@ fn main() {
|
||||
eprintln!("synced in {:?}: {r:?}", started.elapsed());
|
||||
}
|
||||
let started = std::time::Instant::now();
|
||||
let model = ide_build::load(&root, &cache, None);
|
||||
let model = ide_build::load(&root, &cache);
|
||||
println!("{}", serde_json::to_string_pretty(&model).unwrap());
|
||||
eprintln!("loaded in {:?}", started.elapsed());
|
||||
}
|
||||
@@ -225,7 +225,6 @@ fn maven_steps(root: &Path, model: &BuildModel, kind: BuildKind, module: Option<
|
||||
}
|
||||
let step = |p: &maven::MavenProject, extra: &[String]| {
|
||||
let mut s = BuildStep::new(&p.command, &["-B", "-Dstyle.color=never"], &subdir(root, &p.dir), Format::Maven);
|
||||
s.args.extend(p.options.iter().cloned());
|
||||
s.args.extend(extra.iter().cloned());
|
||||
s.args.extend(goals.iter().map(|g| (*g).to_owned()));
|
||||
s.env = p.env.clone();
|
||||
@@ -672,7 +671,7 @@ mod tests {
|
||||
);
|
||||
write(&root, "core/pom.xml", "<project><artifactId>core</artifactId></project>");
|
||||
write(&root, "core/src/main/java/A.java", "class A {}");
|
||||
let model = crate::load(&root, &tmp.path().join("cache"), None);
|
||||
let model = crate::load(&root, &tmp.path().join("cache"));
|
||||
let p = plan(&root, &model, BuildKind::Build, None).unwrap();
|
||||
assert_eq!(p.system, BuildSystem::Maven);
|
||||
assert_eq!(p.title, "demo");
|
||||
@@ -686,7 +685,7 @@ mod tests {
|
||||
let g = tmp.path().join("g");
|
||||
write(&g, "settings.gradle", "include 'app'");
|
||||
write(&g, "app/build.gradle", "apply plugin: 'java'");
|
||||
let model = crate::load(&g, &tmp.path().join("cache2"), None);
|
||||
let model = crate::load(&g, &tmp.path().join("cache2"));
|
||||
let p = plan(&g, &model, BuildKind::Build, Some(&g.join("app/src/A.java"))).unwrap();
|
||||
assert_eq!(p.system, BuildSystem::Gradle);
|
||||
assert_eq!(p.steps[0].args, ["--console=plain", ":app:classes", ":app:testClasses"]);
|
||||
|
||||
@@ -18,7 +18,7 @@ pub use sync::{SyncOptions, SyncProgress, sync_gradle, sync_maven};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::path::Path;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -36,10 +36,9 @@ pub struct BuildModel {
|
||||
}
|
||||
|
||||
/// Static model of the builds under `root`, merged with the sync results cached in `cache_dir`.
|
||||
/// Parent POMs are looked up in `maven_repo` (the configured local repository), else the default one.
|
||||
pub fn load(root: &Path, cache_dir: &Path, maven_repo: Option<PathBuf>) -> BuildModel {
|
||||
pub fn load(root: &Path, cache_dir: &Path) -> BuildModel {
|
||||
let maven = maven::is_maven_project(root).then(|| {
|
||||
let mut m = maven::load_with_repo(root, maven_repo.or_else(maven::default_local_repo));
|
||||
let mut m = maven::load(root);
|
||||
sync::apply_maven_cache(root, cache_dir, &mut m);
|
||||
m
|
||||
});
|
||||
@@ -69,10 +68,10 @@ mod tests {
|
||||
let cache = tmp.path().join("cache");
|
||||
let root = tmp.path().join("p");
|
||||
std::fs::create_dir_all(root.join("svc")).unwrap();
|
||||
assert_eq!(load(&root, &cache, None), BuildModel::default());
|
||||
assert_eq!(load(&root, &cache), BuildModel::default());
|
||||
std::fs::write(root.join("svc/pom.xml"), "<project><artifactId>svc</artifactId></project>").unwrap();
|
||||
std::fs::write(root.join("build.gradle"), "").unwrap();
|
||||
let m = load(&root, &cache, None);
|
||||
let m = load(&root, &cache);
|
||||
assert_eq!(m.maven.unwrap().projects[0].pom, "svc/pom.xml");
|
||||
assert_eq!(m.gradle.unwrap().projects[0].path, ":");
|
||||
assert!(affects_build(Path::new("a/pom.xml")) && affects_build(Path::new("settings.gradle.kts")));
|
||||
|
||||
@@ -92,8 +92,6 @@ pub struct MavenProject {
|
||||
pub java_version: Option<u32>,
|
||||
/// Maven launcher: the nearest `mvnw` up to the project root (absolute), else `mvn`.
|
||||
pub command: String,
|
||||
/// Options before the goals (`-s`, `-Dmaven.repo.local=`); filled in by the shell from settings.
|
||||
pub options: Vec<String>,
|
||||
/// Environment for runs (`JAVA_HOME` of the matching JDK); filled in by the shell.
|
||||
pub env: BTreeMap<String, String>,
|
||||
}
|
||||
@@ -412,7 +410,7 @@ struct Resolver {
|
||||
}
|
||||
|
||||
/// `~/.m2/repository`, or `<localRepository>` from `~/.m2/settings.xml`.
|
||||
pub(crate) fn default_local_repo() -> Option<PathBuf> {
|
||||
fn default_local_repo() -> Option<PathBuf> {
|
||||
let m2 = dirs::home_dir()?.join(".m2");
|
||||
if let Some(settings) = std::fs::read_to_string(m2.join("settings.xml")).ok().and_then(|t| xml::parse(&t))
|
||||
&& let Some(repo) = settings.text_of("localRepository")
|
||||
@@ -926,7 +924,6 @@ pub(crate) fn load_with_repo(root: &Path, local_repo: Option<PathBuf>) -> MavenM
|
||||
profiles: pom.profiles.iter().map(|p| p.id.clone()).collect(),
|
||||
java_version: jv,
|
||||
command: wrapper(root, &dir),
|
||||
options: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
});
|
||||
for m in modules.into_iter().rev() {
|
||||
|
||||
@@ -29,10 +29,6 @@ pub struct SyncOptions {
|
||||
pub profiles: Vec<String>,
|
||||
/// Extra environment (`JAVA_HOME`).
|
||||
pub env: BTreeMap<String, String>,
|
||||
/// Maven launcher replacing the project's `mvnw` / `mvn` (Settings › Maven home).
|
||||
pub maven_command: Option<String>,
|
||||
/// Maven options before the goals (`-s`, `-Dmaven.repo.local=`).
|
||||
pub maven_options: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
@@ -188,7 +184,6 @@ pub fn sync_maven(
|
||||
let effective = cache_dir.join(format!("effective-pom-{n}.xml"));
|
||||
let _ = std::fs::remove_file(&effective);
|
||||
let mut args: Vec<String> = vec!["-B".into(), "-fae".into(), "-Dstyle.color=never".into()];
|
||||
args.extend(options.maven_options.iter().cloned());
|
||||
if options.offline {
|
||||
args.push("-o".into());
|
||||
}
|
||||
@@ -199,8 +194,7 @@ pub fn sync_maven(
|
||||
args.push(format!("-Doutput={}", effective.to_string_lossy()));
|
||||
args.push("dependency:tree".into());
|
||||
progress(SyncProgress { message: format!("Reading {}", top.display_name), fraction: None });
|
||||
let command = options.maven_command.as_deref().unwrap_or(&top.command);
|
||||
let out = run(command, &args, &root.join(&top.dir), &options.env, cancel, |line| {
|
||||
let out = run(&top.command, &args, &root.join(&top.dir), &options.env, cancel, |line| {
|
||||
if let Some((name, i, total)) = maven_building(line) {
|
||||
let fraction = (i.saturating_sub(1) as f32 / total.max(1) as f32).min(1.0);
|
||||
progress(SyncProgress { message: format!("Building model of {name}"), fraction: Some(fraction) });
|
||||
|
||||
@@ -335,7 +335,6 @@ pub struct LanguagesSettings {
|
||||
pub rust: RustSettings,
|
||||
pub go: GoSettings,
|
||||
pub typescript: TypeScriptSettings,
|
||||
pub java: JavaSettings,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -398,31 +397,6 @@ pub struct GoSettings {
|
||||
pub gopath: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct JavaSettings {
|
||||
/// Project JDK home; empty = per module, the installed JDK matching the
|
||||
/// Java version it targets.
|
||||
pub jdk: String,
|
||||
/// Extra JVM options for the Java language server (jdtls), space-separated
|
||||
/// (VS Code's `java.jdt.ls.vmargs`).
|
||||
pub jdtls_vm_args: String,
|
||||
/// Build Tools › Maven.
|
||||
pub maven: MavenSettings,
|
||||
}
|
||||
|
||||
/// Build Tools › Maven.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct MavenSettings {
|
||||
/// Maven home (or its `mvn` executable); empty = the project's `mvnw`, else `mvn` on `PATH`.
|
||||
pub home: String,
|
||||
/// User `settings.xml` (`-s`); empty = `~/.m2/settings.xml`.
|
||||
pub user_settings: String,
|
||||
/// Local repository (`-Dmaven.repo.local`); empty = from `settings.xml`.
|
||||
pub local_repository: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct TypeScriptSettings {
|
||||
|
||||
@@ -24,10 +24,6 @@ const BUILD_TIMEOUT: Duration = Duration::from_secs(300);
|
||||
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);
|
||||
/// Compile errors listed with a launch; the rest are only counted.
|
||||
const MAX_LAUNCH_ERRORS: usize = 10;
|
||||
/// Build markers can be published just after `java/buildWorkspace` answers.
|
||||
const ERRORS_WAIT: Duration = Duration::from_secs(2);
|
||||
|
||||
/// Result of `java/buildWorkspace` (jdtls `BuildWorkspaceStatus`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -74,43 +70,6 @@ pub struct JavaLaunchInfo {
|
||||
pub java_home: Option<ide_core::IpcPath>,
|
||||
/// The `java` launcher to use (filled in by the caller from the installed JDKs).
|
||||
pub java_exec: Option<String>,
|
||||
/// First compile errors of the workspace when the build had errors.
|
||||
pub errors: Vec<JavaCompileError>,
|
||||
/// All compile errors (`errors` is capped).
|
||||
pub error_count: u32,
|
||||
/// Likely causes of the errors worth telling the user (e.g. a missing Lombok agent).
|
||||
pub hints: Vec<String>,
|
||||
}
|
||||
|
||||
/// One error diagnostic; `line` / `column` are 1-based for display.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct JavaCompileError {
|
||||
pub path: ide_core::IpcPath,
|
||||
pub line: u32,
|
||||
pub column: u32,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// Error diagnostics sorted by file and position, capped at `limit`, and their total.
|
||||
pub fn compile_errors(
|
||||
diagnostics: Vec<(PathBuf, lsp_types::Diagnostic)>,
|
||||
limit: usize,
|
||||
) -> (Vec<JavaCompileError>, u32) {
|
||||
let mut errors: Vec<JavaCompileError> = diagnostics
|
||||
.into_iter()
|
||||
.filter(|(_, d)| d.severity == Some(lsp_types::DiagnosticSeverity::ERROR))
|
||||
.map(|(path, d)| JavaCompileError {
|
||||
path: path.into(),
|
||||
line: d.range.start.line + 1,
|
||||
column: d.range.start.character + 1,
|
||||
message: d.message.lines().next().unwrap_or_default().to_owned(),
|
||||
})
|
||||
.collect();
|
||||
errors.sort_by(|a, b| (&a.path, a.line, a.column).cmp(&(&b.path, b.line, b.column)));
|
||||
let count = u32::try_from(errors.len()).unwrap_or(u32::MAX);
|
||||
errors.truncate(limit);
|
||||
(errors, count)
|
||||
}
|
||||
|
||||
/// `java.project.getClasspaths` result.
|
||||
@@ -251,10 +210,6 @@ impl LspManager {
|
||||
/// 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 };
|
||||
let (errors, error_count) = match build {
|
||||
Some(JavaBuildStatus::WithErrors | JavaBuildStatus::Failed) => 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 {
|
||||
Ok(home) => home,
|
||||
@@ -270,24 +225,9 @@ impl LspManager {
|
||||
module_paths: cp.module_paths,
|
||||
java_home: java_home.map(Into::into),
|
||||
java_exec: None,
|
||||
errors,
|
||||
error_count,
|
||||
hints: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
/// 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 collect = || compile_errors(server.diagnostics_snapshot(), MAX_LAUNCH_ERRORS);
|
||||
let found = collect();
|
||||
if found.1 > 0 {
|
||||
return found;
|
||||
}
|
||||
let _ = tokio::time::timeout(ERRORS_WAIT, server.published_notify.notified()).await;
|
||||
collect()
|
||||
}
|
||||
|
||||
/// Starts (or reuses) java-debug's DAP server inside jdtls and returns its port.
|
||||
pub async fn java_debug_server(&self, path: &Path) -> IdeResult<u16> {
|
||||
let v = self.jdtls_command(path, "vscode.java.startDebugSession", Vec::new()).await.map_err(|e| {
|
||||
@@ -316,28 +256,6 @@ impl LspManager {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn launch_errors_are_sorted_and_capped() {
|
||||
let diag = |line: u32, severity, message: &str| lsp_types::Diagnostic {
|
||||
range: lsp_types::Range::new(lsp_types::Position::new(line, 4), lsp_types::Position::new(line, 9)),
|
||||
severity: Some(severity),
|
||||
message: message.into(),
|
||||
..Default::default()
|
||||
};
|
||||
let (errors, count) = compile_errors(
|
||||
vec![
|
||||
(PathBuf::from("/p/B.java"), diag(1, lsp_types::DiagnosticSeverity::ERROR, "b")),
|
||||
(PathBuf::from("/p/A.java"), diag(9, lsp_types::DiagnosticSeverity::ERROR, "a2\nmore")),
|
||||
(PathBuf::from("/p/A.java"), diag(2, lsp_types::DiagnosticSeverity::WARNING, "warning")),
|
||||
(PathBuf::from("/p/A.java"), diag(3, lsp_types::DiagnosticSeverity::ERROR, "a1")),
|
||||
],
|
||||
2,
|
||||
);
|
||||
assert_eq!(count, 3);
|
||||
let shown: Vec<(u32, u32, &str)> = errors.iter().map(|e| (e.line, e.column, e.message.as_str())).collect();
|
||||
assert_eq!(shown, [(4, 5, "a1"), (10, 5, "a2")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classpaths() {
|
||||
let v = json!({
|
||||
|
||||
@@ -330,12 +330,6 @@ impl Server {
|
||||
self.diagnostics.lock().get(path).cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Every published diagnostic, by file.
|
||||
pub fn diagnostics_snapshot(&self) -> Vec<(PathBuf, lsp::Diagnostic)> {
|
||||
let d = self.diagnostics.lock();
|
||||
d.iter().flat_map(|(p, items)| items.iter().map(move |i| (p.clone(), i.clone()))).collect()
|
||||
}
|
||||
|
||||
pub fn take_diagnostic_paths(&self) -> Vec<PathBuf> {
|
||||
self.published.lock().clear();
|
||||
self.diagnostics.lock().drain().map(|(p, _)| p).collect()
|
||||
|
||||
@@ -56,55 +56,6 @@ fn goroot(root: &Path, s: &Settings) -> Option<PathBuf> {
|
||||
setting_path(root, &s.languages.go.goroot)
|
||||
}
|
||||
|
||||
/// The project JDK (`languages.java.jdk`): a JDK home, its `bin` or its `bin/java`.
|
||||
pub fn project_jdk(root: &Path, s: &Settings) -> Option<crate::java::Jdk> {
|
||||
let p = setting_path(root, &s.languages.java.jdk)?;
|
||||
let jdk = p.ancestors().take(3).find_map(crate::java::jdk_at);
|
||||
if jdk.is_none() {
|
||||
tracing::warn!("project JDK {} is not a JDK home", p.display());
|
||||
}
|
||||
jdk
|
||||
}
|
||||
|
||||
/// `mvn` of the configured Maven home (`languages.java.maven.home`): the
|
||||
/// executable itself, `<home>/bin/mvn` or `<bin>/mvn`.
|
||||
pub fn maven_command(root: &Path, s: &Settings) -> Option<PathBuf> {
|
||||
let p = setting_path(root, &s.languages.java.maven.home)?;
|
||||
let name = if cfg!(windows) { "mvn.cmd" } else { "mvn" };
|
||||
let found = [p.clone(), p.join("bin").join(name), p.join(name)].into_iter().find(|c| c.is_file());
|
||||
if found.is_none() {
|
||||
tracing::warn!("Maven home {} has no {name}", p.display());
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// Maven options from settings, placed before the goals: `-s <settings.xml>`
|
||||
/// and `-Dmaven.repo.local=<dir>`.
|
||||
pub fn maven_options(root: &Path, s: &Settings) -> Vec<String> {
|
||||
let m = &s.languages.java.maven;
|
||||
let mut out = Vec::new();
|
||||
if let Some(file) = setting_path(root, &m.user_settings) {
|
||||
out.extend(["-s".to_owned(), file.to_string_lossy().into_owned()]);
|
||||
}
|
||||
if let Some(dir) = setting_path(root, &m.local_repository) {
|
||||
out.push(format!("-Dmaven.repo.local={}", dir.to_string_lossy()));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The Maven local repository from settings: the configured one, else
|
||||
/// `<localRepository>` of the configured user `settings.xml`; `None` = Maven's default.
|
||||
pub fn maven_local_repository(root: &Path, s: &Settings) -> Option<PathBuf> {
|
||||
let m = &s.languages.java.maven;
|
||||
setting_path(root, &m.local_repository).or_else(|| {
|
||||
let text = std::fs::read_to_string(setting_path(root, &m.user_settings)?).ok()?;
|
||||
let repo = crate::java::xml_value(&crate::lombok::strip_xml_comments(&text), "localRepository")?;
|
||||
let home = crate::home_dir().map(|h| h.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let repo = repo.replace("${user.home}", &home);
|
||||
(!repo.is_empty() && !repo.contains("${")).then(|| PathBuf::from(repo))
|
||||
})
|
||||
}
|
||||
|
||||
/// TypeScript `lib` directory for the selected version; `None` = the server's bundled one.
|
||||
pub fn tsdk(root: &Path, s: &Settings) -> Option<PathBuf> {
|
||||
match s.languages.typescript.version.trim() {
|
||||
@@ -215,20 +166,6 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
|
||||
}
|
||||
}
|
||||
|
||||
if name == "jdtls" {
|
||||
// The jdtls launcher forwards `--jvm-arg=` values to the JVM it starts.
|
||||
let args = s.languages.java.jdtls_vm_args.split_whitespace().map(|a| format!("--jvm-arg={a}"));
|
||||
cfg.args.extend(args);
|
||||
// m2e (the Maven import) reads mirrors, servers and `<localRepository>` from it.
|
||||
if let Some(file) = setting_path(root, &s.languages.java.maven.user_settings) {
|
||||
let file = file.to_string_lossy();
|
||||
merge_init_options(
|
||||
cfg,
|
||||
json!({ "settings": { "java": { "configuration": { "maven": { "userSettings": file } } } } }),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(lib) = tsdk(server_root, s).or_else(|| tsdk(root, s)) {
|
||||
let lib_s = lib.to_string_lossy().into_owned();
|
||||
match name {
|
||||
@@ -263,8 +200,7 @@ const PY_RUNNERS: [&str; 3] = ["uv", "poetry", "pdm"];
|
||||
|
||||
/// Points run configurations at the selected toolchains: Python configs use the
|
||||
/// project interpreter, npm scripts the chosen package manager and Node.js,
|
||||
/// cargo / go configs the selected toolchain, Maven / Gradle the project JDK
|
||||
/// (and Maven the configured home and options).
|
||||
/// cargo / go configs the selected toolchain.
|
||||
pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings) {
|
||||
let explicit_python = setting_path(root, &s.languages.python.interpreter);
|
||||
let python = python_interpreter(root, s);
|
||||
@@ -273,9 +209,6 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
|
||||
let rust = rust_bin(root, s);
|
||||
let go = goroot(root, s);
|
||||
let gopath = setting_path(root, &s.languages.go.gopath);
|
||||
let jdk = project_jdk(root, s);
|
||||
let mvn = maven_command(root, s);
|
||||
let mvn_options = maven_options(root, s);
|
||||
|
||||
for c in configs.iter_mut() {
|
||||
let mut path_dirs: Vec<PathBuf> = Vec::new();
|
||||
@@ -342,19 +275,6 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
|
||||
c.env.entry("GOPATH".into()).or_insert_with(|| gopath.to_string_lossy().into_owned());
|
||||
}
|
||||
}
|
||||
"maven" | "gradle" => {
|
||||
if let Some(jdk) = &jdk {
|
||||
c.env.entry("JAVA_HOME".into()).or_insert_with(|| jdk.home.to_string_lossy().into_owned());
|
||||
}
|
||||
if c.kind == "maven" && c.detected {
|
||||
if let Some(mvn) = &mvn {
|
||||
c.command = mvn.to_string_lossy().into_owned();
|
||||
}
|
||||
if !c.args.starts_with(&mvn_options) {
|
||||
c.args.splice(0..0, mvn_options.iter().cloned());
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if !path_dirs.is_empty() && !c.env.contains_key("PATH") {
|
||||
|
||||
@@ -18,8 +18,6 @@ pub fn detect(kind: SdkKind, root: Option<&Path>) -> Vec<Sdk> {
|
||||
SdkKind::Rust => rust(),
|
||||
SdkKind::Go => go(),
|
||||
SdkKind::TypeScript => typescript(root),
|
||||
SdkKind::Jdk => jdk(),
|
||||
SdkKind::Maven => maven(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -384,108 +382,3 @@ fn typescript(root: Option<&Path>) -> Vec<Sdk> {
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ jdk
|
||||
|
||||
/// `KEY="value"` of a JDK `release` file.
|
||||
fn release_value(release: &str, key: &str) -> Option<String> {
|
||||
let line = release.lines().find_map(|l| l.trim().strip_prefix(key)?.strip_prefix('='))?;
|
||||
Some(line.trim().trim_matches('"').to_owned()).filter(|v| !v.is_empty())
|
||||
}
|
||||
|
||||
fn jdk() -> Vec<Sdk> {
|
||||
let java_home = std::env::var_os("JAVA_HOME").and_then(|h| dunce::canonicalize(h).ok());
|
||||
crate::java::rescan_jdks()
|
||||
.iter()
|
||||
.map(|j| {
|
||||
let release = std::fs::read_to_string(j.home.join("release")).unwrap_or_default();
|
||||
let version = release_value(&release, "JAVA_VERSION").unwrap_or_else(|| j.major.to_string());
|
||||
let name = match release_value(&release, "IMPLEMENTOR") {
|
||||
Some(vendor) => format!("{vendor} {version}"),
|
||||
None => format!("JDK {version}"),
|
||||
};
|
||||
let source = if java_home.as_ref() == Some(&j.home) { "JAVA_HOME" } else { "system" };
|
||||
Sdk {
|
||||
path: j.home.clone().into(),
|
||||
name,
|
||||
version: Some(version),
|
||||
source: source.to_owned(),
|
||||
home: Some(j.home.clone().into()),
|
||||
extra: None,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ maven
|
||||
|
||||
/// Maven version from `lib/maven-core-<version>.jar`.
|
||||
fn maven_version(home: &Path) -> Option<String> {
|
||||
std::fs::read_dir(home.join("lib")).ok()?.flatten().find_map(|e| {
|
||||
let name = e.file_name().to_string_lossy().into_owned();
|
||||
Some(name.strip_prefix("maven-core-")?.strip_suffix(".jar")?.to_owned())
|
||||
})
|
||||
}
|
||||
|
||||
/// A Maven home (`bin/mvn` and `lib/`); Homebrew's formula keeps it in `libexec`.
|
||||
fn maven_home(dir: &Path) -> Option<PathBuf> {
|
||||
let mvn = if cfg!(windows) { "mvn.cmd" } else { "mvn" };
|
||||
[dir.join("libexec"), dir.to_path_buf()]
|
||||
.into_iter()
|
||||
.find(|h| h.join("bin").join(mvn).is_file() && h.join("lib").is_dir())
|
||||
}
|
||||
|
||||
fn maven() -> Vec<Sdk> {
|
||||
let mut found: Vec<(PathBuf, &'static str)> = Vec::new();
|
||||
// Windows' Maven ships `mvn.cmd` only (`which` looks for `mvn.exe`).
|
||||
let on_path = if cfg!(windows) {
|
||||
std::env::split_paths(&search_path()).map(|d| d.join("mvn.cmd")).find(|p| p.is_file())
|
||||
} else {
|
||||
which("mvn")
|
||||
};
|
||||
if let Some(mvn) = on_path.and_then(|p| dunce::canonicalize(p).ok())
|
||||
&& let Some(home) = mvn.parent().and_then(Path::parent)
|
||||
{
|
||||
found.push((home.to_path_buf(), "path"));
|
||||
}
|
||||
for var in ["MAVEN_HOME", "M2_HOME"] {
|
||||
if let Some(h) = std::env::var_os(var) {
|
||||
found.push((PathBuf::from(h), "env"));
|
||||
}
|
||||
}
|
||||
for p in ["/opt/homebrew/opt/maven", "/usr/local/opt/maven", "/usr/share/maven", "/opt/maven"] {
|
||||
found.push((PathBuf::from(p), "system"));
|
||||
}
|
||||
if let Some(home) = home_dir() {
|
||||
for d in subdirs(&home.join(".sdkman/candidates/maven")) {
|
||||
found.push((d, "sdkman"));
|
||||
}
|
||||
// Distributions the Maven wrapper downloaded: `dists/apache-maven-3.9.6-bin/<hash>/apache-maven-3.9.6`,
|
||||
// or since wrapper 3.3 the home itself, `dists/apache-maven-3.9.6/<hash>`.
|
||||
for dist in subdirs(&home.join(".m2/wrapper/dists")) {
|
||||
for hash in subdirs(&dist) {
|
||||
found.extend(subdirs(&hash).into_iter().map(|d| (d, "wrapper")));
|
||||
found.push((hash, "wrapper"));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
let mut out = Vec::new();
|
||||
for (dir, source) in found {
|
||||
let Some(home) = maven_home(&dir) else { continue };
|
||||
let home = dunce::canonicalize(&home).unwrap_or(home);
|
||||
if !seen.insert(home.clone()) {
|
||||
continue;
|
||||
}
|
||||
let version = maven_version(&home);
|
||||
out.push(Sdk {
|
||||
path: home.clone().into(),
|
||||
name: format!("Maven {}", version.clone().unwrap_or_default()).trim().to_owned(),
|
||||
version,
|
||||
source: source.to_owned(),
|
||||
home: Some(home.into()),
|
||||
extra: None,
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -25,8 +25,7 @@ pub fn parse_release(release: &str) -> Option<u32> {
|
||||
if first == 1 { parts.next()?.parse().ok() } else { Some(first) }
|
||||
}
|
||||
|
||||
/// The JDK at `home`, if it is one (a `release` file and `bin/java`).
|
||||
pub fn jdk_at(home: &Path) -> Option<Jdk> {
|
||||
fn jdk_at(home: &Path) -> Option<Jdk> {
|
||||
let release = std::fs::read_to_string(home.join("release")).ok()?;
|
||||
if !home.join("bin").join(crate::exe("java")).is_file() {
|
||||
return None;
|
||||
@@ -118,11 +117,6 @@ fn rescan(slot: &mut Option<Scan>) -> Arc<[Jdk]> {
|
||||
slot.insert(Scan { at: Instant::now(), jdks: scan().into() }).jdks.clone()
|
||||
}
|
||||
|
||||
/// Scans for installed JDKs again (Settings › Detect again).
|
||||
pub fn rescan_jdks() -> Arc<[Jdk]> {
|
||||
rescan(&mut JDKS.lock().unwrap_or_else(|e| e.into_inner()))
|
||||
}
|
||||
|
||||
/// Installed JDKs (scanned on first use; [`jdtls_jdks`] may refresh them).
|
||||
pub fn installed_jdks() -> Arc<[Jdk]> {
|
||||
let mut slot = JDKS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
@@ -264,33 +258,20 @@ const METADATA_PROPERTY: &str = "java.import.generatesMetadataFilesAtProjectRoot
|
||||
/// directory, one per server root, and no Eclipse metadata is written into
|
||||
/// the project; it runs on a JDK `min_java`+ (via `JAVA_HOME`, which its
|
||||
/// launcher reads), installed JDKs are registered as runtimes and `bundles`
|
||||
/// (e.g. the java-debug plugin jar) are loaded into the server. The project
|
||||
/// JDK, when set, is the default runtime and preferred for running the server.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
/// (e.g. the java-debug plugin jar) are loaded into the server.
|
||||
pub fn configure_jdtls(
|
||||
cfg: &mut LanguageServerConfig,
|
||||
server_root: &Path,
|
||||
data_dir: &Path,
|
||||
jdks: &[Jdk],
|
||||
project_jdk: Option<&Jdk>,
|
||||
min_java: u32,
|
||||
bundles: &[PathBuf],
|
||||
lombok: Option<&Path>,
|
||||
) {
|
||||
if cfg.name != "jdtls" {
|
||||
return;
|
||||
}
|
||||
// A Lombok agent from the user's JVM arguments wins.
|
||||
let own_agent = crate::lombok::agent_in_args(cfg.args.iter().map(String::as_str));
|
||||
let agent = own_agent.as_deref().or(lombok);
|
||||
if !cfg.args.iter().any(|a| a == "-data") {
|
||||
// ECJ builds incrementally: classes compiled without (or with another) Lombok
|
||||
// agent would be kept, so each agent gets its own workspace and a full build.
|
||||
let key = match agent {
|
||||
Some(jar) => format!("{}-{}", path_key(server_root), path_key(jar)),
|
||||
None => path_key(server_root),
|
||||
};
|
||||
let dir = data_dir.join("lsp").join("jdtls").join(key);
|
||||
let dir = data_dir.join("lsp").join("jdtls").join(path_key(server_root));
|
||||
cfg.args.extend(["-data".to_owned(), dir.to_string_lossy().into_owned()]);
|
||||
}
|
||||
// jdtls reads this one as a system property (its file-system bundle
|
||||
@@ -298,14 +279,6 @@ pub fn configure_jdtls(
|
||||
if !cfg.args.iter().any(|a| a.contains(METADATA_PROPERTY)) {
|
||||
cfg.args.push(format!("--jvm-arg=-D{METADATA_PROPERTY}=false"));
|
||||
}
|
||||
if own_agent.is_none()
|
||||
&& let Some(jar) = lombok
|
||||
{
|
||||
cfg.args.push(format!("--jvm-arg=-javaagent:{}", jar.to_string_lossy()));
|
||||
}
|
||||
let jdks: Vec<Jdk> =
|
||||
project_jdk.into_iter().chain(jdks.iter().filter(|j| Some(*j) != project_jdk)).cloned().collect();
|
||||
let jdks = jdks.as_slice();
|
||||
if !cfg.env.contains_key("JAVA_HOME") {
|
||||
match jdtls_runtime(jdks, min_java) {
|
||||
Some(jdk) => {
|
||||
@@ -314,15 +287,7 @@ pub fn configure_jdtls(
|
||||
None => cfg.launch_error = Some(missing_runtime_message(jdks, min_java)),
|
||||
}
|
||||
}
|
||||
let mut runtimes = runtimes(jdks);
|
||||
if let Some(project) = project_jdk {
|
||||
let home = project.home.to_string_lossy();
|
||||
for r in &mut runtimes {
|
||||
if r["path"] == *home {
|
||||
r["default"] = json!(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
let runtimes = runtimes(jdks);
|
||||
if !runtimes.is_empty() {
|
||||
merge_init_options(cfg, json!({ "settings": { "java": { "configuration": { "runtimes": runtimes } } } }));
|
||||
}
|
||||
@@ -404,7 +369,7 @@ pub fn project_java_version(module_dir: &Path) -> Option<u32> {
|
||||
None
|
||||
}
|
||||
|
||||
pub(crate) fn xml_value(text: &str, tag: &str) -> Option<String> {
|
||||
fn xml_value(text: &str, tag: &str) -> Option<String> {
|
||||
let open = format!("<{tag}>");
|
||||
let start = text.find(&open)? + open.len();
|
||||
let end = text[start..].find('<')?;
|
||||
@@ -444,16 +409,7 @@ mod tests {
|
||||
Jdk { major: 8, home: PathBuf::from("/jdk8") },
|
||||
];
|
||||
let bundles = [PathBuf::from("/tools/java-debug/bin/com.microsoft.java.debug.plugin.jar")];
|
||||
configure_jdtls(
|
||||
&mut cfg,
|
||||
Path::new("/p/demo"),
|
||||
Path::new("/data"),
|
||||
&jdks,
|
||||
None,
|
||||
JDTLS_MIN_JAVA,
|
||||
&bundles,
|
||||
None,
|
||||
);
|
||||
configure_jdtls(&mut cfg, Path::new("/p/demo"), Path::new("/data"), &jdks, JDTLS_MIN_JAVA, &bundles);
|
||||
assert_eq!(cfg.args[0], "-data");
|
||||
assert!(cfg.args[1].starts_with("/data/lsp/jdtls/"), "{}", cfg.args[1]);
|
||||
assert_eq!(cfg.args[2], "--jvm-arg=-Djava.import.generatesMetadataFilesAtProjectRoot=false");
|
||||
@@ -468,84 +424,32 @@ mod tests {
|
||||
|
||||
// Deterministic (reconfigure compares configs) and idempotent.
|
||||
let before = cfg.clone();
|
||||
configure_jdtls(
|
||||
&mut cfg,
|
||||
Path::new("/p/demo"),
|
||||
Path::new("/data"),
|
||||
&jdks,
|
||||
None,
|
||||
JDTLS_MIN_JAVA,
|
||||
&bundles,
|
||||
None,
|
||||
);
|
||||
configure_jdtls(&mut cfg, Path::new("/p/demo"), Path::new("/data"), &jdks, JDTLS_MIN_JAVA, &bundles);
|
||||
assert_eq!(cfg, before);
|
||||
|
||||
// The project JDK is the default runtime, and runs the server when new enough.
|
||||
let project = Jdk { major: 21, home: PathBuf::from("/jdk21b") };
|
||||
let mut cfg: LanguageServerConfig = toml::from_str("name = \"jdtls\"\ncommand = \"jdtls\"").unwrap();
|
||||
configure_jdtls(
|
||||
&mut cfg,
|
||||
Path::new("/p"),
|
||||
Path::new("/data"),
|
||||
&jdks,
|
||||
Some(&project),
|
||||
JDTLS_MIN_JAVA,
|
||||
&[],
|
||||
None,
|
||||
);
|
||||
let opts = serde_json::to_value(cfg.initialization_options.clone().unwrap()).unwrap();
|
||||
let rt = &opts["settings"]["java"]["configuration"]["runtimes"];
|
||||
assert_eq!(rt[1], json!({ "name": "JavaSE-21", "path": "/jdk21b", "default": true }));
|
||||
assert_eq!(cfg.env["JAVA_HOME"], "/jdk21b");
|
||||
|
||||
let mut other: LanguageServerConfig = toml::from_str("name = \"pyright\"\ncommand = \"x\"").unwrap();
|
||||
configure_jdtls(&mut other, Path::new("/p"), Path::new("/data"), &jdks, None, JDTLS_MIN_JAVA, &bundles, None);
|
||||
configure_jdtls(&mut other, Path::new("/p"), Path::new("/data"), &jdks, JDTLS_MIN_JAVA, &bundles);
|
||||
assert!(other.args.is_empty() && other.initialization_options.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jdtls_lombok_agent() {
|
||||
let jdtls = || -> LanguageServerConfig { toml::from_str("name = \"jdtls\"\ncommand = \"jdtls\"").unwrap() };
|
||||
let jar = Path::new("/m2/lombok-1.18.48.jar");
|
||||
let mut cfg = jdtls();
|
||||
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], None, JDTLS_MIN_JAVA, &[], Some(jar));
|
||||
let agent = format!("--jvm-arg=-javaagent:{}", jar.to_string_lossy());
|
||||
assert!(cfg.args.contains(&agent), "{:?}", cfg.args);
|
||||
let mut plain = jdtls();
|
||||
configure_jdtls(&mut plain, Path::new("/p"), Path::new("/data"), &[], None, JDTLS_MIN_JAVA, &[], None);
|
||||
assert_ne!(cfg.args[1], plain.args[1], "a separate workspace, so everything is rebuilt with the agent");
|
||||
let before = cfg.clone();
|
||||
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], None, JDTLS_MIN_JAVA, &[], Some(jar));
|
||||
assert_eq!(cfg, before, "idempotent");
|
||||
|
||||
let mut cfg = jdtls();
|
||||
cfg.args.push("--jvm-arg=-javaagent:/own/lombok.jar".into());
|
||||
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], None, JDTLS_MIN_JAVA, &[], Some(jar));
|
||||
assert!(!cfg.args.contains(&agent), "the user's agent wins");
|
||||
let mut own = jdtls();
|
||||
own.args.push("--jvm-arg=-javaagent:/own/lombok.jar".into());
|
||||
configure_jdtls(&mut own, Path::new("/p"), Path::new("/data"), &[], None, JDTLS_MIN_JAVA, &[], None);
|
||||
assert_eq!(cfg.args, own.args, "its workspace follows the agent in use");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jdtls_needs_a_new_enough_jdk_to_run() {
|
||||
let jdtls = || -> LanguageServerConfig { toml::from_str("name = \"jdtls\"\ncommand = \"jdtls\"").unwrap() };
|
||||
let old = [Jdk { major: 17, home: PathBuf::from("/jdk17") }, Jdk { major: 8, home: PathBuf::from("/jdk8") }];
|
||||
let mut cfg = jdtls();
|
||||
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &old, None, JDTLS_MIN_JAVA, &[], None);
|
||||
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &old, JDTLS_MIN_JAVA, &[]);
|
||||
assert!(!cfg.env.contains_key("JAVA_HOME"));
|
||||
let err = cfg.launch_error.unwrap();
|
||||
assert!(err.contains("JDK 21 or newer") && err.contains("found JDK 8, 17"), "{err}");
|
||||
|
||||
let mut cfg = jdtls();
|
||||
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], None, JDTLS_MIN_JAVA, &[], None);
|
||||
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], JDTLS_MIN_JAVA, &[]);
|
||||
assert!(cfg.launch_error.unwrap().contains("no JDK was found"));
|
||||
|
||||
// An explicit JAVA_HOME is the user's call.
|
||||
let mut cfg = jdtls();
|
||||
cfg.env.insert("JAVA_HOME".into(), "/custom".into());
|
||||
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &old, None, JDTLS_MIN_JAVA, &[], None);
|
||||
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &old, JDTLS_MIN_JAVA, &[]);
|
||||
assert_eq!((cfg.env["JAVA_HOME"].as_str(), cfg.launch_error), ("/custom", None));
|
||||
|
||||
let mixed = [old[0].clone(), Jdk { major: 21, home: PathBuf::from("/jdk21") }];
|
||||
@@ -553,7 +457,7 @@ mod tests {
|
||||
|
||||
// A jdtls whose bundles need 25 doesn't start on 21, and says what it needs.
|
||||
let mut cfg = jdtls();
|
||||
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &mixed, None, 25, &[], None);
|
||||
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &mixed, 25, &[]);
|
||||
let err = cfg.launch_error.unwrap();
|
||||
assert!(err.contains("JDK 25 or newer") && err.contains("found JDK 17, 21"), "{err}");
|
||||
}
|
||||
|
||||
@@ -10,7 +10,6 @@ mod discover;
|
||||
mod exec;
|
||||
pub mod java;
|
||||
pub mod locate;
|
||||
pub mod lombok;
|
||||
pub mod python;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -31,10 +30,6 @@ pub enum SdkKind {
|
||||
Rust,
|
||||
Go,
|
||||
TypeScript,
|
||||
/// JDK homes.
|
||||
Jdk,
|
||||
/// Maven homes.
|
||||
Maven,
|
||||
}
|
||||
|
||||
/// One installed interpreter / toolchain.
|
||||
|
||||
@@ -1,278 +0,0 @@
|
||||
//! Lombok for jdtls: ECJ only generates Lombok members when the language
|
||||
//! server's JVM runs `-javaagent:lombok.jar`, so a project using Lombok gets the
|
||||
//! newest jar available, managed (installed by the IDE) or in the Maven / Gradle caches.
|
||||
|
||||
use crate::home_dir;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Oldest Lombok whose ECJ handlers work in current jdtls builds (Eclipse 2024-06 support);
|
||||
/// older ones throw `NoSuchMethodError` and drop every annotation of the compilation unit.
|
||||
pub const LOMBOK_MIN: [u32; 3] = [1, 18, 34];
|
||||
|
||||
/// What a jdtls instance gets for Lombok.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum LombokAgent {
|
||||
/// The project doesn't use Lombok.
|
||||
Unused,
|
||||
/// The project uses Lombok but no jar was found.
|
||||
Missing,
|
||||
Found {
|
||||
jar: PathBuf,
|
||||
/// `None` for the managed jar (the latest release when installed).
|
||||
version: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
impl LombokAgent {
|
||||
pub fn jar(&self) -> Option<&Path> {
|
||||
match self {
|
||||
Self::Found { jar, .. } => Some(jar),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Too old for current jdtls.
|
||||
pub fn outdated(&self) -> bool {
|
||||
matches!(self, Self::Found { version: Some(v), .. } if parse_version(v).is_some_and(|v| v < LOMBOK_MIN))
|
||||
}
|
||||
|
||||
/// Why Lombok-generated members may be missing, if they may be.
|
||||
pub fn problem(&self) -> Option<String> {
|
||||
const INSTALL: &str =
|
||||
"Install Lombok in Settings › Languages & Frameworks › Language Servers (jdtls restarts with it)";
|
||||
match self {
|
||||
Self::Missing => Some(format!(
|
||||
"The project uses Lombok, but no lombok.jar was found for the Java language server, so Lombok-generated \
|
||||
members are missing. {INSTALL}."
|
||||
)),
|
||||
Self::Found { version: Some(v), .. } if self.outdated() => Some(format!(
|
||||
"Lombok {v} is too old for the Java language server (needs {}.{}.{} or newer): classes using it may \
|
||||
miss generated members. {INSTALL}.",
|
||||
LOMBOK_MIN[0], LOMBOK_MIN[1], LOMBOK_MIN[2]
|
||||
)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Lombok jar of a `-javaagent:` among JVM arguments (bare or as `--jvm-arg=`).
|
||||
pub fn agent_in_args<'a>(args: impl IntoIterator<Item = &'a str>) -> Option<PathBuf> {
|
||||
args.into_iter().find_map(|a| {
|
||||
let jar = a.split_once("-javaagent:")?.1;
|
||||
jar.to_ascii_lowercase().contains("lombok").then(|| PathBuf::from(jar))
|
||||
})
|
||||
}
|
||||
|
||||
/// The Lombok agent for the project at `root`: the user's own (`own`, from the JVM
|
||||
/// options) wins, then `managed` (the IDE-installed jar), then the build caches
|
||||
/// (`maven_repo`, the configured Maven local repository, else the default one).
|
||||
pub fn lombok_agent(
|
||||
root: &Path,
|
||||
own: Option<PathBuf>,
|
||||
managed: Option<PathBuf>,
|
||||
maven_repo: Option<PathBuf>,
|
||||
) -> LombokAgent {
|
||||
if let Some(jar) = own {
|
||||
let version = jar
|
||||
.file_stem()
|
||||
.and_then(|s| s.to_str()?.strip_prefix("lombok-"))
|
||||
.filter(|v| parse_version(v).is_some())
|
||||
.map(str::to_owned);
|
||||
return LombokAgent::Found { jar, version };
|
||||
}
|
||||
if !uses_lombok(root) {
|
||||
return LombokAgent::Unused;
|
||||
}
|
||||
if let Some(jar) = managed {
|
||||
return LombokAgent::Found { jar, version: None };
|
||||
}
|
||||
let home = home_dir();
|
||||
let mut dirs = Vec::new();
|
||||
if let Some(repo) = maven_repo.or_else(|| maven_repository(home.as_deref())) {
|
||||
dirs.push(repo.join("org").join("projectlombok").join("lombok"));
|
||||
}
|
||||
if let Some(gradle) =
|
||||
std::env::var_os("GRADLE_USER_HOME").map(PathBuf::from).or_else(|| home.map(|h| h.join(".gradle")))
|
||||
{
|
||||
dirs.push(gradle.join("caches").join("modules-2").join("files-2.1").join("org.projectlombok").join("lombok"));
|
||||
}
|
||||
match newest_cached(&dirs) {
|
||||
Some((version, jar)) => LombokAgent::Found { jar, version: Some(version) },
|
||||
None => LombokAgent::Missing,
|
||||
}
|
||||
}
|
||||
|
||||
/// Build files under `root` (a few levels, for multi-module builds) mentioning Lombok.
|
||||
pub fn uses_lombok(root: &Path) -> bool {
|
||||
const FILES: [&str; 4] = ["pom.xml", "build.gradle", "build.gradle.kts", "libs.versions.toml"];
|
||||
const SKIP: [&str; 7] = ["target", "build", "node_modules", "out", "bin", "src", ".gradle"];
|
||||
fn walk(dir: &Path, depth: usize) -> bool {
|
||||
if dir.join("lombok.config").is_file() {
|
||||
return true;
|
||||
}
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return false };
|
||||
let mut subdirs = Vec::new();
|
||||
for e in entries.flatten() {
|
||||
let name = e.file_name();
|
||||
let name = name.to_string_lossy();
|
||||
let Ok(ty) = e.file_type() else { continue };
|
||||
if ty.is_dir() {
|
||||
if depth > 0 && !name.starts_with('.') && !SKIP.contains(&name.as_ref()) {
|
||||
subdirs.push(e.path());
|
||||
}
|
||||
} else if FILES.contains(&name.as_ref())
|
||||
&& std::fs::read_to_string(e.path()).is_ok_and(|t| t.contains("lombok"))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
subdirs.iter().any(|d| walk(d, depth - 1))
|
||||
}
|
||||
// `gradle/libs.versions.toml` sits one level down, modules usually no deeper than three.
|
||||
walk(root, 3)
|
||||
}
|
||||
|
||||
/// `<localRepository>` of `~/.m2/settings.xml`, else `~/.m2/repository`.
|
||||
fn maven_repository(home: Option<&Path>) -> Option<PathBuf> {
|
||||
let m2 = home?.join(".m2");
|
||||
let custom = std::fs::read_to_string(m2.join("settings.xml"))
|
||||
.ok()
|
||||
.and_then(|s| crate::java::xml_value(&strip_xml_comments(&s), "localRepository"))
|
||||
.filter(|v| !v.is_empty() && !v.contains("${"))
|
||||
.map(PathBuf::from);
|
||||
Some(custom.unwrap_or_else(|| m2.join("repository")))
|
||||
}
|
||||
|
||||
pub(crate) fn strip_xml_comments(text: &str) -> String {
|
||||
let mut out = String::with_capacity(text.len());
|
||||
let mut rest = text;
|
||||
while let Some(i) = rest.find("<!--") {
|
||||
out.push_str(&rest[..i]);
|
||||
rest = rest[i..].find("-->").map_or("", |j| &rest[i + j + 3..]);
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
|
||||
/// Highest release `<dir>/<version>/…/lombok-<version>.jar` (Maven: directly in
|
||||
/// the version directory; Gradle: one hash directory below it).
|
||||
fn newest_cached(dirs: &[PathBuf]) -> Option<(String, PathBuf)> {
|
||||
let mut best: Option<([u32; 3], String, PathBuf)> = None;
|
||||
for dir in dirs {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { continue };
|
||||
for e in entries.flatten() {
|
||||
let version = e.file_name().to_string_lossy().into_owned();
|
||||
let Some(parsed) = parse_version(&version) else { continue };
|
||||
if best.as_ref().is_some_and(|(b, ..)| *b >= parsed) {
|
||||
continue;
|
||||
}
|
||||
let name = format!("lombok-{version}.jar");
|
||||
let direct = e.path().join(&name);
|
||||
let jar = if direct.is_file() {
|
||||
Some(direct)
|
||||
} else {
|
||||
std::fs::read_dir(e.path())
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.map(|h| h.path().join(&name))
|
||||
.find(|p| p.is_file())
|
||||
};
|
||||
if let Some(jar) = jar {
|
||||
best = Some((parsed, version, jar));
|
||||
}
|
||||
}
|
||||
}
|
||||
best.map(|(_, v, jar)| (v, jar))
|
||||
}
|
||||
|
||||
/// `1.18.34` → `[1, 18, 34]`; snapshots and other qualifiers don't count as releases.
|
||||
fn parse_version(v: &str) -> Option<[u32; 3]> {
|
||||
let mut parts = v.split('.').map(|p| p.parse::<u32>().ok());
|
||||
let out = [parts.next()??, parts.next()??, parts.next().unwrap_or(Some(0))?];
|
||||
parts.next().is_none().then_some(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
|
||||
#[test]
|
||||
fn detects_lombok_in_build_files() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
fs::write(root.join("pom.xml"), "<project><modules><module>api</module></modules></project>").unwrap();
|
||||
assert!(!uses_lombok(root));
|
||||
fs::create_dir_all(root.join("api/src/main")).unwrap();
|
||||
fs::write(root.join("api/src/main/pom.xml"), "<artifactId>lombok</artifactId>").unwrap();
|
||||
assert!(!uses_lombok(root), "sources are not scanned");
|
||||
fs::write(root.join("api/pom.xml"), "<artifactId>lombok</artifactId>").unwrap();
|
||||
assert!(uses_lombok(root));
|
||||
|
||||
let gradle = tempfile::tempdir().unwrap();
|
||||
fs::create_dir_all(gradle.path().join("gradle")).unwrap();
|
||||
fs::write(gradle.path().join("gradle/libs.versions.toml"), "lombok = \"org.projectlombok:lombok:1.18.30\"")
|
||||
.unwrap();
|
||||
assert!(uses_lombok(gradle.path()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picks_the_newest_cached_release() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let m2 = tmp.path().join("m2");
|
||||
let gradle = tmp.path().join("gradle");
|
||||
for v in ["1.18.26", "1.18.36", "1.18.99-SNAPSHOT"] {
|
||||
fs::create_dir_all(m2.join(v)).unwrap();
|
||||
fs::write(m2.join(v).join(format!("lombok-{v}.jar")), b"PK").unwrap();
|
||||
}
|
||||
fs::create_dir_all(m2.join("1.18.40")).unwrap(); // only a .pom: not usable
|
||||
fs::create_dir_all(gradle.join("1.18.38/abc123")).unwrap();
|
||||
fs::write(gradle.join("1.18.38/abc123/lombok-1.18.38.jar"), b"PK").unwrap();
|
||||
let (v, jar) = newest_cached(&[m2.clone(), gradle.clone()]).unwrap();
|
||||
assert_eq!(v, "1.18.38");
|
||||
assert_eq!(jar, gradle.join("1.18.38/abc123/lombok-1.18.38.jar"));
|
||||
assert_eq!(newest_cached(std::slice::from_ref(&m2)).unwrap().0, "1.18.36");
|
||||
assert_eq!(newest_cached(&[tmp.path().join("none")]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_versions_are_reported() {
|
||||
let found = |v: Option<&str>| LombokAgent::Found { jar: "/l.jar".into(), version: v.map(Into::into) };
|
||||
assert!(found(Some("1.18.26")).outdated());
|
||||
assert!(found(Some("1.18.26")).problem().unwrap().contains("1.18.26 is too old"));
|
||||
assert!(!found(Some("1.18.34")).outdated());
|
||||
assert_eq!(found(None).problem(), None);
|
||||
assert!(LombokAgent::Missing.problem().is_some());
|
||||
assert_eq!(LombokAgent::Unused.problem(), None);
|
||||
assert_eq!(parse_version("1.18"), Some([1, 18, 0]));
|
||||
assert_eq!(parse_version("edge-SNAPSHOT"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_users_agent_wins() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let own = agent_in_args(["--jvm-arg=-Xmx2g", "--jvm-arg=-javaagent:/opt/lombok-1.18.26.jar"]);
|
||||
assert_eq!(own.as_deref(), Some(Path::new("/opt/lombok-1.18.26.jar")));
|
||||
assert_eq!(agent_in_args(["-javaagent:/opt/other.jar"]), None);
|
||||
let agent = lombok_agent(tmp.path(), own, Some("/managed/lombok.jar".into()), None);
|
||||
assert_eq!(agent.jar(), Some(Path::new("/opt/lombok-1.18.26.jar")));
|
||||
assert!(agent.outdated(), "its version is read from the file name");
|
||||
let plain = lombok_agent(tmp.path(), agent_in_args(["-javaagent:/opt/lombok.jar"]), None, None);
|
||||
assert_eq!(plain.problem(), None, "a user agent is never reported missing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_settings_local_repository() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let home = tmp.path();
|
||||
assert_eq!(maven_repository(Some(home)), Some(home.join(".m2/repository")));
|
||||
fs::create_dir_all(home.join(".m2")).unwrap();
|
||||
fs::write(
|
||||
home.join(".m2/settings.xml"),
|
||||
"<settings><!-- <localRepository>/old</localRepository> --><localRepository>/repo</localRepository></settings>",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(maven_repository(Some(home)), Some(PathBuf::from("/repo")));
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,4 @@
|
||||
use crate::apply::{
|
||||
apply_to_run_configs, configure_server, maven_command, maven_options, project_jdk, python_interpreter,
|
||||
terminal_activation, tsdk,
|
||||
};
|
||||
use crate::apply::{apply_to_run_configs, configure_server, python_interpreter, terminal_activation, tsdk};
|
||||
use crate::python::parse_pip_list;
|
||||
use crate::{bin_dir, exe, venv_of};
|
||||
use ide_core::settings::Settings;
|
||||
@@ -77,16 +74,6 @@ fn pyright_gets_python_path_and_venv_env() {
|
||||
assert!(cfg.env["PATH"].starts_with(&*tmp.path().join(".venv").join(bin_dir()).to_string_lossy()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jdtls_vm_args() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut s = Settings::default();
|
||||
s.languages.java.jdtls_vm_args = " -Xmx2g -javaagent:/opt/lombok.jar ".into();
|
||||
let mut cfg = server("jdtls");
|
||||
configure_server(&mut cfg, tmp.path(), tmp.path(), &s);
|
||||
assert_eq!(cfg.args, ["--jvm-arg=-Xmx2g", "--jvm-arg=-javaagent:/opt/lombok.jar"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rust_analyzer_check_command_and_toolchain() {
|
||||
if cfg!(windows) {
|
||||
@@ -156,52 +143,6 @@ fn run_configs_use_selected_interpreter_and_package_manager() {
|
||||
assert_eq!(configs[4].command, "python3", "shell configs are left alone");
|
||||
}
|
||||
|
||||
fn fake_jdk(dir: &Path) {
|
||||
std::fs::create_dir_all(dir.join("bin")).unwrap();
|
||||
std::fs::write(dir.join("bin").join(exe("java")), "").unwrap();
|
||||
std::fs::write(dir.join("release"), "JAVA_VERSION=\"17.0.9\"\n").unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_jdk_and_maven_settings() {
|
||||
if cfg!(windows) {
|
||||
return; // Unix paths and shells
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let jdk = tmp.path().join("jdk17");
|
||||
fake_jdk(&jdk);
|
||||
let maven = tmp.path().join("maven");
|
||||
std::fs::create_dir_all(maven.join("bin")).unwrap();
|
||||
std::fs::write(maven.join("bin/mvn"), "").unwrap();
|
||||
|
||||
let mut s = Settings::default();
|
||||
assert_eq!(project_jdk(tmp.path(), &s), None);
|
||||
assert_eq!(maven_command(tmp.path(), &s), None);
|
||||
assert!(maven_options(tmp.path(), &s).is_empty());
|
||||
|
||||
// Project-relative paths, a JDK's `bin/java`, a Maven home.
|
||||
s.languages.java.jdk = "jdk17/bin/java".into();
|
||||
s.languages.java.maven.home = maven.to_string_lossy().into_owned();
|
||||
s.languages.java.maven.user_settings = "/m2/settings.xml".into();
|
||||
s.languages.java.maven.local_repository = "/m2/repo".into();
|
||||
assert_eq!(project_jdk(tmp.path(), &s).map(|j| j.major), Some(17));
|
||||
assert_eq!(maven_command(tmp.path(), &s), Some(maven.join("bin/mvn")));
|
||||
assert_eq!(maven_options(tmp.path(), &s), ["-s", "/m2/settings.xml", "-Dmaven.repo.local=/m2/repo"]);
|
||||
|
||||
let mut configs = vec![run("maven", "./mvnw", &["package"]), run("gradle", "./gradlew", &["build"])];
|
||||
apply_to_run_configs(&mut configs, tmp.path(), &s);
|
||||
let home = project_jdk(tmp.path(), &s).unwrap().home.to_string_lossy().into_owned();
|
||||
assert_eq!(configs[0].command, maven.join("bin/mvn").to_string_lossy());
|
||||
assert_eq!(configs[0].args, ["-s", "/m2/settings.xml", "-Dmaven.repo.local=/m2/repo", "package"]);
|
||||
assert_eq!(configs[0].env["JAVA_HOME"], home);
|
||||
assert_eq!(configs[1].env["JAVA_HOME"], home);
|
||||
apply_to_run_configs(&mut configs, tmp.path(), &s);
|
||||
assert_eq!(configs[0].args.len(), 4, "applied once");
|
||||
|
||||
s.languages.java.jdk = "missing".into();
|
||||
assert_eq!(project_jdk(tmp.path(), &s), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminal_activation_for_project_venv() {
|
||||
if cfg!(windows) {
|
||||
|
||||
@@ -216,10 +216,6 @@ fn usages(langs: &[LanguageConfig]) -> BTreeMap<String, Usage> {
|
||||
add(&d.adapter, &d.command, ToolKind::Debugger, d.install_hint.as_ref(), &l.name);
|
||||
}
|
||||
}
|
||||
for (plugin, host) in registry::PLUGIN_HOSTS {
|
||||
let languages = map.get(*host).map(|u| u.languages.clone()).unwrap_or_default();
|
||||
map.entry(plugin.to_string()).or_default().languages = languages;
|
||||
}
|
||||
map
|
||||
}
|
||||
|
||||
@@ -738,10 +734,6 @@ impl Tools {
|
||||
let json = http.get_text(&sources::openvsx_latest_url(namespace, extension), cancel)?;
|
||||
sources::openvsx_pick(&json, assets, self.platform)
|
||||
}
|
||||
ReleaseSource::MavenCentral { group, artifact } => {
|
||||
let xml = http.get_text(&sources::maven_metadata_url(group, artifact), cancel)?;
|
||||
sources::maven_pick(group, artifact, &xml)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,8 +10,6 @@ use specta::Type;
|
||||
pub enum ToolKind {
|
||||
LanguageServer,
|
||||
Debugger,
|
||||
/// Loaded into another tool's process, e.g. a jdtls agent.
|
||||
Plugin,
|
||||
}
|
||||
|
||||
/// Where release archives come from.
|
||||
@@ -25,8 +23,6 @@ pub enum ReleaseSource {
|
||||
EclipseJdtls,
|
||||
/// Latest version of a VS Code extension (`.vsix`) on open-vsx.org.
|
||||
OpenVsx { namespace: &'static str, extension: &'static str },
|
||||
/// Latest release of a Maven Central artifact (the `.jar` itself).
|
||||
MavenCentral { group: &'static str, artifact: &'static str },
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
@@ -60,7 +56,6 @@ impl Method {
|
||||
Method::Release { source: ReleaseSource::HashiCorp { .. }, .. } => "HashiCorp release",
|
||||
Method::Release { source: ReleaseSource::EclipseJdtls, .. } => "Eclipse download",
|
||||
Method::Release { source: ReleaseSource::OpenVsx { .. }, .. } => "Open VSX",
|
||||
Method::Release { source: ReleaseSource::MavenCentral { .. }, .. } => "Maven Central",
|
||||
Method::Release { .. } => "GitHub release",
|
||||
}
|
||||
}
|
||||
@@ -91,7 +86,7 @@ impl ToolSpec {
|
||||
|
||||
use Arch::{Arm64, X64};
|
||||
use Os::{Linux, Mac, Windows};
|
||||
use ToolKind::{Debugger, LanguageServer, Plugin};
|
||||
use ToolKind::{Debugger, LanguageServer};
|
||||
|
||||
const V: Option<(&str, &[&str])> = None;
|
||||
const fn ver(cmd: &'static str) -> Option<(&'static str, &'static [&'static str])> {
|
||||
@@ -458,24 +453,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
version: V,
|
||||
homepage: "https://github.com/microsoft/java-debug",
|
||||
},
|
||||
ToolSpec {
|
||||
name: "lombok",
|
||||
display: "Lombok (jdtls agent)",
|
||||
kind: Plugin,
|
||||
commands: &["lombok.jar"],
|
||||
// Newer than the Lombok a project pins: old ones fail inside current ECJ.
|
||||
method: Method::Release {
|
||||
source: ReleaseSource::MavenCentral { group: "org.projectlombok", artifact: "lombok" },
|
||||
assets: &[
|
||||
any_arch(Mac, "lombok-*.jar"),
|
||||
any_arch(Linux, "lombok-*.jar"),
|
||||
any_arch(Windows, "lombok-*.jar"),
|
||||
],
|
||||
locate: &["lombok.jar"],
|
||||
},
|
||||
version: V,
|
||||
homepage: "https://projectlombok.org",
|
||||
},
|
||||
ToolSpec {
|
||||
name: "kotlin-lsp",
|
||||
display: "Kotlin LSP (JetBrains)",
|
||||
@@ -501,9 +478,6 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
},
|
||||
];
|
||||
|
||||
/// Plugin tools and the tool that loads them.
|
||||
pub const PLUGIN_HOSTS: &[(&str, &str)] = &[("lombok", "jdtls")];
|
||||
|
||||
pub fn find(name: &str) -> Option<&'static ToolSpec> {
|
||||
TOOLS.iter().find(|t| t.name == name)
|
||||
}
|
||||
@@ -533,7 +507,7 @@ mod tests {
|
||||
known.insert((d.adapter.clone(), d.command.clone()));
|
||||
}
|
||||
}
|
||||
for t in TOOLS.iter().filter(|t| t.kind != Plugin) {
|
||||
for t in TOOLS {
|
||||
assert!(
|
||||
known.contains(&(t.name.to_string(), t.commands[0].to_string())),
|
||||
"{} / {} is not referenced by languages/*.toml",
|
||||
@@ -543,14 +517,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugins_have_a_known_host() {
|
||||
for t in TOOLS.iter().filter(|t| t.kind == Plugin) {
|
||||
let host = PLUGIN_HOSTS.iter().find(|(p, _)| *p == t.name).map(|(_, h)| *h);
|
||||
assert!(host.and_then(find).is_some(), "{} has no known host", t.name);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_release_tool_covers_mac_linux_windows() {
|
||||
for t in TOOLS {
|
||||
|
||||
@@ -209,39 +209,6 @@ pub fn openvsx_pick(json: &str, rules: &[AssetRule], platform: Platform) -> IdeR
|
||||
})
|
||||
}
|
||||
|
||||
const MAVEN_CENTRAL: &str = "https://repo1.maven.org/maven2";
|
||||
|
||||
fn maven_dir(group: &str, artifact: &str) -> String {
|
||||
format!("{MAVEN_CENTRAL}/{}/{artifact}", group.replace('.', "/"))
|
||||
}
|
||||
|
||||
pub fn maven_metadata_url(group: &str, artifact: &str) -> String {
|
||||
format!("{}/maven-metadata.xml", maven_dir(group, artifact))
|
||||
}
|
||||
|
||||
/// The `<release>` jar of a `maven-metadata.xml`. Central publishes only SHA-1
|
||||
/// sums for most artifacts, so the download is not checksum-verified.
|
||||
pub fn maven_pick(group: &str, artifact: &str, metadata: &str) -> IdeResult<Download> {
|
||||
let tag = |t: &str| {
|
||||
let start = metadata.find(&format!("<{t}>"))? + t.len() + 2;
|
||||
let end = start + metadata[start..].find(&format!("</{t}>"))?;
|
||||
Some(metadata[start..end].trim())
|
||||
};
|
||||
let version = tag("release")
|
||||
.or_else(|| tag("latest"))
|
||||
.filter(|v| !v.is_empty() && !v.contains(['/', '\\']))
|
||||
.ok_or_else(|| proto(format!("no release in the Maven metadata of {group}:{artifact}")))?;
|
||||
let name = format!("{artifact}-{version}.jar");
|
||||
Ok(Download {
|
||||
version: version.to_string(),
|
||||
url: format!("{}/{version}/{name}", maven_dir(group, artifact)),
|
||||
name,
|
||||
size: None,
|
||||
sha256: None,
|
||||
checksum_url: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Finds the hash for `file_name` in a checksum file: either a bare hex digest
|
||||
/// or `sha256sum` lines (`<hex> <name>`).
|
||||
pub fn parse_checksum(text: &str, file_name: &str) -> Option<String> {
|
||||
@@ -355,23 +322,6 @@ mod tests {
|
||||
assert!(openvsx_pick(&other, rules, LINUX).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_central() {
|
||||
let xml =
|
||||
"<metadata><versioning><latest>1.18.49-SNAPSHOT</latest><release>1.18.48</release></versioning></metadata>";
|
||||
assert_eq!(
|
||||
maven_metadata_url("org.projectlombok", "lombok"),
|
||||
"https://repo1.maven.org/maven2/org/projectlombok/lombok/maven-metadata.xml"
|
||||
);
|
||||
let d = maven_pick("org.projectlombok", "lombok", xml).unwrap();
|
||||
assert_eq!(d.version, "1.18.48");
|
||||
assert_eq!(d.name, "lombok-1.18.48.jar");
|
||||
assert_eq!(d.url, "https://repo1.maven.org/maven2/org/projectlombok/lombok/1.18.48/lombok-1.18.48.jar");
|
||||
assert!(select_asset(&[d.name.as_str()], find("lombok").unwrap().asset_rules(), LINUX).is_some());
|
||||
assert!(maven_pick("g", "a", "<metadata/>").is_err());
|
||||
assert!(maven_pick("g", "a", "<release>../x</release>").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checksums() {
|
||||
let h = "a".repeat(64);
|
||||
|
||||
@@ -126,18 +126,6 @@ pub struct Branch {
|
||||
pub commit: String,
|
||||
}
|
||||
|
||||
/// Commit Options (IDEA's commit options popup).
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CommitOptions {
|
||||
pub amend: bool,
|
||||
pub sign_off: bool,
|
||||
/// `--author`, e.g. `Name <[email protected]>`; `None` or blank uses the configured user.
|
||||
pub author: Option<String>,
|
||||
/// False skips the pre-commit and commit-msg hooks (`--no-verify`).
|
||||
pub run_hooks: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ChangedFile {
|
||||
@@ -268,7 +256,6 @@ mod patch;
|
||||
mod refs;
|
||||
mod remotes;
|
||||
mod repo;
|
||||
mod roots;
|
||||
pub mod shelf;
|
||||
mod status;
|
||||
mod write;
|
||||
@@ -276,7 +263,6 @@ mod write;
|
||||
pub use cli::{detected_git_executable, git_version, set_git_executable};
|
||||
pub use diff::build_partial_patch;
|
||||
pub use remotes::Remote;
|
||||
pub use roots::Repos;
|
||||
|
||||
/// Clones `url` into `dest` (which must not exist or be empty), streaming progress.
|
||||
pub fn clone(url: &str, dest: &Path, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
|
||||
@@ -322,10 +308,6 @@ impl Repo {
|
||||
pub fn branch_info(&self) -> IdeResult<BranchInfo> {
|
||||
refs::branch_info(self)
|
||||
}
|
||||
/// Merge / rebase / cherry-pick… in progress (cheap: no ref walking).
|
||||
pub fn operation(&self) -> IdeResult<Option<String>> {
|
||||
Ok(refs::operation(&self.gix()?))
|
||||
}
|
||||
/// Content of `path` at `rev` (default HEAD); `None` if absent there.
|
||||
/// `rev` may be any revision git understands, or `":"` / `":0"` for the index.
|
||||
pub fn file_at(&self, path: &Path, rev: Option<&str>) -> IdeResult<Option<String>> {
|
||||
@@ -416,12 +398,7 @@ impl Repo {
|
||||
/// Commits the index; returns the new HEAD commit id. An empty message with
|
||||
/// `amend` keeps the previous message.
|
||||
pub fn commit(&self, message: &str, amend: bool, sign_off: bool) -> IdeResult<String> {
|
||||
let options = CommitOptions { amend, sign_off, author: None, run_hooks: true };
|
||||
write::commit(self, message, &options)
|
||||
}
|
||||
/// Commits with the Commit Options popup's choices.
|
||||
pub fn commit_with(&self, message: &str, options: &CommitOptions) -> IdeResult<String> {
|
||||
write::commit(self, message, options)
|
||||
write::commit(self, message, amend, sign_off)
|
||||
}
|
||||
/// Switches to `branch`. With `create`, creates it at HEAD. Without, a remote branch
|
||||
/// (`origin/x`) gets a local tracking branch and any other revision is checked out
|
||||
|
||||
@@ -30,7 +30,7 @@ pub(crate) fn branch_info(r: &Repo) -> IdeResult<BranchInfo> {
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
pub(crate) fn operation(repo: &gix::Repository) -> Option<String> {
|
||||
fn operation(repo: &gix::Repository) -> Option<String> {
|
||||
use gix::state::InProgress::*;
|
||||
let op = match repo.state()? {
|
||||
ApplyMailbox | ApplyMailboxRebase => "am",
|
||||
|
||||
@@ -1,243 +0,0 @@
|
||||
//! The repositories of a project (IDEA's VCS roots): the one containing the project
|
||||
//! root plus those nested below it (separate clones side by side, submodules).
|
||||
|
||||
use crate::{FileStatus, Repo};
|
||||
use ide_core::IdeResult;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// How deep below the project root nested repositories are looked for.
|
||||
const MAX_DEPTH: usize = 4;
|
||||
|
||||
/// Folders never searched for nested repositories (dependencies, build output).
|
||||
const SKIPPED: &[&str] = &["node_modules", "target", "build", "dist", "out", "vendor", "venv", "__pycache__"];
|
||||
|
||||
/// The repositories of a project, sorted by root; lookups pick the innermost one.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct Repos {
|
||||
repos: Vec<Arc<Repo>>,
|
||||
primary: Option<usize>,
|
||||
}
|
||||
|
||||
impl Repos {
|
||||
/// The repository containing `project_root` and every repository whose worktree
|
||||
/// root lies below it (up to [`MAX_DEPTH`] levels; hidden and dependency folders and
|
||||
/// folders `skip` rejects are not searched).
|
||||
pub fn discover(project_root: &Path, skip: &dyn Fn(&Path) -> bool) -> IdeResult<Self> {
|
||||
let mut repos: Vec<Repo> = Vec::new();
|
||||
if let Some(r) = Repo::discover(project_root)? {
|
||||
repos.push(r);
|
||||
}
|
||||
let mut stack: Vec<(PathBuf, usize)> = vec![(project_root.to_path_buf(), 0)];
|
||||
while let Some((dir, depth)) = stack.pop() {
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
|
||||
for entry in entries.flatten() {
|
||||
if !entry.file_type().is_ok_and(|t| t.is_dir()) {
|
||||
continue;
|
||||
}
|
||||
let name = entry.file_name();
|
||||
let name = name.to_string_lossy();
|
||||
let path = entry.path();
|
||||
if name.starts_with('.') || SKIPPED.contains(&name.as_ref()) || skip(&path) {
|
||||
continue;
|
||||
}
|
||||
if path.join(".git").exists()
|
||||
&& let Ok(Some(r)) = Repo::discover(&path)
|
||||
&& r.root() == path
|
||||
&& !repos.iter().any(|x| x.root() == r.root())
|
||||
{
|
||||
repos.push(r);
|
||||
}
|
||||
if depth + 1 < MAX_DEPTH {
|
||||
stack.push((path, depth + 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Self::new(repos, project_root))
|
||||
}
|
||||
|
||||
/// Only the repository containing `project_root` (the quick lookup on project open).
|
||||
pub fn enclosing(project_root: &Path) -> IdeResult<Self> {
|
||||
Ok(Self::new(Repo::discover(project_root)?.into_iter().collect(), project_root))
|
||||
}
|
||||
|
||||
/// Worktree roots, sorted.
|
||||
pub fn roots(&self) -> Vec<PathBuf> {
|
||||
self.repos.iter().map(|r| r.root().to_path_buf()).collect()
|
||||
}
|
||||
|
||||
fn new(mut repos: Vec<Repo>, project_root: &Path) -> Self {
|
||||
repos.sort_by(|a, b| a.root().cmp(b.root()));
|
||||
let repos: Vec<Arc<Repo>> = repos.into_iter().map(Arc::new).collect();
|
||||
let roots: Vec<&Path> = repos.iter().map(|r| r.root()).collect();
|
||||
let primary = innermost(&roots, project_root, false).or((!repos.is_empty()).then_some(0));
|
||||
Self { repos, primary }
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.repos.is_empty()
|
||||
}
|
||||
|
||||
pub fn all(&self) -> &[Arc<Repo>] {
|
||||
&self.repos
|
||||
}
|
||||
|
||||
/// The repository of the project root, else the first one.
|
||||
pub fn primary(&self) -> Option<&Arc<Repo>> {
|
||||
self.primary.map(|i| &self.repos[i])
|
||||
}
|
||||
|
||||
/// The innermost repository containing `path` (a file or folder). A nested repository's
|
||||
/// root is an entry of the enclosing repository (a submodule or untracked folder there), so
|
||||
/// it belongs to that one; to the repository itself only when nothing encloses it.
|
||||
pub fn for_path(&self, path: &Path) -> Option<&Arc<Repo>> {
|
||||
let roots: Vec<&Path> = self.repos.iter().map(|r| r.root()).collect();
|
||||
let found = innermost(&roots, path, true).or_else(|| {
|
||||
// Another spelling of the same location (symlinks, /var vs /private/var).
|
||||
let canon = dunce::canonicalize(path).ok()?;
|
||||
let roots: Vec<PathBuf> =
|
||||
roots.iter().map(|r| dunce::canonicalize(r).unwrap_or_else(|_| r.to_path_buf())).collect();
|
||||
innermost(&roots.iter().map(PathBuf::as_path).collect::<Vec<_>>(), &canon, true)
|
||||
});
|
||||
found.map(|i| &self.repos[i])
|
||||
}
|
||||
|
||||
/// The repository whose worktree root is `root` (the repository a repository-scoped
|
||||
/// command was given).
|
||||
pub fn at_root(&self, root: &Path) -> Option<&Arc<Repo>> {
|
||||
self.repos.iter().find(|r| r.root() == root).or_else(|| {
|
||||
let canon = dunce::canonicalize(root).ok()?;
|
||||
self.repos.iter().find(|r| dunce::canonicalize(r.root()).is_ok_and(|r| r == canon))
|
||||
})
|
||||
}
|
||||
|
||||
/// `paths` grouped by the repository each belongs to (paths outside every repository are dropped).
|
||||
pub fn group(&self, paths: &[PathBuf]) -> Vec<(Arc<Repo>, Vec<PathBuf>)> {
|
||||
let mut out: Vec<(Arc<Repo>, Vec<PathBuf>)> = Vec::new();
|
||||
for p in paths {
|
||||
let Some(repo) = self.for_path(p) else { continue };
|
||||
match out.iter_mut().find(|(r, _)| Arc::ptr_eq(r, repo)) {
|
||||
Some((_, list)) => list.push(p.clone()),
|
||||
None => out.push((repo.clone(), vec![p.clone()])),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Changes of every repository. A nested repository reports its own files, so the
|
||||
/// enclosing one's "untracked folder" entry for it is dropped. A repository that cannot
|
||||
/// be read (e.g. deleted since the last scan) is left out; fails only when all fail.
|
||||
pub fn status(&self) -> IdeResult<Vec<FileStatus>> {
|
||||
let mut out = Vec::new();
|
||||
let mut first_error = None;
|
||||
let mut read = 0;
|
||||
for repo in &self.repos {
|
||||
let nested: Vec<&Path> = self
|
||||
.repos
|
||||
.iter()
|
||||
.map(|r| r.root())
|
||||
.filter(|r| *r != repo.root() && r.starts_with(repo.root()))
|
||||
.collect();
|
||||
let status = match repo.status() {
|
||||
Ok(status) => {
|
||||
read += 1;
|
||||
status
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("git status of {}: {e}", repo.root().display());
|
||||
first_error.get_or_insert(e);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
out.extend(status.into_iter().filter(|f| {
|
||||
let untracked_root =
|
||||
f.unstaged == Some(crate::ChangeKind::Untracked) && nested.iter().any(|n| f.path.0 == *n);
|
||||
!untracked_root
|
||||
}));
|
||||
}
|
||||
match first_error {
|
||||
Some(e) if read == 0 => Err(e),
|
||||
_ => Ok(out),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Index of the innermost of `roots` containing `path`. With `strict`, a root equal to
|
||||
/// `path` counts only when no other root contains it.
|
||||
fn innermost(roots: &[&Path], path: &Path, strict: bool) -> Option<usize> {
|
||||
let best = |strict: bool| {
|
||||
roots
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, r)| path.starts_with(r) && !(strict && **r == path))
|
||||
.max_by_key(|(_, r)| r.as_os_str().len())
|
||||
.map(|(i, _)| i)
|
||||
};
|
||||
best(strict).or_else(|| best(false))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::process::Command;
|
||||
|
||||
fn git_init(dir: &Path) {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
let ok = Command::new("git").args(["init", "-q"]).current_dir(dir).status().is_ok_and(|s| s.success());
|
||||
assert!(ok, "git init in {}", dir.display());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_nested_repositories_and_routes_paths() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
git_init(&root);
|
||||
git_init(&root.join("services/api"));
|
||||
git_init(&root.join("web"));
|
||||
git_init(&root.join("node_modules/dep"));
|
||||
git_init(&root.join(".cache/repo"));
|
||||
std::fs::write(root.join("services/api/main.rs"), "fn main() {}").unwrap();
|
||||
std::fs::write(root.join("README.md"), "x").unwrap();
|
||||
|
||||
let repos = Repos::discover(&root, &|_| false).unwrap();
|
||||
let roots: Vec<&Path> = repos.all().iter().map(|r| r.root()).collect();
|
||||
assert_eq!(roots, [root.as_path(), &root.join("services/api"), &root.join("web")]);
|
||||
assert_eq!(repos.primary().unwrap().root(), root);
|
||||
assert_eq!(repos.for_path(&root.join("services/api/main.rs")).unwrap().root(), root.join("services/api"));
|
||||
assert_eq!(repos.for_path(&root.join("services/other.txt")).unwrap().root(), root);
|
||||
// A nested root is the enclosing repository's entry (submodule / untracked folder).
|
||||
assert_eq!(repos.for_path(&root.join("services/api")).unwrap().root(), root);
|
||||
assert_eq!(repos.for_path(&root).unwrap().root(), root);
|
||||
assert_eq!(repos.at_root(&root.join("services/api")).unwrap().root(), root.join("services/api"));
|
||||
assert!(repos.at_root(&root.join("services")).is_none());
|
||||
|
||||
let status = repos.status().unwrap();
|
||||
let paths: Vec<String> =
|
||||
status.iter().map(|f| f.path.0.strip_prefix(&root).unwrap().to_string_lossy().replace('\\', "/")).collect();
|
||||
assert!(paths.contains(&"README.md".to_owned()), "{paths:?}");
|
||||
assert!(paths.contains(&"services/api/main.rs".to_owned()), "{paths:?}");
|
||||
assert!(
|
||||
!paths.iter().any(|p| p.trim_end_matches('/') == "web"),
|
||||
"nested root is not an untracked folder: {paths:?}"
|
||||
);
|
||||
|
||||
let groups = repos.group(&[root.join("README.md"), root.join("services/api/main.rs"), root.join("web/x")]);
|
||||
assert_eq!(groups.len(), 3);
|
||||
assert_eq!(groups[1].1, [root.join("services/api/main.rs")]);
|
||||
|
||||
let skipped = Repos::discover(&root, &|p| p.ends_with("services")).unwrap();
|
||||
assert_eq!(skipped.all().len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn side_by_side_repositories_without_an_enclosing_one() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
git_init(&root.join("a"));
|
||||
git_init(&root.join("b"));
|
||||
let repos = Repos::discover(&root, &|_| false).unwrap();
|
||||
assert_eq!(repos.all().len(), 2);
|
||||
assert_eq!(repos.primary().unwrap().root(), root.join("a"), "the first when none contains the project root");
|
||||
assert!(repos.for_path(&root.join("c.txt")).is_none());
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use crate::cli::{self, run};
|
||||
use crate::repo::{gx, resolve};
|
||||
use crate::{BlameLine, CommitOptions, Repo};
|
||||
use crate::{BlameLine, Repo};
|
||||
use gix::bstr::{BStr, ByteSlice};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -222,22 +222,15 @@ pub(crate) fn discard(r: &Repo, paths: &[PathBuf]) -> IdeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn commit(r: &Repo, message: &str, options: &CommitOptions) -> IdeResult<String> {
|
||||
pub(crate) fn commit(r: &Repo, message: &str, amend: bool, sign_off: bool) -> IdeResult<String> {
|
||||
let mut args = vec!["commit", "-q", "--cleanup=whitespace"];
|
||||
if options.amend {
|
||||
if amend {
|
||||
args.push("--amend");
|
||||
}
|
||||
if options.sign_off {
|
||||
if sign_off {
|
||||
args.push("--signoff");
|
||||
}
|
||||
if !options.run_hooks {
|
||||
args.push("--no-verify");
|
||||
}
|
||||
let author = options.author.as_deref().map(str::trim).filter(|a| !a.is_empty()).map(|a| format!("--author={a}"));
|
||||
if let Some(a) = &author {
|
||||
args.push(a.as_str());
|
||||
}
|
||||
let stdin = if options.amend && message.trim().is_empty() {
|
||||
let stdin = if amend && message.trim().is_empty() {
|
||||
args.push("--no-edit");
|
||||
None
|
||||
} else {
|
||||
|
||||
@@ -707,28 +707,6 @@ fn commit_amend_and_signoff() {
|
||||
assert!(repo.commit("nothing", false, false).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commit_with_author_and_without_hooks() {
|
||||
let fx = Fixture::new();
|
||||
fx.write("a", "1\n");
|
||||
fx.commit_all("init");
|
||||
let hook = fx.path(".git/hooks/pre-commit");
|
||||
std::fs::write(&hook, "#!/bin/sh\nexit 1\n").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
let repo = fx.repo();
|
||||
fx.write("a", "2\n");
|
||||
repo.stage(&[fx.path("a")]).unwrap();
|
||||
let hooked = CommitOptions { run_hooks: true, ..Default::default() };
|
||||
assert!(repo.commit_with("blocked", &hooked).is_err(), "the failing pre-commit hook runs");
|
||||
let options = CommitOptions { author: Some(" Other <[email protected]> ".into()), ..Default::default() };
|
||||
repo.commit_with("by other", &options).unwrap();
|
||||
assert_eq!(fx.git(&["log", "-1", "--format=%an <%ae>"]), "Other <[email protected]>");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checkout_create_detached_delete_rebase() {
|
||||
let fx = Fixture::new();
|
||||
|
||||
+1
-1
@@ -16,7 +16,7 @@
|
||||
<rect x="43" y="18" width="8" height="28" rx="1.5" fill="#FF4F1A" />
|
||||
</svg>
|
||||
<span>OpenIDEA</span>
|
||||
<div class="splash-bar" role="progressbar" aria-label="Loading"><i></i></div>
|
||||
<div class="splash-bar" role="progressbar" aria-label="Loading"></div>
|
||||
</div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"name": "openidea",
|
||||
"private": true,
|
||||
"description": "An open-source IDE inspired by IntelliJ IDEA",
|
||||
"version": "0.1.5",
|
||||
"version": "0.1.3",
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/* global document, localStorage, window */
|
||||
/* global document, localStorage */
|
||||
// Runs before the app's CSS loads: restores the last theme (theme.ts stores it)
|
||||
// so a new window starts in it instead of flashing the light default.
|
||||
// An external file because the CSP forbids inline scripts.
|
||||
@@ -9,7 +9,3 @@ try {
|
||||
} catch {
|
||||
/* storage unavailable */
|
||||
}
|
||||
// Settings windows (`settings-<parent>`) load this page too: splash.css drops the logo for them.
|
||||
if (window.__TAURI_INTERNALS__?.metadata?.currentWindow?.label?.startsWith("settings-")) {
|
||||
document.documentElement.dataset.window = "settings";
|
||||
}
|
||||
@@ -2,8 +2,7 @@
|
||||
which voids style-src 'unsafe-inline' and blocks the editor's runtime-injected styles. */
|
||||
/* Start-up splash over the page until the window's launch project is open (platform/splash.ts).
|
||||
Tokens aren't loaded yet, so the colours mirror --bg-frame / --fg-muted / --accent. */
|
||||
/* Not on html: the canvas then takes body's (themed) background, which a fast resize shows before relayout. */
|
||||
body, .splash { background: #e9eaee; }
|
||||
html, body, .splash { background: #e9eaee; }
|
||||
:root[data-theme="dark"] :is(body, .splash) { background: #26282c; }
|
||||
:root:is([data-theme="dark-hc"], [data-theme="dark"][data-contrast="high"]) :is(body, .splash) { background: #1a1b1e; }
|
||||
.splash {
|
||||
@@ -29,20 +28,16 @@ body, .splash { background: #e9eaee; }
|
||||
:root[data-theme^="dark"] .splash { color: #8c8f95; }
|
||||
.splash svg { width: 56px; height: 56px; }
|
||||
.splash-bar { width: 120px; height: 2px; border-radius: 1px; overflow: hidden; background: rgb(127 127 127 / 0.18); }
|
||||
/* Fake progress: eases towards ~90% over the 4 s cap; hideSplash() fills it before fading out. */
|
||||
.splash-bar > i {
|
||||
.splash-bar::after {
|
||||
content: "";
|
||||
display: block;
|
||||
width: 40%;
|
||||
height: 100%;
|
||||
background: #3871e1;
|
||||
transform-origin: left;
|
||||
animation: splash-fill 4s cubic-bezier(0.1, 0.7, 0.3, 1) both;
|
||||
animation: splash-bar 1.1s ease-in-out infinite;
|
||||
}
|
||||
/* Settings window: a dialog, not a launch. Only the bar, and only if loading takes a while. */
|
||||
:root[data-window="settings"] .splash { animation-delay: 400ms; }
|
||||
:root[data-window="settings"] .splash > :not(.splash-bar) { display: none; }
|
||||
@keyframes splash-in { from { opacity: 0; } }
|
||||
@keyframes splash-fill { from { transform: scaleX(0.04); } to { transform: scaleX(0.92); } }
|
||||
/* The fill stays: it grows in place, which reduced motion allows. */
|
||||
@keyframes splash-bar { from { transform: translateX(-100%); } to { transform: translateX(250%); } }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.splash { animation: none; }
|
||||
.splash, .splash-bar::after { animation: none; }
|
||||
}
|
||||
@@ -16,7 +16,6 @@
|
||||
"core:window:allow-set-title",
|
||||
"core:window:allow-set-background-color",
|
||||
"core:webview:allow-set-webview-zoom",
|
||||
"core:webview:allow-set-webview-background-color",
|
||||
"opener:default",
|
||||
"opener:allow-reveal-item-in-dir",
|
||||
"dialog:default",
|
||||
|
||||
@@ -71,7 +71,7 @@ pub async fn open_project(window: Window, path: PathBuf) -> IdeResult<ProjectInf
|
||||
fn project_info(project: &crate::state::Project) -> ProjectInfo {
|
||||
ProjectInfo {
|
||||
name: project.root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),
|
||||
is_git: !project.repos.read().is_empty(),
|
||||
is_git: project.repo.lock().is_some(),
|
||||
settings: project.settings.effective(),
|
||||
root: project.root.clone().into(),
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
use crate::state::AppState;
|
||||
use ide_build::compile::{self, BuildEvent, BuildKind, BuildResult};
|
||||
use ide_build::{BuildModel, BuildTool, SyncOptions, SyncProgress};
|
||||
use ide_core::settings::Settings;
|
||||
use ide_core::{IdeError, IdeEvent, IdeResult, RequestId};
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
@@ -15,32 +14,22 @@ fn join_err(e: tauri::Error) -> IdeError {
|
||||
IdeError::internal(e.to_string())
|
||||
}
|
||||
|
||||
/// `JAVA_HOME`: the project JDK, else the installed JDK matching `release` (none
|
||||
/// when the project names no version).
|
||||
fn java_env(project_jdk: Option<&ide_sdk::java::Jdk>, release: Option<u32>) -> BTreeMap<String, String> {
|
||||
/// `JAVA_HOME` of the installed JDK matching `release` (none when the project names no version).
|
||||
fn java_env(release: Option<u32>) -> BTreeMap<String, String> {
|
||||
let jdks = ide_sdk::java::installed_jdks();
|
||||
let jdk = project_jdk.or_else(|| release.and_then(|r| ide_sdk::java::pick_jdk(&jdks, Some(r))));
|
||||
let jdk = release.and_then(|r| ide_sdk::java::pick_jdk(&jdks, Some(r)));
|
||||
jdk.map(|j| BTreeMap::from([("JAVA_HOME".to_owned(), j.home.to_string_lossy().into_owned())])).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The build model with the launch settings applied: the JDK (`JAVA_HOME`), and
|
||||
/// the Maven home and options from Settings › Maven.
|
||||
pub(crate) fn load(root: &Path, cache: &Path, settings: &Settings) -> BuildModel {
|
||||
let mut model = ide_build::load(root, cache, ide_sdk::apply::maven_local_repository(root, settings));
|
||||
let jdk = ide_sdk::apply::project_jdk(root, settings);
|
||||
pub(crate) fn load(root: &Path, cache: &Path) -> BuildModel {
|
||||
let mut model = ide_build::load(root, cache);
|
||||
if let Some(m) = &mut model.maven {
|
||||
let mvn = ide_sdk::apply::maven_command(root, settings);
|
||||
let options = ide_sdk::apply::maven_options(root, settings);
|
||||
for p in &mut m.projects {
|
||||
p.env = java_env(jdk.as_ref(), p.java_version);
|
||||
if let Some(mvn) = &mvn {
|
||||
p.command = mvn.to_string_lossy().into_owned();
|
||||
}
|
||||
p.options = options.clone();
|
||||
p.env = java_env(p.java_version);
|
||||
}
|
||||
}
|
||||
if let Some(g) = &mut model.gradle {
|
||||
g.env = java_env(jdk.as_ref(), g.java_version);
|
||||
g.env = java_env(g.java_version);
|
||||
}
|
||||
model
|
||||
}
|
||||
@@ -50,8 +39,8 @@ pub(crate) fn load(root: &Path, cache: &Path, settings: &Settings) -> BuildModel
|
||||
#[specta::specta]
|
||||
pub async fn build_model(window: Window, state: State<'_, AppState>) -> IdeResult<BuildModel> {
|
||||
let project = state.project(window.label())?;
|
||||
let (root, cache, settings) = (project.root.clone(), project.build_cache_dir(), project.settings.effective());
|
||||
tauri::async_runtime::spawn_blocking(move || load(&root, &cache, &settings)).await.map_err(join_err)
|
||||
let (root, cache) = (project.root.clone(), project.build_cache_dir());
|
||||
tauri::async_runtime::spawn_blocking(move || load(&root, &cache)).await.map_err(join_err)
|
||||
}
|
||||
|
||||
/// Runs Maven (`help:effective-pom dependency:tree`) or Gradle (`tasks --all`) in the
|
||||
@@ -69,10 +58,10 @@ pub async fn build_sync(
|
||||
on_progress: Channel<SyncProgress>,
|
||||
) -> IdeResult<BuildModel> {
|
||||
let project = state.project(window.label())?;
|
||||
let (root, cache, settings) = (project.root.clone(), project.build_cache_dir(), project.settings.effective());
|
||||
let (root, cache) = (project.root.clone(), project.build_cache_dir());
|
||||
let token = state.begin_request(request);
|
||||
let result = tauri::async_runtime::spawn_blocking(move || {
|
||||
let current = load(&root, &cache, &settings);
|
||||
let current = load(&root, &cache);
|
||||
let env = match tool {
|
||||
BuildTool::Maven => current
|
||||
.maven
|
||||
@@ -82,13 +71,7 @@ pub async fn build_sync(
|
||||
.unwrap_or_default(),
|
||||
BuildTool::Gradle => current.gradle.as_ref().map(|g| g.env.clone()).unwrap_or_default(),
|
||||
};
|
||||
let options = SyncOptions {
|
||||
offline,
|
||||
profiles,
|
||||
env,
|
||||
maven_command: ide_sdk::apply::maven_command(&root, &settings).map(|p| p.to_string_lossy().into_owned()),
|
||||
maven_options: ide_sdk::apply::maven_options(&root, &settings),
|
||||
};
|
||||
let options = SyncOptions { offline, profiles, env };
|
||||
let progress = |p: SyncProgress| {
|
||||
let _ = on_progress.send(p);
|
||||
};
|
||||
@@ -96,7 +79,7 @@ pub async fn build_sync(
|
||||
BuildTool::Maven => ide_build::sync_maven(&root, &cache, &options, &token, &progress)?,
|
||||
BuildTool::Gradle => ide_build::sync_gradle(&root, &cache, &options, &token, &progress)?,
|
||||
}
|
||||
Ok(load(&root, &cache, &settings))
|
||||
Ok(load(&root, &cache))
|
||||
})
|
||||
.await
|
||||
.map_err(join_err);
|
||||
@@ -121,7 +104,6 @@ pub async fn build_run(
|
||||
) -> IdeResult<BuildResult> {
|
||||
let project = state.project(window.label())?;
|
||||
let (root, cache, sink) = (project.root.clone(), project.build_cache_dir(), project.sink.clone());
|
||||
let settings = project.settings.effective();
|
||||
let token = state.begin_request(request);
|
||||
let result = tauri::async_runtime::spawn_blocking(move || {
|
||||
for path in clear {
|
||||
@@ -131,7 +113,7 @@ pub async fn build_run(
|
||||
items: Vec::new(),
|
||||
});
|
||||
}
|
||||
let plan = compile::plan(&root, &load(&root, &cache, &settings), kind, file.as_deref())?;
|
||||
let plan = compile::plan(&root, &load(&root, &cache), kind, file.as_deref())?;
|
||||
let result = compile::run(&root, &plan, &token, &|e| {
|
||||
let _ = on_event.send(e);
|
||||
})?;
|
||||
|
||||
@@ -22,12 +22,10 @@ pub async fn java_resolve_launch(
|
||||
) -> IdeResult<JavaLaunchInfo> {
|
||||
let project = state.project(window.label())?;
|
||||
let module = project.root.join(module);
|
||||
let settings = project.settings.effective();
|
||||
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 (root, cache, module) = (project.root.clone(), project.build_cache_dir(), module.clone());
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
compile::build_for_launch(&root, &load(&root, &cache, &settings), &module, test, &CancellationToken::new())
|
||||
compile::build_for_launch(&root, &load(&root, &cache), &module, test, &CancellationToken::new())
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))??
|
||||
@@ -42,25 +40,13 @@ pub async fn java_resolve_launch(
|
||||
}
|
||||
}
|
||||
info.class_paths = class_paths;
|
||||
// The project JDK, else the JDK jdtls compiles the module against, else one matching its Java version.
|
||||
let project_jdk = ide_sdk::apply::project_jdk(&project.root, &settings);
|
||||
let from_jdtls = info.java_home.as_deref().map(ide_sdk::java::java_executable).filter(|p| p.is_file());
|
||||
let java = project_jdk.map(|j| ide_sdk::java::java_executable(&j.home)).or(from_jdtls).or_else(|| {
|
||||
let java = from_jdtls.or_else(|| {
|
||||
let release = ide_sdk::java::project_java_version(&module);
|
||||
let jdks = ide_sdk::java::installed_jdks();
|
||||
ide_sdk::java::pick_jdk(&jdks, release).map(|j| ide_sdk::java::java_executable(&j.home))
|
||||
});
|
||||
info.java_exec = Some(java.map(|p| p.to_string_lossy().into_owned()).unwrap_or_else(|| "java".to_owned()));
|
||||
if info.error_count > 0 {
|
||||
let vm_args = &settings.languages.java.jdtls_vm_args;
|
||||
let lombok = ide_sdk::lombok::lombok_agent(
|
||||
&project.root,
|
||||
ide_sdk::lombok::agent_in_args(vm_args.split_whitespace()),
|
||||
ide_tools::managed_bundle(&state.data_dir, "lombok"),
|
||||
ide_sdk::apply::maven_local_repository(&project.root, &settings),
|
||||
);
|
||||
info.hints.extend(lombok.problem());
|
||||
}
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
|
||||
@@ -129,7 +129,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
lsp::apply_workspace_edit,
|
||||
lsp::lsp_execute_command,
|
||||
vcs::vcs_status,
|
||||
vcs::vcs_roots,
|
||||
vcs::vcs_branch_info,
|
||||
vcs::vcs_line_hunks,
|
||||
vcs::vcs_file_at,
|
||||
@@ -228,7 +227,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
window::window_toggle_fullscreen,
|
||||
window::window_take_launch,
|
||||
window::window_close_context,
|
||||
window::window_open_projects,
|
||||
window::app_quit,
|
||||
window::app_cancel_quit,
|
||||
window::menu_configure,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::state::{AppState, Project};
|
||||
use crate::state::AppState;
|
||||
use ide_core::{IdeResult, RequestId};
|
||||
use ide_vcs::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -13,59 +13,18 @@ pub(crate) fn apply_git_executable(settings: &ide_core::settings::Settings) {
|
||||
ide_vcs::set_git_executable((!exe.is_empty()).then(|| Path::new(exe)));
|
||||
}
|
||||
|
||||
/// Changes of every repository of the project.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn vcs_status(window: Window, state: State<'_, AppState>) -> IdeResult<Vec<FileStatus>> {
|
||||
let project = state.project(window.label())?;
|
||||
blocking(move || {
|
||||
let settings = project.settings.effective();
|
||||
apply_git_executable(&settings);
|
||||
let repos = project.repos();
|
||||
if repos.is_empty() {
|
||||
return Err(ide_core::IdeError::unavailable("project is not a git repository"));
|
||||
}
|
||||
for r in repos.all() {
|
||||
r.set_ignored_names(settings.ignored_names());
|
||||
}
|
||||
repos.status()
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// A repository of the project (IDEA's VCS root).
|
||||
#[derive(Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct VcsRoot {
|
||||
/// Worktree root.
|
||||
pub root: ide_core::IpcPath,
|
||||
/// Merge / rebase / cherry-pick / revert in progress.
|
||||
pub operation: Option<String>,
|
||||
}
|
||||
|
||||
/// The project's repositories, the primary one first.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn vcs_roots(window: Window, state: State<'_, AppState>) -> IdeResult<Vec<VcsRoot>> {
|
||||
let repos = state.project(window.label())?.repos();
|
||||
let primary = repos.primary().map(|r| r.root().to_path_buf());
|
||||
let mut all: Vec<&std::sync::Arc<Repo>> = repos.all().iter().collect();
|
||||
all.sort_by_key(|r| Some(r.root()) != primary.as_deref());
|
||||
Ok(all
|
||||
.into_iter()
|
||||
.map(|r| VcsRoot { root: r.root().to_path_buf().into(), operation: r.operation().ok().flatten() })
|
||||
.collect())
|
||||
blocking(move || project.with_repo(|r| r.status())).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn vcs_branch_info(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
repo: Option<PathBuf>,
|
||||
) -> IdeResult<BranchInfo> {
|
||||
pub async fn vcs_branch_info(window: Window, state: State<'_, AppState>) -> IdeResult<BranchInfo> {
|
||||
let project = state.project(window.label())?;
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.branch_info())).await
|
||||
blocking(move || project.with_repo(|r| r.branch_info())).await
|
||||
}
|
||||
|
||||
/// Gutter change markers for a file, computed against its current (unsaved) text.
|
||||
@@ -74,7 +33,7 @@ pub async fn vcs_branch_info(
|
||||
pub fn vcs_line_hunks(window: Window, state: State<'_, AppState>, path: PathBuf) -> IdeResult<Vec<LineHunk>> {
|
||||
let project = state.project(window.label())?;
|
||||
let text = project.text_of(&path)?;
|
||||
project.with_repo_of(&path, |r| r.line_hunks(&path, &text, false))
|
||||
project.with_repo(|r| r.line_hunks(&path, &text, false))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -86,7 +45,7 @@ pub async fn vcs_file_at(
|
||||
rev: Option<String>,
|
||||
) -> IdeResult<Option<String>> {
|
||||
let project = state.project(window.label())?;
|
||||
blocking(move || project.with_repo_of(&path, |r| r.file_at(&path, rev.as_deref()))).await
|
||||
blocking(move || project.with_repo(|r| r.file_at(&path, rev.as_deref()))).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -94,19 +53,14 @@ pub async fn vcs_file_at(
|
||||
pub async fn vcs_blame(window: Window, state: State<'_, AppState>, path: PathBuf) -> IdeResult<Vec<BlameLine>> {
|
||||
let project = state.project(window.label())?;
|
||||
let text = project.documents.text_of(&path);
|
||||
blocking(move || project.with_repo_of(&path, |r| r.blame(&path, text.as_deref()))).await
|
||||
blocking(move || project.with_repo(|r| r.blame(&path, text.as_deref()))).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn vcs_log(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
repo: Option<PathBuf>,
|
||||
query: LogQuery,
|
||||
) -> IdeResult<Vec<Commit>> {
|
||||
pub async fn vcs_log(window: Window, state: State<'_, AppState>, query: LogQuery) -> IdeResult<Vec<Commit>> {
|
||||
let project = state.project(window.label())?;
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.log(&query))).await
|
||||
blocking(move || project.with_repo(|r| r.log(&query))).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -114,39 +68,38 @@ pub async fn vcs_log(
|
||||
pub async fn vcs_commit_files(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
repo: Option<PathBuf>,
|
||||
commit: String,
|
||||
) -> IdeResult<Vec<ChangedFile>> {
|
||||
let project = state.project(window.label())?;
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.commit_files(&commit))).await
|
||||
blocking(move || project.with_repo(|r| r.commit_files(&commit))).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn vcs_branches(window: Window, state: State<'_, AppState>, repo: Option<PathBuf>) -> IdeResult<Vec<Branch>> {
|
||||
pub async fn vcs_branches(window: Window, state: State<'_, AppState>) -> IdeResult<Vec<Branch>> {
|
||||
let project = state.project(window.label())?;
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.branches())).await
|
||||
blocking(move || project.with_repo(|r| r.branches())).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn vcs_stashes(window: Window, state: State<'_, AppState>, repo: Option<PathBuf>) -> IdeResult<Vec<Stash>> {
|
||||
pub async fn vcs_stashes(window: Window, state: State<'_, AppState>) -> IdeResult<Vec<Stash>> {
|
||||
let project = state.project(window.label())?;
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.stashes())).await
|
||||
blocking(move || project.with_repo(|r| r.stashes())).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn vcs_stage(window: Window, state: State<'_, AppState>, paths: Vec<PathBuf>) -> IdeResult<()> {
|
||||
let project = state.project(window.label())?;
|
||||
blocking(move || per_repo(&project, &paths, None, |r, paths| r.stage(paths))).await
|
||||
blocking(move || project.with_repo(|r| r.stage(&paths))).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn vcs_unstage(window: Window, state: State<'_, AppState>, paths: Vec<PathBuf>) -> IdeResult<()> {
|
||||
let project = state.project(window.label())?;
|
||||
blocking(move || per_repo(&project, &paths, None, |r, paths| r.unstage(paths))).await
|
||||
blocking(move || project.with_repo(|r| r.unstage(&paths))).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -160,7 +113,7 @@ pub async fn vcs_stage_patch(window: Window, state: State<'_, AppState>, patch:
|
||||
#[specta::specta]
|
||||
pub async fn vcs_discard(window: Window, state: State<'_, AppState>, paths: Vec<PathBuf>) -> IdeResult<()> {
|
||||
let project = state.project(window.label())?;
|
||||
blocking(move || per_repo(&project, &paths, Some("Rollback"), |r, paths| r.discard(paths))).await
|
||||
blocking(move || project.with_repo_recorded(Some("Rollback"), |r| r.discard(&paths))).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -168,27 +121,20 @@ pub async fn vcs_discard(window: Window, state: State<'_, AppState>, paths: Vec<
|
||||
pub async fn vcs_commit(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
repo: Option<PathBuf>,
|
||||
message: String,
|
||||
options: CommitOptions,
|
||||
amend: bool,
|
||||
sign_off: bool,
|
||||
) -> IdeResult<String> {
|
||||
// Commit hooks may run for a long time.
|
||||
let project = state.project(window.label())?;
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.commit_with(&message, &options))).await
|
||||
blocking(move || project.with_repo(|r| r.commit(&message, amend, sign_off))).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn vcs_checkout(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
repo: Option<PathBuf>,
|
||||
branch: String,
|
||||
create: bool,
|
||||
) -> IdeResult<()> {
|
||||
pub async fn vcs_checkout(window: Window, state: State<'_, AppState>, branch: String, create: bool) -> IdeResult<()> {
|
||||
let project = state.project(window.label())?;
|
||||
blocking(move || project.with_repo_recorded(repo.as_deref(), Some("Git checkout"), |r| r.checkout(&branch, create)))
|
||||
.await
|
||||
blocking(move || project.with_repo_recorded(Some("Git checkout"), |r| r.checkout(&branch, create))).await
|
||||
}
|
||||
|
||||
/// New Branch: creates `name` at `start` (HEAD when absent), optionally checking it out.
|
||||
@@ -197,31 +143,22 @@ pub async fn vcs_checkout(
|
||||
pub async fn vcs_create_branch(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
repo: Option<PathBuf>,
|
||||
name: String,
|
||||
start: Option<String>,
|
||||
checkout: bool,
|
||||
) -> IdeResult<()> {
|
||||
let project = state.project(window.label())?;
|
||||
let recorded = checkout.then_some("Git checkout");
|
||||
blocking(move || {
|
||||
project.with_repo_recorded(repo.as_deref(), recorded, |r| r.create_branch(&name, start.as_deref(), checkout))
|
||||
})
|
||||
.await
|
||||
blocking(move || project.with_repo_recorded(recorded, |r| r.create_branch(&name, start.as_deref(), checkout))).await
|
||||
}
|
||||
|
||||
/// Undo Commit: moves HEAD back to the commit's parent, keeping its changes staged.
|
||||
/// Returns the undone commit's message.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn vcs_undo_commit(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
repo: Option<PathBuf>,
|
||||
commit: String,
|
||||
) -> IdeResult<String> {
|
||||
pub async fn vcs_undo_commit(window: Window, state: State<'_, AppState>, commit: String) -> IdeResult<String> {
|
||||
let project = state.project(window.label())?;
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.undo_commit(&commit))).await
|
||||
blocking(move || project.with_repo(|r| r.undo_commit(&commit))).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -229,49 +166,32 @@ pub async fn vcs_undo_commit(
|
||||
pub async fn vcs_delete_branch(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
repo: Option<PathBuf>,
|
||||
branch: String,
|
||||
force: bool,
|
||||
) -> IdeResult<()> {
|
||||
let project = state.project(window.label())?;
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.delete_branch(&branch, force))).await
|
||||
blocking(move || project.with_repo(|r| r.delete_branch(&branch, force))).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn vcs_rename_branch(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
repo: Option<PathBuf>,
|
||||
from: String,
|
||||
to: String,
|
||||
) -> IdeResult<()> {
|
||||
pub async fn vcs_rename_branch(window: Window, state: State<'_, AppState>, from: String, to: String) -> IdeResult<()> {
|
||||
let project = state.project(window.label())?;
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.rename_branch(&from, &to))).await
|
||||
blocking(move || project.with_repo(|r| r.rename_branch(&from, &to))).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn vcs_merge(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
repo: Option<PathBuf>,
|
||||
branch: String,
|
||||
) -> IdeResult<()> {
|
||||
pub async fn vcs_merge(window: Window, state: State<'_, AppState>, branch: String) -> IdeResult<()> {
|
||||
let project = state.project(window.label())?;
|
||||
blocking(move || project.with_repo_recorded(repo.as_deref(), Some("Git merge"), |r| r.merge(&branch))).await
|
||||
blocking(move || project.with_repo_recorded(Some("Git merge"), |r| r.merge(&branch))).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn vcs_rebase(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
repo: Option<PathBuf>,
|
||||
onto: String,
|
||||
) -> IdeResult<()> {
|
||||
pub async fn vcs_rebase(window: Window, state: State<'_, AppState>, onto: String) -> IdeResult<()> {
|
||||
let project = state.project(window.label())?;
|
||||
blocking(move || project.with_repo_recorded(repo.as_deref(), Some("Git rebase"), |r| r.rebase(&onto))).await
|
||||
blocking(move || project.with_repo_recorded(Some("Git rebase"), |r| r.rebase(&onto))).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -279,43 +199,28 @@ pub async fn vcs_rebase(
|
||||
pub async fn vcs_stash_push(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
repo: Option<PathBuf>,
|
||||
message: Option<String>,
|
||||
include_untracked: bool,
|
||||
) -> IdeResult<()> {
|
||||
let project = state.project(window.label())?;
|
||||
blocking(move || {
|
||||
project.with_repo_recorded(repo.as_deref(), Some("Git stash"), |r| {
|
||||
r.stash_push(message.as_deref(), include_untracked)
|
||||
})
|
||||
project.with_repo_recorded(Some("Git stash"), |r| r.stash_push(message.as_deref(), include_untracked))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn vcs_stash_apply(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
repo: Option<PathBuf>,
|
||||
index: u32,
|
||||
pop: bool,
|
||||
) -> IdeResult<()> {
|
||||
pub async fn vcs_stash_apply(window: Window, state: State<'_, AppState>, index: u32, pop: bool) -> IdeResult<()> {
|
||||
let project = state.project(window.label())?;
|
||||
blocking(move || project.with_repo_recorded(repo.as_deref(), Some("Git unstash"), |r| r.stash_apply(index, pop)))
|
||||
.await
|
||||
blocking(move || project.with_repo_recorded(Some("Git unstash"), |r| r.stash_apply(index, pop))).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn vcs_stash_drop(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
repo: Option<PathBuf>,
|
||||
index: u32,
|
||||
) -> IdeResult<()> {
|
||||
pub async fn vcs_stash_drop(window: Window, state: State<'_, AppState>, index: u32) -> IdeResult<()> {
|
||||
let project = state.project(window.label())?;
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.stash_drop(index))).await
|
||||
blocking(move || project.with_repo(|r| r.stash_drop(index))).await
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize, Type)]
|
||||
@@ -354,7 +259,6 @@ pub enum RemoteOp {
|
||||
pub async fn vcs_remote(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
repo: Option<PathBuf>,
|
||||
request: RequestId,
|
||||
op: RemoteOp,
|
||||
on_output: Channel<String>,
|
||||
@@ -366,7 +270,7 @@ pub async fn vcs_remote(
|
||||
let _ = on_output.send(line);
|
||||
};
|
||||
let recorded = matches!(op, RemoteOp::Pull { .. }).then_some("Git pull");
|
||||
project.with_repo_recorded(repo.as_deref(), recorded, |r| match op {
|
||||
project.with_repo_recorded(recorded, |r| match op {
|
||||
RemoteOp::Fetch => r.fetch(&cancel, &out),
|
||||
RemoteOp::Pull { rebase } => r.pull(rebase, &cancel, &out),
|
||||
RemoteOp::Push { force_with_lease, set_upstream, tags } => {
|
||||
@@ -401,7 +305,7 @@ pub async fn vcs_conflict_versions(
|
||||
) -> IdeResult<ConflictVersions> {
|
||||
let project = state.project(window.label())?;
|
||||
blocking(move || {
|
||||
project.with_repo_of(&path, |r| {
|
||||
project.with_repo(|r| {
|
||||
r.conflict_versions(&path).map(|(base, ours, theirs)| ConflictVersions { base, ours, theirs })
|
||||
})
|
||||
})
|
||||
@@ -417,7 +321,7 @@ pub async fn vcs_diff_text(
|
||||
staged: bool,
|
||||
) -> IdeResult<String> {
|
||||
let project = state.project(window.label())?;
|
||||
blocking(move || project.with_repo_of(&path, |r| r.diff_text(&path, staged))).await
|
||||
blocking(move || project.with_repo(|r| r.diff_text(&path, staged))).await
|
||||
}
|
||||
|
||||
/// Line hunks between two arbitrary texts (diff viewer, commit dialog).
|
||||
@@ -434,7 +338,7 @@ pub fn vcs_diff_hunks(old_text: String, new_text: String) -> Vec<LineHunk> {
|
||||
pub fn vcs_stage_hunks(window: Window, state: State<'_, AppState>, path: PathBuf, hunks: Vec<u32>) -> IdeResult<()> {
|
||||
let project = state.project(window.label())?;
|
||||
let current = ide_vfs::load_text(&path)?.text;
|
||||
project.with_repo_of(&path, |r| {
|
||||
project.with_repo(|r| {
|
||||
let index_text = r.file_at(&path, Some(":0"))?.unwrap_or_default();
|
||||
let rel = path.strip_prefix(r.root()).unwrap_or(&path).to_string_lossy().replace('\\', "/");
|
||||
let selected: Vec<usize> = hunks.iter().map(|&h| h as usize).collect();
|
||||
@@ -505,14 +409,9 @@ pub fn vcs_detected_git() -> Option<String> {
|
||||
/// `git config --get <key>` in the project repository; `None` when unset.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn vcs_config_get(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
repo: Option<PathBuf>,
|
||||
key: String,
|
||||
) -> IdeResult<Option<String>> {
|
||||
pub async fn vcs_config_get(window: Window, state: State<'_, AppState>, key: String) -> IdeResult<Option<String>> {
|
||||
let project = state.project(window.label())?;
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.config_get(&key))).await
|
||||
blocking(move || project.with_repo(|r| r.config_get(&key))).await
|
||||
}
|
||||
|
||||
// ---- in-progress operations, history rewriting (Git Log actions) ----
|
||||
@@ -550,7 +449,6 @@ pub enum GitOperation {
|
||||
pub async fn vcs_operation(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
repo: Option<PathBuf>,
|
||||
request: RequestId,
|
||||
op: GitOperation,
|
||||
on_output: Channel<String>,
|
||||
@@ -568,7 +466,7 @@ pub async fn vcs_operation(
|
||||
GitOperation::InteractiveRebase { .. } => Some("Git rebase"),
|
||||
_ => None,
|
||||
};
|
||||
project.with_repo_recorded(repo.as_deref(), recorded, |r| match op {
|
||||
project.with_repo_recorded(recorded, |r| match op {
|
||||
GitOperation::Continue => r.continue_operation(&cancel, &out),
|
||||
GitOperation::Abort => r.abort_operation(&cancel, &out),
|
||||
GitOperation::Skip => r.skip_operation(&cancel, &out),
|
||||
@@ -591,22 +489,20 @@ pub async fn vcs_operation(
|
||||
pub async fn vcs_create_tag(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
repo: Option<PathBuf>,
|
||||
name: String,
|
||||
commit: String,
|
||||
message: Option<String>,
|
||||
force: bool,
|
||||
) -> IdeResult<()> {
|
||||
let project = state.project(window.label())?;
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.create_tag(&name, &commit, message.as_deref(), force)))
|
||||
.await
|
||||
blocking(move || project.with_repo(|r| r.create_tag(&name, &commit, message.as_deref(), force))).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn vcs_tags(window: Window, state: State<'_, AppState>, repo: Option<PathBuf>) -> IdeResult<Vec<String>> {
|
||||
pub async fn vcs_tags(window: Window, state: State<'_, AppState>) -> IdeResult<Vec<String>> {
|
||||
let project = state.project(window.label())?;
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.tags())).await
|
||||
blocking(move || project.with_repo(|r| r.tags())).await
|
||||
}
|
||||
|
||||
/// Compare with Local: tracked files that differ between `rev` and the working tree.
|
||||
@@ -615,42 +511,10 @@ pub async fn vcs_tags(window: Window, state: State<'_, AppState>, repo: Option<P
|
||||
pub async fn vcs_diff_with_worktree(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
repo: Option<PathBuf>,
|
||||
rev: String,
|
||||
) -> IdeResult<Vec<ChangedFile>> {
|
||||
let project = state.project(window.label())?;
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.diff_with_worktree(&rev))).await
|
||||
}
|
||||
|
||||
/// Runs `f` once per repository with the `paths` that belong to it.
|
||||
fn per_repo(
|
||||
project: &Project,
|
||||
paths: &[PathBuf],
|
||||
recorded: Option<&str>,
|
||||
f: impl Fn(&Repo, &[PathBuf]) -> IdeResult<()>,
|
||||
) -> IdeResult<()> {
|
||||
let groups = project.repos().group(paths);
|
||||
if groups.is_empty() {
|
||||
return project.with_repo_recorded(None, recorded, |r| f(r, paths));
|
||||
}
|
||||
for (repo, paths) in groups {
|
||||
project.with_repo_recorded(Some(repo.root()), recorded, |r| f(r, &paths))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Shelf and patches work in the primary repository only: changes of a nested one
|
||||
/// fail instead of being left out silently.
|
||||
fn in_primary_repo(project: &Project, paths: &[PathBuf]) -> IdeResult<()> {
|
||||
let repos = project.repos();
|
||||
let primary = repos.primary().map(|r| r.root());
|
||||
match paths.iter().find(|p| repos.for_path(p).map(|r| r.root()) != primary) {
|
||||
Some(p) => Err(ide_core::IdeError::invalid(format!(
|
||||
"{} is in another git repository; shelving and patches support the project's main repository only",
|
||||
p.display()
|
||||
))),
|
||||
None => Ok(()),
|
||||
}
|
||||
blocking(move || project.with_repo(|r| r.diff_with_worktree(&rev))).await
|
||||
}
|
||||
|
||||
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
|
||||
@@ -676,7 +540,6 @@ pub async fn vcs_create_patch(window: Window, state: State<'_, AppState>, source
|
||||
project.with_repo(|r| match source {
|
||||
PatchSource::Changes { paths, reverse } => {
|
||||
let paths: Vec<PathBuf> = paths.into_iter().map(Into::into).collect();
|
||||
in_primary_repo(&project, &paths)?;
|
||||
r.create_patch(&paths, reverse)
|
||||
}
|
||||
PatchSource::Commits { commits, reverse } => r.create_commits_patch(&commits, reverse),
|
||||
@@ -724,9 +587,8 @@ pub async fn vcs_shelve(
|
||||
) -> IdeResult<ShelvedChangeList> {
|
||||
let project = state.project(window.label())?;
|
||||
blocking(move || {
|
||||
in_primary_repo(&project, &paths)?;
|
||||
keep_private(&project.root);
|
||||
project.with_repo_recorded(None, Some("Shelve"), |r| r.shelve(&shelf_dir(&project.root), &name, &paths))
|
||||
project.with_repo_recorded(Some("Shelve"), |r| r.shelve(&shelf_dir(&project.root), &name, &paths))
|
||||
})
|
||||
.await
|
||||
}
|
||||
@@ -750,7 +612,7 @@ pub async fn vcs_unshelve(
|
||||
) -> IdeResult<ApplyOutcome> {
|
||||
let project = state.project(window.label())?;
|
||||
blocking(move || {
|
||||
project.with_repo_recorded(None, Some("Unshelve"), |r| r.unshelve(&shelf_dir(&project.root), &id, remove))
|
||||
project.with_repo_recorded(Some("Unshelve"), |r| r.unshelve(&shelf_dir(&project.root), &id, remove))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -59,36 +59,6 @@ pub fn window_take_launch(window: WebviewWindow, windows: State<'_, WindowsState
|
||||
windows.take_launch(window.label())
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct OpenProject {
|
||||
pub name: String,
|
||||
pub root: PathBuf,
|
||||
/// Open in the calling window.
|
||||
pub current: bool,
|
||||
}
|
||||
|
||||
/// Projects open in project windows, in window order (title bar project widget).
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn window_open_projects(
|
||||
app: AppHandle,
|
||||
window: WebviewWindow,
|
||||
state: State<'_, AppState>,
|
||||
) -> IdeResult<Vec<OpenProject>> {
|
||||
Ok(windows::project_window_labels(&app)
|
||||
.into_iter()
|
||||
.filter_map(|label| {
|
||||
let project = state.project(&label).ok()?;
|
||||
Some(OpenProject {
|
||||
name: project.root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),
|
||||
root: project.root.clone(),
|
||||
current: label == window.label(),
|
||||
})
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CloseContext {
|
||||
|
||||
+19
-108
@@ -8,7 +8,7 @@ use ide_run::ProcessManager;
|
||||
use ide_syntax::StructureService;
|
||||
use ide_terminal::TerminalManager;
|
||||
use ide_text::{AppliedChange, ByteEdit};
|
||||
use ide_vcs::{Repo, Repos};
|
||||
use ide_vcs::Repo;
|
||||
use ide_vfs::Watcher;
|
||||
use ide_workspace::documents::DocumentObserver;
|
||||
use ide_workspace::{
|
||||
@@ -56,8 +56,7 @@ pub struct Project {
|
||||
pub moves: FileMoves,
|
||||
pub index: Arc<ProjectIndex>,
|
||||
pub lsp: Arc<LspManager>,
|
||||
/// Git repositories: the one containing the project root and those nested below it.
|
||||
pub repos: Arc<RwLock<Repos>>,
|
||||
pub repo: Mutex<Option<Repo>>,
|
||||
/// Incrementally maintained syntax trees of the open documents.
|
||||
pub syntax: Arc<SyntaxCache>,
|
||||
/// Tree-sitter structure queries (LSP fallback) over `syntax`.
|
||||
@@ -243,32 +242,13 @@ impl AppState {
|
||||
let root = root.clone();
|
||||
let data_dir = self.data_dir.clone();
|
||||
lsp.set_config_hook(Box::new(move |cfg, server_root| {
|
||||
let effective = settings.effective();
|
||||
ide_sdk::apply::configure_server(cfg, &root, server_root, &effective);
|
||||
ide_sdk::apply::configure_server(cfg, &root, server_root, &settings.effective());
|
||||
if cfg.name == "jdtls" {
|
||||
let bundles: Vec<PathBuf> =
|
||||
ide_tools::managed_bundle(&data_dir, "java-debug").into_iter().collect();
|
||||
let min_java = ide_sdk::java::jdtls_min_java(cfg);
|
||||
let jdks = ide_sdk::java::jdtls_jdks(min_java);
|
||||
let lombok = ide_sdk::lombok::lombok_agent(
|
||||
server_root,
|
||||
ide_sdk::lombok::agent_in_args(cfg.args.iter().map(String::as_str)),
|
||||
ide_tools::managed_bundle(&data_dir, "lombok"),
|
||||
ide_sdk::apply::maven_local_repository(&root, &effective),
|
||||
);
|
||||
if let Some(problem) = lombok.problem() {
|
||||
tracing::warn!("{problem}");
|
||||
}
|
||||
ide_sdk::java::configure_jdtls(
|
||||
cfg,
|
||||
server_root,
|
||||
&data_dir,
|
||||
&jdks,
|
||||
ide_sdk::apply::project_jdk(&root, &effective).as_ref(),
|
||||
min_java,
|
||||
&bundles,
|
||||
lombok.jar(),
|
||||
);
|
||||
ide_sdk::java::configure_jdtls(cfg, server_root, &data_dir, &jdks, min_java, &bundles);
|
||||
}
|
||||
}));
|
||||
}
|
||||
@@ -281,10 +261,7 @@ impl AppState {
|
||||
documents.add_observer(Arc::new(LspObserver(lsp.clone())));
|
||||
documents.add_observer(Arc::new(HistoryObserver(history.clone())));
|
||||
|
||||
let repos = Arc::new(RwLock::new(Repos::enclosing(&root)?));
|
||||
let watcher = {
|
||||
let repos = repos.clone();
|
||||
let settings = settings.clone();
|
||||
let index = index.clone();
|
||||
let documents = documents.clone();
|
||||
let sink = sink.clone();
|
||||
@@ -310,19 +287,6 @@ impl AppState {
|
||||
sink.emit(IdeEvent::ProjectRootsChanged { root: root.clone().into() });
|
||||
}
|
||||
}
|
||||
// A repository was cloned / initialised / removed below the project: its
|
||||
// `.git/HEAD` (the watcher reports nothing else of `.git`) appeared or went.
|
||||
let known = repos.read().roots();
|
||||
let git_dirs = changed.iter().chain(&batch.removed).any(|p| {
|
||||
let Some(dir) = p.ends_with(".git/HEAD").then(|| p.parent().and_then(Path::parent)).flatten()
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
known.iter().any(|r| r == dir) != p.is_file()
|
||||
});
|
||||
if git_dirs {
|
||||
scan_repositories(&root, &repos, &settings, &sink);
|
||||
}
|
||||
sink.emit(IdeEvent::VcsChanged { root: root.clone().into() });
|
||||
}),
|
||||
)?
|
||||
@@ -349,13 +313,8 @@ impl AppState {
|
||||
};
|
||||
|
||||
mark("watcher");
|
||||
let branch = repos.read().primary().and_then(|r| r.branch_info().ok()).and_then(|b| b.head);
|
||||
{
|
||||
let (root, repos, settings, sink) = (root.clone(), repos.clone(), settings.clone(), sink.clone());
|
||||
std::thread::Builder::new()
|
||||
.name("openidea-vcs-roots".into())
|
||||
.spawn(move || scan_repositories(&root, &repos, &settings, &sink))?;
|
||||
}
|
||||
let repo = Repo::discover(&root)?;
|
||||
let branch = repo.as_ref().and_then(|r| r.branch_info().ok()).and_then(|b| b.head);
|
||||
mark("git");
|
||||
self.recent.touch(&root, branch)?;
|
||||
mark("recent");
|
||||
@@ -372,7 +331,7 @@ impl AppState {
|
||||
moves: FileMoves::new(),
|
||||
index,
|
||||
lsp,
|
||||
repos,
|
||||
repo: Mutex::new(repo),
|
||||
structure: Arc::new(StructureService::new(syntax.clone())),
|
||||
syntax,
|
||||
detected_roots,
|
||||
@@ -414,65 +373,18 @@ impl AppState {
|
||||
}
|
||||
}
|
||||
|
||||
/// Looks for repositories nested below the project (and the one containing it);
|
||||
/// emits `VcsChanged` when the set of roots changed.
|
||||
fn scan_repositories(root: &Path, repos: &RwLock<Repos>, settings: &SettingsStore, sink: &SharedSink) {
|
||||
let ignored = settings.effective().ignored_names();
|
||||
let skip = |p: &Path| p.file_name().is_some_and(|n| ignored.is_ignored_name(&n.to_string_lossy()));
|
||||
match Repos::discover(root, &skip) {
|
||||
Ok(found) => {
|
||||
if found.roots() != repos.read().roots() {
|
||||
*repos.write() = found;
|
||||
sink.emit(IdeEvent::VcsChanged { root: root.to_path_buf().into() });
|
||||
}
|
||||
}
|
||||
Err(e) => tracing::warn!("looking for git repositories: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
impl Project {
|
||||
/// The project's git repositories.
|
||||
pub fn repos(&self) -> Repos {
|
||||
self.repos.read().clone()
|
||||
}
|
||||
|
||||
/// Runs `f` with the repository whose root is `at`, the project's primary repository
|
||||
/// when `None`; fails when there is none (a repository-scoped command never falls back
|
||||
/// to another repository).
|
||||
pub fn with_repo_at<T>(&self, at: Option<&Path>, f: impl FnOnce(&Repo) -> IdeResult<T>) -> IdeResult<T> {
|
||||
let repos = self.repos();
|
||||
match at {
|
||||
Some(root) => match repos.at_root(root) {
|
||||
Some(repo) => self.run_in(repo, f),
|
||||
None => {
|
||||
Err(IdeError::unavailable(format!("{} is not a git repository of the project", root.display())))
|
||||
}
|
||||
},
|
||||
None => match repos.primary() {
|
||||
Some(repo) => self.run_in(repo, f),
|
||||
None => Err(IdeError::unavailable("project is not a git repository")),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `f` with the repository `path` (a file or folder) belongs to.
|
||||
pub fn with_repo_of<T>(&self, path: &Path, f: impl FnOnce(&Repo) -> IdeResult<T>) -> IdeResult<T> {
|
||||
match self.repos().for_path(path) {
|
||||
Some(repo) => self.run_in(repo, f),
|
||||
None => Err(IdeError::unavailable(format!("{} is not in a git repository", path.display()))),
|
||||
}
|
||||
}
|
||||
|
||||
fn run_in<T>(&self, repo: &Repo, f: impl FnOnce(&Repo) -> IdeResult<T>) -> IdeResult<T> {
|
||||
/// Runs `f` with the git repository, or fails when the project is not under git.
|
||||
pub fn with_repo<T>(&self, f: impl FnOnce(&Repo) -> IdeResult<T>) -> IdeResult<T> {
|
||||
let settings = self.settings.effective();
|
||||
crate::commands::vcs::apply_git_executable(&settings);
|
||||
repo.set_ignored_names(settings.ignored_names());
|
||||
f(repo)
|
||||
}
|
||||
|
||||
/// Runs `f` with the project's primary git repository, or fails when the project is not under git.
|
||||
pub fn with_repo<T>(&self, f: impl FnOnce(&Repo) -> IdeResult<T>) -> IdeResult<T> {
|
||||
self.with_repo_at(None, f)
|
||||
match self.repo.lock().as_ref() {
|
||||
Some(repo) => {
|
||||
repo.set_ignored_names(settings.ignored_names());
|
||||
f(repo)
|
||||
}
|
||||
None => Err(IdeError::unavailable("project is not a git repository")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs a VCS operation that rewrites the working tree (checkout, merge,
|
||||
@@ -481,20 +393,19 @@ impl Project {
|
||||
/// `None` runs `f` like [`with_repo`](Self::with_repo) (operations that keep the working tree).
|
||||
pub fn with_repo_recorded<T>(
|
||||
&self,
|
||||
at: Option<&Path>,
|
||||
operation: Option<&str>,
|
||||
f: impl FnOnce(&Repo) -> IdeResult<T>,
|
||||
) -> IdeResult<T> {
|
||||
let Some(name) = operation else { return self.with_repo_at(at, f) };
|
||||
let Some(name) = operation else { return self.with_repo(f) };
|
||||
self.history_label(&format!("Before {name}"));
|
||||
if let Ok(changed) = self.with_repo_at(at, |r| r.status()) {
|
||||
if let Ok(changed) = self.with_repo(|r| r.status()) {
|
||||
for file in changed.iter().take(HISTORY_BATCH_LIMIT) {
|
||||
if let Err(e) = self.history.record_file(&file.path, &format!("Before {name}"), false) {
|
||||
tracing::debug!("local history: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
let result = self.with_repo_at(at, f);
|
||||
let result = self.with_repo(f);
|
||||
self.history_label(&format!("After {name}"));
|
||||
result
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "OpenIDEA",
|
||||
"version": "0.1.5",
|
||||
"version": "0.1.3",
|
||||
"identifier": "ai.l0ng.openidea",
|
||||
"build": {
|
||||
"beforeDevCommand": "pnpm dev",
|
||||
|
||||
+24
-102
@@ -249,41 +249,38 @@ export const commands = {
|
||||
* follow-up command. Edits the server requests arrive via `workspace/applyEdit`.
|
||||
*/
|
||||
lspExecuteCommand: (doc: DocId, command: Command) => typedError<null, IdeError>(__TAURI_INVOKE("lsp_execute_command", { doc, command })),
|
||||
/** Changes of every repository of the project. */
|
||||
vcsStatus: () => typedError<FileStatus[], IdeError>(__TAURI_INVOKE("vcs_status")),
|
||||
/** The project's repositories, the primary one first. */
|
||||
vcsRoots: () => typedError<VcsRoot[], IdeError>(__TAURI_INVOKE("vcs_roots")),
|
||||
vcsBranchInfo: (repo: string | null) => typedError<BranchInfo, IdeError>(__TAURI_INVOKE("vcs_branch_info", { repo })),
|
||||
vcsBranchInfo: () => typedError<BranchInfo, IdeError>(__TAURI_INVOKE("vcs_branch_info")),
|
||||
/** Gutter change markers for a file, computed against its current (unsaved) text. */
|
||||
vcsLineHunks: (path: string) => typedError<LineHunk[], IdeError>(__TAURI_INVOKE("vcs_line_hunks", { path })),
|
||||
vcsFileAt: (path: string, rev: string | null) => typedError<string | null, IdeError>(__TAURI_INVOKE("vcs_file_at", { path, rev })),
|
||||
vcsBlame: (path: string) => typedError<BlameLine[], IdeError>(__TAURI_INVOKE("vcs_blame", { path })),
|
||||
vcsLog: (repo: string | null, query: LogQuery) => typedError<Commit[], IdeError>(__TAURI_INVOKE("vcs_log", { repo, query })),
|
||||
vcsCommitFiles: (repo: string | null, commit: string) => typedError<ChangedFile[], IdeError>(__TAURI_INVOKE("vcs_commit_files", { repo, commit })),
|
||||
vcsBranches: (repo: string | null) => typedError<Branch[], IdeError>(__TAURI_INVOKE("vcs_branches", { repo })),
|
||||
vcsStashes: (repo: string | null) => typedError<Stash[], IdeError>(__TAURI_INVOKE("vcs_stashes", { repo })),
|
||||
vcsLog: (query: LogQuery) => typedError<Commit[], IdeError>(__TAURI_INVOKE("vcs_log", { query })),
|
||||
vcsCommitFiles: (commit: string) => typedError<ChangedFile[], IdeError>(__TAURI_INVOKE("vcs_commit_files", { commit })),
|
||||
vcsBranches: () => typedError<Branch[], IdeError>(__TAURI_INVOKE("vcs_branches")),
|
||||
vcsStashes: () => typedError<Stash[], IdeError>(__TAURI_INVOKE("vcs_stashes")),
|
||||
vcsStage: (paths: string[]) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_stage", { paths })),
|
||||
vcsUnstage: (paths: string[]) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_unstage", { paths })),
|
||||
vcsStagePatch: (patch: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_stage_patch", { patch })),
|
||||
vcsDiscard: (paths: string[]) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_discard", { paths })),
|
||||
vcsCommit: (repo: string | null, message: string, options: CommitOptions) => typedError<string, IdeError>(__TAURI_INVOKE("vcs_commit", { repo, message, options })),
|
||||
vcsCheckout: (repo: string | null, branch: string, create: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_checkout", { repo, branch, create })),
|
||||
vcsDeleteBranch: (repo: string | null, branch: string, force: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_delete_branch", { repo, branch, force })),
|
||||
vcsCommit: (message: string, amend: boolean, signOff: boolean) => typedError<string, IdeError>(__TAURI_INVOKE("vcs_commit", { message, amend, signOff })),
|
||||
vcsCheckout: (branch: string, create: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_checkout", { branch, create })),
|
||||
vcsDeleteBranch: (branch: string, force: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_delete_branch", { branch, force })),
|
||||
/** New Branch: creates `name` at `start` (HEAD when absent), optionally checking it out. */
|
||||
vcsCreateBranch: (repo: string | null, name: string, start: string | null, checkout: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_create_branch", { repo, name, start, checkout })),
|
||||
vcsCreateBranch: (name: string, start: string | null, checkout: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_create_branch", { name, start, checkout })),
|
||||
/**
|
||||
* Undo Commit: moves HEAD back to the commit's parent, keeping its changes staged.
|
||||
* Returns the undone commit's message.
|
||||
*/
|
||||
vcsUndoCommit: (repo: string | null, commit: string) => typedError<string, IdeError>(__TAURI_INVOKE("vcs_undo_commit", { repo, commit })),
|
||||
vcsRenameBranch: (repo: string | null, from: string, to: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_rename_branch", { repo, from, to })),
|
||||
vcsMerge: (repo: string | null, branch: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_merge", { repo, branch })),
|
||||
vcsRebase: (repo: string | null, onto: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_rebase", { repo, onto })),
|
||||
vcsStashPush: (repo: string | null, message: string | null, includeUntracked: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_stash_push", { repo, message, includeUntracked })),
|
||||
vcsStashApply: (repo: string | null, index: number, pop: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_stash_apply", { repo, index, pop })),
|
||||
vcsStashDrop: (repo: string | null, index: number) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_stash_drop", { repo, index })),
|
||||
vcsUndoCommit: (commit: string) => typedError<string, IdeError>(__TAURI_INVOKE("vcs_undo_commit", { commit })),
|
||||
vcsRenameBranch: (from: string, to: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_rename_branch", { from, to })),
|
||||
vcsMerge: (branch: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_merge", { branch })),
|
||||
vcsRebase: (onto: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_rebase", { onto })),
|
||||
vcsStashPush: (message: string | null, includeUntracked: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_stash_push", { message, includeUntracked })),
|
||||
vcsStashApply: (index: number, pop: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_stash_apply", { index, pop })),
|
||||
vcsStashDrop: (index: number) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_stash_drop", { index })),
|
||||
/** Network operation; progress lines stream through `on_output`. Cancellable. */
|
||||
vcsRemote: (repo: string | null, request: RequestId, op: RemoteOp, onOutput: Channel<string>) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_remote", { repo, request, op, onOutput })),
|
||||
vcsRemote: (request: RequestId, op: RemoteOp, onOutput: Channel<string>) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_remote", { request, op, onOutput })),
|
||||
vcsConflictVersions: (path: string) => typedError<ConflictVersions, IdeError>(__TAURI_INVOKE("vcs_conflict_versions", { path })),
|
||||
vcsDiffText: (path: string, staged: boolean) => typedError<string, IdeError>(__TAURI_INVOKE("vcs_diff_text", { path, staged })),
|
||||
/** Line hunks between two arbitrary texts (diff viewer, commit dialog). */
|
||||
@@ -303,16 +300,16 @@ export const commands = {
|
||||
/** The auto-detected git executable (shown as the field's placeholder). */
|
||||
vcsDetectedGit: () => __TAURI_INVOKE<string | null>("vcs_detected_git"),
|
||||
/** `git config --get <key>` in the project repository; `None` when unset. */
|
||||
vcsConfigGet: (repo: string | null, key: string) => typedError<string | null, IdeError>(__TAURI_INVOKE("vcs_config_get", { repo, key })),
|
||||
vcsConfigGet: (key: string) => typedError<string | null, IdeError>(__TAURI_INVOKE("vcs_config_get", { key })),
|
||||
/**
|
||||
* Local history operation that may take a while (hooks, large checkouts); git's
|
||||
* output streams through `on_output`. Cancellable.
|
||||
*/
|
||||
vcsOperation: (repo: string | null, request: RequestId, op: GitOperation, onOutput: Channel<string>) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_operation", { repo, request, op, onOutput })),
|
||||
vcsCreateTag: (repo: string | null, name: string, commit: string, message: string | null, force: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_create_tag", { repo, name, commit, message, force })),
|
||||
vcsTags: (repo: string | null) => typedError<string[], IdeError>(__TAURI_INVOKE("vcs_tags", { repo })),
|
||||
vcsOperation: (request: RequestId, op: GitOperation, onOutput: Channel<string>) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_operation", { request, op, onOutput })),
|
||||
vcsCreateTag: (name: string, commit: string, message: string | null, force: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_create_tag", { name, commit, message, force })),
|
||||
vcsTags: () => typedError<string[], IdeError>(__TAURI_INVOKE("vcs_tags")),
|
||||
/** Compare with Local: tracked files that differ between `rev` and the working tree. */
|
||||
vcsDiffWithWorktree: (repo: string | null, rev: string) => typedError<ChangedFile[], IdeError>(__TAURI_INVOKE("vcs_diff_with_worktree", { repo, rev })),
|
||||
vcsDiffWithWorktree: (rev: string) => typedError<ChangedFile[], IdeError>(__TAURI_INVOKE("vcs_diff_with_worktree", { rev })),
|
||||
vcsCreatePatch: (source: PatchSource) => typedError<string, IdeError>(__TAURI_INVOKE("vcs_create_patch", { source })),
|
||||
vcsPatchPreview: (patch: string) => typedError<PatchFile[], IdeError>(__TAURI_INVOKE("vcs_patch_preview", { patch })),
|
||||
vcsApplyPatch: (patch: string) => typedError<ApplyOutcome, IdeError>(__TAURI_INVOKE("vcs_apply_patch", { patch })),
|
||||
@@ -437,8 +434,6 @@ export const commands = {
|
||||
settingsPage: string | null,
|
||||
} | null>("window_take_launch"),
|
||||
windowCloseContext: () => __TAURI_INVOKE<CloseContext>("window_close_context"),
|
||||
/** Projects open in project windows, in window order (title bar project widget). */
|
||||
windowOpenProjects: () => typedError<OpenProject[], IdeError>(__TAURI_INVOKE("window_open_projects")),
|
||||
/** Quits: closes every window, each of which runs its own unsaved-changes check. */
|
||||
appQuit: () => __TAURI_INVOKE<void>("app_quit"),
|
||||
/** A window vetoed the quit (user cancelled its unsaved-changes prompt). */
|
||||
@@ -1032,16 +1027,6 @@ export type Commit = {
|
||||
refs: string[],
|
||||
};
|
||||
|
||||
/** Commit Options (IDEA's commit options popup). */
|
||||
export type CommitOptions = {
|
||||
amend: boolean,
|
||||
signOff: boolean,
|
||||
/** `--author`, e.g. `Name <[email protected]>`; `None` or blank uses the configured user. */
|
||||
author: string | null,
|
||||
/** False skips the pre-commit and commit-msg hooks (`--no-verify`). */
|
||||
runHooks: boolean,
|
||||
};
|
||||
|
||||
/** Version Control › Commit: commit checks and commit-message inspections. */
|
||||
export type CommitSettings = {
|
||||
analyzeCode?: boolean,
|
||||
@@ -2316,14 +2301,6 @@ export type JavaBuildStatus = "failed" | "succeeded" |
|
||||
/** Compiled, but some project has compile errors. */
|
||||
"withErrors" | "cancelled";
|
||||
|
||||
/** One error diagnostic; `line` / `column` are 1-based for display. */
|
||||
export type JavaCompileError = {
|
||||
path: IpcPath,
|
||||
line: number,
|
||||
column: number,
|
||||
message: string,
|
||||
};
|
||||
|
||||
/** Everything needed to launch a class of a module: build outcome, classpath and JDK. */
|
||||
export type JavaLaunchInfo = {
|
||||
/** `None` when no build was requested. */
|
||||
@@ -2335,27 +2312,6 @@ export type JavaLaunchInfo = {
|
||||
javaHome: IpcPath | null,
|
||||
/** The `java` launcher to use (filled in by the caller from the installed JDKs). */
|
||||
javaExec: string | null,
|
||||
/** First compile errors of the workspace when the build had errors. */
|
||||
errors: JavaCompileError[],
|
||||
/** All compile errors (`errors` is capped). */
|
||||
errorCount: number,
|
||||
/** Likely causes of the errors worth telling the user (e.g. a missing Lombok agent). */
|
||||
hints: string[],
|
||||
};
|
||||
|
||||
export type JavaSettings = {
|
||||
/**
|
||||
* Project JDK home; empty = per module, the installed JDK matching the
|
||||
* Java version it targets.
|
||||
*/
|
||||
jdk?: string,
|
||||
/**
|
||||
* Extra JVM options for the Java language server (jdtls), space-separated
|
||||
* (VS Code's `java.jdt.ls.vmargs`).
|
||||
*/
|
||||
jdtlsVmArgs?: string,
|
||||
/** Build Tools › Maven. */
|
||||
maven?: MavenSettings,
|
||||
};
|
||||
|
||||
/** Editor › Code Style › <Language> › Tabs and Indents (unset fields inherit). */
|
||||
@@ -2415,7 +2371,6 @@ export type LanguagesSettings = {
|
||||
rust?: RustSettings,
|
||||
go?: GoSettings,
|
||||
typescript?: TypeScriptSettings,
|
||||
java?: JavaSettings,
|
||||
};
|
||||
|
||||
/** What a freshly opened window should do once its frontend is up. */
|
||||
@@ -2645,22 +2600,10 @@ export type MavenProject = {
|
||||
javaVersion: number | null,
|
||||
/** Maven launcher: the nearest `mvnw` up to the project root (absolute), else `mvn`. */
|
||||
command: string,
|
||||
/** Options before the goals (`-s`, `-Dmaven.repo.local=`); filled in by the shell from settings. */
|
||||
options: string[],
|
||||
/** Environment for runs (`JAVA_HOME` of the matching JDK); filled in by the shell. */
|
||||
env: { [key in string]: string },
|
||||
};
|
||||
|
||||
/** Build Tools › Maven. */
|
||||
export type MavenSettings = {
|
||||
/** Maven home (or its `mvn` executable); empty = the project's `mvnw`, else `mvn` on `PATH`. */
|
||||
home?: string,
|
||||
/** User `settings.xml` (`-s`); empty = `~/.m2/settings.xml`. */
|
||||
userSettings?: string,
|
||||
/** Local repository (`-Dmaven.repo.local`); empty = from `settings.xml`. */
|
||||
localRepository?: string,
|
||||
};
|
||||
|
||||
export type MemoryCategory =
|
||||
/** The backend and its WebView processes. */
|
||||
"app" | "languageServer" |
|
||||
@@ -2750,13 +2693,6 @@ export type OpenOutcome =
|
||||
/** The caller should open the project in its own window. */
|
||||
{ kind: "current" };
|
||||
|
||||
export type OpenProject = {
|
||||
name: string,
|
||||
root: string,
|
||||
/** Open in the calling window. */
|
||||
current: boolean,
|
||||
};
|
||||
|
||||
/** A node of a document outline (Structure tool window, breadcrumbs). */
|
||||
export type OutlineItem = {
|
||||
name: string,
|
||||
@@ -3303,11 +3239,7 @@ export type Sdk = {
|
||||
/** What [`detect`] looks for. */
|
||||
export type SdkKind = "python" | "node" |
|
||||
/** npm / pnpm / yarn executables. */
|
||||
"packageManager" | "rust" | "go" | "typeScript" |
|
||||
/** JDK homes. */
|
||||
"jdk" |
|
||||
/** Maven homes. */
|
||||
"maven";
|
||||
"packageManager" | "rust" | "go" | "typeScript";
|
||||
|
||||
export type SearchEvent = { type: "file"; file: FileMatches } | { type: "done"; summary: SearchSummary };
|
||||
|
||||
@@ -3846,9 +3778,7 @@ export type ToolInfo = {
|
||||
homepage: string | null,
|
||||
};
|
||||
|
||||
export type ToolKind = "languageServer" | "debugger" |
|
||||
/** Loaded into another tool's process, e.g. a jdtls agent. */
|
||||
"plugin";
|
||||
export type ToolKind = "languageServer" | "debugger";
|
||||
|
||||
export type ToolStatus =
|
||||
/** Installed by the IDE (managed tools dir or a toolchain component it manages). */
|
||||
@@ -3900,14 +3830,6 @@ export type VcsConfirmationSettings = {
|
||||
onDelete?: string,
|
||||
};
|
||||
|
||||
/** A repository of the project (IDEA's VCS root). */
|
||||
export type VcsRoot = {
|
||||
/** Worktree root. */
|
||||
root: IpcPath,
|
||||
/** Merge / rebase / cherry-pick / revert in progress. */
|
||||
operation: string | null,
|
||||
};
|
||||
|
||||
/** Version Control (main page) and its sub-pages. */
|
||||
export type VcsSettings = {
|
||||
/** Colour folders that contain changed files (project tree, tabs). */
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { closePopup, useLspPopup } from "@/editor/lsp/popupStore";
|
||||
import type { DocModel } from "./model/document";
|
||||
import { readOnlyQuestion, toggleReadOnly } from "./fileAttributes";
|
||||
|
||||
@@ -12,34 +13,34 @@ function model(readOnly: boolean, extra: Partial<{ virtual: boolean; banner: str
|
||||
} as unknown as DocModel & { setReadOnly: ReturnType<typeof vi.fn> };
|
||||
}
|
||||
|
||||
let answer = true;
|
||||
const { confirm } = vi.hoisted(() => ({ confirm: vi.fn(async () => answer) }));
|
||||
vi.mock("@/workbench/messages", () => ({ confirm }));
|
||||
|
||||
beforeEach(() => confirm.mockClear());
|
||||
beforeEach(() => closePopup());
|
||||
|
||||
describe("Toggle Read-only Attribute", () => {
|
||||
it("asks before making a read-only file writable, then toggles", async () => {
|
||||
const m = model(true);
|
||||
answer = true;
|
||||
toggleReadOnly(m);
|
||||
expect(confirm).toHaveBeenCalledWith(expect.objectContaining({ title: "Make File Writable", ok: "Make Writable" }));
|
||||
const popup = useLspPopup.getState().popup;
|
||||
expect(popup).toMatchObject({ kind: "choice", title: "Make File Writable" });
|
||||
if (popup?.kind !== "choice") throw new Error("no choice");
|
||||
expect(popup.choices.map((c) => c.label)).toEqual(["Make Writable", "Cancel"]);
|
||||
popup.choices[0]!.run();
|
||||
await vi.waitFor(() => expect(m.setReadOnly).toHaveBeenCalledWith(false));
|
||||
});
|
||||
|
||||
it("Cancel leaves the file alone", async () => {
|
||||
it("Cancel leaves the file alone", () => {
|
||||
const m = model(false);
|
||||
answer = false;
|
||||
toggleReadOnly(m);
|
||||
expect(confirm).toHaveBeenCalledWith(expect.objectContaining({ title: "Make File Read-only" }));
|
||||
await Promise.resolve();
|
||||
const popup = useLspPopup.getState().popup;
|
||||
if (popup?.kind !== "choice") throw new Error("no choice");
|
||||
expect(popup.title).toBe("Make File Read-only");
|
||||
popup.choices[1]!.run();
|
||||
expect(m.setReadOnly).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does nothing for library and binary documents", () => {
|
||||
toggleReadOnly(model(true, { virtual: true }));
|
||||
toggleReadOnly(model(true, { banner: "binary" }));
|
||||
expect(confirm).not.toHaveBeenCalled();
|
||||
expect(useLspPopup.getState().popup).toBeNull();
|
||||
expect(readOnlyQuestion("a.txt", false).confirm).toBe("Make Read-only");
|
||||
});
|
||||
});
|
||||
@@ -5,8 +5,8 @@
|
||||
*/
|
||||
import { call, commands, isTauri } from "@/platform/ipc";
|
||||
import { basename } from "@/platform/project";
|
||||
import { openPopup } from "@/editor/lsp/popupStore";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { confirm } from "@/workbench/messages";
|
||||
import type { DocModel } from "./model/document";
|
||||
|
||||
export function readOnlyQuestion(name: string, readOnly: boolean) {
|
||||
@@ -36,7 +36,13 @@ export function toggleReadOnly(model: DocModel) {
|
||||
const meta = model.getMeta();
|
||||
if (meta.banner === "binary" || meta.banner === "tooLarge") return;
|
||||
const q = readOnlyQuestion(basename(model.path), meta.readOnly);
|
||||
void confirm({ title: q.title, message: q.message, ok: q.confirm }).then(
|
||||
(ok) => ok && void setFileWritable(model, meta.readOnly),
|
||||
);
|
||||
openPopup({
|
||||
kind: "choice",
|
||||
title: q.title,
|
||||
message: q.message,
|
||||
choices: [
|
||||
{ label: q.confirm, primary: true, run: () => void setFileWritable(model, meta.readOnly) },
|
||||
{ label: "Cancel", run: () => {} },
|
||||
],
|
||||
});
|
||||
}
|
||||
@@ -8,7 +8,7 @@ import { useEffect, useLayoutEffect, useRef, type KeyboardEvent } from "react";
|
||||
import { create } from "zustand";
|
||||
import clsx from "clsx";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { Button, IconButton, SearchField, T } from "@/ui";
|
||||
import { Button, IconButton, SearchField } from "@/ui";
|
||||
import { editorController, useFindBars, useTabs } from "../controller";
|
||||
import {
|
||||
countMatches,
|
||||
@@ -198,11 +198,7 @@ function FindBarInner({ paneId, replace, seq }: { paneId: string; replace: boole
|
||||
else run(replaceNext);
|
||||
} else run(back ? findPrevious : findNext);
|
||||
} else if (e.altKey && !e.metaKey && !e.ctrlKey) {
|
||||
const map: Record<string, "caseSensitive" | "wholeWord" | "regexp"> = {
|
||||
KeyC: "caseSensitive",
|
||||
KeyW: "wholeWord",
|
||||
KeyX: "regexp",
|
||||
};
|
||||
const map: Record<string, "caseSensitive" | "wholeWord" | "regexp"> = { KeyC: "caseSensitive", KeyW: "wholeWord", KeyX: "regexp" };
|
||||
const k = map[e.code];
|
||||
if (k) {
|
||||
e.preventDefault();
|
||||
@@ -239,51 +235,17 @@ function FindBarInner({ paneId, replace, seq }: { paneId: string; replace: boole
|
||||
invalid={invalid || none}
|
||||
onKeyDown={(e) => onKeyDown(e, "find")}
|
||||
toggles={[
|
||||
{
|
||||
id: "case",
|
||||
icon: "case",
|
||||
title: "Match Case",
|
||||
shortcut: "⌥C",
|
||||
pressed: opts.caseSensitive,
|
||||
onToggle: () => toggle("caseSensitive"),
|
||||
},
|
||||
{
|
||||
id: "word",
|
||||
icon: "word",
|
||||
title: "Words",
|
||||
shortcut: "⌥W",
|
||||
pressed: opts.wholeWord,
|
||||
onToggle: () => toggle("wholeWord"),
|
||||
},
|
||||
{
|
||||
id: "regex",
|
||||
icon: "regex",
|
||||
title: "Regex",
|
||||
shortcut: "⌥X",
|
||||
pressed: opts.regexp,
|
||||
onToggle: () => toggle("regexp"),
|
||||
},
|
||||
{
|
||||
id: "scope",
|
||||
icon: "filter",
|
||||
title: "In Selection",
|
||||
shortcut: "⌥E",
|
||||
pressed: scoped,
|
||||
onToggle: () => toggleScope(paneId),
|
||||
},
|
||||
{ id: "case", icon: "case", title: "Match Case", shortcut: "⌥C", pressed: opts.caseSensitive, onToggle: () => toggle("caseSensitive") },
|
||||
{ id: "word", icon: "word", title: "Words", shortcut: "⌥W", pressed: opts.wholeWord, onToggle: () => toggle("wholeWord") },
|
||||
{ id: "regex", icon: "regex", title: "Regex", shortcut: "⌥X", pressed: opts.regexp, onToggle: () => toggle("regexp") },
|
||||
{ id: "scope", icon: "filter", title: "In Selection", shortcut: "⌥E", pressed: scoped, onToggle: () => toggleScope(paneId) },
|
||||
]}
|
||||
/>
|
||||
<div className={styles.findButtons}>
|
||||
<span className={clsx(styles.findCount, (none || invalid) && styles.findCountNone)} aria-live="polite">
|
||||
{counter}
|
||||
</span>
|
||||
<IconButton
|
||||
icon="arrow-up"
|
||||
title="Previous Occurrence"
|
||||
shortcut="⇧↵"
|
||||
size="small"
|
||||
onClick={() => run(findPrevious)}
|
||||
/>
|
||||
<IconButton icon="arrow-up" title="Previous Occurrence" shortcut="⇧↵" size="small" onClick={() => run(findPrevious)} />
|
||||
<IconButton icon="arrow-down" title="Next Occurrence" shortcut="↵" size="small" onClick={() => run(findNext)} />
|
||||
<IconButton
|
||||
icon="replace"
|
||||
@@ -308,10 +270,10 @@ function FindBarInner({ paneId, replace, seq }: { paneId: string; replace: boole
|
||||
/>
|
||||
<div className={styles.replaceButtons}>
|
||||
<Button size="small" onClick={() => run(replaceNext)} disabled={!opts.search || invalid}>
|
||||
<T>Replace</T>
|
||||
Replace
|
||||
</Button>
|
||||
<Button size="small" onClick={() => run(replaceAll)} disabled={!opts.search || invalid}>
|
||||
<T>Replace All</T>
|
||||
Replace All
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
|
||||
@@ -9,19 +9,11 @@ import clsx from "clsx";
|
||||
import { create } from "zustand";
|
||||
import { call, commands, isTauri, type OutlineItem } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { Icon, Popup, T } from "@/ui";
|
||||
import { Icon, Popup } from "@/ui";
|
||||
import { editorController, useEditorStatus } from "../controller";
|
||||
import { useOutline } from "../model/document";
|
||||
import { symbolChain } from "./outline";
|
||||
import {
|
||||
dirChildren,
|
||||
iconOf,
|
||||
navSegments,
|
||||
stepSegment,
|
||||
symbolChildren,
|
||||
type NavChild,
|
||||
type NavSegment,
|
||||
} from "./navBar";
|
||||
import { dirChildren, iconOf, navSegments, stepSegment, symbolChildren, type NavChild, type NavSegment } from "./navBar";
|
||||
import styles from "./NavBarPopup.module.css";
|
||||
|
||||
export const useNavBarPopup = create<{ open: boolean; seq: number }>(() => ({ open: false, seq: 0 }));
|
||||
@@ -56,12 +48,7 @@ function NavBar({ path, line, col }: { path: string; line: number; col: number }
|
||||
const project = useProject((s) => s.project);
|
||||
const outline = useOutline((s) => s[path]);
|
||||
const initial = useMemo(
|
||||
() =>
|
||||
navSegments(
|
||||
project ? { root: project.root, name: project.name } : null,
|
||||
path,
|
||||
outline ? symbolChain(outline, line, col) : [],
|
||||
),
|
||||
() => navSegments(project ? { root: project.root, name: project.name } : null, path, outline ? symbolChain(outline, line, col) : []),
|
||||
// The bar is a snapshot of where ⌘↑ was pressed.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[],
|
||||
@@ -89,10 +76,7 @@ function NavBar({ path, line, col }: { path: string; line: number; col: number }
|
||||
const choose = (child: NavChild) => {
|
||||
if (!list) return;
|
||||
if (child.kind === "dir") {
|
||||
const segs: NavSegment[] = [
|
||||
...segments.slice(0, list.seg + 1),
|
||||
{ kind: "dir", path: child.path, label: child.label },
|
||||
];
|
||||
const segs: NavSegment[] = [...segments.slice(0, list.seg + 1), { kind: "dir", path: child.path, label: child.label }];
|
||||
setSegments(segs);
|
||||
setActive(segs.length - 1);
|
||||
void openList(segs.length - 1, segs);
|
||||
@@ -117,8 +101,7 @@ function NavBar({ path, line, col }: { path: string; line: number; col: number }
|
||||
if (e.key === "ArrowLeft") move(-1);
|
||||
else if (e.key === "ArrowRight") move(1);
|
||||
else if (e.key === "ArrowDown" && !list) void openList(active);
|
||||
else if (e.key === "ArrowDown" && list)
|
||||
setList({ ...list, active: Math.min(list.items.length - 1, list.active + 1) });
|
||||
else if (e.key === "ArrowDown" && list) setList({ ...list, active: Math.min(list.items.length - 1, list.active + 1) });
|
||||
else if (e.key === "ArrowUp" && list) setList({ ...list, active: Math.max(0, list.active - 1) });
|
||||
else if (e.key === "Enter" && list) {
|
||||
const child = list.items[list.active];
|
||||
@@ -140,23 +123,8 @@ function NavBar({ path, line, col }: { path: string; line: number; col: number }
|
||||
}, [list]);
|
||||
|
||||
return (
|
||||
<Popup
|
||||
open
|
||||
anchor={anchor}
|
||||
placement="bottom-start"
|
||||
offset={0}
|
||||
onClose={close}
|
||||
aria-label="Navigation bar"
|
||||
className={styles.popup}
|
||||
>
|
||||
<div
|
||||
className={styles.root}
|
||||
tabIndex={0}
|
||||
data-autofocus
|
||||
onKeyDown={onKeyDown}
|
||||
role="toolbar"
|
||||
aria-label="Navigation bar"
|
||||
>
|
||||
<Popup open anchor={anchor} placement="bottom-start" offset={0} onClose={close} aria-label="Navigation bar" className={styles.popup}>
|
||||
<div className={styles.root} tabIndex={0} data-autofocus onKeyDown={onKeyDown} role="toolbar" aria-label="Navigation bar">
|
||||
<div className={styles.bar}>
|
||||
{segments.map((s, i) => (
|
||||
<span key={`${i}:${s.path}:${s.label}`} className={styles.segmentWrap}>
|
||||
@@ -179,18 +147,8 @@ function NavBar({ path, line, col }: { path: string; line: number; col: number }
|
||||
))}
|
||||
</div>
|
||||
{list && (
|
||||
<div
|
||||
ref={listRef}
|
||||
className={styles.list}
|
||||
style={{ marginLeft: list.left }}
|
||||
role="listbox"
|
||||
aria-label="Children"
|
||||
>
|
||||
{list.items.length === 0 && (
|
||||
<div className={styles.empty}>
|
||||
<T>Nothing here</T>
|
||||
</div>
|
||||
)}
|
||||
<div ref={listRef} className={styles.list} style={{ marginLeft: list.left }} role="listbox" aria-label="Children">
|
||||
{list.items.length === 0 && <div className={styles.empty}>Nothing here</div>}
|
||||
{list.items.map((c, i) => (
|
||||
<div
|
||||
key={`${c.path}:${c.label}:${i}`}
|
||||
|
||||
@@ -276,3 +276,14 @@
|
||||
color: var(--fg-search-match, inherit);
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
.choiceMessage {
|
||||
padding: 14px 16px 4px;
|
||||
font-size: var(--fs-ui);
|
||||
color: var(--fg);
|
||||
}
|
||||
.choiceDetail {
|
||||
padding: 4px 16px 12px;
|
||||
font-size: var(--fs-ui);
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { LspPopups } from "./Popups";
|
||||
import { openPopup, useLspPopup } from "./popupStore";
|
||||
|
||||
function openUsagesDetected() {
|
||||
const view = vi.fn();
|
||||
const anyway = vi.fn();
|
||||
const cancel = vi.fn();
|
||||
act(() =>
|
||||
openPopup({
|
||||
kind: "choice",
|
||||
title: "Usages Detected",
|
||||
message: "Function 'unused' has 1 usage that is not safe to delete.",
|
||||
choices: [
|
||||
{ label: "View Usages", primary: true, run: view },
|
||||
{ label: "Delete Anyway", run: anyway },
|
||||
{ label: "Cancel", run: cancel },
|
||||
],
|
||||
onDismiss: cancel,
|
||||
}),
|
||||
);
|
||||
return { view, anyway, cancel };
|
||||
}
|
||||
|
||||
const footerLabels = () =>
|
||||
[...screen.getByRole("dialog").querySelectorAll("[data-dialog-footer] button")].map((b) => b.textContent);
|
||||
|
||||
describe("Usages Detected dialog", () => {
|
||||
const os = usePlatform.getState().os;
|
||||
afterEach(() => {
|
||||
usePlatform.setState({ os });
|
||||
act(() => useLspPopup.setState({ popup: null }));
|
||||
});
|
||||
|
||||
it("macOS: Cancel · Delete Anyway · View Usages (default rightmost, focused); Enter views usages", () => {
|
||||
usePlatform.setState({ os: "macos" });
|
||||
render(<LspPopups />);
|
||||
const { view } = openUsagesDetected();
|
||||
expect(footerLabels()).toEqual(["Cancel", "Delete Anyway", "View Usages"]);
|
||||
expect(document.activeElement).toBe(screen.getByRole("button", { name: "View Usages" }));
|
||||
fireEvent.keyDown(screen.getByRole("dialog"), { key: "Enter" });
|
||||
expect(view).toHaveBeenCalledTimes(1);
|
||||
expect(useLspPopup.getState().popup).toBeNull();
|
||||
});
|
||||
|
||||
it("Windows: View Usages · Delete Anyway · Cancel; Escape and the close button cancel", () => {
|
||||
usePlatform.setState({ os: "windows" });
|
||||
render(<LspPopups />);
|
||||
let { cancel } = openUsagesDetected();
|
||||
expect(footerLabels()).toEqual(["View Usages", "Delete Anyway", "Cancel"]);
|
||||
fireEvent.keyDown(document.body, { key: "Escape" });
|
||||
expect(cancel).toHaveBeenCalledTimes(1);
|
||||
({ cancel } = openUsagesDetected());
|
||||
fireEvent.click(screen.getByRole("button", { name: "Close" }));
|
||||
expect(cancel).toHaveBeenCalledTimes(1);
|
||||
expect(screen.queryByRole("dialog")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,19 +1,7 @@
|
||||
/** React popups for LSP editor features, rendered as a workbench overlay. */
|
||||
import { useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
|
||||
import clsx from "clsx";
|
||||
import {
|
||||
Button,
|
||||
Dialog,
|
||||
HighlightedText,
|
||||
Icon,
|
||||
Input,
|
||||
List,
|
||||
Popup,
|
||||
SymbolBadge,
|
||||
fileIconName,
|
||||
fuzzyMatch,
|
||||
T,
|
||||
} from "@/ui";
|
||||
import { Button, Dialog, HighlightedText, Icon, Input, List, Popup, SymbolBadge, fileIconName, fuzzyMatch } from "@/ui";
|
||||
import { basename, relativePath, useProject } from "@/platform/project";
|
||||
import { editorService } from "@/workbench/contributions";
|
||||
import { closePopup, useLspPopup, type ListPopupItem, type LspPopup } from "./popupStore";
|
||||
@@ -36,7 +24,9 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
|
||||
const [query, setQuery] = useState("");
|
||||
const filtered = useMemo(() => {
|
||||
if (!query) return popup.items.map((item) => ({ item, match: null as number[] | null }));
|
||||
return popup.items.map((item) => ({ item, match: fuzzyMatch(item.label, query) })).filter((r) => r.match !== null);
|
||||
return popup.items
|
||||
.map((item) => ({ item, match: fuzzyMatch(item.label, query) }))
|
||||
.filter((r) => r.match !== null);
|
||||
}, [popup.items, query]);
|
||||
const firstEnabled = Math.max(
|
||||
0,
|
||||
@@ -69,9 +59,7 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
|
||||
const width = useMemo(() => {
|
||||
const chars = Math.max(
|
||||
popup.title.length,
|
||||
...popup.items.map(
|
||||
(i) => i.label.length + (i.preview?.length ?? 0) + (i.detail?.length ?? 0) + (i.shortcut?.length ?? 0),
|
||||
),
|
||||
...popup.items.map((i) => i.label.length + (i.preview?.length ?? 0) + (i.detail?.length ?? 0) + (i.shortcut?.length ?? 0)),
|
||||
);
|
||||
return Math.min(720, Math.max(320, chars * 7 + 90));
|
||||
}, [popup]);
|
||||
@@ -97,11 +85,7 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
|
||||
hoverSelects
|
||||
aria-label={popup.title}
|
||||
onActivate={(r) => activate(r.item)}
|
||||
empty={
|
||||
<span className={styles.empty}>
|
||||
<T>Nothing matches</T>
|
||||
</span>
|
||||
}
|
||||
empty={<span className={styles.empty}>Nothing matches</span>}
|
||||
renderItem={({ item, match }) => (
|
||||
<div
|
||||
className={clsx(styles.item, item.disabled && styles.disabled, item.emphasis && styles.emphasis)}
|
||||
@@ -141,14 +125,7 @@ function RenamePopup({ popup }: { popup: Extract<LspPopup, { kind: "rename" }> }
|
||||
return true;
|
||||
};
|
||||
return (
|
||||
<Popup
|
||||
open
|
||||
anchor={popup.anchor}
|
||||
placement="bottom-start"
|
||||
onClose={closePopup}
|
||||
aria-label={popup.title}
|
||||
className={styles.renamePopup}
|
||||
>
|
||||
<Popup open anchor={popup.anchor} placement="bottom-start" onClose={closePopup} aria-label={popup.title} className={styles.renamePopup}>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
@@ -166,8 +143,7 @@ function RenamePopup({ popup }: { popup: Extract<LspPopup, { kind: "rename" }> }
|
||||
value={value}
|
||||
onChange={(e) => setValue(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if ((e.key === "ArrowDown" || e.key === "ArrowUp") && pick(e.key === "ArrowDown" ? 1 : -1))
|
||||
e.preventDefault();
|
||||
if ((e.key === "ArrowDown" || e.key === "ArrowUp") && pick(e.key === "ArrowDown" ? 1 : -1)) e.preventDefault();
|
||||
}}
|
||||
invalid={!value.trim()}
|
||||
aria-label="New name"
|
||||
@@ -238,11 +214,14 @@ function DefinitionPopup({ popup }: { popup: Extract<LspPopup, { kind: "definiti
|
||||
</span>
|
||||
<span className={styles.spacer} />
|
||||
<Button size="small" variant="ghost" onClick={open}>
|
||||
<T>Open</T>
|
||||
Open
|
||||
</Button>
|
||||
</div>
|
||||
<div className={clsx(popup.themeClasses, styles.docScope)}>
|
||||
<DomContent className={styles.defBody} build={() => renderCode(popup.text, popup.language, "cm-lsp-code")} />
|
||||
<DomContent
|
||||
className={styles.defBody}
|
||||
build={() => renderCode(popup.text, popup.language, "cm-lsp-code")}
|
||||
/>
|
||||
</div>
|
||||
</Popup>
|
||||
);
|
||||
@@ -297,28 +276,53 @@ function PreviewDialog({ popup }: { popup: Extract<LspPopup, { kind: "preview" }
|
||||
})}
|
||||
</ul>
|
||||
) : (
|
||||
<ul className={styles.previewList} aria-label="Changes">
|
||||
{summary.entries.map((e) => (
|
||||
<li key={e.path} className={styles.previewRow}>
|
||||
<Icon name={fileIconName(basename(e.path))} size={14} className={styles.itemIcon} />
|
||||
<span className={styles.previewName}>{basename(e.path)}</span>
|
||||
<span className={styles.previewPath}>{relativePath(root, e.path)}</span>
|
||||
<span className={styles.spacer} />
|
||||
{e.operation === "rename" && e.to && <span className={styles.previewOp}>→ {basename(e.to)}</span>}
|
||||
{e.operation && e.operation !== "rename" && <span className={styles.previewOp}>{e.operation}</span>}
|
||||
{e.edits > 0 && (
|
||||
<span className={styles.previewCount}>
|
||||
{e.edits} {e.edits === 1 ? "occurrence" : "occurrences"}
|
||||
</span>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<ul className={styles.previewList} aria-label="Changes">
|
||||
{summary.entries.map((e) => (
|
||||
<li key={e.path} className={styles.previewRow}>
|
||||
<Icon name={fileIconName(basename(e.path))} size={14} className={styles.itemIcon} />
|
||||
<span className={styles.previewName}>{basename(e.path)}</span>
|
||||
<span className={styles.previewPath}>{relativePath(root, e.path)}</span>
|
||||
<span className={styles.spacer} />
|
||||
{e.operation === "rename" && e.to && <span className={styles.previewOp}>→ {basename(e.to)}</span>}
|
||||
{e.operation && e.operation !== "rename" && <span className={styles.previewOp}>{e.operation}</span>}
|
||||
{e.edits > 0 && (
|
||||
<span className={styles.previewCount}>
|
||||
{e.edits} {e.edits === 1 ? "occurrence" : "occurrences"}
|
||||
</span>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function ChoiceDialog({ popup }: { popup: Extract<LspPopup, { kind: "choice" }> }) {
|
||||
// Answer first, then close (unless the answer opened another popup).
|
||||
const answer = (run?: () => void) => {
|
||||
run?.();
|
||||
if (useLspPopup.getState().popup === popup) closePopup();
|
||||
};
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
onClose={() => answer(popup.onDismiss)}
|
||||
title={popup.title}
|
||||
width={460}
|
||||
buttons={popup.choices.map((c) => ({
|
||||
label: c.label,
|
||||
role: c.primary ? "default" : c.label === "Cancel" ? "cancel" : "extra",
|
||||
autoFocus: c.primary,
|
||||
onClick: () => answer(c.run),
|
||||
}))}
|
||||
>
|
||||
<div className={styles.choiceMessage}>{popup.message}</div>
|
||||
{popup.detail && <div className={styles.choiceDetail}>{popup.detail}</div>}
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
/** Overlay host: renders the current LSP popup, if any. */
|
||||
export function LspPopups() {
|
||||
const popup = useLspPopup((s) => s.popup);
|
||||
@@ -335,5 +339,7 @@ export function LspPopups() {
|
||||
return <DefinitionPopup key={seq} popup={popup} />;
|
||||
case "preview":
|
||||
return <PreviewDialog key={seq} popup={popup} />;
|
||||
case "choice":
|
||||
return <ChoiceDialog key={seq} popup={popup} />;
|
||||
}
|
||||
}
|
||||
@@ -61,8 +61,25 @@ export type LspPopup =
|
||||
warnings?: string[];
|
||||
/** Individual occurrences with line previews (single-file syntax-based renames). */
|
||||
occurrences?: PreviewOccurrence[];
|
||||
}
|
||||
| {
|
||||
/** Modal question with several answers, e.g. Safe Delete's "Usages Detected". */
|
||||
kind: "choice";
|
||||
title: string;
|
||||
message: string;
|
||||
detail?: string;
|
||||
choices: PopupChoice[];
|
||||
/** Escape / close button / replaced by another popup. */
|
||||
onDismiss?: () => void;
|
||||
};
|
||||
|
||||
export interface PopupChoice {
|
||||
label: string;
|
||||
/** The default button (Enter). */
|
||||
primary?: boolean;
|
||||
run: () => void;
|
||||
}
|
||||
|
||||
export interface PreviewOccurrence {
|
||||
line: number;
|
||||
/** The line's text and the occurrence within it. */
|
||||
|
||||
@@ -2,7 +2,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { EditorState, Text } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { history, undo } from "@codemirror/commands";
|
||||
import type { MessageRequest } from "@/workbench/messages";
|
||||
import type { LocalSymbol, Location, Locals, OutlineItem, Range, StructuralRanges, SyntaxNode } from "@/bindings";
|
||||
|
||||
// --- backend fakes ---------------------------------------------------------
|
||||
@@ -57,13 +56,9 @@ const showHint = vi.fn();
|
||||
vi.mock("@/editor/lsp/hint", () => ({ showHint }));
|
||||
const executeAction = vi.fn();
|
||||
vi.mock("@/platform/actions", () => ({ executeAction }));
|
||||
let answer = "cancel";
|
||||
const ask = vi.fn(async (_request: MessageRequest) => ({ button: answer, checked: false }));
|
||||
vi.mock("@/workbench/messages", () => ({ ask }));
|
||||
|
||||
const { deletionRange, localDeclaration, outlineItemAt, safeDelete, fileUsages, usagesMessage } =
|
||||
await import("./safeDelete");
|
||||
const { closePopup } = await import("@/editor/lsp/popupStore");
|
||||
const { deletionRange, localDeclaration, outlineItemAt, safeDelete, fileUsages, usagesMessage } = await import("./safeDelete");
|
||||
const { useLspPopup, closePopup } = await import("@/editor/lsp/popupStore");
|
||||
const { lspDoc } = await import("@/editor/lsp/lsp");
|
||||
|
||||
// --- helpers ----------------------------------------------------------------
|
||||
@@ -106,6 +101,8 @@ function item(text: string, name: string, decl: string, kind: OutlineItem["kind"
|
||||
};
|
||||
}
|
||||
|
||||
const flush = () => new Promise((r) => setTimeout(r, 0));
|
||||
|
||||
beforeEach(() => {
|
||||
goto = ok([]);
|
||||
outline = ok([]);
|
||||
@@ -226,23 +223,26 @@ describe("safeDelete in the editor", () => {
|
||||
outline = ok([item(text, "used", "fn used() {}")]);
|
||||
references = ok([usage]);
|
||||
|
||||
const run = async (button: string) => {
|
||||
const run = async (choice: string) => {
|
||||
const v = editor(text, "used() {}");
|
||||
answer = button;
|
||||
ask.mockClear();
|
||||
await safeDelete(v);
|
||||
const request = ask.mock.calls[0]![0];
|
||||
expect(request.title).toBe("Usages Detected");
|
||||
expect(request.body).toBe("1 usage found\nFunction 'used' has 1 usage that is not safe to delete.");
|
||||
expect(request.buttons.map((b) => b.label)).toEqual(["View Usages", "Delete Anyway"]);
|
||||
const done = safeDelete(v);
|
||||
for (let i = 0; i < 20 && useLspPopup.getState().popup?.kind !== "choice"; i++) await flush();
|
||||
const popup = useLspPopup.getState().popup;
|
||||
if (popup?.kind !== "choice") throw new Error("no dialog");
|
||||
expect(popup.title).toBe("Usages Detected");
|
||||
expect(popup.message).toBe("1 usage found");
|
||||
expect(popup.choices.map((c) => c.label)).toEqual(["View Usages", "Delete Anyway", "Cancel"]);
|
||||
popup.choices.find((c) => c.label === choice)!.run();
|
||||
closePopup();
|
||||
await done;
|
||||
return v;
|
||||
};
|
||||
|
||||
expect((await run("cancel")).state.doc.toString()).toBe(text);
|
||||
expect((await run("Cancel")).state.doc.toString()).toBe(text);
|
||||
expect(executeAction).not.toHaveBeenCalled();
|
||||
expect((await run("view")).state.doc.toString()).toBe(text);
|
||||
expect((await run("View Usages")).state.doc.toString()).toBe(text);
|
||||
expect(executeAction).toHaveBeenCalledWith("find.showUsageResults", { symbol: "used", locations: [usage] });
|
||||
expect((await run("delete")).state.doc.toString()).toBe("fn unused() {\n unused();\n}\n\nfn main() {}\n");
|
||||
expect((await run("Delete Anyway")).state.doc.toString()).toBe("fn unused() {\n unused();\n}\n\nfn main() {}\n");
|
||||
});
|
||||
|
||||
it("refuses a declaration in another file instead of doing something else", async () => {
|
||||
|
||||
@@ -20,7 +20,7 @@ import { structure } from "@/editor/structure";
|
||||
import { docOf, isUnavailable, lspRequest } from "@/editor/lsp/lsp";
|
||||
import { comparePos, offsetToPos, rangeContains, rangeToOffsets } from "@/editor/lsp/positions";
|
||||
import { showHint } from "@/editor/lsp/hint";
|
||||
import { ask } from "@/workbench/messages";
|
||||
import { openPopup, useLspPopup } from "@/editor/lsp/popupStore";
|
||||
import { cannotPerform } from "./catalog";
|
||||
import { cancelled, languageName } from "./query";
|
||||
|
||||
@@ -56,9 +56,7 @@ export function deletionRange(
|
||||
const restOk =
|
||||
!rest ||
|
||||
/^[;,]$/.test(rest) ||
|
||||
(!!comments.line &&
|
||||
(rest.startsWith(comments.line) ||
|
||||
(/^[;,]\s*/.test(rest) && rest.replace(/^[;,]\s*/, "").startsWith(comments.line))));
|
||||
(!!comments.line && (rest.startsWith(comments.line) || /^[;,]\s*/.test(rest) && rest.replace(/^[;,]\s*/, "").startsWith(comments.line)));
|
||||
if (!restOk) return null;
|
||||
|
||||
// Attached comments and annotations above (no blank line in between).
|
||||
@@ -90,8 +88,7 @@ export function deletionRange(
|
||||
const next = last.number + 1;
|
||||
if (blank(next) && next < doc.lines) end = doc.line(next).to + 1;
|
||||
else if (blank(next)) end = doc.line(next).to;
|
||||
else if (blank(startLine - 1) && /^[}\])]|^end\b/.test(doc.line(next).text.trim()))
|
||||
start = doc.line(startLine - 1).from;
|
||||
else if (blank(startLine - 1) && /^[}\])]|^end\b/.test(doc.line(next).text.trim())) start = doc.line(startLine - 1).from;
|
||||
} else if (startLine > 1) {
|
||||
// Last line: take the line break before it (and a blank line above).
|
||||
start = doc.line(blank(startLine - 1) && startLine > 2 ? startLine - 2 : startLine - 1).to;
|
||||
@@ -150,17 +147,14 @@ const FUNCTION_STATEMENT = /function|method|^def|^fn|func|procedure/;
|
||||
/** Declaration statement of a syntax-resolved local, or why it can't be deleted on its own. */
|
||||
export function localDeclaration(doc: Text, symbol: LocalSymbol, statement: SyntaxNode | null): Range | string {
|
||||
if (symbol.kind === "parameter") return "Deleting a parameter changes its call sites; use Change Signature";
|
||||
if (symbol.kind === "label" || symbol.kind === "type" || symbol.kind === "macro")
|
||||
return "Caret should be on a variable or function declaration";
|
||||
if (symbol.kind === "label" || symbol.kind === "type" || symbol.kind === "macro") return "Caret should be on a variable or function declaration";
|
||||
if (!symbol.certain) return `'${symbol.name}' is declared more than once in this scope`;
|
||||
if (!statement || !rangeContains(statement.range, symbol.definition.start))
|
||||
return "The declaration could not be determined";
|
||||
if (!statement || !rangeContains(statement.range, symbol.definition.start)) return "The declaration could not be determined";
|
||||
const kind = statement.kind;
|
||||
if (symbol.kind === "function") {
|
||||
return FUNCTION_STATEMENT.test(kind) ? statement.range : "The declaration could not be determined";
|
||||
}
|
||||
if (COMPOUND_STATEMENT.test(kind) || !DECLARATION_STATEMENT.test(kind))
|
||||
return `'${symbol.name}' is not declared by a separate statement`;
|
||||
if (COMPOUND_STATEMENT.test(kind) || !DECLARATION_STATEMENT.test(kind)) return `'${symbol.name}' is not declared by a separate statement`;
|
||||
const { from, to } = rangeToOffsets(doc, statement.range);
|
||||
const defEnd = rangeToOffsets(doc, symbol.definition).to;
|
||||
// Up to the initializer, the statement must declare only this name (no `a, b` / destructuring).
|
||||
@@ -199,13 +193,7 @@ async function resolveTarget(view: EditorView, ctx: EditorDocContext): Promise<R
|
||||
if (lsp)
|
||||
return {
|
||||
status: "ok",
|
||||
target: {
|
||||
name: item.name,
|
||||
kind: kindLabel(item.kind),
|
||||
at: item.selection_range.start,
|
||||
range: item.range,
|
||||
local: null,
|
||||
},
|
||||
target: { name: item.name, kind: kindLabel(item.kind), at: item.selection_range.start, range: item.range, local: null },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -236,20 +224,14 @@ async function resolveTarget(view: EditorView, ctx: EditorDocContext): Promise<R
|
||||
reason: `The language server for ${lang} is not available; only local declarations can be deleted safely without it`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
status: "refused",
|
||||
reason: item ? `'${name}' can't be deleted` : "Caret should be on the name of a declaration",
|
||||
};
|
||||
return { status: "refused", reason: item ? `'${name}' can't be deleted` : "Caret should be on the name of a declaration" };
|
||||
}
|
||||
|
||||
/** LSP references to the target, its own declaration excluded. */
|
||||
async function findUsages(ctx: EditorDocContext, target: SafeDeleteTarget): Promise<Location[]> {
|
||||
const outside = (path: string, range: Range) =>
|
||||
path !== ctx.path ||
|
||||
comparePos(range.start, target.range.start) < 0 ||
|
||||
comparePos(range.start, target.range.end) > 0;
|
||||
if (target.local)
|
||||
return target.local.references.filter((r) => outside(ctx.path, r)).map((range) => ({ path: ctx.path, range }));
|
||||
path !== ctx.path || comparePos(range.start, target.range.start) < 0 || comparePos(range.start, target.range.end) > 0;
|
||||
if (target.local) return target.local.references.filter((r) => outside(ctx.path, r)).map((range) => ({ path: ctx.path, range }));
|
||||
const refs = await lspRequest(() => commands.lspReferences(ctx.doc, target.at, false));
|
||||
return refs.filter((l) => outside(l.path, l.range));
|
||||
}
|
||||
@@ -260,11 +242,7 @@ async function findUsages(ctx: EditorDocContext, target: SafeDeleteTarget): Prom
|
||||
export type UsagesAnswer = "view" | "delete" | "cancel";
|
||||
|
||||
/** `subject`: "Function 'foo'", "File 'a.ts'", "3 files" (`plural`). */
|
||||
export function usagesMessage(
|
||||
subject: string,
|
||||
usages: readonly Location[],
|
||||
plural = false,
|
||||
): { message: string; detail: string } {
|
||||
export function usagesMessage(subject: string, usages: readonly Location[], plural = false): { message: string; detail: string } {
|
||||
const n = usages.length;
|
||||
const files = new Set(usages.map((u) => u.path)).size;
|
||||
const noun = n === 1 ? "usage that is" : "usages that are";
|
||||
@@ -274,23 +252,34 @@ export function usagesMessage(
|
||||
};
|
||||
}
|
||||
|
||||
/** IDEA's "Usages Detected" question; resolves "cancel" when dismissed. */
|
||||
export async function askUsagesDetected(
|
||||
subject: string,
|
||||
usages: readonly Location[],
|
||||
plural = false,
|
||||
): Promise<UsagesAnswer> {
|
||||
const { message, detail } = usagesMessage(subject, usages, plural);
|
||||
const { button } = await ask({
|
||||
title: "Usages Detected",
|
||||
icon: "warning",
|
||||
body: `${message}\n${detail}`,
|
||||
buttons: [
|
||||
{ id: "view", label: "View Usages", primary: true },
|
||||
{ id: "delete", label: "Delete Anyway" },
|
||||
],
|
||||
/** IDEA's "Usages Detected" question; resolves "cancel" when dismissed or replaced. */
|
||||
export function askUsagesDetected(subject: string, usages: readonly Location[], plural = false): Promise<UsagesAnswer> {
|
||||
return new Promise((resolve) => {
|
||||
let done = false;
|
||||
const finish = (a: UsagesAnswer) => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
unsub();
|
||||
resolve(a);
|
||||
};
|
||||
const { message, detail } = usagesMessage(subject, usages, plural);
|
||||
openPopup({
|
||||
kind: "choice",
|
||||
title: "Usages Detected",
|
||||
message,
|
||||
detail,
|
||||
choices: [
|
||||
{ label: "View Usages", primary: true, run: () => finish("view") },
|
||||
{ label: "Delete Anyway", run: () => finish("delete") },
|
||||
{ label: "Cancel", run: () => finish("cancel") },
|
||||
],
|
||||
onDismiss: () => finish("cancel"),
|
||||
});
|
||||
const mine = useLspPopup.getState().popup;
|
||||
const unsub = useLspPopup.subscribe((s) => {
|
||||
if (s.popup !== mine) finish("cancel");
|
||||
});
|
||||
});
|
||||
return button === "view" || button === "delete" ? button : "cancel";
|
||||
}
|
||||
|
||||
/** Opens the Find Usages tool window with `usages` (code-insight's `find.showUsageResults`). */
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
type StructuralLanguage,
|
||||
} from "@/platform/ipc";
|
||||
import { basename } from "@/platform/project";
|
||||
import { Checkbox, Dialog, Input, Select, Spinner, T } from "@/ui";
|
||||
import { Checkbox, Dialog, Input, Select, Spinner } from "@/ui";
|
||||
import { ScopeFields, openDialog } from "./dialogs";
|
||||
import { locateDuplicates, loadDuplicateOptions } from "./duplicates";
|
||||
import { runInspection } from "./inspect";
|
||||
@@ -45,9 +45,7 @@ function InspectCodeDialog({ onClose }: { onClose: () => void }) {
|
||||
>
|
||||
<div className={styles.form}>
|
||||
<ScopeFields name="inspect-scope" value={scope} onChange={setScope} />
|
||||
<div className={styles.hint}>
|
||||
<T>Files are checked by their language servers; files without one are skipped.</T>
|
||||
</div>
|
||||
<div className={styles.hint}>Files are checked by their language servers; files without one are skipped.</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
@@ -78,9 +76,7 @@ function DuplicatesDialog({ onClose }: { onClose: () => void }) {
|
||||
<div className={styles.form}>
|
||||
<ScopeFields name="duplicates-scope" value={scope} onChange={setScope} />
|
||||
<label className={styles.fieldRow}>
|
||||
<span>
|
||||
<T>Minimum size</T>
|
||||
</span>
|
||||
<span>Minimum size</span>
|
||||
<Input
|
||||
className={styles.number}
|
||||
type="number"
|
||||
@@ -189,9 +185,7 @@ function StructuralDialog({ replace, onClose }: { replace: boolean; onClose: ()
|
||||
>
|
||||
<div className={styles.form}>
|
||||
<div className={styles.fieldRow}>
|
||||
<span>
|
||||
<T>Language</T>
|
||||
</span>
|
||||
<span>Language</span>
|
||||
<Select
|
||||
value={language || null}
|
||||
options={options}
|
||||
@@ -202,7 +196,7 @@ function StructuralDialog({ replace, onClose }: { replace: boolean; onClose: ()
|
||||
/>
|
||||
</div>
|
||||
<label className={styles.fieldLabel} htmlFor="ssr-template">
|
||||
<T>Search template</T>
|
||||
Search template
|
||||
</label>
|
||||
<textarea
|
||||
id="ssr-template"
|
||||
@@ -217,7 +211,7 @@ function StructuralDialog({ replace, onClose }: { replace: boolean; onClose: ()
|
||||
{replace && (
|
||||
<>
|
||||
<label className={styles.fieldLabel} htmlFor="ssr-replacement">
|
||||
<T>Replace template</T>
|
||||
Replace template
|
||||
</label>
|
||||
<textarea
|
||||
id="ssr-replacement"
|
||||
@@ -230,8 +224,8 @@ function StructuralDialog({ replace, onClose }: { replace: boolean; onClose: ()
|
||||
</>
|
||||
)}
|
||||
<div className={styles.hint}>
|
||||
<T>Placeholders:</T> <code>$name$</code> or <code>$NAME</code> <T>match one node,</T> <code>$$$NAME</code>{" "}
|
||||
<T>any number of nodes (arguments, statements). A placeholder used twice must match equal code.</T>
|
||||
Placeholders: <code>$name$</code> or <code>$NAME</code> match one node, <code>$$$NAME</code> any number of
|
||||
nodes (arguments, statements). A placeholder used twice must match equal code.
|
||||
</div>
|
||||
<ScopeFields name="ssr-scope" value={scope} onChange={setScope} />
|
||||
</div>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { Fragment, type ReactNode } from "react";
|
||||
import { create } from "zustand";
|
||||
import { isTauri } from "@/platform/ipc";
|
||||
import { Button, Input, T } from "@/ui";
|
||||
import { Button, Input } from "@/ui";
|
||||
import { SCOPE_LABELS, currentFile, type ScopeChoice, type ScopeKind } from "./scope";
|
||||
import styles from "./Analysis.module.css";
|
||||
|
||||
@@ -57,9 +57,7 @@ export function ScopeFields({
|
||||
const file = currentFile();
|
||||
return (
|
||||
<fieldset className={styles.scope}>
|
||||
<legend className={styles.fieldLabel}>
|
||||
<T>Scope</T>
|
||||
</legend>
|
||||
<legend className={styles.fieldLabel}>Scope</legend>
|
||||
{KINDS.map((kind) => (
|
||||
<label key={kind} className={styles.radioRow}>
|
||||
<input
|
||||
@@ -83,7 +81,7 @@ export function ScopeFields({
|
||||
<Button
|
||||
onClick={() => void browseDirectory(value.directory).then((d) => d && onChange({ ...value, directory: d }))}
|
||||
>
|
||||
<T>Browse…</T>
|
||||
Browse…
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -9,7 +9,7 @@ import { create } from "zustand";
|
||||
import type { InvalidateCachesOptions } from "@/bindings";
|
||||
import { registerActions } from "@/platform/actions";
|
||||
import { call, commands, isTauri } from "@/platform/ipc";
|
||||
import { Checkbox, Dialog, T } from "@/ui";
|
||||
import { Checkbox, Dialog } from "@/ui";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import styles from "./app.module.css";
|
||||
|
||||
@@ -30,11 +30,7 @@ export const DEFAULT_INVALIDATE_OPTIONS: Required<InvalidateCachesOptions> = {
|
||||
/** Schedules the invalidation (or none, for Just Restart) and restarts. */
|
||||
export async function invalidateAndRestart(options: InvalidateCachesOptions | null): Promise<void> {
|
||||
if (!isTauri()) {
|
||||
notifications().notify({
|
||||
level: "info",
|
||||
title: "Restart is only available in the desktop app",
|
||||
key: "app.invalidateCaches",
|
||||
});
|
||||
notifications().notify({ level: "info", title: "Restart is only available in the desktop app", key: "app.invalidateCaches" });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
@@ -82,15 +78,10 @@ export function InvalidateCachesDialog({ onClose = close }: { onClose?: () => vo
|
||||
>
|
||||
<div className={styles.invalidateBody}>
|
||||
<p className={styles.invalidateText}>
|
||||
<T>
|
||||
{
|
||||
"The caches will be invalidated and rebuilt on the next startup: the symbol index of every project and the syntax caches."
|
||||
}
|
||||
</T>
|
||||
The caches will be invalidated and rebuilt on the next startup: the symbol index of every project and the
|
||||
syntax caches.
|
||||
</p>
|
||||
<div className={styles.invalidateHeading}>
|
||||
<T>Optional:</T>
|
||||
</div>
|
||||
<div className={styles.invalidateHeading}>Optional:</div>
|
||||
<Checkbox
|
||||
label="Clear file system cache and Local History"
|
||||
checked={options.localHistory}
|
||||
@@ -108,7 +99,7 @@ export function InvalidateCachesDialog({ onClose = close }: { onClose?: () => vo
|
||||
/>
|
||||
{options.localHistory && (
|
||||
<p className={styles.invalidateWarning} role="note">
|
||||
<T>Local History of all projects will be deleted.</T>
|
||||
Local History of all projects will be deleted.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { confirmExitEnabled, decideClose, type CloseDeps, type CloseInput } from "../closeGuard";
|
||||
import type { MessageRequest as PromptRequest, MessageResult as PromptResult } from "@/workbench/messages";
|
||||
import type { PromptRequest, PromptResult } from "../prompt";
|
||||
|
||||
function deps(answers: PromptResult[]) {
|
||||
const asked: PromptRequest[] = [];
|
||||
@@ -28,7 +28,7 @@ describe("decideClose", () => {
|
||||
it("confirms exit for the last window when enabled", async () => {
|
||||
const { d, asked } = deps([{ button: "exit", checked: false }]);
|
||||
await expect(decideClose({ ...base, confirmExit: true }, d)).resolves.toBe(true);
|
||||
expect(asked[0]?.title).toBe("Confirm Exit");
|
||||
expect(asked[0]?.title).toBe("Exit OpenIDEA?");
|
||||
expect(d.disableConfirmExit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { Action } from "@/platform/actions";
|
||||
import { keymapReference, KeymapReferenceOverlay, showKeymapReference } from "../KeymapReference";
|
||||
import { windowTitle } from "../title";
|
||||
import { aboutRows } from "../AboutDialog";
|
||||
import { ask, MessagesHost as PromptOverlay } from "@/workbench/messages";
|
||||
import { ask, PromptOverlay } from "../prompt";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
|
||||
describe("window title", () => {
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
.promptBody {
|
||||
margin: 0;
|
||||
padding: 14px 16px;
|
||||
color: var(--fg);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
/* About (JetBrains-style: logo left, product facts as plain lines) */
|
||||
.about {
|
||||
display: flex;
|
||||
|
||||
@@ -11,7 +11,7 @@ import { commands, isTauri, onIdeEvent, type Settings } from "@/platform/ipc";
|
||||
import { t } from "@/platform/i18n";
|
||||
import { provideLeaveProjectGuard, useProject } from "@/platform/project";
|
||||
import { maybeEditorService, notifications } from "@/workbench/contributions";
|
||||
import { ask, type Ask } from "@/workbench/messages";
|
||||
import { ask, type Ask } from "./prompt";
|
||||
|
||||
/** Document ids the backend reports dirty in this window. */
|
||||
const dirtyDocs = new Set<number>();
|
||||
@@ -59,7 +59,6 @@ export async function decideClose(input: CloseInput, deps: CloseDeps): Promise<b
|
||||
{ id: "discard", label: t("app.unsaved.discard") },
|
||||
{ id: "save", label: t("app.unsaved.save"), primary: true },
|
||||
],
|
||||
icon: "warning",
|
||||
});
|
||||
if (r.button === "cancel") return false;
|
||||
if (r.button === "save") {
|
||||
|
||||
@@ -11,18 +11,17 @@ import { buildInfo } from "./host";
|
||||
import { KeymapReferenceOverlay } from "./KeymapReference";
|
||||
import { installLocaleSync, registerLocalizedActions } from "./locale";
|
||||
import { installMenuBridge } from "./menuBridge";
|
||||
import { PromptOverlay } from "./prompt";
|
||||
import { installWindowTitle } from "./title";
|
||||
import { installLaunchHandling, windowActions } from "./windows";
|
||||
|
||||
/** The UI locale of a secondary (Settings) window. */
|
||||
export const activateLocale = installLocaleSync;
|
||||
|
||||
export function activate(): () => void {
|
||||
const disposers = [
|
||||
installLocaleSync(),
|
||||
registerLocalizedActions(() => [...appActions(), ...windowActions()]),
|
||||
registerOverlay({ id: "app.about", component: AboutOverlay }),
|
||||
registerOverlay({ id: "app.keymapReference", component: KeymapReferenceOverlay }),
|
||||
registerOverlay({ id: "app.prompt", component: PromptOverlay }),
|
||||
registerOverlay({ id: "app.invalidateCaches", component: InvalidateCachesOverlay }),
|
||||
registerInvalidateCachesActions(),
|
||||
installMenuBridge(),
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
/** Promise-based modal prompts (exit confirmation, unsaved changes). */
|
||||
import { useState } from "react";
|
||||
import { create } from "zustand";
|
||||
import { useT } from "@/platform/i18n";
|
||||
import { Checkbox, Dialog } from "@/ui";
|
||||
import styles from "./app.module.css";
|
||||
|
||||
export interface PromptButton {
|
||||
id: string;
|
||||
label: string;
|
||||
primary?: boolean;
|
||||
}
|
||||
|
||||
export interface PromptRequest {
|
||||
title: string;
|
||||
body: string;
|
||||
/** Declaration order (IDEA `createActions`); the dialog orders them per platform. A Cancel button (id `cancel`) is added unless present. */
|
||||
buttons: PromptButton[];
|
||||
checkbox?: string;
|
||||
}
|
||||
|
||||
export interface PromptResult {
|
||||
button: string;
|
||||
checked: boolean;
|
||||
}
|
||||
|
||||
export type Ask = (request: PromptRequest) => Promise<PromptResult>;
|
||||
|
||||
interface PromptState {
|
||||
current: (PromptRequest & { resolve: (r: PromptResult) => void }) | null;
|
||||
}
|
||||
|
||||
export const usePrompt = create<PromptState>(() => ({ current: null }));
|
||||
|
||||
/** Shows a prompt; a prompt already open is cancelled first. */
|
||||
export const ask: Ask = (request) => {
|
||||
usePrompt.getState().current?.resolve({ button: "cancel", checked: false });
|
||||
return new Promise((resolve) => {
|
||||
usePrompt.setState({
|
||||
current: {
|
||||
...request,
|
||||
resolve: (r) => {
|
||||
usePrompt.setState({ current: null });
|
||||
resolve(r);
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
export function PromptOverlay() {
|
||||
const current = usePrompt((s) => s.current);
|
||||
if (!current) return null;
|
||||
// Keyed so the checkbox state resets per prompt.
|
||||
return <PromptDialog key={current.title + current.body} request={current} />;
|
||||
}
|
||||
|
||||
function PromptDialog({ request }: { request: NonNullable<PromptState["current"]> }) {
|
||||
const t = useT();
|
||||
const [checked, setChecked] = useState(false);
|
||||
const done = (button: string) => request.resolve({ button, checked });
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
onClose={() => done("cancel")}
|
||||
title={request.title}
|
||||
width={420}
|
||||
footerStart={
|
||||
request.checkbox && <Checkbox checked={checked} onChange={setChecked} label={request.checkbox} />
|
||||
}
|
||||
buttons={[
|
||||
...request.buttons.map((b) => ({
|
||||
label: b.label,
|
||||
role: b.primary ? ("default" as const) : b.id === "cancel" ? ("cancel" as const) : ("extra" as const),
|
||||
onClick: () => done(b.id),
|
||||
})),
|
||||
...(request.buttons.some((b) => b.id === "cancel") ? [] : [{ label: t("common.cancel"), role: "cancel" as const }]),
|
||||
]}
|
||||
>
|
||||
<p className={styles.promptBody}>{request.body}</p>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import { call, commands, isTauri } from "@/platform/ipc";
|
||||
import { basename, confirmLeaveProject, openProject, provideStartupLaunch, useProject } from "@/platform/project";
|
||||
import { holdSplash } from "@/platform/splash";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { ask } from "@/workbench/messages";
|
||||
import { ask } from "./prompt";
|
||||
|
||||
export const LAUNCH_EVENT = "openidea://launch";
|
||||
|
||||
@@ -76,8 +76,8 @@ export async function openProjectWithPolicy(path: string): Promise<void> {
|
||||
title: t("app.window.askTitle"),
|
||||
body: t("app.window.askBody", { name: basename(path) }),
|
||||
buttons: [
|
||||
{ id: "new", label: t("app.window.askNew") },
|
||||
{ id: "same", label: t("app.window.askThis"), primary: true },
|
||||
{ id: "same", label: t("app.window.askThis") },
|
||||
{ id: "new", label: t("app.window.askNew"), primary: true },
|
||||
{ id: "cancel", label: t("common.cancel") },
|
||||
],
|
||||
checkbox: t("app.window.askRemember"),
|
||||
@@ -86,9 +86,7 @@ export async function openProjectWithPolicy(path: string): Promise<void> {
|
||||
mode = r.button;
|
||||
if (r.checked) {
|
||||
try {
|
||||
useProject.setState({
|
||||
settings: await call(commands.settingsSet("global", "general.openProjectIn", JSON.stringify(mode))),
|
||||
});
|
||||
useProject.setState({ settings: await call(commands.settingsSet("global", "general.openProjectIn", JSON.stringify(mode))) });
|
||||
} catch {
|
||||
/* the choice still applies to this open */
|
||||
}
|
||||
|
||||
@@ -4,19 +4,7 @@ import clsx from "clsx";
|
||||
import type { BuildTool, GradleModel, MavenModel, RunConfig } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { editorService } from "@/workbench/contributions";
|
||||
import {
|
||||
Button,
|
||||
Checkbox,
|
||||
EmptyState,
|
||||
Icon,
|
||||
IconButton,
|
||||
Spinner,
|
||||
Tree,
|
||||
showContextMenu,
|
||||
type MenuItem,
|
||||
type TreeRowState,
|
||||
T,
|
||||
} from "@/ui";
|
||||
import { Button, Checkbox, EmptyState, Icon, IconButton, Spinner, Tree, showContextMenu, type MenuItem, type TreeRowState } from "@/ui";
|
||||
import {
|
||||
gradleChildren,
|
||||
gradleRoots,
|
||||
@@ -31,16 +19,7 @@ import {
|
||||
withGradleOptions,
|
||||
type BuildNode,
|
||||
} from "./model";
|
||||
import {
|
||||
createRunConfig,
|
||||
initialExpanded,
|
||||
runConfig,
|
||||
setCurrentProject,
|
||||
setExpanded,
|
||||
setProfile,
|
||||
syncTool,
|
||||
useBuild,
|
||||
} from "./store";
|
||||
import { createRunConfig, initialExpanded, runConfig, setCurrentProject, setExpanded, setProfile, syncTool, useBuild } from "./store";
|
||||
import styles from "./BuildTools.module.css";
|
||||
|
||||
export function MavenView() {
|
||||
@@ -52,15 +31,11 @@ export function GradleView() {
|
||||
}
|
||||
|
||||
/** The run configuration a runnable node (or several of one project) starts. */
|
||||
export function nodeConfig(
|
||||
nodes: readonly BuildNode[],
|
||||
model: { maven?: MavenModel | null; gradle?: GradleModel | null },
|
||||
) {
|
||||
export function nodeConfig(nodes: readonly BuildNode[], model: { maven?: MavenModel | null; gradle?: GradleModel | null }) {
|
||||
const settings = useBuild.getState().settings;
|
||||
const first = nodes[0];
|
||||
if (!first) return null;
|
||||
if (first.kind === "runConfig")
|
||||
return first.config.kind === "gradle" ? withGradleOptions(first.config, settings.gradle) : first.config;
|
||||
if (first.kind === "runConfig") return first.config.kind === "gradle" ? withGradleOptions(first.config, settings.gradle) : first.config;
|
||||
if ((first.kind === "phase" || first.kind === "goal") && model.maven) {
|
||||
const same = nodes.filter(
|
||||
(n): n is Extract<BuildNode, { kind: "phase" | "goal" }> =>
|
||||
@@ -70,37 +45,19 @@ export function nodeConfig(
|
||||
return mavenGoalConfig(first.project, goals, model.maven, settings.maven);
|
||||
}
|
||||
if (first.kind === "task" && model.gradle) {
|
||||
const same = nodes.filter(
|
||||
(n): n is Extract<BuildNode, { kind: "task" }> => n.kind === "task" && n.project.path === first.project.path,
|
||||
);
|
||||
return gradleTaskConfig(
|
||||
model.gradle,
|
||||
first.project,
|
||||
same.map((n) => n.task.name),
|
||||
settings.gradle,
|
||||
);
|
||||
const same = nodes.filter((n): n is Extract<BuildNode, { kind: "task" }> => n.kind === "task" && n.project.path === first.project.path);
|
||||
return gradleTaskConfig(model.gradle, first.project, same.map((n) => n.task.name), settings.gradle);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Memoised children lookup (node objects stay stable while the model is unchanged). */
|
||||
function childrenOf(
|
||||
tool: BuildTool,
|
||||
maven: MavenModel | null,
|
||||
gradle: GradleModel | null,
|
||||
configs: readonly RunConfig[],
|
||||
) {
|
||||
function childrenOf(tool: BuildTool, maven: MavenModel | null, gradle: GradleModel | null, configs: readonly RunConfig[]) {
|
||||
const cache = new Map<string, BuildNode[] | undefined>();
|
||||
return (n: BuildNode) => {
|
||||
if (cache.has(n.key)) return cache.get(n.key);
|
||||
const kids =
|
||||
tool === "maven"
|
||||
? maven
|
||||
? mavenChildren(n, maven, configs)
|
||||
: undefined
|
||||
: gradle
|
||||
? gradleChildren(n, gradle, configs)
|
||||
: undefined;
|
||||
tool === "maven" ? (maven ? mavenChildren(n, maven, configs) : undefined) : gradle ? gradleChildren(n, gradle, configs) : undefined;
|
||||
cache.set(n.key, kids);
|
||||
return kids;
|
||||
};
|
||||
@@ -138,12 +95,7 @@ function Toolbar({ tool, selection }: { tool: BuildTool; selection: BuildNode[]
|
||||
disabled={!runnable.length}
|
||||
onClick={runSelected}
|
||||
/>
|
||||
<IconButton
|
||||
icon="run-anything"
|
||||
size="small"
|
||||
iconSize={16}
|
||||
action={maven ? "maven.executeGoal" : "gradle.executeTask"}
|
||||
/>
|
||||
<IconButton icon="run-anything" size="small" iconSize={16} action={maven ? "maven.executeGoal" : "gradle.executeTask"} />
|
||||
<IconButton
|
||||
icon="build-offline"
|
||||
size="small"
|
||||
@@ -152,13 +104,7 @@ function Toolbar({ tool, selection }: { tool: BuildTool; selection: BuildNode[]
|
||||
pressed={maven ? settings.maven.offline : settings.gradle.offline}
|
||||
/>
|
||||
{maven && (
|
||||
<IconButton
|
||||
icon="skip-tests"
|
||||
size="small"
|
||||
iconSize={16}
|
||||
action="maven.toggleSkipTests"
|
||||
pressed={settings.maven.skipTests}
|
||||
/>
|
||||
<IconButton icon="skip-tests" size="small" iconSize={16} action="maven.toggleSkipTests" pressed={settings.maven.skipTests} />
|
||||
)}
|
||||
<span className={styles.sep} />
|
||||
<IconButton icon="expand-all" size="small" iconSize={16} action={`${tool}.expandAll`} />
|
||||
@@ -183,9 +129,7 @@ function Banner({ tool }: { tool: BuildTool }) {
|
||||
return (
|
||||
<div className={styles.banner}>
|
||||
<Icon name={tool === "maven" ? "maven-load-changes" : "gradle-load-changes"} size={16} />
|
||||
<span className={styles.bannerText}>
|
||||
<T>Build files changed since the last reload</T>
|
||||
</span>
|
||||
<span className={styles.bannerText}>Build files changed since the last reload</span>
|
||||
<Button size="small" variant="ghost" onClick={() => void syncTool(tool)}>
|
||||
{tool === "maven" ? "Load Maven Changes" : "Load Gradle Changes"}
|
||||
</Button>
|
||||
@@ -251,8 +195,7 @@ function BuildToolView({ tool }: { tool: BuildTool }) {
|
||||
|
||||
const hasModel = tool === "maven" ? !!maven : !!gradle;
|
||||
useEffect(() => {
|
||||
if (model && hasModel && useBuild.getState().expanded[tool].size === 0)
|
||||
setExpanded(tool, initialExpanded(tool, model));
|
||||
if (model && hasModel && useBuild.getState().expanded[tool].size === 0) setExpanded(tool, initialExpanded(tool, model));
|
||||
}, [model, hasModel, tool]);
|
||||
|
||||
const nodesByKey = useCallback(
|
||||
@@ -287,33 +230,20 @@ function BuildToolView({ tool }: { tool: BuildTool }) {
|
||||
{ label: `Debug '${config.name}'`, icon: "debug", run: () => runConfig(config, "debug") },
|
||||
{ kind: "separator" },
|
||||
);
|
||||
if (node.kind === "runConfig")
|
||||
items.push({ kind: "action", action: "run.editConfigs", arg: node.config.id, label: "Edit Configuration…" });
|
||||
if (node.kind === "runConfig") items.push({ kind: "action", action: "run.editConfigs", arg: node.config.id, label: "Edit Configuration…" });
|
||||
else items.push({ label: "Create Run Configuration…", icon: "edit", run: () => void createRunConfig(config) });
|
||||
}
|
||||
if (node.kind === "mavenProject") {
|
||||
items.push(
|
||||
{
|
||||
label: "Open pom.xml",
|
||||
icon: "file-maven",
|
||||
run: () => void editorService().openFile(`${root}/${node.project.pom}`),
|
||||
},
|
||||
{ label: "Open pom.xml", icon: "file-maven", run: () => void editorService().openFile(`${root}/${node.project.pom}`) },
|
||||
{ kind: "action", action: "maven.reload", label: "Reload All Maven Projects" },
|
||||
{ kind: "action", action: "maven.executeGoal" },
|
||||
);
|
||||
}
|
||||
if (node.kind === "gradleProject") {
|
||||
const file = node.project.buildFile;
|
||||
if (file)
|
||||
items.push({
|
||||
label: `Open ${file.split("/").pop()}`,
|
||||
icon: "file-gradle",
|
||||
run: () => void editorService().openFile(`${root}/${file}`),
|
||||
});
|
||||
items.push(
|
||||
{ kind: "action", action: "gradle.reload", label: "Reload All Gradle Projects" },
|
||||
{ kind: "action", action: "gradle.executeTask" },
|
||||
);
|
||||
if (file) items.push({ label: `Open ${file.split("/").pop()}`, icon: "file-gradle", run: () => void editorService().openFile(`${root}/${file}`) });
|
||||
items.push({ kind: "action", action: "gradle.reload", label: "Reload All Gradle Projects" }, { kind: "action", action: "gradle.executeTask" });
|
||||
}
|
||||
if (node.kind === "dependency") {
|
||||
const d = node.dependency;
|
||||
@@ -327,13 +257,7 @@ function BuildToolView({ tool }: { tool: BuildTool }) {
|
||||
return (
|
||||
<div className={styles.view}>
|
||||
<div className={styles.loading}>
|
||||
{error ? (
|
||||
error
|
||||
) : loading ? (
|
||||
<>
|
||||
<Spinner size={14} /> <T>Loading…</T>
|
||||
</>
|
||||
) : null}
|
||||
{error ? error : loading ? <><Spinner size={14} /> Loading…</> : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
import { useMemo, useState, type KeyboardEvent } from "react";
|
||||
import clsx from "clsx";
|
||||
import type { BuildTool } from "@/platform/ipc";
|
||||
import { HighlightedText, Input, List, Popup, Select, listNavigate, T } from "@/ui";
|
||||
import { HighlightedText, Input, List, Popup, Select, listNavigate } from "@/ui";
|
||||
import {
|
||||
goalCompletions,
|
||||
gradleTaskConfig,
|
||||
@@ -115,9 +115,7 @@ function ExecutePopup({ tool }: { tool: BuildTool }) {
|
||||
<div className={styles.popupBody}>
|
||||
<div className={styles.popupHeader}>
|
||||
<span className={styles.popupTitle}>{title}</span>
|
||||
<span>
|
||||
<T>Tab to complete, Enter to run</T>
|
||||
</span>
|
||||
<span>Tab to complete, Enter to run</span>
|
||||
</div>
|
||||
<div className={styles.inputRow}>
|
||||
<span className={styles.inputPrefix}>{tool === "maven" ? "mvn" : "gradle"}</span>
|
||||
@@ -150,19 +148,14 @@ function ExecutePopup({ tool }: { tool: BuildTool }) {
|
||||
renderItem={(c, state) => (
|
||||
<div className={clsx(styles.completion, state.active && styles.activeRow)}>
|
||||
<span className={styles.completionLabel}>
|
||||
<HighlightedText
|
||||
text={c.label}
|
||||
indices={c.detail === "recent" ? undefined : [...Array(Math.min(word.length, c.label.length)).keys()]}
|
||||
/>
|
||||
<HighlightedText text={c.label} indices={c.detail === "recent" ? undefined : [...Array(Math.min(word.length, c.label.length)).keys()]} />
|
||||
</span>
|
||||
{c.detail && <span className={styles.completionDetail}>{c.detail}</span>}
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
<div className={styles.popupFooter}>
|
||||
<span>
|
||||
<T>Project:</T>
|
||||
</span>
|
||||
<span>Project:</span>
|
||||
<Select
|
||||
className={styles.footerSelect}
|
||||
value={project}
|
||||
|
||||
@@ -27,7 +27,6 @@ const mavenModel: BuildModel = {
|
||||
profiles: ["ci"],
|
||||
javaVersion: 21,
|
||||
command: "/p/mvnw",
|
||||
options: [],
|
||||
env: {},
|
||||
},
|
||||
],
|
||||
|
||||
@@ -95,10 +95,6 @@ export function activate(): () => void {
|
||||
if ([...e.created, ...e.modified, ...e.removed].some((p) => BUILD_FILE.test(p))) scheduleLoad();
|
||||
}),
|
||||
onIdeEvent("projectRootsChanged", scheduleLoad),
|
||||
// Project JDK / Maven home and options are applied to the model's launchers.
|
||||
onIdeEvent("settingsChanged", (e) => {
|
||||
if (e.key === "languages" || e.key.startsWith("languages.java")) scheduleLoad();
|
||||
}),
|
||||
registerActions([
|
||||
{
|
||||
id: "maven.reload",
|
||||
|
||||
@@ -37,7 +37,6 @@ function project(over: Partial<MavenProject>): MavenProject {
|
||||
profiles: [],
|
||||
javaVersion: 21,
|
||||
command: "/p/mvnw",
|
||||
options: [],
|
||||
env: { JAVA_HOME: "/jdk21" },
|
||||
...over,
|
||||
};
|
||||
@@ -185,11 +184,6 @@ describe("Maven runs", () => {
|
||||
const root = mavenGoalConfig(maven.projects[0]!, ["clean"], maven, { offline: false, skipTests: false, profiles: {} });
|
||||
expect(root.cwd).toBeNull();
|
||||
expect(root.isTest).toBe(false);
|
||||
// Settings › Maven options go before the goals.
|
||||
const configured = { ...core, options: ["-s", "/m2/settings.xml"] };
|
||||
expect(mavenGoalConfig(configured, ["test"], maven, { offline: false, skipTests: true, profiles: {} }).args).toEqual(
|
||||
["-s", "/m2/settings.xml", "test", "-DskipTests"],
|
||||
);
|
||||
});
|
||||
|
||||
it("parses typed command lines", () => {
|
||||
|
||||
@@ -401,7 +401,7 @@ export function mavenGoalConfig(
|
||||
model: Pick<MavenModel, "profiles">,
|
||||
options: MavenRunOptions,
|
||||
): RunConfig {
|
||||
const args = [...project.options, ...mavenArgs(goals, model, options)];
|
||||
const args = mavenArgs(goals, model, options);
|
||||
return {
|
||||
id: `maven:goal:${project.pom}:${goals.join(" ")}`,
|
||||
name: mavenConfigName(project, goals),
|
||||
|
||||
@@ -19,7 +19,6 @@ import {
|
||||
Tree,
|
||||
fileIconName,
|
||||
type TreeRowState,
|
||||
T,
|
||||
} from "@/ui";
|
||||
import type { BuildMessage, Severity } from "@/platform/ipc";
|
||||
import {
|
||||
@@ -63,9 +62,7 @@ function rootDetail(status: BuildStatus, durationMs: number | null, errors: numb
|
||||
if (status === "running") return "running…";
|
||||
if (status === "cancelled") return "cancelled";
|
||||
const summary = finishSummary({ success: status === "success", errors, warnings, durationMs });
|
||||
return status === "success"
|
||||
? `finished ${formatDuration(durationMs ?? 0)}`
|
||||
: summary.replace(/^Build failed:?\s*/, "") || "failed";
|
||||
return status === "success" ? `finished ${formatDuration(durationMs ?? 0)}` : summary.replace(/^Build failed:?\s*/, "") || "failed";
|
||||
}
|
||||
|
||||
export function BuildHeaderActions() {
|
||||
@@ -110,18 +107,13 @@ function BuildTree() {
|
||||
if (n.kind === "file") {
|
||||
const errors = n.messages.filter((m) => m.severity === "error").length;
|
||||
const warnings = n.messages.filter((m) => m.severity === "warning").length;
|
||||
const counts = [
|
||||
errors && `${errors} error${errors === 1 ? "" : "s"}`,
|
||||
warnings && `${warnings} warning${warnings === 1 ? "" : "s"}`,
|
||||
]
|
||||
const counts = [errors && `${errors} error${errors === 1 ? "" : "s"}`, warnings && `${warnings} warning${warnings === 1 ? "" : "s"}`]
|
||||
.filter(Boolean)
|
||||
.join(", ");
|
||||
return (
|
||||
<span className={styles.row}>
|
||||
<Icon name={fileIconName(basename(n.path))} size={16} className={styles.fileIcon} />
|
||||
<span className={clsx(styles.strong, errors > 0 && styles.fileError, state.selected && styles.selected)}>
|
||||
{basename(n.path)}
|
||||
</span>
|
||||
<span className={clsx(styles.strong, errors > 0 && styles.fileError, state.selected && styles.selected)}>{basename(n.path)}</span>
|
||||
<span className={styles.muted}>{relativeDir(root, n.path)}</span>
|
||||
<span className={styles.muted}>{counts}</span>
|
||||
</span>
|
||||
@@ -133,11 +125,7 @@ function BuildTree() {
|
||||
<span className={styles.row} title={m.text}>
|
||||
<Icon name={SEVERITY_ICON[m.severity]} size={14} className={styles[`sev-${m.severity}`]} />
|
||||
<span className={styles.message}>{m.text.split("\n")[0]}</span>
|
||||
{start && (
|
||||
<span className={styles.position}>
|
||||
:{start.line + 1}:{start.col + 1}
|
||||
</span>
|
||||
)}
|
||||
{start && <span className={styles.position}>:{start.line + 1}:{start.col + 1}</span>}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
@@ -204,11 +192,7 @@ function BuildConsole() {
|
||||
{virtualizer.getVirtualItems().map((v) => {
|
||||
const line = lines[v.index]!;
|
||||
return (
|
||||
<div
|
||||
key={v.key}
|
||||
className={clsx(styles.line, styles[line.kind])}
|
||||
style={{ transform: `translateY(${v.start}px)` }}
|
||||
>
|
||||
<div key={v.key} className={clsx(styles.line, styles[line.kind])} style={{ transform: `translateY(${v.start}px)` }}>
|
||||
{line.text || " "}
|
||||
</div>
|
||||
);
|
||||
@@ -223,9 +207,7 @@ export function BuildView() {
|
||||
if (!hasBuild) {
|
||||
return (
|
||||
<div className={styles.view}>
|
||||
<EmptyState title="No build output">
|
||||
<T>Build the project to see compiler messages here</T>
|
||||
</EmptyState>
|
||||
<EmptyState title="No build output">Build the project to see compiler messages here</EmptyState>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/** "hierarchy" tool window: call hierarchy (⌃⌥H) and type hierarchy (⌃H). */
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { basename, relativePath, useProject } from "@/platform/project";
|
||||
import { EmptyState, IconButton, Spinner, SymbolBadge, Tabs, Tree, badgeKind, type TreeRowState, T } from "@/ui";
|
||||
import { EmptyState, IconButton, Spinner, SymbolBadge, Tabs, Tree, badgeKind, type TreeRowState } from "@/ui";
|
||||
import { openLocation } from "./ipc";
|
||||
import {
|
||||
ROOT_ID,
|
||||
@@ -68,7 +68,8 @@ export function HierarchyView() {
|
||||
const roots = useMemo<Node[]>(() => (root ? [{ kind: "root", id: ROOT_ID }] : []), [root]);
|
||||
|
||||
const getChildren = useCallback(
|
||||
(n: Node): Node[] | undefined => children.get(n.id)?.map((c) => ({ kind: "item", id: c.id, node: c }) as Node),
|
||||
(n: Node): Node[] | undefined =>
|
||||
children.get(n.id)?.map((c) => ({ kind: "item", id: c.id, node: c }) as Node),
|
||||
[children],
|
||||
);
|
||||
const isExpandable = useCallback(
|
||||
@@ -81,9 +82,7 @@ export function HierarchyView() {
|
||||
|
||||
if (!root)
|
||||
return (
|
||||
<EmptyState>
|
||||
<T>Use Call Hierarchy (⌃⌥H) or Type Hierarchy (⌃H) on a symbol to see its hierarchy here</T>
|
||||
</EmptyState>
|
||||
<EmptyState>Use Call Hierarchy (⌃⌥H) or Type Hierarchy (⌃H) on a symbol to see its hierarchy here</EmptyState>
|
||||
);
|
||||
|
||||
const renderNode = (n: Node, _state: TreeRowState) => {
|
||||
@@ -96,11 +95,7 @@ export function HierarchyView() {
|
||||
{basename(root.path)}:{root.line + 1}
|
||||
</span>
|
||||
{loading && <Spinner size={12} />}
|
||||
{failed.has(ROOT_ID) && (
|
||||
<span className={styles.error}>
|
||||
<T>failed to load</T>
|
||||
</span>
|
||||
)}
|
||||
{failed.has(ROOT_ID) && <span className={styles.error}>failed to load</span>}
|
||||
{!loading && !failed.has(ROOT_ID) && children.get(ROOT_ID)?.length === 0 && (
|
||||
<span className={styles.muted}>— no {directionLabel(mode, direction).toLowerCase()} found</span>
|
||||
)}
|
||||
@@ -118,11 +113,7 @@ export function HierarchyView() {
|
||||
{basename(item.path)}:{item.selectionRange.start.line + 1}
|
||||
</span>
|
||||
{calls > 1 && <span className={styles.muted}>({calls} calls)</span>}
|
||||
{failed.has(n.id) && (
|
||||
<span className={styles.error}>
|
||||
<T>failed to load</T>
|
||||
</span>
|
||||
)}
|
||||
{failed.has(n.id) && <span className={styles.error}>failed to load</span>}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -6,7 +6,7 @@ import type { Diagnostic, Severity } from "@/bindings";
|
||||
import { useEditorRegistry } from "@/editor/api";
|
||||
import { basename, relativeDir, useProject } from "@/platform/project";
|
||||
import { editorService } from "@/workbench/contributions";
|
||||
import { EmptyState, Icon, IconButton, Tabs, Tree, fileIconName, type TreeRowState, T } from "@/ui";
|
||||
import { EmptyState, Icon, IconButton, Tabs, Tree, fileIconName, type TreeRowState } from "@/ui";
|
||||
import { countSeverities, fileDiagnostics, useProblems, type ProblemsMap } from "./problemsStore";
|
||||
import styles from "./ProblemsView.module.css";
|
||||
|
||||
@@ -65,20 +65,8 @@ export function ProblemsHeaderActions() {
|
||||
return (
|
||||
<>
|
||||
<IconButton icon="error" title="Show Errors" size="small" pressed={show.error} onClick={() => toggle("error")} />
|
||||
<IconButton
|
||||
icon="warning"
|
||||
title="Show Warnings"
|
||||
size="small"
|
||||
pressed={show.warning}
|
||||
onClick={() => toggle("warning")}
|
||||
/>
|
||||
<IconButton
|
||||
icon="info"
|
||||
title="Show Infos and Hints"
|
||||
size="small"
|
||||
pressed={show.info}
|
||||
onClick={() => toggle("info")}
|
||||
/>
|
||||
<IconButton icon="warning" title="Show Warnings" size="small" pressed={show.warning} onClick={() => toggle("warning")} />
|
||||
<IconButton icon="info" title="Show Infos and Hints" size="small" pressed={show.info} onClick={() => toggle("info")} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -92,8 +80,7 @@ export function ProblemsTabs() {
|
||||
const fileCount = current ? countSeverities(fileDiagnostics(map, current)) : null;
|
||||
const projectErrors = useMemo(() => {
|
||||
let n = 0;
|
||||
for (const sources of map.values())
|
||||
for (const items of sources.values()) n += items.filter((d) => d.severity === "error").length;
|
||||
for (const sources of map.values()) for (const items of sources.values()) n += items.filter((d) => d.severity === "error").length;
|
||||
return n;
|
||||
}, [map]);
|
||||
return (
|
||||
@@ -108,7 +95,7 @@ export function ProblemsTabs() {
|
||||
id: "file",
|
||||
label: current ? (
|
||||
<>
|
||||
<T>File</T> <span className={styles.tabFile}>{basename(current)}</span>
|
||||
File <span className={styles.tabFile}>{basename(current)}</span>
|
||||
</>
|
||||
) : (
|
||||
"File"
|
||||
@@ -141,10 +128,7 @@ export function ProblemsView() {
|
||||
return buildProblemNodes(map, paths, show);
|
||||
}, [map, tab, current, show]);
|
||||
|
||||
const expanded = useMemo(
|
||||
() => new Set(roots.filter((r) => !collapsed.has(r.key)).map((r) => r.key)),
|
||||
[roots, collapsed],
|
||||
);
|
||||
const expanded = useMemo(() => new Set(roots.filter((r) => !collapsed.has(r.key)).map((r) => r.key)), [roots, collapsed]);
|
||||
|
||||
const getChildren = useCallback(
|
||||
(n: Node): Node[] | undefined =>
|
||||
@@ -157,15 +141,15 @@ export function ProblemsView() {
|
||||
const renderNode = (n: Node, state: TreeRowState) => {
|
||||
if (n.kind === "file") {
|
||||
const c = countSeverities(n.items);
|
||||
const parts = [plural(c.error, "error"), plural(c.warning, "warning"), plural(c.info + c.hint, "info")].filter(
|
||||
Boolean,
|
||||
);
|
||||
const parts = [
|
||||
plural(c.error, "error"),
|
||||
plural(c.warning, "warning"),
|
||||
plural(c.info + c.hint, "info"),
|
||||
].filter(Boolean);
|
||||
return (
|
||||
<span className={styles.row}>
|
||||
<Icon name={fileIconName(basename(n.path))} size={16} className={styles.fileIcon} />
|
||||
<span
|
||||
className={clsx(styles.fileName, c.error > 0 && styles.fileError, state.selected && styles.selectedText)}
|
||||
>
|
||||
<span className={clsx(styles.fileName, c.error > 0 && styles.fileError, state.selected && styles.selectedText)}>
|
||||
{basename(n.path)}
|
||||
</span>
|
||||
<span className={styles.muted}>{relativeDir(root, n.path)}</span>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { useMemo, useRef, useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import { getAction, executeAction } from "@/platform/actions";
|
||||
import { BarButton, Button, IconButton, Popup, T } from "@/ui";
|
||||
import { BarButton, Button, IconButton, Popup } from "@/ui";
|
||||
import { relativePath, useProject } from "@/platform/project";
|
||||
import { STATUS_LABEL, restartServer, serversSummary, useServers } from "./servers";
|
||||
import styles from "./ServerStatus.module.css";
|
||||
@@ -38,9 +38,7 @@ export function ServerStatus() {
|
||||
aria-label="Language servers"
|
||||
>
|
||||
<div className={styles.panel}>
|
||||
<div className={styles.header}>
|
||||
<T>Language Servers</T>
|
||||
</div>
|
||||
<div className={styles.header}>Language Servers</div>
|
||||
{servers.map((s) => (
|
||||
<div key={s.id} className={styles.server}>
|
||||
<div className={styles.line}>
|
||||
@@ -57,7 +55,7 @@ export function ServerStatus() {
|
||||
void executeAction("tools.install", s.name);
|
||||
}}
|
||||
>
|
||||
<T>Install</T>
|
||||
Install
|
||||
</Button>
|
||||
) : (
|
||||
<IconButton
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/** "usages" tool window: Find Usages results grouped by file with line previews. */
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { basename, relativeDir, useProject } from "@/platform/project";
|
||||
import { EmptyState, Icon, IconButton, Spinner, Tabs, Tree, fileIconName, type TreeRowState, T } from "@/ui";
|
||||
import { EmptyState, Icon, IconButton, Spinner, Tabs, Tree, fileIconName, type TreeRowState } from "@/ui";
|
||||
import { openLocation } from "./ipc";
|
||||
import { trimPreview, usageCount, useUsages, type Usage, type UsageGroup } from "./usages";
|
||||
import styles from "./UsagesView.module.css";
|
||||
@@ -68,12 +68,7 @@ export function UsagesView() {
|
||||
[files],
|
||||
);
|
||||
|
||||
if (!search)
|
||||
return (
|
||||
<EmptyState>
|
||||
<T>Use Find Usages (⌥F7) on a symbol to see its usages here</T>
|
||||
</EmptyState>
|
||||
);
|
||||
if (!search) return <EmptyState>Use Find Usages (⌥F7) on a symbol to see its usages here</EmptyState>;
|
||||
const total = usageCount(search.groups);
|
||||
const setAll = (collapse: boolean) =>
|
||||
setCollapsed({ id: search.id, keys: collapse ? new Set(files.map((f) => f.key)) : new Set() });
|
||||
@@ -82,9 +77,7 @@ export function UsagesView() {
|
||||
if (n.kind === "summary")
|
||||
return (
|
||||
<span className={styles.row}>
|
||||
<span className={styles.groupLabel}>
|
||||
<T>Found usages</T>
|
||||
</span>
|
||||
<span className={styles.groupLabel}>Found usages</span>
|
||||
<span className={styles.count}>
|
||||
{total} {total === 1 ? "result" : "results"}
|
||||
</span>
|
||||
@@ -162,13 +155,7 @@ export function UsagesView() {
|
||||
const u = n.kind === "usage" ? n.usage : n.kind === "file" ? n.group.usages[0] : undefined;
|
||||
if (u) openLocation(u.path, u.line, u.col);
|
||||
}}
|
||||
empty={
|
||||
!search.loading && !search.error ? (
|
||||
<EmptyState>
|
||||
<T>No usages found</T>
|
||||
</EmptyState>
|
||||
) : undefined
|
||||
}
|
||||
empty={!search.loading && !search.error ? <EmptyState>No usages found</EmptyState> : undefined}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useMemo, useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { EmptyState, Icon, IconButton, Tabs, Tree, fileIconName, T } from "@/ui";
|
||||
import { EmptyState, Icon, IconButton, Tabs, Tree, fileIconName } from "@/ui";
|
||||
import { editorService } from "@/workbench/contributions";
|
||||
import { coverageTree, formatPercent, percent, sortTree, type CoverageNode, type SortKey } from "./model";
|
||||
import { activeSuite, closeSuite, selectSuite, setCoverageVisible, useCoverage } from "./store";
|
||||
@@ -72,23 +72,15 @@ export function CoverageView() {
|
||||
const [sort, setSort] = useState<{ key: SortKey; ascending: boolean }>({ key: "name", ascending: true });
|
||||
const [expanded, setExpanded] = useState<Set<string> | null>(null);
|
||||
|
||||
const roots = useMemo(
|
||||
() => (suite ? sortTree(coverageTree(suite.data, root), sort.key, sort.ascending) : []),
|
||||
[suite, root, sort],
|
||||
);
|
||||
const effectiveExpanded = useMemo(
|
||||
() => expanded ?? new Set(roots.filter((n) => n.dir).map((n) => n.path)),
|
||||
[expanded, roots],
|
||||
);
|
||||
const roots = useMemo(() => (suite ? sortTree(coverageTree(suite.data, root), sort.key, sort.ascending) : []), [suite, root, sort]);
|
||||
const effectiveExpanded = useMemo(() => expanded ?? new Set(roots.filter((n) => n.dir).map((n) => n.path)), [expanded, roots]);
|
||||
|
||||
if (!suite) {
|
||||
return (
|
||||
<EmptyState title="No coverage data">
|
||||
<span>
|
||||
<T>Run a configuration with coverage to see which lines its tests execute.</T>
|
||||
</span>
|
||||
<span>Run a configuration with coverage to see which lines its tests execute.</span>
|
||||
<button type="button" className={styles.link} onClick={() => void executeAction("run.coverage")}>
|
||||
<T>Run with Coverage</T>
|
||||
Run with Coverage
|
||||
</button>
|
||||
</EmptyState>
|
||||
);
|
||||
@@ -100,11 +92,7 @@ export function CoverageView() {
|
||||
|
||||
return (
|
||||
<div className={styles.view}>
|
||||
{!visible && (
|
||||
<div className={styles.banner}>
|
||||
<T>Coverage is hidden in editors and the project view.</T>
|
||||
</div>
|
||||
)}
|
||||
{!visible && <div className={styles.banner}>Coverage is hidden in editors and the project view.</div>}
|
||||
<div className={clsx(styles.header, !branches && styles.noBranches)} role="row">
|
||||
{columns.map((c) => (
|
||||
<button
|
||||
|
||||
@@ -9,18 +9,7 @@ import type { DbTableDetails } from "@/platform/ipc";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
import {
|
||||
Button,
|
||||
EmptyState,
|
||||
Icon,
|
||||
IconButton,
|
||||
Menu,
|
||||
Tree,
|
||||
showContextMenu,
|
||||
tooltipAttrs,
|
||||
type TreeHandle,
|
||||
T,
|
||||
} from "@/ui";
|
||||
import { Button, EmptyState, Icon, IconButton, Menu, Tree, showContextMenu, tooltipAttrs, type TreeHandle } from "@/ui";
|
||||
import { databaseKey, driverIcon, splitTarget, targetOf } from "./model";
|
||||
import { nodeTarget, type DbNode as Node, type Group } from "./nodes";
|
||||
import {
|
||||
@@ -41,12 +30,7 @@ import { DB_VIEW_FOCUS, openTableData } from "./treeActions";
|
||||
import { newMenu, nodeMenu } from "./treeMenu";
|
||||
import styles from "./Database.module.css";
|
||||
|
||||
const GROUP_LABELS: Record<Group, string> = {
|
||||
columns: "columns",
|
||||
keys: "keys",
|
||||
foreignKeys: "foreign keys",
|
||||
indexes: "indexes",
|
||||
};
|
||||
const GROUP_LABELS: Record<Group, string> = { columns: "columns", keys: "keys", foreignKeys: "foreign keys", indexes: "indexes" };
|
||||
|
||||
function status<T>(key: string, l: Loaded<T> | undefined, map: (v: T) => Node[]): Node[] | undefined {
|
||||
if (!l) return undefined;
|
||||
@@ -106,9 +90,7 @@ export function DatabaseView() {
|
||||
};
|
||||
|
||||
const schemasOf = (key: string, id: string) =>
|
||||
status(key, st.schemas[id], (v) =>
|
||||
v.map((schema) => ({ kind: "schema", key: `${id}/${schema}`, id, schema }) as Node),
|
||||
);
|
||||
status(key, st.schemas[id], (v) => v.map((schema) => ({ kind: "schema", key: `${id}/${schema}`, id, schema }) as Node));
|
||||
|
||||
const children = (n: Node): readonly Node[] | undefined => {
|
||||
switch (n.kind) {
|
||||
@@ -142,14 +124,7 @@ export function DatabaseView() {
|
||||
const d = st.details[detailsKey(n.id, n.schema, n.table.name)];
|
||||
if (!d || d.status === "loading") return undefined;
|
||||
if (d.status === "error") return [{ kind: "message", key: `${n.key}/err`, text: d.message, error: true }];
|
||||
return groupsOf(d.value).map((group) => ({
|
||||
kind: "group",
|
||||
key: `${n.key}/${group}`,
|
||||
id: n.id,
|
||||
schema: n.schema,
|
||||
table: n.table.name,
|
||||
group,
|
||||
}));
|
||||
return groupsOf(d.value).map((group) => ({ kind: "group", key: `${n.key}/${group}`, id: n.id, schema: n.schema, table: n.table.name, group }));
|
||||
}
|
||||
case "group": {
|
||||
const d = detailsOf(n.id, n.schema, n.table);
|
||||
@@ -158,13 +133,7 @@ export function DatabaseView() {
|
||||
const at = { id: n.id, schema: n.schema, table: n.table };
|
||||
switch (n.group) {
|
||||
case "columns":
|
||||
return d.columns.map((column) => ({
|
||||
kind: "column",
|
||||
key: `${n.key}/${column.name}`,
|
||||
column,
|
||||
foreignKey: fkCols.has(column.name),
|
||||
...at,
|
||||
}));
|
||||
return d.columns.map((column) => ({ kind: "column", key: `${n.key}/${column.name}`, column, foreignKey: fkCols.has(column.name), ...at }));
|
||||
case "keys":
|
||||
return [{ kind: "key", key: `${n.key}/pk`, columns: primaryKey(d), ...at }];
|
||||
case "foreignKeys":
|
||||
@@ -236,9 +205,7 @@ export function DatabaseView() {
|
||||
return s?.status === "ok" ? String(s.value.length) : undefined;
|
||||
}
|
||||
case "folder":
|
||||
return String(
|
||||
(tablesOf(n.id, n.schema) ?? []).filter((t) => (t.kind === "view") === (n.folder === "views")).length,
|
||||
);
|
||||
return String((tablesOf(n.id, n.schema) ?? []).filter((t) => (t.kind === "view") === (n.folder === "views")).length);
|
||||
case "group": {
|
||||
const d = detailsOf(n.id, n.schema, n.table);
|
||||
return d ? String(groupSize(d, n.group)) : undefined;
|
||||
@@ -288,7 +255,7 @@ export function DatabaseView() {
|
||||
<DatabaseToolbar />
|
||||
<EmptyState title="No data sources">
|
||||
<Button variant="ghost" onClick={() => void executeAction("db.newDataSource")}>
|
||||
<T>New Data Source…</T>
|
||||
New Data Source…
|
||||
</Button>
|
||||
</EmptyState>
|
||||
</div>
|
||||
@@ -312,13 +279,7 @@ export function DatabaseView() {
|
||||
getLabel={label}
|
||||
getChildren={children}
|
||||
isExpandable={(n) =>
|
||||
n.kind === "source" ||
|
||||
n.kind === "database" ||
|
||||
n.kind === "schema" ||
|
||||
n.kind === "folder" ||
|
||||
n.kind === "table" ||
|
||||
n.kind === "group"
|
||||
}
|
||||
n.kind === "source" || n.kind === "database" || n.kind === "schema" || n.kind === "folder" || n.kind === "table" || n.kind === "group"}
|
||||
loadChildren={load}
|
||||
getIcon={(n) => icon(n)}
|
||||
getDetail={detail}
|
||||
@@ -328,11 +289,7 @@ export function DatabaseView() {
|
||||
const d = detail(n);
|
||||
const counted = n.kind === "source" || n.kind === "database" || n.kind === "folder" || n.kind === "group";
|
||||
const labelClass =
|
||||
n.kind === "message" && n.error
|
||||
? styles.treeError
|
||||
: n.kind === "key" || n.kind === "foreignKey"
|
||||
? styles.keyLabel
|
||||
: styles.nodeLabel;
|
||||
n.kind === "message" && n.error ? styles.treeError : n.kind === "key" || n.kind === "foreignKey" ? styles.keyLabel : styles.nodeLabel;
|
||||
const live = n.kind === "source" && [...st.connected].some((t) => splitTarget(t).id === n.source.id);
|
||||
return (
|
||||
<span className={styles.nodeRow}>
|
||||
@@ -345,26 +302,14 @@ export function DatabaseView() {
|
||||
)}
|
||||
<span className={labelClass}>{label(n)}</span>
|
||||
{d && (
|
||||
<span
|
||||
className={
|
||||
n.kind === "source"
|
||||
? styles.treeBadge
|
||||
: counted
|
||||
? styles.treeCount
|
||||
: n.kind === "column"
|
||||
? styles.treeType
|
||||
: styles.treeDetail
|
||||
}
|
||||
>
|
||||
<span className={n.kind === "source" ? styles.treeBadge : counted ? styles.treeCount : n.kind === "column" ? styles.treeType : styles.treeDetail}>
|
||||
{d}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}}
|
||||
onSelectionChange={(_, lead) =>
|
||||
useDatabase.setState({ selectedSource: lead ? nodeTarget(lead) : null, selectedNode: lead })
|
||||
}
|
||||
onSelectionChange={(_, lead) => useDatabase.setState({ selectedSource: lead ? nodeTarget(lead) : null, selectedNode: lead })}
|
||||
onActivate={(n) => {
|
||||
if (n.kind === "table") openTableData(n.id, n.schema, n.table.name);
|
||||
else if (n.kind === "source") void openConsole(n.source.id ?? "");
|
||||
@@ -410,14 +355,7 @@ function DatabaseToolbar() {
|
||||
aria-expanded={newOpen}
|
||||
onClick={() => setNewOpen(!newOpen)}
|
||||
/>
|
||||
<Menu
|
||||
open={newOpen}
|
||||
anchor={plus}
|
||||
items={newMenu()}
|
||||
placement="bottom-start"
|
||||
onClose={() => setNewOpen(false)}
|
||||
aria-label="New"
|
||||
/>
|
||||
<Menu open={newOpen} anchor={plus} items={newMenu()} placement="bottom-start" onClose={() => setNewOpen(false)} aria-label="New" />
|
||||
<IconButton {...button} icon="db-properties" action="db.properties" disabled={!sources.length} />
|
||||
<span className={styles.dbToolbarSep} />
|
||||
<IconButton {...button} icon="refresh" action="db.refresh" disabled={!sources.length} />
|
||||
@@ -434,7 +372,7 @@ function DatabaseToolbar() {
|
||||
onClick={() => void executeAction("db.goToDdl")}
|
||||
{...tooltipAttrs("Go to DDL", shortcutLabel("db.goToDdl"))}
|
||||
>
|
||||
<T>DDL</T>
|
||||
DDL
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
type DbSshAuth,
|
||||
type DbSslMode,
|
||||
} from "@/platform/ipc";
|
||||
import { Button, Checkbox, Dialog, Input, Select, Tabs, lazyComponent, T } from "@/ui";
|
||||
import { Button, Checkbox, Dialog, Input, Select, Tabs, lazyComponent } from "@/ui";
|
||||
import { connectRemedy, fileSourceName, newSourceId, sshLabel } from "./model";
|
||||
import { closeDialog, saveSource, useDatabase } from "./store";
|
||||
import styles from "./Database.module.css";
|
||||
@@ -147,7 +147,7 @@ function SourceDialog({
|
||||
width={560}
|
||||
footerStart={
|
||||
<Button onClick={() => void runTest()} disabled={busy || !valid}>
|
||||
<T>Test Connection</T>
|
||||
Test Connection
|
||||
</Button>
|
||||
}
|
||||
buttons={[
|
||||
@@ -169,35 +169,19 @@ function SourceDialog({
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
<div
|
||||
className={styles.form}
|
||||
role={sqlite ? undefined : "tabpanel"}
|
||||
id={sqlite ? undefined : `db-source-panel-${tab}`}
|
||||
>
|
||||
<div className={styles.form} role={sqlite ? undefined : "tabpanel"} id={sqlite ? undefined : `db-source-panel-${tab}`}>
|
||||
{sqlite || tab === "general" ? (
|
||||
<>
|
||||
<label className={styles.formLabel} htmlFor="db-name">
|
||||
<T>Name:</T>
|
||||
Name:
|
||||
</label>
|
||||
<Input
|
||||
id="db-name"
|
||||
value={s.name ?? ""}
|
||||
placeholder={name}
|
||||
onChange={(e) => set({ name: e.target.value })}
|
||||
/>
|
||||
<span className={styles.formLabel}>
|
||||
<T>Driver:</T>
|
||||
</span>
|
||||
<Select
|
||||
aria-label="Driver"
|
||||
value={s.driver ?? "postgres"}
|
||||
options={DRIVERS}
|
||||
onChange={(driver) => set({ driver })}
|
||||
/>
|
||||
<Input id="db-name" value={s.name ?? ""} placeholder={name} onChange={(e) => set({ name: e.target.value })} />
|
||||
<span className={styles.formLabel}>Driver:</span>
|
||||
<Select aria-label="Driver" value={s.driver ?? "postgres"} options={DRIVERS} onChange={(driver) => set({ driver })} />
|
||||
{sqlite ? (
|
||||
<>
|
||||
<label className={styles.formLabel} htmlFor="db-file">
|
||||
<T>File:</T>
|
||||
File:
|
||||
</label>
|
||||
<div className={styles.formRow}>
|
||||
<Input
|
||||
@@ -207,25 +191,18 @@ function SourceDialog({
|
||||
placeholder="path/to/database.db (absolute or project-relative)"
|
||||
onChange={(e) => set({ file: e.target.value || null })}
|
||||
/>
|
||||
<Button onClick={() => void browse()}>
|
||||
<T>Browse…</T>
|
||||
</Button>
|
||||
<Button onClick={() => void browse()}>Browse…</Button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<label className={styles.formLabel} htmlFor="db-host">
|
||||
<T>Host:</T>
|
||||
Host:
|
||||
</label>
|
||||
<div className={styles.formRow}>
|
||||
<Input
|
||||
id="db-host"
|
||||
className={styles.fill}
|
||||
value={s.host ?? ""}
|
||||
onChange={(e) => set({ host: e.target.value })}
|
||||
/>
|
||||
<Input id="db-host" className={styles.fill} value={s.host ?? ""} onChange={(e) => set({ host: e.target.value })} />
|
||||
<label className={styles.formLabel} htmlFor="db-port">
|
||||
<T>Port:</T>
|
||||
Port:
|
||||
</label>
|
||||
<Input
|
||||
id="db-port"
|
||||
@@ -243,11 +220,11 @@ function SourceDialog({
|
||||
</>
|
||||
)}
|
||||
<label className={styles.formLabel} htmlFor="db-user">
|
||||
<T>User:</T>
|
||||
User:
|
||||
</label>
|
||||
<Input id="db-user" value={s.user ?? ""} onChange={(e) => set({ user: e.target.value })} />
|
||||
<label className={styles.formLabel} htmlFor="db-password">
|
||||
<T>Password:</T>
|
||||
Password:
|
||||
</label>
|
||||
<div className={styles.formRow}>
|
||||
<Input
|
||||
@@ -265,7 +242,7 @@ function SourceDialog({
|
||||
/>
|
||||
</div>
|
||||
<label className={styles.formLabel} htmlFor="db-database">
|
||||
<T>Database:</T>
|
||||
Database:
|
||||
</label>
|
||||
<Input id="db-database" value={s.database ?? ""} onChange={(e) => set({ database: e.target.value })} />
|
||||
</>
|
||||
@@ -278,7 +255,7 @@ function SourceDialog({
|
||||
<span />
|
||||
<Checkbox checked={!!ssh.enabled} onChange={(enabled) => setSsh({ enabled })} label="Use SSH tunnel" />
|
||||
<label className={styles.formLabel} htmlFor="db-ssh-host">
|
||||
<T>Host:</T>
|
||||
Host:
|
||||
</label>
|
||||
<div className={styles.formRow}>
|
||||
<Input
|
||||
@@ -290,7 +267,7 @@ function SourceDialog({
|
||||
onChange={(e) => setSsh({ host: e.target.value })}
|
||||
/>
|
||||
<label className={styles.formLabel} htmlFor="db-ssh-port">
|
||||
<T>Port:</T>
|
||||
Port:
|
||||
</label>
|
||||
<Input
|
||||
id="db-ssh-port"
|
||||
@@ -303,7 +280,7 @@ function SourceDialog({
|
||||
/>
|
||||
</div>
|
||||
<label className={styles.formLabel} htmlFor="db-ssh-user">
|
||||
<T>User:</T>
|
||||
User:
|
||||
</label>
|
||||
<Input
|
||||
id="db-ssh-user"
|
||||
@@ -312,9 +289,7 @@ function SourceDialog({
|
||||
placeholder={ssh.auth === "openSsh" ? "from ~/.ssh/config" : ""}
|
||||
onChange={(e) => setSsh({ user: e.target.value })}
|
||||
/>
|
||||
<span className={styles.formLabel}>
|
||||
<T>Authentication:</T>
|
||||
</span>
|
||||
<span className={styles.formLabel}>Authentication:</span>
|
||||
<Select
|
||||
aria-label="SSH authentication type"
|
||||
disabled={!sshOn}
|
||||
@@ -325,7 +300,7 @@ function SourceDialog({
|
||||
{ssh.auth === "keyPair" && (
|
||||
<>
|
||||
<label className={styles.formLabel} htmlFor="db-ssh-key">
|
||||
<T>Private key:</T>
|
||||
Private key:
|
||||
</label>
|
||||
<div className={styles.formRow}>
|
||||
<Input
|
||||
@@ -337,7 +312,7 @@ function SourceDialog({
|
||||
onChange={(e) => setSsh({ keyFile: e.target.value })}
|
||||
/>
|
||||
<Button disabled={!sshOn} onClick={() => void browseKey()}>
|
||||
<T>Browse…</T>
|
||||
Browse…
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
@@ -346,11 +321,7 @@ function SourceDialog({
|
||||
<>
|
||||
<span />
|
||||
<span className={styles.formHint}>
|
||||
<T>
|
||||
{
|
||||
"Uses HostName, User, Port, IdentityFile and ProxyJump from ~/.ssh/config, and keys of the SSH agent."
|
||||
}
|
||||
</T>
|
||||
Uses HostName, User, Port, IdentityFile and ProxyJump from ~/.ssh/config, and keys of the SSH agent.
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
@@ -377,9 +348,7 @@ function SourceDialog({
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<span className={styles.formLabel}>
|
||||
<T>SSL:</T>
|
||||
</span>
|
||||
<span className={styles.formLabel}>SSL:</span>
|
||||
<Select aria-label="SSL mode" value={s.ssl ?? "prefer"} options={SSL} onChange={(ssl) => set({ ssl })} />
|
||||
</>
|
||||
)}
|
||||
@@ -389,7 +358,7 @@ function SourceDialog({
|
||||
<>
|
||||
{" "}
|
||||
<Button size="small" onClick={() => void trustAndRetry()} disabled={busy}>
|
||||
<T>Trust Host and Retry</T>
|
||||
Trust Host and Retry
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
@@ -422,20 +391,12 @@ function PasswordDialog({ source, resolve }: { source: DataSource; resolve: (ok:
|
||||
]}
|
||||
>
|
||||
<div className={styles.form}>
|
||||
<span className={styles.formLabel}>
|
||||
<T>User:</T>
|
||||
</span>
|
||||
<span className={styles.formLabel}>User:</span>
|
||||
<span>{source.user || "(default)"}</span>
|
||||
<label className={styles.formLabel} htmlFor="db-ask-password">
|
||||
<T>Password:</T>
|
||||
Password:
|
||||
</label>
|
||||
<Input
|
||||
id="db-ask-password"
|
||||
type="password"
|
||||
autoFocus
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
/>
|
||||
<Input id="db-ask-password" type="password" autoFocus value={password} onChange={(e) => setPassword(e.target.value)} />
|
||||
<span />
|
||||
<Checkbox checked={save} onChange={setSave} label="Save password" />
|
||||
</div>
|
||||
@@ -444,15 +405,7 @@ function PasswordDialog({ source, resolve }: { source: DataSource; resolve: (ok:
|
||||
}
|
||||
|
||||
/** SSH password / key passphrase asked on connect. */
|
||||
function SshSecretDialog({
|
||||
source,
|
||||
prompt,
|
||||
resolve,
|
||||
}: {
|
||||
source: DataSource;
|
||||
prompt: string;
|
||||
resolve: (ok: boolean) => void;
|
||||
}) {
|
||||
function SshSecretDialog({ source, prompt, resolve }: { source: DataSource; prompt: string; resolve: (ok: boolean) => void }) {
|
||||
const [secret, setSecret] = useState("");
|
||||
const [save, setSave] = useState(!!source.ssh?.saveSecret);
|
||||
const password = source.ssh?.auth === "password" || /password required/.test(prompt);
|
||||
@@ -481,13 +434,7 @@ function SshSecretDialog({
|
||||
<label className={styles.formLabel} htmlFor="db-ask-ssh-secret">
|
||||
{password ? "Password:" : "Passphrase:"}
|
||||
</label>
|
||||
<Input
|
||||
id="db-ask-ssh-secret"
|
||||
type="password"
|
||||
autoFocus
|
||||
value={secret}
|
||||
onChange={(e) => setSecret(e.target.value)}
|
||||
/>
|
||||
<Input id="db-ask-ssh-secret" type="password" autoFocus value={secret} onChange={(e) => setSecret(e.target.value)} />
|
||||
<span />
|
||||
<Checkbox checked={save} onChange={setSave} label="Save password" />
|
||||
</div>
|
||||
@@ -495,14 +442,33 @@ function SshSecretDialog({
|
||||
);
|
||||
}
|
||||
|
||||
/** First connection to an SSH host: trust its key (added to ~/.ssh/known_hosts)? */
|
||||
function HostKeyDialog({ prompt, resolve }: { prompt: string; resolve: (ok: boolean) => void }) {
|
||||
const done = (ok: boolean) => {
|
||||
closeDialog();
|
||||
resolve(ok);
|
||||
};
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
onClose={() => done(false)}
|
||||
title="Unknown SSH Host"
|
||||
width={480}
|
||||
buttons={[
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
{ label: "Trust and Connect", role: "default", onClick: () => done(true) },
|
||||
]}
|
||||
>
|
||||
<div className={styles.dialogText}>
|
||||
{prompt}. The authenticity of the host cannot be established. Trust it and add the key to ~/.ssh/known_hosts?
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
/** Overlay host: whichever dialog the store asks for. */
|
||||
/** IDEA's parameter dialog: one SQL value per query parameter, remembered for the next run. */
|
||||
function ParamsDialog({
|
||||
names,
|
||||
resolve,
|
||||
}: {
|
||||
names: string[];
|
||||
resolve: (values: Record<string, string> | null) => void;
|
||||
}) {
|
||||
function ParamsDialog({ names, resolve }: { names: string[]; resolve: (values: Record<string, string> | null) => void }) {
|
||||
const [values, setValues] = useState<Record<string, string>>(() => {
|
||||
const last = useDatabase.getState().paramValues;
|
||||
return Object.fromEntries(names.map((n) => [n, last[n] ?? ""]));
|
||||
@@ -546,33 +512,47 @@ function ParamsDialog({
|
||||
</Fragment>
|
||||
))}
|
||||
<span />
|
||||
<span className={styles.formHint}>
|
||||
<T>Values are inserted as SQL: quote strings, e.g. 'abc'.</T>
|
||||
</span>
|
||||
<span className={styles.formHint}>Values are inserted as SQL: quote strings, e.g. 'abc'.</span>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
/** Leaving manual commit with changes pending (IDEA asks the same). */
|
||||
function EndTransactionDialog({ source, resolve }: { source: DataSource; resolve: (commit: boolean | null) => void }) {
|
||||
const done = (v: boolean | null) => {
|
||||
closeDialog();
|
||||
resolve(v);
|
||||
};
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
onClose={() => done(null)}
|
||||
title="Switch to Auto-Commit"
|
||||
width={420}
|
||||
buttons={[
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
{ label: "Roll Back", onClick: () => done(false) },
|
||||
{ label: "Commit", role: "default", onClick: () => done(true) },
|
||||
]}
|
||||
>
|
||||
<div className={styles.dialogText}>
|
||||
{source.name} has uncommitted changes. Commit or roll them back before switching to auto-commit?
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
/** Overlay host: whichever dialog the store asks for. */
|
||||
export function DatabaseDialogs() {
|
||||
const dialog = useDatabase((s) => s.dialog);
|
||||
if (!dialog) return null;
|
||||
if (dialog.kind === "source")
|
||||
return (
|
||||
<SourceDialog
|
||||
key={dialog.source?.id ?? "new"}
|
||||
initial={dialog.source}
|
||||
preset={dialog.preset}
|
||||
presetPassword={dialog.password}
|
||||
/>
|
||||
);
|
||||
return <SourceDialog key={dialog.source?.id ?? "new"} initial={dialog.source} preset={dialog.preset} presetPassword={dialog.password} />;
|
||||
if (dialog.kind === "params") return <ParamsDialog names={dialog.names} resolve={dialog.resolve} />;
|
||||
if (dialog.kind === "endTransaction") return <EndTransactionDialog source={dialog.source} resolve={dialog.resolve} />;
|
||||
if (dialog.kind === "sshSecret")
|
||||
return (
|
||||
<SshSecretDialog key={dialog.source.id} source={dialog.source} prompt={dialog.prompt} resolve={dialog.resolve} />
|
||||
);
|
||||
if (dialog.kind === "password")
|
||||
return <PasswordDialog key={dialog.source.id} source={dialog.source} resolve={dialog.resolve} />;
|
||||
return <SshSecretDialog key={dialog.source.id} source={dialog.source} prompt={dialog.prompt} resolve={dialog.resolve} />;
|
||||
if (dialog.kind === "hostKey") return <HostKeyDialog prompt={dialog.prompt} resolve={dialog.resolve} />;
|
||||
if (dialog.kind === "password") return <PasswordDialog key={dialog.source.id} source={dialog.source} resolve={dialog.resolve} />;
|
||||
return <ObjectDialogs />;
|
||||
}
|
||||
@@ -4,9 +4,9 @@
|
||||
* run), Remove Data Source, Data Source from URL, and the Quick Documentation popup.
|
||||
*/
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { call, commands, type DbColumnInfo, type DbDriver } from "@/platform/ipc";
|
||||
import { call, commands, type DataSource, type DbColumnInfo, type DbDriver } from "@/platform/ipc";
|
||||
import { highlightInto } from "@/editor/lsp/markdown";
|
||||
import { Button, Checkbox, Dialog, IconButton, Input, Popup, Icon, T } from "@/ui";
|
||||
import { Button, Checkbox, Dialog, IconButton, Input, Popup, Icon } from "@/ui";
|
||||
import { parseSourceUrl, sourceLabel, splitTarget } from "./model";
|
||||
import { nodeTarget, tableOf, type DbNode } from "./nodes";
|
||||
import {
|
||||
@@ -24,7 +24,9 @@ import {
|
||||
} from "./objects";
|
||||
import {
|
||||
closeDialog,
|
||||
deleteSource,
|
||||
detailsKey,
|
||||
disconnect,
|
||||
connectedTargets,
|
||||
loadDetails,
|
||||
openSourceDialog,
|
||||
@@ -156,16 +158,9 @@ function DropDialog({ id, object }: { id: string; object: DbObjectRef }) {
|
||||
checked={ifExists}
|
||||
onChange={setIfExists}
|
||||
label="Use IF EXISTS syntax"
|
||||
disabled={
|
||||
(object.kind === "column" && driver !== "postgres") || (object.kind === "index" && driver === "mysql")
|
||||
}
|
||||
/>
|
||||
<Checkbox
|
||||
checked={cascade}
|
||||
onChange={setCascade}
|
||||
label="Use DROP CASCADE syntax"
|
||||
disabled={driver !== "postgres"}
|
||||
disabled={(object.kind === "column" && driver !== "postgres") || (object.kind === "index" && driver === "mysql")}
|
||||
/>
|
||||
<Checkbox checked={cascade} onChange={setCascade} label="Use DROP CASCADE syntax" disabled={driver !== "postgres"} />
|
||||
<SqlPreview sql={sql} />
|
||||
</div>
|
||||
</Dialog>
|
||||
@@ -191,7 +186,7 @@ function TruncateDialog({ id, schema, table }: { id: string; schema: string; tab
|
||||
>
|
||||
<div className={styles.dialogBody}>
|
||||
<div className={styles.dialogLead}>
|
||||
<T>Delete all rows of</T> <strong>{table}</strong>?
|
||||
Delete all rows of <strong>{table}</strong>?
|
||||
</div>
|
||||
{driver === "postgres" && (
|
||||
<>
|
||||
@@ -228,21 +223,7 @@ const TYPES: Record<DbDriver, string[]> = {
|
||||
"jsonb",
|
||||
"bytea",
|
||||
],
|
||||
mysql: [
|
||||
"int",
|
||||
"bigint",
|
||||
"smallint",
|
||||
"tinyint(1)",
|
||||
"decimal(10,2)",
|
||||
"double",
|
||||
"varchar(255)",
|
||||
"text",
|
||||
"date",
|
||||
"datetime",
|
||||
"timestamp",
|
||||
"json",
|
||||
"blob",
|
||||
],
|
||||
mysql: ["int", "bigint", "smallint", "tinyint(1)", "decimal(10,2)", "double", "varchar(255)", "text", "date", "datetime", "timestamp", "json", "blob"],
|
||||
};
|
||||
|
||||
interface ModifyProps {
|
||||
@@ -279,26 +260,13 @@ function ModifyTableDialog(props: ModifyProps) {
|
||||
if (!table) return <ModifyTableForm {...props} initial={null} />;
|
||||
if (details?.status === "ok") return <ModifyTableForm {...props} initial={details.value.columns} />;
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
onClose={closeDialog}
|
||||
title={`Modify Table ${table}`}
|
||||
width={440}
|
||||
buttons={[{ label: "Cancel", role: "cancel" }]}
|
||||
>
|
||||
<Dialog open onClose={closeDialog} title={`Modify Table ${table}`} width={440} buttons={[{ label: "Cancel", role: "cancel" }]}>
|
||||
<div className={styles.dialogText}>{details?.status === "error" ? details.message : "Loading…"}</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function ModifyTableForm({
|
||||
id,
|
||||
schema,
|
||||
table,
|
||||
focusColumn,
|
||||
addColumn,
|
||||
initial,
|
||||
}: ModifyProps & { initial: DbColumnInfo[] | null }) {
|
||||
function ModifyTableForm({ id, schema, table, focusColumn, addColumn, initial }: ModifyProps & { initial: DbColumnInfo[] | null }) {
|
||||
const driver = driverOf(id);
|
||||
const [name, setName] = useState(table ?? "table_name");
|
||||
const [columns, setColumns] = useState<ColumnDraft[]>(() => {
|
||||
@@ -319,8 +287,7 @@ function ModifyTableForm({
|
||||
}, [columns, driver, schema, table, name]);
|
||||
|
||||
const current = columns.find((c) => c.key === selected) ?? null;
|
||||
const patch = (p: Partial<ColumnDraft>) =>
|
||||
setColumns((cs) => cs.map((c) => (c.key === selected ? { ...c, ...p } : c)));
|
||||
const patch = (p: Partial<ColumnDraft>) => setColumns((cs) => cs.map((c) => (c.key === selected ? { ...c, ...p } : c)));
|
||||
const add = () => {
|
||||
const c = blankColumn(driver, columns.length + 1);
|
||||
setColumns((cs) => [...cs, c]);
|
||||
@@ -358,15 +325,9 @@ function ModifyTableForm({
|
||||
<div className={styles.modifyBody}>
|
||||
<div className={styles.formRow}>
|
||||
<label className={styles.formLabel} htmlFor="db-table-name">
|
||||
<T>Table:</T>
|
||||
Table:
|
||||
</label>
|
||||
<Input
|
||||
id="db-table-name"
|
||||
className={styles.fill}
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
autoFocus={!table}
|
||||
/>
|
||||
<Input id="db-table-name" className={styles.fill} value={name} onChange={(e) => setName(e.target.value)} autoFocus={!table} />
|
||||
<span className={styles.formHint}>{schema}</span>
|
||||
</div>
|
||||
<div className={styles.modifyMain}>
|
||||
@@ -403,16 +364,11 @@ function ModifyTableForm({
|
||||
{current ? (
|
||||
<>
|
||||
<label className={styles.formLabel} htmlFor="db-col-name">
|
||||
<T>Name</T>
|
||||
Name
|
||||
</label>
|
||||
<Input
|
||||
id="db-col-name"
|
||||
value={current.name}
|
||||
disabled={current.dropped}
|
||||
onChange={(e) => patch({ name: e.target.value })}
|
||||
/>
|
||||
<Input id="db-col-name" value={current.name} disabled={current.dropped} onChange={(e) => patch({ name: e.target.value })} />
|
||||
<label className={styles.formLabel} htmlFor="db-col-type">
|
||||
<T>Data type</T>
|
||||
Data type
|
||||
</label>
|
||||
<Input
|
||||
id="db-col-type"
|
||||
@@ -423,24 +379,15 @@ function ModifyTableForm({
|
||||
onChange={(e) => patch({ dataType: e.target.value })}
|
||||
/>
|
||||
<span />
|
||||
<Checkbox
|
||||
checked={current.notNull}
|
||||
disabled={current.dropped || locked}
|
||||
onChange={(notNull) => patch({ notNull })}
|
||||
label="Not null"
|
||||
/>
|
||||
<Checkbox checked={current.notNull} disabled={current.dropped || locked} onChange={(notNull) => patch({ notNull })} label="Not null" />
|
||||
{!table && (
|
||||
<>
|
||||
<span />
|
||||
<Checkbox
|
||||
checked={current.primaryKey}
|
||||
onChange={(primaryKey) => patch({ primaryKey })}
|
||||
label="Primary key"
|
||||
/>
|
||||
<Checkbox checked={current.primaryKey} onChange={(primaryKey) => patch({ primaryKey })} label="Primary key" />
|
||||
</>
|
||||
)}
|
||||
<label className={styles.formLabel} htmlFor="db-col-default">
|
||||
<T>Default</T>
|
||||
Default
|
||||
</label>
|
||||
<Input
|
||||
id="db-col-default"
|
||||
@@ -453,16 +400,12 @@ function ModifyTableForm({
|
||||
{locked && (
|
||||
<>
|
||||
<span />
|
||||
<span className={styles.formHint}>
|
||||
<T>SQLite can rename or drop an existing column, not change its type, NOT NULL or default.</T>
|
||||
</span>
|
||||
<span className={styles.formHint}>SQLite can rename or drop an existing column, not change its type, NOT NULL or default.</span>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<span className={styles.formHint}>
|
||||
<T>Select a column</T>
|
||||
</span>
|
||||
<span className={styles.formHint}>Select a column</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
@@ -479,6 +422,31 @@ function ModifyTableForm({
|
||||
|
||||
// ---- Data sources -------------------------------------------------------------
|
||||
|
||||
function RemoveSourceDialog({ source }: { source: DataSource }) {
|
||||
const remove = async () => {
|
||||
const id = source.id ?? "";
|
||||
closeDialog();
|
||||
if (connectedTargets(id).length) await disconnect(id);
|
||||
await deleteSource(id);
|
||||
};
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
onClose={closeDialog}
|
||||
title="Remove Data Source"
|
||||
width={440}
|
||||
buttons={[
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
{ label: "Remove", role: "default", onClick: () => void remove() },
|
||||
]}
|
||||
>
|
||||
<div className={styles.dialogText}>
|
||||
Remove data source <strong>{source.name}</strong>? Its query console file stays on disk.
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function SourceUrlDialog() {
|
||||
const [url, setUrl] = useState("");
|
||||
const parsed = url.trim() ? parseSourceUrl(url) : null;
|
||||
@@ -502,7 +470,7 @@ function SourceUrlDialog() {
|
||||
>
|
||||
<div className={styles.dialogBody}>
|
||||
<label className={styles.formLabelLeft} htmlFor="db-url">
|
||||
<T>URL:</T>
|
||||
URL:
|
||||
</label>
|
||||
<Input
|
||||
id="db-url"
|
||||
@@ -553,10 +521,7 @@ function QuickDoc({ node, anchor }: { node: DbNode; anchor: { x: number; y: numb
|
||||
rows.push(
|
||||
node.source.driver === "sqlite"
|
||||
? ["File", node.source.file ?? ""]
|
||||
: [
|
||||
"Host",
|
||||
`${node.source.host ?? ""}${node.source.port ? `:${node.source.port}` : ""}${node.source.database ? `/${node.source.database}` : ""}`,
|
||||
],
|
||||
: ["Host", `${node.source.host ?? ""}${node.source.port ? `:${node.source.port}` : ""}${node.source.database ? `/${node.source.database}` : ""}`],
|
||||
);
|
||||
rows.push(["Status", connectedTargets(node.source.id ?? "").length ? "Connected" : "Not connected"]);
|
||||
break;
|
||||
@@ -583,15 +548,7 @@ function QuickDoc({ node, anchor }: { node: DbNode; anchor: { x: number; y: numb
|
||||
definition = `primary key (${node.columns.join(", ")})`;
|
||||
}
|
||||
return (
|
||||
<Popup
|
||||
open
|
||||
onClose={closeDialog}
|
||||
anchor={anchor}
|
||||
placement="bottom-start"
|
||||
className={styles.quickDoc}
|
||||
role="dialog"
|
||||
aria-label="Quick Documentation"
|
||||
>
|
||||
<Popup open onClose={closeDialog} anchor={anchor} placement="bottom-start" className={styles.quickDoc} role="dialog" aria-label="Quick Documentation">
|
||||
<dl className={styles.quickDocRows}>
|
||||
{rows.map(([k, v]) => (
|
||||
<div key={k}>
|
||||
@@ -611,7 +568,7 @@ function QuickDoc({ node, anchor }: { node: DbNode; anchor: { x: number; y: numb
|
||||
openTableData(t.id, t.schema, t.table);
|
||||
}}
|
||||
>
|
||||
<T>Show table data</T>
|
||||
Show table data
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
@@ -639,6 +596,8 @@ export function ObjectDialogs() {
|
||||
addColumn={dialog.addColumn}
|
||||
/>
|
||||
);
|
||||
case "removeSource":
|
||||
return <RemoveSourceDialog source={dialog.source} />;
|
||||
case "sourceUrl":
|
||||
return <SourceUrlDialog />;
|
||||
case "quickDoc":
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import clsx from "clsx";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { EmptyState, IconButton, Spinner, Tabs, showContextMenu, type MenuItem, T } from "@/ui";
|
||||
import { EmptyState, IconButton, Spinner, Tabs, showContextMenu, type MenuItem } from "@/ui";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { EXPORT_FORMATS, exportData, type ExportData, type ExportFormat } from "./export";
|
||||
import { Grid } from "./Grid";
|
||||
@@ -68,10 +68,7 @@ async function saveExport(format: ExportFormat, data: ExportData) {
|
||||
let path: string | null;
|
||||
try {
|
||||
const { save } = await import("@tauri-apps/plugin-dialog");
|
||||
path = await save({
|
||||
defaultPath: `${data.table}.${f.extension}`,
|
||||
filters: [{ name: f.label, extensions: [f.extension] }],
|
||||
});
|
||||
path = await save({ defaultPath: `${data.table}.${f.extension}`, filters: [{ name: f.label, extensions: [f.extension] }] });
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
@@ -80,26 +77,21 @@ async function saveExport(format: ExportFormat, data: ExportData) {
|
||||
await call(commands.dbExportFile(path, exportData(format, data)));
|
||||
notifications().notify({ level: "info", title: `${data.rows.length} rows exported`, body: path, key: "db-export" });
|
||||
} catch (e) {
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: "Cannot export data",
|
||||
body: e instanceof Error ? e.message : String(e),
|
||||
});
|
||||
notifications().notify({ level: "error", title: "Cannot export data", body: e instanceof Error ? e.message : String(e) });
|
||||
}
|
||||
}
|
||||
|
||||
function exportMenu(data: ExportData): MenuItem[] {
|
||||
return [
|
||||
...EXPORT_FORMATS.map((f): MenuItem => ({
|
||||
label: `Copy as ${f.label}`,
|
||||
icon: "copy",
|
||||
run: () => void navigator.clipboard?.writeText(exportData(f.id, data)),
|
||||
})),
|
||||
...EXPORT_FORMATS.map(
|
||||
(f): MenuItem => ({
|
||||
label: `Copy as ${f.label}`,
|
||||
icon: "copy",
|
||||
run: () => void navigator.clipboard?.writeText(exportData(f.id, data)),
|
||||
}),
|
||||
),
|
||||
{ kind: "separator" },
|
||||
...EXPORT_FORMATS.map((f): MenuItem => ({
|
||||
label: `Export to ${f.label} File…`,
|
||||
run: () => void saveExport(f.id, data),
|
||||
})),
|
||||
...EXPORT_FORMATS.map((f): MenuItem => ({ label: `Export to ${f.label} File…`, run: () => void saveExport(f.id, data) })),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -145,11 +137,7 @@ export function ResultsView() {
|
||||
const active = useDatabase((s) => s.activeResult);
|
||||
const hasOutput = useDatabase((s) => s.output.length > 0);
|
||||
if (!results.length && !hasOutput)
|
||||
return (
|
||||
<EmptyState title="No results">
|
||||
<T>Execute a statement in a query console with ⌘↩.</T>
|
||||
</EmptyState>
|
||||
);
|
||||
return <EmptyState title="No results">Execute a statement in a query console with ⌘↩.</EmptyState>;
|
||||
const tab = results.find((r) => r.id === active);
|
||||
return (
|
||||
<div className={styles.view}>
|
||||
|
||||
@@ -4,16 +4,8 @@
|
||||
* together in one transaction. Tables without a primary key are read-only.
|
||||
*/
|
||||
import { useEffect, useState } from "react";
|
||||
import {
|
||||
call,
|
||||
commands,
|
||||
isCancelled,
|
||||
nextRequestId,
|
||||
type DbSortKey,
|
||||
type DbTablePage,
|
||||
type RequestId,
|
||||
} from "@/platform/ipc";
|
||||
import { Button, EmptyState, IconButton, Input, Select, Spinner, T } from "@/ui";
|
||||
import { call, commands, isCancelled, nextRequestId, type DbSortKey, type DbTablePage, type RequestId } from "@/platform/ipc";
|
||||
import { Button, EmptyState, IconButton, Input, Select, Spinner } from "@/ui";
|
||||
import { notifications, type EditorInput } from "@/workbench/contributions";
|
||||
import { Grid } from "./Grid";
|
||||
import { buildRowEdits, emptyEdits, hasEdits, type Cell, type PendingEdits } from "./model";
|
||||
@@ -55,12 +47,7 @@ export function TableEditor({ input }: { input: EditorInput }) {
|
||||
setLoadedPage({ key, page: p, error: null });
|
||||
setEdits(emptyEdits());
|
||||
} catch (e) {
|
||||
if (!isCancelled(e))
|
||||
setLoadedPage((prev) => ({
|
||||
key,
|
||||
page: prev?.page ?? null,
|
||||
error: e instanceof Error ? e.message : String(e),
|
||||
}));
|
||||
if (!isCancelled(e)) setLoadedPage((prev) => ({ key, page: prev?.page ?? null, error: e instanceof Error ? e.message : String(e) }));
|
||||
} finally {
|
||||
done = true;
|
||||
}
|
||||
@@ -197,10 +184,10 @@ export function TableEditor({ input }: { input: EditorInput }) {
|
||||
onClick={() => setEdits((e) => ({ ...e, inserts: [...e.inserts, new Map()] }))}
|
||||
/>
|
||||
<Button size="small" variant="primary" disabled={!dirty} onClick={() => void submit()}>
|
||||
<T>Submit</T>
|
||||
Submit
|
||||
</Button>
|
||||
<Button size="small" disabled={!dirty} onClick={() => setEdits(emptyEdits())}>
|
||||
<T>Revert</T>
|
||||
Revert
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -21,7 +21,6 @@ import {
|
||||
} from "@/platform/ipc";
|
||||
import { editorsFor } from "@/editor/api";
|
||||
import { editorService, notifications, showServiceView, toolWindowService } from "@/workbench/contributions";
|
||||
import { ask, confirm } from "@/workbench/messages";
|
||||
import { connectRemedy, databaseKey, newSourceId, splitTarget } from "./model";
|
||||
import type { DbNode } from "./nodes";
|
||||
import type { DbObjectRef } from "./objects";
|
||||
@@ -67,6 +66,7 @@ export type DialogState =
|
||||
| { kind: "source"; source: DataSource | null; preset?: Partial<DataSource>; password?: string | null }
|
||||
/** Data Source from URL. */
|
||||
| { kind: "sourceUrl" }
|
||||
| { kind: "removeSource"; source: DataSource }
|
||||
/** Rename a data source (`object` null) or a schema object of target `id`. */
|
||||
| { kind: "rename"; id: string; object: DbObjectRef | null }
|
||||
/** Confirm Drop / Truncate, with a preview of the statement. */
|
||||
@@ -79,8 +79,12 @@ export type DialogState =
|
||||
| { kind: "password"; source: DataSource; resolve: (ok: boolean) => void }
|
||||
/** SSH password or key passphrase (`prompt` is the backend's reason). */
|
||||
| { kind: "sshSecret"; source: DataSource; prompt: string; resolve: (ok: boolean) => void }
|
||||
/** Confirm an unknown SSH host key (`prompt` names it with its fingerprint). */
|
||||
| { kind: "hostKey"; source: DataSource; prompt: string; resolve: (ok: boolean) => void }
|
||||
/** Values of query parameters (`null`: cancelled). */
|
||||
| { kind: "params"; names: string[]; resolve: (values: Record<string, string> | null) => void };
|
||||
| { kind: "params"; names: string[]; resolve: (values: Record<string, string> | null) => void }
|
||||
/** Leaving manual commit with changes pending: commit, roll back or stay. */
|
||||
| { kind: "endTransaction"; source: DataSource; resolve: (commit: boolean | null) => void };
|
||||
|
||||
interface DatabaseState {
|
||||
sources: DataSource[];
|
||||
@@ -254,19 +258,6 @@ export async function renameSource(id: string, name: string): Promise<void> {
|
||||
await loadSources();
|
||||
}
|
||||
|
||||
/** Removes the data source after asking (Database tree › Drop on a source). */
|
||||
export async function removeSource(source: DataSource): Promise<void> {
|
||||
const ok = await confirm({
|
||||
title: "Remove Data Source",
|
||||
message: `Remove data source '${source.name}'? Its query console file stays on disk.`,
|
||||
ok: "Remove",
|
||||
});
|
||||
if (!ok) return;
|
||||
const id = source.id ?? "";
|
||||
if (connectedTargets(id).length) await disconnect(id);
|
||||
await deleteSource(id);
|
||||
}
|
||||
|
||||
export async function deleteSource(id: string): Promise<void> {
|
||||
await call(commands.dbSaveSources(useDatabase.getState().sources.filter((s) => s.id !== id)));
|
||||
forget(id);
|
||||
@@ -290,18 +281,8 @@ function askPassword(source: DataSource): Promise<boolean> {
|
||||
return new Promise((resolve) => useDatabase.setState({ dialog: { kind: "password", source, resolve } }));
|
||||
}
|
||||
|
||||
function askSshSecret(source: DataSource, prompt: string): Promise<boolean> {
|
||||
return new Promise((resolve) => useDatabase.setState({ dialog: { kind: "sshSecret", source, prompt, resolve } }));
|
||||
}
|
||||
|
||||
/** First connection to an SSH host: trust its key (added to ~/.ssh/known_hosts)? */
|
||||
function askTrustHost(prompt: string): Promise<boolean> {
|
||||
return confirm({
|
||||
title: "Unknown SSH Host",
|
||||
icon: "warning",
|
||||
message: `${prompt}. The authenticity of the host cannot be established. Trust it and add the key to ~/.ssh/known_hosts?`,
|
||||
ok: "Trust and Connect",
|
||||
});
|
||||
function ask(kind: "sshSecret" | "hostKey", source: DataSource, prompt: string): Promise<boolean> {
|
||||
return new Promise((resolve) => useDatabase.setState({ dialog: { kind, source, prompt, resolve } }));
|
||||
}
|
||||
|
||||
/** Asks the user what a failed connection needs (password, SSH secret, host key trust); false = give up. */
|
||||
@@ -311,9 +292,9 @@ export async function resolveConnectError(e: unknown, source: DataSource): Promi
|
||||
case "password":
|
||||
return askPassword(source);
|
||||
case "sshSecret":
|
||||
return askSshSecret(source, e.message);
|
||||
return ask("sshSecret", source, e.message);
|
||||
case "trustHostKey":
|
||||
if (!(await askTrustHost(e.message))) return false;
|
||||
if (!(await ask("hostKey", source, e.message))) return false;
|
||||
await call(commands.dbTrustSshHost(source.id ?? ""));
|
||||
return true;
|
||||
default:
|
||||
@@ -772,19 +753,6 @@ export async function finishTransaction(id: string, commit: boolean): Promise<bo
|
||||
}
|
||||
}
|
||||
|
||||
/** Leaving manual commit with changes pending (IDEA asks the same); null when cancelled. */
|
||||
async function askEndTransaction(source: DataSource): Promise<boolean | null> {
|
||||
const { button } = await ask({
|
||||
title: "Switch to Auto-Commit",
|
||||
body: `${source.name} has uncommitted changes. Commit or roll them back before switching to auto-commit?`,
|
||||
buttons: [
|
||||
{ id: "rollback", label: "Roll Back" },
|
||||
{ id: "commit", label: "Commit", primary: true },
|
||||
],
|
||||
});
|
||||
return button === "cancel" ? null : button === "commit";
|
||||
}
|
||||
|
||||
/**
|
||||
* IDEA's Tx: Auto / Manual. Leaving manual mode with changes pending asks
|
||||
* whether to commit or roll them back.
|
||||
@@ -794,7 +762,9 @@ export async function setManualCommit(id: string, manual: boolean): Promise<void
|
||||
if (manual === st.manualCommit.has(id)) return;
|
||||
if (!manual && st.pendingTx.has(id)) {
|
||||
const source = sourceById(id);
|
||||
const commit = source ? await askEndTransaction(source) : false;
|
||||
const commit = source
|
||||
? await new Promise<boolean | null>((resolve) => useDatabase.setState({ dialog: { kind: "endTransaction", source, resolve } }))
|
||||
: false;
|
||||
if (commit === null || !(await finishTransaction(id, commit))) return;
|
||||
}
|
||||
await call(commands.dbSetManualCommit(id, manual));
|
||||
|
||||
@@ -33,7 +33,6 @@ import {
|
||||
tablesKey,
|
||||
useDatabase,
|
||||
withConnection,
|
||||
removeSource,
|
||||
} from "./store";
|
||||
import { tableInput } from "./tableInput";
|
||||
|
||||
@@ -258,7 +257,7 @@ export function registerDatabaseTreeActions(): () => void {
|
||||
const n = nodeFrom(arg);
|
||||
if (!n) return;
|
||||
const id = nodeTarget(n);
|
||||
if (n.kind === "source") return void removeSource(n.source);
|
||||
if (n.kind === "source") return openDialog({ kind: "removeSource", source: n.source });
|
||||
const o = objectOf(n);
|
||||
if (id && o && canDrop(driverOf(id), o)) openDialog({ kind: "drop", id, object: o });
|
||||
},
|
||||
|
||||
@@ -18,9 +18,6 @@ vi.mock("@/platform/ipc", async (orig) => {
|
||||
modulePaths: [],
|
||||
javaHome: "/jdk21",
|
||||
javaExec: "/jdk21/bin/java",
|
||||
errors: [],
|
||||
errorCount: 0,
|
||||
hints: [],
|
||||
});
|
||||
},
|
||||
javaDebugServer: (...a: unknown[]) => {
|
||||
|
||||
@@ -6,13 +6,7 @@
|
||||
*/
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { call, commands, IpcError, type LaunchConfig, type RunConfig } from "@/platform/ipc";
|
||||
import {
|
||||
formatCompileErrors,
|
||||
isJvmApplication,
|
||||
joinJavaArgs,
|
||||
parseJavaArgs,
|
||||
resolveJavaCommand,
|
||||
} from "@/platform/javaLaunch";
|
||||
import { isJvmApplication, joinJavaArgs, parseJavaArgs, resolveJavaCommand } from "@/platform/javaLaunch";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
|
||||
export const JAVA_ADAPTER = "java-debug";
|
||||
@@ -58,14 +52,6 @@ export async function javaLaunchConfig(rc: RunConfig, root: string): Promise<Lau
|
||||
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));
|
||||
if (info.errorCount > 0)
|
||||
notifications().notify({
|
||||
group: "run",
|
||||
level: "warning",
|
||||
key: "debug.java-compile-errors",
|
||||
title: `'${rc.name}' has compile errors; debugging the last compiled classes`,
|
||||
body: formatCompileErrors(info).trimEnd(),
|
||||
});
|
||||
const resolved = resolveJavaCommand(rc, info);
|
||||
const port = await debugServer(module);
|
||||
const classPaths = parsed.explicitClasspath ? parsed.explicitClasspath.split(/[:;]/) : info.classPaths;
|
||||
|
||||
@@ -19,7 +19,6 @@ import {
|
||||
showContextMenu,
|
||||
type MenuItem,
|
||||
type TabItem,
|
||||
T,
|
||||
} from "@/ui";
|
||||
import { setMuted, useBreakpoints } from "../breakpoints/store";
|
||||
import { frameLabel, groupFrames } from "../frames";
|
||||
@@ -142,8 +141,7 @@ export function DebugToolWindow() {
|
||||
return (
|
||||
<div className={styles.emptyWrap}>
|
||||
<EmptyState title="Not debugging">
|
||||
<T>Start a debug configuration with</T> <Kbd action="run.debug" />{" "}
|
||||
<T>or click a line number to set a breakpoint.</T>
|
||||
Start a debug configuration with <Kbd action="run.debug" /> or click a line number to set a breakpoint.
|
||||
</EmptyState>
|
||||
</div>
|
||||
);
|
||||
@@ -620,3 +618,4 @@ function ConsoleView({ session }: { session: DebugSession }) {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import { basename, relativePath, useProject } from "@/platform/project";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { call, commands, type AttachableProcess, type RunConfig, type Variable } from "@/platform/ipc";
|
||||
import { maybeEditorService, notifications } from "@/workbench/contributions";
|
||||
import { Button, Checkbox, Dialog, Icon, IconButton, Input, Kbd, List, Popup, Toggle, T } from "@/ui";
|
||||
import { Button, Checkbox, Dialog, Icon, IconButton, Input, Kbd, List, Popup, Toggle } from "@/ui";
|
||||
import { isConditional, type BreakpointEntry } from "../breakpoints/model";
|
||||
import {
|
||||
removeAllBreakpoints,
|
||||
@@ -117,9 +117,7 @@ function BreakpointEditor({
|
||||
label="Enabled"
|
||||
/>
|
||||
<label className={styles.field}>
|
||||
<span className={styles.label}>
|
||||
<T>Condition</T>
|
||||
</span>
|
||||
<span className={styles.label}>Condition</span>
|
||||
<Input
|
||||
mono
|
||||
value={condition}
|
||||
@@ -131,9 +129,7 @@ function BreakpointEditor({
|
||||
/>
|
||||
</label>
|
||||
<label className={styles.field}>
|
||||
<span className={styles.label}>
|
||||
<T>Hit count</T>
|
||||
</span>
|
||||
<span className={styles.label}>Hit count</span>
|
||||
<Input
|
||||
mono
|
||||
value={hitCondition}
|
||||
@@ -164,7 +160,7 @@ function BreakpointEditor({
|
||||
void executeAction("debug.viewBreakpoints");
|
||||
}}
|
||||
>
|
||||
<T>More</T> <Kbd action="debug.viewBreakpoints" />
|
||||
More <Kbd action="debug.viewBreakpoints" />
|
||||
</button>
|
||||
<div className={styles.spacer} />
|
||||
<Button
|
||||
@@ -175,10 +171,10 @@ function BreakpointEditor({
|
||||
closeBreakpointPopover();
|
||||
}}
|
||||
>
|
||||
<T>Remove</T>
|
||||
Remove
|
||||
</Button>
|
||||
<Button size="small" variant="primary" onClick={close}>
|
||||
<T>Done</T>
|
||||
Done
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -207,9 +203,7 @@ function SpecialEditor({ bp, at }: { bp: SpecialBreakpoint; at: { x: number; y:
|
||||
</div>
|
||||
<Checkbox checked={bp.enabled} onChange={(enabled) => updateSpecial(bp.id, { enabled })} label="Enabled" />
|
||||
<label className={styles.field}>
|
||||
<span className={styles.label}>
|
||||
<T>Condition</T>
|
||||
</span>
|
||||
<span className={styles.label}>Condition</span>
|
||||
<Input
|
||||
mono
|
||||
value={condition}
|
||||
@@ -220,9 +214,7 @@ function SpecialEditor({ bp, at }: { bp: SpecialBreakpoint; at: { x: number; y:
|
||||
/>
|
||||
</label>
|
||||
<label className={styles.field}>
|
||||
<span className={styles.label}>
|
||||
<T>Hit count</T>
|
||||
</span>
|
||||
<span className={styles.label}>Hit count</span>
|
||||
<Input
|
||||
mono
|
||||
value={hitCondition}
|
||||
@@ -240,7 +232,7 @@ function SpecialEditor({ bp, at }: { bp: SpecialBreakpoint; at: { x: number; y:
|
||||
void executeAction("debug.viewBreakpoints");
|
||||
}}
|
||||
>
|
||||
<T>More</T> <Kbd action="debug.viewBreakpoints" />
|
||||
More <Kbd action="debug.viewBreakpoints" />
|
||||
</button>
|
||||
<div className={styles.spacer} />
|
||||
<Button
|
||||
@@ -251,10 +243,10 @@ function SpecialEditor({ bp, at }: { bp: SpecialBreakpoint; at: { x: number; y:
|
||||
closeBreakpointPopover();
|
||||
}}
|
||||
>
|
||||
<T>Remove</T>
|
||||
Remove
|
||||
</Button>
|
||||
<Button size="small" variant="primary" onClick={close}>
|
||||
<T>Done</T>
|
||||
Done
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -292,14 +284,8 @@ function BreakpointsDialog() {
|
||||
if (list.length) out.push({ type: "section", key: `section:${label}`, label }, ...list);
|
||||
};
|
||||
section("Line Breakpoints", lines);
|
||||
section(
|
||||
"Method Breakpoints",
|
||||
methods.map((bp) => ({ type: "special" as const, key: bp.id, bp })),
|
||||
);
|
||||
section(
|
||||
"Field Watchpoints",
|
||||
fields.map((bp) => ({ type: "special" as const, key: bp.id, bp })),
|
||||
);
|
||||
section("Method Breakpoints", methods.map((bp) => ({ type: "special" as const, key: bp.id, bp })));
|
||||
section("Field Watchpoints", fields.map((bp) => ({ type: "special" as const, key: bp.id, bp })));
|
||||
return out;
|
||||
}, [byFile, methods, fields]);
|
||||
const items = rows.filter((r) => r.type !== "section");
|
||||
@@ -342,13 +328,7 @@ function BreakpointsDialog() {
|
||||
size="small"
|
||||
onClick={() => setSelected(addMethodBreakpoint("").id)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="trash"
|
||||
title="Remove All Breakpoints"
|
||||
size="small"
|
||||
disabled={!items.length}
|
||||
onClick={removeAll}
|
||||
/>
|
||||
<IconButton icon="trash" title="Remove All Breakpoints" size="small" disabled={!items.length} onClick={removeAll} />
|
||||
</div>
|
||||
<List
|
||||
items={rows}
|
||||
@@ -360,11 +340,7 @@ function BreakpointsDialog() {
|
||||
onActivate={(r) => goTo(r)}
|
||||
aria-label="All breakpoints"
|
||||
className={styles.bpList}
|
||||
empty={
|
||||
<div className={styles.empty}>
|
||||
<T>No breakpoints. Click a line number to add one.</T>
|
||||
</div>
|
||||
}
|
||||
empty={<div className={styles.empty}>No breakpoints. Click a line number to add one.</div>}
|
||||
renderItem={(r) => {
|
||||
if (r.type === "section") return null;
|
||||
if (r.type === "special") {
|
||||
@@ -441,29 +417,16 @@ function ExceptionBreakpoints({ open }: { open: boolean }) {
|
||||
}, [open]);
|
||||
return (
|
||||
<section className={styles.exceptions} aria-label="Exception breakpoints">
|
||||
<div className={styles.exceptionsTitle}>
|
||||
<T>Exception Breakpoints</T>
|
||||
</div>
|
||||
<div className={styles.exceptionsTitle}>Exception Breakpoints</div>
|
||||
{groups.length === 0 ? (
|
||||
<div className={styles.exceptionsEmpty}>
|
||||
<T>Start a debug session to see the exception filters of its adapter.</T>
|
||||
</div>
|
||||
<div className={styles.exceptionsEmpty}>Start a debug session to see the exception filters of its adapter.</div>
|
||||
) : (
|
||||
groups.map((g) => (
|
||||
<div
|
||||
key={g.adapter}
|
||||
className={styles.exceptionGroup}
|
||||
role="group"
|
||||
aria-label={`${g.adapter} exception filters`}
|
||||
>
|
||||
<div key={g.adapter} className={styles.exceptionGroup} role="group" aria-label={`${g.adapter} exception filters`}>
|
||||
{groups.length > 1 && <div className={styles.exceptionAdapter}>{g.adapter}</div>}
|
||||
{g.filters.map((f) => (
|
||||
<span key={f.filter} title={f.description ?? undefined} className={styles.exceptionRow}>
|
||||
<Checkbox
|
||||
checked={f.enabled}
|
||||
onChange={(on) => setExceptionFilter(g.adapter, f.filter, on)}
|
||||
label={f.label}
|
||||
/>
|
||||
<Checkbox checked={f.enabled} onChange={(on) => setExceptionFilter(g.adapter, f.filter, on)} label={f.label} />
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
@@ -488,19 +451,17 @@ function BreakpointDetail({ row, onGo }: { row: BpRow; onGo: () => void }) {
|
||||
</span>
|
||||
<div className={styles.spacer} />
|
||||
<Button size="small" variant="ghost" onClick={onGo}>
|
||||
<T>Go to Source</T>
|
||||
Go to Source
|
||||
</Button>
|
||||
<Button size="small" variant="ghost" onClick={() => removeBreakpoint(path, bp.id)}>
|
||||
<T>Remove</T>
|
||||
Remove
|
||||
</Button>
|
||||
</div>
|
||||
{st && <div className={styles.statusLine}>{st.verified ? "Verified" : (st.message ?? "Not verified")}</div>}
|
||||
<Checkbox checked={bp.enabled} onChange={(enabled) => commit({ enabled })} label="Enabled" />
|
||||
<Checkbox checked={!!bp.temporary} onChange={(temporary) => commit({ temporary })} label="Remove once hit" />
|
||||
<label className={styles.field}>
|
||||
<span className={styles.label}>
|
||||
<T>Condition</T>
|
||||
</span>
|
||||
<span className={styles.label}>Condition</span>
|
||||
<Input
|
||||
mono
|
||||
value={condition}
|
||||
@@ -510,9 +471,7 @@ function BreakpointDetail({ row, onGo }: { row: BpRow; onGo: () => void }) {
|
||||
/>
|
||||
</label>
|
||||
<label className={styles.field}>
|
||||
<span className={styles.label}>
|
||||
<T>Hit count</T>
|
||||
</span>
|
||||
<span className={styles.label}>Hit count</span>
|
||||
<Input
|
||||
mono
|
||||
value={hitCondition}
|
||||
@@ -522,9 +481,7 @@ function BreakpointDetail({ row, onGo }: { row: BpRow; onGo: () => void }) {
|
||||
/>
|
||||
</label>
|
||||
<label className={styles.field}>
|
||||
<span className={styles.label}>
|
||||
<T>Log message</T>
|
||||
</span>
|
||||
<span className={styles.label}>Log message</span>
|
||||
<Input
|
||||
mono
|
||||
value={logMessage}
|
||||
@@ -551,20 +508,18 @@ function SpecialDetail({ bp, onGo }: { bp: SpecialBreakpoint; onGo: () => void }
|
||||
<div className={styles.spacer} />
|
||||
{bp.path && (
|
||||
<Button size="small" variant="ghost" onClick={onGo}>
|
||||
<T>Go to Source</T>
|
||||
Go to Source
|
||||
</Button>
|
||||
)}
|
||||
<Button size="small" variant="ghost" onClick={() => removeSpecial(bp.id)}>
|
||||
<T>Remove</T>
|
||||
Remove
|
||||
</Button>
|
||||
</div>
|
||||
{st && <div className={styles.statusLine}>{st.verified ? "Verified" : (st.message ?? "Not verified")}</div>}
|
||||
<Checkbox checked={bp.enabled} onChange={(enabled) => updateSpecial(bp.id, { enabled })} label="Enabled" />
|
||||
{bp.kind === "method" ? (
|
||||
<label className={styles.field}>
|
||||
<span className={styles.label}>
|
||||
<T>Method</T>
|
||||
</span>
|
||||
<span className={styles.label}>Method</span>
|
||||
<Input
|
||||
mono
|
||||
value={name}
|
||||
@@ -579,9 +534,7 @@ function SpecialDetail({ bp, onGo }: { bp: SpecialBreakpoint; onGo: () => void }
|
||||
<>
|
||||
<div className={styles.statusLine}>Watching {bp.dataId}</div>
|
||||
<label className={styles.field}>
|
||||
<span className={styles.label}>
|
||||
<T>Suspend on</T>
|
||||
</span>
|
||||
<span className={styles.label}>Suspend on</span>
|
||||
<span className={styles.exceptionGroup}>
|
||||
<Checkbox
|
||||
checked={bp.accessType !== "read"}
|
||||
@@ -600,9 +553,7 @@ function SpecialDetail({ bp, onGo }: { bp: SpecialBreakpoint; onGo: () => void }
|
||||
</>
|
||||
)}
|
||||
<label className={styles.field}>
|
||||
<span className={styles.label}>
|
||||
<T>Condition</T>
|
||||
</span>
|
||||
<span className={styles.label}>Condition</span>
|
||||
<Input
|
||||
mono
|
||||
value={condition}
|
||||
@@ -612,9 +563,7 @@ function SpecialDetail({ bp, onGo }: { bp: SpecialBreakpoint; onGo: () => void }
|
||||
/>
|
||||
</label>
|
||||
<label className={styles.field}>
|
||||
<span className={styles.label}>
|
||||
<T>Hit count</T>
|
||||
</span>
|
||||
<span className={styles.label}>Hit count</span>
|
||||
<Input
|
||||
mono
|
||||
value={hitCondition}
|
||||
@@ -667,7 +616,7 @@ function EvaluateDialogInner({ initial }: { initial: string }) {
|
||||
}}
|
||||
disabled={!expression.trim()}
|
||||
>
|
||||
<T>Add to Watches</T>
|
||||
Add to Watches
|
||||
</Button>
|
||||
}
|
||||
buttons={[
|
||||
@@ -677,9 +626,7 @@ function EvaluateDialogInner({ initial }: { initial: string }) {
|
||||
>
|
||||
<div className={styles.evalBody}>
|
||||
<label className={styles.field}>
|
||||
<span className={styles.label}>
|
||||
<T>Expression</T>
|
||||
</span>
|
||||
<span className={styles.label}>Expression</span>
|
||||
<Input
|
||||
mono
|
||||
value={expression}
|
||||
@@ -809,9 +756,7 @@ function AttachPopup() {
|
||||
aria-label="Filter processes"
|
||||
/>
|
||||
{state.processes == null ? (
|
||||
<div className={styles.empty}>
|
||||
<T>Loading processes…</T>
|
||||
</div>
|
||||
<div className={styles.empty}>Loading processes…</div>
|
||||
) : state.error ? (
|
||||
<div className={styles.empty}>{state.error}</div>
|
||||
) : (
|
||||
|
||||
@@ -21,7 +21,6 @@ import {
|
||||
Tabs,
|
||||
showContextMenu,
|
||||
type MenuItem,
|
||||
T,
|
||||
} from "@/ui";
|
||||
import {
|
||||
checksSummary,
|
||||
@@ -44,11 +43,7 @@ const STATES: Array<{ value: PrStateFilter; label: string }> = [
|
||||
];
|
||||
|
||||
function Unavailable({ availability }: { availability: GhAvailability }) {
|
||||
const retry = (
|
||||
<Button size="small" onClick={() => void refreshAll()}>
|
||||
<T>Retry</T>
|
||||
</Button>
|
||||
);
|
||||
const retry = <Button size="small" onClick={() => void refreshAll()}>Retry</Button>;
|
||||
switch (availability.kind) {
|
||||
case "notInstalled":
|
||||
return (
|
||||
@@ -56,15 +51,12 @@ function Unavailable({ availability }: { availability: GhAvailability }) {
|
||||
title="GitHub CLI is not installed"
|
||||
actions={
|
||||
<>
|
||||
<Button size="small" onClick={() => void openUrl("https://cli.github.com")}>
|
||||
<T>Install gh…</T>
|
||||
</Button>
|
||||
<Button size="small" onClick={() => void openUrl("https://cli.github.com")}>Install gh…</Button>
|
||||
{retry}
|
||||
</>
|
||||
}
|
||||
>
|
||||
<T>Pull requests use the</T> <code>gh</code> <T>command line tool. Install it, then run</T>{" "}
|
||||
<code>gh auth login</code>.
|
||||
Pull requests use the <code>gh</code> command line tool. Install it, then run <code>gh auth login</code>.
|
||||
</EmptyState>
|
||||
);
|
||||
case "notLoggedIn":
|
||||
@@ -76,29 +68,21 @@ function Unavailable({ availability }: { availability: GhAvailability }) {
|
||||
<Button
|
||||
size="small"
|
||||
variant="primary"
|
||||
onClick={() =>
|
||||
void executeAction("terminal.runCommand", {
|
||||
program: "gh",
|
||||
args: ["auth", "login"],
|
||||
name: "gh auth login",
|
||||
})
|
||||
}
|
||||
onClick={() => void executeAction("terminal.runCommand", { program: "gh", args: ["auth", "login"], name: "gh auth login" })}
|
||||
>
|
||||
<T>Run gh auth login</T>
|
||||
Run gh auth login
|
||||
</Button>
|
||||
{retry}
|
||||
</>
|
||||
}
|
||||
>
|
||||
<T>Run</T> <code>gh auth login</code> <T>in a terminal, then retry.</T>
|
||||
Run <code>gh auth login</code> in a terminal, then retry.
|
||||
</EmptyState>
|
||||
);
|
||||
case "notGitHub":
|
||||
return (
|
||||
<EmptyState title="No GitHub repository" actions={retry}>
|
||||
<div>
|
||||
<T>This project has no remote on GitHub.</T>
|
||||
</div>
|
||||
<div>This project has no remote on GitHub.</div>
|
||||
<div className={styles.hint}>{availability.message}</div>
|
||||
</EmptyState>
|
||||
);
|
||||
@@ -129,21 +113,11 @@ function Filters() {
|
||||
}, [search]);
|
||||
return (
|
||||
<div className={styles.filters}>
|
||||
<SearchField
|
||||
value={search}
|
||||
onChange={setSearch}
|
||||
placeholder="Search (GitHub syntax)"
|
||||
aria-label="Search pull requests"
|
||||
className={styles.search}
|
||||
/>
|
||||
<SearchField value={search} onChange={setSearch} placeholder="Search (GitHub syntax)" aria-label="Search pull requests" className={styles.search} />
|
||||
<div className={styles.filterRow}>
|
||||
<Select value={query.state} options={STATES} onChange={(state) => setQuery({ state })} aria-label="State" />
|
||||
<Checkbox checked={query.authorMe} onChange={(authorMe) => setQuery({ authorMe })} label="Mine" />
|
||||
<Checkbox
|
||||
checked={query.reviewRequested}
|
||||
onChange={(reviewRequested) => setQuery({ reviewRequested })}
|
||||
label="Review requested"
|
||||
/>
|
||||
<Checkbox checked={query.reviewRequested} onChange={(reviewRequested) => setQuery({ reviewRequested })} label="Review requested" />
|
||||
<span className={styles.flex} />
|
||||
{loading ? <Spinner size={14} /> : <IconButton icon="refresh" size="small" action="github.refresh" />}
|
||||
<IconButton icon="plus" size="small" action="github.createPullRequest" />
|
||||
@@ -210,12 +184,7 @@ function PullRequestList() {
|
||||
|
||||
function Markdown({ text }: { text: string }) {
|
||||
const html = useMarkupHtml({ kind: "markdown", value: text });
|
||||
if (!text.trim())
|
||||
return (
|
||||
<div className={styles.dim}>
|
||||
<T>No description provided.</T>
|
||||
</div>
|
||||
);
|
||||
if (!text.trim()) return <div className={styles.dim}>No description provided.</div>;
|
||||
return (
|
||||
<div
|
||||
className={styles.markdown}
|
||||
@@ -256,33 +225,19 @@ function Overview({ pr }: { pr: PullRequestDetails }) {
|
||||
</span>
|
||||
{c.url && (
|
||||
<button type="button" className={styles.link} onClick={() => void openUrl(c.url!)}>
|
||||
<T>Details</T>
|
||||
Details
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
<section className={styles.section}>
|
||||
<h3 className={styles.sectionTitle}>
|
||||
<T>Reviewers</T>
|
||||
</h3>
|
||||
{pr.reviewers.length === 0 && (
|
||||
<div className={styles.dim}>
|
||||
<T>No reviews</T>
|
||||
</div>
|
||||
)}
|
||||
<h3 className={styles.sectionTitle}>Reviewers</h3>
|
||||
{pr.reviewers.length === 0 && <div className={styles.dim}>No reviews</div>}
|
||||
{pr.reviewers.map((r) => (
|
||||
<div key={r.login} className={styles.checkRow}>
|
||||
<Icon
|
||||
name={
|
||||
r.state === "APPROVED"
|
||||
? "success"
|
||||
: r.state === "CHANGES_REQUESTED"
|
||||
? "error"
|
||||
: r.state === "REQUESTED"
|
||||
? "clock"
|
||||
: "info"
|
||||
}
|
||||
name={r.state === "APPROVED" ? "success" : r.state === "CHANGES_REQUESTED" ? "error" : r.state === "REQUESTED" ? "clock" : "info"}
|
||||
size={14}
|
||||
className={styles[`review-${r.state}`]}
|
||||
/>
|
||||
@@ -321,14 +276,7 @@ function Files({ pr }: { pr: PullRequestDetails }) {
|
||||
{pr.files.map((f) => {
|
||||
const slash = f.path.lastIndexOf("/");
|
||||
return (
|
||||
<button
|
||||
key={f.path}
|
||||
type="button"
|
||||
role="listitem"
|
||||
className={styles.fileRow}
|
||||
onClick={(e) => e.detail <= 1 && void openFileDiff(pr, f)}
|
||||
title={f.path}
|
||||
>
|
||||
<button key={f.path} type="button" role="listitem" className={styles.fileRow} onClick={(e) => e.detail <= 1 && void openFileDiff(pr, f)} title={f.path}>
|
||||
<Icon name="diff" size={14} className={styles[`change-${f.changeType}`]} />
|
||||
<span className={clsx(styles.fileName, styles[`change-${f.changeType}`])}>{f.path.slice(slash + 1)}</span>
|
||||
<span className={clsx(styles.dim, styles.ellipsis)}>{slash > 0 ? f.path.slice(0, slash) : ""}</span>
|
||||
@@ -356,11 +304,7 @@ function Commits({ pr }: { pr: PullRequestDetails }) {
|
||||
e.preventDefault();
|
||||
showContextMenu({ x: e.clientX, y: e.clientY }, [
|
||||
{ label: "Copy Revision Number", icon: "copy", run: () => void navigator.clipboard?.writeText(c.oid) },
|
||||
{
|
||||
label: "Open in Browser",
|
||||
icon: "external-link",
|
||||
run: () => void openUrl(`${pr.summary.url}/commits/${c.oid}`),
|
||||
},
|
||||
{ label: "Open in Browser", icon: "external-link", run: () => void openUrl(`${pr.summary.url}/commits/${c.oid}`) },
|
||||
]);
|
||||
}}
|
||||
>
|
||||
@@ -386,19 +330,13 @@ function Conversation({ pr }: { pr: PullRequestDetails }) {
|
||||
<article key={i} className={styles.comment}>
|
||||
<header className={styles.commentHead}>
|
||||
<strong>{t.author}</strong>
|
||||
{t.reviewState && (
|
||||
<span className={styles[`review-${t.reviewState}`]}>{reviewStateLabel(t.reviewState)}</span>
|
||||
)}
|
||||
{t.reviewState && <span className={styles[`review-${t.reviewState}`]}>{reviewStateLabel(t.reviewState)}</span>}
|
||||
<span className={styles.dim}>{relativeTime(t.createdAt)}</span>
|
||||
</header>
|
||||
{t.body.trim() && <Markdown text={t.body} />}
|
||||
</article>
|
||||
))}
|
||||
{threads.length > 0 && (
|
||||
<h3 className={styles.sectionTitle}>
|
||||
<T>Review comments</T>
|
||||
</h3>
|
||||
)}
|
||||
{threads.length > 0 && <h3 className={styles.sectionTitle}>Review comments</h3>}
|
||||
{threads.map((t) => (
|
||||
<article key={t.root.id} className={styles.comment}>
|
||||
<header className={styles.commentHead}>
|
||||
@@ -439,7 +377,7 @@ function Conversation({ pr }: { pr: PullRequestDetails }) {
|
||||
setPosting(false);
|
||||
}}
|
||||
>
|
||||
<T>Comment</T>
|
||||
Comment
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -458,7 +396,7 @@ function Details() {
|
||||
if (error) return <EmptyState title="Could not load the pull request">{error}</EmptyState>;
|
||||
return loading ? (
|
||||
<div className={styles.loading}>
|
||||
<Spinner size={14} /> <T>Loading…</T>
|
||||
<Spinner size={14} /> Loading…
|
||||
</div>
|
||||
) : (
|
||||
<EmptyState title="Select a pull request" />
|
||||
@@ -485,24 +423,18 @@ function Details() {
|
||||
<span>
|
||||
#{s.number} by <strong>{s.author}</strong> · {s.baseRef} ← {s.headRef}
|
||||
</span>
|
||||
{reviewDecisionLabel(s.reviewDecision) && (
|
||||
<span className={styles.dim}>· {reviewDecisionLabel(s.reviewDecision)}</span>
|
||||
)}
|
||||
{pr.mergeable === "CONFLICTING" && (
|
||||
<span className={styles.conflict}>
|
||||
<T>· Conflicts</T>
|
||||
</span>
|
||||
)}
|
||||
{reviewDecisionLabel(s.reviewDecision) && <span className={styles.dim}>· {reviewDecisionLabel(s.reviewDecision)}</span>}
|
||||
{pr.mergeable === "CONFLICTING" && <span className={styles.conflict}>· Conflicts</span>}
|
||||
</div>
|
||||
<div className={styles.actions}>
|
||||
<Button size="small" icon="branch" onClick={() => void checkoutPullRequest(s.number)}>
|
||||
<T>Checkout</T>
|
||||
Checkout
|
||||
</Button>
|
||||
<Button size="small" icon="edit" onClick={reviewMenu}>
|
||||
<T>Review ▾</T>
|
||||
Review ▾
|
||||
</Button>
|
||||
<Button size="small" icon="external-link" onClick={() => void openUrl(s.url)}>
|
||||
<T>Open in Browser</T>
|
||||
Open in Browser
|
||||
</Button>
|
||||
<span className={styles.flex} />
|
||||
<IconButton icon="refresh" size="small" title="Reload" onClick={() => void loadDetails(s.number)} />
|
||||
@@ -564,7 +496,11 @@ export function PullRequestsView() {
|
||||
if (!useGithub.getState().availability) void refreshAll();
|
||||
}, []);
|
||||
if (!availability)
|
||||
return <div className={styles.loading}>{checking && <Spinner size={14} />} Connecting to GitHub…</div>;
|
||||
return (
|
||||
<div className={styles.loading}>
|
||||
{checking && <Spinner size={14} />} Connecting to GitHub…
|
||||
</div>
|
||||
);
|
||||
if (availability.kind !== "ready")
|
||||
return (
|
||||
<div className={styles.view}>
|
||||
@@ -593,3 +529,4 @@ export function PullRequestsHeader() {
|
||||
if (availability?.kind !== "ready") return null;
|
||||
return <span className={styles.repo}>{availability.repo.nameWithOwner}</span>;
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { Fragment, useEffect, useState, type ReactNode } from "react";
|
||||
import { create } from "zustand";
|
||||
import type { ReviewEvent } from "@/platform/ipc";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { Checkbox, Dialog, Input, Select, T } from "@/ui";
|
||||
import { Checkbox, Dialog, Input, Select } from "@/ui";
|
||||
import styles from "./Github.module.css";
|
||||
|
||||
interface Entry {
|
||||
@@ -45,22 +45,11 @@ export interface CreatePrInput {
|
||||
}
|
||||
|
||||
/** Asks for the new pull request's title, description, base branch and options. */
|
||||
export function createPullRequestDialog(opts: {
|
||||
head: string;
|
||||
defaultBase: string | null;
|
||||
title: string;
|
||||
needsPush: boolean;
|
||||
}) {
|
||||
export function createPullRequestDialog(opts: { head: string; defaultBase: string | null; title: string; needsPush: boolean }) {
|
||||
return open<CreatePrInput>((done) => <CreateDialog {...opts} onDone={done} />);
|
||||
}
|
||||
|
||||
function CreateDialog(props: {
|
||||
head: string;
|
||||
defaultBase: string | null;
|
||||
title: string;
|
||||
needsPush: boolean;
|
||||
onDone: (v: CreatePrInput | null) => void;
|
||||
}) {
|
||||
function CreateDialog(props: { head: string; defaultBase: string | null; title: string; needsPush: boolean; onDone: (v: CreatePrInput | null) => void }) {
|
||||
const [title, setTitle] = useState(props.title);
|
||||
const [body, setBody] = useState("");
|
||||
const [base, setBase] = useState(props.defaultBase ?? "");
|
||||
@@ -71,7 +60,7 @@ function CreateDialog(props: {
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
// Base candidates: branches of the remotes (without `origin/`), the default first.
|
||||
call(commands.vcsBranches(null))
|
||||
call(commands.vcsBranches())
|
||||
.then((branches) => {
|
||||
const names = new Set<string>();
|
||||
if (props.defaultBase) names.add(props.defaultBase);
|
||||
@@ -106,24 +95,11 @@ function CreateDialog(props: {
|
||||
>
|
||||
<div className={styles.form}>
|
||||
<div className={styles.formRow}>
|
||||
<label className={styles.fieldLabel}>
|
||||
<T>Base:</T>
|
||||
</label>
|
||||
<Select
|
||||
value={base || null}
|
||||
options={bases.map((b) => ({ value: b, label: b }))}
|
||||
onChange={setBase}
|
||||
aria-label="Base branch"
|
||||
/>
|
||||
<label className={styles.fieldLabel}>Base:</label>
|
||||
<Select value={base || null} options={bases.map((b) => ({ value: b, label: b }))} onChange={setBase} aria-label="Base branch" />
|
||||
<span className={styles.fieldLabel}>← {props.head}</span>
|
||||
</div>
|
||||
<Input
|
||||
data-autofocus
|
||||
aria-label="Title"
|
||||
placeholder="Title"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
/>
|
||||
<Input data-autofocus aria-label="Title" placeholder="Title" value={title} onChange={(e) => setTitle(e.target.value)} />
|
||||
<textarea
|
||||
aria-label="Description"
|
||||
placeholder="Description (Markdown)"
|
||||
@@ -141,24 +117,14 @@ function CreateDialog(props: {
|
||||
);
|
||||
}
|
||||
|
||||
const REVIEW_LABEL: Record<ReviewEvent, string> = {
|
||||
approve: "Approve",
|
||||
requestChanges: "Request Changes",
|
||||
comment: "Comment",
|
||||
};
|
||||
const REVIEW_LABEL: Record<ReviewEvent, string> = { approve: "Approve", requestChanges: "Request Changes", comment: "Comment" };
|
||||
|
||||
/** Asks for a review comment; resolves with the chosen event and body. */
|
||||
export function reviewDialog(number: number, initial: ReviewEvent) {
|
||||
return open<{ event: ReviewEvent; body: string }>((done) => (
|
||||
<ReviewDialog number={number} initial={initial} onDone={done} />
|
||||
));
|
||||
return open<{ event: ReviewEvent; body: string }>((done) => <ReviewDialog number={number} initial={initial} onDone={done} />);
|
||||
}
|
||||
|
||||
function ReviewDialog(props: {
|
||||
number: number;
|
||||
initial: ReviewEvent;
|
||||
onDone: (v: { event: ReviewEvent; body: string } | null) => void;
|
||||
}) {
|
||||
function ReviewDialog(props: { number: number; initial: ReviewEvent; onDone: (v: { event: ReviewEvent; body: string } | null) => void }) {
|
||||
const [body, setBody] = useState("");
|
||||
const [event, setEvent] = useState<ReviewEvent>(props.initial);
|
||||
const needsBody = event !== "approve";
|
||||
@@ -169,12 +135,7 @@ function ReviewDialog(props: {
|
||||
onClose={() => props.onDone(null)}
|
||||
width={520}
|
||||
buttons={[
|
||||
{
|
||||
label: REVIEW_LABEL[event],
|
||||
role: "default",
|
||||
disabled: needsBody && !body.trim(),
|
||||
onClick: () => props.onDone({ event, body }),
|
||||
},
|
||||
{ label: REVIEW_LABEL[event], role: "default", disabled: needsBody && !body.trim(), onClick: () => props.onDone({ event, body }) },
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
]}
|
||||
>
|
||||
@@ -226,17 +187,8 @@ function NumberDialog(props: { title: string; onDone: (v: number | null) => void
|
||||
if (ok) props.onDone(n);
|
||||
}}
|
||||
>
|
||||
<label className={styles.fieldLabel}>
|
||||
<T>Pull request number:</T>
|
||||
</label>
|
||||
<Input
|
||||
data-autofocus
|
||||
mono
|
||||
aria-label="Pull request number"
|
||||
placeholder="#123"
|
||||
value={value}
|
||||
onChange={(e) => setValue(e.target.value)}
|
||||
/>
|
||||
<label className={styles.fieldLabel}>Pull request number:</label>
|
||||
<Input data-autofocus mono aria-label="Pull request number" placeholder="#123" value={value} onChange={(e) => setValue(e.target.value)} />
|
||||
</form>
|
||||
</Dialog>
|
||||
);
|
||||
|
||||
@@ -89,7 +89,7 @@ export async function createPullRequest() {
|
||||
let needsPush = true;
|
||||
let title = "";
|
||||
try {
|
||||
const info = await call(commands.vcsBranchInfo(null));
|
||||
const info = await call(commands.vcsBranchInfo());
|
||||
head = info.head;
|
||||
needsPush = !info.upstream || info.ahead > 0;
|
||||
if (head) title = head.replace(/^[^/]+\//, "").replace(/[-_]+/g, " ").replace(/^\w/, (c) => c.toUpperCase());
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import type { HttpExchange, HttpHistoryEntry } from "@/platform/ipc";
|
||||
import { EmptyState, IconButton, SplitGroup, SplitHandle, SplitPanel, Spinner, Tabs, T } from "@/ui";
|
||||
import { EmptyState, IconButton, SplitGroup, SplitHandle, SplitPanel, Spinner, Tabs } from "@/ui";
|
||||
import { bodyKind, formatMs, formatSize, prettyBody } from "./format";
|
||||
import { cancelRunning, clearHistory, refreshHistory, selectEntry, useHttpClient } from "./store";
|
||||
import styles from "./HttpClient.module.css";
|
||||
@@ -98,9 +98,7 @@ function ExchangeView({ ex }: { ex: HttpExchange }) {
|
||||
) : (
|
||||
<pre className={styles.pre} aria-label="Response body">
|
||||
{body}
|
||||
{r.truncated && (
|
||||
<span className={styles.truncated}>{`\n… truncated (${formatSize(r.size)} received)`}</span>
|
||||
)}
|
||||
{r.truncated && <span className={styles.truncated}>{`\n… truncated (${formatSize(r.size)} received)`}</span>}
|
||||
</pre>
|
||||
))}
|
||||
{tab === "headers" && r && <HeaderTable headers={r.headers} />}
|
||||
@@ -149,9 +147,7 @@ export function HttpClientView() {
|
||||
</div>
|
||||
)}
|
||||
{history.length === 0 && !running ? (
|
||||
<EmptyState title="No requests yet">
|
||||
<T>Run a request from an .http file with the gutter ▶ or ⌘↩.</T>
|
||||
</EmptyState>
|
||||
<EmptyState title="No requests yet">Run a request from an .http file with the gutter ▶ or ⌘↩.</EmptyState>
|
||||
) : (
|
||||
history.map((h) => <EntryRow key={h.id} entry={h} selected={h.id === selected} />)
|
||||
)}
|
||||
|
||||
@@ -11,16 +11,8 @@ import type { EditorDocContext } from "@/editor/api";
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
import { isVirtualUri } from "@/platform/virtualDocs";
|
||||
import type { HttpRequestBlock } from "@/platform/ipc";
|
||||
import { IconButton, Select, iconMarkup, T } from "@/ui";
|
||||
import {
|
||||
cancelRunning,
|
||||
loadEnvironments,
|
||||
parseRequests,
|
||||
runAll,
|
||||
runRequest,
|
||||
setEnvironment,
|
||||
useHttpClient,
|
||||
} from "./store";
|
||||
import { IconButton, Select, iconMarkup } from "@/ui";
|
||||
import { cancelRunning, loadEnvironments, parseRequests, runAll, runRequest, setEnvironment, useHttpClient } from "./store";
|
||||
import styles from "./HttpClient.module.css";
|
||||
|
||||
export const HTTP_LANGUAGE = "http";
|
||||
@@ -71,11 +63,7 @@ class RequestMarker extends GutterMarker {
|
||||
super();
|
||||
}
|
||||
override eq(other: GutterMarker): boolean {
|
||||
return (
|
||||
other instanceof RequestMarker &&
|
||||
other.request.index === this.request.index &&
|
||||
other.request.url === this.request.url
|
||||
);
|
||||
return other instanceof RequestMarker && other.request.index === this.request.index && other.request.url === this.request.url;
|
||||
}
|
||||
override toDOM(): Node {
|
||||
const el = document.createElement("div");
|
||||
@@ -113,9 +101,7 @@ function Toolbar({ path, view }: { path: string | null; view: EditorView }) {
|
||||
onClick={() => void runAll(path, view.state.doc.toString())}
|
||||
/>
|
||||
<IconButton icon="stop" title="Stop" disabled={!running} onClick={cancelRunning} />
|
||||
<span className={styles.toolbarLabel}>
|
||||
<T>Run with:</T>
|
||||
</span>
|
||||
<span className={styles.toolbarLabel}>Run with:</span>
|
||||
<Select
|
||||
aria-label="Environment"
|
||||
value={chosen && envs?.includes(chosen) ? chosen : ""}
|
||||
|
||||
@@ -20,8 +20,8 @@ import { activate as build } from "./build";
|
||||
import { activate as templates, activateSettingsPages as templatesPages } from "./templates";
|
||||
import { activate as todo, activateSettingsPages as todoPages } from "./todo";
|
||||
import { activate as settings, activateSettingsWindow } from "./settings";
|
||||
import { activate as app, activateLocale as appLocale } from "./app";
|
||||
import { activate as perf } from "./perf";
|
||||
import { activate as app } from "./app";
|
||||
import { activate as perf, activateSettingsPages as perfPages } from "./perf";
|
||||
import { activate as plugins, activateSettingsPages as pluginsPages } from "./plugins";
|
||||
import { activate as tools, activateSettingsPages as toolsPages } from "./tools";
|
||||
import { activate as scratch } from "./scratch";
|
||||
@@ -86,11 +86,11 @@ export { SettingsWindow, settingsWindowParent } from "./settings";
|
||||
*/
|
||||
export function activateSettingsWindowFeatures(parent: string): () => void {
|
||||
const pages: Array<[string, Activate]> = [
|
||||
["locale", appLocale],
|
||||
["settings", () => activateSettingsWindow(parent)],
|
||||
["templates", templatesPages],
|
||||
["todo", todoPages],
|
||||
["plugins", pluginsPages],
|
||||
["perf", perfPages],
|
||||
["tools", toolsPages],
|
||||
];
|
||||
const disposers: Array<() => void> = [];
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
*/
|
||||
import { useEffect, useRef } from "react";
|
||||
import clsx from "clsx";
|
||||
import { BarButton, Button, Popup, T } from "@/ui";
|
||||
import { BarButton, Button, Popup } from "@/ui";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { isTauri, type AppMetrics } from "@/platform/ipc";
|
||||
import { formatBytes, formatCount, formatMs, formatSize, formatUptime } from "./format";
|
||||
@@ -109,9 +109,7 @@ export function MemoryDetails({ metrics: m }: { metrics: AppMetrics }) {
|
||||
))}
|
||||
<div className={styles.section}>
|
||||
<div className={styles.groupRow}>
|
||||
<span className={styles.groupTitle}>
|
||||
<T>Total</T>
|
||||
</span>
|
||||
<span className={styles.groupTitle}>Total</span>
|
||||
<span className={styles.value}>{formatSize(summary.total)}</span>
|
||||
</div>
|
||||
<Row label="Physical memory" value={formatSize(m.totalMemoryBytes)} />
|
||||
@@ -139,7 +137,7 @@ export function MemoryDetails({ metrics: m }: { metrics: AppMetrics }) {
|
||||
{error && <div className={styles.error}>{error}</div>}
|
||||
<div className={styles.actions}>
|
||||
<Button size="small" icon="trash" onClick={() => void executeAction("file.invalidateCaches")}>
|
||||
<T>Clear caches</T>
|
||||
Clear caches
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
.page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 22px;
|
||||
max-width: 680px;
|
||||
}
|
||||
.title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
height: 22px;
|
||||
margin-bottom: 6px;
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
.rule {
|
||||
flex: 1;
|
||||
height: 1px;
|
||||
background: var(--border);
|
||||
}
|
||||
.body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding-left: 18px;
|
||||
}
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-height: 26px;
|
||||
}
|
||||
.label {
|
||||
color: var(--fg);
|
||||
min-width: 220px;
|
||||
}
|
||||
.value {
|
||||
min-width: 72px;
|
||||
text-align: right;
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-small);
|
||||
font-variant-numeric: tabular-nums;
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
.meter {
|
||||
position: relative;
|
||||
height: 8px;
|
||||
max-width: 420px;
|
||||
margin: 4px 0 8px;
|
||||
border-radius: var(--radius-small);
|
||||
background: var(--bg-control);
|
||||
overflow: hidden;
|
||||
}
|
||||
.fill {
|
||||
position: absolute;
|
||||
inset: 0 auto 0 0;
|
||||
background: var(--accent);
|
||||
}
|
||||
.hint {
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
.error {
|
||||
color: var(--danger);
|
||||
}
|
||||
.empty {
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
.strong .label,
|
||||
.strong .value {
|
||||
color: var(--fg-strong);
|
||||
font-weight: 600;
|
||||
}
|
||||
.indented .label {
|
||||
padding-left: 16px;
|
||||
min-width: 204px;
|
||||
}
|
||||
.group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
/**
|
||||
* Settings › Memory Usage: memory of OpenIDEA, its language servers and other
|
||||
* processes, subsystem sizes, "Clear caches" and the status bar indicator toggle.
|
||||
*/
|
||||
import { useEffect, type ReactNode } from "react";
|
||||
import clsx from "clsx";
|
||||
import { Button, Checkbox } from "@/ui";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { isTauri } from "@/platform/ipc";
|
||||
import { isStatusItemVisible, setStatusWidgetVisible, useStatusWidgetOverrides } from "@/workbench/statusBarWidgets";
|
||||
import { formatBytes, formatCount, formatMs, formatSize, formatUptime, memoryRatio } from "./format";
|
||||
import { memorySections, summarizeMemory } from "./memory";
|
||||
import { MEMORY_WIDGET } from "./MemoryStatus";
|
||||
import { startPolling } from "./poll";
|
||||
import { refreshMetrics, usePerf } from "./store";
|
||||
import styles from "./MemoryUsage.module.css";
|
||||
|
||||
function Row({
|
||||
label,
|
||||
value,
|
||||
strong,
|
||||
indented,
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
strong?: boolean;
|
||||
indented?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<div className={clsx(styles.row, strong && styles.strong, indented && styles.indented)}>
|
||||
<span className={styles.label}>{label}:</span>
|
||||
<span className={styles.value}>{value}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** The same setting as the status bar context menu's "Memory Indicator". */
|
||||
function IndicatorToggle() {
|
||||
const overrides = useStatusWidgetOverrides();
|
||||
const shown = isStatusItemVisible(MEMORY_WIDGET, overrides);
|
||||
return (
|
||||
<Checkbox
|
||||
checked={shown}
|
||||
onChange={(on) => void setStatusWidgetVisible(MEMORY_WIDGET.id, on)}
|
||||
label="Show memory indicator in the status bar"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function Section({ title, children }: { title: string; children: ReactNode }) {
|
||||
return (
|
||||
<section className={styles.section} aria-label={title}>
|
||||
<div className={styles.title}>
|
||||
{title}
|
||||
<span className={styles.rule} aria-hidden />
|
||||
</div>
|
||||
<div className={styles.body}>{children}</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export function MemoryUsagePage() {
|
||||
const m = usePerf((s) => s.metrics);
|
||||
const error = usePerf((s) => s.error);
|
||||
useEffect(() => {
|
||||
if (!isTauri()) return;
|
||||
return startPolling(() => void refreshMetrics(), { intervalMs: 2000 });
|
||||
}, []);
|
||||
|
||||
if (!isTauri()) return <div className={styles.empty}>Memory usage is available in the desktop app.</div>;
|
||||
if (!m) return <div className={styles.empty}>Loading…</div>;
|
||||
const summary = summarizeMemory(m);
|
||||
const own = (summary.app ?? 0) + (summary.languageServers ?? 0);
|
||||
const ratio = memoryRatio(own, m.totalMemoryBytes);
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
<Section title="Memory">
|
||||
<IndicatorToggle />
|
||||
<div
|
||||
className={styles.meter}
|
||||
role="meter"
|
||||
aria-label="OpenIDEA and language servers, share of physical memory"
|
||||
aria-valuenow={Math.round(ratio * 100)}
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={100}
|
||||
>
|
||||
<span className={styles.fill} style={{ width: `${Math.max(ratio * 100, ratio > 0 ? 1 : 0)}%` }} />
|
||||
</div>
|
||||
<div className={styles.hint}>
|
||||
OpenIDEA and its language servers use {formatSize(own)} ({Math.round(ratio * 100)}%) of{" "}
|
||||
{formatSize(m.totalMemoryBytes)} physical memory.
|
||||
</div>
|
||||
{memorySections(m.memory ?? []).map((sec) => (
|
||||
<div key={sec.title} className={styles.group}>
|
||||
<Row label={sec.title} value={sec.total} strong />
|
||||
{sec.rows.map((r) => (
|
||||
<Row key={r.key} label={r.detail ? `${r.label} (${r.detail})` : r.label} value={r.value} indented />
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
<Row label="Total" value={formatSize(summary.total)} strong />
|
||||
{m.heapBytes != null && <Row label="Backend malloc in use" value={formatBytes(m.heapBytes)} />}
|
||||
<div className={styles.hint}>
|
||||
Memory as the OS reports it (macOS: Activity Monitor’s “Memory”; Linux: PSS; Windows: private bytes),
|
||||
including child processes.
|
||||
</div>
|
||||
</Section>
|
||||
<Section title="Caches">
|
||||
<Row label="Open projects" value={formatCount(m.projects)} />
|
||||
<Row label="Open documents" value={formatCount(m.openDocuments)} />
|
||||
<Row
|
||||
label={m.indexing ? "Index (indexing…)" : "Index"}
|
||||
value={`${formatCount(m.indexFiles)} files · ${formatCount(m.indexSymbols)} symbols`}
|
||||
/>
|
||||
<Row label="Language servers" value={formatCount(m.languageServers)} />
|
||||
<Row
|
||||
label="Syntax trees"
|
||||
value={`${m.syntax.trees} / ${m.syntax.documents} documents · ${formatBytes(m.syntax.treeTextBytes)}`}
|
||||
/>
|
||||
<div className={styles.actions}>
|
||||
<Button icon="trash" onClick={() => void executeAction("perf.clearCaches")}>
|
||||
Clear Caches
|
||||
</Button>
|
||||
<span className={styles.hint}>
|
||||
Drops syntax trees and EditorConfig data and compacts the index; they are rebuilt on demand.
|
||||
</span>
|
||||
</div>
|
||||
</Section>
|
||||
<Section title="Startup">
|
||||
<Row label="Uptime" value={formatUptime(m.uptimeMs)} />
|
||||
<Row label="Process → main" value={formatMs(m.startup.processToMainMs)} />
|
||||
<Row label="Process → backend ready" value={formatMs(m.startup.processToSetupMs)} />
|
||||
<Row label="Backend set-up" value={formatMs(m.startup.setupMs)} />
|
||||
<Row label="Process → first IPC" value={formatMs(m.startup.firstIpcMs)} />
|
||||
<div className={styles.hint}>
|
||||
“Process → main” is spent before any OpenIDEA code runs: exec, code-signature checks and dynamic loading. macOS
|
||||
scans a freshly built, unsigned debug binary for several seconds on its first launch.
|
||||
</div>
|
||||
</Section>
|
||||
{error && <div className={styles.error}>{error}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
/** Dev diagnostics: keystroke → paint latency, IPC round trips, long tasks. */
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { IconButton, T } from "@/ui";
|
||||
import { IconButton } from "@/ui";
|
||||
import { isTauri } from "@/platform/ipc";
|
||||
import { formatMs } from "./format";
|
||||
import { FRAME_BUDGET_MS, keystrokeLatencies, supportsEntryType, type EventEntryLike } from "./events";
|
||||
@@ -72,9 +72,7 @@ function PerfPanel({ onClose }: { onClose: () => void }) {
|
||||
return (
|
||||
<section className={styles.overlay} aria-label="Performance overlay (dev diagnostics)">
|
||||
<div className={styles.overlayHeader}>
|
||||
<span className={styles.overlayTitle}>
|
||||
<T>Performance (dev diagnostics)</T>
|
||||
</span>
|
||||
<span className={styles.overlayTitle}>Performance (dev diagnostics)</span>
|
||||
<IconButton icon="close" size="small" title="Close performance overlay" onClick={onClose} />
|
||||
</div>
|
||||
<Block
|
||||
@@ -103,9 +101,7 @@ function Block({ title, summary, budget, note }: { title: string; summary?: Summ
|
||||
<span className={styles.value}>{s ? `${s.count} samples` : "–"}</span>
|
||||
</div>
|
||||
<div className={styles.row}>
|
||||
<span className={styles.label}>
|
||||
<T>last · p50 · p95 · max</T>
|
||||
</span>
|
||||
<span className={styles.label}>last · p50 · p95 · max</span>
|
||||
<span className={styles.value}>{s ? [s.last, s.p50, s.p95, s.max].map(formatMs).join(" · ") : "–"}</span>
|
||||
</div>
|
||||
<div className={styles.row}>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { ProcessMemory } from "@/platform/ipc";
|
||||
import { formatBytes, formatCount, formatMs, formatSize, formatUptime } from "../format";
|
||||
import { formatBytes, formatCount, formatMs, formatSize, formatUptime, memoryRatio } from "../format";
|
||||
import { indicatorLabel, indicatorTooltip, memorySections, summarizeMemory } from "../memory";
|
||||
import { RollingWindow, percentile } from "../stats";
|
||||
import { isEditorTypingEntry, keystrokeLatencies, supportsEntryType } from "../events";
|
||||
@@ -26,6 +26,9 @@ describe("format", () => {
|
||||
expect(formatSize(1.1 * GB)).toBe("1.1 GB");
|
||||
expect(formatSize(12 * 1024)).toBe("12 KB");
|
||||
expect(formatSize(null)).toBe("–");
|
||||
expect(memoryRatio(GB, 2 * GB)).toBe(0.5);
|
||||
expect(memoryRatio(3 * GB, 2 * GB)).toBe(1);
|
||||
expect(memoryRatio(null, 2 * GB)).toBe(0);
|
||||
});
|
||||
|
||||
it("formats durations and counts", () => {
|
||||
|
||||
@@ -29,6 +29,12 @@ export function formatSize(bytes: number | null | undefined): string {
|
||||
return `${trim(bytes / GB)} GB`;
|
||||
}
|
||||
|
||||
/** Share (0..1) of `total`, clamped. */
|
||||
export function memoryRatio(used: number | null | undefined, total: number | null | undefined): number {
|
||||
if (!used || !total || total <= 0) return 0;
|
||||
return Math.min(1, Math.max(0, used / total));
|
||||
}
|
||||
|
||||
/** `0.4 ms`, `16 ms`, `2.3 s`. */
|
||||
export function formatMs(ms: number | null | undefined): string {
|
||||
if (ms == null || !Number.isFinite(ms)) return "–";
|
||||
|
||||
@@ -1,16 +1,30 @@
|
||||
/** Memory indicator, "Clear caches" and the dev performance overlay. */
|
||||
import { lazyComponent } from "@/ui";
|
||||
import { registerActions } from "@/platform/actions";
|
||||
import { registerOverlay, registerStatusItem } from "@/workbench/contributions";
|
||||
import { registerOverlay, registerSettingsPage, registerStatusItem } from "@/workbench/contributions";
|
||||
import { perfActions } from "./actions";
|
||||
import { MEMORY_WIDGET, MemoryStatus } from "./MemoryStatus";
|
||||
import { PerfOverlay } from "./PerfOverlay";
|
||||
|
||||
/** Settings › Memory Usage (also used by the Settings window). */
|
||||
export function activateSettingsPages(): () => void {
|
||||
// Top level after Plugins, as in IDEA.
|
||||
return registerSettingsPage({
|
||||
id: "memory",
|
||||
title: "Memory Usage",
|
||||
order: 950,
|
||||
keywords: ["memory", "ram", "clear caches", "index"],
|
||||
component: lazyComponent(() => import("./MemoryUsagePage").then((m) => m.MemoryUsagePage)),
|
||||
});
|
||||
}
|
||||
|
||||
export function activate(): () => void {
|
||||
const disposers = [
|
||||
registerActions(perfActions()),
|
||||
// Far right and hidden by default, like IDEA's memory indicator.
|
||||
registerStatusItem({ ...MEMORY_WIDGET, align: "right", priority: 100, component: MemoryStatus }),
|
||||
registerOverlay({ id: "perf.overlay", component: PerfOverlay }),
|
||||
activateSettingsPages(),
|
||||
];
|
||||
return () => disposers.reverse().forEach((d) => d());
|
||||
}
|
||||
@@ -22,7 +22,6 @@ import {
|
||||
Tabs,
|
||||
showContextMenu,
|
||||
type MenuItem,
|
||||
T,
|
||||
} from "@/ui";
|
||||
import { pluginActionId } from "./bridge";
|
||||
import {
|
||||
@@ -126,7 +125,7 @@ function InstalledRow({ plugin, selected, onSelect }: { plugin: PluginInfo; sele
|
||||
{plugin.source === "dev" && <span className={styles.devTag}>dev</span>}
|
||||
{plugin.status === "failed" && (
|
||||
<Badge dot tone="danger">
|
||||
<T>Failed</T>
|
||||
Failed
|
||||
</Badge>
|
||||
)}
|
||||
</span>
|
||||
@@ -221,9 +220,7 @@ function DetailTabs({ notes, overview }: { notes: string | null; overview: React
|
||||
) : notes ? (
|
||||
<pre className={styles.notes}>{notes.trim()}</pre>
|
||||
) : (
|
||||
<p className={styles.muted}>
|
||||
<T>This version has no release notes.</T>
|
||||
</p>
|
||||
<p className={styles.muted}>This version has no release notes.</p>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
@@ -247,25 +244,17 @@ function InstalledDetails({ plugin }: { plugin: PluginInfo }) {
|
||||
{plugin.description && <p className={styles.description}>{plugin.description}</p>}
|
||||
|
||||
<dl className={styles.facts}>
|
||||
<dt>
|
||||
<T>Id</T>
|
||||
</dt>
|
||||
<dt>Id</dt>
|
||||
<dd className={styles.mono}>{plugin.id}</dd>
|
||||
<dt>
|
||||
<T>Location</T>
|
||||
</dt>
|
||||
<dt>Location</dt>
|
||||
<dd className={styles.mono} title={plugin.path}>
|
||||
{plugin.path}
|
||||
</dd>
|
||||
<dt>
|
||||
<T>Code</T>
|
||||
</dt>
|
||||
<dt>Code</dt>
|
||||
<dd>{plugin.hasCode ? "WebAssembly component (sandboxed)" : "None — contributions only"}</dd>
|
||||
{plugin.homepage && (
|
||||
<>
|
||||
<dt>
|
||||
<T>Homepage</T>
|
||||
</dt>
|
||||
<dt>Homepage</dt>
|
||||
<dd className={styles.mono}>{plugin.homepage}</dd>
|
||||
</>
|
||||
)}
|
||||
@@ -274,9 +263,7 @@ function InstalledDetails({ plugin }: { plugin: PluginInfo }) {
|
||||
{plugin.hasCode && (
|
||||
<Section title="Permissions">
|
||||
{plugin.permissions.length === 0 ? (
|
||||
<div className={styles.muted}>
|
||||
<T>No special permissions.</T>
|
||||
</div>
|
||||
<div className={styles.muted}>No special permissions.</div>
|
||||
) : (
|
||||
<ul className={styles.items}>
|
||||
{plugin.permissions.map((p) => (
|
||||
@@ -310,7 +297,7 @@ function InstalledDetails({ plugin }: { plugin: PluginInfo }) {
|
||||
onClick={() => void runPluginCommand(plugin.id, c.id)}
|
||||
aria-label={`Run ${c.title}`}
|
||||
>
|
||||
<T>Run</T>
|
||||
Run
|
||||
</Button>
|
||||
</li>
|
||||
);
|
||||
@@ -330,7 +317,7 @@ function InstalledDetails({ plugin }: { plugin: PluginInfo }) {
|
||||
<span className={styles.muted}>{t.kind === "dark" ? "Dark" : "Light"}</span>
|
||||
{isActive ? (
|
||||
<Button size="small" variant="secondary" onClick={() => void selectPluginTheme(null, null)}>
|
||||
<T>Use Default Theme</T>
|
||||
Use Default Theme
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
@@ -340,7 +327,7 @@ function InstalledDetails({ plugin }: { plugin: PluginInfo }) {
|
||||
onClick={() => void selectPluginTheme(plugin.id, t.id)}
|
||||
aria-label={`Apply theme ${t.name}`}
|
||||
>
|
||||
<T>Apply</T>
|
||||
Apply
|
||||
</Button>
|
||||
)}
|
||||
</li>
|
||||
@@ -375,11 +362,7 @@ function InstalledDetails({ plugin }: { plugin: PluginInfo }) {
|
||||
<div className={styles.titleLine}>
|
||||
<span className={styles.version}>{plugin.version}</span>
|
||||
<Badge tone={status.tone}>{status.label}</Badge>
|
||||
{plugin.source === "dev" && (
|
||||
<Badge tone="warning">
|
||||
<T>Dev plugin</T>
|
||||
</Badge>
|
||||
)}
|
||||
{plugin.source === "dev" && <Badge tone="warning">Dev plugin</Badge>}
|
||||
</div>
|
||||
</div>
|
||||
<div className={styles.headerActions}>
|
||||
@@ -409,15 +392,15 @@ function InstalledDetails({ plugin }: { plugin: PluginInfo }) {
|
||||
onClick={() => void uninstallPlugin(plugin.id)}
|
||||
aria-label={`Confirm uninstall ${plugin.name}`}
|
||||
>
|
||||
<T>Uninstall</T>
|
||||
Uninstall
|
||||
</Button>
|
||||
<Button size="small" variant="ghost" onClick={() => setConfirmUninstall(false)}>
|
||||
<T>Cancel</T>
|
||||
Cancel
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<Button size="small" disabled={busy} onClick={() => setConfirmUninstall(true)}>
|
||||
<T>Uninstall…</T>
|
||||
Uninstall…
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
@@ -442,25 +425,17 @@ function CatalogDetails({ entry }: { entry: CatalogPlugin }) {
|
||||
)}
|
||||
{entry.description && <p className={styles.description}>{entry.description}</p>}
|
||||
<dl className={styles.facts}>
|
||||
<dt>
|
||||
<T>Id</T>
|
||||
</dt>
|
||||
<dt>Id</dt>
|
||||
<dd className={styles.mono}>{entry.id}</dd>
|
||||
<dt>
|
||||
<T>Source</T>
|
||||
</dt>
|
||||
<dt>Source</dt>
|
||||
<dd className={styles.mono} title={entry.path}>
|
||||
{entry.path}
|
||||
</dd>
|
||||
<dt>
|
||||
<T>Code</T>
|
||||
</dt>
|
||||
<dt>Code</dt>
|
||||
<dd>{entry.hasCode ? "WebAssembly component (sandboxed)" : "None — contributions only"}</dd>
|
||||
{contributes.length > 0 && (
|
||||
<>
|
||||
<dt>
|
||||
<T>Contributes</T>
|
||||
</dt>
|
||||
<dt>Contributes</dt>
|
||||
<dd>{contributes.join(", ")}</dd>
|
||||
</>
|
||||
)}
|
||||
@@ -656,17 +631,15 @@ export function PluginsPage() {
|
||||
<InstalledDetails key={selected.id} plugin={selected} />
|
||||
) : (
|
||||
<EmptyState className={styles.detailsEmpty} title={loaded ? "No plugin selected" : "Loading…"}>
|
||||
<T>Plugins are folders with a</T> <code>plugin.toml</code>
|
||||
<T>. Use the gear menu to install one from disk, or put dev plugins in</T> <code>.openidea/plugins/</code>{" "}
|
||||
<T>inside your project.</T>
|
||||
Plugins are folders with a <code>plugin.toml</code>. Use the gear menu to install one from disk, or put
|
||||
dev plugins in <code>.openidea/plugins/</code> inside your project.
|
||||
</EmptyState>
|
||||
)
|
||||
) : selectedEntry ? (
|
||||
<CatalogDetails key={selectedEntry.id} entry={selectedEntry} />
|
||||
) : (
|
||||
<EmptyState className={styles.detailsEmpty} title={NO_REPOSITORY}>
|
||||
<T>Install a plugin folder with</T> <code>plugin.toml</code>{" "}
|
||||
<T>via the gear menu › Install Plugin from Disk….</T>
|
||||
Install a plugin folder with <code>plugin.toml</code> via the gear menu › Install Plugin from Disk….
|
||||
</EmptyState>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
import { useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import type { Profile } from "@/platform/ipc";
|
||||
import { EmptyState, IconButton, Input, Tabs, Tree, T } from "@/ui";
|
||||
import { EmptyState, IconButton, Input, Tabs, Tree } from "@/ui";
|
||||
import { editorService } from "@/workbench/contributions";
|
||||
import { colorSlot, flameLayout, formatWeight, frameLocation, matchingFrames, share } from "./model";
|
||||
import { activeSnapshot, closeSnapshot, useProfiler, type ProfilerTab } from "./store";
|
||||
@@ -17,10 +17,7 @@ const ROW = 18;
|
||||
function openFrame(profile: Profile, frame: number) {
|
||||
const f = profile.frames[frame];
|
||||
if (!f?.file) return;
|
||||
void editorService().openFile(
|
||||
f.file,
|
||||
f.line !== null ? { selection: { line: f.line, col: 0 }, focus: true } : { focus: true },
|
||||
);
|
||||
void editorService().openFile(f.file, f.line !== null ? { selection: { line: f.line, col: 0 }, focus: true } : { focus: true });
|
||||
}
|
||||
|
||||
export function ProfilerTabs() {
|
||||
@@ -191,12 +188,10 @@ function MethodList({ profile, query }: { profile: Profile; query: string }) {
|
||||
{location && <span className={styles.muted}>{location}</span>}
|
||||
</td>
|
||||
<td className={styles.num}>
|
||||
{formatWeight(m.selfWeight ?? 0, profile.unit)}{" "}
|
||||
<span className={styles.muted}>{share(m.selfWeight ?? 0, total)}</span>
|
||||
{formatWeight(m.selfWeight ?? 0, profile.unit)} <span className={styles.muted}>{share(m.selfWeight ?? 0, total)}</span>
|
||||
</td>
|
||||
<td className={styles.num}>
|
||||
{formatWeight(m.total ?? 0, profile.unit)}{" "}
|
||||
<span className={styles.muted}>{share(m.total ?? 0, total)}</span>
|
||||
{formatWeight(m.total ?? 0, profile.unit)} <span className={styles.muted}>{share(m.total ?? 0, total)}</span>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
@@ -214,9 +209,7 @@ export function ProfilerView() {
|
||||
if (!snapshot) {
|
||||
return (
|
||||
<EmptyState title="No profiler snapshots">
|
||||
<span>
|
||||
<T>Profile a run configuration to see where it spends its time.</T>
|
||||
</span>
|
||||
<span>Profile a run configuration to see where it spends its time.</span>
|
||||
</EmptyState>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { useEffect, type ReactNode } from "react";
|
||||
import { create } from "zustand";
|
||||
import { Dialog } from "@/ui";
|
||||
import styles from "./ProjectView.module.css";
|
||||
|
||||
interface ConfirmRequest {
|
||||
title: string;
|
||||
message: ReactNode;
|
||||
okLabel: string;
|
||||
resolve: (ok: boolean) => void;
|
||||
}
|
||||
|
||||
const useConfirm = create<{ request: ConfirmRequest | null }>(() => ({ request: null }));
|
||||
|
||||
/** Shows a modal Yes/Cancel dialog; resolves with the choice. */
|
||||
export function confirmDialog(opts: Omit<ConfirmRequest, "resolve">): Promise<boolean> {
|
||||
useConfirm.getState().request?.resolve(false);
|
||||
return new Promise((resolve) => {
|
||||
useConfirm.setState({
|
||||
request: {
|
||||
...opts,
|
||||
resolve: (ok) => {
|
||||
useConfirm.setState({ request: null });
|
||||
resolve(ok);
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** Overlay contribution rendering the pending confirmation. */
|
||||
export function ConfirmDialogHost() {
|
||||
const request = useConfirm((s) => s.request);
|
||||
useEffect(() => () => useConfirm.getState().request?.resolve(false), []);
|
||||
if (!request) return null;
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
title={request.title}
|
||||
onClose={() => request.resolve(false)}
|
||||
width={420}
|
||||
buttons={[
|
||||
{ label: request.okLabel, role: "default", autoFocus: true, onClick: () => request.resolve(true) },
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
]}
|
||||
>
|
||||
<div className={styles.confirmBody}>{request.message}</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { create } from "zustand";
|
||||
import type { FileMove } from "@/bindings";
|
||||
import { Checkbox, Dialog, Input, Spinner, T } from "@/ui";
|
||||
import { Checkbox, Dialog, Input, Spinner } from "@/ui";
|
||||
import { runFileRefactoring, type FileRefactorOptions } from "./fileRefactor";
|
||||
import { isSameOrInside, joinPath, nameOf, parentOf, relativeTo, splitExtension, validateName } from "./paths";
|
||||
import { useProjectTree } from "./store";
|
||||
@@ -147,9 +147,7 @@ function Busy() {
|
||||
return (
|
||||
<div className={styles.busy} role="status">
|
||||
<Spinner size={14} />
|
||||
<span>
|
||||
<T>Looking for references…</T>
|
||||
</span>
|
||||
<span>Looking for references…</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -275,7 +273,7 @@ function MoveDialog({ request }: { request: Extract<FileRefactorRequest, { kind:
|
||||
>
|
||||
<div className={styles.subject}>{subject}</div>
|
||||
<label className={styles.fieldLabel} htmlFor="file-move-target">
|
||||
<T>To directory:</T>
|
||||
To directory:
|
||||
</label>
|
||||
<Input
|
||||
id="file-move-target"
|
||||
|
||||
@@ -115,3 +115,10 @@
|
||||
pointer-events: none;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.confirmBody {
|
||||
padding: 14px;
|
||||
color: var(--fg);
|
||||
line-height: 1.5;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import { getContext } from "@/platform/context";
|
||||
import { provideEditorService, type EditorService } from "@/workbench/contributions";
|
||||
import { activate } from "./index";
|
||||
import { MemoryFs, setProjectFsForTests } from "./fs";
|
||||
import { MessagesHost } from "@/workbench/messages";
|
||||
import { ConfirmDialogHost } from "./ConfirmDialog";
|
||||
import { FileRefactorDialogHost } from "./FileRefactorDialogs";
|
||||
import { setRefactorBackendForTests } from "./fileRefactor";
|
||||
import { ProjectView } from "./ProjectView";
|
||||
@@ -46,7 +46,7 @@ function setup() {
|
||||
render(
|
||||
<>
|
||||
<ProjectView />
|
||||
<MessagesHost />
|
||||
<ConfirmDialogHost />
|
||||
<FileRefactorDialogHost />
|
||||
</>,
|
||||
);
|
||||
|
||||
Loaded 100 of 237 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача