дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-17 23:25:45 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
7af0ff3754 | ||
|
|
d4f6114be1 | ||
|
|
ad93e491c9 | ||
|
|
098e80dbef | ||
|
|
6ab7627fc4 | ||
|
|
55e778897f | ||
|
|
cc6ed6b5fd | ||
|
|
5efd58d3af | ||
|
|
d250b351bb | ||
|
|
033f049caf | ||
|
|
74157ffe54 | ||
|
|
732e92f756 | ||
|
|
a83bad107c | ||
|
|
39f709def5 | ||
|
|
ea6638b05e | ||
|
|
a91421c6e0 | ||
|
|
973f0a18a8 | ||
|
|
fb64f0cd26 | ||
|
|
34f2e18ff1 | ||
|
|
83a949ffe9 | ||
|
|
af8bd1afcd | ||
|
|
ce12f68613 |
No files matched your search
@@ -135,6 +135,8 @@ pub struct CommitSettings {
|
||||
/// `Settings::default()`, or `SettingsStore::set` rejects the key as unknown.
|
||||
#[specta(optional)]
|
||||
pub double_click_opens_diff: Option<bool>,
|
||||
/// Team conventions for Generate Commit Message with Agent, added to its prompt.
|
||||
pub agent_instructions: String,
|
||||
}
|
||||
|
||||
impl Default for CommitSettings {
|
||||
@@ -156,6 +158,7 @@ impl Default for CommitSettings {
|
||||
wrap_at_margin: false,
|
||||
disabled_plugin_checks: Vec::new(),
|
||||
double_click_opens_diff: None,
|
||||
agent_instructions: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,7 +142,7 @@ pub fn snapshot(ep: &DockerEndpoint) -> DockerSnapshot {
|
||||
}
|
||||
const FMT: &str = "{{json .}}";
|
||||
let (containers, images, volumes, networks) = std::thread::scope(|s| {
|
||||
let c = s.spawn(|| run(ep, &["ps", "--all", "--no-trunc", "--format", FMT], QUICK));
|
||||
let c = s.spawn(|| run(ep, &["ps", "--all", "--no-trunc", "--format", PS_FORMAT], QUICK));
|
||||
let i = s.spawn(|| run(ep, &["image", "ls", "--no-trunc", "--format", FMT], QUICK));
|
||||
let v = s.spawn(|| run(ep, &["volume", "ls", "--format", FMT], QUICK));
|
||||
let n = s.spawn(|| run(ep, &["network", "ls", "--no-trunc", "--format", FMT], QUICK));
|
||||
|
||||
@@ -226,6 +226,16 @@ fn lines<T: for<'de> Deserialize<'de>>(text: &str) -> impl Iterator<Item = T> +
|
||||
})
|
||||
}
|
||||
|
||||
/// The `docker ps --format` template: only the fields [`RawContainer`] reads. `{{json .}}`
|
||||
/// would also include `Size`, which makes the daemon compute every container's writable
|
||||
/// layer and can take tens of seconds.
|
||||
pub const PS_FORMAT: &str = concat!(
|
||||
r#"{"ID":{{json .ID}},"Names":{{json .Names}},"Image":{{json .Image}},"#,
|
||||
r#""Command":{{json .Command}},"State":{{json .State}},"Status":{{json .Status}},"#,
|
||||
r#""Ports":{{json .Ports}},"CreatedAt":{{json .CreatedAt}},"Labels":{{json .Labels}},"#,
|
||||
r#""Mounts":{{json .Mounts}},"Networks":{{json .Networks}}}"#,
|
||||
);
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(rename_all = "PascalCase", default)]
|
||||
struct RawContainer {
|
||||
@@ -247,7 +257,7 @@ fn split_csv(raw: &str) -> Vec<String> {
|
||||
raw.split(',').map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned).collect()
|
||||
}
|
||||
|
||||
/// `docker ps -a --no-trunc --format '{{json .}}'`.
|
||||
/// `docker ps -a --no-trunc --format` [`PS_FORMAT`] (or `'{{json .}}'`).
|
||||
pub fn parse_containers(text: &str) -> Vec<DockerContainer> {
|
||||
let mut out: Vec<DockerContainer> = lines::<RawContainer>(text)
|
||||
.map(|r| {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//! Parsing of recorded `docker … --format '{{json .}}'` output.
|
||||
|
||||
use ide_docker::{
|
||||
parse_container_stats, parse_container_top, parse_containers, parse_image_history, parse_images, parse_networks,
|
||||
parse_volumes,
|
||||
PS_FORMAT, parse_container_stats, parse_container_top, parse_containers, parse_image_history, parse_images,
|
||||
parse_networks, parse_volumes,
|
||||
};
|
||||
|
||||
const PS: &str = include_str!("fixtures/ps.jsonl");
|
||||
@@ -10,6 +10,27 @@ const IMAGES: &str = include_str!("fixtures/images.jsonl");
|
||||
const VOLUMES: &str = include_str!("fixtures/volumes.jsonl");
|
||||
const NETWORKS: &str = include_str!("fixtures/networks.jsonl");
|
||||
|
||||
/// Fills `{{json .Field}}` placeholders of a `--format` template from a `{{json .}}` line.
|
||||
fn render(template: &str, line: &str) -> String {
|
||||
let fields: serde_json::Map<String, serde_json::Value> = serde_json::from_str(line).unwrap();
|
||||
let mut out = template.to_owned();
|
||||
while let Some(start) = out.find("{{json .") {
|
||||
let end = start + out[start..].find("}}").unwrap() + 2;
|
||||
let key = &out[start + "{{json .".len()..end - 2];
|
||||
let value = fields.get(key).unwrap_or_else(|| panic!("fixture lacks {key}"));
|
||||
out.replace_range(start..end, &value.to_string());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ps_format_carries_everything_the_parser_reads_but_size() {
|
||||
assert!(!PS_FORMAT.contains("Size"), "Size makes the daemon compute container sizes");
|
||||
let rendered: Vec<String> = PS.lines().filter(|l| l.starts_with('{')).map(|l| render(PS_FORMAT, l)).collect();
|
||||
assert_eq!(rendered.len(), 2);
|
||||
assert_eq!(parse_containers(&rendered.join("\n")), parse_containers(PS));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn containers_with_compose_labels() {
|
||||
let c = parse_containers(PS);
|
||||
|
||||
@@ -33,10 +33,10 @@ struct Decl {
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct Agent {
|
||||
pub(super) struct Agent {
|
||||
/// The jar, resolved inside the package.
|
||||
jar: PathBuf,
|
||||
args: Option<String>,
|
||||
pub(super) jar: PathBuf,
|
||||
pub(super) args: Option<String>,
|
||||
}
|
||||
|
||||
/// Agents of enabled plugins.
|
||||
@@ -47,6 +47,10 @@ pub struct JavaAgents {
|
||||
}
|
||||
|
||||
impl JavaAgents {
|
||||
pub(super) fn for_plugin(&self, plugin: &str) -> Option<Agent> {
|
||||
self.items.read().iter().find(|(_, id, _)| id == plugin).map(|(_, _, agent)| agent.clone())
|
||||
}
|
||||
|
||||
fn add(self: &Arc<Self>, plugin: String, agent: Agent) -> Disposable {
|
||||
let seq = self.seq.fetch_add(1, Ordering::Relaxed);
|
||||
self.items.write().push((seq, plugin, agent));
|
||||
|
||||
@@ -3087,6 +3087,26 @@ impl PluginHost {
|
||||
homepage: m.homepage.clone(),
|
||||
change_notes: m.change_notes.clone(),
|
||||
icon: p.icon.clone(),
|
||||
java_agent: self.java_agents.for_plugin(&m.id).map(|agent| {
|
||||
let pin = self
|
||||
.ledger
|
||||
.lock()
|
||||
.get(&p.subject())
|
||||
.filter(|grant| grant.has(&Capability::JavaAgent))
|
||||
.and_then(|grant| grant.binaries.get(&Capability::JavaAgent.to_string()).cloned());
|
||||
let approved = pin.as_ref().is_some_and(|pin| {
|
||||
pin.path == agent.jar && ledger::file_hash(&pin.path).is_ok_and(|hash| hash == pin.hash)
|
||||
});
|
||||
PluginJavaAgent {
|
||||
file_name: agent
|
||||
.jar
|
||||
.file_name()
|
||||
.map(|name| name.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| agent.jar.display().to_string()),
|
||||
args: agent.args,
|
||||
approved,
|
||||
}
|
||||
}),
|
||||
source: p.source,
|
||||
path: p.dir().to_path_buf().into(),
|
||||
enabled: !self.state.lock().disabled.contains(&m.id),
|
||||
|
||||
@@ -55,6 +55,18 @@ impl PluginStatus {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Java agent a plugin contributes, for Settings › Plugins.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PluginJavaAgent {
|
||||
/// The jar's file name.
|
||||
pub file_name: String,
|
||||
/// The optional argument passed after `=`.
|
||||
pub args: Option<String>,
|
||||
/// The jar still has the hash recorded when `java.agent` was granted.
|
||||
pub approved: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PluginInfo {
|
||||
@@ -66,6 +78,8 @@ pub struct PluginInfo {
|
||||
pub homepage: Option<String>,
|
||||
pub change_notes: Option<String>,
|
||||
pub icon: Option<PluginIcon>,
|
||||
/// The Java agent this plugin declares, and whether it is still approved.
|
||||
pub java_agent: Option<PluginJavaAgent>,
|
||||
pub source: PluginSource,
|
||||
/// Package directory.
|
||||
pub path: ide_core::IpcPath,
|
||||
|
||||
@@ -2204,6 +2204,10 @@ fn java_agent_loads_only_while_granted_and_unchanged() {
|
||||
let info = f.host.install_from_dir(&pkg, &Consent::default()).unwrap();
|
||||
assert_eq!(info.status, PluginStatus::Static, "{:?}", info.error);
|
||||
assert!(info.contributions.iter().any(|c| c.point == "javaAgents" && c.label == "fixture agent.jar=mode=test"));
|
||||
let agent = info.java_agent.clone().expect("agent metadata");
|
||||
assert_eq!(agent.file_name, "fixture agent.jar");
|
||||
assert_eq!(agent.args.as_deref(), Some("mode=test"));
|
||||
assert!(!agent.approved);
|
||||
let source = f.host.java_agents();
|
||||
let launch = || {
|
||||
let agents = ide_run::java_agent::approved(&source.agents());
|
||||
@@ -2217,6 +2221,7 @@ fn java_agent_loads_only_while_granted_and_unchanged() {
|
||||
// Granted: the installed jar with its arguments, one argument after the VM options.
|
||||
let info = f.host.set_capability("java-agent", "java.agent", true).unwrap();
|
||||
assert!(info.capabilities.iter().any(|c| c.id == "java.agent" && c.granted));
|
||||
assert!(info.java_agent.as_ref().is_some_and(|agent| agent.approved));
|
||||
let jar = dunce::canonicalize(f.installed("java-agent").join("agent/fixture agent.jar")).unwrap();
|
||||
let option = format!("-javaagent:{}=mode=test", jar.display());
|
||||
let mut with_agent = plain.clone();
|
||||
@@ -2228,7 +2233,11 @@ fn java_agent_loads_only_while_granted_and_unchanged() {
|
||||
let (args, notes) = launch();
|
||||
assert_eq!(args, plain);
|
||||
assert!(notes.len() == 1 && notes[0].contains("changed since it was approved"), "{notes:?}");
|
||||
let changed = f.host.info_of("java-agent").unwrap();
|
||||
assert!(!changed.java_agent.as_ref().unwrap().approved, "Settings must show the changed jar");
|
||||
f.host.set_capability("java-agent", "java.agent", false).unwrap();
|
||||
f.host.set_capability("java-agent", "java.agent", true).unwrap();
|
||||
assert!(f.host.info_of("java-agent").unwrap().java_agent.as_ref().is_some_and(|a| a.approved));
|
||||
assert_eq!(launch(), (with_agent.clone(), vec![]));
|
||||
|
||||
// Revoked, then the plugin disabled: no agent either way.
|
||||
|
||||
@@ -68,7 +68,7 @@ pub(crate) struct Shared {
|
||||
pub store: Option<Store>,
|
||||
pub indexing: AtomicBool,
|
||||
pub cancelled: AtomicBool,
|
||||
/// Files whose content was (re)read and parsed; observability for tests.
|
||||
/// Non-cached content reads, including binary/unsupported files; used by tests.
|
||||
pub parsed: std::sync::atomic::AtomicUsize,
|
||||
queue: Mutex<Queue>,
|
||||
wake: Condvar,
|
||||
@@ -160,14 +160,38 @@ impl Shared {
|
||||
q.busy = true;
|
||||
}
|
||||
if scan {
|
||||
let startup_started = Instant::now();
|
||||
// A warm start can trust the snapshot when neither the scope nor any
|
||||
// directory/file metadata changed. Rebuilding the walk's file list is
|
||||
// the expensive part; validate the flat manifest first.
|
||||
if !self.try_fast_start() {
|
||||
let snapshot_started = Instant::now();
|
||||
let fast = self.try_fast_start();
|
||||
let snapshot_elapsed = snapshot_started.elapsed();
|
||||
if !fast {
|
||||
let snapshot_guard = SystemTime::now();
|
||||
let walk_started = Instant::now();
|
||||
let found = self.walk_roots(None);
|
||||
let walk_elapsed = walk_started.elapsed();
|
||||
let hydration_started = Instant::now();
|
||||
self.load_persisted(&found);
|
||||
let hydration_elapsed = hydration_started.elapsed();
|
||||
self.full_scan(Some(found), snapshot_guard);
|
||||
if !self.is_cancelled() {
|
||||
tracing::info!(
|
||||
mode = "fallback",
|
||||
snapshot_attempt_ms = snapshot_elapsed.as_millis() as u64,
|
||||
walk_ms = walk_elapsed.as_millis() as u64,
|
||||
hydration_ms = hydration_elapsed.as_millis() as u64,
|
||||
elapsed_ms = startup_started.elapsed().as_millis() as u64,
|
||||
"index startup completed"
|
||||
);
|
||||
}
|
||||
} else if !self.is_cancelled() {
|
||||
tracing::info!(
|
||||
mode = "snapshot",
|
||||
elapsed_ms = startup_started.elapsed().as_millis() as u64,
|
||||
"index startup completed"
|
||||
);
|
||||
}
|
||||
} else {
|
||||
self.indexing.store(false, Ordering::SeqCst);
|
||||
@@ -234,6 +258,7 @@ impl Shared {
|
||||
return false;
|
||||
}
|
||||
let root = filter.root();
|
||||
let validation_started = Instant::now();
|
||||
for i in 0..snapshot.dirs_len() {
|
||||
let rel = snapshot.dir(i);
|
||||
let path = if rel.is_empty() { root.to_owned() } else { root.join(rel) };
|
||||
@@ -265,6 +290,7 @@ impl Shared {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
let validation_elapsed = validation_started.elapsed();
|
||||
let build_started = Instant::now();
|
||||
let entries: Vec<Option<(FileEntry, Vec<StoredSymbol>)>> = INDEX_POOL.install(|| {
|
||||
(0..snapshot.len())
|
||||
@@ -302,9 +328,16 @@ impl Shared {
|
||||
d.load_bulk(entries, dirs);
|
||||
drop(d);
|
||||
tracing::info!(
|
||||
"index snapshot: warm start in {:?} (load {loaded:?}, validate/build {built:?}, insert {:?})",
|
||||
started.elapsed(),
|
||||
insert_started.elapsed()
|
||||
mode = "snapshot",
|
||||
snapshot_hydrated = snapshot.len(),
|
||||
discovered = 0usize,
|
||||
symbol_extractions = 0usize,
|
||||
load_ms = loaded.as_millis() as u64,
|
||||
directory_validation_ms = validation_elapsed.as_millis() as u64,
|
||||
file_validation_build_ms = built.as_millis() as u64,
|
||||
insert_ms = insert_started.elapsed().as_millis() as u64,
|
||||
elapsed_ms = started.elapsed().as_millis() as u64,
|
||||
"index snapshot hydrated"
|
||||
);
|
||||
#[cfg(test)]
|
||||
eprintln!(
|
||||
@@ -441,7 +474,7 @@ impl Shared {
|
||||
self.scan(None, found, guard);
|
||||
}
|
||||
|
||||
fn scan(&self, dirs: Option<&[PathBuf]>, prewalked: Option<Vec<Found>>, guard: SystemTime) {
|
||||
fn scan(&self, dirs: Option<&[PathBuf]>, prewalked: Option<Vec<Found>>, guard: SystemTime) -> Option<ScanCounts> {
|
||||
let started = Instant::now();
|
||||
self.indexing.store(true, Ordering::SeqCst);
|
||||
self.emit_state();
|
||||
@@ -457,10 +490,12 @@ impl Shared {
|
||||
|
||||
let filter = self.filter();
|
||||
let walk_started = Instant::now();
|
||||
let was_prewalked = prewalked.is_some();
|
||||
let found = prewalked.unwrap_or_else(|| self.walk_roots(dirs));
|
||||
let walk = walk_started.elapsed();
|
||||
if self.is_cancelled() {
|
||||
return self.end_scan(task);
|
||||
self.end_scan(task);
|
||||
return None;
|
||||
}
|
||||
let classify_started = Instant::now();
|
||||
let seen: HashSet<&Path> = found.iter().map(|f| f.path.as_path()).collect();
|
||||
@@ -487,6 +522,7 @@ impl Shared {
|
||||
self.persist(&[], &stale, false);
|
||||
|
||||
let total = todo.len();
|
||||
let update_started = Instant::now();
|
||||
let mut laps = ChunkLaps::default();
|
||||
{
|
||||
// One streaming parallel pass: parse on `INDEX_POOL` without
|
||||
@@ -546,11 +582,14 @@ impl Shared {
|
||||
laps.extract = pass_started.elapsed();
|
||||
}
|
||||
if self.is_cancelled() {
|
||||
return self.end_scan(task);
|
||||
self.end_scan(task);
|
||||
return None;
|
||||
}
|
||||
let durable_started = Instant::now();
|
||||
self.persist(&[], &[], true);
|
||||
let durable = durable_started.elapsed();
|
||||
let update_elapsed = update_started.elapsed();
|
||||
let snapshot_started = Instant::now();
|
||||
if let Some(store) = &self.store {
|
||||
let recent: Vec<String> = self.recent.lock().iter().filter_map(|p| filter.store_key(p)).collect();
|
||||
let d = self.data.read();
|
||||
@@ -563,6 +602,7 @@ impl Shared {
|
||||
tracing::warn!("index recent snapshot: {e}");
|
||||
}
|
||||
}
|
||||
let snapshot_elapsed = snapshot_started.elapsed();
|
||||
*self.snapshot_due.lock() = None;
|
||||
self.indexing.store(false, Ordering::SeqCst);
|
||||
self.sink.emit(IdeEvent::Task {
|
||||
@@ -574,20 +614,47 @@ impl Shared {
|
||||
cancellable: false,
|
||||
});
|
||||
self.emit_state();
|
||||
if self.is_cancelled() {
|
||||
return None;
|
||||
}
|
||||
laps.outcomes.not_processed += total - laps.outcomes.total();
|
||||
let counts = ScanCounts {
|
||||
discovered: found.len(),
|
||||
metadata_reused: found.len() - total,
|
||||
scheduled: total,
|
||||
outcomes: laps.outcomes,
|
||||
};
|
||||
let outcomes = &counts.outcomes;
|
||||
let d = self.data.read();
|
||||
tracing::info!(
|
||||
"indexed {} files ({} parsed, {} symbols) in {:?} (walk {:?}, classify {:?}, extract {:?}, insert {:?}, persist {:?}, durable {:?})",
|
||||
d.file_count,
|
||||
total,
|
||||
d.symbol_count,
|
||||
started.elapsed(),
|
||||
walk,
|
||||
classify,
|
||||
laps.extract,
|
||||
laps.insert,
|
||||
laps.persist,
|
||||
durable
|
||||
scope = if dirs.is_some() { "subtree" } else { "full" },
|
||||
files = d.file_count,
|
||||
symbols = d.symbol_count,
|
||||
discovered = counts.discovered,
|
||||
metadata_reused = counts.metadata_reused,
|
||||
scheduled = counts.scheduled,
|
||||
hash_reused = outcomes.hash_reused,
|
||||
symbol_extractions = outcomes.symbol_extractions,
|
||||
ignored = outcomes.ignored,
|
||||
oversized = outcomes.oversized,
|
||||
binary = outcomes.binary,
|
||||
unsupported = outcomes.unsupported,
|
||||
read_failed = outcomes.read_failed,
|
||||
not_processed = outcomes.not_processed,
|
||||
prewalked = was_prewalked,
|
||||
walk_ms = walk.as_millis() as u64,
|
||||
classify_ms = classify.as_millis() as u64,
|
||||
// Pipeline and update wall times overlap insert/persist; do not sum these fields.
|
||||
extract_pipeline_ms = laps.extract.as_millis() as u64,
|
||||
insert_ms = laps.insert.as_millis() as u64,
|
||||
persist_ms = laps.persist.as_millis() as u64,
|
||||
durable_ms = durable.as_millis() as u64,
|
||||
update_ms = update_elapsed.as_millis() as u64,
|
||||
snapshot_write_ms = snapshot_elapsed.as_millis() as u64,
|
||||
elapsed_ms = started.elapsed().as_millis() as u64,
|
||||
"index scan completed"
|
||||
);
|
||||
Some(counts)
|
||||
}
|
||||
|
||||
/// Extracts records in parallel, then publishes them to memory and disk.
|
||||
@@ -599,6 +666,7 @@ impl Shared {
|
||||
files.par_iter().filter_map(|(f, prev_hash)| self.parse_found(f, *prev_hash, &filter)).collect()
|
||||
});
|
||||
laps.extract = started.elapsed();
|
||||
laps.outcomes.not_processed = files.len() - extracted.len();
|
||||
if extracted.is_empty() {
|
||||
return laps;
|
||||
}
|
||||
@@ -622,9 +690,9 @@ impl Shared {
|
||||
let key = filter.store_key(&f.path);
|
||||
let outcome = match self.extract(f, prev_hash) {
|
||||
Extracted::Unchanged => ParsedOutcome::Unchanged { mtime: f.mtime, size: f.size, ignored: f.ignored },
|
||||
Extracted::New(rec) => {
|
||||
Extracted::New(rec, extraction) => {
|
||||
let bytes = key.as_ref().and_then(|_| postcard::to_allocvec(&rec).ok());
|
||||
ParsedOutcome::New { rec, bytes }
|
||||
ParsedOutcome::New { rec, bytes, extraction }
|
||||
}
|
||||
};
|
||||
Some(ParsedFile { rel, key, outcome, path: f.path.clone() })
|
||||
@@ -640,7 +708,8 @@ impl Shared {
|
||||
for out in batch {
|
||||
let ParsedFile { rel, key, outcome, path } = out;
|
||||
match outcome {
|
||||
ParsedOutcome::New { rec, bytes } => {
|
||||
ParsedOutcome::New { rec, bytes, extraction } => {
|
||||
laps.outcomes.record(extraction);
|
||||
if let (Some(key), Some(bytes)) = (key, bytes) {
|
||||
puts.push((key, bytes));
|
||||
}
|
||||
@@ -658,10 +727,13 @@ impl Shared {
|
||||
d.insert(e, symbols);
|
||||
}
|
||||
for r in refreshes {
|
||||
if let Some(rec) = d.refresh_metadata(&r.path, r.mtime, r.size, r.ignored)
|
||||
&& let Some(key) = r.key
|
||||
{
|
||||
refreshed_records.push((key, rec));
|
||||
if let Some(rec) = d.refresh_metadata(&r.path, r.mtime, r.size, r.ignored) {
|
||||
laps.outcomes.record(Extraction::HashReused);
|
||||
if let Some(key) = r.key {
|
||||
refreshed_records.push((key, rec));
|
||||
}
|
||||
} else {
|
||||
laps.outcomes.not_processed += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -726,15 +798,18 @@ impl Shared {
|
||||
|
||||
fn extract(&self, f: &Found, prev_hash: Option<[u8; 32]>) -> Extracted {
|
||||
let mut rec = FileRecord { mtime: f.mtime, size: f.size, ignored: f.ignored, ..Default::default() };
|
||||
if f.ignored || f.size > MAX_SYMBOL_FILE {
|
||||
return Extracted::New(rec);
|
||||
if f.ignored {
|
||||
return Extracted::New(rec, Extraction::Ignored);
|
||||
}
|
||||
if f.size > MAX_SYMBOL_FILE {
|
||||
return Extracted::New(rec, Extraction::Oversized);
|
||||
}
|
||||
let mut bytes = Vec::with_capacity(f.size as usize);
|
||||
match std::fs::File::open(&f.path).and_then(|mut file| file.read_to_end(&mut bytes)) {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
tracing::debug!("index: cannot read {}: {e}", f.path.display());
|
||||
return Extracted::New(rec);
|
||||
return Extracted::New(rec, Extraction::ReadFailed);
|
||||
}
|
||||
}
|
||||
rec.hash = *blake3::hash(&bytes).as_bytes();
|
||||
@@ -743,7 +818,7 @@ impl Shared {
|
||||
}
|
||||
self.parsed.fetch_add(1, Ordering::Relaxed);
|
||||
if bytes[..bytes.len().min(8192)].contains(&0) {
|
||||
return Extracted::New(rec);
|
||||
return Extracted::New(rec, Extraction::Binary);
|
||||
}
|
||||
let text = String::from_utf8_lossy(&bytes);
|
||||
let lang = self.languages.detect(&f.path, Some(first_line(&text)));
|
||||
@@ -760,8 +835,9 @@ impl Shared {
|
||||
bases: t.bases,
|
||||
})
|
||||
.collect();
|
||||
return Extracted::New(rec, Extraction::Symbols);
|
||||
}
|
||||
Extracted::New(rec)
|
||||
Extracted::New(rec, Extraction::Unsupported)
|
||||
}
|
||||
|
||||
fn process(&self, jobs: Vec<Job>) {
|
||||
@@ -938,7 +1014,7 @@ fn first_line(text: &str) -> &str {
|
||||
enum Extracted {
|
||||
/// Content hash matches the indexed version.
|
||||
Unchanged,
|
||||
New(FileRecord),
|
||||
New(FileRecord, Extraction),
|
||||
}
|
||||
|
||||
/// Wall-time laps of one `index_files` chunk, accumulated by the scan.
|
||||
@@ -947,6 +1023,7 @@ struct ChunkLaps {
|
||||
extract: Duration,
|
||||
insert: Duration,
|
||||
persist: Duration,
|
||||
outcomes: ExtractionCounts,
|
||||
}
|
||||
|
||||
impl ChunkLaps {
|
||||
@@ -954,6 +1031,7 @@ impl ChunkLaps {
|
||||
self.extract += other.extract;
|
||||
self.insert += other.insert;
|
||||
self.persist += other.persist;
|
||||
self.outcomes.add(other.outcomes);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -967,7 +1045,7 @@ struct MetadataRefresh {
|
||||
|
||||
enum ParsedOutcome {
|
||||
Unchanged { mtime: u64, size: u64, ignored: bool },
|
||||
New { rec: FileRecord, bytes: Option<Vec<u8>> },
|
||||
New { rec: FileRecord, bytes: Option<Vec<u8>>, extraction: Extraction },
|
||||
}
|
||||
|
||||
/// One file parsed off the index thread: its outcome ready to publish, with new
|
||||
@@ -980,6 +1058,356 @@ struct ParsedFile {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
/// Mutually exclusive outcomes for this batch, not all files in the index. "Symbols"
|
||||
/// means tags() was called, even when no symbols were found.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Extraction {
|
||||
HashReused,
|
||||
Symbols,
|
||||
Ignored,
|
||||
Oversized,
|
||||
Binary,
|
||||
Unsupported,
|
||||
ReadFailed,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, PartialEq, Eq)]
|
||||
struct ExtractionCounts {
|
||||
hash_reused: usize,
|
||||
symbol_extractions: usize,
|
||||
ignored: usize,
|
||||
oversized: usize,
|
||||
binary: usize,
|
||||
unsupported: usize,
|
||||
read_failed: usize,
|
||||
/// Cancellation, a changed root configuration, or a concurrently removed entry.
|
||||
not_processed: usize,
|
||||
}
|
||||
|
||||
impl ExtractionCounts {
|
||||
fn total(&self) -> usize {
|
||||
self.hash_reused
|
||||
+ self.symbol_extractions
|
||||
+ self.ignored
|
||||
+ self.oversized
|
||||
+ self.binary
|
||||
+ self.unsupported
|
||||
+ self.read_failed
|
||||
+ self.not_processed
|
||||
}
|
||||
|
||||
fn record(&mut self, outcome: Extraction) {
|
||||
*match outcome {
|
||||
Extraction::HashReused => &mut self.hash_reused,
|
||||
Extraction::Symbols => &mut self.symbol_extractions,
|
||||
Extraction::Ignored => &mut self.ignored,
|
||||
Extraction::Oversized => &mut self.oversized,
|
||||
Extraction::Binary => &mut self.binary,
|
||||
Extraction::Unsupported => &mut self.unsupported,
|
||||
Extraction::ReadFailed => &mut self.read_failed,
|
||||
} += 1;
|
||||
}
|
||||
|
||||
fn add(&mut self, other: Self) {
|
||||
self.hash_reused += other.hash_reused;
|
||||
self.symbol_extractions += other.symbol_extractions;
|
||||
self.ignored += other.ignored;
|
||||
self.oversized += other.oversized;
|
||||
self.binary += other.binary;
|
||||
self.unsupported += other.unsupported;
|
||||
self.read_failed += other.read_failed;
|
||||
self.not_processed += other.not_processed;
|
||||
}
|
||||
}
|
||||
|
||||
struct ScanCounts {
|
||||
/// Files yielded by the filtered walker, not every file on disk.
|
||||
discovered: usize,
|
||||
/// Metadata matched an in-memory entry (possibly loaded from disk cache).
|
||||
metadata_reused: usize,
|
||||
scheduled: usize,
|
||||
outcomes: ExtractionCounts,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod metric_tests {
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
|
||||
fn index_files<'a>(index: &Shared, files: impl Iterator<Item = &'a Found>, force: bool) -> ExtractionCounts {
|
||||
let files: Vec<_> = files
|
||||
.map(|f| {
|
||||
let hash = if force || f.ignored { None } else { index.data.read().get(&f.path).map(|e| e.hash) };
|
||||
(f.clone(), hash)
|
||||
})
|
||||
.collect();
|
||||
index.index_files(&files).outcomes
|
||||
}
|
||||
|
||||
fn shared(root: &Path) -> Shared {
|
||||
Shared::new(
|
||||
PathFilter::new(root, &crate::IndexRoots::from(Vec::new()), &[]),
|
||||
Arc::new(LanguageRegistry::load(None).unwrap()),
|
||||
Arc::new(Syntax::new()),
|
||||
Arc::new(ide_core::NullSink),
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streaming_scan_counts_full_batch_and_tail() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
let shared = shared(&root);
|
||||
let count = SCAN_BATCH + 3;
|
||||
for i in 0..count {
|
||||
std::fs::write(root.join(format!("file_{i}.unknown")), "plain").unwrap();
|
||||
}
|
||||
let cold = shared.scan(None, None, SystemTime::now()).unwrap();
|
||||
assert_eq!((cold.discovered, cold.metadata_reused, cold.scheduled), (count, 0, count));
|
||||
assert_eq!(cold.outcomes, ExtractionCounts { unsupported: count, ..Default::default() });
|
||||
assert_eq!(shared.data.read().file_count as usize, count);
|
||||
let hot = shared.scan(None, None, SystemTime::now()).unwrap();
|
||||
assert_eq!((hot.discovered, hot.metadata_reused, hot.scheduled), (count, count, 0));
|
||||
assert_eq!(hot.outcomes.total(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removed_entry_is_not_counted_as_hash_reuse() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
let shared = shared(&root);
|
||||
let path = root.join("main.rs");
|
||||
std::fs::write(&path, "fn main() {}").unwrap();
|
||||
shared.scan(None, None, SystemTime::now()).unwrap();
|
||||
let (found, hash) = {
|
||||
let data = shared.data.read();
|
||||
let e = data.get(&path).unwrap();
|
||||
(Found { path: path.clone(), mtime: e.mtime, size: e.size, ignored: e.ignored }, e.hash)
|
||||
};
|
||||
let parsed = shared.parse_found(&found, Some(hash), &shared.filter()).unwrap();
|
||||
shared.data.write().remove(&path).unwrap();
|
||||
let counts = shared.publish(std::iter::once(parsed)).outcomes;
|
||||
assert_eq!(counts, ExtractionCounts { not_processed: 1, ..Default::default() });
|
||||
assert_eq!(shared.data.read().file_count, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_distinguishes_cold_metadata_and_hash_reuse() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
let path = root.join("main.rs");
|
||||
std::fs::write(&path, "fn main() {}\n").unwrap();
|
||||
let shared = shared(&root);
|
||||
let cold = shared.scan(None, None, SystemTime::now()).unwrap();
|
||||
assert_eq!((cold.discovered, cold.metadata_reused, cold.scheduled), (1, 0, 1));
|
||||
assert_eq!(cold.outcomes, ExtractionCounts { symbol_extractions: 1, ..Default::default() });
|
||||
let hot = shared.scan(None, None, SystemTime::now()).unwrap();
|
||||
assert_eq!((hot.discovered, hot.metadata_reused, hot.scheduled), (1, 1, 0));
|
||||
assert_eq!(hot.outcomes, ExtractionCounts::default());
|
||||
// Force a metadata mismatch without a timestamp-resolution-dependent sleep.
|
||||
let mut rec = {
|
||||
let data = shared.data.read();
|
||||
data.record(data.get(&path).unwrap())
|
||||
};
|
||||
rec.mtime = rec.mtime.wrapping_add(1);
|
||||
let (entry, symbols) = FileEntry::new(path.clone(), "main.rs".into(), rec);
|
||||
shared.data.write().insert(entry, symbols);
|
||||
let touched = shared.scan(None, None, SystemTime::now()).unwrap();
|
||||
assert_eq!((touched.discovered, touched.metadata_reused, touched.scheduled), (1, 0, 1));
|
||||
assert_eq!(touched.outcomes, ExtractionCounts { hash_reused: 1, ..Default::default() });
|
||||
assert_eq!(shared.data.read().symbol_count, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extraction_outcomes_are_exclusive_and_forced_parsing_is_counted() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
let shared = shared(&root);
|
||||
let mut found = Vec::new();
|
||||
for (name, contents, ignored, size) in [
|
||||
("source.rs", "fn source() {}", false, 14),
|
||||
("ignored.rs", "fn hidden() {}", true, 14),
|
||||
("huge.rs", "", false, MAX_SYMBOL_FILE + 1),
|
||||
("binary.rs", "\0", false, 1),
|
||||
("plain.unknown", "plain", false, 5),
|
||||
("missing.rs", "", false, 0),
|
||||
] {
|
||||
let path = root.join(name);
|
||||
if name != "missing.rs" {
|
||||
std::fs::write(&path, contents).unwrap();
|
||||
}
|
||||
found.push(Found { path, mtime: 0, size, ignored });
|
||||
}
|
||||
let counts = index_files(&shared, found.iter(), false);
|
||||
assert_eq!(
|
||||
counts,
|
||||
ExtractionCounts {
|
||||
symbol_extractions: 1,
|
||||
ignored: 1,
|
||||
oversized: 1,
|
||||
binary: 1,
|
||||
unsupported: 1,
|
||||
read_failed: 1,
|
||||
hash_reused: 0,
|
||||
not_processed: 0,
|
||||
}
|
||||
);
|
||||
assert_eq!(shared.data.read().file_count as usize, found.len());
|
||||
assert_eq!(index_files(&shared, found[..1].iter(), false).hash_reused, 1);
|
||||
assert_eq!(index_files(&shared, found[..1].iter(), true).symbol_extractions, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reopened_cache_counts_metadata_reuse() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().join("project");
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
let root = dunce::canonicalize(root).unwrap();
|
||||
std::fs::write(root.join("main.rs"), "fn main() {}\n").unwrap();
|
||||
let cache = dir.path().join("cache");
|
||||
{
|
||||
let mut index = shared(&root);
|
||||
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
|
||||
assert_eq!(index.scan(None, None, SystemTime::now()).unwrap().outcomes.symbol_extractions, 1);
|
||||
}
|
||||
let mut index = shared(&root);
|
||||
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
|
||||
let found = index.walk_roots(None);
|
||||
index.load_persisted(&found);
|
||||
let counts = index.scan(None, Some(found), SystemTime::now()).unwrap();
|
||||
assert_eq!((counts.discovered, counts.metadata_reused, counts.scheduled), (1, 1, 0));
|
||||
assert_eq!(counts.outcomes, ExtractionCounts::default());
|
||||
assert_eq!(index.data.read().symbol_count, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warm_snapshot_hydrates_without_symbol_extraction() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().join("project");
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
let root = dunce::canonicalize(root).unwrap();
|
||||
std::fs::write(root.join("main.rs"), "fn main() {}\n").unwrap();
|
||||
let cache = dir.path().join("cache");
|
||||
{
|
||||
let mut index = shared(&root);
|
||||
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
|
||||
assert_eq!(index.scan(None, None, SystemTime::now()).unwrap().outcomes.symbol_extractions, 1);
|
||||
}
|
||||
let mut index = shared(&root);
|
||||
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
|
||||
assert!(index.try_fast_start());
|
||||
assert_eq!(index.parsed.load(Ordering::Relaxed), 0);
|
||||
assert_eq!(index.data.read().file_count, 1);
|
||||
assert_eq!(index.data.read().symbol_count, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelled_warm_start_does_not_log_completion() {
|
||||
struct CompletionCounter(Arc<std::sync::atomic::AtomicUsize>);
|
||||
impl tracing::Subscriber for CompletionCounter {
|
||||
fn enabled(&self, _: &tracing::Metadata<'_>) -> bool {
|
||||
true
|
||||
}
|
||||
fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id {
|
||||
tracing::span::Id::from_u64(1)
|
||||
}
|
||||
fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {}
|
||||
fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {}
|
||||
fn enter(&self, _: &tracing::span::Id) {}
|
||||
fn exit(&self, _: &tracing::span::Id) {}
|
||||
fn event(&self, event: &tracing::Event<'_>) {
|
||||
struct Message(bool);
|
||||
impl tracing::field::Visit for Message {
|
||||
fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
|
||||
if field.name() == "message" && format!("{value:?}").contains("index startup completed") {
|
||||
self.0 = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut message = Message(false);
|
||||
event.record(&mut message);
|
||||
if message.0 {
|
||||
self.0.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
}
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().join("project");
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
let root = dunce::canonicalize(root).unwrap();
|
||||
std::fs::write(root.join("main.rs"), "fn main() {}\n").unwrap();
|
||||
let cache = dir.path().join("cache");
|
||||
{
|
||||
let mut index = shared(&root);
|
||||
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
|
||||
index.scan(None, None, SystemTime::now()).unwrap();
|
||||
}
|
||||
let mut index = shared(&root);
|
||||
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
|
||||
let count = Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||
index.cancel();
|
||||
tracing::subscriber::with_default(CompletionCounter(count.clone()), || {
|
||||
tracing::info!("index startup completed");
|
||||
assert_eq!(count.swap(0, Ordering::Relaxed), 1);
|
||||
index.run(true);
|
||||
});
|
||||
assert_eq!(index.parsed.load(Ordering::Relaxed), 0);
|
||||
assert_eq!(index.data.read().file_count, 1);
|
||||
assert_eq!(count.load(Ordering::Relaxed), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_outside_current_scope_and_cancelled_batches_are_accounted_for() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().join("project");
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
let index = shared(&root);
|
||||
// A scan can retain Found values from a root removed by set_scope.
|
||||
let outside = Found { path: dir.path().join("outside.rs"), mtime: 0, size: 0, ignored: false };
|
||||
assert_eq!(
|
||||
index_files(&index, [&outside].into_iter(), false),
|
||||
ExtractionCounts { not_processed: 1, ..Default::default() }
|
||||
);
|
||||
index.cancel();
|
||||
let inside = Found { path: root.join("inside.rs"), mtime: 0, size: 0, ignored: false };
|
||||
assert_eq!(
|
||||
index_files(&index, [&inside].into_iter(), false),
|
||||
ExtractionCounts { not_processed: 1, ..Default::default() }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancellation_during_final_notifications_suppresses_completion() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
std::fs::write(root.join("source.rs"), "fn source() {}").unwrap();
|
||||
let index: Arc<Shared> = Arc::new_cyclic(|weak: &std::sync::Weak<Shared>| {
|
||||
let mut index = shared(&root);
|
||||
let weak = weak.clone();
|
||||
index.sink = Arc::new(move |event| {
|
||||
if matches!(event, IdeEvent::Task { done: true, .. }) {
|
||||
weak.upgrade().unwrap().cancel();
|
||||
}
|
||||
});
|
||||
index
|
||||
});
|
||||
assert!(index.scan(None, None, SystemTime::now()).is_none());
|
||||
assert!(index.is_cancelled());
|
||||
assert!(!index.indexing.load(Ordering::Relaxed));
|
||||
assert_eq!(index.data.read().file_count, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelled_scan_does_not_report_completion() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let shared = shared(dir.path());
|
||||
shared.cancel();
|
||||
assert!(shared.scan(None, None, SystemTime::now()).is_none());
|
||||
assert!(!shared.indexing.load(Ordering::Relaxed));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::data::safe_rel;
|
||||
|
||||
@@ -13,12 +13,18 @@ pub(super) fn detect(dir: &Path, out: &mut Vec<RunConfig>) {
|
||||
let src = code_only(&src);
|
||||
out.push(config(BUILD_ID, "zig build", "zig", "zig", &["build"]));
|
||||
let roots = test_roots(&src);
|
||||
let run_exes = run_step_exes(&src);
|
||||
for step in steps(&src) {
|
||||
// `install` is what plain `zig build` runs.
|
||||
if step == "install" || step == "uninstall" {
|
||||
continue;
|
||||
}
|
||||
let mut c = config(format!("zig:{step}"), format!("zig build {step}"), "zig", "zig", &["build", &step]);
|
||||
// A build step that runs an executable has no debug adapter of its own; point it at the
|
||||
// executable config, which builds first and debugs the installed binary under CodeLLDB.
|
||||
if let Some(exe) = run_exes.iter().find(|(name, _)| name == &step) {
|
||||
c.extras.params.insert("debugTarget".into(), format!("zig:exe:{}", exe.1));
|
||||
}
|
||||
if step == "test" || step.starts_with("test-") || step.starts_with("test_") {
|
||||
c = c.test();
|
||||
if let Some((_, root)) = roots.iter().find(|(name, _)| *name == step) {
|
||||
@@ -109,52 +115,51 @@ struct Executable {
|
||||
source: Option<String>,
|
||||
}
|
||||
|
||||
/// `addExecutable(.{ .name = "…", … .root_source_file = <b>.path("…") … })`: the name at the
|
||||
/// options' top level (an `imports` entry has its own `.name`) and the first root source file.
|
||||
/// `.name` and `.root_source_file` of an `addExecutable` call body (just after its `(`).
|
||||
/// The name is read at the options' top level — an `imports` entry has its own `.name`.
|
||||
fn add_executable_fields(body: &str) -> (Option<String>, Option<String>) {
|
||||
let (mut depth, mut in_string, mut escaped) = (0usize, false, false);
|
||||
let (mut name, mut source) = (None, None);
|
||||
for (i, c) in body.char_indices() {
|
||||
if in_string {
|
||||
match c {
|
||||
_ if escaped => escaped = false,
|
||||
'\\' => escaped = true,
|
||||
'"' => in_string = false,
|
||||
_ => {}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match c {
|
||||
'"' => in_string = true,
|
||||
'{' | '[' => depth += 1,
|
||||
'}' | ']' => depth -= 1,
|
||||
'.' => {
|
||||
let field = &body[i + 1..];
|
||||
let value = |key: &str| field.strip_prefix(key)?.trim_start().strip_prefix('=').map(str::trim_start);
|
||||
if depth == 1 && name.is_none() {
|
||||
name = value("name").and_then(string_at);
|
||||
}
|
||||
if source.is_none()
|
||||
&& let Some(v) = value("root_source_file")
|
||||
&& let Some(call) = v.find(".path(")
|
||||
&& v[..call].chars().all(|c| c.is_alphanumeric() || c == '_')
|
||||
{
|
||||
source = string_at(&v[call + ".path(".len()..]);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
(name, source)
|
||||
}
|
||||
|
||||
/// `addExecutable(.{ .name = "…", … })`: the name at the options' top level and the first root source file.
|
||||
fn executables(src: &str) -> Vec<Executable> {
|
||||
let mut out: Vec<Executable> = Vec::new();
|
||||
for (start, _) in src.match_indices("addExecutable(") {
|
||||
let body = &src[start + "addExecutable(".len()..];
|
||||
let (mut depth, mut in_string, mut escaped) = (1usize, false, false);
|
||||
let mut name = None;
|
||||
let mut source = None;
|
||||
for (i, c) in body.char_indices() {
|
||||
if in_string {
|
||||
match c {
|
||||
_ if escaped => escaped = false,
|
||||
'\\' => escaped = true,
|
||||
'"' => in_string = false,
|
||||
_ => {}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match c {
|
||||
'"' => in_string = true,
|
||||
'(' | '{' | '[' => depth += 1,
|
||||
')' | '}' | ']' => {
|
||||
depth -= 1;
|
||||
if depth == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
'.' => {
|
||||
let field = &body[i + 1..];
|
||||
let value =
|
||||
|key: &str| field.strip_prefix(key)?.trim_start().strip_prefix('=').map(str::trim_start);
|
||||
if depth == 2 && name.is_none() {
|
||||
name = value("name").and_then(string_at);
|
||||
}
|
||||
if source.is_none()
|
||||
&& let Some(v) = value("root_source_file")
|
||||
&& let Some(call) = v.find(".path(")
|
||||
&& v[..call].chars().all(|c| c.is_alphanumeric() || c == '_')
|
||||
{
|
||||
source = string_at(&v[call + ".path(".len()..]);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let body = call_body(src, start + "addExecutable(".len());
|
||||
let (name, source) = add_executable_fields(body);
|
||||
if let Some(name) = name
|
||||
&& !name.is_empty()
|
||||
&& !out.iter().any(|e| e.name == name)
|
||||
@@ -165,6 +170,109 @@ fn executables(src: &str) -> Vec<Executable> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Variables assigned from `addExecutable` calls, mapped to the executable's name.
|
||||
fn executable_vars(src: &str) -> Vec<(String, String)> {
|
||||
let mut out: Vec<(String, String)> = Vec::new();
|
||||
for (start, _) in src.match_indices("addExecutable(") {
|
||||
let body = call_body(src, start + "addExecutable(".len());
|
||||
let (Some(name), Some(var)) = (add_executable_fields(body).0, assigned_var(src, start)) else { continue };
|
||||
if !name.is_empty() && !out.iter().any(|(v, _)| v == var) {
|
||||
out.push((var.to_owned(), name));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Variables assigned from `b.addRunArtifact(x)` calls, mapped to `x` (an executable or test).
|
||||
fn run_artifact_vars(src: &str) -> Vec<(String, String)> {
|
||||
let mut out: Vec<(String, String)> = Vec::new();
|
||||
for (start, _) in src.match_indices("addRunArtifact(") {
|
||||
let body = call_body(src, start + "addRunArtifact(".len());
|
||||
let arg: String = body.trim_start().chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect();
|
||||
if arg.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if let Some(var) = assigned_var(src, start)
|
||||
&& !out.iter().any(|(v, _)| v == var)
|
||||
{
|
||||
out.push((var.to_owned(), arg));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Step variables assigned from `b.step("name", …)` calls, mapped to the step's name.
|
||||
fn step_vars(src: &str) -> Vec<(String, String)> {
|
||||
let mut out: Vec<(String, String)> = Vec::new();
|
||||
for (i, _) in src.match_indices(".step(\"") {
|
||||
let Some(name) = string_at(&src[i + ".step(".len()..]) else { continue };
|
||||
if let Some(var) = assigned_var(src, i + 1)
|
||||
&& !out.iter().any(|(v, _)| v == var)
|
||||
{
|
||||
out.push((var.to_owned(), name));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The argument of a `.dependOn(&…)` call: `after` starts just past its `&`. Stopping at the
|
||||
/// matching `)` keeps a later `addRunArtifact(` in a different step from being mistaken for this
|
||||
/// step's artifact.
|
||||
fn depend_arg(after: &str) -> &str {
|
||||
let (mut depth, mut in_string, mut escaped) = (1usize, false, false);
|
||||
for (i, c) in after.char_indices() {
|
||||
if in_string {
|
||||
match c {
|
||||
_ if escaped => escaped = false,
|
||||
'\\' => escaped = true,
|
||||
'"' => in_string = false,
|
||||
_ => {}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match c {
|
||||
'"' => in_string = true,
|
||||
'(' | '{' | '[' => depth += 1,
|
||||
')' | '}' | ']' => {
|
||||
depth -= 1;
|
||||
if depth == 0 {
|
||||
return &after[..i];
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
after
|
||||
}
|
||||
|
||||
/// Steps whose `dependOn` runs an executable: `(step name, executable name)`. Both the inline
|
||||
/// (`step.dependOn(&b.addRunArtifact(exe).step)`) and the assigned form
|
||||
/// (`const cmd = b.addRunArtifact(exe); step.dependOn(&cmd.step)`) are handled.
|
||||
fn run_step_exes(src: &str) -> Vec<(String, String)> {
|
||||
let exes = executable_vars(src);
|
||||
let artifacts = run_artifact_vars(src);
|
||||
let steps = step_vars(src);
|
||||
let mut out: Vec<(String, String)> = Vec::new();
|
||||
for (i, _) in src.match_indices(".dependOn(&") {
|
||||
let Some(step_var) = receiver_var(src, i + 1) else { continue };
|
||||
let Some((_, name)) = steps.iter().find(|(v, _)| v == step_var) else { continue };
|
||||
let arg = depend_arg(&src[i + ".dependOn(&".len()..]);
|
||||
let exe_var = if let Some(at) = arg.find("addRunArtifact(") {
|
||||
let v = &arg[at + "addRunArtifact(".len()..];
|
||||
v.chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect::<String>()
|
||||
} else {
|
||||
let v: String = arg.trim_start().chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect();
|
||||
artifacts.iter().find(|(var, _)| var == &v).map(|(_, exe)| exe.clone()).unwrap_or_default()
|
||||
};
|
||||
if let Some((_, exe_name)) = exes.iter().find(|(var, _)| var == &exe_var)
|
||||
&& !out.iter().any(|(n, _)| n == name)
|
||||
{
|
||||
out.push((name.clone(), exe_name.clone()));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The call's argument text: from just after its `(` to the matching `)`.
|
||||
fn call_body(src: &str, start: usize) -> &str {
|
||||
let (mut depth, mut in_string, mut escaped) = (1usize, false, false);
|
||||
@@ -255,14 +363,7 @@ fn test_roots(src: &str) -> Vec<(String, String)> {
|
||||
tests.push((var.to_owned(), root));
|
||||
}
|
||||
}
|
||||
let mut steps: Vec<(String, String)> = Vec::new();
|
||||
for (i, _) in src.match_indices(".step(\"") {
|
||||
let Some(name) = string_at(&src[i + ".step(".len()..]) else { continue };
|
||||
// The match includes the dot, so the assignment ends one character earlier.
|
||||
if let Some(var) = assigned_var(src, i + 1) {
|
||||
steps.push((var.to_owned(), name));
|
||||
}
|
||||
}
|
||||
let steps = step_vars(src);
|
||||
let mut out: Vec<(String, String)> = Vec::new();
|
||||
for (i, _) in src.match_indices(".dependOn(&") {
|
||||
let Some(step) = receiver_var(src, i + 1) else { continue };
|
||||
@@ -325,6 +426,7 @@ pub fn build(b: *std.Build) void {
|
||||
}) });
|
||||
_ = tool;
|
||||
const run_step = b.step("run", "Run the app");
|
||||
run_step.dependOn(&b.addRunArtifact(exe).step);
|
||||
const tests = b.addTest(.{ .root_module = mod });
|
||||
const test_step = b.step("test", "Run tests");
|
||||
test_step.dependOn(&b.addRunArtifact(tests).step);
|
||||
@@ -358,6 +460,11 @@ pub fn build(b: *std.Build) void {
|
||||
(test.command.as_str(), test.args.as_slice()),
|
||||
("zig", ["build".to_owned(), "test".to_owned()].as_slice())
|
||||
);
|
||||
// The run step has no adapter of its own, but points at the executable config that does.
|
||||
let run = out.iter().find(|c| c.id == "zig:run").unwrap();
|
||||
assert_eq!(run.debug_adapter, None);
|
||||
assert_eq!(run.extras.params.get("debugTarget").map(String::as_str), Some("zig:exe:app"));
|
||||
assert!(!out.iter().find(|c| c.id == "zig:docs").unwrap().extras.params.contains_key("debugTarget"));
|
||||
let app = out.iter().find(|c| c.id == "zig:exe:app").unwrap();
|
||||
assert_eq!(app.kind, "zig-application");
|
||||
assert!(app.command.ends_with(if cfg!(windows) { "app.exe" } else { "zig-out/bin/app" }));
|
||||
@@ -400,4 +507,36 @@ pub fn build(b: *std.Build) void {
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
const ASSIGNED_RUN: &str = r#"const std = @import("std");
|
||||
pub fn build(b: *std.Build) void {
|
||||
const exe = b.addExecutable(.{ .name = "app", .root_module = b.createModule(.{
|
||||
.root_source_file = b.path("src/main.zig"),
|
||||
}) });
|
||||
b.installArtifact(exe);
|
||||
const run_cmd = b.addRunArtifact(exe);
|
||||
run_cmd.step.dependOn(b.getInstallStep());
|
||||
const run_step = b.step("run", "Run the app");
|
||||
run_step.dependOn(&run_cmd.step);
|
||||
const tests = b.addTest(.{ .root_module = b.createModule(.{
|
||||
.root_source_file = b.path("src/tally.zig"),
|
||||
}) });
|
||||
const test_step = b.step("test", "Run tests");
|
||||
test_step.dependOn(&b.addRunArtifact(tests).step);
|
||||
}
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
fn a_run_step_linked_through_an_assigned_command_finds_its_executable() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(dir.path().join("build.zig"), ASSIGNED_RUN).unwrap();
|
||||
let mut out = Vec::new();
|
||||
detect(dir.path(), &mut out);
|
||||
// The test step below the run step has its own inline addRunArtifact; it must not be
|
||||
// mistaken for the run step's executable.
|
||||
let run = out.iter().find(|c| c.id == "zig:run").unwrap();
|
||||
assert_eq!(run.extras.params.get("debugTarget").map(String::as_str), Some("zig:exe:app"));
|
||||
let test = out.iter().find(|c| c.id == "zig:test").unwrap();
|
||||
assert!(!test.extras.params.contains_key("debugTarget"));
|
||||
}
|
||||
}
|
||||
@@ -360,6 +360,10 @@ pub struct Stash {
|
||||
pub index: u32,
|
||||
pub message: String,
|
||||
pub time_ms: f64,
|
||||
/// The stash commit; its changes are those against `base`.
|
||||
pub id: String,
|
||||
/// The commit the stash was made on (the stash commit's first parent).
|
||||
pub base: Option<String>,
|
||||
}
|
||||
|
||||
/// Push dialog › Push tags: every tag, or only annotated tags on the pushed commits.
|
||||
@@ -529,9 +533,12 @@ pub enum CheckoutOutcome {
|
||||
LocalChanges {
|
||||
files: Vec<String>,
|
||||
},
|
||||
/// These untracked files (repository-relative paths) would be overwritten.
|
||||
/// These untracked files (repository-relative paths) would be overwritten by the
|
||||
/// checkout; with `removed`, they would be removed by it (tracked here, absent
|
||||
/// from the target).
|
||||
UntrackedFiles {
|
||||
files: Vec<String>,
|
||||
removed: bool,
|
||||
},
|
||||
/// Local branch `local` has commits that remote branch `remote` does not.
|
||||
LocalBranchAhead {
|
||||
|
||||
@@ -158,7 +158,15 @@ pub(crate) fn stashes(r: &Repo) -> IdeResult<Vec<Stash>> {
|
||||
for (index, line) in lines.enumerate() {
|
||||
let line = line.map_err(gx)?;
|
||||
let time_ms = line.signature.time.seconds as f64 * 1000.0;
|
||||
out.push(Stash { index: index as u32, message: to_string(line.message.as_ref()), time_ms });
|
||||
let id = line.new_oid.to_owned();
|
||||
let base = repo.find_commit(id).ok().and_then(|c| c.parent_ids().next().map(|p| p.to_string()));
|
||||
out.push(Stash {
|
||||
index: index as u32,
|
||||
message: to_string(line.message.as_ref()),
|
||||
time_ms,
|
||||
id: id.to_string(),
|
||||
base,
|
||||
});
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -771,9 +771,14 @@ fn overwritten_files(stderr: &str) -> Option<Vec<String>> {
|
||||
listed_files(stderr, "local changes to the following files would be overwritten")
|
||||
}
|
||||
|
||||
/// Untracked files git refuses to overwrite, from its error message.
|
||||
fn overwritten_untracked(stderr: &str) -> Option<Vec<String>> {
|
||||
listed_files(stderr, "untracked working tree files would be")
|
||||
/// Untracked files git refuses to lose, from its error message: they would be *removed*
|
||||
/// by the checkout (tracked here, absent from the target) or *overwritten* by it (present
|
||||
/// in the target). Returns the files and whether they would be removed.
|
||||
fn refused_untracked(stderr: &str) -> Option<(Vec<String>, bool)> {
|
||||
if let Some(files) = listed_files(stderr, "untracked working tree files would be removed") {
|
||||
return Some((files, true));
|
||||
}
|
||||
Some((listed_files(stderr, "untracked working tree files would be")?, false))
|
||||
}
|
||||
|
||||
/// The branch git refused to check out or update because another worktree has it, from
|
||||
@@ -840,8 +845,8 @@ pub(crate) fn checkout_with(
|
||||
if let Some((branch, path)) = branch_of_other_worktree(&stderr) {
|
||||
return Ok(CheckoutOutcome::CheckedOutInWorktree { branch, path: path.into() });
|
||||
}
|
||||
if let Some(files) = overwritten_untracked(&stderr) {
|
||||
return Ok(CheckoutOutcome::UntrackedFiles { files });
|
||||
if let Some((files, removed)) = refused_untracked(&stderr) {
|
||||
return Ok(CheckoutOutcome::UntrackedFiles { files, removed });
|
||||
}
|
||||
let Some(files) = overwritten_files(&stderr) else {
|
||||
return Err(cli::failure(&argv, &out.stderr, &out.stdout, out.code));
|
||||
|
||||
@@ -849,6 +849,11 @@ fn stash_push_list_apply_pop() {
|
||||
assert!(stashes[0].message.contains("WIP on main"), "{stashes:?}");
|
||||
assert!(stashes[1].message.contains("first stash"), "{stashes:?}");
|
||||
assert!(stashes[0].time_ms > 0.0);
|
||||
// Each stash lists the files it changed against the commit it was made on.
|
||||
let head = repo.head().unwrap().1.unwrap();
|
||||
assert!(stashes.iter().all(|s| s.base.as_deref() == Some(head.as_str())), "{stashes:?}");
|
||||
let files = repo.commit_files(&stashes[1].id).unwrap();
|
||||
assert_eq!(files.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(), ["s.txt"]);
|
||||
|
||||
repo.stash_apply(1, false, false).unwrap();
|
||||
assert_eq!(fx.read("s.txt"), "change 1\n");
|
||||
@@ -2074,12 +2079,37 @@ fn checkout_reports_untracked_files_it_would_overwrite() {
|
||||
for mode in [CheckoutMode::Normal, CheckoutMode::Smart] {
|
||||
let opts = CheckoutOptions { mode, ..Default::default() };
|
||||
let outcome = repo.checkout_with("other", false, &opts).unwrap();
|
||||
assert_eq!(outcome, CheckoutOutcome::UntrackedFiles { files: vec!["dir/new.txt".into()] });
|
||||
assert_eq!(outcome, CheckoutOutcome::UntrackedFiles { files: vec!["dir/new.txt".into()], removed: false });
|
||||
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"));
|
||||
assert_eq!(fx.read("dir/new.txt"), "mine\n");
|
||||
}
|
||||
}
|
||||
|
||||
/// Untracked on disk but tracked on the current branch and gone from the target
|
||||
/// (as after `git rm --cached`): git refuses to *remove* the file, and the outcome
|
||||
/// says so (#3980).
|
||||
#[test]
|
||||
fn checkout_reports_untracked_files_it_would_remove() {
|
||||
let fx = Fixture::new();
|
||||
fx.write("TEST.md", "hi\n");
|
||||
fx.commit_all("base");
|
||||
fx.git(&["checkout", "-q", "-b", "feature/x"]);
|
||||
fx.git(&["rm", "-q", "TEST.md"]);
|
||||
fx.commit_all("remove TEST.md on feature/x");
|
||||
fx.git(&["checkout", "-q", "main"]);
|
||||
fx.git(&["rm", "--cached", "TEST.md"]);
|
||||
fx.write("TEST.md", "local dirty version\n");
|
||||
let repo = fx.repo();
|
||||
for mode in [CheckoutMode::Normal, CheckoutMode::Smart] {
|
||||
// The refusal leaves the repository untouched, so both modes see the same state.
|
||||
let opts = CheckoutOptions { mode, ..Default::default() };
|
||||
let outcome = repo.checkout_with("feature/x", false, &opts).unwrap();
|
||||
assert_eq!(outcome, CheckoutOutcome::UntrackedFiles { files: vec!["TEST.md".into()], removed: true });
|
||||
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"));
|
||||
assert_eq!(fx.read("TEST.md"), "local dirty version\n");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reword_keeps_local_changes_and_can_be_undone() {
|
||||
let fx = Fixture::new();
|
||||
|
||||
@@ -846,6 +846,7 @@ mod tests {
|
||||
"wrapAtMargin": false,
|
||||
"disabledPluginChecks": [],
|
||||
"doubleClickOpensDiff": null,
|
||||
"agentInstructions": "",
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@@ -129,6 +129,14 @@ OpenIDEA indexes Spring Web endpoints (`@RestController` / `@Controller` classes
|
||||
|
||||
Plugins can contribute endpoints of other frameworks; they get an **Open in HTTP Client** gutter icon.
|
||||
|
||||
### Feign navigation
|
||||
|
||||
In Java and Kotlin `@FeignClient` interfaces, click the **Go to Feign Endpoint** gutter arrow or use the same action from the editor menu or Find Action. On a literal mapping path such as `@GetMapping("/users/{id}")`, modifier-click or Go to Declaration also opens matching controller methods. Multiple matches use the existing declaration chooser; method declarations keep their usual Find Usages behavior.
|
||||
|
||||
The built-in index matches HTTP methods and literal paths, including whole `{variable}` segments. A literal Feign `name` or `value` narrows candidates against an unambiguous `spring.application.name` in the destination module's `src/main/resources/application.properties`, `.yml` or `.yaml` (also under `resources/config`). Configuration is never inherited from a parent module or test sources. Conflicting profile names, dynamic or missing identities, and clients with explicit/dynamic `url` retain method/path candidates. No HTTP request is sent.
|
||||
|
||||
This is source navigation, not service-discovery or effective runtime configuration resolution. Custom source sets, composed/aliased annotations, inherited mappings, dynamic mapping paths, `@RequestLine`, Ant/regex path patterns and reverse controller-to-client navigation are outside this first version. Navigation reads bounded local configuration and rechecks current controller text, including unsaved editor changes.
|
||||
|
||||
## Not supported
|
||||
|
||||
- JavaScript response handlers (`> {% ... %}`, `> handler.js`) and pre-request scripts. Handler lines are recognized and skipped.
|
||||
|
||||
@@ -129,6 +129,14 @@ OpenIDEA 会为 Java 和 Kotlin 中的 Spring Web 端点(带 `@RequestMapping`
|
||||
|
||||
插件可以提供其他框架的端点,这些端点旁会有 **在 HTTP 客户端中打开** 边栏图标。
|
||||
|
||||
### Feign 导航
|
||||
|
||||
在 Java 或 Kotlin 的 `@FeignClient` 接口中,点击装订线上的 **跳转到 Feign 端点** 箭头,或从编辑器菜单、查找操作中执行同名操作。在 `@GetMapping("/users/{id}")` 等字面量路径上,也可以使用修饰键点击或跳转到声明。有多个候选时会显示已有的声明选择器;方法声明仍保留原来的查找用法行为。
|
||||
|
||||
内置索引按 HTTP 方法和字面量路径匹配控制器,支持完整的 `{variable}` 路径段。Feign 的字面量 `name` 或 `value` 会与目标模块 `src/main/resources` 或其 `config` 子目录中 `application.properties`、`.yml`、`.yaml` 的明确 `spring.application.name` 比较。不会继承父模块或测试资源的配置。配置身份缺失、动态或有冲突,以及客户端指定显式或动态 `url` 时,仍保留方法和路径匹配的候选。导航不会发送 HTTP 请求。
|
||||
|
||||
这是源码导航,不解析服务发现或运行时生效配置。首个版本不支持自定义源码目录、组合或别名注解、继承映射、动态路径、`@RequestLine`、Ant/正则路径模式及控制器到客户端的反向导航。配置读取有数量和大小限制;跳转前会重新检查当前控制器文本,包括未保存的编辑。
|
||||
|
||||
## 暂不支持
|
||||
|
||||
- JavaScript 响应处理脚本(`> {% ... %}`、`> handler.js`)和请求前脚本。处理脚本行能被识别,但会跳过。
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test.use({ video: "on" });
|
||||
|
||||
test("Feign navigation selects the named service and offers ambiguous source targets", async ({
|
||||
workbench: page,
|
||||
}, testInfo) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const backend = "/src/editor/core/backend.ts";
|
||||
const contributions = "/src/workbench/contributions.ts";
|
||||
const { docBackend } = await import(backend);
|
||||
const files: Map<string, string> = docBackend().files;
|
||||
const root = "/dev/acme-api";
|
||||
const client = `package shop;
|
||||
import org.springframework.cloud.openfeign.FeignClient;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
@FeignClient(name = "users")
|
||||
interface UserClient {
|
||||
@GetMapping("/users/{id}")
|
||||
String find();
|
||||
}`;
|
||||
files.set(`${root}/client/src/main/java/UserClient.java`, client);
|
||||
for (const service of ["users", "admin"]) {
|
||||
files.set(
|
||||
`${root}/${service}/src/main/java/UserController.java`,
|
||||
`package shop;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
@RestController
|
||||
class UserController {
|
||||
@GetMapping("/users/{id}")
|
||||
String find() { return "${service}"; }
|
||||
}`,
|
||||
);
|
||||
files.set(`${root}/${service}/src/main/resources/application.properties`, `spring.application.name=${service}\n`);
|
||||
}
|
||||
window.__ipc.handlers.spring_route_sources = () =>
|
||||
[...files].filter(([p]) => p.endsWith("UserController.java")).map(([path, text]) => ({ path, text }));
|
||||
window.__ipc.handlers.fs_read_text = ({ path }) => {
|
||||
if (!files.has(String(path))) throw { kind: "notFound", message: "No fixture file" };
|
||||
return files.get(String(path));
|
||||
};
|
||||
window.__ipc.handlers.fs_read_dir = ({ path }) =>
|
||||
[
|
||||
...new Set(
|
||||
[...files.keys()]
|
||||
.filter((p) => p.startsWith(`${path}/`))
|
||||
.map((p) => p.slice(String(path).length + 1).split("/")[0]!),
|
||||
),
|
||||
].map((name) => ({
|
||||
path: `${path}/${name}`,
|
||||
name,
|
||||
kind: files.has(`${path}/${name}`) ? "file" : "dir",
|
||||
size: files.get(`${path}/${name}`)?.length ?? 0,
|
||||
mtimeMs: 0,
|
||||
ignored: false,
|
||||
excluded: false,
|
||||
hidden: false,
|
||||
}));
|
||||
window.__ipc.handlers.lsp_goto = () => [];
|
||||
await (await import(contributions)).editorService().openFile(`${root}/client/src/main/java/UserClient.java`);
|
||||
});
|
||||
await expect(page.locator(".cm-content").last()).toContainText("@FeignClient");
|
||||
await page.screenshot({ path: testInfo.outputPath("feign-source.png"), animations: "disabled" });
|
||||
await page.locator('button[data-icon-source="feign"]').click();
|
||||
await expect(page.locator(".cm-content").last()).toContainText('return "users"');
|
||||
await page.screenshot({ path: testInfo.outputPath("feign-target.png"), animations: "disabled" });
|
||||
await page.evaluate(async () => {
|
||||
const backend = "/src/editor/core/backend.ts";
|
||||
const contributions = "/src/workbench/contributions.ts";
|
||||
const ipc = "/src/platform/ipc.ts";
|
||||
const path = "/dev/acme-api/admin/src/main/resources/application.properties";
|
||||
(await import(backend)).docBackend().files.set(path, "spring.application.name=users\n");
|
||||
(await import(ipc)).emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [path], removed: [] });
|
||||
await (await import(contributions)).editorService().openFile("/dev/acme-api/client/src/main/java/UserClient.java");
|
||||
});
|
||||
await page.locator('button[data-icon-source="feign"]').click();
|
||||
const chooser = page.getByRole("dialog", { name: "Choose Feign Endpoint" });
|
||||
await expect(chooser.getByRole("option")).toHaveCount(2);
|
||||
await page.screenshot({ path: testInfo.outputPath("feign-chooser.png"), animations: "disabled" });
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(page.locator(".cm-content").last()).toContainText("@FeignClient");
|
||||
await page.locator('button[data-icon-source="feign"]').click();
|
||||
await expect(chooser.getByRole("option")).toHaveCount(2);
|
||||
await page.evaluate(async () => {
|
||||
const ipc = "/src/platform/ipc.ts";
|
||||
(await import(ipc)).emitLocalIdeEvent({
|
||||
type: "fsChanged",
|
||||
created: [],
|
||||
modified: ["/dev/acme-api/admin/src/main/resources/application.properties"],
|
||||
removed: [],
|
||||
});
|
||||
});
|
||||
await chooser.getByRole("option").filter({ hasText: "admin/" }).click();
|
||||
await expect(chooser).not.toBeVisible();
|
||||
await expect(page.locator(".cm-content").last()).toContainText("@FeignClient");
|
||||
// The existing declaration navigation handles mapping URLs; method names
|
||||
// retain the usual declaration-to-usages behavior.
|
||||
await page.evaluate(async () => {
|
||||
const api = "/src/editor/api.ts";
|
||||
const editor = (await import(api)).activeEditor();
|
||||
const offset = editor.view.state.doc.toString().indexOf("/users/{id}") + 2;
|
||||
editor.view.dispatch({ selection: { anchor: offset } });
|
||||
editor.view.focus();
|
||||
});
|
||||
await page.keyboard.press("Meta+b");
|
||||
const declarations = page.getByRole("dialog", { name: "Choose Declaration" });
|
||||
await expect(declarations.getByRole("option")).toHaveCount(2);
|
||||
await declarations.getByRole("option").filter({ hasText: "admin/" }).click();
|
||||
await expect(page.locator(".cm-content").last()).toContainText('return "admin"');
|
||||
});
|
||||
@@ -2217,8 +2217,10 @@ args = "optional-arguments" # optional
|
||||
`[capabilities]` (a manifest that lists it is refused). On grant the IDE
|
||||
records the jar's content hash and checks it again before every launch; a
|
||||
changed jar is left out, with a line in the console, until the user approves
|
||||
`java.agent` again in Settings › Plugins, which shows the agent's file name
|
||||
and arguments next to the permission. Refusing or revoking it keeps the rest
|
||||
`java.agent` again in Settings › Plugins. Settings shows the agent's file name
|
||||
and arguments next to the permission, and when the jar no longer matches the
|
||||
approved hash it shows the reason and an **Approve new jar** action. Refusing
|
||||
or revoking it keeps the rest
|
||||
of the plugin working, and the next launch has no agent.
|
||||
- The IDE adds one `-javaagent:<absolute path>[=<args>]` argument to the Java
|
||||
command line of **Application**, **Spring Boot** and **JAR Application**
|
||||
|
||||
@@ -29,8 +29,9 @@ pub async fn window_group_select(window: WebviewWindow, label: String) -> IdeRes
|
||||
#[desktop_command(trust = always)]
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn window_group_detach(window: WebviewWindow) -> IdeResult<()> {
|
||||
groups::detach(window.app_handle(), window.label())?;
|
||||
pub async fn window_group_detach(window: WebviewWindow, label: String) -> IdeResult<()> {
|
||||
groups::select(window.app_handle(), window.label(), &label)?;
|
||||
groups::detach(window.app_handle(), &label)?;
|
||||
groups::persist(window.app_handle()).await
|
||||
}
|
||||
|
||||
|
||||
@@ -180,29 +180,6 @@ unsafe extern "C-unwind" fn should_terminate(_this: *mut AnyObject, _selector: S
|
||||
|
||||
static APP: std::sync::OnceLock<AppHandle> = std::sync::OnceLock::new();
|
||||
|
||||
/// Escape the page leaves unhandled reaches the window as `cancelOperation:`, on which NSWindow
|
||||
/// leaves full screen, so pressing Escape once more after closing a popup left full screen. The
|
||||
/// IDE's windows answer it with nothing; View › Appearance › Toggle Full Screen (⌃⌘F) leaves it.
|
||||
pub fn keep_full_screen_on_escape() {
|
||||
static ONCE: std::sync::Once = std::sync::Once::new();
|
||||
ONCE.call_once(|| unsafe {
|
||||
let Some(class) = AnyClass::get(c"TaoWindow") else {
|
||||
tracing::warn!("no TaoWindow class: Escape leaves full screen");
|
||||
return;
|
||||
};
|
||||
let imp: Imp = std::mem::transmute(ignore_cancel_operation as CancelOperation);
|
||||
let class = class as *const AnyClass as *mut AnyClass;
|
||||
let added = objc2::ffi::class_addMethod(class, objc2::sel!(cancelOperation:), imp, c"v@:@".as_ptr());
|
||||
if !added.as_bool() {
|
||||
tracing::warn!("could not handle cancelOperation:");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
type CancelOperation = unsafe extern "C-unwind" fn(*mut AnyObject, Sel, *mut AnyObject);
|
||||
|
||||
unsafe extern "C-unwind" fn ignore_cancel_operation(_this: *mut AnyObject, _selector: Sel, _sender: *mut AnyObject) {}
|
||||
|
||||
/// Whether AppKit is handling a key press right now. A menu item performed at this point
|
||||
/// was chosen by its key equivalent: a click, arrow keys plus Return and accessibility
|
||||
/// presses all run with a non-key current event.
|
||||
|
||||
@@ -730,8 +730,6 @@ fn build_project_window(app: &AppHandle, mut config: WindowConfig) -> IdeResult<
|
||||
decorate_csd(&window);
|
||||
#[cfg(target_os = "macos")]
|
||||
crate::page_swipe::install(&window);
|
||||
#[cfg(target_os = "macos")]
|
||||
crate::macos::keep_full_screen_on_escape();
|
||||
apply_zoom(app, &window);
|
||||
#[cfg(target_os = "macos")]
|
||||
align_titlebar(app, &window, app.try_state::<WindowsState>().is_some_and(|w| w.opens_project(window.label())));
|
||||
|
||||
+25
-3
@@ -1812,7 +1812,7 @@ export const commands = {
|
||||
/** Closes several project tabs one by one (each asks about its own unsaved changes), then selects `keep`. */
|
||||
windowGroupCloseTabs: (keep: string, labels: string[]) => typedError<null, IdeError>(__TAURI_INVOKE("window_group_close_tabs", { keep, labels })),
|
||||
windowGroupCurrent: () => typedError<WindowTab[], IdeError>(__TAURI_INVOKE("window_group_current")),
|
||||
windowGroupDetach: () => typedError<null, IdeError>(__TAURI_INVOKE("window_group_detach")),
|
||||
windowGroupDetach: (label: string) => typedError<null, IdeError>(__TAURI_INVOKE("window_group_detach", { label })),
|
||||
windowGroupMerge: () => typedError<null, IdeError>(__TAURI_INVOKE("window_group_merge")),
|
||||
windowGroupReorder: (labels: string[]) => typedError<null, IdeError>(__TAURI_INVOKE("window_group_reorder", { labels })),
|
||||
windowGroupRestore: () => typedError<null, IdeError>(__TAURI_INVOKE("window_group_restore")),
|
||||
@@ -3293,8 +3293,12 @@ export type CheckoutOptions = {
|
||||
export type CheckoutOutcome = { kind: "done" } |
|
||||
/** These local changes (repository-relative paths) would be overwritten. */
|
||||
{ kind: "localChanges"; files: string[] } |
|
||||
/** These untracked files (repository-relative paths) would be overwritten. */
|
||||
{ kind: "untrackedFiles"; files: string[] } |
|
||||
/**
|
||||
* These untracked files (repository-relative paths) would be overwritten by the
|
||||
* checkout; with `removed`, they would be removed by it (tracked here, absent
|
||||
* from the target).
|
||||
*/
|
||||
{ kind: "untrackedFiles"; files: string[]; removed: boolean } |
|
||||
/** Local branch `local` has commits that remote branch `remote` does not. */
|
||||
{ kind: "localBranchAhead"; local: string; remote: string } |
|
||||
/**
|
||||
@@ -3579,6 +3583,8 @@ export type CommitSettings = {
|
||||
* `Settings::default()`, or `SettingsStore::set` rejects the key as unknown.
|
||||
*/
|
||||
doubleClickOpensDiff?: boolean | null,
|
||||
/** Team conventions for Generate Commit Message with Agent, added to its prompt. */
|
||||
agentInstructions?: string,
|
||||
};
|
||||
|
||||
export type Commit_Deserialize = {
|
||||
@@ -8876,6 +8882,8 @@ export type PluginInfo = {
|
||||
homepage: string | null,
|
||||
changeNotes: string | null,
|
||||
icon: PluginIcon | null,
|
||||
/** The Java agent this plugin declares, and whether it is still approved. */
|
||||
javaAgent: PluginJavaAgent | null,
|
||||
source: PluginSource,
|
||||
/** Package directory. */
|
||||
path: IpcPath,
|
||||
@@ -8910,6 +8918,16 @@ export type PluginInfo = {
|
||||
extensionPoints: ExtensionPointInfo[],
|
||||
};
|
||||
|
||||
/** The Java agent a plugin contributes, for Settings › Plugins. */
|
||||
export type PluginJavaAgent = {
|
||||
/** The jar's file name. */
|
||||
fileName: string,
|
||||
/** The optional argument passed after `=`. */
|
||||
args: string | null,
|
||||
/** The jar still has the hash recorded when `java.agent` was granted. */
|
||||
approved: boolean,
|
||||
};
|
||||
|
||||
/**
|
||||
* Commands of this module the remote server answers.
|
||||
* Versioned plugin visuals, refreshed after the editor synchronizes its buffer.
|
||||
@@ -10781,6 +10799,10 @@ export type Stash = {
|
||||
index: number,
|
||||
message: string,
|
||||
timeMs: number | null,
|
||||
/** The stash commit; its changes are those against `base`. */
|
||||
id: string,
|
||||
/** The commit the stash was made on (the stash commit's first parent). */
|
||||
base: string | null,
|
||||
};
|
||||
|
||||
/** A plugin's status bar item. */
|
||||
|
||||
@@ -570,14 +570,24 @@ function copyReference(reference: Promise<string>) {
|
||||
}
|
||||
}
|
||||
|
||||
function copyPathReferencePopup(view: EditorView, slot: EditorSlot) {
|
||||
const path = slot.model.path;
|
||||
const { doc, selection } = view.state;
|
||||
const line = doc.lineAt(selection.main.head).number;
|
||||
/** The selected lines (1-based), leaving out the one a selection ends at the start of. */
|
||||
function selectedLines(state: EditorState): { first: number; last: number } {
|
||||
const { doc, selection } = state;
|
||||
const { from, to } = selection.main;
|
||||
// The selected lines, leaving out the one a selection ends at the start of.
|
||||
const first = doc.lineAt(from).number;
|
||||
const last = Math.max(first, doc.lineAt(to).number - (to > from && doc.lineAt(to).from === to ? 1 : 0));
|
||||
return { first, last };
|
||||
}
|
||||
|
||||
/** `path:12`, or `path:12-18` for a selection over several lines. */
|
||||
function pathWithLines(state: EditorState, path: string): string {
|
||||
const { first, last } = selectedLines(state);
|
||||
return `${pathToCopy("relative", path)}:${first}${last > first ? `-${last}` : ""}`;
|
||||
}
|
||||
|
||||
function copyPathReferencePopup(view: EditorView, slot: EditorSlot) {
|
||||
const path = slot.model.path;
|
||||
const { first, last } = selectedLines(view.state);
|
||||
const contributed = menuGroupItems("copyPath", {
|
||||
paths: [path],
|
||||
line: first - 1,
|
||||
@@ -603,7 +613,7 @@ function copyPathReferencePopup(view: EditorView, slot: EditorSlot) {
|
||||
{
|
||||
id: "editor.copyPathWithLineNumber",
|
||||
label: "Path with line number",
|
||||
value: `${pathToCopy("relative", path)}:${line}`,
|
||||
value: pathWithLines(view.state, path),
|
||||
},
|
||||
];
|
||||
const popup: Extract<LspPopup, { kind: "list" }> = {
|
||||
@@ -1280,12 +1290,7 @@ export function registerEditorActions(): () => void {
|
||||
when: TEXT_WHEN,
|
||||
run: ({ arg }) => {
|
||||
if (typeof arg === "string") copyEditorPath(arg);
|
||||
else
|
||||
withView((view, slot) =>
|
||||
copyEditorPath(
|
||||
`${pathToCopy("relative", slot.model.path)}:${view.state.doc.lineAt(view.state.selection.main.head).number}`,
|
||||
),
|
||||
)();
|
||||
else withView((view, slot) => copyEditorPath(pathWithLines(view.state, slot.model.path)))();
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { LanguageDescription, type Language } from "@codemirror/language";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { getIndentation } from "@codemirror/language";
|
||||
import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight";
|
||||
import { logWarning } from "./highlight";
|
||||
import { findLanguageDescription, loadSupport } from "./languages";
|
||||
import { fencedCodeMode, findLanguageDescription, loadSupport } from "./languages";
|
||||
|
||||
describe("language modes", () => {
|
||||
it("distinguishes PHP classes, method declarations and fields for imported schemes", async () => {
|
||||
@@ -270,6 +272,28 @@ describe("language modes", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps C++ namespace and extern "C" contents at the level of their braces', async () => {
|
||||
const support = await loadSupport(findLanguageDescription("C++", "/p/a.cpp")!);
|
||||
const doc = [
|
||||
"namespace foo {",
|
||||
"class Bar {",
|
||||
" int x;",
|
||||
"};",
|
||||
"namespace inner {",
|
||||
"void f() {",
|
||||
" g();",
|
||||
"}",
|
||||
"} // namespace inner",
|
||||
"} // namespace foo",
|
||||
'extern "C" {',
|
||||
"int h();",
|
||||
"}",
|
||||
].join("\n");
|
||||
const state = EditorState.create({ doc, extensions: [support!, EditorState.tabSize.of(2)] });
|
||||
const indent = (line: number) => getIndentation(state, state.doc.line(line).from);
|
||||
expect([2, 3, 4, 5, 6, 7, 9, 10, 12, 13].map(indent)).toEqual([0, 2, 0, 0, 0, 2, 0, 0, 0, 0]);
|
||||
});
|
||||
|
||||
it("colours `this`, `super` and Rust's `self` as keywords", async () => {
|
||||
const highlighter = tagHighlighter([
|
||||
{ tag: t.keyword, class: "keyword" },
|
||||
@@ -309,4 +333,109 @@ describe("language modes", () => {
|
||||
expect(support?.language).toBeTruthy();
|
||||
}
|
||||
});
|
||||
|
||||
const keywordHighlighter = tagHighlighter([{ tag: t.keyword, class: "keyword" }]);
|
||||
|
||||
function keywords(language: Language, source: string) {
|
||||
const found: string[] = [];
|
||||
highlightTree(language.parser.parse(source), keywordHighlighter, (from, to) => found.push(source.slice(from, to)));
|
||||
return found;
|
||||
}
|
||||
|
||||
it("colours TOML keys as keywords in files, lock files and ```toml code blocks", async () => {
|
||||
for (const path of ["/p/Cargo.toml", "/p/uv.lock"]) {
|
||||
const support = await loadSupport(findLanguageDescription("TOML", path)!);
|
||||
expect(keywords(support!.language, '[package]\nname = "x"'), path).toEqual(["package", "name"]);
|
||||
}
|
||||
const fenced = fencedCodeMode("toml")!;
|
||||
expect(fenced.name).toBe("TOML");
|
||||
const language =
|
||||
fenced.language instanceof LanguageDescription ? (await fenced.language.load()).language : fenced.language;
|
||||
expect(keywords(language, 'name = "x"')).toEqual(["name"]);
|
||||
});
|
||||
|
||||
const propertiesHighlighter = tagHighlighter([
|
||||
{ tag: t.keyword, class: "keyword" },
|
||||
{ tag: t.operator, class: "operator" },
|
||||
{ tag: t.string, class: "string" },
|
||||
{ tag: t.comment, class: "comment" },
|
||||
{ tag: t.heading, class: "heading" },
|
||||
]);
|
||||
|
||||
function highlightProperties(language: Language, source: string) {
|
||||
const found: Array<[string, string]> = [];
|
||||
highlightTree(language.parser.parse(source), propertiesHighlighter, (from, to, style) =>
|
||||
found.push([source.slice(from, to), style]),
|
||||
);
|
||||
return found;
|
||||
}
|
||||
|
||||
it("colours properties and .env keys as keywords, the first separator as an operator and the whole value as a string", async () => {
|
||||
const support = await loadSupport(findLanguageDescription("Properties files", "/p/.env")!);
|
||||
const source = [
|
||||
"APP_NAME=core-user",
|
||||
"DATABASE_URL=postgres://u:p@h:5432/db",
|
||||
"APP_KEY=base64:abc==",
|
||||
"key = value",
|
||||
"key: value",
|
||||
"export A=b",
|
||||
"# c",
|
||||
"[section]",
|
||||
"a=b\\",
|
||||
" c",
|
||||
"=x",
|
||||
// A blank line ends a continued value.
|
||||
"d=e\\",
|
||||
"",
|
||||
"f=g",
|
||||
].join("\n");
|
||||
expect(highlightProperties(support!.language, source)).toEqual([
|
||||
["APP_NAME", "keyword"],
|
||||
["=", "operator"],
|
||||
["core-user", "string"],
|
||||
["DATABASE_URL", "keyword"],
|
||||
["=", "operator"],
|
||||
["postgres://u:p@h:5432/db", "string"],
|
||||
["APP_KEY", "keyword"],
|
||||
["=", "operator"],
|
||||
["base64:abc==", "string"],
|
||||
["key ", "keyword"],
|
||||
["=", "operator"],
|
||||
[" value", "string"],
|
||||
["key", "keyword"],
|
||||
[":", "operator"],
|
||||
[" value", "string"],
|
||||
["export A", "keyword"],
|
||||
["=", "operator"],
|
||||
["b", "string"],
|
||||
["# c", "comment"],
|
||||
["[section]", "heading"],
|
||||
["a", "keyword"],
|
||||
["=", "operator"],
|
||||
["b\\", "string"],
|
||||
[" c", "string"],
|
||||
["=", "operator"],
|
||||
["x", "string"],
|
||||
["d", "keyword"],
|
||||
["=", "operator"],
|
||||
["e\\", "string"],
|
||||
["f", "keyword"],
|
||||
["=", "operator"],
|
||||
["g", "string"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("colours properties keys in ```ini and ```properties code blocks", async () => {
|
||||
for (const info of ["ini", "properties"]) {
|
||||
const fenced = fencedCodeMode(info)!;
|
||||
expect(fenced.name, info).toBe("Properties files");
|
||||
const language =
|
||||
fenced.language instanceof LanguageDescription ? (await fenced.language.load()).language : fenced.language;
|
||||
expect(highlightProperties(language, "a=b"), info).toEqual([
|
||||
["a", "keyword"],
|
||||
["=", "operator"],
|
||||
["b", "string"],
|
||||
]);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -11,6 +11,8 @@ import {
|
||||
LanguageDescription,
|
||||
LanguageSupport,
|
||||
StreamLanguage,
|
||||
delimitedIndent,
|
||||
indentNodeProp,
|
||||
indentService,
|
||||
language as languageFacet,
|
||||
type StreamParser,
|
||||
@@ -195,6 +197,14 @@ const OWN_MODES = [
|
||||
);
|
||||
},
|
||||
}),
|
||||
LanguageDescription.of({
|
||||
name: "TOML",
|
||||
load: async () => new LanguageSupport(StreamLanguage.define((await import("./toml")).tomlParser)),
|
||||
}),
|
||||
LanguageDescription.of({
|
||||
name: "Properties files",
|
||||
load: async () => new LanguageSupport((await import("./properties")).propertiesLanguage),
|
||||
}),
|
||||
LanguageDescription.of({
|
||||
name: "Markdown",
|
||||
extensions: ["md", "markdown", "mkd"],
|
||||
@@ -413,12 +423,28 @@ const EXTRA_TAGS: Record<string, Parameters<typeof styleTags>[0]> = {
|
||||
YAML: { "Key/Literal Key/QuotedLiteral": t.keyword },
|
||||
};
|
||||
|
||||
const bracedIndent = delimitedIndent({ closing: "}" });
|
||||
|
||||
/** Grammar props the stock languages lack: indentation that follows the language's usual style. */
|
||||
const EXTRA_PROPS: Record<string, NonNullable<Parameters<LRLanguage["configure"]>[0]["props"]>> = {
|
||||
// clang-format's built-in styles (NamespaceIndentation: None, no extern block indent) keep the
|
||||
// contents of `namespace x { … }` and `extern "C" { … }` at the level of the braces' line.
|
||||
"C++": [
|
||||
indentNodeProp.add({
|
||||
// The stock rule for every `{ … }` body, except the bodies of these two.
|
||||
CompoundStatement: (cx) =>
|
||||
cx.node.parent?.name === "NamespaceDefinition" || cx.node.parent?.name === "LinkageSpecification"
|
||||
? cx.baseIndent
|
||||
: bracedIndent(cx),
|
||||
}),
|
||||
],
|
||||
};
|
||||
|
||||
function patchSupport(desc: LanguageDescription, support: LanguageSupport): LanguageSupport {
|
||||
const extra = EXTRA_TAGS[desc.name];
|
||||
const props = [...(extra ? [styleTags(extra)] : []), ...(EXTRA_PROPS[desc.name] ?? [])];
|
||||
const language =
|
||||
extra && support.language instanceof LRLanguage
|
||||
? support.language.configure({ props: [styleTags(extra)] })
|
||||
: support.language;
|
||||
props.length && support.language instanceof LRLanguage ? support.language.configure({ props }) : support.language;
|
||||
const result = new LanguageSupport(language, [
|
||||
support.support,
|
||||
docCommentTags(desc.name),
|
||||
|
||||
@@ -57,6 +57,7 @@ import { stringClipboard } from "./stringClipboard";
|
||||
import { filterCopiedText } from "./clipboard";
|
||||
import { LINE_INSET } from "./lineInset";
|
||||
import { codeLensPositions } from "./codeLens";
|
||||
import { wheelZoomStep } from "@/platform/wheelZoom";
|
||||
|
||||
// --- soft wraps ---------------------------------------------------------------
|
||||
|
||||
@@ -452,9 +453,10 @@ export function resetConfiguredEditorsFontZoom(origin: EditorView): void {
|
||||
/** Exported for tests: the ⌘/Ctrl+wheel handler of the prefs compartment. */
|
||||
export const wheelZoom = EditorView.domEventHandlers({
|
||||
wheel(e, view) {
|
||||
if (!e.metaKey && !e.ctrlKey) return false;
|
||||
const step = wheelZoomStep(e);
|
||||
if (step === null) return false;
|
||||
e.preventDefault();
|
||||
stepConfiguredEditorsFontZoom(view, e.deltaY < 0 ? 1 : -1);
|
||||
if (step) stepConfiguredEditorsFontZoom(view, step);
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* `.properties`, `.ini`, `.env` and Godot resources, coloured like IntelliJ's Properties and
|
||||
* DotEnv highlighters: the key is KEYWORD, the first `=` or `:` is OPERATION_SIGN and the rest
|
||||
* of the line (with its continuation lines) is STRING. The legacy mode finds the parts; its
|
||||
* own `def` and `quote` styles would read as a variable and plain text.
|
||||
*/
|
||||
import { StreamLanguage, type StreamParser } from "@codemirror/language";
|
||||
import { properties } from "@codemirror/legacy-modes/mode/properties";
|
||||
|
||||
/** The legacy state with the one field read here, plus the line's separator. */
|
||||
interface State {
|
||||
nextMultiline: boolean;
|
||||
separated: boolean;
|
||||
}
|
||||
|
||||
const parser: StreamParser<State> = {
|
||||
name: properties.name,
|
||||
startState: (indentUnit) => ({ ...(properties.startState!(indentUnit) as State), separated: false }),
|
||||
// CodeMirror skips `token` on empty lines; a blank line ends a continued value.
|
||||
blankLine(state) {
|
||||
state.nextMultiline = false;
|
||||
},
|
||||
token(stream, state) {
|
||||
if (stream.sol() && !state.nextMultiline) state.separated = false;
|
||||
const style = properties.token(stream, state);
|
||||
if (style === "def") return "keyword";
|
||||
if (style === "quote") return "string";
|
||||
// The legacy mode returns null only for `=` and `:`.
|
||||
if (style === null) {
|
||||
if (state.separated) return "string";
|
||||
state.separated = true;
|
||||
return "operator";
|
||||
}
|
||||
return style;
|
||||
},
|
||||
};
|
||||
|
||||
export const propertiesLanguage = StreamLanguage.define(parser);
|
||||
@@ -0,0 +1,337 @@
|
||||
// @vitest-environment node
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { StreamLanguage } from "@codemirror/language";
|
||||
import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight";
|
||||
import { tomlParser } from "./toml";
|
||||
|
||||
const language = StreamLanguage.define(tomlParser);
|
||||
|
||||
const highlighter = tagHighlighter([
|
||||
{ tag: t.keyword, class: "keyword" },
|
||||
{ tag: t.string, class: "string" },
|
||||
{ tag: t.number, class: "number" },
|
||||
{ tag: t.standard(t.variableName), class: "builtin" },
|
||||
{ tag: t.comment, class: "comment" },
|
||||
{ tag: t.escape, class: "escape" },
|
||||
{ tag: t.invalid, class: "invalid" },
|
||||
]);
|
||||
|
||||
function highlighted(source: string) {
|
||||
const found: Array<[string, string]> = [];
|
||||
highlightTree(language.parser.parse(source), highlighter, (from, to, style) =>
|
||||
found.push([source.slice(from, to), style]),
|
||||
);
|
||||
return found;
|
||||
}
|
||||
|
||||
describe("TOML highlighting", () => {
|
||||
// IntelliJ's colour settings demo (plugins/toml highlighterDemoText.toml). Its two escape lines
|
||||
// tag only the escapes; the keys and string bodies around them get KEY and STRING there too.
|
||||
it("colours IntelliJ's TOML demo like IntelliJ", () => {
|
||||
const demo = [
|
||||
"# This is a TOML document.",
|
||||
"",
|
||||
'title = "TOML Example"',
|
||||
'description = """',
|
||||
" Multiline",
|
||||
" description",
|
||||
'"""',
|
||||
"date = 2019-11-04T07:32:00-08:00",
|
||||
"",
|
||||
"[database]",
|
||||
'server = "192.168.1.1"',
|
||||
"ports = [ 8001, 8001, 8002 ]",
|
||||
'"connection_max" = 5000',
|
||||
"enabled = true",
|
||||
"",
|
||||
"[servers]",
|
||||
"alpha = { ip = '10.0.0.1', dc = \"eqdc10\" }",
|
||||
"beta = { ip = '10.0.0.2', dc = \"eqdc10\" }",
|
||||
"",
|
||||
"[clients]",
|
||||
'data = [ ["gamma", "delta"], [1.0, 2.0] ]',
|
||||
"",
|
||||
"hosts = [",
|
||||
' "alpha",',
|
||||
' "omega",',
|
||||
"]",
|
||||
"",
|
||||
'valid-escapes = """\\tline \\"1\\"',
|
||||
" line\\u00202",
|
||||
" line 3\\U0000002E",
|
||||
'"""',
|
||||
'invalid-escapes = "\\a \\u20 \\U0020"',
|
||||
].join("\n");
|
||||
expect(highlighted(demo)).toEqual([
|
||||
["# This is a TOML document.", "comment"],
|
||||
["title", "keyword"],
|
||||
['"TOML Example"', "string"],
|
||||
["description", "keyword"],
|
||||
['"""', "string"],
|
||||
[" Multiline", "string"],
|
||||
[" description", "string"],
|
||||
['"""', "string"],
|
||||
["date", "keyword"],
|
||||
["2019-11-04T07:32:00-08:00", "builtin"],
|
||||
["database", "keyword"],
|
||||
["server", "keyword"],
|
||||
['"192.168.1.1"', "string"],
|
||||
["ports", "keyword"],
|
||||
["8001", "number"],
|
||||
["8001", "number"],
|
||||
["8002", "number"],
|
||||
['"connection_max"', "string"],
|
||||
["5000", "number"],
|
||||
["enabled", "keyword"],
|
||||
["true", "builtin"],
|
||||
["servers", "keyword"],
|
||||
["alpha", "keyword"],
|
||||
["ip", "keyword"],
|
||||
["'10.0.0.1'", "string"],
|
||||
["dc", "keyword"],
|
||||
['"eqdc10"', "string"],
|
||||
["beta", "keyword"],
|
||||
["ip", "keyword"],
|
||||
["'10.0.0.2'", "string"],
|
||||
["dc", "keyword"],
|
||||
['"eqdc10"', "string"],
|
||||
["clients", "keyword"],
|
||||
["data", "keyword"],
|
||||
['"gamma"', "string"],
|
||||
['"delta"', "string"],
|
||||
["1.0", "number"],
|
||||
["2.0", "number"],
|
||||
["hosts", "keyword"],
|
||||
['"alpha"', "string"],
|
||||
['"omega"', "string"],
|
||||
["valid-escapes", "keyword"],
|
||||
['"""', "string"],
|
||||
["\\t", "escape"],
|
||||
["line ", "string"],
|
||||
['\\"', "escape"],
|
||||
["1", "string"],
|
||||
['\\"', "escape"],
|
||||
[" line", "string"],
|
||||
["\\u0020", "escape"],
|
||||
["2", "string"],
|
||||
[" line 3", "string"],
|
||||
["\\U0000002E", "escape"],
|
||||
['"""', "string"],
|
||||
["invalid-escapes", "keyword"],
|
||||
['"', "string"],
|
||||
["\\a", "invalid"],
|
||||
[" ", "string"],
|
||||
["\\u", "invalid"],
|
||||
["20 ", "string"],
|
||||
["\\U", "invalid"],
|
||||
['0020"', "string"],
|
||||
]);
|
||||
});
|
||||
|
||||
// IntelliJ's TomlHighlightingAnnotatorTest: numbers, dates and booleans can be keys too.
|
||||
it("colours numbers and dates as values and bare keys of any shape as keys", () => {
|
||||
expect(
|
||||
highlighted(
|
||||
[
|
||||
'k1= "foo"',
|
||||
'k2."k3".k4 = "bar"',
|
||||
'123 = "baz"',
|
||||
'2019-11-08 = "qqq"',
|
||||
"true = 1",
|
||||
"k5 = { k6 = 123, k7 = 2019-11-08 }",
|
||||
"[foo.bar]",
|
||||
].join("\n"),
|
||||
),
|
||||
).toEqual([
|
||||
["k1", "keyword"],
|
||||
['"foo"', "string"],
|
||||
["k2", "keyword"],
|
||||
['"k3"', "string"],
|
||||
["k4", "keyword"],
|
||||
['"bar"', "string"],
|
||||
["123", "keyword"],
|
||||
['"baz"', "string"],
|
||||
["2019-11-08", "keyword"],
|
||||
['"qqq"', "string"],
|
||||
["true", "keyword"],
|
||||
["1", "number"],
|
||||
["k5", "keyword"],
|
||||
["k6", "keyword"],
|
||||
["123", "number"],
|
||||
["k7", "keyword"],
|
||||
["2019-11-08", "builtin"],
|
||||
["foo", "keyword"],
|
||||
["bar", "keyword"],
|
||||
]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["t = 07:32:00", [["07:32:00", "builtin"]]],
|
||||
// A time needs seconds: this is two numbers around a stray colon, as in IntelliJ's lexer.
|
||||
[
|
||||
"t = 07:32",
|
||||
[
|
||||
["07", "number"],
|
||||
["32", "number"],
|
||||
],
|
||||
],
|
||||
[
|
||||
"d = 2019-11-08 # c",
|
||||
[
|
||||
["2019-11-08", "builtin"],
|
||||
["# c", "comment"],
|
||||
],
|
||||
],
|
||||
["d = 1979-05-27 07:32:00Z", [["1979-05-27 07:32:00Z", "builtin"]]],
|
||||
["d = 1979-05-27T00:32:00.999999+07:00", [["1979-05-27T00:32:00.999999+07:00", "builtin"]]],
|
||||
["n = +inf", [["+inf", "number"]]],
|
||||
["n = 1_000", [["1_000", "number"]]],
|
||||
["n = 6.626e-34", [["6.626e-34", "number"]]],
|
||||
["n = 0xdead_beef", [["0xdead_beef", "number"]]],
|
||||
["n = 0o755", [["0o755", "number"]]],
|
||||
["n = 0b1101", [["0b1101", "number"]]],
|
||||
// Not a number (a hex digit has to follow `0x`) or not a boolean: a bare key to IntelliJ's lexer.
|
||||
["n = 0x_1", [["0x_1", "keyword"]]],
|
||||
["b = trueish", [["trueish", "keyword"]]],
|
||||
["s = 'C:\\Users\\nodejs'", [["'C:\\Users\\nodejs'", "string"]]],
|
||||
['s = """"q""""', [['""""q""""', "string"]]],
|
||||
["s = ''''q''''", [["''''q''''", "string"]]],
|
||||
[
|
||||
's = "\\uD800"',
|
||||
[
|
||||
['"', "string"],
|
||||
["\\uD800", "invalid"],
|
||||
['"', "string"],
|
||||
],
|
||||
],
|
||||
[
|
||||
's = "\\U0010FFFF\\U00110000"',
|
||||
[
|
||||
['"', "string"],
|
||||
["\\U0010FFFF", "escape"],
|
||||
["\\U00110000", "invalid"],
|
||||
['"', "string"],
|
||||
],
|
||||
],
|
||||
[
|
||||
's = "\\e"',
|
||||
[
|
||||
['"', "string"],
|
||||
["\\e", "invalid"],
|
||||
['"', "string"],
|
||||
],
|
||||
],
|
||||
[
|
||||
's = "\\\\"',
|
||||
[
|
||||
['"', "string"],
|
||||
["\\\\", "escape"],
|
||||
['"', "string"],
|
||||
],
|
||||
],
|
||||
// A line-ending backslash trims the line break in a multi-line basic string only.
|
||||
[
|
||||
's = """a \\\n b"""',
|
||||
[
|
||||
['"""a ', "string"],
|
||||
["\\", "escape"],
|
||||
[' b"""', "string"],
|
||||
],
|
||||
],
|
||||
// Whitespace may follow that backslash.
|
||||
[
|
||||
's = """a \\ \t\n b"""',
|
||||
[
|
||||
['"""a ', "string"],
|
||||
["\\ \t", "escape"],
|
||||
[' b"""', "string"],
|
||||
],
|
||||
],
|
||||
[
|
||||
's = "a \\\nb = 1',
|
||||
[
|
||||
['"a ', "string"],
|
||||
["\\", "invalid"],
|
||||
["b", "keyword"],
|
||||
["1", "number"],
|
||||
],
|
||||
],
|
||||
[
|
||||
"k = 'a'.b",
|
||||
[
|
||||
["'a'", "string"],
|
||||
["b", "keyword"],
|
||||
],
|
||||
],
|
||||
[" [dependencies]", [["dependencies", "keyword"]]],
|
||||
["[[bin]]", [["bin", "keyword"]]],
|
||||
[
|
||||
'[ "a b" . c ]',
|
||||
[
|
||||
['"a b"', "string"],
|
||||
["c", "keyword"],
|
||||
],
|
||||
],
|
||||
["x = [{}, 1]", [["1", "number"]]],
|
||||
[
|
||||
"x = [{ a = 1 }, { b = [2, { c = 3 }] }]",
|
||||
[
|
||||
["a", "keyword"],
|
||||
["1", "number"],
|
||||
["b", "keyword"],
|
||||
["2", "number"],
|
||||
["c", "keyword"],
|
||||
["3", "number"],
|
||||
],
|
||||
],
|
||||
[
|
||||
'features = [\n "derive", # serde\n 1,\n]\nb = true',
|
||||
[
|
||||
['"derive"', "string"],
|
||||
["# serde", "comment"],
|
||||
["1", "number"],
|
||||
["b", "keyword"],
|
||||
["true", "builtin"],
|
||||
],
|
||||
],
|
||||
// A nested array at column 0 is no table header.
|
||||
[
|
||||
"x = [\n[1],\n[true]\n]\ny = 2",
|
||||
[
|
||||
["1", "number"],
|
||||
["true", "builtin"],
|
||||
["y", "keyword"],
|
||||
["2", "number"],
|
||||
],
|
||||
],
|
||||
// An unclosed array while typing: the next key line starts over.
|
||||
[
|
||||
'deps = [\n[package]\nname = "x"',
|
||||
[
|
||||
["package", "keyword"],
|
||||
["name", "keyword"],
|
||||
['"x"', "string"],
|
||||
],
|
||||
],
|
||||
[
|
||||
'deps = [\nname = "x"',
|
||||
[
|
||||
["name", "keyword"],
|
||||
['"x"', "string"],
|
||||
],
|
||||
],
|
||||
// An unclosed single-line string ends with its line.
|
||||
[
|
||||
's = "abc\nk = 1',
|
||||
[
|
||||
['"abc', "string"],
|
||||
["k", "keyword"],
|
||||
["1", "number"],
|
||||
],
|
||||
],
|
||||
] as Array<[string, Array<[string, string]>]>)("colours %j", (source, values) => {
|
||||
const found = highlighted(source);
|
||||
const key = source.match(/^[A-Za-z0-9_-]+(?= ?=)/)?.[0];
|
||||
expect(found).toEqual(key ? [[key, "keyword"], ...values] : values);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,160 @@
|
||||
/**
|
||||
* TOML coloured like IntelliJ's TOML plugin (TomlHighlighter, TomlHighlightingAnnotator): a bare
|
||||
* key is KEYWORD wherever it stands (headers, dotted keys, inline tables), even when it reads as
|
||||
* a number, date or boolean; booleans and dates are PREDEFINED_SYMBOL; escapes in basic strings
|
||||
* are valid or invalid as in TomlEscapeLexer. `=`, brackets, `,` and `.` stay plain. Values
|
||||
* follow the TOML 1.0 lexer (TomlLexer.flex), so a time needs its seconds.
|
||||
*/
|
||||
import type { StreamParser, StringStream } from "@codemirror/language";
|
||||
|
||||
type Delimiter = '"' | "'" | '"""' | "'''";
|
||||
|
||||
export interface TomlState {
|
||||
/** The string being read; a multi-line one carries over to the next lines. */
|
||||
string: Delimiter | null;
|
||||
/** Open arrays and inline tables, innermost last. */
|
||||
stack: Array<"array" | "inline">;
|
||||
position: "key" | "value";
|
||||
}
|
||||
|
||||
const KEY_PART = String.raw`(?:[A-Za-z0-9_-]+|"(?:[^"\\]|\\.)*"|'[^']*')`;
|
||||
const DOTTED_KEY = String.raw`${KEY_PART}(?:\s*\.\s*${KEY_PART})*`;
|
||||
/** A key/value line ends a container left open by a typo; no valid array or inline table holds one. */
|
||||
const NEW_ENTRY = new RegExp(String.raw`^\s*${DOTTED_KEY}\s*=`);
|
||||
|
||||
const BARE_KEY = /^[A-Za-z0-9_-]+/;
|
||||
const DATE_TIME =
|
||||
/^(?:\d{4}-\d{2}-\d{2}(?:[Tt ]\d{2}:\d{2}:\d{2}(?:\.\d+)?)?|\d{2}:\d{2}:\d{2}(?:\.\d+)?)(?:[Zz]|[+-]\d{2}:\d{2})?/;
|
||||
const BOOLEAN = /^(?:true|false)/;
|
||||
const DEC_INT = String.raw`[-+]?(?:0|[1-9](?:_?\d)*)`;
|
||||
const DIGITS = String.raw`\d(?:_?\d)*`;
|
||||
const NUMBERS = [
|
||||
new RegExp(String.raw`^${DEC_INT}(?:[eE][-+]?${DIGITS}|\.${DIGITS}(?:[eE][-+]?${DIGITS})?)`),
|
||||
/^[-+]?(?:inf|nan)/,
|
||||
/^0x[0-9a-fA-F](?:_?[0-9a-fA-F])*/,
|
||||
/^0o[0-7](?:_?[0-7])*/,
|
||||
/^0b[01](?:_?[01])*/,
|
||||
new RegExp(`^${DEC_INT}`),
|
||||
// Leading zeros: a key in IntelliJ's lexer, a number where a value stands.
|
||||
/^-?\d+/,
|
||||
];
|
||||
|
||||
function matchLength(stream: StringStream, pattern: RegExp): number {
|
||||
const match = stream.match(pattern, false) as RegExpMatchArray | null;
|
||||
return match ? match[0].length : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Numbers, dates and booleans by the longest match, as JFlex picks. A longer bare word is a
|
||||
* bare key to IntelliJ's lexer, which colours it as one wherever it stands.
|
||||
*/
|
||||
function scalar(stream: StringStream): string | null {
|
||||
const word = matchLength(stream, BARE_KEY);
|
||||
const date = matchLength(stream, DATE_TIME);
|
||||
const bool = matchLength(stream, BOOLEAN);
|
||||
const number = Math.max(...NUMBERS.map((pattern) => matchLength(stream, pattern)));
|
||||
const longest = Math.max(date, bool, number);
|
||||
if (longest === 0 || longest < word) {
|
||||
if (!word) {
|
||||
stream.next();
|
||||
return null;
|
||||
}
|
||||
stream.pos += word;
|
||||
return "keyword";
|
||||
}
|
||||
stream.pos += longest;
|
||||
return number === longest ? "number" : "builtin";
|
||||
}
|
||||
|
||||
function isScalarValue(value: number): boolean {
|
||||
return value <= 0xd7ff || (value >= 0xe000 && value <= 0x10ffff);
|
||||
}
|
||||
|
||||
function escape(stream: StringStream, multiline: boolean): string {
|
||||
stream.next();
|
||||
// A line-ending backslash, whitespace after it allowed, trims the line break of a multi-line string.
|
||||
if (multiline && stream.match(/^[ \t]*$/)) return "escape";
|
||||
const ch = stream.next();
|
||||
if (ch === undefined) return "invalid";
|
||||
if (ch === "u" || ch === "U") {
|
||||
const hex = stream.match(ch === "u" ? /^[0-9a-fA-F]{4}/ : /^[0-9a-fA-F]{8}/) as RegExpMatchArray | null;
|
||||
return hex && isScalarValue(parseInt(hex[0], 16)) ? "escape" : "invalid";
|
||||
}
|
||||
return 'btnfr"\\'.includes(ch) ? "escape" : "invalid";
|
||||
}
|
||||
|
||||
function stringBody(stream: StringStream, state: TomlState): string {
|
||||
const delimiter = state.string!;
|
||||
const quote = delimiter.charAt(0);
|
||||
const basic = quote === '"';
|
||||
if (basic && stream.peek() === "\\") return escape(stream, delimiter === '"""');
|
||||
while (!stream.eol()) {
|
||||
if (basic && stream.peek() === "\\") return "string";
|
||||
if (stream.match(delimiter)) {
|
||||
// A multi-line string may end in up to two quotes of its own right before the closing three.
|
||||
if (delimiter.length === 3) for (let i = 0; i < 2 && stream.eat(quote); i++);
|
||||
state.string = null;
|
||||
return "string";
|
||||
}
|
||||
stream.next();
|
||||
}
|
||||
if (delimiter.length === 1) state.string = null;
|
||||
return "string";
|
||||
}
|
||||
|
||||
function openString(stream: StringStream, state: TomlState): boolean {
|
||||
const quote = stream.match(/^(?:"""|'''|"|')/) as RegExpMatchArray | null;
|
||||
if (quote) state.string = quote[0] as Delimiter;
|
||||
return quote !== null;
|
||||
}
|
||||
|
||||
export const tomlParser: StreamParser<TomlState> = {
|
||||
name: "toml",
|
||||
startState: () => ({ string: null, stack: [], position: "key" }),
|
||||
token(stream, state) {
|
||||
if (stream.sol()) {
|
||||
if (state.string === '"' || state.string === "'") state.string = null;
|
||||
if (!state.string && (!state.stack.length || NEW_ENTRY.test(stream.string))) {
|
||||
state.stack = [];
|
||||
state.position = "key";
|
||||
}
|
||||
}
|
||||
if (state.string) return stringBody(stream, state);
|
||||
if (stream.eatSpace()) return null;
|
||||
if (stream.peek() === "#") {
|
||||
stream.skipToEnd();
|
||||
return "comment";
|
||||
}
|
||||
if (openString(stream, state)) return "string";
|
||||
const top = state.stack[state.stack.length - 1];
|
||||
if (state.position === "key") {
|
||||
if (stream.match(BARE_KEY)) return "keyword";
|
||||
const ch = stream.next();
|
||||
if (ch === "=") state.position = "value";
|
||||
else if (ch === "}" && top === "inline") {
|
||||
state.stack.pop();
|
||||
state.position = "value";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
const ch = stream.peek();
|
||||
if (ch === "[" || ch === "{") {
|
||||
stream.next();
|
||||
state.stack.push(ch === "[" ? "array" : "inline");
|
||||
if (ch === "{") state.position = "key";
|
||||
return null;
|
||||
}
|
||||
if (ch === "]" || ch === "}") {
|
||||
stream.next();
|
||||
if (top === (ch === "]" ? "array" : "inline")) state.stack.pop();
|
||||
return null;
|
||||
}
|
||||
if (ch === ",") {
|
||||
stream.next();
|
||||
if (top === "inline") state.position = "key";
|
||||
return null;
|
||||
}
|
||||
return scalar(stream);
|
||||
},
|
||||
languageData: { commentTokens: { line: "#" } },
|
||||
};
|
||||
@@ -1,4 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { getIndentation } from "@codemirror/language";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { findLanguageDescription, loadSupport } from "./languages";
|
||||
|
||||
describe("vue language mode", () => {
|
||||
@@ -23,4 +25,31 @@ describe("vue language mode", () => {
|
||||
expect(tree).toContain("Declaration");
|
||||
expect(tree).not.toContain("SassVariableName");
|
||||
});
|
||||
|
||||
it("indents the top-level <template>'s children only, not <script setup> or <style> code", async () => {
|
||||
const support = await loadSupport(findLanguageDescription("Vue", "/p/a.vue")!);
|
||||
const doc = [
|
||||
"<template>",
|
||||
"<div>",
|
||||
"</div>",
|
||||
"</template>",
|
||||
'<script setup lang="ts">',
|
||||
"const a = 1",
|
||||
"function f() {",
|
||||
"return a",
|
||||
"}",
|
||||
"</script>",
|
||||
"<style>",
|
||||
".a { color: red; }",
|
||||
"</style>",
|
||||
].join("\n");
|
||||
const state = EditorState.create({ doc, extensions: [support!, EditorState.tabSize.of(2)] });
|
||||
const indent = (line: number) => getIndentation(state, state.doc.line(line).from);
|
||||
expect(indent(2)).toBe(2);
|
||||
expect(indent(6)).toBe(0);
|
||||
expect(indent(7)).toBe(0);
|
||||
expect(indent(8)).toBe(2);
|
||||
expect(indent(10)).toBe(0);
|
||||
expect(indent(12)).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -4,24 +4,38 @@
|
||||
* stock `vue()` parses every `<style>` as plain CSS, which loses the SCSS
|
||||
* colours.
|
||||
*/
|
||||
import { LanguageSupport } from "@codemirror/language";
|
||||
import { indentNodeProp, LanguageSupport, type LRLanguage, type TreeIndentContext } from "@codemirror/language";
|
||||
import { html } from "@codemirror/lang-html";
|
||||
import { sassLanguage } from "@codemirror/lang-sass";
|
||||
import { vue } from "@codemirror/lang-vue";
|
||||
|
||||
/**
|
||||
* WebStorm's Vue code style indents the children of the top-level `<template>` only: code in
|
||||
* `<script setup>` or `<style>` starts at the margin, as `npm create vue` writes it.
|
||||
*/
|
||||
function elementIndent(context: TreeIndentContext): number | null {
|
||||
const after = /^(\s*)(<\/)?/.exec(context.textAfter)!;
|
||||
const node = context.node;
|
||||
if (node.to <= context.pos + after[0].length) return context.continue();
|
||||
const tag = node.firstChild?.getChild("TagName");
|
||||
const flat =
|
||||
node.parent?.name === "Document" && !!tag && context.state.sliceDoc(tag.from, tag.to).toLowerCase() !== "template";
|
||||
return context.lineIndent(node.from) + (after[2] || flat ? 0 : context.unit);
|
||||
}
|
||||
|
||||
export function vueLanguage(): LanguageSupport {
|
||||
return vue({
|
||||
base: html({
|
||||
selfClosingTags: true,
|
||||
// `<style>` without `lang` (or with `lang="css"`) keeps HTML's own CSS
|
||||
// nesting; only an explicit SCSS/Sass dialect re-parses it.
|
||||
nestedLanguages: [
|
||||
{
|
||||
tag: "style",
|
||||
attrs: (a) => a.lang === "scss" || a.lang === "sass",
|
||||
parser: sassLanguage.parser,
|
||||
},
|
||||
],
|
||||
}),
|
||||
const base = html({
|
||||
selfClosingTags: true,
|
||||
// `<style>` without `lang` (or with `lang="css"`) keeps HTML's own CSS
|
||||
// nesting; only an explicit SCSS/Sass dialect re-parses it.
|
||||
nestedLanguages: [
|
||||
{
|
||||
tag: "style",
|
||||
attrs: (a) => a.lang === "scss" || a.lang === "sass",
|
||||
parser: sassLanguage.parser,
|
||||
},
|
||||
],
|
||||
});
|
||||
const language = (base.language as LRLanguage).configure({ props: [indentNodeProp.add({ Element: elementIndent })] });
|
||||
return vue({ base: new LanguageSupport(language, base.support) });
|
||||
}
|
||||
@@ -154,6 +154,18 @@ describe("editor Copy Path/Reference chooser", () => {
|
||||
expect(writeText).toHaveBeenCalledExactlyOnceWith(path);
|
||||
});
|
||||
|
||||
it("copies a selection over several lines as path:first-last", async () => {
|
||||
const view = ctrl.activeSlot!.view!;
|
||||
view.dispatch({ selection: { anchor: 0, head: documentText.indexOf("A {}") } });
|
||||
await executeAction("editor.copyPathReference");
|
||||
const item = popup().items.find((item) => item.id === "editor.copyPathWithLineNumber")!;
|
||||
expect(item.preview).toBe("src/A.java:1-2");
|
||||
// A selection that ends at the start of a line leaves that line out.
|
||||
view.dispatch({ selection: { anchor: 0, head: documentText.indexOf("class") } });
|
||||
await executeAction("editor.copyPathWithLineNumber");
|
||||
await vi.waitFor(() => expect(writeText).toHaveBeenLastCalledWith("src/A.java:1"));
|
||||
});
|
||||
|
||||
it("uses path:line off a symbol and ignores stale reference resolution", async () => {
|
||||
ctrl.activeSlot!.view!.dispatch({ selection: { anchor: documentText.length - 1 } });
|
||||
await executeAction("editor.copyPathReference");
|
||||
|
||||
@@ -4,6 +4,7 @@ import { EditorView } from "@codemirror/view";
|
||||
import { useEditorRegistry, type TextEditorHandle } from "@/editor/api";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { fontZoom, resetAllEditorsFontZoom, setFontZoom, stepAllEditorsFontZoom, wheelZoom } from "./cm/prefs";
|
||||
import { resetWheelZoomGesture } from "@/platform/wheelZoom";
|
||||
|
||||
const zoomOf = (view: EditorView) => view.state.field(fontZoom, false);
|
||||
|
||||
@@ -19,6 +20,7 @@ describe("editor font zoom (active editor by default, all editors when configure
|
||||
return view;
|
||||
};
|
||||
beforeEach(() => {
|
||||
resetWheelZoomGesture();
|
||||
resetAllEditorsFontZoom();
|
||||
useProject.setState({ settings: null });
|
||||
});
|
||||
@@ -45,6 +47,16 @@ describe("editor font zoom (active editor by default, all editors when configure
|
||||
expect(zoomOf(second)).toBe(-1);
|
||||
});
|
||||
|
||||
it("doesn't zoom from the inertia of a scroll when ⌘/Ctrl is pressed during it", () => {
|
||||
const view = makeView();
|
||||
const plain = new WheelEvent("wheel", { bubbles: true, cancelable: true, deltaY: -40 });
|
||||
view.contentDOM.dispatchEvent(plain);
|
||||
const coasting = new WheelEvent("wheel", { bubbles: true, cancelable: true, metaKey: true, deltaY: -20 });
|
||||
view.contentDOM.dispatchEvent(coasting);
|
||||
expect(coasting.defaultPrevented).toBe(false);
|
||||
expect(zoomOf(view)).toBe(0);
|
||||
});
|
||||
|
||||
it("zooms every open editor from ⌘/Ctrl+wheel when wheelZoomScope is 'all' (#2480)", () => {
|
||||
useProject.setState({ settings: { editor: { general: { wheelZoomScope: "all" } } } } as never);
|
||||
const first = makeView();
|
||||
|
||||
@@ -35,9 +35,14 @@ const hintField = StateField.define<Hint | null>({
|
||||
pos: h.pos,
|
||||
above: true,
|
||||
strictSide: false,
|
||||
create: () => {
|
||||
create: (view) => {
|
||||
const dom = document.createElement("div");
|
||||
dom.className = `cm-lsp-hint cm-lsp-hint-${h.tone}`;
|
||||
// Clicked or focused (a value tree expanded in it): the user works in the hint, so
|
||||
// it stays until an edit, a caret move or Escape.
|
||||
const keep = () => clearTimeout(timers.get(view));
|
||||
dom.addEventListener("pointerdown", keep);
|
||||
dom.addEventListener("focusin", keep);
|
||||
dom.setAttribute("role", "status");
|
||||
if (h.pending) dom.dataset.pending = "true";
|
||||
Object.assign(dom.dataset, h.data);
|
||||
@@ -63,7 +68,8 @@ const timers = new WeakMap<EditorView, ReturnType<typeof setTimeout>>();
|
||||
export function showHint(
|
||||
view: EditorView,
|
||||
content: Hint["content"],
|
||||
opts: { pos?: number; tone?: Hint["tone"]; timeout?: number; pending?: boolean; data?: Hint["data"] } = {},
|
||||
/** `timeout: null`: the hint stays until an edit, a caret move or Escape. */
|
||||
opts: { pos?: number; tone?: Hint["tone"]; timeout?: number | null; pending?: boolean; data?: Hint["data"] } = {},
|
||||
) {
|
||||
const pos = opts.pos ?? view.state.selection.main.head;
|
||||
const effects: StateEffect<unknown>[] = [
|
||||
@@ -72,6 +78,7 @@ export function showHint(
|
||||
if (!view.state.field(hintField, false)) effects.push(StateEffect.appendConfig.of(hintExtension()));
|
||||
view.dispatch({ effects });
|
||||
clearTimeout(timers.get(view));
|
||||
if (opts.timeout === null) return;
|
||||
timers.set(
|
||||
view,
|
||||
// Also while the view is hidden: it would show the hint again when its tab is shown.
|
||||
|
||||
@@ -406,6 +406,11 @@ function SessionStatus({
|
||||
>
|
||||
{/* Where the task works, in one quiet line like the new-task page: project (in a workspace), branch, worktree. */}
|
||||
<span className={styles.where} title={task.cwd}>
|
||||
{/* Which agent runs the task: with several tasks side by side, this tells their answers apart. */}
|
||||
<span className={styles.fact} title={providerName(task.provider)}>
|
||||
<Icon name={providerIcon(task.provider)} size={13} />
|
||||
<span className={styles.factText}>{providerName(task.provider)}</span>
|
||||
</span>
|
||||
{project?.workspace && projectName && (
|
||||
<span className={styles.fact}>
|
||||
<Icon name="folder" size={13} />
|
||||
|
||||
@@ -112,6 +112,15 @@ describe("commitMessagePrompt", () => {
|
||||
it("leaves out the style hint without earlier commits", () => {
|
||||
expect(commitMessagePrompt(PATCH, 72, [])).not.toContain("latest commits");
|
||||
});
|
||||
|
||||
it("adds the project's commit conventions before the recent subjects", () => {
|
||||
const prompt = commitMessagePrompt(PATCH, 72, ["fix: y"], " Use Conventional Commits.\nPrefix the issue key. ");
|
||||
const conventions = prompt.indexOf("Follow these conventions for commit messages here:\nUse Conventional Commits.");
|
||||
expect(conventions).toBeGreaterThan(0);
|
||||
expect(prompt).toContain("Prefix the issue key.\n");
|
||||
expect(conventions).toBeLessThan(prompt.indexOf("latest commits"));
|
||||
expect(commitMessagePrompt(PATCH, 72, [], " \n ")).not.toContain("conventions");
|
||||
});
|
||||
});
|
||||
|
||||
describe("commitMessageOf", () => {
|
||||
|
||||
@@ -44,7 +44,12 @@ export function fitPatch(patch: string, budget = PATCH_BUDGET, perFile = FILE_BU
|
||||
return omitted.length ? `${out}\nDiff omitted for: ${omitted.join(", ")}\n` : out;
|
||||
}
|
||||
|
||||
export function commitMessagePrompt(patch: string, subjectLimit: number, recentSubjects: readonly string[]): string {
|
||||
export function commitMessagePrompt(
|
||||
patch: string,
|
||||
subjectLimit: number,
|
||||
recentSubjects: readonly string[],
|
||||
instructions = "",
|
||||
): string {
|
||||
const lines = [
|
||||
"Write a commit message",
|
||||
"",
|
||||
@@ -54,6 +59,8 @@ export function commitMessagePrompt(patch: string, subjectLimit: number, recentS
|
||||
"- Don't edit files or run commands. The whole diff is below.",
|
||||
"- Reply with the commit message only: no quotes, no code fence, no commentary.",
|
||||
];
|
||||
// The project's own conventions (Settings › Version Control › Commit) come before the style of recent commits.
|
||||
if (instructions.trim()) lines.push("", "Follow these conventions for commit messages here:", instructions.trim());
|
||||
if (recentSubjects.length) {
|
||||
lines.push(
|
||||
"",
|
||||
@@ -250,7 +257,12 @@ async function generate(): Promise<void> {
|
||||
|
||||
const { commit } = workflowSettings().vcs;
|
||||
const subjects = await recentSubjects(changes.roots[0]);
|
||||
const prompt = commitMessagePrompt(changes.patch, commit.limitSubject ? commit.subjectLimit : 72, subjects);
|
||||
const prompt = commitMessagePrompt(
|
||||
changes.patch,
|
||||
commit.limitSubject ? commit.subjectLimit : 72,
|
||||
subjects,
|
||||
commit.agentInstructions,
|
||||
);
|
||||
let task: AgentTask | undefined;
|
||||
let release = () => {};
|
||||
try {
|
||||
|
||||
@@ -373,6 +373,11 @@ describe("composer UI during submission", () => {
|
||||
expect(screen.getByRole("button", { name: "Send" })).toBeEnabled();
|
||||
});
|
||||
|
||||
it("names the task's agent under the composer", () => {
|
||||
render(<SessionEditor input={{ kind: SESSION_KIND, key: sessionKey("A"), data: { task: "A" } }} />);
|
||||
expect(screen.getByTitle("Codex")).toHaveTextContent("Codex");
|
||||
});
|
||||
|
||||
it("clears an unchanged session draft after only moving the caret", async () => {
|
||||
const response = deferred();
|
||||
backend.prompt.mockReturnValue(response.promise);
|
||||
|
||||
@@ -3,6 +3,7 @@ import { create } from "zustand";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { registerFontZoomSurface, useEditorShown, useEditorTabId, useToolWindowShown } from "@/workbench/contributions";
|
||||
import { wheelZoomStep } from "@/platform/wheelZoom";
|
||||
|
||||
const MIN_FONT_ZOOM = -6;
|
||||
const MAX_FONT_ZOOM = 36;
|
||||
@@ -74,10 +75,12 @@ export function useAgentFontZoomSurface(
|
||||
if (!active || !el) return;
|
||||
const step = (delta: number) => stepAgentSurfaceFontZoom(surfaceKey, delta);
|
||||
const onWheel = (e: WheelEvent) => {
|
||||
if ((!e.ctrlKey && !e.metaKey) || e.deltaY === 0 || !editorPrefs().general.wheelZoom) return;
|
||||
if (!editorPrefs().general.wheelZoom) return;
|
||||
const zoom = wheelZoomStep(e);
|
||||
if (zoom === null) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
step(e.deltaY < 0 ? 1 : -1);
|
||||
if (zoom) step(zoom);
|
||||
};
|
||||
el.addEventListener("wheel", onWheel, { capture: true, passive: false });
|
||||
const release = registerFontZoomSurface(el, step, { isolated: true });
|
||||
|
||||
@@ -406,7 +406,10 @@ export function windowActions(): Action[] {
|
||||
title: "Move Tab to New Window",
|
||||
category: t("app.category.window"),
|
||||
when: "windowGrouped",
|
||||
run: () => call(commands.windowGroupDetach()),
|
||||
run: async ({ arg }) => {
|
||||
const label = typeof arg === "string" ? arg : useWindowGroup.getState().tabs.find((tab) => tab.current)?.label;
|
||||
if (label) await call(commands.windowGroupDetach(label));
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "window.selectTab",
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
const opened = vi.hoisted(() => [] as string[]);
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const ipc = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
const doc = (path: string) => Promise.resolve({ status: "ok", data: { id: 3, path } });
|
||||
return {
|
||||
...ipc,
|
||||
isTauri: () => true,
|
||||
commands: {
|
||||
...ipc.commands,
|
||||
docOpen: (path: string) => (opened.push(`file ${path}`), doc(path)),
|
||||
docOpenVirtual: (uri: string) => (opened.push(`virtual ${uri}`), doc(uri)),
|
||||
docClose: () => Promise.resolve(),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const { withDocument } = await import("./ipc");
|
||||
|
||||
describe("withDocument", () => {
|
||||
it("opens a library type through its language server, a project file from disk", async () => {
|
||||
const uri = "jdt://contents/java.base/java.util/UUID.class?=demo/%5C/jdk%5C/lib%5C/jrt-fs.jar%60java.base";
|
||||
await withDocument(uri, async (doc) => doc);
|
||||
await withDocument("/p/src/App.java", async (doc) => doc);
|
||||
expect(opened).toEqual([`virtual ${uri}`, "file /p/src/App.java"]);
|
||||
});
|
||||
});
|
||||
@@ -134,7 +134,8 @@ export async function readManyFileLines(
|
||||
export async function withDocument<T>(path: string, fn: (doc: number) => Promise<T>): Promise<T> {
|
||||
const open = editorsFor(path)[0];
|
||||
if (open) return fn(open.ctx.doc);
|
||||
const info = await lspRequest(() => commands.docOpen(path));
|
||||
// Library types (`jdt://…`) are documents the language server provides, not files on disk.
|
||||
const info = await lspRequest(() => (isVirtualUri(path) ? commands.docOpenVirtual(path) : commands.docOpen(path)));
|
||||
try {
|
||||
return await fn(info.id);
|
||||
} finally {
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import type { DebugSessionId, Variable } from "@/bindings";
|
||||
import { showHint } from "@/editor/lsp/hint";
|
||||
import { valueHint } from "../editor/valueTooltip";
|
||||
|
||||
vi.mock("../ui/ValueHintTree", () => ({
|
||||
mountValueTree: (host: HTMLElement) => {
|
||||
host.append(Object.assign(document.createElement("div"), { className: "tree" }));
|
||||
return { unmount: () => {} };
|
||||
},
|
||||
}));
|
||||
|
||||
const session = 7 as DebugSessionId;
|
||||
const order: Variable = {
|
||||
name: "order",
|
||||
value: "Order@12",
|
||||
typeName: "Order",
|
||||
variablesReference: 3,
|
||||
evaluateName: "order",
|
||||
} as Variable;
|
||||
let view: EditorView;
|
||||
const expand = () => {
|
||||
const button = document.querySelector<HTMLButtonElement>("[aria-label='Expand value']")!;
|
||||
button.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true }));
|
||||
button.click();
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
view = new EditorView({ state: EditorState.create({ doc: "order.total" }), parent: document.body });
|
||||
});
|
||||
afterEach(() => {
|
||||
view.destroy();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe("value hint", () => {
|
||||
it("keeps a hint whose value was expanded past the hint's timeout", () => {
|
||||
showHint(view, () => valueHint("order", order, session), { pos: 0, timeout: 4000 });
|
||||
expand();
|
||||
expect(document.querySelector(".cm-lsp-hint .tree")).not.toBeNull();
|
||||
vi.advanceTimersByTime(60_000);
|
||||
expect(document.querySelector(".cm-lsp-hint .tree")).not.toBeNull();
|
||||
});
|
||||
|
||||
it("hands an expanded hover hint to its pin instead of growing in place", () => {
|
||||
const pin = vi.fn();
|
||||
showHint(view, () => valueHint("order", order, session, 400, { pin }), { pos: 0 });
|
||||
expand();
|
||||
expect(pin).toHaveBeenCalled();
|
||||
expect(document.querySelector(".tree")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -5,11 +5,11 @@
|
||||
*/
|
||||
import type { EditorState, Extension } from "@codemirror/state";
|
||||
import type { DebugSessionId, Variable } from "@/bindings";
|
||||
import { hoverTooltip, ViewPlugin, type EditorView, type ViewUpdate } from "@codemirror/view";
|
||||
import { showHint } from "@/editor/lsp/hint";
|
||||
import { closeHoverTooltips, hoverTooltip, ViewPlugin, type EditorView, type ViewUpdate } from "@codemirror/view";
|
||||
import { hideHint, showHint } from "@/editor/lsp/hint";
|
||||
import { workflowSettings } from "@/platform/workflowSettings";
|
||||
import { navigationModifierHeld } from "@/platform/navigationModifier";
|
||||
import { activeSession, evaluate } from "../state";
|
||||
import { activeSession, evaluate, useDebug } from "../state";
|
||||
import { inlineValue, shownValue } from "../values";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { iconMarkup, selectableText } from "@/ui";
|
||||
@@ -45,10 +45,20 @@ export function valueHint(
|
||||
value: Variable,
|
||||
session: DebugSessionId,
|
||||
max: number | null = 400,
|
||||
opts: { expanded?: boolean; pin?: () => void } = {},
|
||||
): { dom: HTMLElement; destroy: () => void } {
|
||||
const dom = document.createElement("div");
|
||||
dom.className = `${styles.valueTooltip} ${selectableText}`;
|
||||
let tree: { unmount(): void } | null = null;
|
||||
const expandTree = () => {
|
||||
dom.classList.replace(selectableText, styles.valueTooltipTree!);
|
||||
dom.replaceChildren();
|
||||
tree = mountValueTree(dom, expression, value, session);
|
||||
};
|
||||
if (value.variablesReference > 0 && opts.expanded) {
|
||||
expandTree();
|
||||
return { dom, destroy: () => tree?.unmount() };
|
||||
}
|
||||
if (value.variablesReference > 0) {
|
||||
// IDEA's value hint: the "+" expands the object into a variables tree in place.
|
||||
const expand = document.createElement("button");
|
||||
@@ -60,10 +70,9 @@ export function valueHint(
|
||||
expand.addEventListener("mousedown", (e) => e.preventDefault());
|
||||
expand.addEventListener("click", () => {
|
||||
if (tree) return;
|
||||
if (opts.pin) return opts.pin();
|
||||
expand.remove();
|
||||
dom.classList.replace(selectableText, styles.valueTooltipTree!);
|
||||
dom.replaceChildren();
|
||||
tree = mountValueTree(dom, expression, value, session);
|
||||
expandTree();
|
||||
});
|
||||
dom.append(expand);
|
||||
}
|
||||
@@ -109,15 +118,48 @@ export function valueTooltip(): Extension {
|
||||
pos: expr.from,
|
||||
end: expr.to,
|
||||
above: true,
|
||||
create: () => {
|
||||
return valueHint(expr.text, value, session.id);
|
||||
},
|
||||
create: (view) =>
|
||||
valueHint(expr.text, value, session.id, 400, {
|
||||
// The tree outgrows the hint and may move to the other side of the line, away from the
|
||||
// mouse, which closed the hover tooltip before it could be reached. Like IDEA's value
|
||||
// popup it stays until Escape, a click in the editor or the next step.
|
||||
pin: () => {
|
||||
view.dispatch({ effects: closeHoverTooltips });
|
||||
showHint(view, () => pinnedTree(view, expr.text, value, session.id), {
|
||||
pos: expr.from,
|
||||
timeout: null,
|
||||
});
|
||||
},
|
||||
}),
|
||||
};
|
||||
},
|
||||
{ hoverTime: BASE_HOVER },
|
||||
);
|
||||
}
|
||||
|
||||
/** An expanded value tree, closed when its session leaves the stop it was evaluated in. */
|
||||
function pinnedTree(view: EditorView, expression: string, value: Variable, session: DebugSessionId) {
|
||||
const stop = useDebug.getState().stopSeq;
|
||||
const unsubscribe = useDebug.subscribe((s) => {
|
||||
if (s.stopSeq !== stop || s.sessions[session]?.status !== "paused") hideHint(view);
|
||||
});
|
||||
const hint = valueHint(expression, value, session, 400, { expanded: true });
|
||||
// The tree has the focus, so the editor's Escape doesn't reach the hint.
|
||||
hint.dom.addEventListener("keydown", (e) => {
|
||||
if (e.key !== "Escape" || e.defaultPrevented) return;
|
||||
e.preventDefault();
|
||||
hideHint(view);
|
||||
view.focus();
|
||||
});
|
||||
return {
|
||||
dom: hint.dom,
|
||||
destroy: () => {
|
||||
unsubscribe();
|
||||
hint.destroy();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const SELECTION_DELAY = 400;
|
||||
const MAX_SELECTION = 200;
|
||||
|
||||
|
||||
@@ -33,6 +33,13 @@ import {
|
||||
import { endpointEditorExtension, OPEN_ENDPOINT, openEndpoint } from "./endpoints";
|
||||
import type { EndpointEntry } from "@/workbench/contributions";
|
||||
import { registerSpringEndpointProvider } from "./spring/routeIndex";
|
||||
import {
|
||||
feignEditorExtension,
|
||||
feignMenuItems,
|
||||
GO_TO_FEIGN_ENDPOINT,
|
||||
goToFeignEndpoint,
|
||||
registerFeignNavigation,
|
||||
} from "./spring/feignNavigation";
|
||||
|
||||
const SPRING_WHEN = "editorLangId == java || editorLangId == kotlin";
|
||||
|
||||
@@ -134,6 +141,7 @@ async function newRequest(directory?: string) {
|
||||
export function activate(): () => void {
|
||||
const disposers = [
|
||||
registerSpringEndpointProvider(),
|
||||
registerFeignNavigation(),
|
||||
registerVariableNavigation(),
|
||||
registerFileNavigation(),
|
||||
useProject.subscribe((s, prev) => {
|
||||
@@ -143,7 +151,13 @@ export function activate(): () => void {
|
||||
registerEditorContribution({ id: "http.requests", order: 56, extensions: httpEditorExtension }),
|
||||
registerEditorContribution({ id: "http.endpoints", order: 58, extensions: endpointEditorExtension }),
|
||||
registerEditorContribution({ id: "http.spring", order: 57, extensions: springEditorExtension }),
|
||||
registerMenuGroup({ id: "http.spring", menus: ["editor"], order: 40, items: (_menu, ctx) => menuGroupItems(ctx) }),
|
||||
registerEditorContribution({ id: "http.feign", order: 59, extensions: feignEditorExtension }),
|
||||
registerMenuGroup({
|
||||
id: "http.spring",
|
||||
menus: ["editor"],
|
||||
order: 40,
|
||||
items: (_menu, ctx) => [...menuGroupItems(ctx), ...feignMenuItems(ctx)],
|
||||
}),
|
||||
registerServiceView({
|
||||
id: SERVICE_VIEW,
|
||||
title: "HTTP Client",
|
||||
@@ -161,6 +175,15 @@ export function activate(): () => void {
|
||||
directory ? [{ kind: "action", action: "http.newRequest", arg: { directory }, label: "HTTP Request" }] : [],
|
||||
}),
|
||||
registerActions([
|
||||
{
|
||||
id: GO_TO_FEIGN_ENDPOINT,
|
||||
title: "Go to Feign Endpoint",
|
||||
category: "Navigate",
|
||||
icon: "arrow-right",
|
||||
keywords: ["spring", "feign", "microservice", "endpoint"],
|
||||
when: SPRING_WHEN,
|
||||
run: ({ arg }) => goToFeignEndpoint(arg),
|
||||
},
|
||||
{
|
||||
id: OPEN_ENDPOINT,
|
||||
title: "Open in HTTP Client",
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { callsEndpoint, controllerMethods, feignMethods, sameHttpPath } from "./feign";
|
||||
|
||||
const imports = `import org.springframework.cloud.openfeign.FeignClient;
|
||||
import org.springframework.web.bind.annotation.*;\n`;
|
||||
const client = (
|
||||
annotation = '@FeignClient(name="users", path="/api")',
|
||||
mapping = '@GetMapping("/users/{id}")',
|
||||
) => `${imports}${annotation}
|
||||
interface Client { ${mapping} String find(); }`;
|
||||
const server = (mapping = '@GetMapping("/{user}")', prefix = '@RequestMapping("/api/users")') => `${imports}
|
||||
@RestController ${prefix} class Users { ${mapping} String get() { return ""; } }`;
|
||||
|
||||
describe("literal source Feign navigation", () => {
|
||||
it("reads Java and Kotlin methods, including literal name/value aliases and exact link spans", () => {
|
||||
for (const annotation of [
|
||||
'@FeignClient(name="users",path="/api")',
|
||||
'@FeignClient(value="users",path="/api")',
|
||||
'@FeignClient("users")',
|
||||
]) {
|
||||
const text = client(annotation);
|
||||
const method = feignMethods(text)[0]!;
|
||||
expect(method.service).toBe("users");
|
||||
expect(method.name).toBe("Client.find");
|
||||
expect(text.slice(method.links[0]!.from, method.links[0]!.to)).toBe("/users/{id}");
|
||||
expect(text.slice(method.nameFrom, method.nameFrom + 4)).toBe("find");
|
||||
}
|
||||
const kotlin = `${imports.replaceAll(";", "")}@FeignClient(value="users",path="/api")\ninterface Users {\n @GetMapping("/users/{id}")\n fun find(): String\n}`;
|
||||
expect(feignMethods(kotlin)[0]).toMatchObject({ service: "users", methods: ["GET"], paths: ["/api/users/{id}"] });
|
||||
});
|
||||
|
||||
it("keeps unresolved discovery names and explicit URLs as method/path candidates", () => {
|
||||
for (const args of [
|
||||
'name="${service}"',
|
||||
"name=NAME",
|
||||
'name="users",value="admin"',
|
||||
'name="users",url="http://localhost"',
|
||||
'name="users",url="${url:}"',
|
||||
]) {
|
||||
expect(feignMethods(client(`@FeignClient(${args})`))[0]?.service).toBeNull();
|
||||
}
|
||||
expect(feignMethods(client('@FeignClient(name="users",contextId="admin")'))[0]?.service).toBe("users");
|
||||
});
|
||||
|
||||
it("rejects foreign/shadowed annotations, malformed aliases, dynamic paths and default methods", () => {
|
||||
expect(
|
||||
feignMethods(client().replace("org.springframework.cloud.openfeign.FeignClient", "other.FeignClient")),
|
||||
).toEqual([]);
|
||||
expect(feignMethods(client() + " class FeignClient {} ")).toEqual([]);
|
||||
expect(feignMethods(client('@FeignClient(name="users",name="admin")'))).toEqual([]);
|
||||
expect(feignMethods(client('@FeignClient(name="users",path=PREFIX)'))).toEqual([]);
|
||||
expect(feignMethods(client(undefined, "@GetMapping(PATH)"))).toEqual([]);
|
||||
expect(feignMethods(client(undefined, '@GetMapping("/${path}")'))).toEqual([]);
|
||||
expect(feignMethods(client().replace("String find();", 'default String find() { return ""; }'))).toEqual([]);
|
||||
expect(feignMethods(client().replace("interface Client", "class Client"))).toEqual([]);
|
||||
});
|
||||
|
||||
it("supports fully qualified annotations and preserves UTF-16 offsets", () => {
|
||||
const text =
|
||||
'// 😀\[email protected]("users") interface Client { @org.springframework.web.bind.annotation.GetMapping("/users") String find(); }';
|
||||
const method = feignMethods(text)[0]!;
|
||||
expect(method.service).toBe("users");
|
||||
expect(method.nameFrom).toBe(text.indexOf("find()"));
|
||||
});
|
||||
|
||||
it("handles multiple server methods and unconstrained mappings without inventing GET-only semantics", () => {
|
||||
const get = feignMethods(client())[0]!;
|
||||
expect(callsEndpoint(get, controllerMethods(server())[0]!)).toBe(true);
|
||||
expect(callsEndpoint(get, controllerMethods(server('@PostMapping("/{user}")'))[0]!)).toBe(false);
|
||||
for (const verb of ["POST", "PATCH", "GET"]) {
|
||||
const c = feignMethods(
|
||||
client(undefined, `@RequestMapping(value="/users/{id}",method=RequestMethod.${verb})`),
|
||||
)[0]!;
|
||||
expect(callsEndpoint(c, controllerMethods(server('@RequestMapping("/{user}")'))[0]!)).toBe(true);
|
||||
}
|
||||
const c = feignMethods(client(undefined, '@PostMapping("/users/{id}")'))[0]!;
|
||||
expect(
|
||||
callsEndpoint(
|
||||
c,
|
||||
controllerMethods(server('@RequestMapping(path="/{user}",method={RequestMethod.GET,RequestMethod.POST})'))[0]!,
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
callsEndpoint(
|
||||
c,
|
||||
controllerMethods(
|
||||
server('@RequestMapping("/{user}")', '@RequestMapping(path="/api/users",method=RequestMethod.GET)'),
|
||||
)[0]!,
|
||||
),
|
||||
).toBe(false);
|
||||
const combined = controllerMethods(
|
||||
server('@PostMapping("/{user}")', '@RequestMapping(path="/api/users",method=RequestMethod.GET)'),
|
||||
)[0]!;
|
||||
expect(combined.methods).toEqual(["GET", "POST"]);
|
||||
expect(callsEndpoint(get, combined)).toBe(true);
|
||||
expect(callsEndpoint(c, combined)).toBe(true);
|
||||
});
|
||||
|
||||
it("matches each path alternative, HEAD-to-GET and only supported whole path segments", () => {
|
||||
const c = feignMethods(client(undefined, '@GetMapping({"/other", "/users/{id}"})'))[0]!;
|
||||
expect(callsEndpoint(c, controllerMethods(server())[0]!)).toBe(true);
|
||||
const head = { ...c, methods: ["HEAD"] };
|
||||
expect(callsEndpoint(head, controllerMethods(server())[0]!)).toBe(true);
|
||||
for (const [a, b, expected] of [
|
||||
["/a/{id}", "/a/{name}", true],
|
||||
["/a/{id}", "/a/b/c", false],
|
||||
["/a/**", "/a/b", false],
|
||||
["/a/{id:[0-9]+}", "/a/1", false],
|
||||
["/a/${id}", "/a/1", false],
|
||||
] as const) {
|
||||
expect(sameHttpPath(a, b)).toBe(expected);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,238 @@
|
||||
/** Source-only Feign relationships. Request generation's default GET is not a
|
||||
* server constraint: unconstrained controller mappings accept every method. */
|
||||
import { joinPaths } from "./endpoints";
|
||||
import { allClasses, parseSource, type Annotation, type Expr, type SourceFile, type Tok } from "./source";
|
||||
|
||||
const WEB = "org.springframework.web.bind.annotation";
|
||||
const FEIGN = "org.springframework.cloud.openfeign.FeignClient";
|
||||
const VERBS = new Set(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "TRACE"]);
|
||||
const SHORTCUTS: Record<string, string> = {
|
||||
GetMapping: "GET",
|
||||
PostMapping: "POST",
|
||||
PutMapping: "PUT",
|
||||
PatchMapping: "PATCH",
|
||||
DeleteMapping: "DELETE",
|
||||
};
|
||||
export const MAX_NAVIGATION_SOURCE = 128 * 1024;
|
||||
|
||||
export interface HttpShape {
|
||||
paths: string[];
|
||||
methods: string[];
|
||||
}
|
||||
export interface FeignMethod extends HttpShape {
|
||||
name: string;
|
||||
from: number;
|
||||
to: number;
|
||||
nameFrom: number;
|
||||
/** Literal URL spans, excluding quotes, for modifier-click navigation. */
|
||||
links: { from: number; to: number }[];
|
||||
service: string | null;
|
||||
}
|
||||
export interface ControllerMethod extends HttpShape {
|
||||
name: string;
|
||||
from: number;
|
||||
to: number;
|
||||
}
|
||||
|
||||
function owned(a: Annotation, file: SourceFile, qualified: string): boolean {
|
||||
if (a.duplicateArgs) return false;
|
||||
if (a.qualifiedName) return a.qualifiedName === qualified;
|
||||
if (a.name !== qualified.slice(qualified.lastIndexOf(".") + 1)) return false;
|
||||
if (allClasses(file).some((c) => c.name === a.name)) return false;
|
||||
const explicit = file.imports.filter((i) => i.endsWith(`.${a.name}`));
|
||||
if (explicit.length) return explicit.every((i) => i === qualified);
|
||||
return file.imports.includes(`${qualified.slice(0, qualified.lastIndexOf("."))}.*`);
|
||||
}
|
||||
|
||||
function literal(t: Tok | undefined): string | null {
|
||||
return t?.kind === "str" && /^"[^"\\\r\n]*"$/.test(t.text) && !t.value?.includes("$") ? (t.value ?? "") : null;
|
||||
}
|
||||
|
||||
function strings(expr: Expr | undefined): { values: string[]; links: { from: number; to: number }[] } | null {
|
||||
if (!expr) return { values: [""], links: [] };
|
||||
let tokens = expr;
|
||||
if (
|
||||
(tokens[0]?.text === "{" && tokens.at(-1)?.text === "}") ||
|
||||
(tokens[0]?.text === "[" && tokens.at(-1)?.text === "]")
|
||||
)
|
||||
tokens = tokens.slice(1, -1);
|
||||
else if (tokens[0]?.text === "arrayOf" && tokens[1]?.text === "(" && tokens.at(-1)?.text === ")")
|
||||
tokens = tokens.slice(2, -1);
|
||||
const values: string[] = [];
|
||||
const links: { from: number; to: number }[] = [];
|
||||
for (let i = 0; i < tokens.length; i++) {
|
||||
const t = tokens[i]!;
|
||||
if (i % 2) {
|
||||
if (t.kind !== "p" || t.text !== ",") return null;
|
||||
continue;
|
||||
}
|
||||
const value = literal(t);
|
||||
if (value === null || values.length === 64) return null;
|
||||
values.push(value);
|
||||
if (t.end > t.start + 2) links.push({ from: t.start + 1, to: t.end - 1 });
|
||||
}
|
||||
return values.length ? { values, links } : { values: [""], links: [] };
|
||||
}
|
||||
|
||||
function single(a: Annotation, key: string): string | null {
|
||||
const expr = a.args.get(key);
|
||||
return expr === undefined ? "" : expr.length === 1 ? literal(expr[0]) : null;
|
||||
}
|
||||
|
||||
function service(a: Annotation): string | null {
|
||||
if (single(a, "url") !== "") return null;
|
||||
const name = single(a, "name"),
|
||||
value = single(a, "value");
|
||||
if (name === null || value === null || (name && value && name !== value)) return null;
|
||||
const selected = name || value;
|
||||
return /^[\w.-]{1,255}$/.test(selected) ? selected : null;
|
||||
}
|
||||
|
||||
function mapping(annotations: Annotation[], file: SourceFile) {
|
||||
const found = annotations.filter(
|
||||
(a) => (a.name === "RequestMapping" || a.name in SHORTCUTS) && owned(a, file, `${WEB}.${a.name}`),
|
||||
);
|
||||
return found.length === 1 ? found[0]! : null;
|
||||
}
|
||||
|
||||
function paths(a: Annotation | null) {
|
||||
if (!a) return strings(undefined);
|
||||
const value = strings(a.args.get("value")),
|
||||
path = strings(a.args.get("path"));
|
||||
if (!value || !path) return null;
|
||||
if (a.args.has("value") && a.args.has("path") && JSON.stringify(value.values) !== JSON.stringify(path.values))
|
||||
return null;
|
||||
return a.args.has("path") ? path : value;
|
||||
}
|
||||
|
||||
function methods(a: Annotation | null, file: SourceFile): string[] | null {
|
||||
if (!a) return ["*"];
|
||||
if (SHORTCUTS[a.name]) return [SHORTCUTS[a.name]!];
|
||||
const expr = a.args.get("method");
|
||||
if (!expr) return ["*"];
|
||||
const written = expr
|
||||
.map((t) => t.text)
|
||||
.join("")
|
||||
.replace(/^(?:\{|\[)|(?:\}|\])$/g, "");
|
||||
if (!written) return ["*"];
|
||||
const names = written
|
||||
.split(",")
|
||||
.filter(Boolean)
|
||||
.map((name) => {
|
||||
const verb = name.split(".").at(-1)!;
|
||||
if (!VERBS.has(verb)) return null;
|
||||
if (name === `${WEB}.RequestMethod.${verb}`) return verb;
|
||||
if (
|
||||
name === `RequestMethod.${verb}` &&
|
||||
(file.imports.includes(`${WEB}.RequestMethod`) || file.imports.includes(`${WEB}.*`))
|
||||
)
|
||||
return verb;
|
||||
return name === verb &&
|
||||
(file.imports.includes(`${WEB}.RequestMethod.${verb}`) || file.imports.includes(`${WEB}.RequestMethod.*`))
|
||||
? verb
|
||||
: null;
|
||||
});
|
||||
return names.every((n): n is string => n !== null) ? names : null;
|
||||
}
|
||||
|
||||
function combine(base: string[], own: string[]): string[] {
|
||||
return base.flatMap((b) => own.map((p) => joinPaths(b, p))).slice(0, 256);
|
||||
}
|
||||
|
||||
export function feignMethods(text: string): FeignMethod[] {
|
||||
if (text.length > MAX_NAVIGATION_SOURCE || !text.includes("FeignClient")) return [];
|
||||
const file = parseSource(text);
|
||||
const result: FeignMethod[] = [];
|
||||
for (const cls of allClasses(file)) {
|
||||
const feign = cls.annotations.find((a) => owned(a, file, FEIGN));
|
||||
if (!feign || cls.kind !== "interface") continue;
|
||||
const prefix = single(feign, "path");
|
||||
if (prefix === null) continue;
|
||||
for (const method of cls.methods) {
|
||||
if (method.hasBody) continue;
|
||||
const annotation = mapping(method.annotations, file);
|
||||
if (!annotation) continue;
|
||||
const urls = paths(annotation),
|
||||
verbs = methods(annotation, file);
|
||||
if (!urls || !verbs) continue;
|
||||
result.push({
|
||||
name: `${cls.name}.${method.name}`,
|
||||
from: method.start,
|
||||
to: method.end,
|
||||
nameFrom: method.nameStart,
|
||||
paths: combine([prefix], urls.values),
|
||||
methods: verbs.map((v) => (v === "*" ? "GET" : v)),
|
||||
links: urls.links,
|
||||
service: service(feign),
|
||||
});
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function controllerMethods(text: string, file?: SourceFile): ControllerMethod[] {
|
||||
if (text.length > MAX_NAVIGATION_SOURCE || !text.includes("Controller")) return [];
|
||||
file ??= parseSource(text);
|
||||
const result: ControllerMethod[] = [];
|
||||
for (const cls of allClasses(file)) {
|
||||
if (
|
||||
!cls.annotations.some(
|
||||
(a) =>
|
||||
["Controller", "RestController"].includes(a.name) &&
|
||||
owned(
|
||||
a,
|
||||
file,
|
||||
a.name === "Controller" ? "org.springframework.stereotype.Controller" : `${WEB}.RestController`,
|
||||
),
|
||||
)
|
||||
)
|
||||
continue;
|
||||
const classMapping = mapping(cls.annotations, file);
|
||||
if (!classMapping && cls.annotations.some((a) => a.name === "RequestMapping")) continue;
|
||||
const base = paths(classMapping),
|
||||
classMethods = methods(classMapping, file);
|
||||
if (!base || !classMethods) continue;
|
||||
for (const method of cls.methods) {
|
||||
const annotation = mapping(method.annotations, file);
|
||||
if (!annotation) continue;
|
||||
const own = paths(annotation),
|
||||
verbs = methods(annotation, file);
|
||||
if (!own || !verbs) continue;
|
||||
result.push({
|
||||
name: `${cls.name}.${method.name}`,
|
||||
from: method.nameStart,
|
||||
to: method.nameStart + method.name.length,
|
||||
paths: combine(base.values, own.values),
|
||||
methods: verbs.includes("*")
|
||||
? classMethods
|
||||
: classMethods.includes("*")
|
||||
? verbs
|
||||
: [...new Set([...classMethods, ...verbs])],
|
||||
});
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Literal segments or whole `{variable}` segments; Ant/regex paths remain unresolved. */
|
||||
export function sameHttpPath(a: string, b: string): boolean {
|
||||
const segments = (s: string) => s.split("/").filter(Boolean);
|
||||
const x = segments(a),
|
||||
y = segments(b);
|
||||
const variable = (s: string) => /^\{[\w.-]+\}$/.test(s);
|
||||
const supported = (s: string) => variable(s) || !/[{}*$?]/.test(s);
|
||||
return (
|
||||
x.length === y.length &&
|
||||
[...x, ...y].every(supported) &&
|
||||
x.every((s, i) => s === y[i] || variable(s) || variable(y[i]!))
|
||||
);
|
||||
}
|
||||
|
||||
export function callsEndpoint(client: HttpShape, server: HttpShape): boolean {
|
||||
return (
|
||||
client.methods.some(
|
||||
(m) =>
|
||||
server.methods.includes("*") || server.methods.includes(m) || (m === "HEAD" && server.methods.includes("GET")),
|
||||
) && client.paths.some((p) => server.paths.some((s) => sameHttpPath(p, s)))
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { _emitEditorEvent } from "@/editor/api";
|
||||
import { commands, emitLocalIdeEvent, type ProjectInfo } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { feignMethods } from "./feign";
|
||||
import { feignTargets, registerFeignNavigation } from "./feignNavigation";
|
||||
|
||||
const root = "/p";
|
||||
const clientPath = "/p/client/src/main/java/Client.java";
|
||||
const client = `import org.springframework.cloud.openfeign.FeignClient;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
@FeignClient(name="users") interface Client { @GetMapping("/users/{id}") String find(); }`;
|
||||
const server = `import org.springframework.web.bind.annotation.*;
|
||||
@RestController class Users { @GetMapping("/users/{userId}") String find() { return ""; } }`;
|
||||
const users = "/p/users/src/main/java/Users.java";
|
||||
const admin = "/p/admin/src/main/java/Users.java";
|
||||
let files: Map<string, string>;
|
||||
let dispose: () => void;
|
||||
|
||||
function project(path = root): ProjectInfo {
|
||||
return { root: path, name: "fixture", settings: {}, trusted: true, isGit: false };
|
||||
}
|
||||
const resolve = (text = client) => feignTargets(clientPath, feignMethods(text)[0]!);
|
||||
|
||||
beforeEach(() => {
|
||||
files = new Map([
|
||||
[users, server],
|
||||
[admin, server],
|
||||
["/p/users/src/main/resources/application.properties", "spring.application.name=users\n"],
|
||||
["/p/admin/src/main/resources/application.yaml", "spring.application.name: admin\n"],
|
||||
]);
|
||||
useProject.setState({ project: project() });
|
||||
vi.spyOn(commands, "springRouteSources").mockImplementation(async () => ({
|
||||
status: "ok",
|
||||
data: [...files].filter(([p]) => p.endsWith(".java") || p.endsWith(".kt")).map(([path, text]) => ({ path, text })),
|
||||
}));
|
||||
vi.spyOn(commands, "fsReadText").mockImplementation(async (path) =>
|
||||
files.has(path)
|
||||
? { status: "ok", data: files.get(path)! }
|
||||
: { status: "error", error: { kind: "notFound", message: "Fixture file missing", detail: null } },
|
||||
);
|
||||
vi.spyOn(commands, "fsReadDir").mockImplementation(async (path) => ({
|
||||
status: "ok",
|
||||
data: [
|
||||
...new Set(
|
||||
[...files.keys()].filter((p) => p.startsWith(`${path}/`)).map((p) => p.slice(path.length + 1).split("/")[0]!),
|
||||
),
|
||||
].map((name) => ({
|
||||
path: `${path}/${name}`,
|
||||
name,
|
||||
kind: files.has(`${path}/${name}`) ? "file" : "dir",
|
||||
size: files.get(`${path}/${name}`)?.length ?? 0,
|
||||
mtimeMs: 0,
|
||||
ignored: false,
|
||||
excluded: false,
|
||||
hidden: false,
|
||||
})),
|
||||
}));
|
||||
dispose = registerFeignNavigation();
|
||||
});
|
||||
afterEach(() => {
|
||||
dispose();
|
||||
vi.restoreAllMocks();
|
||||
useProject.setState({ project: null });
|
||||
});
|
||||
|
||||
describe("core service-aware Feign navigation", () => {
|
||||
it("selects the correct service despite identical paths, and caches the project/configuration inventory", async () => {
|
||||
expect((await resolve()).map((t) => t.path)).toEqual([users]);
|
||||
expect((await resolve()).map((t) => t.path)).toEqual([users]);
|
||||
expect(commands.springRouteSources).toHaveBeenCalledTimes(1);
|
||||
expect(commands.fsReadDir).toHaveBeenCalledTimes(4);
|
||||
expect((await resolve())[0]?.range).toEqual({
|
||||
start: { line: 1, col: server.split("\n")[1]!.indexOf("find()") },
|
||||
end: { line: 1, col: server.split("\n")[1]!.indexOf("find()") + 4 },
|
||||
});
|
||||
});
|
||||
|
||||
it("returns every candidate for unknown identities and explicit URLs", async () => {
|
||||
expect((await resolve(client.replace('name="users"', 'name="${service}"'))).map((t) => t.path)).toEqual([
|
||||
admin,
|
||||
users,
|
||||
]);
|
||||
expect(
|
||||
(await resolve(client.replace('name="users"', 'name="users",url="https://api.example"'))).map((t) => t.path),
|
||||
).toEqual([admin, users]);
|
||||
files.delete("/p/admin/src/main/resources/application.yaml");
|
||||
expect((await resolve()).map((t) => t.path)).toEqual([admin, users]);
|
||||
});
|
||||
|
||||
it("refreshes identities and targets after configuration and source filesystem events", async () => {
|
||||
expect((await resolve()).map((t) => t.path)).toEqual([users]);
|
||||
const config = "/p/admin/src/main/resources/application.yaml";
|
||||
files.set(config, "spring.application.name: users\n");
|
||||
emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [config], removed: [] });
|
||||
expect((await resolve()).map((t) => t.path)).toEqual([admin, users]);
|
||||
files.set(users, server.replace("/users/{userId}", "/elsewhere"));
|
||||
emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [users], removed: [] });
|
||||
expect((await resolve()).map((t) => t.path)).toEqual([admin]);
|
||||
files.delete(admin);
|
||||
expect(await resolve()).toEqual([]); // Current source revalidation rejects the cached target.
|
||||
});
|
||||
|
||||
it("overlays recently edited unsaved controllers absent from the disk index", async () => {
|
||||
await resolve();
|
||||
const path = "/p/users/src/main/kotlin/Added.kt";
|
||||
const text = `import org.springframework.web.bind.annotation.*\n@RestController class Added { @GetMapping("/users/{id}") fun added(): String = "" }`;
|
||||
files.set(path, text);
|
||||
vi.mocked(commands.springRouteSources).mockResolvedValue({
|
||||
status: "ok",
|
||||
data: [
|
||||
{ path: users, text: server },
|
||||
{ path: admin, text: server },
|
||||
],
|
||||
});
|
||||
_emitEditorEvent({ type: "docChanged", doc: 9, path, baseVersion: 1, version: 2, changes: [] });
|
||||
expect((await resolve()).map((t) => t.path)).toEqual([users, path]);
|
||||
});
|
||||
|
||||
it("does not inherit parent module identities or leave the open project", async () => {
|
||||
files.set("/p/src/main/resources/application.properties", "spring.application.name=admin\n");
|
||||
files.set("/p/users/child/src/main/java/Child.java", server);
|
||||
files.set("/outside/src/main/java/Other.java", server);
|
||||
expect((await resolve()).map((t) => t.path)).toEqual(["/p/users/child/src/main/java/Child.java", users]);
|
||||
useProject.setState({ project: { ...project(), trusted: false } });
|
||||
expect(await resolve()).toEqual([]);
|
||||
});
|
||||
|
||||
it("discards a delayed result after a project switch and retries a failed inventory", async () => {
|
||||
let finish!: (result: Awaited<ReturnType<typeof commands.springRouteSources>>) => void;
|
||||
vi.mocked(commands.springRouteSources).mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
finish = resolve;
|
||||
}),
|
||||
);
|
||||
const pending = resolve();
|
||||
useProject.setState({ project: project("/other") });
|
||||
finish({ status: "ok", data: [{ path: users, text: server }] });
|
||||
expect(await pending).toEqual([]);
|
||||
useProject.setState({ project: project() });
|
||||
vi.mocked(commands.springRouteSources).mockRejectedValueOnce(new Error("temporarily unavailable"));
|
||||
await expect(resolve()).rejects.toThrow("temporarily unavailable");
|
||||
expect((await resolve()).map((t) => t.path)).toEqual([users]);
|
||||
});
|
||||
|
||||
it("keeps service configuration reads inside the controller's owning project member", async () => {
|
||||
useProject.setState({
|
||||
project: {
|
||||
...project("/workspace"),
|
||||
workspace: {
|
||||
version: 1,
|
||||
name: "Sources only",
|
||||
projects: ["/p/client/src/main/java", "/p/users/src/main/java", "/p/admin/src/main/java"],
|
||||
},
|
||||
},
|
||||
});
|
||||
expect((await resolve()).map((t) => t.path)).toEqual([admin, users]);
|
||||
expect(commands.fsReadDir).not.toHaveBeenCalled();
|
||||
expect(vi.mocked(commands.fsReadText).mock.calls.every(([path]) => path.endsWith(".java"))).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,300 @@
|
||||
import { RangeSet, StateEffect, StateField, Text, type Extension } from "@codemirror/state";
|
||||
import { EditorView, GutterMarker, ViewPlugin, type ViewUpdate } from "@codemirror/view";
|
||||
import {
|
||||
activeEditor,
|
||||
editorsFor,
|
||||
iconAreaSource,
|
||||
onEditorEvent,
|
||||
useEditorRegistry,
|
||||
type EditorDocContext,
|
||||
} from "@/editor/api";
|
||||
import { docOf } from "@/editor/lsp/lsp";
|
||||
import { locationItems, navigateTo } from "@/editor/lsp/navigation";
|
||||
import { caretAnchor, openPopup } from "@/editor/lsp/popupStore";
|
||||
import { invalidateNavigationProviders, registerNavigationProvider } from "@/editor/navigationProviders";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { call, commands, onIdeEvent, type Location, type ProjectInfo } from "@/platform/ipc";
|
||||
import { isSameOrInside } from "@/platform/paths";
|
||||
import { projectFolder, useProject } from "@/platform/project";
|
||||
import { gutterIconMarkup, type MenuItem } from "@/ui";
|
||||
import { notifications, type MenuGroupContext } from "@/workbench/contributions";
|
||||
import { callsEndpoint, controllerMethods, feignMethods, MAX_NAVIGATION_SOURCE, type FeignMethod } from "./feign";
|
||||
import { clearRouteIndex, controllerIndex, isRouteSource, type ControllerTarget } from "./routeIndex";
|
||||
import { isServiceConfiguration, loadServiceName, sourceModule } from "./serviceIdentity";
|
||||
import styles from "../HttpClient.module.css";
|
||||
|
||||
export const GO_TO_FEIGN_ENDPOINT = "http.goToFeignEndpoint";
|
||||
const serviceNames = new Map<string, Promise<string | null>>();
|
||||
const changedSources = new Set<string>();
|
||||
let epoch = 0;
|
||||
|
||||
function projectKey(project: ProjectInfo | null): string {
|
||||
return JSON.stringify([project?.root, project?.workspace?.projects, project?.trusted]);
|
||||
}
|
||||
function inside(project: ProjectInfo, path: string): boolean {
|
||||
const folder = projectFolder(project, path);
|
||||
return !!folder && isSameOrInside(path, folder.root);
|
||||
}
|
||||
async function read(path: string): Promise<string> {
|
||||
return editorsFor(path)[0]?.view.state.doc.toString() ?? (await call(commands.fsReadText(path)));
|
||||
}
|
||||
function invalidate() {
|
||||
epoch++;
|
||||
serviceNames.clear();
|
||||
clearRouteIndex();
|
||||
invalidateNavigationProviders();
|
||||
}
|
||||
|
||||
function named(module: string): Promise<string | null> {
|
||||
let pending = serviceNames.get(module);
|
||||
if (!pending) {
|
||||
if (serviceNames.size >= 128) serviceNames.clear();
|
||||
pending = loadServiceName(module, { directory: (path) => call(commands.fsReadDir(path)), read });
|
||||
serviceNames.set(module, pending);
|
||||
}
|
||||
return pending;
|
||||
}
|
||||
|
||||
function location(
|
||||
path: string,
|
||||
text: string,
|
||||
method: ReturnType<typeof controllerMethods>[number],
|
||||
): Location & { name: string } {
|
||||
const doc = Text.of(text.split("\n"));
|
||||
const from = doc.lineAt(method.from),
|
||||
to = doc.lineAt(method.to);
|
||||
return {
|
||||
path,
|
||||
name: method.name,
|
||||
range: {
|
||||
start: { line: from.number - 1, col: method.from - from.from },
|
||||
end: { line: to.number - 1, col: method.to - to.from },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** The index supplies candidates; current source/configuration supplies the navigation target. */
|
||||
export async function feignTargets(source: string, client: FeignMethod): Promise<(Location & { name: string })[]> {
|
||||
const project = useProject.getState().project;
|
||||
if (!project?.trusted || !inside(project, source)) return [];
|
||||
const key = projectKey(project),
|
||||
started = epoch;
|
||||
const stale = () => started !== epoch || key !== projectKey(useProject.getState().project);
|
||||
const indexed = await controllerIndex(project.root);
|
||||
if (stale()) return [];
|
||||
const overlays = new Set(
|
||||
[...new Set([...changedSources, ...[...useEditorRegistry.getState().editors].map((e) => e.ctx.path)])]
|
||||
.filter((path) => isRouteSource(path) && inside(project, path))
|
||||
.slice(0, 256),
|
||||
);
|
||||
const currentText = new Map<string, string>();
|
||||
const candidates: ControllerTarget[] = indexed.filter((target) => !overlays.has(target.path));
|
||||
// Visible and recently edited source files include unsaved/new controllers
|
||||
// that the filesystem inventory has not seen yet. Never keep their full text.
|
||||
for (const path of overlays) {
|
||||
const text = await read(path).catch(() => null);
|
||||
if (text === null || text.length > MAX_NAVIGATION_SOURCE || stale()) continue;
|
||||
currentText.set(path, text);
|
||||
candidates.push(...controllerMethods(text).map((method) => ({ ...method, path })));
|
||||
}
|
||||
const paths = [
|
||||
...new Set(candidates.filter((target) => callsEndpoint(client, target)).map((target) => target.path)),
|
||||
].sort();
|
||||
const result: (Location & { name: string })[] = [];
|
||||
for (const path of paths.slice(0, 256)) {
|
||||
if (stale()) return [];
|
||||
const module = sourceModule(path);
|
||||
const folder = projectFolder(project, path);
|
||||
if (client.service && module && folder && isSameOrInside(module, folder.root)) {
|
||||
const name = await named(module);
|
||||
if (name && name !== client.service) continue;
|
||||
}
|
||||
const text = currentText.get(path) ?? (await read(path).catch(() => null));
|
||||
if (text === null || text.length > MAX_NAVIGATION_SOURCE) continue;
|
||||
for (const method of controllerMethods(text).filter((method) => callsEndpoint(client, method))) {
|
||||
const target = location(path, text, method);
|
||||
if (
|
||||
!result.some(
|
||||
(r) =>
|
||||
r.path === path &&
|
||||
r.range.start.line === target.range.start.line &&
|
||||
r.range.start.col === target.range.start.col,
|
||||
)
|
||||
)
|
||||
result.push(target);
|
||||
if (result.length === 256) break;
|
||||
}
|
||||
if (result.length === 256) break;
|
||||
}
|
||||
return stale() ? [] : result;
|
||||
}
|
||||
|
||||
export function registerFeignNavigation(): () => void {
|
||||
invalidate();
|
||||
const unregister = registerNavigationProvider(async (view, offset) => {
|
||||
const doc = docOf(view);
|
||||
if (!doc || doc.virtual || !["java", "kotlin"].includes(doc.language)) return null;
|
||||
const client = feignMethods(view.state.doc.toString()).find((c) =>
|
||||
c.links.some((l) => l.from <= offset && offset < l.to),
|
||||
);
|
||||
const link = client?.links.find((l) => l.from <= offset && offset < l.to);
|
||||
if (!client || !link) return null;
|
||||
return { ...link, targets: await feignTargets(doc.path, client) };
|
||||
});
|
||||
const filesystem = onIdeEvent("fsChanged", (event) => {
|
||||
if (
|
||||
[...event.created, ...event.modified, ...event.removed].some((p) => isRouteSource(p) || isServiceConfiguration(p))
|
||||
)
|
||||
invalidate();
|
||||
});
|
||||
const editors = onEditorEvent((event) => {
|
||||
if (
|
||||
!["docChanged", "docSaved", "docClosed"].includes(event.type) ||
|
||||
!event.path ||
|
||||
(!isRouteSource(event.path) && !isServiceConfiguration(event.path))
|
||||
)
|
||||
return;
|
||||
if (event.type === "docChanged" && isRouteSource(event.path)) {
|
||||
if (changedSources.size < 256) changedSources.add(event.path);
|
||||
} else if (event.type === "docClosed" || event.type === "docSaved") changedSources.delete(event.path);
|
||||
invalidate();
|
||||
});
|
||||
const projects = useProject.subscribe((state, previous) => {
|
||||
if (projectKey(state.project) === projectKey(previous.project)) return;
|
||||
changedSources.clear();
|
||||
invalidate();
|
||||
});
|
||||
return () => {
|
||||
unregister();
|
||||
filesystem();
|
||||
editors();
|
||||
projects();
|
||||
changedSources.clear();
|
||||
invalidate();
|
||||
};
|
||||
}
|
||||
|
||||
export async function goToFeignEndpoint(arg?: unknown): Promise<void> {
|
||||
const requested = arg as { path?: unknown; offset?: unknown } | undefined;
|
||||
const editor = typeof requested?.path === "string" ? editorsFor(requested.path)[0] : activeEditor();
|
||||
if (!editor || editor.ctx.virtual || !["java", "kotlin"].includes(editor.ctx.language)) return;
|
||||
const view = editor.view,
|
||||
before = view.state.doc,
|
||||
started = epoch;
|
||||
const offset = typeof requested?.offset === "number" ? requested.offset : view.state.selection.main.head;
|
||||
const client = feignMethods(before.toString()).find((c) => c.from <= offset && offset <= c.to);
|
||||
if (!client) return;
|
||||
const stale = () =>
|
||||
view.state.doc !== before || started !== epoch || !editorsFor(editor.ctx.path).some((e) => e.view === view);
|
||||
try {
|
||||
const targets = await feignTargets(editor.ctx.path, client);
|
||||
if (stale()) return;
|
||||
if (!targets.length) {
|
||||
notifications().notify({ level: "info", title: tx("No matching Feign endpoint found"), key: "feign-navigation" });
|
||||
} else if (targets.length === 1) await navigateTo(targets[0]!);
|
||||
else {
|
||||
const items = await locationItems(targets);
|
||||
if (stale()) return;
|
||||
openPopup({
|
||||
kind: "list",
|
||||
title: tx("Choose Feign Endpoint"),
|
||||
anchor: caretAnchor(view, Math.min(offset, before.length)),
|
||||
items: items.map((item) => ({ ...item, run: () => (stale() ? undefined : item.run()) })),
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: tx("Cannot navigate to Feign endpoint"),
|
||||
body: String(error),
|
||||
key: "feign-navigation",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function feignMenuItems(context: MenuGroupContext): MenuItem[] {
|
||||
const editor = activeEditor();
|
||||
if (!editor || editor.ctx.path !== context.paths[0]) return [];
|
||||
const offset = editor.view.state.selection.main.head;
|
||||
return feignMethods(editor.view.state.doc.toString()).some((c) => c.from <= offset && offset <= c.to)
|
||||
? [{ kind: "action", action: GO_TO_FEIGN_ENDPOINT, icon: "arrow-right" }]
|
||||
: [];
|
||||
}
|
||||
|
||||
type Mark = { pos: number; offset: number };
|
||||
const setMarks = StateEffect.define<Mark[]>();
|
||||
const marks = StateField.define<Mark[]>({
|
||||
create: () => [],
|
||||
update(value, transaction) {
|
||||
for (const effect of transaction.effects) if (effect.is(setMarks)) return effect.value;
|
||||
return transaction.docChanged ? [] : value;
|
||||
},
|
||||
});
|
||||
class FeignMarker extends GutterMarker {
|
||||
constructor(
|
||||
readonly path: string,
|
||||
readonly offset: number,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
override eq(other: GutterMarker) {
|
||||
return other instanceof FeignMarker && other.path === this.path && other.offset === this.offset;
|
||||
}
|
||||
override toDOM(): Node {
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.className = styles.runMarker ?? "";
|
||||
button.dataset.iconSource = "feign";
|
||||
button.title = tx("Go to Feign Endpoint");
|
||||
button.setAttribute("aria-label", button.title);
|
||||
button.innerHTML = gutterIconMarkup("arrow-right") ?? "";
|
||||
button.onclick = (event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
void executeAction(GO_TO_FEIGN_ENDPOINT, { path: this.path, offset: this.offset });
|
||||
};
|
||||
return button;
|
||||
}
|
||||
}
|
||||
|
||||
export function feignEditorExtension(context: EditorDocContext): Extension {
|
||||
if (context.virtual || !["java", "kotlin"].includes(context.language)) return [];
|
||||
return [
|
||||
marks,
|
||||
ViewPlugin.fromClass(
|
||||
class {
|
||||
timer: ReturnType<typeof setTimeout> | undefined;
|
||||
constructor(readonly view: EditorView) {
|
||||
this.schedule(0);
|
||||
}
|
||||
update(update: ViewUpdate) {
|
||||
if (update.docChanged) this.schedule(400);
|
||||
}
|
||||
schedule(delay: number) {
|
||||
clearTimeout(this.timer);
|
||||
this.timer = setTimeout(() => {
|
||||
const found = feignMethods(this.view.state.doc.toString()).map((c) => ({
|
||||
pos: this.view.state.doc.lineAt(c.nameFrom).from,
|
||||
offset: c.nameFrom,
|
||||
}));
|
||||
this.view.dispatch({
|
||||
effects: setMarks.of(found.filter((m, i) => found.findIndex((v) => v.pos === m.pos) === i)),
|
||||
});
|
||||
}, delay);
|
||||
}
|
||||
destroy() {
|
||||
clearTimeout(this.timer);
|
||||
}
|
||||
},
|
||||
),
|
||||
iconAreaSource.of({
|
||||
order: 31,
|
||||
markers: (view) =>
|
||||
RangeSet.of(
|
||||
view.state.field(marks).map((m) => new FeignMarker(context.path, m.offset).range(m.pos)),
|
||||
true,
|
||||
),
|
||||
}),
|
||||
];
|
||||
}
|
||||
@@ -3,7 +3,17 @@ import { call, commands, onIdeEvent, type ProjectInfo } from "@/platform/ipc";
|
||||
import { ipcPath, isSameOrInside } from "@/platform/paths";
|
||||
import { projectFolder, relativePath, useProject } from "@/platform/project";
|
||||
import { registerEndpointProvider, type EndpointEntry } from "@/workbench/contributions";
|
||||
import { springControllers } from "./endpoints";
|
||||
import { controllersOf } from "./endpoints";
|
||||
import { controllerMethods, type ControllerMethod } from "./feign";
|
||||
import { parseSource } from "./source";
|
||||
|
||||
export interface ControllerTarget extends ControllerMethod {
|
||||
path: string;
|
||||
}
|
||||
interface RouteIndex {
|
||||
routes: EndpointEntry[];
|
||||
controllers: ControllerTarget[];
|
||||
}
|
||||
|
||||
export function registerSpringEndpointProvider(): () => void {
|
||||
clearRouteIndex();
|
||||
@@ -18,7 +28,7 @@ export function registerSpringEndpointProvider(): () => void {
|
||||
};
|
||||
}
|
||||
|
||||
let cached: { key: string; promise: Promise<EndpointEntry[]> } | null = null;
|
||||
let cached: { key: string; promise: Promise<RouteIndex> } | null = null;
|
||||
|
||||
/** Whether `path` is a source a mapping can live in (a Java or Kotlin file). */
|
||||
export function isRouteSource(path: string): boolean {
|
||||
@@ -32,26 +42,41 @@ export function clearRouteIndex() {
|
||||
|
||||
/** The project's routes, scanned once per project and kept in memory. */
|
||||
export function routeIndex(root: string | null): Promise<EndpointEntry[]> {
|
||||
if (!root) return Promise.resolve([]);
|
||||
return index(root).then((result) => result.routes);
|
||||
}
|
||||
|
||||
export function controllerIndex(root: string | null): Promise<ControllerTarget[]> {
|
||||
return index(root).then((result) => result.controllers);
|
||||
}
|
||||
|
||||
function index(root: string | null): Promise<RouteIndex> {
|
||||
if (!root) return Promise.resolve({ routes: [], controllers: [] });
|
||||
const current = useProject.getState().project;
|
||||
const project = current?.root === root ? current : null;
|
||||
const key = JSON.stringify([root, project?.workspace?.projects ?? null]);
|
||||
if (cached?.key === key) return cached.promise;
|
||||
const promise = scan(root, project);
|
||||
const promise = scan(root, project).catch((error: unknown) => {
|
||||
if (cached?.promise === promise) cached = null;
|
||||
throw error;
|
||||
});
|
||||
cached = { key, promise };
|
||||
return promise;
|
||||
}
|
||||
|
||||
async function scan(root: string, project: ProjectInfo | null): Promise<EndpointEntry[]> {
|
||||
async function scan(root: string, project: ProjectInfo | null): Promise<RouteIndex> {
|
||||
const sources = await call(commands.springRouteSources());
|
||||
const routes: EndpointEntry[] = [];
|
||||
const controllers: ControllerTarget[] = [];
|
||||
for (const source of sources) {
|
||||
const path = ipcPath(source.path);
|
||||
const folder = project ? projectFolder(project, path)?.root : root;
|
||||
if (!folder) continue;
|
||||
const base = ipcPath(folder).replace(/\/$/, "");
|
||||
if (!isSameOrInside(path, base)) continue;
|
||||
for (const controller of springControllers(source.text)) {
|
||||
if (!source.text.includes("Controller")) continue;
|
||||
const file = parseSource(source.text);
|
||||
controllers.push(...controllerMethods(source.text, file).map((method) => ({ ...method, path })));
|
||||
for (const controller of controllersOf(file)) {
|
||||
for (const endpoint of controller.endpoints) {
|
||||
const at = lineCol(source.text, endpoint.offset);
|
||||
// A mapping without a path answers nothing to look up by URL; the method
|
||||
@@ -71,7 +96,7 @@ async function scan(root: string, project: ProjectInfo | null): Promise<Endpoint
|
||||
}
|
||||
}
|
||||
}
|
||||
return routes;
|
||||
return { routes, controllers };
|
||||
}
|
||||
|
||||
function lineCol(text: string, offset: number): { line: number; col: number } {
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { FileEntry } from "@/platform/ipc";
|
||||
import { loadServiceName, sourceModule, type ServiceReader } from "./serviceIdentity";
|
||||
|
||||
function reader(configs: Record<string, string>, override?: Partial<FileEntry>): ServiceReader {
|
||||
const folder = (path: string): FileEntry => ({
|
||||
path,
|
||||
name: path.split("/").at(-1)!,
|
||||
kind: "dir",
|
||||
size: 0,
|
||||
mtimeMs: 0,
|
||||
ignored: false,
|
||||
excluded: false,
|
||||
hidden: false,
|
||||
});
|
||||
return {
|
||||
directory: async (path) =>
|
||||
path.endsWith("/main")
|
||||
? [folder(`${path}/resources`)]
|
||||
: [
|
||||
...(path.endsWith("/resources") && Object.keys(configs).some((key) => key.startsWith("config/"))
|
||||
? [folder(`${path}/config`)]
|
||||
: []),
|
||||
...Object.entries(configs)
|
||||
.filter(([name]) => path.endsWith("/config") === name.startsWith("config/"))
|
||||
.map(([name, text]): FileEntry => {
|
||||
name = name.replace(/^config\//, "");
|
||||
return {
|
||||
path: `${path}/${name}`,
|
||||
name,
|
||||
kind: "file",
|
||||
size: text.length,
|
||||
mtimeMs: 0,
|
||||
ignored: false,
|
||||
excluded: false,
|
||||
hidden: false,
|
||||
...override,
|
||||
};
|
||||
}),
|
||||
],
|
||||
read: async (path) => configs[path.split("/src/main/resources/")[1]!]!,
|
||||
};
|
||||
}
|
||||
|
||||
describe("source-declared Spring service identity", () => {
|
||||
it("reads properties/YAML in the exact module, including resources/config", async () => {
|
||||
for (const configs of [
|
||||
{ "application.properties": "spring.application.name=users\n" },
|
||||
{ "application.yml": "spring:\n application:\n name: 'users' # local\n" },
|
||||
{ "config/application.yaml": "spring.application.name: users\n" },
|
||||
{
|
||||
"application.properties": "spring.application.name=users\n",
|
||||
"application-dev.properties": "spring.application.name=users\n",
|
||||
},
|
||||
] as Record<string, string>[])
|
||||
expect(await loadServiceName("/p/users", reader(configs))).toBe("users");
|
||||
expect(sourceModule("D:\\p\\users\\src\\main\\kotlin\\Users.kt")).toBe("D:/p/users");
|
||||
expect(sourceModule("/p/users/child/src/main/java/C.java")).toBe("/p/users/child");
|
||||
expect(sourceModule("/p/users/src/test/java/C.java")).toBeNull();
|
||||
expect(sourceModule("/p/users/src/other/C.java")).toBeNull();
|
||||
});
|
||||
|
||||
it("withholds identity for unknown, conflicting, profile-only and unsupported configuration", async () => {
|
||||
const samples: Record<string, string>[] = [
|
||||
{},
|
||||
{ "application.yaml": "description: |\n spring.application.name: fake\n" },
|
||||
{ "application-dev.properties": "spring.application.name=users\n" },
|
||||
{ "application.properties": "spring.application.name=${SERVICE:users}\n" },
|
||||
{ "application.properties": "spring.application.name=users\nspring.application.name=admin\n" },
|
||||
{
|
||||
"application.properties": "spring.application.name=users\n",
|
||||
"application-dev.yaml": "spring.application.name: admin\n",
|
||||
},
|
||||
{ "application.yaml": "spring.application.name: users\n---\nspring.application.name: admin\n" },
|
||||
{ "application.yaml": "spring.application.name: users\nspring.config.activate.on-profile: dev\n" },
|
||||
{ "application.properties": "spring.application.name=users\nspring.config.import=optional:configserver:\n" },
|
||||
{
|
||||
"application.properties": "spring.application.name=users\n",
|
||||
"application-dev.yaml": "spring: {application: {name: admin}}\n",
|
||||
},
|
||||
{
|
||||
"application.properties": "spring.application.name=users\n",
|
||||
"application-dev.yaml": "{spring.application.name: admin}\n",
|
||||
},
|
||||
{
|
||||
"application.properties": "spring.application.name=users\n",
|
||||
"application-dev.yaml": "spring.config: {import: 'optional:configserver:'}\n",
|
||||
},
|
||||
{
|
||||
"application.properties": "spring.application.name=users\n",
|
||||
"application-dev.yaml": "!custom {spring.application.name: admin}\n",
|
||||
},
|
||||
{
|
||||
"application.properties": "spring.application.name=users\n",
|
||||
"application-dev.properties": "spring.application.\\u006eame=admin\n",
|
||||
},
|
||||
{
|
||||
"application.properties": "spring.application.name=users\n",
|
||||
"application-dev.yaml": '"spring.application.\\u006eame": admin\n',
|
||||
},
|
||||
{
|
||||
"application.properties": "spring.application.name=users\n",
|
||||
"bootstrap.yaml": "spring.application.name: admin\n",
|
||||
},
|
||||
];
|
||||
for (const configs of samples)
|
||||
expect(await loadServiceName("/p/users", reader(configs)), JSON.stringify(configs)).toBeNull();
|
||||
});
|
||||
|
||||
it("does not follow symlinks, read excluded configs, or trust capped/unreadable inventories", async () => {
|
||||
const configs = { "application.properties": "spring.application.name=users\n" };
|
||||
for (const override of [
|
||||
{ kind: "symlink" },
|
||||
{ excluded: true },
|
||||
{ ignored: true },
|
||||
{ size: 200_000 },
|
||||
{ path: "/outside/application.properties" },
|
||||
] as Partial<FileEntry>[]) {
|
||||
const r = reader(configs, override);
|
||||
r.read = async () => {
|
||||
throw new Error("Must not be read");
|
||||
};
|
||||
expect(await loadServiceName("/p/users", r)).toBeNull();
|
||||
}
|
||||
const denied = reader(configs);
|
||||
denied.directory = async () => {
|
||||
throw { kind: "permissionDenied" };
|
||||
};
|
||||
expect(await loadServiceName("/p/users", denied)).toBeNull();
|
||||
const many = Object.fromEntries(
|
||||
Array.from({ length: 33 }, (_, i) => [`application-${i}.properties`, "spring.application.name=users\n"]),
|
||||
);
|
||||
expect(await loadServiceName("/p/users", reader({ ...configs, ...many }))).toBeNull();
|
||||
for (const entry of [{ kind: "symlink" }, { excluded: true }, { ignored: true }]) {
|
||||
const r = reader(configs);
|
||||
const list = r.directory;
|
||||
r.directory = vi.fn(async (path) => (await list(path)).map((file) => ({ ...file, ...entry }) as FileEntry));
|
||||
r.read = vi.fn();
|
||||
expect(await loadServiceName("/p/users", r)).toBeNull();
|
||||
expect(r.directory).toHaveBeenCalledTimes(1);
|
||||
expect(r.read).not.toHaveBeenCalled();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
/** Bounded local configuration evidence, never an effective runtime identity. */
|
||||
import type { FileEntry } from "@/platform/ipc";
|
||||
import { ipcPath } from "@/platform/paths";
|
||||
|
||||
export interface ServiceReader {
|
||||
directory(path: string): Promise<FileEntry[]>;
|
||||
read(path: string): Promise<string>;
|
||||
}
|
||||
|
||||
export function sourceModule(path: string): string | null {
|
||||
return /^(.*)\/src\/main\/(?:java|kotlin)\//.exec(ipcPath(path))?.[1] ?? null;
|
||||
}
|
||||
|
||||
export function isServiceConfiguration(path: string): boolean {
|
||||
return /\/(?:application|bootstrap)(?:-[^/]+)?\.(?:properties|ya?ml)$/.test(ipcPath(path));
|
||||
}
|
||||
|
||||
interface Evidence {
|
||||
names: string[];
|
||||
base: boolean;
|
||||
unresolved: boolean;
|
||||
}
|
||||
|
||||
/** Keep duplicate keys and reject YAML features whose property sources we cannot establish. */
|
||||
function evidence(name: string, text: string): Evidence {
|
||||
const entries: [string, string][] = [];
|
||||
const stack: { indent: number; key: string }[] = [];
|
||||
let unresolved = false;
|
||||
let blockIndent: number | null = null;
|
||||
const properties = name.endsWith(".properties");
|
||||
for (const raw of text.split(/\r?\n/)) {
|
||||
const line = raw.trim();
|
||||
const indent = raw.length - raw.trimStart().length;
|
||||
if (blockIndent !== null) {
|
||||
if (!line || indent > blockIndent) continue;
|
||||
blockIndent = null;
|
||||
}
|
||||
if (/^(?:---|\.\.\.|#---|!---)(?:\s|$)/.test(line)) unresolved = true;
|
||||
if (!line || line.startsWith("#") || (properties && line.startsWith("!"))) continue;
|
||||
if (properties) {
|
||||
if (line.endsWith("\\")) unresolved = true;
|
||||
const match = /^((?:\\.|[^=:\s])+)\s*[=:\s]\s*(.*)$/.exec(line);
|
||||
if (match) {
|
||||
unresolved ||= match[1]!.includes("\\");
|
||||
entries.push([match[1]!, match[2]!.trim()]);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (/^\s*<<\s*:/.test(raw) || /^\s*\t/.test(raw) || /^[{[&*!]/.test(line)) unresolved = true;
|
||||
const match = /^( *)("[^"]*"|'[^']*'|[^:]+?)\s*:(?:\s+(.*))?$/.exec(raw);
|
||||
if (!match) continue;
|
||||
while (stack.length && stack.at(-1)!.indent >= indent) stack.pop();
|
||||
const key = match[2]!.replace(/^["']|["']$/g, "");
|
||||
unresolved ||= key.includes("\\");
|
||||
const path = [...stack.map((s) => s.key), key].join(".");
|
||||
const value = (match[3] ?? "").replace(/\s+#.*$/, "").trim();
|
||||
entries.push([path, value.replace(/^"([^"\\]*)"$|^'([^']*)'$/, "$1$2")]);
|
||||
if (!value) stack.push({ indent, key });
|
||||
if (/^[|>][+-]?\d?$/.test(value)) blockIndent = indent;
|
||||
if (["spring", "spring.application", "spring.config"].includes(path) && value) unresolved = true;
|
||||
}
|
||||
const names = entries.filter(([key]) => key === "spring.application.name").map(([, value]) => value);
|
||||
unresolved ||= names.length > 1 || names.some((value) => !/^[\w.-]{1,255}$/.test(value));
|
||||
unresolved ||= entries.some(([key]) => /^spring\.config\.(?:import|location|additional-location|name)$/.test(key));
|
||||
const conditional = entries.some(([key]) => key === "spring.profiles" || key.startsWith("spring.config.activate."));
|
||||
return { names, unresolved, base: /^application\.(?:properties|ya?ml)$/.test(name) && !conditional };
|
||||
}
|
||||
|
||||
/** Only this module's resources, including its config/ directory; never parent or test resources. */
|
||||
export async function loadServiceName(module: string, reader: ServiceReader): Promise<string | null> {
|
||||
const sources: Evidence[] = [];
|
||||
let count = 0,
|
||||
bytes = 0;
|
||||
const main = `${module}/src/main`;
|
||||
let children: FileEntry[];
|
||||
try {
|
||||
children = await reader.directory(main);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
for (const [parent, name] of [
|
||||
[main, "resources"],
|
||||
[`${main}/resources`, "config"],
|
||||
]) {
|
||||
const directory = `${parent}/${name}`;
|
||||
const entry = children.find((file) => file.name === name);
|
||||
if (!entry) break;
|
||||
if (entry.kind !== "dir" || entry.ignored || entry.excluded || ipcPath(entry.path) !== directory) return null;
|
||||
let entries: FileEntry[];
|
||||
try {
|
||||
entries = await reader.directory(directory);
|
||||
} catch (error) {
|
||||
if ((error as { kind?: string }).kind === "notFound") continue;
|
||||
return null;
|
||||
}
|
||||
for (const file of entries) {
|
||||
if (!isServiceConfiguration(`/${file.name}`)) continue;
|
||||
// Do not follow configuration symlinks or read excluded files as evidence.
|
||||
if (
|
||||
file.kind !== "file" ||
|
||||
file.ignored ||
|
||||
file.excluded ||
|
||||
file.name.includes("/") ||
|
||||
file.name.includes("\\") ||
|
||||
ipcPath(file.path) !== `${directory}/${file.name}` ||
|
||||
file.size > 128 * 1024 ||
|
||||
++count > 32
|
||||
)
|
||||
return null;
|
||||
let text: string;
|
||||
try {
|
||||
text = await reader.read(file.path);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
bytes += text.length;
|
||||
if (text.length > 128 * 1024 || bytes > 1024 * 1024) return null;
|
||||
sources.push(evidence(file.name, text));
|
||||
}
|
||||
children = entries;
|
||||
}
|
||||
if (sources.some((s) => s.unresolved) || !sources.some((s) => s.base && s.names.length === 1)) return null;
|
||||
const names = new Set(sources.flatMap((s) => s.names));
|
||||
return names.size === 1 ? [...names][0]! : null;
|
||||
}
|
||||
@@ -22,6 +22,8 @@ export type Expr = Tok[];
|
||||
export interface Annotation {
|
||||
/** Simple name (`GetMapping` of `@org.springframework…GetMapping`). */
|
||||
name: string;
|
||||
qualifiedName?: string;
|
||||
duplicateArgs?: boolean;
|
||||
/** Arguments by name; a positional argument is `value`. */
|
||||
args: Map<string, Expr>;
|
||||
}
|
||||
@@ -42,6 +44,7 @@ export interface Field {
|
||||
|
||||
export interface Method {
|
||||
name: string;
|
||||
hasBody: boolean;
|
||||
annotations: Annotation[];
|
||||
params: Param[];
|
||||
/** Offset of the name. */
|
||||
@@ -53,6 +56,7 @@ export interface Method {
|
||||
|
||||
export interface ClassDecl {
|
||||
name: string;
|
||||
kind: string;
|
||||
annotations: Annotation[];
|
||||
nameStart: number;
|
||||
/** Whole declaration, annotations included. */
|
||||
@@ -254,27 +258,33 @@ class Reader {
|
||||
if (!this.is(i, "@") || this.toks[i + 1]?.kind !== "id" || this.is(i + 1, "interface")) return null;
|
||||
let j = i + 1;
|
||||
let name = this.toks[j]!.text;
|
||||
let qualifiedName = name;
|
||||
// Kotlin use-site targets: `@field:JsonProperty`.
|
||||
if (this.is(j + 1, ":") && this.toks[j + 2]?.kind === "id") {
|
||||
j += 2;
|
||||
name = this.toks[j]!.text;
|
||||
qualifiedName = name;
|
||||
}
|
||||
while (this.is(j + 1, ".") && this.toks[j + 2]?.kind === "id") {
|
||||
j += 2;
|
||||
name = this.toks[j]!.text;
|
||||
qualifiedName += `.${name}`;
|
||||
}
|
||||
j++;
|
||||
const args = new Map<string, Expr>();
|
||||
let duplicateArgs = false;
|
||||
if (this.is(j, "(") && !this.toks[j]!.nl) {
|
||||
const close = this.match[j]!;
|
||||
const positional: Tok[][] = [];
|
||||
for (const part of this.split(j + 1, close)) {
|
||||
if (!part.length) continue;
|
||||
if (part[0]!.kind === "id" && part[1]?.text === "=" && part[1].kind === "p" && part[2]?.text !== "=")
|
||||
if (part[0]!.kind === "id" && part[1]?.text === "=" && part[1].kind === "p" && part[2]?.text !== "=") {
|
||||
duplicateArgs ||= args.has(part[0]!.text);
|
||||
args.set(part[0]!.text, part.slice(2));
|
||||
else positional.push(part);
|
||||
} else positional.push(part);
|
||||
}
|
||||
// Kotlin `vararg value`: `@GetMapping("/a", "/b")` is an array.
|
||||
if (positional.length) duplicateArgs ||= args.has("value");
|
||||
if (positional.length === 1) args.set("value", positional[0]!);
|
||||
else if (positional.length > 1) {
|
||||
const p = (text: string, at: Tok): Tok => ({ kind: "p", text, start: at.start, end: at.start, nl: false });
|
||||
@@ -287,7 +297,10 @@ class Reader {
|
||||
}
|
||||
j = close + 1;
|
||||
}
|
||||
return [{ name, args }, j];
|
||||
return [
|
||||
{ name, args, ...(qualifiedName !== name ? { qualifiedName } : {}), ...(duplicateArgs ? { duplicateArgs } : {}) },
|
||||
j,
|
||||
];
|
||||
}
|
||||
|
||||
/** Splits `[from, to)` at top-level commas (brackets and generics nest). */
|
||||
@@ -405,6 +418,7 @@ class Reader {
|
||||
const nameTok = companion ? t : this.toks[i + 1]!;
|
||||
const cls: ClassDecl = {
|
||||
name: companion ? "Companion" : nameTok.text,
|
||||
kind: t.text,
|
||||
annotations,
|
||||
nameStart: nameTok.start,
|
||||
start: declStart,
|
||||
@@ -464,8 +478,10 @@ class Reader {
|
||||
) {
|
||||
const params = this.params(i + 1);
|
||||
let j = this.match[i + 1]! + 1;
|
||||
let hasBody = false;
|
||||
for (; j < to; j++) {
|
||||
if (this.is(j, "{")) {
|
||||
hasBody = true;
|
||||
j = this.match[j]! + 1;
|
||||
break;
|
||||
}
|
||||
@@ -474,10 +490,11 @@ class Reader {
|
||||
break;
|
||||
}
|
||||
if (this.startsMember(j)) break;
|
||||
if (this.is(j, "=")) hasBody = true;
|
||||
if (this.toks[j]!.kind === "p" && OPEN[this.toks[j]!.text]) j = this.match[j]!;
|
||||
}
|
||||
const end = this.toks[Math.min(j, this.toks.length) - 1]?.end ?? t.end;
|
||||
into.methods.push({ name: t.text, annotations, params, nameStart: t.start, start: declStart, end });
|
||||
into.methods.push({ name: t.text, hasBody, annotations, params, nameStart: t.start, start: declStart, end });
|
||||
reset();
|
||||
i = j;
|
||||
continue;
|
||||
@@ -560,6 +577,7 @@ export function parseSource(text: string): SourceFile {
|
||||
}
|
||||
const root: ClassDecl = {
|
||||
name: "",
|
||||
kind: "",
|
||||
annotations: [],
|
||||
nameStart: 0,
|
||||
start: 0,
|
||||
|
||||
@@ -581,7 +581,7 @@ function CapabilityList({ plugin, busy }: { plugin: PluginInfo; busy: boolean })
|
||||
c.id.startsWith("process:") ? (
|
||||
<ProgramPermission plugin={plugin} cap={c} disabled={busy || !confirmed} />
|
||||
) : (
|
||||
c.id === "java.agent" && <JavaAgentDetail plugin={plugin} />
|
||||
c.id === "java.agent" && <JavaAgentDetail plugin={plugin} cap={c} disabled={busy || !confirmed} />
|
||||
)
|
||||
}
|
||||
>
|
||||
@@ -601,14 +601,31 @@ function CapabilityList({ plugin, busy }: { plugin: PluginInfo; busy: boolean })
|
||||
}
|
||||
|
||||
/** The agent a `java.agent` grant loads: its jar's file name and arguments, as `-javaagent:` takes them. */
|
||||
function JavaAgentDetail({ plugin }: { plugin: PluginInfo }) {
|
||||
const agent = plugin.contributions.find((c) => c.point === "javaAgents");
|
||||
function JavaAgentDetail({ plugin, cap, disabled }: { plugin: PluginInfo; cap: CapabilityInfo; disabled: boolean }) {
|
||||
const agent = plugin.javaAgent;
|
||||
if (!agent) return null;
|
||||
const approve = async () => {
|
||||
// Revoking and granting again recomputes the jar's hash in the host.
|
||||
if (await setPluginCapability(plugin.id, cap.id, false)) {
|
||||
await setPluginCapability(plugin.id, cap.id, true);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<div className={styles.programPermission}>
|
||||
<span className={clsx(styles.mono, styles.programPath)} aria-label={tx("Java agent")}>
|
||||
{agent.label}
|
||||
{agent.fileName}
|
||||
{agent.args ? `=${agent.args}` : ""}
|
||||
</span>
|
||||
{cap.granted && !agent.approved && (
|
||||
<div className={styles.error} role="alert">
|
||||
<p>
|
||||
<T>The agent jar changed since you approved it. Approve the new jar before the next launch.</T>
|
||||
</p>
|
||||
<Button size="small" variant="primary" disabled={disabled} onClick={() => void approve()}>
|
||||
<T>Approve new jar</T>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -69,6 +69,7 @@ function plugin(partial: Partial<PluginInfo> & Pick<PluginInfo, "id">): PluginIn
|
||||
homepage: null,
|
||||
changeNotes: null,
|
||||
icon: null,
|
||||
javaAgent: null,
|
||||
source: "installed",
|
||||
path: `/plugins/${partial.id}`,
|
||||
enabled: true,
|
||||
@@ -1604,6 +1605,7 @@ describe("marketplace", () => {
|
||||
},
|
||||
],
|
||||
contributions: [{ point: "javaAgents", label: "spring-agent.jar=port=0" }],
|
||||
javaAgent: { fileName: "spring-agent.jar", args: "port=0", approved: true },
|
||||
}),
|
||||
]),
|
||||
);
|
||||
@@ -1613,6 +1615,47 @@ describe("marketplace", () => {
|
||||
expect(within(permissions).getByLabelText("Java agent")).toHaveTextContent("spring-agent.jar=port=0");
|
||||
});
|
||||
|
||||
it("warns when a granted Java agent jar changed and can approve it again", async () => {
|
||||
const user = userEvent.setup();
|
||||
const base = createMemoryPluginsBackend([
|
||||
plugin({
|
||||
id: "spring",
|
||||
name: "Spring",
|
||||
hasCode: false,
|
||||
status: "static",
|
||||
javaAgent: { fileName: "spring-agent.jar", args: null, approved: false },
|
||||
capabilities: [
|
||||
{
|
||||
id: "java.agent",
|
||||
risk: "high",
|
||||
description: "Run code inside the Java applications you start",
|
||||
optional: true,
|
||||
granted: true,
|
||||
},
|
||||
],
|
||||
contributions: [{ point: "javaAgents", label: "spring-agent.jar" }],
|
||||
}),
|
||||
]);
|
||||
const calls: [string, string, boolean][] = [];
|
||||
setPluginsBackend({
|
||||
...base,
|
||||
setCapability: async (id, capability, granted) => {
|
||||
calls.push([id, capability, granted]);
|
||||
return base.setCapability(id, capability, granted);
|
||||
},
|
||||
});
|
||||
render(<PluginsPage initialTab="installed" />);
|
||||
const permissions = await screen.findByRole("list", { name: "Permissions" });
|
||||
expect(within(permissions).getByRole("alert")).toHaveTextContent("The agent jar changed since you approved it");
|
||||
await user.click(within(permissions).getByRole("button", { name: "Approve new jar" }));
|
||||
await waitFor(() =>
|
||||
expect(calls).toEqual([
|
||||
["spring", "java.agent", false],
|
||||
["spring", "java.agent", true],
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("offers to roll back an update", async () => {
|
||||
const base = createMemoryPluginsBackend([
|
||||
plugin({ id: "p", name: "P", version: "2.0.0", previousVersion: "1.0.0" }),
|
||||
|
||||
@@ -453,6 +453,7 @@ function samplePlugins(): PluginInfo[] {
|
||||
homepage: null,
|
||||
changeNotes: null,
|
||||
icon: null,
|
||||
javaAgent: null,
|
||||
source: "installed" as const,
|
||||
enabled: true,
|
||||
error: null,
|
||||
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
openPluginDiff,
|
||||
type PluginContentEditorData,
|
||||
} from "./contentTab";
|
||||
import { wheelZoomStep } from "@/platform/wheelZoom";
|
||||
|
||||
export function pluginContentEditorTitle(input: EditorInput): string {
|
||||
const s = sessions.get(input.key);
|
||||
@@ -171,9 +172,10 @@ function isActionStroke(stroke: string | null, actionId: string): boolean {
|
||||
|
||||
const wheelZoom = EditorView.domEventHandlers({
|
||||
wheel(e, view) {
|
||||
if (!e.metaKey && !e.ctrlKey) return false;
|
||||
const step = wheelZoomStep(e);
|
||||
if (step === null) return false;
|
||||
e.preventDefault();
|
||||
stepFontZoom(view, e.deltaY < 0 ? 1 : -1);
|
||||
if (step) stepFontZoom(view, step);
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
@@ -26,6 +26,7 @@ import { boundedLog, type PluginLogEditorData } from "./logTab";
|
||||
import { logTabPtyBackend, webPtyBackend } from "./ptyBackend";
|
||||
import { outputKey, usePluginOutput } from "./outputStore";
|
||||
import { ptyBridge } from "./ptyBridge";
|
||||
import { wheelZoomStep } from "@/platform/wheelZoom";
|
||||
|
||||
export const PLUGIN_LOG_EDITOR_KIND = "pluginLog";
|
||||
|
||||
@@ -42,9 +43,10 @@ function isActionStroke(stroke: string | null, actionId: string): boolean {
|
||||
|
||||
const wheelZoom = EditorView.domEventHandlers({
|
||||
wheel(e, view) {
|
||||
if (!e.metaKey && !e.ctrlKey) return false;
|
||||
const step = wheelZoomStep(e);
|
||||
if (step === null) return false;
|
||||
e.preventDefault();
|
||||
stepFontZoom(view, e.deltaY < 0 ? 1 : -1);
|
||||
if (step) stepFontZoom(view, step);
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
@@ -63,6 +63,7 @@ import { compoundChildren } from "./configs";
|
||||
import { containerDebuggable, remoteDebugBlocked } from "./remote";
|
||||
import { debugInContainer } from "./containerDebug";
|
||||
import { isDebugOnly, registerBuiltinTypes } from "./types";
|
||||
import { isZigBuildStep, zigDebugTarget } from "./zigDebug";
|
||||
import { junitType } from "./junitType";
|
||||
import { listenForApplicationDeactivation, showApplicationUpdate, updatableSessions } from "./applicationUpdate";
|
||||
import { npmGutter } from "./npmGutter";
|
||||
@@ -221,6 +222,21 @@ async function debugLaunch(config: RunConfig, chain: readonly string[], show?: b
|
||||
await debugWithAgent(config, show);
|
||||
return;
|
||||
}
|
||||
// `zig build run` (and other steps that run an executable) have no adapter of their own: debug
|
||||
// through the executable config, which builds the binary first and launches it under CodeLLDB.
|
||||
if (isZigBuildStep(config)) {
|
||||
const target = zigDebugTarget(config, useRun.getState().configs);
|
||||
if (target && getAction("debug.startConfig")) {
|
||||
// Run the executable's before-launch build, then keep the clicked step as the session's
|
||||
// origin so the Run widget, tab identity, rerun and stop follow what the user asked to debug.
|
||||
if (!(await prepareLaunch(target, [config.id], show))) return;
|
||||
await executeAction(
|
||||
"debug.startConfig",
|
||||
show === false ? { config: target, origin: config, show: false } : { config: target, origin: config },
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (getAction("debug.startConfig")) {
|
||||
await executeAction("debug.startConfig", show === false ? { config, show: false } : config);
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
import { isZigBuildStep, zigDebugTarget } from "./zigDebug";
|
||||
|
||||
const config = (over: Partial<RunConfig> = {}): RunConfig =>
|
||||
({
|
||||
id: "zig:run",
|
||||
name: "zig build run",
|
||||
kind: "zig",
|
||||
command: "zig",
|
||||
args: ["build", "run"],
|
||||
detected: true,
|
||||
debugAdapter: null,
|
||||
isTest: false,
|
||||
env: {},
|
||||
cwd: null,
|
||||
...over,
|
||||
}) as RunConfig;
|
||||
|
||||
const exe = (id: string, over: Partial<RunConfig> = {}): RunConfig =>
|
||||
config({
|
||||
id,
|
||||
name: id,
|
||||
kind: "zig-application",
|
||||
command: "./zig-out/bin/app",
|
||||
args: [],
|
||||
debugAdapter: "codelldb",
|
||||
...over,
|
||||
});
|
||||
|
||||
describe("debugging a Zig build step", () => {
|
||||
it("recognises detected build steps, but not the build, tests or executables", () => {
|
||||
expect(isZigBuildStep(config())).toBe(true);
|
||||
expect(isZigBuildStep(config({ id: "zig:serve", args: ["build", "serve"] }))).toBe(true);
|
||||
expect(isZigBuildStep(config({ id: "zig:test", args: ["build", "test"], isTest: true }))).toBe(false);
|
||||
expect(isZigBuildStep(config({ id: "zig:build", args: ["build"] }))).toBe(false);
|
||||
expect(isZigBuildStep(config({ detected: false }))).toBe(false);
|
||||
expect(isZigBuildStep(exe("zig:exe:app"))).toBe(false);
|
||||
});
|
||||
|
||||
it("never sends a test step to the app binary", () => {
|
||||
const test = config({ id: "zig:test", args: ["build", "test"], isTest: true });
|
||||
expect(zigDebugTarget(test, [exe("zig:exe:app")])).toBeNull();
|
||||
});
|
||||
|
||||
it("delegates to the executable the backend linked via debugTarget", () => {
|
||||
const step = config({ params: { debugTarget: "zig:exe:two" } });
|
||||
const configs = [exe("zig:exe:one"), exe("zig:exe:two")];
|
||||
expect(zigDebugTarget(step, configs)?.id).toBe("zig:exe:two");
|
||||
});
|
||||
|
||||
it("does not guess which executable to debug when there is no link", () => {
|
||||
expect(zigDebugTarget(config(), [exe("zig:exe:app")])).toBeNull();
|
||||
expect(zigDebugTarget(config(), [exe("zig:exe:one"), exe("zig:exe:two")])).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores a stale or non-debuggable link", () => {
|
||||
expect(zigDebugTarget(config({ params: { debugTarget: "zig:exe:gone" } }), [exe("zig:exe:app")])).toBeNull();
|
||||
expect(
|
||||
zigDebugTarget(config({ params: { debugTarget: "zig:exe:app" } }), [exe("zig:exe:app", { debugAdapter: null })]),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when the project has no debuggable Zig executable", () => {
|
||||
expect(zigDebugTarget(config(), [])).toBeNull();
|
||||
expect(zigDebugTarget(config(), [exe("zig:exe:app", { debugAdapter: null })])).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* A Zig build step (`zig build <step>`) builds but has no debug adapter of its own. The project's
|
||||
* executable configs build the binary first and debug it under CodeLLDB, so debugging a step is
|
||||
* delegated to the executable it runs.
|
||||
*/
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
|
||||
const EXE_KIND = "zig-application";
|
||||
|
||||
/**
|
||||
* A detected `zig build <step>` config that runs an executable, which has no debug adapter of its
|
||||
* own. Test steps are excluded: their tests are not the project's app binary.
|
||||
*/
|
||||
export function isZigBuildStep(config: RunConfig): boolean {
|
||||
return (
|
||||
config.detected &&
|
||||
!config.isTest &&
|
||||
config.kind === "zig" &&
|
||||
config.id.startsWith("zig:") &&
|
||||
config.args[0] === "build" &&
|
||||
config.args.length > 1
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The debuggable executable config for a Zig build step, as linked by the backend. Detected
|
||||
* configs are regenerated on load, so a step that runs an executable always carries the link;
|
||||
* without one there is nothing to safely delegate to (a test step, an unparsed build script…).
|
||||
*/
|
||||
export function zigDebugTarget(step: RunConfig, configs: readonly RunConfig[]): RunConfig | null {
|
||||
if (!isZigBuildStep(step)) return null;
|
||||
const linked = step.params?.debugTarget;
|
||||
if (!linked) return null;
|
||||
return configs.find((c) => c.kind === EXE_KIND && !!c.debugAdapter && c.id === linked) ?? null;
|
||||
}
|
||||
@@ -28,6 +28,7 @@ import logStyles from "@/ui/LogPane.module.css";
|
||||
import { editorService, type EditorInput } from "@/workbench/contributions";
|
||||
import { isRunning } from "./model";
|
||||
import { connectionState, endpointOf, errorMessage, useServices } from "./store";
|
||||
import { wheelZoomStep } from "@/platform/wheelZoom";
|
||||
|
||||
export const DOCKER_LOG_EDITOR_KIND = "dockerLog";
|
||||
|
||||
@@ -71,9 +72,10 @@ function isActionStroke(stroke: string | null, actionId: string): boolean {
|
||||
|
||||
const wheelZoom = EditorView.domEventHandlers({
|
||||
wheel(e, view) {
|
||||
if (!e.metaKey && !e.ctrlKey) return false;
|
||||
const step = wheelZoomStep(e);
|
||||
if (step === null) return false;
|
||||
e.preventDefault();
|
||||
stepFontZoom(view, e.deltaY < 0 ? 1 : -1);
|
||||
if (step) stepFontZoom(view, step);
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
|
||||
import type { ComponentType } from "react";
|
||||
import { afterEach, beforeEach, expect, it } from "vitest";
|
||||
import { DEFAULT_DEPLOYMENT_SERVER } from "@/platform/remoteSettings";
|
||||
import { useContextMenuStore } from "@/ui";
|
||||
import { PageContext } from "../components/context";
|
||||
import { DEFAULT_SETTINGS } from "../model/schema";
|
||||
import { stagedValue, useSettingsDialog } from "../model/staging";
|
||||
import { DEPLOYMENT_PAGES } from "../pages/deployment";
|
||||
|
||||
const server = (id: string, name: string) => ({ ...DEFAULT_DEPLOYMENT_SERVER, id, name });
|
||||
|
||||
beforeEach(() => {
|
||||
const base = structuredClone(DEFAULT_SETTINGS) as typeof DEFAULT_SETTINGS & { deployment: Record<string, unknown> };
|
||||
base.deployment = { ...base.deployment, servers: [server("a", "Alpha"), server("b", "Beta")], defaultServer: "a" };
|
||||
useSettingsDialog.setState({ base, globalBase: structuredClone(DEFAULT_SETTINGS), staged: {}, query: "" });
|
||||
});
|
||||
afterEach(() => {
|
||||
act(() => useContextMenuStore.setState({ menu: null }));
|
||||
cleanup();
|
||||
});
|
||||
|
||||
function renderList() {
|
||||
const page = DEPLOYMENT_PAGES.find((p) => p.id === "build.deployment")!;
|
||||
const option = page
|
||||
.sections!.flatMap((s) => s.options)
|
||||
.find((o) => o.kind === "custom" && o.label === "Deployment servers");
|
||||
const Editor = (option as unknown as { component: ComponentType }).component;
|
||||
render(
|
||||
<PageContext.Provider value={{ pageId: page.id, scope: "project" }}>
|
||||
<Editor />
|
||||
</PageContext.Provider>,
|
||||
);
|
||||
}
|
||||
|
||||
const menuItem = (label: string) => {
|
||||
const item = useContextMenuStore.getState().menu!.items.find((i) => "label" in i && i.label === label) as {
|
||||
run?: () => void;
|
||||
disabled?: boolean;
|
||||
};
|
||||
return item;
|
||||
};
|
||||
const staged = (key: string) => stagedValue(useSettingsDialog.getState(), "project", key);
|
||||
|
||||
it("offers Add, Duplicate, Use as Default and Remove on a server row", () => {
|
||||
renderList();
|
||||
fireEvent.contextMenu(screen.getByRole("option", { name: /Beta/ }));
|
||||
expect(screen.getByRole("option", { name: /Beta/ })).toHaveAttribute("aria-selected", "true");
|
||||
expect(menuItem("Add")).toBeDefined();
|
||||
act(() => menuItem("Use as Default").run!());
|
||||
expect(staged("deployment.defaultServer")).toBe("b");
|
||||
fireEvent.contextMenu(screen.getByRole("option", { name: /Beta/ }));
|
||||
expect(menuItem("Use as Default").disabled).toBe(true);
|
||||
act(() => menuItem("Duplicate").run!());
|
||||
expect((staged("deployment.servers") as { name: string }[]).map((s) => s.name)).toEqual([
|
||||
"Alpha",
|
||||
"Beta",
|
||||
"Beta (copy)",
|
||||
]);
|
||||
fireEvent.contextMenu(screen.getByRole("option", { name: /Alpha/ }));
|
||||
act(() => menuItem("Remove").run!());
|
||||
expect((staged("deployment.servers") as { name: string }[]).map((s) => s.name)).toEqual(["Beta", "Beta (copy)"]);
|
||||
});
|
||||
|
||||
it("only adds from the empty part of the list", () => {
|
||||
renderList();
|
||||
fireEvent.contextMenu(screen.getByRole("listbox", { name: "Deployment servers" }));
|
||||
const labels = useContextMenuStore.getState().menu!.items.map((i) => ("label" in i ? i.label : i.kind));
|
||||
expect(labels).toEqual(["Add"]);
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import { beforeEach, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
|
||||
const { choose, tauri } = vi.hoisted(() => ({ choose: vi.fn(), tauri: { on: true } }));
|
||||
vi.mock("@/platform/choosePath", () => ({ choosePath: choose }));
|
||||
vi.mock("@/platform/ipc", async (original) => ({
|
||||
...(await original<typeof import("@/platform/ipc")>()),
|
||||
isTauri: () => tauri.on,
|
||||
}));
|
||||
import { GlobListEditor } from "../components/Form";
|
||||
|
||||
beforeEach(() => {
|
||||
choose.mockReset();
|
||||
tauri.on = true;
|
||||
});
|
||||
|
||||
const browse = { directory: true, title: "Choose Include Path" };
|
||||
|
||||
it("adds the folder picked in the chooser and leaves the list alone when it is cancelled", async () => {
|
||||
const onChange = vi.fn();
|
||||
choose.mockResolvedValueOnce("/opt/platform").mockResolvedValueOnce(null);
|
||||
render(<GlobListEditor value={["/a"]} onChange={onChange} browse={browse} aria-label="Include paths" />);
|
||||
await act(async () => fireEvent.click(screen.getByRole("button", { name: "Add" })));
|
||||
expect(choose).toHaveBeenCalledWith({ directory: true, title: "Choose Include Path" });
|
||||
expect(onChange).toHaveBeenCalledWith(["/a", "/opt/platform"]);
|
||||
await act(async () => fireEvent.click(screen.getByRole("button", { name: "Add" })));
|
||||
expect(onChange).toHaveBeenCalledTimes(1);
|
||||
expect(screen.queryByRole("textbox")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("types the path inline without a chooser", async () => {
|
||||
tauri.on = false;
|
||||
render(<GlobListEditor value={[]} onChange={vi.fn()} browse={browse} itemLabel="Include path" />);
|
||||
await act(async () => fireEvent.click(screen.getByRole("button", { name: "Add" })));
|
||||
expect(choose).not.toHaveBeenCalled();
|
||||
expect(screen.getByRole("textbox", { name: "Include path" })).toBeInTheDocument();
|
||||
});
|
||||
@@ -7,6 +7,8 @@ import { useId, useRef, useState, type KeyboardEvent, type ReactNode } from "rea
|
||||
import clsx from "clsx";
|
||||
import { Checkbox, IconButton, Input, Select as UiSelect, type SelectOption, T } from "@/ui";
|
||||
import { tx, useTx } from "@/platform/i18n";
|
||||
import { choosePath } from "@/platform/choosePath";
|
||||
import { isTauri } from "@/platform/ipc";
|
||||
import { highlightIndices } from "../model/pages";
|
||||
import { HEX_COLOR } from "../model/schema";
|
||||
import { useLabelMatch, useSearchQuery, useSetting } from "./context";
|
||||
@@ -303,6 +305,8 @@ export interface GlobListEditorProps {
|
||||
emptyText?: string;
|
||||
/** Accessible name of the inline editor. */
|
||||
itemLabel?: string;
|
||||
/** Entries are paths: + opens this chooser (Edit still takes typing). */
|
||||
browse?: { directory: boolean; title: string };
|
||||
}
|
||||
|
||||
/** Editable list of glob patterns (+ / − / edit toolbar, inline editing); also plain string lists. */
|
||||
@@ -312,6 +316,7 @@ export function GlobListEditor({
|
||||
placeholder = "**/pattern",
|
||||
emptyText = "No patterns",
|
||||
itemLabel = "Pattern",
|
||||
browse,
|
||||
...aria
|
||||
}: GlobListEditorProps) {
|
||||
const [selected, setSelected] = useState<number | null>(null);
|
||||
@@ -340,6 +345,19 @@ export function GlobListEditor({
|
||||
setEditing(null);
|
||||
};
|
||||
|
||||
const add = async () => {
|
||||
// Outside the desktop app there is no chooser: type the path instead.
|
||||
if (!browse || !isTauri()) {
|
||||
setEditing({ index: value.length, text: "" });
|
||||
return;
|
||||
}
|
||||
const picked = await choosePath({ ...browse, title: tx(browse.title) });
|
||||
if (!picked) return;
|
||||
const next = [...new Set([...value, picked])];
|
||||
onChange(next);
|
||||
setSelected(next.indexOf(picked));
|
||||
};
|
||||
|
||||
const remove = () => {
|
||||
if (selected === null) return;
|
||||
const next = value.filter((_, i) => i !== selected);
|
||||
@@ -380,12 +398,7 @@ export function GlobListEditor({
|
||||
return (
|
||||
<div className={styles.globEditor}>
|
||||
<div className={styles.listToolbar} role="toolbar" aria-controls={listId}>
|
||||
<IconButton
|
||||
icon="plus"
|
||||
title="Add"
|
||||
size="small"
|
||||
onClick={() => setEditing({ index: value.length, text: "" })}
|
||||
/>
|
||||
<IconButton icon="plus" title="Add" size="small" onClick={() => void add()} />
|
||||
<IconButton icon="minus" title="Remove" size="small" disabled={selected === null} onClick={remove} />
|
||||
<IconButton
|
||||
icon="edit"
|
||||
|
||||
@@ -221,6 +221,7 @@ export function PhpPage() {
|
||||
emptyText="No include paths"
|
||||
itemLabel="Include path"
|
||||
aria-label="Include paths"
|
||||
browse={{ directory: true, title: "Choose Include Path" }}
|
||||
/>
|
||||
</Row>
|
||||
<Row
|
||||
|
||||
@@ -244,3 +244,30 @@
|
||||
.toolsLayout .alignedRow {
|
||||
grid-template-columns: subgrid;
|
||||
}
|
||||
|
||||
/* Multi-line setting (agent instructions): a text field frame, full width. */
|
||||
.instructions {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
min-height: 72px;
|
||||
padding: var(--space-1-5) var(--space-2);
|
||||
border: 0;
|
||||
border-radius: var(--radius-control, 4px);
|
||||
background: var(--bg-field, var(--bg-button));
|
||||
box-shadow: inset 0 0 0 1px var(--border-button);
|
||||
color: var(--fg-strong);
|
||||
font: inherit;
|
||||
font-size: var(--fs-ui);
|
||||
resize: vertical;
|
||||
outline: none;
|
||||
-webkit-user-select: text;
|
||||
user-select: text;
|
||||
}
|
||||
.instructions::placeholder {
|
||||
color: var(--fg-faint);
|
||||
}
|
||||
.instructions:focus {
|
||||
box-shadow:
|
||||
inset 0 0 0 1px var(--focus-ring),
|
||||
0 0 0 1px var(--focus-ring);
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
* mappings, excluded remote paths) and the transfer options. Consumed by the
|
||||
* deployment feature and `ide-remote` (automatic upload, remote delete).
|
||||
*/
|
||||
import { useEffect, useId, useState, type KeyboardEvent } from "react";
|
||||
import { useEffect, useId, useState, type KeyboardEvent, type MouseEvent as ReactMouseEvent } from "react";
|
||||
import clsx from "clsx";
|
||||
import { call, commands, IpcError, isTauri, type FsConnection, type RemoteEntry } from "@/platform/ipc";
|
||||
import { useTx, tx, txTemplate } from "@/platform/i18n";
|
||||
@@ -30,6 +30,7 @@ import {
|
||||
Spinner,
|
||||
T,
|
||||
Tabs,
|
||||
type MenuItem,
|
||||
} from "@/ui";
|
||||
import { GlobListEditor, Row } from "../components/Form";
|
||||
import { SshConfigSelect, useSshConfigs } from "../components/SshConfigSelect";
|
||||
@@ -769,6 +770,26 @@ function DeploymentServersEditor() {
|
||||
setGroups([...groupList, group]);
|
||||
setSelected({ kind: "group", id: group.id });
|
||||
};
|
||||
const removeTarget = (target: Selection) => {
|
||||
if (!target) return;
|
||||
if (target.kind === "group") {
|
||||
const group = groupList.find((g) => g.id === target.id);
|
||||
if (!group) return;
|
||||
const index = groupList.indexOf(group);
|
||||
const rest = groupList.filter((g) => g.id !== group.id);
|
||||
setGroups(rest);
|
||||
const next = rest[Math.min(index, rest.length - 1)] ?? null;
|
||||
setSelected(next ? { kind: "group", id: next.id } : list[0] ? { kind: "server", id: list[0].id } : null);
|
||||
return;
|
||||
}
|
||||
const server = list.find((s) => s.id === target.id);
|
||||
if (!server) return;
|
||||
const index = list.indexOf(server);
|
||||
const rest = list.filter((s) => s.id !== server.id);
|
||||
commit(rest);
|
||||
const next = rest[Math.min(index, rest.length - 1)] ?? null;
|
||||
setSelected(next ? { kind: "server", id: next.id } : null);
|
||||
};
|
||||
const remove = () => {
|
||||
if (currentGroup) {
|
||||
const index = groupList.indexOf(currentGroup);
|
||||
@@ -786,6 +807,34 @@ function DeploymentServersEditor() {
|
||||
setSelected(next ? { kind: "server", id: next.id } : null);
|
||||
};
|
||||
const isSelected = (kind: "server" | "group", id: string) => selected?.kind === kind && selected.id === id;
|
||||
const addItems: MenuItem[] = [
|
||||
{ label: "Server", icon: "web", run: () => add() },
|
||||
{ label: "Server Group", icon: "folder", run: addGroup },
|
||||
];
|
||||
// Right-click on a row works on that row (it is selected first); on the empty list it only adds.
|
||||
const rowMenu = (e: ReactMouseEvent, target: Selection) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setSelected(target);
|
||||
const server = target?.kind === "server" ? list.find((s) => s.id === target.id) : undefined;
|
||||
showContextMenu(e, [
|
||||
{ label: "Add", icon: "plus", submenu: addItems },
|
||||
...(server
|
||||
? [
|
||||
{ label: "Duplicate", icon: "copy", run: () => add(server) } as MenuItem,
|
||||
{
|
||||
label: "Use as Default",
|
||||
icon: "check",
|
||||
disabled: server.id === effectiveDefault,
|
||||
run: () => setDefaultServer(server.id),
|
||||
} as MenuItem,
|
||||
]
|
||||
: []),
|
||||
{ kind: "separator" },
|
||||
// `remove` acts on the selection, which the state update above has not applied yet.
|
||||
{ label: "Remove", icon: "minus", run: () => removeTarget(target) },
|
||||
]);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={styles.layout}>
|
||||
@@ -797,10 +846,7 @@ function DeploymentServersEditor() {
|
||||
size="small"
|
||||
onClick={(e) => {
|
||||
const r = e.currentTarget.getBoundingClientRect();
|
||||
showContextMenu({ x: r.left, y: r.bottom }, [
|
||||
{ label: "Server", icon: "web", run: () => add() },
|
||||
{ label: "Server Group", icon: "folder", run: addGroup },
|
||||
]);
|
||||
showContextMenu({ x: r.left, y: r.bottom }, addItems);
|
||||
}}
|
||||
/>
|
||||
<IconButton icon="minus" title="Remove" size="small" disabled={!current && !currentGroup} onClick={remove} />
|
||||
@@ -819,7 +865,15 @@ function DeploymentServersEditor() {
|
||||
onClick={() => current && setDefaultServer(current.id)}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.serverList} role="listbox" aria-label={tx("Deployment servers")}>
|
||||
<div
|
||||
className={styles.serverList}
|
||||
role="listbox"
|
||||
aria-label={tx("Deployment servers")}
|
||||
onContextMenu={(e) => {
|
||||
e.preventDefault();
|
||||
showContextMenu(e, [{ label: "Add", icon: "plus", submenu: addItems }]);
|
||||
}}
|
||||
>
|
||||
{list.length === 0 && groupList.length === 0 && (
|
||||
<div className={styles.empty}>
|
||||
<T>No servers. Click + to add one.</T>
|
||||
@@ -832,6 +886,7 @@ function DeploymentServersEditor() {
|
||||
aria-selected={isSelected("group", g.id)}
|
||||
className={clsx(styles.serverRow, isSelected("group", g.id) && styles.serverSelected)}
|
||||
onMouseDown={() => setSelected({ kind: "group", id: g.id })}
|
||||
onContextMenu={(e) => rowMenu(e, { kind: "group", id: g.id })}
|
||||
>
|
||||
<Icon name="folder" />
|
||||
<span className={styles.serverName}>{g.name || g.id}</span>
|
||||
@@ -845,6 +900,7 @@ function DeploymentServersEditor() {
|
||||
aria-selected={isSelected("server", s.id)}
|
||||
className={clsx(styles.serverRow, isSelected("server", s.id) && styles.serverSelected)}
|
||||
onMouseDown={() => setSelected({ kind: "server", id: s.id })}
|
||||
onContextMenu={(e) => rowMenu(e, { kind: "server", id: s.id })}
|
||||
>
|
||||
<Icon name="web" />
|
||||
<span className={clsx(styles.serverName, s.id === effectiveDefault && styles.default)}>
|
||||
|
||||
@@ -277,6 +277,31 @@ function MessageLimits() {
|
||||
);
|
||||
}
|
||||
|
||||
function AgentInstructionsRow() {
|
||||
const [value, set] = useSetting<string>("vcs.commit.agentInstructions");
|
||||
const id = useId();
|
||||
return (
|
||||
<Row
|
||||
label="Instructions for Generate Commit Message with Agent"
|
||||
htmlFor={id}
|
||||
hint="Added to the agent's prompt, e.g. a commit format, issue key prefixes or the language to write in."
|
||||
stacked
|
||||
>
|
||||
<textarea
|
||||
id={id}
|
||||
className={styles.instructions}
|
||||
rows={4}
|
||||
spellCheck={false}
|
||||
placeholder={tx(
|
||||
"Use Conventional Commits (feat:, fix:, …) and start with the issue key if the branch has one.",
|
||||
)}
|
||||
value={value}
|
||||
onChange={(e) => set(e.target.value)}
|
||||
/>
|
||||
</Row>
|
||||
);
|
||||
}
|
||||
|
||||
function CommitChecks() {
|
||||
return (
|
||||
<Grid
|
||||
@@ -402,6 +427,17 @@ export const VCS_PAGES: PageSpec[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Commit Message Generation",
|
||||
options: [
|
||||
{
|
||||
kind: "custom",
|
||||
label: "Instructions for Generate Commit Message with Agent",
|
||||
keywords: ["agent", "ai", "prompt", "conventional commits"],
|
||||
component: AgentInstructionsRow,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Commit Checks",
|
||||
options: [
|
||||
|
||||
@@ -42,6 +42,7 @@ import {
|
||||
type TerminalFontSettings,
|
||||
MIN_CONTRAST_RATIO,
|
||||
} from "./theme";
|
||||
import { wheelZoomStep } from "@/platform/wheelZoom";
|
||||
|
||||
export interface TerminalSearchOptions {
|
||||
caseSensitive: boolean;
|
||||
@@ -464,10 +465,12 @@ export class TerminalSession {
|
||||
}
|
||||
|
||||
private onWheelZoom = (e: WheelEvent) => {
|
||||
if ((!e.ctrlKey && !e.metaKey) || e.deltaY === 0 || !editorPrefs().general.wheelZoom) return;
|
||||
if (!editorPrefs().general.wheelZoom) return;
|
||||
const zoom = wheelZoomStep(e);
|
||||
if (zoom === null) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
this.stepFontSize(e.deltaY < 0 ? 1 : -1);
|
||||
if (zoom) this.stepFontSize(zoom);
|
||||
};
|
||||
|
||||
private onMiddleClick = (e: MouseEvent) => {
|
||||
|
||||
@@ -26,7 +26,6 @@ import {
|
||||
EmptyState,
|
||||
Icon,
|
||||
IconButton,
|
||||
List,
|
||||
Menu,
|
||||
Select,
|
||||
SplitGroup,
|
||||
@@ -103,7 +102,8 @@ import {
|
||||
import { DiffEditor } from "./DiffEditor";
|
||||
import { KIND_COLOR, KIND_LABEL, fileCount, formatTime, stashLabel, stripSlash } from "./model";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import type { FileStatus } from "@/bindings";
|
||||
import type { Commit, FileStatus, Stash } from "@/bindings";
|
||||
import { showChangesDiff, toLogChanges, type LogChange } from "./logChanges";
|
||||
import { OperationBanner } from "./operations";
|
||||
import { runOp } from "./ops";
|
||||
import { ShelfPanel, loadShelves, useShelf } from "./shelf";
|
||||
@@ -1334,18 +1334,33 @@ function CommitPanel({ included }: { included: number }) {
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type StashEntry = Stash & { repo: string | null };
|
||||
type StashNode = { key: string; stash: StashEntry; change?: LogChange };
|
||||
|
||||
const stashKey = (s: StashEntry) => `${s.repo}:${s.index}:${s.id}`;
|
||||
const STASH_PREVIEW_DELAY = 120;
|
||||
|
||||
/** A stash's changes against the commit it was made on, as Git Log changes (diffs, line counts). */
|
||||
async function stashFileChanges(stash: StashEntry): Promise<LogChange[]> {
|
||||
const files = await call(commands.vcsCommitFiles(stash.repo, stash.id));
|
||||
const commit = { id: stash.id, shortId: stash.id.slice(0, 8), parents: stash.base ? [stash.base] : [] };
|
||||
return toLogChanges(files, commit as unknown as Commit, stash.repo, true);
|
||||
}
|
||||
|
||||
export function StashesPanel() {
|
||||
const repo = useVcs((s) => s.repo);
|
||||
const repos = useVcs((s) => s.roots);
|
||||
const version = useVcs((s) => s.version);
|
||||
const [tick, setTick] = useState(0);
|
||||
const [active, setActive] = useState(0);
|
||||
const [selectedKey, setSelectedKey] = useState<string | null>(null);
|
||||
const request = useMemo(() => ({ repos, repo, version, tick }), [repos, repo, version, tick]);
|
||||
const [result, setResult] = useState<{
|
||||
request: typeof request;
|
||||
stashes: (import("@/bindings").Stash & { repo: string | null })[];
|
||||
stashes: StashEntry[];
|
||||
error: string | null;
|
||||
} | null>(null);
|
||||
const [files, setFiles] = useState<ReadonlyMap<string, LogChange[]>>(new Map());
|
||||
const previewTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
|
||||
const loaded = result?.request === request;
|
||||
const stashes = loaded ? result.stashes : [];
|
||||
const error = loaded ? result.error : null;
|
||||
@@ -1366,7 +1381,29 @@ export function StashesPanel() {
|
||||
live = false;
|
||||
};
|
||||
}, [request]);
|
||||
const current = stashes[active];
|
||||
useEffect(() => () => clearTimeout(previewTimer.current), []);
|
||||
const roots = useMemo<StashNode[]>(() => stashes.map((stash) => ({ key: stashKey(stash), stash })), [stashes]);
|
||||
const childrenOf = (node: StashNode): StashNode[] | undefined =>
|
||||
node.change
|
||||
? undefined
|
||||
: files.get(node.key)?.map((change) => ({ key: `${node.key}\u0000${change.path}`, stash: node.stash, change }));
|
||||
const loadFiles = async (node: StashNode) => {
|
||||
if (files.has(node.key)) return;
|
||||
const changes = await stashFileChanges(node.stash).catch(() => []);
|
||||
setFiles((prev) => new Map(prev).set(node.key, changes));
|
||||
};
|
||||
const nodeOf = (key: string | null): StashNode | undefined => {
|
||||
if (!key) return undefined;
|
||||
const root = roots.find((r) => key === r.key || key.startsWith(`${r.key}\u0000`));
|
||||
if (!root || key === root.key) return root;
|
||||
return childrenOf(root)?.find((n) => n.key === key);
|
||||
};
|
||||
const selectedNode = nodeOf(selectedKey);
|
||||
const current = selectedNode?.stash ?? stashes[0];
|
||||
const showDiff = (node: StashNode, preview: boolean) => {
|
||||
const chain = files.get(stashKey(node.stash)) ?? [];
|
||||
if (node.change) void showChangesDiff([node.change], preview, chain).catch(() => undefined);
|
||||
};
|
||||
return (
|
||||
<div className={styles.changes}>
|
||||
<div className={styles.toolbar} role="toolbar" aria-label={tx("Stashes")}>
|
||||
@@ -1378,7 +1415,15 @@ export function StashesPanel() {
|
||||
options={repos.map((root) => ({ value: root, label: repoName(root) }))}
|
||||
/>
|
||||
)}
|
||||
<IconButton icon="refresh" title="Refresh" size="small" onClick={() => setTick((n) => n + 1)} />
|
||||
<IconButton
|
||||
icon="refresh"
|
||||
title="Refresh"
|
||||
size="small"
|
||||
onClick={() => {
|
||||
setFiles(new Map());
|
||||
setTick((n) => n + 1);
|
||||
}}
|
||||
/>
|
||||
<IconButton icon="plus" title="Stash Changes…" size="small" onClick={() => void stashChanges()} />
|
||||
<span className={styles.sep} />
|
||||
<IconButton
|
||||
@@ -1403,44 +1448,77 @@ export function StashesPanel() {
|
||||
onClick={() => current && void dropStash(current.index, current.message, current.repo)}
|
||||
/>
|
||||
</div>
|
||||
<List
|
||||
items={stashes}
|
||||
getKey={(s) => `${s.repo}:${s.index}`}
|
||||
activeIndex={Math.min(active, Math.max(0, stashes.length - 1))}
|
||||
onActiveChange={setActive}
|
||||
rowHeight={22}
|
||||
aria-label="Stashes"
|
||||
className={styles.stashList}
|
||||
empty={<span className={styles.empty}>{error ?? (loaded ? tx("No stashes") : tx("Loading…"))}</span>}
|
||||
onActivate={(s, _i, e) => {
|
||||
if (e.type === "click" && (e as MouseEvent).detail < 2) return;
|
||||
void applyStash(s.index, false, s.repo);
|
||||
}}
|
||||
onContextMenu={(s, i, e) => {
|
||||
e.preventDefault();
|
||||
setActive(i);
|
||||
showContextMenu(e, [
|
||||
{ label: "Apply Stash", icon: "check", run: () => void applyStash(s.index, false, s.repo) },
|
||||
{ label: "Pop Stash", icon: "undo", run: () => void applyStash(s.index, true, s.repo) },
|
||||
{ label: "Unstash…", run: () => showUnstashDialog(s.index, s.repo) },
|
||||
{ kind: "separator" },
|
||||
{ label: "Drop Stash", icon: "trash", run: () => void dropStash(s.index, s.message, s.repo) },
|
||||
]);
|
||||
}}
|
||||
renderItem={(s) => {
|
||||
const { branch, text } = stashLabel(s.message);
|
||||
return (
|
||||
<span className={styles.stashRow} title={`stash@{${s.index}}: ${s.message}`}>
|
||||
<span className={styles.stashMessage}>
|
||||
{repos.length > 1 && s.repo ? `${repoName(s.repo)} · ` : ""}
|
||||
{text}
|
||||
<div className={styles.treeWrap}>
|
||||
<Tree<StashNode>
|
||||
roots={roots}
|
||||
getKey={(n) => n.key}
|
||||
getLabel={(n) => (n.change ? basename(n.change.path) : n.stash.message)}
|
||||
getChildren={childrenOf}
|
||||
isExpandable={(n) => !n.change}
|
||||
loadChildren={loadFiles}
|
||||
selected={useMemo(() => new Set(selectedKey ? [selectedKey] : []), [selectedKey])}
|
||||
multiSelect={false}
|
||||
rowHeight={22}
|
||||
aria-label="Stashes"
|
||||
className={styles.stashList}
|
||||
empty={<span className={styles.empty}>{error ?? (loaded ? tx("No stashes") : tx("Loading…"))}</span>}
|
||||
onSelectionChange={(sel) => {
|
||||
const key = [...sel][0] ?? null;
|
||||
setSelectedKey(key);
|
||||
clearTimeout(previewTimer.current);
|
||||
const node = nodeOf(key);
|
||||
// With Show Diff Preview on, the selection walks a preview tab through the stash's files.
|
||||
if (node?.change && useCommit.getState().diffPreview && !vcsDiffInFront())
|
||||
previewTimer.current = setTimeout(() => showDiff(node, true), STASH_PREVIEW_DELAY);
|
||||
}}
|
||||
onActivate={(n) => showDiff(n, false)}
|
||||
onContextMenu={(n, _sel, e) => {
|
||||
if (!n) return;
|
||||
e.preventDefault();
|
||||
setSelectedKey(n.key);
|
||||
const s = n.stash;
|
||||
showContextMenu(e, [
|
||||
...(n.change
|
||||
? [
|
||||
{ label: "Show Diff", icon: "diff", run: () => showDiff(n, false) } as MenuItem,
|
||||
{ kind: "separator" } as MenuItem,
|
||||
]
|
||||
: []),
|
||||
{ label: "Apply Stash", icon: "check", run: () => void applyStash(s.index, false, s.repo) },
|
||||
{ label: "Pop Stash", icon: "undo", run: () => void applyStash(s.index, true, s.repo) },
|
||||
{ label: "Unstash…", run: () => showUnstashDialog(s.index, s.repo) },
|
||||
{ kind: "separator" },
|
||||
{ label: "Drop Stash", icon: "trash", run: () => void dropStash(s.index, s.message, s.repo) },
|
||||
]);
|
||||
}}
|
||||
renderNode={(n) => {
|
||||
if (n.change) {
|
||||
const kind = n.change.kind === "untracked" ? "added" : n.change.kind;
|
||||
return (
|
||||
<>
|
||||
<Icon name={fileIconName(basename(n.change.path), n.change.path)} size={16} className={styles.icon} />
|
||||
<span className={styles.label} style={{ color: KIND_COLOR[kind] }}>
|
||||
{basename(n.change.path)}
|
||||
</span>
|
||||
<span className={styles.detail}>{dirname(n.change.path)}</span>
|
||||
</>
|
||||
);
|
||||
}
|
||||
const s = n.stash;
|
||||
const { branch, text } = stashLabel(s.message);
|
||||
return (
|
||||
<span className={styles.stashRow} title={`stash@{${s.index}}: ${s.message}`}>
|
||||
<span className={styles.stashMessage}>
|
||||
{repos.length > 1 && s.repo ? `${repoName(s.repo)} · ` : ""}
|
||||
{text}
|
||||
</span>
|
||||
{branch && <span className={clsx(styles.detail, styles.stashBranch)}>{branch}</span>}
|
||||
<span className={clsx(styles.detail, styles.stashTime)}>{formatTime(s.timeMs)}</span>
|
||||
</span>
|
||||
{branch && <span className={clsx(styles.detail, styles.stashBranch)}>{branch}</span>}
|
||||
<span className={clsx(styles.detail, styles.stashTime)}>{formatTime(s.timeMs)}</span>
|
||||
</span>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -219,6 +219,34 @@ it("does not open the worktree when the checkout offer is declined", async () =>
|
||||
expect(mocks.executeAction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("names the files git would remove when untracked ones block the checkout", async () => {
|
||||
mocks.checkout.mockResolvedValue(ok({ kind: "untrackedFiles", files: ["TEST.md"], removed: true }));
|
||||
await checkoutBranch("feature/x");
|
||||
expect(mocks.checkout).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.notify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
level: "error",
|
||||
title: "Untracked files prevent checkout",
|
||||
body: expect.stringContaining(
|
||||
"The following untracked working tree files would be removed by checkout:\nTEST.md",
|
||||
),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("still says overwritten when untracked files would be overwritten", async () => {
|
||||
mocks.checkout.mockResolvedValue(ok({ kind: "untrackedFiles", files: ["dir/new.txt"], removed: false }));
|
||||
await checkoutBranch("feature/x");
|
||||
expect(mocks.notify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
level: "error",
|
||||
body: expect.stringContaining(
|
||||
"The following untracked working tree files would be overwritten by checkout:\ndir/new.txt",
|
||||
),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps the branch when the worktree question is turned down", async () => {
|
||||
mocks.worktrees.mockResolvedValue(ok([worktree("/p/front-feature-wt", "feature/wt")]));
|
||||
mocks.confirm.mockResolvedValue(false);
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import { beforeEach, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
const { apply, list } = vi.hoisted(() => ({ apply: vi.fn(), list: vi.fn() }));
|
||||
const { apply, list, files, diff } = vi.hoisted(() => ({
|
||||
apply: vi.fn(),
|
||||
list: vi.fn(),
|
||||
files: vi.fn(),
|
||||
diff: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/platform/ipc", async (original) => {
|
||||
const real = await original<typeof import("@/platform/ipc")>();
|
||||
return {
|
||||
@@ -8,6 +13,7 @@ vi.mock("@/platform/ipc", async (original) => {
|
||||
commands: {
|
||||
...real.commands,
|
||||
vcsStashes: list,
|
||||
vcsCommitFiles: files,
|
||||
},
|
||||
};
|
||||
});
|
||||
@@ -15,15 +21,32 @@ vi.mock("../changeOps", async (original) => ({
|
||||
...(await original<typeof import("../changeOps")>()),
|
||||
applyStash: apply,
|
||||
}));
|
||||
vi.mock("../logChanges", async (original) => ({
|
||||
...(await original<typeof import("../logChanges")>()),
|
||||
showChangesDiff: diff,
|
||||
}));
|
||||
import { StashesPanel } from "../CommitView";
|
||||
import { useVcs } from "../store";
|
||||
|
||||
beforeEach(() => {
|
||||
apply.mockReset();
|
||||
diff.mockReset().mockResolvedValue(undefined);
|
||||
files.mockReset().mockResolvedValue({
|
||||
status: "ok",
|
||||
data: [{ path: "src/app.ts", kind: "modified", oldPath: null }],
|
||||
});
|
||||
list.mockReset().mockImplementation((repo: string) =>
|
||||
Promise.resolve({
|
||||
status: "ok",
|
||||
data: [{ index: 0, message: `On main: ${repo.endsWith("front") ? "First" : "Second"}`, timeMs: 0 }],
|
||||
data: [
|
||||
{
|
||||
index: 0,
|
||||
message: `On main: ${repo.endsWith("front") ? "First" : "Second"}`,
|
||||
timeMs: 0,
|
||||
id: `${repo}-stash`,
|
||||
base: `${repo}-base`,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
useVcs.setState({ root: "/p", roots: ["/p/front", "/p/back"], repo: "/p/front" });
|
||||
@@ -53,9 +76,24 @@ it("disables stale stash actions while another repository is loading", async ()
|
||||
expect(screen.queryByText("front · First")).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Apply Stash" })).toBeDisabled();
|
||||
await act(async () => {
|
||||
resolve({ status: "ok", data: [{ index: 0, message: "On main: New project", timeMs: 0 }] });
|
||||
resolve({ status: "ok", data: [{ index: 0, message: "On main: New project", timeMs: 0, id: "n", base: "b" }] });
|
||||
});
|
||||
await screen.findByText("New project");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Apply Stash" }));
|
||||
expect(apply).toHaveBeenCalledWith(0, false, "/other");
|
||||
});
|
||||
|
||||
it("lists a stash's changed files and opens their diff instead of applying the stash", async () => {
|
||||
render(<StashesPanel />);
|
||||
const row = await screen.findByText("front · First");
|
||||
// Double-clicking a stash expands it; it never applies the stash.
|
||||
fireEvent.doubleClick(row);
|
||||
expect(await screen.findByText("app.ts")).toBeInTheDocument();
|
||||
expect(files).toHaveBeenCalledWith("/p/front", "/p/front-stash");
|
||||
expect(apply).not.toHaveBeenCalled();
|
||||
fireEvent.doubleClick(screen.getByText("app.ts"));
|
||||
expect(diff).toHaveBeenCalledTimes(1);
|
||||
const [[change], preview] = diff.mock.calls[0]!;
|
||||
expect(preview).toBe(false);
|
||||
expect(change).toMatchObject({ path: "src/app.ts", before: "/p/front-base", after: "/p/front-stash" });
|
||||
});
|
||||
@@ -48,7 +48,7 @@ import { VcsDialogHost } from "../dialogs";
|
||||
import { showUnstashDialog } from "../changeOps";
|
||||
import { useVcs } from "../store";
|
||||
|
||||
const stash = (index: number, message: string): Stash => ({ index, message, timeMs: null });
|
||||
const stash = (index: number, message: string): Stash => ({ index, message, timeMs: null, id: `s${index}`, base: "b" });
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.stashes = new Map([
|
||||
|
||||
@@ -104,11 +104,17 @@ async function performCheckout(
|
||||
return true;
|
||||
case "untrackedFiles": {
|
||||
const files = outcome.files.join("\n");
|
||||
// git refuses untracked files in two ways: they would be overwritten by the
|
||||
// checkout (present in the target), or removed by it (tracked here, absent
|
||||
// from the target); each names its files the way git's own message does.
|
||||
const body = outcome.removed
|
||||
? tx`The following untracked working tree files would be removed by checkout:\n${files}\nPlease move or remove them before you switch branches.`
|
||||
: tx`The following untracked working tree files would be overwritten by checkout:\n${files}\nPlease move or remove them before you switch branches.`;
|
||||
notifications().notify({
|
||||
group: "vcs",
|
||||
level: "error",
|
||||
title: "Untracked files prevent checkout",
|
||||
body: tx`The following untracked working tree files would be overwritten by checkout:\n${files}\nPlease move or remove them before you switch branches.`,
|
||||
body,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -54,6 +54,7 @@ import {
|
||||
import { applyImageZoomWidth, svgDataUrlSize } from "@/ui/svgSize";
|
||||
import styles from "./Markdown.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { wheelZoomStep } from "@/platform/wheelZoom";
|
||||
|
||||
/** Loaded local images by absolute path (data URLs), shared by all previews. */
|
||||
const imageCache = new Map<string, Promise<string>>();
|
||||
@@ -380,11 +381,13 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
const root = ref.current;
|
||||
if (!root) return;
|
||||
const onWheel = (e: WheelEvent) => {
|
||||
if ((!e.ctrlKey && !e.metaKey) || e.deltaY === 0 || !editorPrefs().general.wheelZoom) return;
|
||||
if (!editorPrefs().general.wheelZoom) return;
|
||||
const zoom = wheelZoomStep(e);
|
||||
if (zoom === null) return;
|
||||
if ((e.target as Element | null)?.closest?.('.mermaid-output[data-zoomed="true"]')) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
stepMarkdownPreviewFontZoom(path, root, e.deltaY < 0 ? 1 : -1);
|
||||
if (zoom) stepMarkdownPreviewFontZoom(path, root, zoom);
|
||||
};
|
||||
root.addEventListener("wheel", onWheel, { capture: true, passive: false });
|
||||
const release = registerFontZoomSurface(root, (delta) => stepMarkdownPreviewFontZoom(path, root, delta));
|
||||
|
||||
@@ -28,6 +28,7 @@ import { call, commands, isTauri } from "./platform/ipc";
|
||||
import { hideSplash } from "./platform/splash";
|
||||
import { prefetchLazyComponents } from "./ui";
|
||||
import { installWindowDrag } from "./workbench/window-drag";
|
||||
import { installFullscreenEscapeGuard } from "./workbench/fullscreenEscape";
|
||||
|
||||
if (import.meta.env.DEV && isTauri()) {
|
||||
// The Tauri MCP bridge returns eval results via `window.__TAURI__` on Windows/Linux
|
||||
@@ -71,6 +72,8 @@ if (aux?.kind === "settings") {
|
||||
activateSecondaryWindow();
|
||||
activateDeploymentWindowFeatures(aux.parent);
|
||||
} else {
|
||||
// Before the features' and the dispatcher's key handlers: it wraps the Escape they see.
|
||||
installFullscreenEscapeGuard();
|
||||
activateWorkbench();
|
||||
// `vite build --mode perf` is a production bundle for the performance harness (`perf/`).
|
||||
const perfBuild = import.meta.env.MODE === "perf";
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
{
|
||||
"Trust Project in Codex": "Trust Project in Codex",
|
||||
"Go to Feign Endpoint": "Go to Feign Endpoint",
|
||||
"Choose Feign Endpoint": "Choose Feign Endpoint",
|
||||
"No matching Feign endpoint found": "No matching Feign endpoint found",
|
||||
"Cannot navigate to Feign endpoint": "Cannot navigate to Feign endpoint",
|
||||
"Keep Untrusted": "Keep Untrusted",
|
||||
"Unity Editor": "Unity Editor",
|
||||
"Attach to Unity Process": "Attach to Unity Process",
|
||||
@@ -2134,6 +2138,7 @@
|
||||
"No classes to move to": "No classes to move to",
|
||||
"Move {name} to a new file": "Move {name} to a new file",
|
||||
"Move {name} to another class": "Move {name} to another class",
|
||||
"Move {name} to New Window": "Move {name} to New Window",
|
||||
"(default package)": "(default package)",
|
||||
"Field": "Field",
|
||||
"Move": "Move",
|
||||
@@ -2370,5 +2375,12 @@
|
||||
"Install IDE Copy": "Install IDE Copy",
|
||||
"Not installed:": "Not installed:",
|
||||
"Additional servers": "Additional servers",
|
||||
"Run alongside the one above": "Run alongside the one above"
|
||||
"Run alongside the one above": "Run alongside the one above",
|
||||
"The agent jar changed since you approved it. Approve the new jar before the next launch.": "The agent jar changed since you approved it. Approve the new jar before the next launch.",
|
||||
"Approve new jar": "Approve new jar",
|
||||
"Commit Message Generation": "Commit Message Generation",
|
||||
"Instructions for Generate Commit Message with Agent": "Instructions for Generate Commit Message with Agent",
|
||||
"Added to the agent's prompt, e.g. a commit format, issue key prefixes or the language to write in.": "Added to the agent's prompt, e.g. a commit format, issue key prefixes or the language to write in.",
|
||||
"Use Conventional Commits (feat:, fix:, …) and start with the issue key if the branch has one.": "Use Conventional Commits (feat:, fix:, …) and start with the issue key if the branch has one.",
|
||||
"Choose Include Path": "Choose Include Path"
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
{
|
||||
"Trust Project in Codex": "在 Codex 中信任项目",
|
||||
"Go to Feign Endpoint": "跳转到 Feign 端点",
|
||||
"Choose Feign Endpoint": "选择 Feign 端点",
|
||||
"No matching Feign endpoint found": "未找到匹配的 Feign 端点",
|
||||
"Cannot navigate to Feign endpoint": "无法跳转到 Feign 端点",
|
||||
"Keep Untrusted": "保持不信任",
|
||||
"Unity Editor": "Unity 编辑器",
|
||||
"Attach to Unity Process": "附加到 Unity 进程",
|
||||
@@ -7001,6 +7005,7 @@
|
||||
"Choose Declaration": "选择声明",
|
||||
"Go to mapping: {target}": "跳转到映射:{target}",
|
||||
"Untracked files prevent checkout": "未跟踪的文件阻止了签出",
|
||||
"The following untracked working tree files would be removed by checkout:\n{files}\nPlease move or remove them before you switch branches.": "签出将删除以下未跟踪的工作区文件:\n{files}\n请在切换分支前移动或删除它们。",
|
||||
"The following untracked working tree files would be overwritten by checkout:\n{files}\nPlease move or remove them before you switch branches.": "签出将覆盖以下未跟踪的工作区文件:\n{files}\n请在切换分支前移动或删除它们。",
|
||||
"Select Target Changelist": "选择目标更改列表",
|
||||
"Rebase undone": "已撤销变基",
|
||||
@@ -8515,6 +8520,7 @@
|
||||
"No classes to move to": "没有可移动到的类",
|
||||
"Move {name} to a new file": "将 {name} 移动到新文件",
|
||||
"Move {name} to another class": "将 {name} 移动到其他类",
|
||||
"Move {name} to New Window": "将 {name} 移到新窗口",
|
||||
"(default package)": "(默认包)",
|
||||
"Field": "字段",
|
||||
"Extract Interface…": "提取接口…",
|
||||
@@ -8747,5 +8753,12 @@
|
||||
"Install IDE Copy": "安装到 IDE",
|
||||
"Not installed:": "未安装:",
|
||||
"Additional servers": "附加服务器",
|
||||
"Run alongside the one above": "与上面选中的服务器同时运行"
|
||||
"Run alongside the one above": "与上面选中的服务器同时运行",
|
||||
"The agent jar changed since you approved it. Approve the new jar before the next launch.": "Agent jar 在授权后发生了变化。请先批准新的 jar,再启动应用。",
|
||||
"Approve new jar": "批准新的 jar",
|
||||
"Commit Message Generation": "提交信息生成",
|
||||
"Instructions for Generate Commit Message with Agent": "用 Agent 生成提交信息时的要求",
|
||||
"Added to the agent's prompt, e.g. a commit format, issue key prefixes or the language to write in.": "会加到 Agent 的提示词里,例如提交格式、问题编号前缀或使用的语言。",
|
||||
"Use Conventional Commits (feat:, fix:, …) and start with the issue key if the branch has one.": "使用 Conventional Commits(feat:、fix: 等),分支带问题编号时以它开头。",
|
||||
"Choose Include Path": "选择包含路径"
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { resetWheelZoomGesture, wheelZoomStep } from "./wheelZoom";
|
||||
|
||||
let t = 0;
|
||||
const wheel = (deltaY: number, mod = true, gap = 16) => {
|
||||
t += gap;
|
||||
return wheelZoomStep({ deltaY, metaKey: mod, ctrlKey: false, timeStamp: t });
|
||||
};
|
||||
|
||||
describe("wheelZoomStep", () => {
|
||||
beforeEach(() => {
|
||||
resetWheelZoomGesture();
|
||||
t = 1000;
|
||||
});
|
||||
|
||||
it("zooms in and out with ⌘ held from the start of the gesture", () => {
|
||||
expect(wheel(-4)).toBe(1);
|
||||
expect(wheel(-6)).toBe(1);
|
||||
expect(wheel(10, true, 500)).toBe(-1);
|
||||
});
|
||||
|
||||
it("leaves plain scrolling alone", () => {
|
||||
expect(wheel(-10, false)).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps scrolling the inertia of a plain scroll when ⌘ is pressed during it", () => {
|
||||
expect(wheel(-40, false)).toBeNull();
|
||||
expect(wheel(-30)).toBeNull();
|
||||
expect(wheel(-20)).toBeNull();
|
||||
expect(wheel(-10, true, 500)).toBe(1);
|
||||
});
|
||||
|
||||
it("stops zooming once the deltas decay like inertia, without scrolling", () => {
|
||||
for (const d of [-8, -12, -15]) expect(wheel(d)).toBe(1);
|
||||
expect(wheel(-14)).toBe(1);
|
||||
expect(wheel(-12)).toBe(1);
|
||||
expect(wheel(-9)).toBe(1);
|
||||
expect(wheel(-6)).toBe(0);
|
||||
expect(wheel(-4)).toBe(0);
|
||||
expect(wheel(-5)).toBe(0);
|
||||
});
|
||||
|
||||
it("never swallows a plain wheel event, even during a zoom gesture", () => {
|
||||
expect(wheel(-10)).toBe(1);
|
||||
expect(wheel(-10, false)).toBeNull();
|
||||
});
|
||||
|
||||
it("gives the same answer for repeated calls with one event", () => {
|
||||
const e = { deltaY: -10, metaKey: true, ctrlKey: false, timeStamp: 5000 };
|
||||
expect(wheelZoomStep(e)).toBe(1);
|
||||
expect(wheelZoomStep(e)).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* ⌘/Ctrl+wheel font zoom that ignores scroll inertia.
|
||||
*
|
||||
* WebViews don't expose macOS momentum phases, so a gesture is a run of wheel events
|
||||
* less than `GESTURE_GAP_MS` apart (momentum continues the run of the swipe that started it).
|
||||
* A run that started without ⌘/Ctrl (a scroll still coasting when ⌘ is pressed) never zooms
|
||||
* and keeps scrolling; a run that started with it stops zooming (and scrolling) once the deltas
|
||||
* keep shrinking, which is the inertia after the fingers left the trackpad. A wheel event
|
||||
* without ⌘/Ctrl always scrolls.
|
||||
*/
|
||||
|
||||
const GESTURE_GAP_MS = 150;
|
||||
/** Consecutive shrinking deltas after which the rest of the run is inertia. */
|
||||
const INERTIA_SHRINKS = 4;
|
||||
|
||||
type WheelLike = Pick<WheelEvent, "deltaY" | "metaKey" | "ctrlKey" | "timeStamp">;
|
||||
|
||||
let lastTime = Number.NEGATIVE_INFINITY;
|
||||
let run = { zoom: false, prev: 0, shrinks: 0, inertia: false };
|
||||
let lastEvent: WheelLike | null = null;
|
||||
let lastResult: number | null = null;
|
||||
|
||||
/**
|
||||
* The font zoom step for a wheel event: `1` / `-1` to zoom in / out, `0` for a ⌘/Ctrl
|
||||
* event of a zoom gesture that must neither zoom nor scroll (its inertia), `null` for one
|
||||
* that isn't a zoom (scroll as usual), which includes every event without ⌘/Ctrl. Repeated calls for one event agree.
|
||||
*/
|
||||
export function wheelZoomStep(e: WheelLike): number | null {
|
||||
if (e === lastEvent) return lastResult;
|
||||
const mod = e.metaKey || e.ctrlKey;
|
||||
const abs = Math.abs(e.deltaY);
|
||||
if (e.timeStamp - lastTime > GESTURE_GAP_MS) {
|
||||
run = { zoom: mod, prev: abs, shrinks: 0, inertia: false };
|
||||
} else {
|
||||
run.shrinks = abs < run.prev ? run.shrinks + 1 : 0;
|
||||
run.prev = abs;
|
||||
if (run.shrinks >= INERTIA_SHRINKS) run.inertia = true;
|
||||
}
|
||||
lastTime = e.timeStamp;
|
||||
lastEvent = e;
|
||||
lastResult = !mod || !run.zoom ? null : e.deltaY === 0 || run.inertia ? 0 : e.deltaY < 0 ? 1 : -1;
|
||||
return lastResult;
|
||||
}
|
||||
|
||||
// Track every wheel event, not only those reaching a zoom surface, so a scroll that started
|
||||
// elsewhere and coasts into one is still known as a scroll.
|
||||
if (typeof window !== "undefined") {
|
||||
window.addEventListener("wheel", (e) => void wheelZoomStep(e), {
|
||||
capture: true,
|
||||
passive: true,
|
||||
});
|
||||
}
|
||||
|
||||
/** Tests: forget the current gesture. */
|
||||
export function resetWheelZoomGesture(): void {
|
||||
lastTime = Number.NEGATIVE_INFINITY;
|
||||
lastEvent = null;
|
||||
lastResult = null;
|
||||
}
|
||||
@@ -59,6 +59,8 @@ export interface CommitSettingsValid {
|
||||
disabledPluginChecks: string[];
|
||||
/** Double-click opens the diff (`true`), the source file (`false`), or follows the interface (`null`). */
|
||||
doubleClickOpensDiff: boolean | null;
|
||||
/** Team conventions for Generate Commit Message with Agent, added to its prompt. */
|
||||
agentInstructions: string;
|
||||
}
|
||||
|
||||
export interface VcsSettingsValid {
|
||||
@@ -274,6 +276,7 @@ export const DEFAULT_WORKFLOW: WorkflowSettings = {
|
||||
wrapAtMargin: false,
|
||||
disabledPluginChecks: [],
|
||||
doubleClickOpensDiff: null,
|
||||
agentInstructions: "",
|
||||
},
|
||||
confirmation: {
|
||||
onCreate: "ask",
|
||||
@@ -433,6 +436,7 @@ export function validateVcs(raw: unknown): VcsSettingsValid {
|
||||
wrapAtMargin: bool(c.wrapAtMargin, d.commit.wrapAtMargin),
|
||||
disabledPluginChecks: strings(c.disabledPluginChecks, d.commit.disabledPluginChecks),
|
||||
doubleClickOpensDiff: tri(c.doubleClickOpensDiff),
|
||||
agentInstructions: text(c.agentInstructions, d.commit.agentInstructions),
|
||||
},
|
||||
confirmation: {
|
||||
onCreate: oneOf(conf.onCreate, confirm, d.confirmation.onCreate),
|
||||
|
||||
@@ -86,8 +86,15 @@
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* The per-tab detach button mirrors .close on the right edge, centred like it by the row. */
|
||||
.detach {
|
||||
position: absolute;
|
||||
right: var(--stripe-outer-padding);
|
||||
top: 0;
|
||||
right: 6px;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
opacity: 0;
|
||||
}
|
||||
.item:hover .detach,
|
||||
.item:focus-within .detach {
|
||||
opacity: 1;
|
||||
}
|
||||
@@ -64,3 +64,24 @@ it("offers closing the other tabs and those on either side of the clicked tab",
|
||||
expect(executeAction).toHaveBeenLastCalledWith("window.closeTabsToLeft", "project-1");
|
||||
expect(menuFor("Docs")("Close Tabs to the Right").disabled).toBe(true);
|
||||
});
|
||||
|
||||
it("moves any tab to a new window from its own arrow, without selecting it first", () => {
|
||||
render(<WindowGroupTabs />);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Move Backend to New Window" }));
|
||||
expect(executeAction).toHaveBeenLastCalledWith("window.detachTab", "project-1");
|
||||
expect(executeAction).not.toHaveBeenCalledWith("window.selectTab", "project-1");
|
||||
});
|
||||
|
||||
it("offers Move Tab to New Window for every tab in its context menu", () => {
|
||||
render(<WindowGroupTabs />);
|
||||
fireEvent.contextMenu(screen.getByRole("tab", { name: "Backend" }));
|
||||
const item = useContextMenuStore
|
||||
.getState()
|
||||
.menu!.items.find((i) => "label" in i && i.label === "Move Tab to New Window") as {
|
||||
disabled?: boolean;
|
||||
run?: () => unknown;
|
||||
};
|
||||
expect(item.disabled).toBeUndefined();
|
||||
void item.run?.();
|
||||
expect(executeAction).toHaveBeenLastCalledWith("window.detachTab", "project-1");
|
||||
});
|
||||
@@ -102,8 +102,7 @@ export function WindowGroupTabs() {
|
||||
showContextMenu(e, [
|
||||
{
|
||||
label: "Move Tab to New Window",
|
||||
disabled: !tab.current,
|
||||
run: () => executeAction("window.detachTab"),
|
||||
run: () => executeAction("window.detachTab", tab.label),
|
||||
},
|
||||
{ kind: "separator" },
|
||||
{
|
||||
@@ -156,15 +155,16 @@ export function WindowGroupTabs() {
|
||||
title={tx`Close ${tab.name}`}
|
||||
onClick={() => run(executeAction("window.closeTab", tab.label))}
|
||||
/>
|
||||
<IconButton
|
||||
icon="external-link"
|
||||
size="small"
|
||||
className={styles.detach}
|
||||
title={tx`Move ${tab.name} to New Window`}
|
||||
onClick={() => run(executeAction("window.detachTab", tab.label))}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<IconButton
|
||||
className={styles.detach}
|
||||
icon="external-link"
|
||||
title="Move Tab to New Window"
|
||||
action="window.detachTab"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { installFullscreenEscapeGuard } from "./fullscreenEscape";
|
||||
|
||||
let fullscreen = true;
|
||||
let dispose = () => {};
|
||||
const escape = (target: EventTarget) => {
|
||||
const e = new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true });
|
||||
target.dispatchEvent(e);
|
||||
return e;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
fullscreen = true;
|
||||
usePlatform.setState({ os: "macos" });
|
||||
dispose = installFullscreenEscapeGuard(window, () => fullscreen);
|
||||
});
|
||||
afterEach(() => {
|
||||
dispose();
|
||||
document.body.replaceChildren();
|
||||
});
|
||||
|
||||
describe("Escape in full screen", () => {
|
||||
it("is marked handled when nothing handles it, so the window stays in full screen", () => {
|
||||
expect(escape(document.body).defaultPrevented).toBe(true);
|
||||
});
|
||||
|
||||
it("is marked handled when a handler stops it", () => {
|
||||
const popup = document.body.appendChild(document.createElement("div"));
|
||||
popup.addEventListener("keydown", (e) => e.stopPropagation());
|
||||
expect(escape(popup).defaultPrevented).toBe(true);
|
||||
// The next key press is not affected by a listener left behind.
|
||||
fullscreen = false;
|
||||
expect(escape(document.body).defaultPrevented).toBe(false);
|
||||
});
|
||||
|
||||
it("reaches other handlers not yet default-prevented", () => {
|
||||
let seen: boolean | null = null;
|
||||
const onKey = (e: KeyboardEvent) => (seen = e.defaultPrevented);
|
||||
window.addEventListener("keydown", onKey);
|
||||
escape(document.body);
|
||||
window.removeEventListener("keydown", onKey);
|
||||
expect(seen).toBe(false);
|
||||
});
|
||||
|
||||
it("is left alone outside full screen and on other systems", () => {
|
||||
fullscreen = false;
|
||||
expect(escape(document.body).defaultPrevented).toBe(false);
|
||||
fullscreen = true;
|
||||
usePlatform.setState({ os: "windows" });
|
||||
expect(escape(document.body).defaultPrevented).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* macOS: an Escape key press the page leaves unhandled (not default-prevented) goes back from
|
||||
* WebKit to AppKit as the web view's `cancelOperation:`, and AppKit answers it in a full-screen
|
||||
* window by leaving full screen, so pressing Escape once more after closing a popup dropped the
|
||||
* IDE out of full screen. While this window is in full screen, Escape is marked handled after
|
||||
* everything else has seen it; View › Appearance › Toggle Full Screen (⌃⌘F) leaves full screen.
|
||||
*/
|
||||
import { commands, isTauri, onIdeEvent } from "@/platform/ipc";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
|
||||
/** Installs the guard on `target`; `isFullscreen` is this window's state (tests pass their own). */
|
||||
export function installFullscreenEscapeGuard(
|
||||
target: Window = window,
|
||||
isFullscreen: () => boolean = trackFullscreen(),
|
||||
): () => void {
|
||||
const onCapture = (e: KeyboardEvent) => {
|
||||
if (e.key !== "Escape" || e.isComposing || usePlatform.getState().os !== "macos" || !isFullscreen()) return;
|
||||
// Runs last in the bubble phase: handlers that check `defaultPrevented` see the event as it was.
|
||||
const handled = () => e.preventDefault();
|
||||
target.addEventListener("keydown", handled, { once: true });
|
||||
// A handler that stops the event has handled it; the bubble listener above won't run then.
|
||||
for (const name of ["stopPropagation", "stopImmediatePropagation"] as const) {
|
||||
const stop = e[name].bind(e);
|
||||
e[name] = () => {
|
||||
target.removeEventListener("keydown", handled);
|
||||
e.preventDefault();
|
||||
stop();
|
||||
};
|
||||
}
|
||||
};
|
||||
// Capture on the window before anything else is installed: it runs first.
|
||||
target.addEventListener("keydown", onCapture, true);
|
||||
return () => target.removeEventListener("keydown", onCapture, true);
|
||||
}
|
||||
|
||||
function trackFullscreen(): () => boolean {
|
||||
let fullscreen = false;
|
||||
if (!isTauri()) return () => fullscreen;
|
||||
const sync = () =>
|
||||
void commands
|
||||
.windowIsFullscreen()
|
||||
.then((on) => (fullscreen = on))
|
||||
.catch(() => {});
|
||||
sync();
|
||||
onIdeEvent("windowFullscreenChanged", sync);
|
||||
return () => fullscreen;
|
||||
}
|
||||
Reference in new issue
Заблокувати користувача