mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-24 18:43:16 -10:00
Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ed4998c236 | ||
|
|
97e9657fd3 | ||
|
|
1205ffecd2 | ||
|
|
51766249f9 | ||
|
|
ff55bcdf9a | ||
|
|
fd6d1d5d0e | ||
|
|
9ad5bad82e |
No files matched your search
@@ -65,6 +65,8 @@ concurrency:
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_INCREMENTAL: 0
|
||||
# Line tables keep test backtraces readable and the binaries the build job hands on small.
|
||||
CARGO_PROFILE_DEV_DEBUG: line-tables-only
|
||||
|
||||
jobs:
|
||||
# The languages a pull request can affect: a change to one language's fixture, definition or
|
||||
@@ -132,10 +134,40 @@ jobs:
|
||||
done < files.txt
|
||||
echo "languages=$(emit "$langs")" | tee -a "$GITHUB_OUTPUT"
|
||||
|
||||
smoke:
|
||||
name: Language smoke (${{ matrix.language }})
|
||||
# Builds the smoke test binaries and openidea-server once for every language below.
|
||||
build:
|
||||
name: Build
|
||||
needs: changes
|
||||
if: needs.changes.outputs.languages != '[]'
|
||||
# The tests find the fixtures through the checkout path compiled into them (CARGO_MANIFEST_DIR),
|
||||
# which is the same on every GitHub-hosted runner.
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
shared-key: language-smoke
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
- run: |
|
||||
set -euo pipefail
|
||||
mkdir -p smoke-bin
|
||||
cargo test --locked -p ide-host --test language_smoke --test project_smoke --no-run --message-format=json \
|
||||
| jq -r 'select(.reason == "compiler-artifact" and .executable != null and .target.kind == ["test"]) | "\(.target.name) \(.executable)"' \
|
||||
| while read -r name exe; do cp "$exe" "smoke-bin/$name"; done
|
||||
cargo build --locked -p ide-host --bin openidea-server
|
||||
cp target/debug/openidea-server smoke-bin/
|
||||
ls -l smoke-bin
|
||||
test -x smoke-bin/language_smoke && test -x smoke-bin/project_smoke
|
||||
# A tar keeps the executable bits, which artifacts drop.
|
||||
tar -cf smoke-bin.tar smoke-bin
|
||||
- uses: actions/upload-artifact@v6
|
||||
with: { name: smoke-bin, path: smoke-bin.tar, retention-days: 1 }
|
||||
|
||||
smoke:
|
||||
name: Language smoke (${{ matrix.language }})
|
||||
needs: [changes, build]
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
@@ -149,11 +181,11 @@ jobs:
|
||||
- run: grep -E '^[A-Z0-9_]+=' .github/tool-versions.env >> "$GITHUB_ENV"
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with: { components: "rust-analyzer, rustfmt" }
|
||||
# One build cache for every language; main saves it.
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
shared-key: language-smoke
|
||||
save-if: ${{ github.ref == 'refs/heads/main' && matrix.language == 'rust' }}
|
||||
- uses: actions/download-artifact@v6
|
||||
with: { name: smoke-bin }
|
||||
- run: |
|
||||
tar -xf smoke-bin.tar && rm smoke-bin.tar
|
||||
mkdir -p target/debug && mv smoke-bin/openidea-server target/debug/
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
with: { version: 11 }
|
||||
@@ -209,17 +241,20 @@ jobs:
|
||||
- if: matrix.language == 'php'
|
||||
run: npm install --global "intelephense@$INTELEPHENSE"
|
||||
|
||||
- run: cargo test --locked -p ide-host --test language_smoke --no-run
|
||||
- run: cargo test --locked -p ide-host --test language_smoke -- --ignored --exact ${{ matrix.language }}
|
||||
# The binaries from the build job, run from the crate directory as `cargo test` does.
|
||||
- working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/language_smoke --ignored --exact ${{ matrix.language }}
|
||||
- if: matrix.language == 'java'
|
||||
run: cargo test --locked -p ide-host --test project_smoke -- --ignored --exact maven_sync jdk maven_launch_classpath_uses_the_runner_jdk_classifier
|
||||
working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/project_smoke --ignored --exact maven_sync jdk maven_launch_classpath_uses_the_runner_jdk_classifier
|
||||
- if: matrix.language == 'kotlin'
|
||||
run: cargo test --locked -p ide-host --test project_smoke -- --ignored --exact gradle_sync
|
||||
working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/project_smoke --ignored --exact gradle_sync
|
||||
- if: matrix.language == 'python'
|
||||
run: cargo test --locked -p ide-host --test project_smoke -- --ignored --exact python_venv
|
||||
working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/project_smoke --ignored --exact python_venv
|
||||
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: cargo build --locked -p ide-host --bin openidea-server
|
||||
- run: pnpm smoke smoke/run.test.ts -t "^${{ matrix.language }}$"
|
||||
- run: pnpm smoke smoke/debug.test.ts -t "^${{ matrix.language }}$"
|
||||
# The IDE installs the debugger from GitHub releases: authenticated, against rate limits.
|
||||
|
||||
@@ -76,6 +76,8 @@ pub struct Project {
|
||||
/// watchers for (a virtualenv elsewhere, a path dependency).
|
||||
lsp_watchers: Mutex<Vec<(PathBuf, Watcher)>>,
|
||||
pub(crate) _scratch_watcher: Option<Watcher>,
|
||||
/// Git metadata of repositories whose git directory lies outside the project folder.
|
||||
pub(crate) git_metadata: Option<Arc<ide_vcs::MetadataWatch>>,
|
||||
/// Picks up data sources edited on disk outside the Database tool window.
|
||||
_db_sources_watch: Option<ide_db::SourcesWatch>,
|
||||
/// A LightEdit window's loose files ([`Host::open_light`]): global settings only,
|
||||
@@ -385,6 +387,10 @@ impl Host {
|
||||
for repo in repos.read().all() {
|
||||
repo.set_execution_allowed(trusted.load(Ordering::Acquire));
|
||||
}
|
||||
let git_metadata = git_metadata_watch(&root, &sink);
|
||||
if let Some(watch) = &git_metadata {
|
||||
watch.set_repos(repos.read().all(), &root);
|
||||
}
|
||||
// Shared handle: `unwatched_reason` is a live query on the watcher,
|
||||
// filled after `start` returns so the on-change callback can reach it.
|
||||
let watcher_weak = Arc::new(std::sync::OnceLock::<std::sync::Weak<Watcher>>::new());
|
||||
@@ -398,6 +404,7 @@ impl Host {
|
||||
let kotlin_bridge = kotlin_bridge.clone();
|
||||
let phpstan = phpstan.clone();
|
||||
let repos = repos.clone();
|
||||
let git_metadata = git_metadata.clone();
|
||||
let settings = settings.clone();
|
||||
let index = index.clone();
|
||||
let documents = documents.clone();
|
||||
@@ -521,6 +528,7 @@ impl Host {
|
||||
scan_repositories(
|
||||
&root,
|
||||
&repos,
|
||||
git_metadata.as_deref(),
|
||||
&settings,
|
||||
&sink,
|
||||
&build_cache,
|
||||
@@ -611,11 +619,11 @@ impl Host {
|
||||
mark("watcher");
|
||||
{
|
||||
let (root, repos, settings, sink) = (root.clone(), repos.clone(), settings.clone(), sink.clone());
|
||||
let build_cache = build_cache.clone();
|
||||
let (build_cache, git_metadata) = (build_cache.clone(), git_metadata.clone());
|
||||
let trusted = trusted.load(Ordering::Acquire);
|
||||
std::thread::Builder::new()
|
||||
.name("openidea-vcs-roots".into())
|
||||
.spawn(move || scan_repositories(&root, &repos, &settings, &sink, &build_cache, trusted))?;
|
||||
std::thread::Builder::new().name("openidea-vcs-roots".into()).spawn(move || {
|
||||
scan_repositories(&root, &repos, git_metadata.as_deref(), &settings, &sink, &build_cache, trusted)
|
||||
})?;
|
||||
}
|
||||
mark("git");
|
||||
tracing::info!("opened {} in window {window} in {} ms {laps:?}", root.display(), started.elapsed().as_millis());
|
||||
@@ -664,6 +672,7 @@ impl Host {
|
||||
content_watchers: Mutex::new(content_watchers),
|
||||
lsp_watchers: Mutex::new(Vec::new()),
|
||||
_scratch_watcher: scratch_watcher,
|
||||
git_metadata,
|
||||
_db_sources_watch: db_sources_watch,
|
||||
files_events_active,
|
||||
light: false,
|
||||
@@ -911,6 +920,7 @@ impl Host {
|
||||
content_watchers: Mutex::new(Vec::new()),
|
||||
lsp_watchers: Mutex::new(Vec::new()),
|
||||
_scratch_watcher: None,
|
||||
git_metadata: None,
|
||||
_db_sources_watch: None,
|
||||
files_events_active: Arc::new(AtomicBool::new(false)),
|
||||
light: true,
|
||||
@@ -1014,6 +1024,7 @@ fn light_watcher(
|
||||
fn scan_repositories(
|
||||
root: &Path,
|
||||
repos: &RwLock<Repos>,
|
||||
git_metadata: Option<&ide_vcs::MetadataWatch>,
|
||||
settings: &SettingsStore,
|
||||
sink: &SharedSink,
|
||||
build_cache: &Path,
|
||||
@@ -1022,6 +1033,9 @@ fn scan_repositories(
|
||||
match discover_repositories(root, settings, build_cache, trusted) {
|
||||
Ok(found) => {
|
||||
if found.roots() != repos.read().roots() {
|
||||
if let Some(watch) = git_metadata {
|
||||
watch.set_repos(found.all(), root);
|
||||
}
|
||||
*repos.write() = found;
|
||||
sink.emit(IdeEvent::VcsChanged { root: root.to_path_buf().into() });
|
||||
}
|
||||
@@ -1075,6 +1089,7 @@ impl Project {
|
||||
scan_repositories(
|
||||
&self.root,
|
||||
&self.repos,
|
||||
self.git_metadata.as_deref(),
|
||||
&self.settings,
|
||||
&self.sink,
|
||||
&self.build_cache_dir(),
|
||||
@@ -2329,6 +2344,20 @@ mod maven_linkage_tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Commits, checkouts and resets made outside the IDE in a git directory the project
|
||||
/// watcher doesn't see (the project is a subfolder of its repository, or a linked worktree).
|
||||
fn git_metadata_watch(root: &Path, sink: &SharedSink) -> Option<Arc<ide_vcs::MetadataWatch>> {
|
||||
let (root, sink) = (root.to_path_buf(), sink.clone());
|
||||
ide_vcs::MetadataWatch::new(move |paths| {
|
||||
if paths.iter().any(|p| vcs_path_changed(p)) {
|
||||
sink.emit(IdeEvent::VcsChanged { root: root.clone().into() });
|
||||
}
|
||||
})
|
||||
.map(Arc::new)
|
||||
.map_err(|e| tracing::warn!("{}", e.message))
|
||||
.ok()
|
||||
}
|
||||
|
||||
fn vcs_path_changed(path: &Path) -> bool {
|
||||
!path.ends_with(".git/index") || !ide_vcs::is_own_index_write(path)
|
||||
}
|
||||
@@ -2613,3 +2642,77 @@ mod content_roots_tests {
|
||||
assert_eq!(members[&root], ["/dist", "/target"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod external_git_metadata_tests {
|
||||
use crate::{Host, HostConfig};
|
||||
use ide_core::{IdeEvent, SharedSink};
|
||||
use parking_lot::Mutex;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
fn git(dir: &Path, args: &[&str]) {
|
||||
let out = std::process::Command::new("git")
|
||||
.current_dir(dir)
|
||||
.args(["-c", "[email protected]", "-c", "user.name=t", "-c", "commit.gpgsign=false"])
|
||||
.args(args)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
}
|
||||
|
||||
/// A commit made in a terminal refreshes the project's VCS state when the project folder
|
||||
/// is the repository root, a subfolder of it, or a linked worktree, and for a submodule.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn external_commits_refresh_vcs_wherever_the_git_dir_lives() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let main = base.join("main");
|
||||
std::fs::create_dir_all(main.join("sub")).unwrap();
|
||||
git(&main, &["init", "-q", "-b", "main"]);
|
||||
git(&main, &["commit", "-q", "--allow-empty", "-m", "init"]);
|
||||
git(&main, &["worktree", "add", "-q", "-b", "topic", base.join("wt").to_str().unwrap()]);
|
||||
let lib = base.join("lib");
|
||||
std::fs::create_dir(&lib).unwrap();
|
||||
git(&lib, &["init", "-q", "-b", "main"]);
|
||||
git(&lib, &["commit", "-q", "--allow-empty", "-m", "init"]);
|
||||
let sup = base.join("super");
|
||||
std::fs::create_dir(&sup).unwrap();
|
||||
git(&sup, &["init", "-q", "-b", "main"]);
|
||||
git(&sup, &["-c", "protocol.file.allow=always", "submodule", "add", "-q", lib.to_str().unwrap(), "lib"]);
|
||||
git(&sup, &["commit", "-q", "-m", "submodule"]);
|
||||
let seen = Arc::new(Mutex::new(0usize));
|
||||
let counted = seen.clone();
|
||||
let sink: SharedSink = Arc::new(move |e: IdeEvent| {
|
||||
if matches!(e, IdeEvent::VcsChanged { .. }) {
|
||||
*counted.lock() += 1;
|
||||
}
|
||||
});
|
||||
let host = Host::new(HostConfig {
|
||||
sink_for: Box::new(move |_| sink.clone()),
|
||||
local_data_dir: base.join("local"),
|
||||
..HostConfig::for_test(&base)
|
||||
});
|
||||
let cases = [
|
||||
(main.clone(), main.clone()),
|
||||
(main.join("sub"), main.join("sub")),
|
||||
(base.join("wt"), base.join("wt")),
|
||||
(sup.clone(), sup.join("lib")),
|
||||
];
|
||||
for (project, repo) in cases {
|
||||
host.open_project("main", &project).unwrap();
|
||||
std::thread::sleep(Duration::from_millis(1500));
|
||||
*seen.lock() = 0;
|
||||
std::fs::write(repo.join("a.txt"), repo.to_string_lossy().as_bytes()).unwrap();
|
||||
git(&repo, &["add", "a.txt"]);
|
||||
git(&repo, &["commit", "-q", "-m", "change"]);
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while *seen.lock() == 0 && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
assert!(*seen.lock() > 0, "no VcsChanged for a commit in {}", repo.display());
|
||||
host.close_project("main");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -432,6 +432,14 @@ async fn patches_read_and_write_the_requested_repository() {
|
||||
})
|
||||
.collect::<String>();
|
||||
let root = Some(roots[0].clone());
|
||||
// Automatic mappings wait for indexing; the new folders and exclude rule may start a rescan.
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
for _ in 0..500 {
|
||||
if !project.index.status().indexing {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
let preview = vcs::vcs_patch_preview(&host, "main", root.clone(), patch.clone(), None, None).await.unwrap();
|
||||
assert!(preview.files.iter().all(|file| file.applies && !file.missing_base));
|
||||
assert_eq!(preview.automatic_mappings.len(), 1);
|
||||
|
||||
@@ -1605,7 +1605,10 @@ mod pipenv_tests {
|
||||
#[test]
|
||||
fn environments_are_named_as_pipenv_names_them() {
|
||||
// `sanitize(folder)[:42] + "-" + urlsafe_b64encode(sha256(Pipfile path).digest()[:6])`, from pipenv.
|
||||
#[cfg(unix)]
|
||||
assert_eq!(pipenv_env_name(Path::new("/home/me/My Shop (2)")), "My_Shop__2_-6rNTtAUD");
|
||||
#[cfg(windows)]
|
||||
assert_eq!(pipenv_env_name(Path::new(r"C:\Users\me\My Shop (2)")), "My_Shop__2_-ED1rXUDC");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -597,7 +597,7 @@ fn saved_python_configs_keep_their_explicit_interpreter() {
|
||||
config.cwd = Some(Path::new("member").into());
|
||||
apply_to_run_configs(std::slice::from_mut(&mut config), root, &settings);
|
||||
assert_eq!(config.command, command);
|
||||
assert_eq!(config.env["VIRTUAL_ENV"], root.join("member/.override").to_string_lossy());
|
||||
assert_eq!(config.env["VIRTUAL_ENV"], root.join("member").join(".override").to_string_lossy());
|
||||
let saved = without_derived(&config, root, &settings);
|
||||
assert_eq!(saved.command, command);
|
||||
}
|
||||
|
||||
@@ -933,6 +933,8 @@ mod ignore;
|
||||
mod index_writes;
|
||||
mod log_index;
|
||||
mod manage;
|
||||
mod metadata_watch;
|
||||
pub use metadata_watch::MetadataWatch;
|
||||
mod ops;
|
||||
mod patch;
|
||||
mod preserve;
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
use crate::Repo;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use notify::{RecommendedWatcher, RecursiveMode, Watcher};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex, mpsc};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const QUIET: Duration = Duration::from_millis(100);
|
||||
const MAX_WAIT: Duration = Duration::from_secs(1);
|
||||
|
||||
/// Watches the Git metadata (`HEAD`, `index`, `packed-refs`, `refs/**`) of repositories whose
|
||||
/// git directories lie outside the project's own file watcher: a project opened in a
|
||||
/// subfolder of its repository, a linked worktree, a mapped repository elsewhere. Commits,
|
||||
/// checkouts and resets run in a terminal then reach the IDE like those below the project.
|
||||
pub struct MetadataWatch {
|
||||
watcher: Mutex<RecommendedWatcher>,
|
||||
/// Watched directory → whether only its top-level metadata files count (`false`: a
|
||||
/// recursively watched `refs` directory, where every non-lock file counts).
|
||||
dirs: Arc<Mutex<BTreeMap<PathBuf, bool>>>,
|
||||
}
|
||||
|
||||
impl MetadataWatch {
|
||||
/// `changed` receives the metadata files that changed, coalesced over short bursts.
|
||||
pub fn new(changed: impl Fn(Vec<PathBuf>) + Send + 'static) -> IdeResult<Self> {
|
||||
let dirs = Arc::new(Mutex::new(BTreeMap::<PathBuf, bool>::new()));
|
||||
let (tx, rx) = mpsc::channel::<PathBuf>();
|
||||
let watched = dirs.clone();
|
||||
let watcher = notify::recommended_watcher(move |event: notify::Result<notify::Event>| {
|
||||
let Ok(event) = event else { return };
|
||||
if event.kind.is_access() {
|
||||
return;
|
||||
}
|
||||
let dirs = watched.lock().unwrap_or_else(|e| e.into_inner());
|
||||
for path in event.paths.iter().filter(|p| is_metadata(&dirs, p)) {
|
||||
let _ = tx.send(path.clone());
|
||||
}
|
||||
})
|
||||
.map_err(|e| IdeError::internal(format!("Git metadata watcher: {e}")))?;
|
||||
std::thread::Builder::new()
|
||||
.name("openidea-git-metadata".into())
|
||||
.spawn(move || {
|
||||
while let Ok(first) = rx.recv() {
|
||||
let deadline = Instant::now() + MAX_WAIT;
|
||||
let mut paths = BTreeSet::from([first]);
|
||||
while Instant::now() < deadline
|
||||
&& let Ok(path) = rx.recv_timeout(QUIET)
|
||||
{
|
||||
paths.insert(path);
|
||||
}
|
||||
changed(paths.into_iter().collect());
|
||||
}
|
||||
})
|
||||
.map_err(|e| IdeError::internal(format!("Git metadata watcher: {e}")))?;
|
||||
Ok(Self { watcher: Mutex::new(watcher), dirs })
|
||||
}
|
||||
|
||||
/// Watches the metadata of `repos` that the project watcher of `covered` doesn't report:
|
||||
/// git directories outside it, and submodule git directories (`.git/modules/…`) inside it.
|
||||
pub fn set_repos(&self, repos: &[Arc<Repo>], covered: &Path) {
|
||||
let covered = dunce::canonicalize(covered).unwrap_or_else(|_| covered.to_path_buf());
|
||||
let mut wanted = BTreeMap::new();
|
||||
for repo in repos {
|
||||
let Ok([git_dir, common_dir]) = repo.metadata_dirs() else { continue };
|
||||
for (dir, top_level) in [(git_dir, true), (common_dir.clone(), true), (common_dir.join("refs"), false)] {
|
||||
if let Ok(dir) = dunce::canonicalize(&dir)
|
||||
&& !watched_by_project(&covered, &dir)
|
||||
{
|
||||
wanted.insert(dir, top_level);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut watcher = self.watcher.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut dirs = self.dirs.lock().unwrap_or_else(|e| e.into_inner());
|
||||
for dir in dirs.keys().filter(|d| !wanted.contains_key(*d)) {
|
||||
let _ = watcher.unwatch(dir);
|
||||
}
|
||||
wanted.retain(|dir, top_level| {
|
||||
if dirs.contains_key(dir) {
|
||||
return true;
|
||||
}
|
||||
let mode = if *top_level { RecursiveMode::NonRecursive } else { RecursiveMode::Recursive };
|
||||
watcher.watch(dir, mode).map_err(|e| tracing::debug!("Git metadata watcher {}: {e}", dir.display())).is_ok()
|
||||
});
|
||||
*dirs = wanted;
|
||||
}
|
||||
|
||||
pub fn watched_dirs(&self) -> Vec<PathBuf> {
|
||||
self.dirs.lock().unwrap_or_else(|e| e.into_inner()).keys().cloned().collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn watched_by_project(root: &Path, dir: &Path) -> bool {
|
||||
dir.strip_prefix(root)
|
||||
.is_ok_and(|rel| !rel.components().skip_while(|c| c.as_os_str() != ".git").any(|c| c.as_os_str() == "modules"))
|
||||
}
|
||||
|
||||
fn is_metadata(dirs: &BTreeMap<PathBuf, bool>, path: &Path) -> bool {
|
||||
if path.file_name().is_some_and(|n| n.to_string_lossy().ends_with(".lock")) {
|
||||
return false;
|
||||
}
|
||||
dirs.iter().any(|(dir, top_level)| match path.strip_prefix(dir) {
|
||||
Ok(rest) if *top_level => rest.to_str().is_some_and(|r| matches!(r, "HEAD" | "index" | "packed-refs")),
|
||||
Ok(rest) => !rest.as_os_str().is_empty(),
|
||||
Err(_) => false,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn git(dir: &Path, args: &[&str]) {
|
||||
let out = std::process::Command::new("git")
|
||||
.current_dir(dir)
|
||||
.args(["-c", "[email protected]", "-c", "user.name=t", "-c", "commit.gpgsign=false"])
|
||||
.args(args)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
}
|
||||
|
||||
fn wait_for(seen: &Mutex<Vec<PathBuf>>, pred: impl Fn(&[PathBuf]) -> bool) -> bool {
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while Instant::now() < deadline {
|
||||
if pred(&seen.lock().unwrap()) {
|
||||
return true;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metadata_files_count_and_locks_and_objects_do_not() {
|
||||
let dirs = BTreeMap::from([(PathBuf::from("/r/.git"), true), (PathBuf::from("/r/.git/refs"), false)]);
|
||||
for (path, expected) in [
|
||||
("/r/.git/HEAD", true),
|
||||
("/r/.git/index", true),
|
||||
("/r/.git/packed-refs", true),
|
||||
("/r/.git/refs/heads/main", true),
|
||||
("/r/.git/refs/heads/feature/x", true),
|
||||
("/r/.git/index.lock", false),
|
||||
("/r/.git/refs/heads/main.lock", false),
|
||||
("/r/.git/objects/aa/bb", false),
|
||||
("/r/.git/logs/HEAD", false),
|
||||
("/r/.git/COMMIT_EDITMSG", false),
|
||||
("/r/src/HEAD", false),
|
||||
] {
|
||||
assert_eq!(is_metadata(&dirs, Path::new(path)), expected, "{path}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The project folder is a subfolder of its repository, or a linked worktree: a commit made
|
||||
/// in a terminal writes only outside it, and still surfaces.
|
||||
#[test]
|
||||
fn external_commits_surface_for_projects_outside_their_git_dir() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let main = base.join("main");
|
||||
std::fs::create_dir_all(main.join("sub")).unwrap();
|
||||
git(&main, &["init", "-q", "-b", "main"]);
|
||||
git(&main, &["commit", "-q", "--allow-empty", "-m", "init"]);
|
||||
git(&main, &["worktree", "add", "-q", "-b", "topic", base.join("wt").to_str().unwrap()]);
|
||||
for project in [main.join("sub"), base.join("wt")] {
|
||||
let repo = Arc::new(Repo::discover(&project).unwrap().unwrap());
|
||||
let seen = Arc::new(Mutex::new(Vec::new()));
|
||||
let watch = {
|
||||
let seen = seen.clone();
|
||||
MetadataWatch::new(move |paths| seen.lock().unwrap().extend(paths)).unwrap()
|
||||
};
|
||||
watch.set_repos(std::slice::from_ref(&repo), &project);
|
||||
assert!(!watch.watched_dirs().is_empty(), "{}", project.display());
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
std::fs::write(project.join("a.txt"), project.to_string_lossy().as_bytes()).unwrap();
|
||||
git(&project, &["add", "a.txt"]);
|
||||
git(&project, &["commit", "-q", "-m", "change"]);
|
||||
assert!(
|
||||
wait_for(&seen, |p| p.iter().any(|p| p.starts_with(repo.metadata_dirs().unwrap()[1].join("refs")))),
|
||||
"{}: {:?}",
|
||||
project.display(),
|
||||
seen.lock().unwrap()
|
||||
);
|
||||
assert!(
|
||||
wait_for(&seen, |p| p.iter().any(|p| p.ends_with("index"))),
|
||||
"{}: {:?}",
|
||||
project.display(),
|
||||
seen.lock().unwrap()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_project_watcher_reports_its_git_dirs_but_not_submodule_ones() {
|
||||
let root = Path::new("/p");
|
||||
for (dir, expected) in [
|
||||
("/p/.git", true),
|
||||
("/p/.git/refs", true),
|
||||
("/p/.git/worktrees/wt", true),
|
||||
("/p/nested/.git", true),
|
||||
("/p/.git/modules/lib", false),
|
||||
("/p/.git/modules/lib/refs", false),
|
||||
("/p/.git/modules/a/modules/b", false),
|
||||
("/elsewhere/.git", false),
|
||||
] {
|
||||
assert_eq!(watched_by_project(root, Path::new(dir)), expected, "{dir}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metadata_below_the_covered_folder_is_left_to_the_project_watcher() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
git(&root, &["init", "-q"]);
|
||||
let repo = Arc::new(Repo::discover(&root).unwrap().unwrap());
|
||||
let watch = MetadataWatch::new(|_| {}).unwrap();
|
||||
watch.set_repos(std::slice::from_ref(&repo), &root);
|
||||
assert!(watch.watched_dirs().is_empty());
|
||||
watch.set_repos(std::slice::from_ref(&repo), &root.join("elsewhere"));
|
||||
assert_eq!(watch.watched_dirs().len(), 2, "{:?}", watch.watched_dirs());
|
||||
watch.set_repos(&[], &root);
|
||||
assert!(watch.watched_dirs().is_empty());
|
||||
}
|
||||
}
|
||||
@@ -430,6 +430,53 @@ test("Git Log puts affected changes on the changed-files toolbar and groups prev
|
||||
await expect(notes).toBeVisible();
|
||||
});
|
||||
|
||||
test("Git Log file selection stays in place and opens a diff on activation", async ({ workbench: page }) => {
|
||||
await page.clock.install();
|
||||
await page.evaluate(() => {
|
||||
window.__ipc.handlers.vcs_commit_files = () =>
|
||||
Array.from({ length: 30 }, (_, index) => ({
|
||||
path: `src/change-${String(index).padStart(2, "0")}.ts`,
|
||||
kind: "modified",
|
||||
oldPath: null,
|
||||
}));
|
||||
});
|
||||
await page.getByRole("listbox", { name: "Commits" }).getByRole("option").first().click();
|
||||
const tree = page.getByRole("tree", { name: "Changed files" });
|
||||
const first = tree.getByRole("treeitem", { name: "change-10.ts" });
|
||||
const second = tree.getByRole("treeitem", { name: "change-11.ts" });
|
||||
const firstDiff = page.getByRole("tab", { name: /^change-10\.ts/ });
|
||||
const secondDiff = page.getByRole("tab", { name: /^change-11\.ts/ });
|
||||
|
||||
await tree.evaluate((el) => (el.scrollTop = 24 * 11));
|
||||
await expect(first).toBeInViewport({ ratio: 1 });
|
||||
await expect(second).toBeInViewport({ ratio: 1 });
|
||||
const scrollTop = () => tree.evaluate((el) => el.scrollTop);
|
||||
const initialScroll = await scrollTop();
|
||||
await first.click();
|
||||
await page.clock.runFor(150);
|
||||
await expect(first).toHaveAttribute("aria-selected", "true");
|
||||
await expect(firstDiff).toHaveCount(0);
|
||||
expect(await scrollTop()).toBe(initialScroll);
|
||||
|
||||
await first.dblclick();
|
||||
await expect(firstDiff).toHaveAttribute("aria-selected", "true");
|
||||
expect(await scrollTop()).toBe(initialScroll);
|
||||
|
||||
await second.click();
|
||||
await expect(secondDiff).toHaveAttribute("aria-selected", "true");
|
||||
await expect(firstDiff).toHaveCount(0);
|
||||
await expect(second).toHaveAttribute("aria-selected", "true");
|
||||
expect(await scrollTop()).toBe(initialScroll);
|
||||
|
||||
await secondDiff.dblclick(); // Keep the preview tab open.
|
||||
await first.click();
|
||||
await page.clock.runFor(150);
|
||||
await expect(firstDiff).toHaveCount(0);
|
||||
await expect(secondDiff).toHaveAttribute("aria-selected", "true");
|
||||
await tree.press("Enter");
|
||||
await expect(firstDiff).toHaveAttribute("aria-selected", "true");
|
||||
});
|
||||
|
||||
test("Not Cherry-Picked Commits dims other rows while keeping unpicked commits readable", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
|
||||
@@ -679,3 +679,111 @@ test("Docker Compose dashboard shows per-service resource usage and named projec
|
||||
});
|
||||
await expect(detail).toContainText("27.40%", { timeout: 5000 });
|
||||
});
|
||||
|
||||
test("Docker Compose dashboard keeps its action row pinned when scrolling", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1200, height: 640 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const containers = Array.from({ length: 10 }, (_, idx) => {
|
||||
const n = idx + 1;
|
||||
return {
|
||||
id: `runner-${n}`,
|
||||
name: `selfhost-github-runner-${n}`,
|
||||
image: "myoung34/github-runner:latest",
|
||||
command: "./bin/Runner.Listener run",
|
||||
state: "running",
|
||||
status: "Up 24 hours",
|
||||
ports: "",
|
||||
createdAt: "2026-11-22T20:00:00Z",
|
||||
composeProject: "selfhost",
|
||||
composeService: `github-runner-${n}`,
|
||||
composeWorkingDir: "/work/selfhost",
|
||||
composeFiles: ["/work/selfhost/docker-compose.yml"],
|
||||
mounts: [],
|
||||
networks: ["selfhost_default"],
|
||||
};
|
||||
});
|
||||
const snapshot = {
|
||||
availability: { kind: "ready", clientVersion: "28.0.1", serverVersion: "28.0.1", context: "desktop-linux" },
|
||||
executable: "/usr/bin/docker",
|
||||
containers,
|
||||
images: [],
|
||||
volumes: [],
|
||||
networks: [],
|
||||
errors: [],
|
||||
};
|
||||
window.__ipc.handlers.docker_settings = () => ({
|
||||
connections: [{ id: "default", name: "Docker", endpoint: { kind: "default" } }],
|
||||
registries: [],
|
||||
});
|
||||
window.__ipc.handlers.docker_snapshot = () => snapshot;
|
||||
window.__ipc.handlers.docker_events = () => new Promise(() => {});
|
||||
window.__ipc.handlers.docker_inspect = () => "[]";
|
||||
window.__ipc.handlers.docker_container_stats = () => ({
|
||||
cpuPerc: "0.04%",
|
||||
memUsage: "99.85MiB / 114.3GiB",
|
||||
memPerc: "0.09%",
|
||||
netIo: "1.1MB / 3.75MB",
|
||||
blockIo: "0B / 213kB",
|
||||
pids: "15",
|
||||
});
|
||||
|
||||
const storeMod = "/src/features/services/store.ts";
|
||||
const treeMod = "/src/features/services/tree.ts";
|
||||
const { useServices } = await import(/* @vite-ignore */ storeMod);
|
||||
const { useServicesTree } = await import(/* @vite-ignore */ treeMod);
|
||||
useServices.setState({
|
||||
settings: { connections: [{ id: "default", name: "Docker", endpoint: { kind: "default" } }], registries: [] },
|
||||
conns: { default: { snapshot, loading: false, error: null } },
|
||||
});
|
||||
useServicesTree.setState({
|
||||
expanded: new Set(["docker:default"]),
|
||||
selectedKey: "docker:default:compose:selfhost",
|
||||
selectedKeys: new Set(["docker:default:compose:selfhost"]),
|
||||
});
|
||||
});
|
||||
|
||||
await page.keyboard.press("Meta+8");
|
||||
const services = page.getByRole("region", { name: "Services", exact: true });
|
||||
const detail = services.locator("[data-panel][id=services-detail]");
|
||||
const startBtn = detail.getByRole("button", { name: "Start", exact: true });
|
||||
const stopBtn = detail.getByRole("button", { name: "Stop", exact: true });
|
||||
const restartBtn = detail.getByRole("button", { name: "Restart", exact: true });
|
||||
const downBtn = detail.getByRole("button", { name: "Compose Down", exact: true });
|
||||
await expect(downBtn).toBeVisible();
|
||||
|
||||
const beforeStart = (await startBtn.boundingBox())!;
|
||||
const beforeDown = (await downBtn.boundingBox())!;
|
||||
const beforeBanner = (await detail.getByText("Compose project 'selfhost'").boundingBox())!;
|
||||
|
||||
const scrollState = await detail.evaluate((panel) => {
|
||||
const scrollers = Array.from(panel.querySelectorAll<HTMLElement>("*")).filter((el) => {
|
||||
const cs = getComputedStyle(el);
|
||||
return (cs.overflowY === "auto" || cs.overflowY === "scroll") && el.scrollHeight - el.clientHeight > 2;
|
||||
});
|
||||
scrollers[0]!.scrollTop = 160;
|
||||
return {
|
||||
scrollerCount: scrollers.length,
|
||||
scrollTop: scrollers[0]!.scrollTop,
|
||||
scrollerTop: scrollers[0]!.getBoundingClientRect().top,
|
||||
};
|
||||
});
|
||||
|
||||
expect(scrollState.scrollerCount).toBe(1);
|
||||
expect(scrollState.scrollTop).toBeGreaterThan(100);
|
||||
// The scroll container starts strictly below the pinned action row.
|
||||
expect(scrollState.scrollerTop).toBeGreaterThanOrEqual(beforeDown.y + beforeDown.height);
|
||||
|
||||
await expect(startBtn).toBeVisible();
|
||||
await expect(stopBtn).toBeVisible();
|
||||
await expect(restartBtn).toBeVisible();
|
||||
await expect(downBtn).toBeVisible();
|
||||
|
||||
const afterStart = (await startBtn.boundingBox())!;
|
||||
const afterDown = (await downBtn.boundingBox())!;
|
||||
const afterBanner = (await detail.getByText("Compose project 'selfhost'").boundingBox())!;
|
||||
|
||||
expect(afterStart.y).toBe(beforeStart.y);
|
||||
expect(afterDown.y).toBe(beforeDown.y);
|
||||
expect(afterBanner.y).toBeLessThan(beforeBanner.y - 100);
|
||||
});
|
||||
+10
-4
@@ -228,6 +228,14 @@ mod tests {
|
||||
(coalescing_sink(Arc::new(move |event| saved.lock().push(event)), tokio::runtime::Handle::current()), events)
|
||||
}
|
||||
|
||||
/// Waits for the coalescing window to flush `n` events (a fixed sleep is too short on slow CI timers).
|
||||
async fn wait_for_events(events: &Mutex<Vec<IdeEvent>>, n: usize) {
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(5);
|
||||
while events.lock().len() < n && std::time::Instant::now() < deadline {
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
}
|
||||
|
||||
fn diagnostics(path: &str, source: &str, message: &str) -> IdeEvent {
|
||||
IdeEvent::Diagnostics {
|
||||
path: IpcPath::from(path),
|
||||
@@ -316,9 +324,7 @@ mod tests {
|
||||
sink.emit(diagnostics("/p/b.rs", "rust-analyzer", "other"));
|
||||
|
||||
assert!(events.lock().is_empty());
|
||||
tokio::task::yield_now().await;
|
||||
tokio::time::sleep(Duration::from_millis(30)).await;
|
||||
tokio::task::yield_now().await;
|
||||
wait_for_events(&events, 3).await;
|
||||
|
||||
{
|
||||
let saved_events = events.lock();
|
||||
@@ -381,7 +387,7 @@ mod tests {
|
||||
}
|
||||
assert_eq!(events.lock().len(), MAX_PENDING_DIAGNOSTICS);
|
||||
|
||||
tokio::time::sleep(Duration::from_millis(30)).await;
|
||||
wait_for_events(&events, MAX_PENDING_DIAGNOSTICS + 1).await;
|
||||
assert_eq!(events.lock().len(), MAX_PENDING_DIAGNOSTICS + 1);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
import { beforeAll, describe, expect, it } from "vitest";
|
||||
import type { LanguageSupport } from "@codemirror/language";
|
||||
import { highlightTree, tags as t, type Tag } from "@lezer/highlight";
|
||||
import { findLanguageDescription, loadSupport } from "./languages";
|
||||
import { openideaHighlightStyle } from "./highlight";
|
||||
|
||||
let java: LanguageSupport;
|
||||
|
||||
beforeAll(async () => {
|
||||
java = (await loadSupport(findLanguageDescription("Java", "")!))!;
|
||||
});
|
||||
|
||||
function tokens(doc: string): { text: string; cls: string }[] {
|
||||
const out: { text: string; cls: string }[] = [];
|
||||
highlightTree(java.language.parser.parse(doc), openideaHighlightStyle, (from, to, cls) => {
|
||||
out.push({ text: doc.slice(from, to), cls });
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
const cls = (tag: Tag) => openideaHighlightStyle.style([tag])!;
|
||||
|
||||
function expectTokens(doc: string, expected: readonly (readonly [string, Tag])[]) {
|
||||
const got = tokens(doc);
|
||||
for (const [text, tag] of expected) expect(got, text).toContainEqual({ text, cls: cls(tag) });
|
||||
}
|
||||
|
||||
/** The literal holding `text` is one string token: nothing is embedded. */
|
||||
function expectPlainString(doc: string, text: string) {
|
||||
expect(
|
||||
tokens(doc).some((tok) => tok.cls === cls(t.string) && tok.text.includes(text)),
|
||||
text,
|
||||
).toBe(true);
|
||||
}
|
||||
|
||||
const JPA = "import org.springframework.data.jpa.repository.Query;\n";
|
||||
const VALUE = "import org.springframework.beans.factory.annotation.Value;\n";
|
||||
|
||||
describe("Java annotation string languages", () => {
|
||||
it("highlights JPQL in Spring Data JPA @Query, also concatenated and as countQuery", () => {
|
||||
const doc = `${JPA}interface Repo {
|
||||
@Query(value = "select u from User u " + "where u.email = :email", countQuery = "select count(u) from User u")
|
||||
User find(String email);
|
||||
}`;
|
||||
expectTokens(doc, [
|
||||
["select", t.keyword],
|
||||
["from", t.keyword],
|
||||
["where", t.keyword],
|
||||
["count", t.keyword],
|
||||
// The quotes stay the Java string's.
|
||||
['"', t.string],
|
||||
]);
|
||||
expect(tokens(doc).filter((tok) => tok.cls === cls(t.string) && tok.text.includes("select"))).toEqual([]);
|
||||
// JPQL names entities: `User` is not SQL's `USER` keyword.
|
||||
expect(tokens(doc).filter((tok) => tok.text === "User" && tok.cls === cls(t.keyword))).toEqual([]);
|
||||
});
|
||||
|
||||
it("highlights native SQL in a text block", () => {
|
||||
const doc = `${JPA}interface Repo {
|
||||
@Query(nativeQuery = true, value = """
|
||||
SELECT * FROM User WHERE id = 1
|
||||
""")
|
||||
User find();
|
||||
}`;
|
||||
expectTokens(doc, [
|
||||
["SELECT", t.keyword],
|
||||
["WHERE", t.keyword],
|
||||
["1", t.number],
|
||||
// Native SQL keeps SQL's keywords.
|
||||
["User", t.keyword],
|
||||
]);
|
||||
});
|
||||
|
||||
it("resolves the annotation through a package import or its qualified name", () => {
|
||||
expectTokens('import org.springframework.data.jpa.repository.*;\ninterface R { @Query("select 1") void f(); }', [
|
||||
["select", t.keyword],
|
||||
]);
|
||||
expectTokens('interface R { @org.springframework.data.jpa.repository.Query("select 1") void f(); }', [
|
||||
["select", t.keyword],
|
||||
]);
|
||||
});
|
||||
|
||||
it("leaves other annotations named Query as plain strings", () => {
|
||||
expectPlainString('import com.example.Query;\ninterface R { @Query("select u from User u") void f(); }', "select");
|
||||
expectPlainString('interface R { @Query("select u from User u") void f(); }', "select");
|
||||
expectPlainString(
|
||||
'import org.springframework.data.mongodb.repository.Query;\ninterface R { @Query("{ name: ?0 }") void f(); }',
|
||||
"name",
|
||||
);
|
||||
expectPlainString(
|
||||
'import org.springframework.data.mongodb.repository.*;\ninterface R { @Query("{ name: ?0 }") void f(); }',
|
||||
"name",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps escape sequences out of the embedded text", () => {
|
||||
const doc = `${JPA}interface R { @Query("select u from User u where u.name = \\"x\\"") void f(); }`;
|
||||
const got = tokens(doc);
|
||||
// The escapes keep the Java string's colour; the escape colouring of the semantic layer marks them.
|
||||
expect(got).toContainEqual({ text: '\\"', cls: cls(t.string) });
|
||||
expect(got).toContainEqual({ text: "where", cls: cls(t.keyword) });
|
||||
// The escaped quotes don't open an SQL quoted identifier: `x` is plain text.
|
||||
expect(got.filter((tok) => tok.text.includes("x"))).toEqual([]);
|
||||
});
|
||||
|
||||
it("highlights placeholders and SpEL in @Value", () => {
|
||||
const doc = `${VALUE}class C {
|
||||
@Value("\${app.timeout:30}") int timeout;
|
||||
@Value("#{systemProperties['user.region'] ?: 'eu'}") String region;
|
||||
@Value("prefix-#{@config.name()}") String name;
|
||||
}`;
|
||||
expectTokens(doc, [
|
||||
["${", t.meta],
|
||||
["app.timeout", t.propertyName],
|
||||
["30", t.string],
|
||||
["#{", t.meta],
|
||||
["}", t.meta],
|
||||
["systemProperties", t.variableName],
|
||||
["'user.region'", t.string],
|
||||
["?:", t.operator],
|
||||
["prefix-", t.string],
|
||||
["#{@config", t.meta],
|
||||
["name", t.function(t.propertyName)],
|
||||
]);
|
||||
});
|
||||
|
||||
it("highlights the whole value as SpEL in security and cache annotations", () => {
|
||||
const doc = `import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
class C {
|
||||
@PreAuthorize("hasRole('ADMIN') and #id == authentication.principal.id")
|
||||
@Cacheable(cacheNames = "users", key = "#id", unless = "#result == null")
|
||||
User find(long id) { return null; }
|
||||
}`;
|
||||
expectTokens(doc, [
|
||||
["hasRole", t.function(t.variableName)],
|
||||
["'ADMIN'", t.string],
|
||||
["and", t.keyword],
|
||||
["#id", t.standard(t.variableName)],
|
||||
["principal", t.propertyName],
|
||||
["#result", t.standard(t.variableName)],
|
||||
["null", t.null],
|
||||
]);
|
||||
// Not a SpEL attribute.
|
||||
expectPlainString(doc, "users");
|
||||
});
|
||||
|
||||
it("closes #{…} after an inline list", () => {
|
||||
expectTokens(`${VALUE}class C { @Value("#{ {1, 2}.size() } items") int n; }`, [
|
||||
["size", t.function(t.propertyName)],
|
||||
[" items", t.string],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,261 @@
|
||||
/**
|
||||
* Embedded languages in Java annotation strings, as IntelliJ IDEA Ultimate's Spring support
|
||||
* injects them: JPQL (SQL with `nativeQuery = true`) in Spring Data JPA's `@Query`, SpEL in `@PreAuthorize`, `@Cacheable(key = …)`
|
||||
* and the like, and SpEL `#{…}` with property placeholders `${…}` in `@Value` and
|
||||
* `@ConditionalOnExpression`.
|
||||
*
|
||||
* An annotation counts only by its resolved name: written fully qualified, or by a simple name the file
|
||||
* imports (the class itself or its package with `.*`), so a project's own `@Query` keeps a plain string.
|
||||
* Escape sequences stay outside the embedded text and keep the Java string's colours.
|
||||
*/
|
||||
import { LanguageSupport, LRLanguage, StreamLanguage, type StringStream } from "@codemirror/language";
|
||||
import { java } from "@codemirror/lang-java";
|
||||
import {
|
||||
parseMixed,
|
||||
type Input,
|
||||
type NestedParse,
|
||||
type Parser,
|
||||
type SyntaxNode,
|
||||
type SyntaxNodeRef,
|
||||
} from "@lezer/common";
|
||||
import { SQLDialect, StandardSQL } from "@codemirror/lang-sql";
|
||||
|
||||
type Embedded = "SQL" | "SpEL" | "SpEL template";
|
||||
|
||||
const PREPOST = "org.springframework.security.access.prepost.";
|
||||
const CACHE = "org.springframework.cache.annotation.";
|
||||
const CACHE_ATTRIBUTES = {
|
||||
key: "SpEL",
|
||||
condition: "SpEL",
|
||||
unless: "SpEL",
|
||||
} as const;
|
||||
|
||||
/** Annotation class → attribute → embedded language. */
|
||||
const INJECTIONS: Record<string, Record<string, Embedded>> = {
|
||||
"org.springframework.data.jpa.repository.Query": {
|
||||
value: "SQL",
|
||||
countQuery: "SQL",
|
||||
},
|
||||
"org.springframework.beans.factory.annotation.Value": {
|
||||
value: "SpEL template",
|
||||
},
|
||||
"org.springframework.boot.autoconfigure.condition.ConditionalOnExpression": {
|
||||
value: "SpEL template",
|
||||
},
|
||||
[`${PREPOST}PreAuthorize`]: { value: "SpEL" },
|
||||
[`${PREPOST}PostAuthorize`]: { value: "SpEL" },
|
||||
[`${PREPOST}PreFilter`]: { value: "SpEL" },
|
||||
[`${PREPOST}PostFilter`]: { value: "SpEL" },
|
||||
[`${CACHE}Cacheable`]: CACHE_ATTRIBUTES,
|
||||
[`${CACHE}CachePut`]: CACHE_ATTRIBUTES,
|
||||
[`${CACHE}CacheEvict`]: CACHE_ATTRIBUTES,
|
||||
};
|
||||
|
||||
const SIMPLE_NAMES = new Set(Object.keys(INJECTIONS).map((name) => name.slice(name.lastIndexOf(".") + 1)));
|
||||
|
||||
const text = (node: SyntaxNode, input: Input) => input.read(node.from, node.to).replace(/\s+/g, "");
|
||||
|
||||
/** The annotation's class: `name` as written when qualified, else the import that brings it in. */
|
||||
function annotationClass(annotation: SyntaxNode, input: Input): string | null {
|
||||
const nameNode = annotation.getChild("Identifier") ?? annotation.getChild("ScopedIdentifier");
|
||||
if (!nameNode) return null;
|
||||
const name = text(nameNode, input);
|
||||
if (name.includes(".")) return name;
|
||||
if (!SIMPLE_NAMES.has(name)) return null;
|
||||
let program = annotation;
|
||||
while (program.parent) program = program.parent;
|
||||
for (const decl of program.getChildren("ImportDeclaration")) {
|
||||
if (decl.getChild("static")) continue;
|
||||
const path = decl.getChild("ScopedIdentifier");
|
||||
if (!path) continue;
|
||||
const imported = text(path, input);
|
||||
if (!decl.getChild("Asterisk")) {
|
||||
if (imported.endsWith(`.${name}`)) return imported;
|
||||
} else if (INJECTIONS[`${imported}.${name}`]) return `${imported}.${name}`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The string literals of an attribute value: one literal, or several joined with `+`. */
|
||||
function literals(value: SyntaxNode, out: SyntaxNode[] = []): SyntaxNode[] {
|
||||
if (value.name === "StringLiteral" || value.name === "TextBlock") out.push(value);
|
||||
else if (value.name === "BinaryExpression" || value.name === "ParenthesizedExpression")
|
||||
for (let child = value.firstChild; child; child = child.nextSibling) literals(child, out);
|
||||
return out;
|
||||
}
|
||||
|
||||
const ESCAPE = /\\(?:u+[0-9a-fA-F]{4}|[0-7]{1,3}|[\s\S])/g;
|
||||
|
||||
/** The literal's text between its quotes, without escape sequences. */
|
||||
function contentRanges(literal: SyntaxNode, input: Input, out: { from: number; to: number }[]) {
|
||||
const quote = literal.name === "TextBlock" ? 3 : 1;
|
||||
const from = literal.from + quote;
|
||||
const raw = input.read(literal.from, literal.to);
|
||||
const closed = raw.length >= 2 * quote && raw.endsWith(quote === 3 ? '"""' : '"');
|
||||
const to = closed ? literal.to - quote : literal.to;
|
||||
let start = from;
|
||||
// ponytail: an escape splits the embedded text, so `FROM\nUser` reads as `FROMUser`; rare in queries.
|
||||
for (const m of input.read(from, to).matchAll(ESCAPE)) {
|
||||
const at = from + m.index;
|
||||
if (at > start) out.push({ from: start, to: at });
|
||||
start = at + m[0].length;
|
||||
}
|
||||
if (to > start) out.push({ from: start, to });
|
||||
}
|
||||
|
||||
const SPEL_KEYWORDS = /^(?:and|or|not|eq|ne|lt|gt|le|ge|div|mod|instanceof|matches|between|new|T)\b(?![\w$])/;
|
||||
|
||||
interface Frame {
|
||||
kind: "#" | "$";
|
||||
/** Inside a placeholder, past the `:` before its default value. */
|
||||
fallback: boolean;
|
||||
/** Open `{` of inline lists and maps inside a `#{…}`. */
|
||||
braces: number;
|
||||
}
|
||||
|
||||
interface SpelState {
|
||||
/** Open `#{` / `${`. Outside them a template string is text and an expression-only string is SpEL. */
|
||||
stack: Frame[];
|
||||
/** The last token was `.` or `?.`: a property or method name follows. */
|
||||
member: boolean;
|
||||
}
|
||||
|
||||
function spelToken(stream: StringStream, state: SpelState, template: boolean): string | null {
|
||||
if (stream.match(/^[#$]\{/)) {
|
||||
state.stack.push({
|
||||
kind: stream.current()[0] as "#" | "$",
|
||||
fallback: false,
|
||||
braces: 0,
|
||||
});
|
||||
return "meta";
|
||||
}
|
||||
const frame = state.stack[state.stack.length - 1];
|
||||
if (frame && (frame.kind === "$" || !frame.braces) && stream.eat("}")) {
|
||||
state.stack.pop();
|
||||
return "meta";
|
||||
}
|
||||
if (template && !frame) {
|
||||
if (!stream.match(/^[^#$]+/)) stream.next();
|
||||
return "string";
|
||||
}
|
||||
if (frame?.kind === "$") {
|
||||
if (frame.fallback) {
|
||||
if (!stream.match(/^[^#$}]+/)) stream.next();
|
||||
return "string";
|
||||
}
|
||||
if (stream.eat(":")) {
|
||||
frame.fallback = true;
|
||||
return "operator";
|
||||
}
|
||||
if (!stream.match(/^[^:#$}]+/)) stream.next();
|
||||
return "propertyName";
|
||||
}
|
||||
if (stream.eatSpace()) return null;
|
||||
const member = state.member;
|
||||
state.member = false;
|
||||
if (stream.eat("'")) {
|
||||
while (!stream.eol()) if (stream.next() === "'" && !stream.eat("'")) break;
|
||||
return "string";
|
||||
}
|
||||
if (stream.match(/^\d+(?:\.\d+)?(?:[eE][-+]?\d+)?[lLfFdD]?/)) return "number";
|
||||
if (stream.match(/^#\w+/)) return "variableName.standard";
|
||||
if (stream.match(/^[@&][\w$]+/)) return "meta";
|
||||
if (!member && stream.match(/^(?:true|false)\b/)) return "bool";
|
||||
if (!member && stream.match(/^null\b/)) return "null";
|
||||
if (!member && stream.match(SPEL_KEYWORDS)) return "keyword";
|
||||
if (stream.match(/^[A-Za-z_$][\w$]*/)) {
|
||||
const call = stream.match(/^\s*\(/, false);
|
||||
if (member) return call ? "propertyName.function" : "propertyName";
|
||||
return call ? "variableName.function" : "variableName";
|
||||
}
|
||||
if (stream.match(/^\??\./)) {
|
||||
state.member = true;
|
||||
return "derefOperator";
|
||||
}
|
||||
if (stream.match(/^(?:\?:|\.\?|\.\^|\.\$|[!=<>]=?|&&|\|\||[-+*/%^?:])/)) return "operator";
|
||||
if (frame && stream.match(/^[{}]/)) frame.braces += stream.current() === "{" ? 1 : -1;
|
||||
else if (!stream.match(/^[()[\]{}]/)) {
|
||||
if (stream.eat(",")) return "separator";
|
||||
stream.next();
|
||||
return null;
|
||||
}
|
||||
return "bracket";
|
||||
}
|
||||
|
||||
function spel(template: boolean): Parser {
|
||||
return StreamLanguage.define<SpelState>({
|
||||
name: template ? "spel-template" : "spel",
|
||||
startState: () => ({ stack: [], member: false }),
|
||||
copyState: (s) => ({
|
||||
stack: s.stack.map((f) => ({ ...f })),
|
||||
member: s.member,
|
||||
}),
|
||||
token: (stream, state) => spelToken(stream, state, template),
|
||||
}).parser;
|
||||
}
|
||||
|
||||
/** JPQL / HQL: entity names such as `User` or `Order` are not keywords, unlike in SQL. */
|
||||
const JPQL_KEYWORDS =
|
||||
"select from where and or not as join left right inner outer full cross fetch on with distinct order by group " +
|
||||
"having asc desc nulls first last in like escape between is null empty member of exists all any some case when " +
|
||||
"then else end new update set delete insert into union intersect except true false count sum avg min max upper " +
|
||||
"lower trim leading trailing both length locate abs sqrt mod size index key value entry treat type coalesce " +
|
||||
"nullif concat substring cast extract function current_date current_time current_timestamp object limit offset";
|
||||
|
||||
let parsers: Record<Embedded | "JPQL", Parser> | null = null;
|
||||
|
||||
/** Whether `@Query(…)` has `nativeQuery = true`. */
|
||||
function nativeQuery(args: SyntaxNode, input: Input): boolean {
|
||||
return args
|
||||
.getChildren("ElementValuePair")
|
||||
.some((pair) => /^nativeQuery\s*=\s*true$/.test(input.read(pair.from, pair.to)));
|
||||
}
|
||||
|
||||
/** The nested parse for an annotation attribute value (`ElementValuePair`) or a lone value. */
|
||||
export function javaInjection() {
|
||||
return (ref: SyntaxNodeRef, input: Input): NestedParse | null => {
|
||||
// Called for every node on each parse: rule out the rest before materializing the node.
|
||||
if (ref.name !== "ElementValuePair" && ref.name !== "AnnotationArgumentList") return null;
|
||||
const node = ref.node;
|
||||
let attribute: string;
|
||||
let value: SyntaxNode | null;
|
||||
let annotation: SyntaxNode | null;
|
||||
if (node.name === "ElementValuePair") {
|
||||
const name = node.getChild("Identifier");
|
||||
attribute = name ? input.read(name.from, name.to) : "";
|
||||
value = node.lastChild;
|
||||
annotation = node.parent?.parent ?? null;
|
||||
} else {
|
||||
// `@Ann("…")`: the value attribute's shorthand.
|
||||
attribute = "value";
|
||||
value = node.firstChild?.nextSibling ?? null;
|
||||
if (value?.name === "ElementValuePair") return null;
|
||||
annotation = node.parent;
|
||||
}
|
||||
if (!value || annotation?.name !== "Annotation") return null;
|
||||
const cls = annotationClass(annotation, input);
|
||||
const language = cls ? INJECTIONS[cls]?.[attribute] : undefined;
|
||||
if (!language) return null;
|
||||
const overlay: { from: number; to: number }[] = [];
|
||||
for (const literal of literals(value)) contentRanges(literal, input, overlay);
|
||||
if (!overlay.length) return null;
|
||||
parsers ??= {
|
||||
SQL: StandardSQL.language.parser,
|
||||
JPQL: SQLDialect.define({ keywords: JPQL_KEYWORDS, types: "", builtin: "" }).language.parser,
|
||||
SpEL: spel(false),
|
||||
"SpEL template": spel(true),
|
||||
};
|
||||
// ponytail: the mount is per attribute, so toggling `nativeQuery` restyles the query once it is edited.
|
||||
const jpql = language === "SQL" && !nativeQuery(annotation.getChild("AnnotationArgumentList")!, input);
|
||||
return { parser: parsers[jpql ? "JPQL" : language], overlay };
|
||||
};
|
||||
}
|
||||
|
||||
/** `java()` that also parses the embedded languages of Spring annotation strings. */
|
||||
export function javaWithInjections(): LanguageSupport {
|
||||
const base = java();
|
||||
const language = (base.language as LRLanguage).configure({
|
||||
wrap: parseMixed(javaInjection()),
|
||||
});
|
||||
return new LanguageSupport(language, base.support);
|
||||
}
|
||||
@@ -411,6 +411,29 @@ describe("language modes", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("leaves Java statement labels uncoloured, unlike JavaScript's", async () => {
|
||||
const highlighter = tagHighlighter([
|
||||
{ tag: t.labelName, class: "label" },
|
||||
{ tag: t.variableName, class: "variable" },
|
||||
]);
|
||||
const labels = async (mode: string, path: string, doc: string) => {
|
||||
const support = await loadSupport(findLanguageDescription(mode, path)!);
|
||||
const found: string[] = [];
|
||||
highlightTree(support!.language.parser.parse(doc), highlighter, (from, to, style) =>
|
||||
found.push(`${doc.slice(from, to)}:${style}`),
|
||||
);
|
||||
return found.filter((s) => s.startsWith("outer"));
|
||||
};
|
||||
expect(await labels("Java", "/p/A.java", "class A { void f() { outer: for (;;) { break outer; } } }")).toEqual([
|
||||
"outer:variable",
|
||||
"outer:variable",
|
||||
]);
|
||||
expect(await labels("JavaScript", "/p/a.js", "outer: for (;;) { break outer; }")).toEqual([
|
||||
"outer:label",
|
||||
"outer:label",
|
||||
]);
|
||||
});
|
||||
|
||||
it("recognizes go.mod and go.work files by mode and filename", async () => {
|
||||
for (const [mode, path] of [
|
||||
["GoMod", "/project/go.mod"],
|
||||
|
||||
@@ -224,6 +224,11 @@ const OWN_MODES = [
|
||||
load: () => import("./templateLanguages").then((m) => m.javascriptWithTemplates(config, templateLanguage)),
|
||||
}),
|
||||
),
|
||||
// JPQL / SQL in `@Query`, SpEL and property placeholders in Spring annotation strings.
|
||||
LanguageDescription.of({
|
||||
name: "Java",
|
||||
load: () => import("./javaInjections").then((m) => m.javaWithInjections()),
|
||||
}),
|
||||
// Only for template literals: `.graphql` files keep the backend's tree-sitter highlighting.
|
||||
LanguageDescription.of({
|
||||
name: "GraphQL",
|
||||
@@ -495,6 +500,8 @@ const CSS_TAGS: Parameters<typeof styleTags>[0] = {
|
||||
export const JAVA_TAGS: Parameters<typeof styleTags>[0] = {
|
||||
"MarkerAnnotation/Identifier Annotation/Identifier MarkerAnnotation Annotation": t.annotation,
|
||||
this: t.keyword,
|
||||
// IntelliJ has no Java label colour: `outer:` stays plain text, like `break outer`.
|
||||
Label: t.variableName,
|
||||
};
|
||||
|
||||
// @lezer/go leaves `default` uncoloured, unlike `case` and `switch`.
|
||||
|
||||
@@ -2171,8 +2171,10 @@ export class EditorController implements SlotHost {
|
||||
return this.removeGuarded((s) => closeKey(s, key));
|
||||
}
|
||||
|
||||
activeInput(): EditorInput | null {
|
||||
return this.activeTabOf()?.input ?? null;
|
||||
activeInput(options?: { previewOnly?: boolean }): EditorInput | null {
|
||||
const tab = this.activeTabOf();
|
||||
if (options?.previewOnly && (!tab?.preview || !editorPrefs().tabs.previewTab)) return null;
|
||||
return tab?.input ?? null;
|
||||
}
|
||||
|
||||
onActiveInputChange(fn: (input: EditorInput | null) => void): () => void {
|
||||
|
||||
@@ -58,7 +58,7 @@ export function activate(): void | (() => void) {
|
||||
onOpenTabsChange: (fn) => useTabs.subscribe(fn),
|
||||
openTabs: () => ctrl.openTabs(),
|
||||
tabInput: (paneId, tabId) => ctrl.tabInput(paneId, tabId),
|
||||
activeInput: () => ctrl.activeInput(),
|
||||
activeInput: (options) => ctrl.activeInput(options),
|
||||
onActiveInputChange: (fn) => ctrl.onActiveInputChange(fn),
|
||||
closePath: (path) => ctrl.closePath(path),
|
||||
closeInput: (key) => ctrl.closeInput(key),
|
||||
|
||||
@@ -96,6 +96,7 @@
|
||||
}
|
||||
.detailPane {
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
@@ -235,6 +236,7 @@
|
||||
user-select: text;
|
||||
}
|
||||
.dashboardActions {
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
@@ -254,6 +256,10 @@
|
||||
border-top: 1px solid var(--border);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.dashboard > .sectionBanner:first-child,
|
||||
.dashboardActions + .sectionBanner {
|
||||
border-top: 0;
|
||||
}
|
||||
.propList {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
+138
-136
@@ -1888,7 +1888,7 @@ export function ComposeProjectDashboard({
|
||||
const { byId: activeStats, loading: statsLoading } = useLiveContainerStats(conn, runningIdsKey);
|
||||
|
||||
return (
|
||||
<div className={styles.dashboard} tabIndex={0} onKeyDown={copySelectionOnKeyDown}>
|
||||
<div className={styles.detailBody}>
|
||||
<div className={styles.dashboardActions}>
|
||||
<OpButton busy={busy === "start"} disabled={!canStart(target)} onClick={() => void start(target)}>
|
||||
Start
|
||||
@@ -1904,144 +1904,146 @@ export function ComposeProjectDashboard({
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<SectionBanner>{txTemplate(`Compose project '${project}'`)}</SectionBanner>
|
||||
<div className={styles.propList}>
|
||||
<PropRow label={<T>Project</T>}>
|
||||
<span className={styles.mono}>{project}</span>
|
||||
</PropRow>
|
||||
<PropRow label={<T>Status</T>}>
|
||||
<span>
|
||||
{runningCount}/{containers.length} running
|
||||
</span>
|
||||
</PropRow>
|
||||
<PropRow label={<T>Working directory</T>} hidden={!first?.composeWorkingDir}>
|
||||
<span className={styles.mono}>{first?.composeWorkingDir}</span>
|
||||
</PropRow>
|
||||
<PropRow label={<T>Compose files</T>} hidden={!first?.composeFiles.length}>
|
||||
<span className={styles.inlineRow}>
|
||||
{first?.composeFiles.map((file) => (
|
||||
<button
|
||||
key={file}
|
||||
type="button"
|
||||
className={styles.link}
|
||||
onClick={() => void openComposeFile(file, first.composeWorkingDir)}
|
||||
>
|
||||
<span className={styles.mono}>{file}</span>
|
||||
</button>
|
||||
))}
|
||||
</span>
|
||||
</PropRow>
|
||||
</div>
|
||||
<div className={styles.dashboard} tabIndex={0} onKeyDown={copySelectionOnKeyDown}>
|
||||
<SectionBanner>{txTemplate(`Compose project '${project}'`)}</SectionBanner>
|
||||
<div className={styles.propList}>
|
||||
<PropRow label={<T>Project</T>}>
|
||||
<span className={styles.mono}>{project}</span>
|
||||
</PropRow>
|
||||
<PropRow label={<T>Status</T>}>
|
||||
<span>
|
||||
{runningCount}/{containers.length} running
|
||||
</span>
|
||||
</PropRow>
|
||||
<PropRow label={<T>Working directory</T>} hidden={!first?.composeWorkingDir}>
|
||||
<span className={styles.mono}>{first?.composeWorkingDir}</span>
|
||||
</PropRow>
|
||||
<PropRow label={<T>Compose files</T>} hidden={!first?.composeFiles.length}>
|
||||
<span className={styles.inlineRow}>
|
||||
{first?.composeFiles.map((file) => (
|
||||
<button
|
||||
key={file}
|
||||
type="button"
|
||||
className={styles.link}
|
||||
onClick={() => void openComposeFile(file, first.composeWorkingDir)}
|
||||
>
|
||||
<span className={styles.mono}>{file}</span>
|
||||
</button>
|
||||
))}
|
||||
</span>
|
||||
</PropRow>
|
||||
</div>
|
||||
|
||||
<SectionBanner>
|
||||
<T>Services</T>
|
||||
</SectionBanner>
|
||||
<div className={styles.composeTableWrap}>
|
||||
<table className={clsx(styles.gridTable, styles.composeServicesTable)}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>
|
||||
<T>Service</T>
|
||||
</th>
|
||||
<th>
|
||||
<T>Status</T>
|
||||
</th>
|
||||
<th>
|
||||
<T>CPU</T>
|
||||
</th>
|
||||
<th>
|
||||
<T>Memory</T>
|
||||
</th>
|
||||
<th>
|
||||
<T>Network I/O</T>
|
||||
</th>
|
||||
<th>
|
||||
<T>Block I/O</T>
|
||||
</th>
|
||||
<th>
|
||||
<T>PIDs</T>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{containers.map((c) => {
|
||||
const running = isRunning(c);
|
||||
const stats = running ? activeStats[c.id] : undefined;
|
||||
const cpuPct = stats ? parsePercent(stats.cpuPerc) : 0;
|
||||
const memPair = stats ? parseUsagePair(stats.memUsage) : null;
|
||||
const memPct = memPair ? memPair.percent : stats ? parsePercent(stats.memPerc) : 0;
|
||||
return (
|
||||
<tr key={c.id}>
|
||||
<td className={styles.composeServiceCell}>
|
||||
<button type="button" className={styles.link} onClick={() => selectContainerInTree(conn, c)}>
|
||||
<span className={clsx(styles.statusDot, running ? styles.dotOk : styles.dotMuted)} />
|
||||
<span className={styles.mono}>{c.name}</span>
|
||||
</button>
|
||||
{c.composeService && !c.name.includes(c.composeService) && (
|
||||
<span className={styles.mutedMeta}>{c.composeService}</span>
|
||||
)}
|
||||
</td>
|
||||
<td className={styles.nowrapCell}>
|
||||
<StatusBadge state={c.state} text={c.status || c.state} />
|
||||
</td>
|
||||
<td className={styles.composeMetricCell}>
|
||||
{stats ? (
|
||||
<div className={styles.composeMetric}>
|
||||
<span className={styles.mono}>{stats.cpuPerc}</span>
|
||||
<LineProgress percent={cpuPct} />
|
||||
</div>
|
||||
) : running && statsLoading ? (
|
||||
<Spinner size={12} />
|
||||
) : (
|
||||
<span className={styles.mutedMeta}>—</span>
|
||||
)}
|
||||
</td>
|
||||
<td className={styles.composeMemoryCell}>
|
||||
{stats ? (
|
||||
<div className={styles.composeMetric}>
|
||||
<span className={styles.mono}>
|
||||
{stats.memUsage} ({stats.memPerc})
|
||||
<SectionBanner>
|
||||
<T>Services</T>
|
||||
</SectionBanner>
|
||||
<div className={styles.composeTableWrap}>
|
||||
<table className={clsx(styles.gridTable, styles.composeServicesTable)}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>
|
||||
<T>Service</T>
|
||||
</th>
|
||||
<th>
|
||||
<T>Status</T>
|
||||
</th>
|
||||
<th>
|
||||
<T>CPU</T>
|
||||
</th>
|
||||
<th>
|
||||
<T>Memory</T>
|
||||
</th>
|
||||
<th>
|
||||
<T>Network I/O</T>
|
||||
</th>
|
||||
<th>
|
||||
<T>Block I/O</T>
|
||||
</th>
|
||||
<th>
|
||||
<T>PIDs</T>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{containers.map((c) => {
|
||||
const running = isRunning(c);
|
||||
const stats = running ? activeStats[c.id] : undefined;
|
||||
const cpuPct = stats ? parsePercent(stats.cpuPerc) : 0;
|
||||
const memPair = stats ? parseUsagePair(stats.memUsage) : null;
|
||||
const memPct = memPair ? memPair.percent : stats ? parsePercent(stats.memPerc) : 0;
|
||||
return (
|
||||
<tr key={c.id}>
|
||||
<td className={styles.composeServiceCell}>
|
||||
<button type="button" className={styles.link} onClick={() => selectContainerInTree(conn, c)}>
|
||||
<span className={clsx(styles.statusDot, running ? styles.dotOk : styles.dotMuted)} />
|
||||
<span className={styles.mono}>{c.name}</span>
|
||||
</button>
|
||||
{c.composeService && !c.name.includes(c.composeService) && (
|
||||
<span className={styles.mutedMeta}>{c.composeService}</span>
|
||||
)}
|
||||
</td>
|
||||
<td className={styles.nowrapCell}>
|
||||
<StatusBadge state={c.state} text={c.status || c.state} />
|
||||
</td>
|
||||
<td className={styles.composeMetricCell}>
|
||||
{stats ? (
|
||||
<div className={styles.composeMetric}>
|
||||
<span className={styles.mono}>{stats.cpuPerc}</span>
|
||||
<LineProgress percent={cpuPct} />
|
||||
</div>
|
||||
) : running && statsLoading ? (
|
||||
<Spinner size={12} />
|
||||
) : (
|
||||
<span className={styles.mutedMeta}>—</span>
|
||||
)}
|
||||
</td>
|
||||
<td className={styles.composeMemoryCell}>
|
||||
{stats ? (
|
||||
<div className={styles.composeMetric}>
|
||||
<span className={styles.mono}>
|
||||
{stats.memUsage} ({stats.memPerc})
|
||||
</span>
|
||||
<LineProgress percent={memPct} />
|
||||
</div>
|
||||
) : running && statsLoading ? (
|
||||
<span className={styles.mutedMeta}>
|
||||
<T>Loading…</T>
|
||||
</span>
|
||||
<LineProgress percent={memPct} />
|
||||
</div>
|
||||
) : running && statsLoading ? (
|
||||
<span className={styles.mutedMeta}>
|
||||
<T>Loading…</T>
|
||||
</span>
|
||||
) : (
|
||||
<span className={styles.mutedMeta}>—</span>
|
||||
)}
|
||||
</td>
|
||||
<td className={clsx(styles.mono, styles.nowrapCell)}>
|
||||
{stats?.netIo || <span className={styles.mutedMeta}>—</span>}
|
||||
</td>
|
||||
<td className={clsx(styles.mono, styles.nowrapCell)}>
|
||||
{stats?.blockIo || <span className={styles.mutedMeta}>—</span>}
|
||||
</td>
|
||||
<td className={clsx(styles.mono, styles.nowrapCell)}>
|
||||
{stats?.pids || <span className={styles.mutedMeta}>—</span>}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : (
|
||||
<span className={styles.mutedMeta}>—</span>
|
||||
)}
|
||||
</td>
|
||||
<td className={clsx(styles.mono, styles.nowrapCell)}>
|
||||
{stats?.netIo || <span className={styles.mutedMeta}>—</span>}
|
||||
</td>
|
||||
<td className={clsx(styles.mono, styles.nowrapCell)}>
|
||||
{stats?.blockIo || <span className={styles.mutedMeta}>—</span>}
|
||||
</td>
|
||||
<td className={clsx(styles.mono, styles.nowrapCell)}>
|
||||
{stats?.pids || <span className={styles.mutedMeta}>—</span>}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<SectionBanner>
|
||||
<T>Volumes</T>
|
||||
</SectionBanner>
|
||||
{namedVolumes.length > 0 ? (
|
||||
<div className={styles.chipGroup}>
|
||||
{namedVolumes.map((v) => (
|
||||
<VolumeLinkChip key={v.name} conn={conn} volume={v} />
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className={styles.emptySection}>
|
||||
<T>No named volumes</T>
|
||||
</div>
|
||||
)}
|
||||
<SectionBanner>
|
||||
<T>Volumes</T>
|
||||
</SectionBanner>
|
||||
{namedVolumes.length > 0 ? (
|
||||
<div className={styles.chipGroup}>
|
||||
{namedVolumes.map((v) => (
|
||||
<VolumeLinkChip key={v.name} conn={conn} volume={v} />
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className={styles.emptySection}>
|
||||
<T>No named volumes</T>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -21,18 +21,20 @@ import {
|
||||
type TreeHandle,
|
||||
} from "@/ui";
|
||||
import { maybeEditorService, type EditorInput } from "@/workbench/contributions";
|
||||
import { useToolWindowLayout } from "@/workbench/toolwindows/store";
|
||||
import clsx from "clsx";
|
||||
import {
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useEffectEvent,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type MouseEvent as ReactMouseEvent,
|
||||
} from "react";
|
||||
import { DIFF_KIND, diffInput, vcsDiffInFront } from "../diffInput";
|
||||
import { DIFF_KIND, diffInput } from "../diffInput";
|
||||
import { buildFileTree, dirKeys, type FileTreeNode } from "../fileTree";
|
||||
import styles from "../GitLog.module.css";
|
||||
import {
|
||||
@@ -213,29 +215,28 @@ export function CommitDetails({ commits, fileHistory = false }: { commits: Commi
|
||||
const ordered = useMemo(() => filesUnder(tree), [tree]);
|
||||
const chosenChanges = useMemo(() => filesUnder(tree, selectedKeys), [tree, selectedKeys]);
|
||||
|
||||
// Show Diff Preview: a single selected file follows into the editor's preview tab.
|
||||
// Selection updates an open preview. Double-click, Enter and Show Diff open it.
|
||||
const previewTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
|
||||
useEffect(() => {
|
||||
if (!active) clearTimeout(previewTimer.current);
|
||||
return () => clearTimeout(previewTimer.current);
|
||||
}, [active]);
|
||||
useEffect(() => () => clearTimeout(previewTimer.current), [active, diffLocation, ordered, preview]);
|
||||
const previewSelection = (sel: ReadonlySet<string>) => {
|
||||
clearTimeout(previewTimer.current);
|
||||
if (syncingDiff.current || sel.size !== 1) return;
|
||||
// While the editor shows one of this pane's diffs, the selection walks it along (a click or
|
||||
// arrow key), as in the Commit window.
|
||||
const shown = maybeEditorService()?.activeInput?.();
|
||||
const following = shown?.kind === DIFF_KIND && ordered.some((c) => diffInput(c.diff).key === shown.key);
|
||||
if (!following && (!logOptions().diffPreview || logOptions().diffLocation !== "editor" || vcsDiffInFront())) return;
|
||||
if (!active || !preview || diffLocation !== "editor" || syncingDiff.current || sel.size !== 1) return;
|
||||
const editor = maybeEditorService();
|
||||
const shown = editor?.activeInput?.({ previewOnly: true });
|
||||
if (shown?.kind !== DIFF_KIND || !ordered.some((c) => diffInput(c.diff).key === shown.key)) return;
|
||||
const file = fileNodeAt(tree, [...sel][0]!)?.file;
|
||||
// A preview that cannot open (no editor yet, the file went away) is just skipped.
|
||||
if (file)
|
||||
previewTimer.current = setTimeout(() => void showChangesDiff([file], true).catch(() => undefined), PREVIEW_DELAY);
|
||||
if (!file || diffInput(file.diff).key === shown.key) return;
|
||||
previewTimer.current = setTimeout(() => {
|
||||
if (!useToolWindowLayout.getState().maximized && editor?.activeInput?.({ previewOnly: true })?.key === shown.key)
|
||||
void showChangesDiff([file], true, ordered).catch(() => undefined);
|
||||
}, PREVIEW_DELAY);
|
||||
};
|
||||
|
||||
// Follow only this pane's exact diff (path AND revisions); another commit or
|
||||
// Compare with Local must not move its selection. Never take focus from F7.
|
||||
const isOnlySelected = useEffectEvent((key: string) => selectedKeys.size === 1 && selectedKeys.has(key));
|
||||
useEffect(() => {
|
||||
if (!active) return;
|
||||
const editor = maybeEditorService();
|
||||
const followDiff = (input: EditorInput | null) => {
|
||||
if (input?.kind !== DIFF_KIND) return;
|
||||
@@ -243,16 +244,19 @@ export function CommitDetails({ commits, fileHistory = false }: { commits: Commi
|
||||
if (!change) return;
|
||||
clearTimeout(previewTimer.current);
|
||||
const rel = changeTreePath(change);
|
||||
const key = `f:${rel}`;
|
||||
// The tree already selected this row. Revealing it would scroll it to the center.
|
||||
if (isOnlySelected(key)) return;
|
||||
setExpanded((current) => {
|
||||
const next = new Set(current ?? allDirs);
|
||||
for (const key of allDirs) if (rel.startsWith(key.slice(2) + "/")) next.add(key);
|
||||
return next;
|
||||
});
|
||||
setDiffToReveal({ key: `f:${rel}` });
|
||||
setDiffToReveal({ key });
|
||||
};
|
||||
followDiff(editor?.activeInput?.() ?? null);
|
||||
return editor?.onActiveInputChange?.(followDiff);
|
||||
}, [ordered, allDirs, changeTreePath]);
|
||||
}, [active, ordered, allDirs, changeTreePath]);
|
||||
|
||||
// Tree.reveal needs the expanded rows to have rendered. Suppress the reverse
|
||||
// preview update so it cannot reopen the diff and lose its requested chunk.
|
||||
@@ -440,7 +444,10 @@ export function CommitDetails({ commits, fileHistory = false }: { commits: Commi
|
||||
previewSelection(sel);
|
||||
}}
|
||||
renderNode={(n) => <ChangedFileRow node={n} flat={!groupByDirectory} />}
|
||||
onActivate={(n) => n.file && void showChangesDiff([n.file])}
|
||||
onActivate={(n) => {
|
||||
clearTimeout(previewTimer.current);
|
||||
if (n.file) void showChangesDiff([n.file]);
|
||||
}}
|
||||
onJumpToSource={(n, sel) => {
|
||||
const files = sel.has(n.key) ? filesUnder(tree, sel) : filesUnder([n]);
|
||||
void executeAction("vcs.log.changes.jumpToSource", files);
|
||||
|
||||
@@ -34,7 +34,7 @@ export interface LogOptions {
|
||||
showBranches: boolean;
|
||||
/** Changed files grouped by directory (else a flat list). */
|
||||
groupByDirectory: boolean;
|
||||
/** Selecting a changed file shows its diff in the editor's preview tab. */
|
||||
/** Selecting a changed file updates the embedded preview or an open editor preview. */
|
||||
diffPreview: boolean;
|
||||
/** Changed files show how many lines the commit added and deleted. */
|
||||
showLineStats: boolean;
|
||||
|
||||
@@ -770,8 +770,8 @@ export interface EditorService {
|
||||
openTabs?(): OpenEditorTab[];
|
||||
/** Input of the tab `tabId` in pane `paneId` (dragging tabs between views), null if there is none. */
|
||||
tabInput?(paneId: string, tabId: string): EditorInput | null;
|
||||
/** Input of the active tab (any kind), if any. */
|
||||
activeInput?(): EditorInput | null;
|
||||
/** Input of the active tab, optionally restricted to the replaceable preview tab. */
|
||||
activeInput?(options?: { previewOnly?: boolean }): EditorInput | null;
|
||||
/** Calls `fn` whenever the active tab changes; returns the unsubscribe. */
|
||||
onActiveInputChange?(fn: (input: EditorInput | null) => void): () => void;
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user