Порівняти коміти

..
Автор SHA1 Повідомлення Дата
l0ng-ai 2ab0d55c80 fix(vue): don't indent code in top-level <script> and <style> blocks
Pressing Enter in <script setup> indented the new line one level, because
the HTML base indents every element's children. WebStorm's Vue code style
indents the children of the top-level <template> only, so code in
<script> and <style> starts at the margin, as npm create vue writes it.

Fixes #3982
2026-11-17 21:10:26 +08:00
90 змінених файлів з 259 додано та 4246 видалено

No files matched your search

-3
Переглянути файл
@@ -135,8 +135,6 @@ 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 {
@@ -158,7 +156,6 @@ impl Default for CommitSettings {
wrap_at_margin: false,
disabled_plugin_checks: Vec::new(),
double_click_opens_diff: None,
agent_instructions: String::new(),
}
}
}
+1 -1
Переглянути файл
@@ -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", PS_FORMAT], QUICK));
let c = s.spawn(|| run(ep, &["ps", "--all", "--no-trunc", "--format", FMT], 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));
+1 -11
Переглянути файл
@@ -226,16 +226,6 @@ 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 {
@@ -257,7 +247,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` [`PS_FORMAT`] (or `'{{json .}}'`).
/// `docker ps -a --no-trunc --format '{{json .}}'`.
pub fn parse_containers(text: &str) -> Vec<DockerContainer> {
let mut out: Vec<DockerContainer> = lines::<RawContainer>(text)
.map(|r| {
+2 -23
Переглянути файл
@@ -1,8 +1,8 @@
//! Parsing of recorded `docker … --format '{{json .}}'` output.
use ide_docker::{
PS_FORMAT, parse_container_stats, parse_container_top, parse_containers, parse_image_history, parse_images,
parse_networks, parse_volumes,
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,27 +10,6 @@ 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);
+28 -41
Переглянути файл
@@ -5,7 +5,7 @@ use ide_extension::Capability;
use ide_plugin::{EventKind, HostError, WorkbenchEvent};
use std::{
collections::{BTreeSet, HashMap},
path::{Path, PathBuf},
path::Path,
};
#[derive(Clone, Default)]
@@ -136,14 +136,32 @@ impl PluginHost {
if !path.is_absolute() {
return None;
}
let root = file_project(workspace.as_deref()?, client, path)?;
let workspace = workspace.as_ref()?;
let real = ide_plugin::resolve_real(path);
// The file's own project, not the invoking window's: annotations follow
// the file, so a plugin hears about a file another window has open.
let root = match client {
Some(client) => workspace
.project_of(client)
.filter(|r| real.starts_with(ide_plugin::resolve_real(r)))
.or_else(|| {
workspace
.projects()
.into_iter()
.filter(|r| real.starts_with(ide_plugin::resolve_real(r)))
.max_by_key(|r| r.components().count())
}),
None => workspace
.projects()
.into_iter()
.filter(|r| real.starts_with(ide_plugin::resolve_real(r)))
.max_by_key(|r| r.components().count()),
}?;
if plugin.dev_root.as_deref().is_some_and(|r| r != root) {
return None;
}
if let WorkbenchEvent::DocumentChanged(_) = event {
if let WorkbenchEvent::DocumentChanged(change) = event {
// Typed text: only for plugins that may read editors, and only for paths they named.
// The path stays absolute until delivery (`relativize_documents`): the batch is
// filtered again then, against the grants and subscriptions of that moment.
let filter = filters.and_then(|filters| filters.get(event.kind().name()))?;
let granted = &plugin.meta.lock().granted;
if !granted.contains(&Capability::ProjectRead)
@@ -152,7 +170,11 @@ impl PluginHost {
{
return None;
}
return Some(event.clone());
let real = ide_plugin::resolve_real(path);
let relative = real.strip_prefix(ide_plugin::resolve_real(&root)).ok()?;
let mut change = change.clone();
change.path = relative.to_string_lossy().replace('\\', "/");
return Some(WorkbenchEvent::DocumentChanged(change));
}
filters
.and_then(|filters| filters.get(event.kind().name()))
@@ -161,41 +183,6 @@ impl PluginHost {
})
.collect()
}
/// What a plugin receives for `document-changed`: the path relative to the file's own project.
pub(super) fn relativize_documents(
shared: &super::api::Shared,
client: Option<&str>,
events: Vec<WorkbenchEvent>,
) -> Vec<WorkbenchEvent> {
let workspace = shared.workspace();
events
.into_iter()
.filter_map(|event| {
let WorkbenchEvent::DocumentChanged(mut change) = event else { return Some(event) };
let path = Path::new(&change.path);
let root = file_project(workspace.as_deref()?, client, path)?;
let relative = ide_plugin::resolve_real(path)
.strip_prefix(ide_plugin::resolve_real(&root))
.ok()?
.to_string_lossy()
.replace('\\', "/");
change.path = relative;
Some(WorkbenchEvent::DocumentChanged(change))
})
.collect()
}
}
/// The open project an absolute `path` belongs to: the invoking window's when the file is in
/// it, else the innermost open project containing it. Annotations follow the file, so a
/// plugin hears about a file another window has open.
fn file_project(workspace: &dyn super::api::PluginWorkspace, client: Option<&str>, path: &Path) -> Option<PathBuf> {
let real = ide_plugin::resolve_real(path);
let contains = |r: &PathBuf| real.starts_with(ide_plugin::resolve_real(r));
client
.and_then(|client| workspace.project_of(client).filter(contains))
.or_else(|| workspace.projects().into_iter().filter(contains).max_by_key(|r| r.components().count()))
}
#[cfg(test)]
+3 -7
Переглянути файл
@@ -33,10 +33,10 @@ struct Decl {
}
#[derive(Clone, Debug)]
pub(super) struct Agent {
struct Agent {
/// The jar, resolved inside the package.
pub(super) jar: PathBuf,
pub(super) args: Option<String>,
jar: PathBuf,
args: Option<String>,
}
/// Agents of enabled plugins.
@@ -47,10 +47,6 @@ 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));
-21
Переглянути файл
@@ -2214,7 +2214,6 @@ impl PluginHost {
if events.is_empty() {
return Ok(());
}
let events = Self::relativize_documents(&shared, invocation.client.as_deref(), events);
rt.handle_events(events, invocation)
},
move |result| {
@@ -3088,26 +3087,6 @@ 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),
-14
Переглянути файл
@@ -55,18 +55,6 @@ 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 {
@@ -78,8 +66,6 @@ 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,
-32
Переглянути файл
@@ -2204,10 +2204,6 @@ 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());
@@ -2221,7 +2217,6 @@ 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();
@@ -2233,11 +2228,7 @@ 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.
@@ -5284,29 +5275,6 @@ fn plugin_readonly_fields_and_table_row_extensions_round_trip() {
}
}
#[test]
fn document_changes_reach_plugins_relative_to_the_project() {
let f = fixture(Limits::default());
f.install(&sample("path-events"));
f.run("test.path-events", "count", None).unwrap();
let deliver = |path: &str| {
let change = ide_plugin::DocumentChanged {
path: to_ipc(&f.project.join(path)),
base_version: 1,
version: 2,
changes: Vec::new(),
};
f.host.post_events(Some("main"), vec![WorkbenchEvent::DocumentChanged(change)]);
f.host.flush_events_at(Instant::now() + Duration::from_secs(3));
assert!(f.host.wait_events(Duration::from_secs(10)));
};
deliver("src/main.rs");
assert_eq!(f.run("test.path-events", "document", None).unwrap(), None, "outside the subscribed paths");
// Queued with the absolute path, filtered again at delivery, handed over project-relative.
deliver("config/app.yaml");
assert_eq!(f.run("test.path-events", "document", None).unwrap().as_deref(), Some("config/app.yaml"));
}
#[test]
fn path_filtered_events_do_not_wake_idle_plugins_and_recheck_queued_filters() {
let f = fixture(Limits { idle_timeout: Some(Duration::from_millis(100)), ..Limits::default() });
+33 -461
Переглянути файл
@@ -68,7 +68,7 @@ pub(crate) struct Shared {
pub store: Option<Store>,
pub indexing: AtomicBool,
pub cancelled: AtomicBool,
/// Non-cached content reads, including binary/unsupported files; used by tests.
/// Files whose content was (re)read and parsed; observability for tests.
pub parsed: std::sync::atomic::AtomicUsize,
queue: Mutex<Queue>,
wake: Condvar,
@@ -160,38 +160,14 @@ 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.
let snapshot_started = Instant::now();
let fast = self.try_fast_start();
let snapshot_elapsed = snapshot_started.elapsed();
if !fast {
if !self.try_fast_start() {
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);
@@ -258,7 +234,6 @@ 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) };
@@ -290,7 +265,6 @@ 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())
@@ -328,16 +302,9 @@ impl Shared {
d.load_bulk(entries, dirs);
drop(d);
tracing::info!(
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"
"index snapshot: warm start in {:?} (load {loaded:?}, validate/build {built:?}, insert {:?})",
started.elapsed(),
insert_started.elapsed()
);
#[cfg(test)]
eprintln!(
@@ -474,7 +441,7 @@ impl Shared {
self.scan(None, found, guard);
}
fn scan(&self, dirs: Option<&[PathBuf]>, prewalked: Option<Vec<Found>>, guard: SystemTime) -> Option<ScanCounts> {
fn scan(&self, dirs: Option<&[PathBuf]>, prewalked: Option<Vec<Found>>, guard: SystemTime) {
let started = Instant::now();
self.indexing.store(true, Ordering::SeqCst);
self.emit_state();
@@ -490,12 +457,10 @@ 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() {
self.end_scan(task);
return None;
return self.end_scan(task);
}
let classify_started = Instant::now();
let seen: HashSet<&Path> = found.iter().map(|f| f.path.as_path()).collect();
@@ -522,7 +487,6 @@ 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
@@ -582,14 +546,11 @@ impl Shared {
laps.extract = pass_started.elapsed();
}
if self.is_cancelled() {
self.end_scan(task);
return None;
return self.end_scan(task);
}
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();
@@ -602,7 +563,6 @@ 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 {
@@ -614,47 +574,20 @@ 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!(
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"
"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
);
Some(counts)
}
/// Extracts records in parallel, then publishes them to memory and disk.
@@ -666,7 +599,6 @@ 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;
}
@@ -690,9 +622,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, extraction) => {
Extracted::New(rec) => {
let bytes = key.as_ref().and_then(|_| postcard::to_allocvec(&rec).ok());
ParsedOutcome::New { rec, bytes, extraction }
ParsedOutcome::New { rec, bytes }
}
};
Some(ParsedFile { rel, key, outcome, path: f.path.clone() })
@@ -708,8 +640,7 @@ impl Shared {
for out in batch {
let ParsedFile { rel, key, outcome, path } = out;
match outcome {
ParsedOutcome::New { rec, bytes, extraction } => {
laps.outcomes.record(extraction);
ParsedOutcome::New { rec, bytes } => {
if let (Some(key), Some(bytes)) = (key, bytes) {
puts.push((key, bytes));
}
@@ -727,13 +658,10 @@ 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) {
laps.outcomes.record(Extraction::HashReused);
if let Some(key) = r.key {
refreshed_records.push((key, rec));
}
} else {
laps.outcomes.not_processed += 1;
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));
}
}
}
@@ -798,18 +726,15 @@ 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 {
return Extracted::New(rec, Extraction::Ignored);
}
if f.size > MAX_SYMBOL_FILE {
return Extracted::New(rec, Extraction::Oversized);
if f.ignored || f.size > MAX_SYMBOL_FILE {
return Extracted::New(rec);
}
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, Extraction::ReadFailed);
return Extracted::New(rec);
}
}
rec.hash = *blake3::hash(&bytes).as_bytes();
@@ -818,7 +743,7 @@ impl Shared {
}
self.parsed.fetch_add(1, Ordering::Relaxed);
if bytes[..bytes.len().min(8192)].contains(&0) {
return Extracted::New(rec, Extraction::Binary);
return Extracted::New(rec);
}
let text = String::from_utf8_lossy(&bytes);
let lang = self.languages.detect(&f.path, Some(first_line(&text)));
@@ -835,9 +760,8 @@ impl Shared {
bases: t.bases,
})
.collect();
return Extracted::New(rec, Extraction::Symbols);
}
Extracted::New(rec, Extraction::Unsupported)
Extracted::New(rec)
}
fn process(&self, jobs: Vec<Job>) {
@@ -1014,7 +938,7 @@ fn first_line(text: &str) -> &str {
enum Extracted {
/// Content hash matches the indexed version.
Unchanged,
New(FileRecord, Extraction),
New(FileRecord),
}
/// Wall-time laps of one `index_files` chunk, accumulated by the scan.
@@ -1023,7 +947,6 @@ struct ChunkLaps {
extract: Duration,
insert: Duration,
persist: Duration,
outcomes: ExtractionCounts,
}
impl ChunkLaps {
@@ -1031,7 +954,6 @@ impl ChunkLaps {
self.extract += other.extract;
self.insert += other.insert;
self.persist += other.persist;
self.outcomes.add(other.outcomes);
}
}
@@ -1045,7 +967,7 @@ struct MetadataRefresh {
enum ParsedOutcome {
Unchanged { mtime: u64, size: u64, ignored: bool },
New { rec: FileRecord, bytes: Option<Vec<u8>>, extraction: Extraction },
New { rec: FileRecord, bytes: Option<Vec<u8>> },
}
/// One file parsed off the index thread: its outcome ready to publish, with new
@@ -1058,356 +980,6 @@ 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;
-2
Переглянути файл
@@ -90,7 +90,6 @@ const BUILTIN: &[(&str, &str)] = &[
("toml", include_str!("../../../languages/toml.toml")),
("typescript", include_str!("../../../languages/typescript.toml")),
("typescriptreact", include_str!("../../../languages/typescriptreact.toml")),
("typst", include_str!("../../../languages/typst.toml")),
("vue", include_str!("../../../languages/vue.toml")),
("xml", include_str!("../../../languages/xml.toml")),
("yaml", include_str!("../../../languages/yaml.toml")),
@@ -613,7 +612,6 @@ mod tests {
"TTCN",
"TTCN_CFG",
"Turtle",
"Typst",
"Web IDL",
"VB.NET",
"VBScript",
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
872f94f4bbc441457f36ed7b44b3a2fb6b87021f2f0a66104caf5c807b524147
f9c0cb4fca66ede5adcb1951dd05c3938c218224cb61e63a574ba08a93f4a041
+2 -6
Переглянути файл
@@ -1,13 +1,13 @@
id = "test.path-events"
name = "Path event fixture"
version = "0.1.0"
engines.openidea = "^1.6"
engines.openidea = "^1.3"
wasm = "dist/plugin.wasm"
activation = ["on-command:*"]
[capabilities]
required = ["storage"]
optional = ["events", "project.read", "editor.read"]
optional = ["events", "project.read"]
[[contributes.providers]]
kinds = ["hover"]
@@ -29,10 +29,6 @@ title = "all"
id = "off"
title = "off"
[[contributes.commands]]
id = "document"
title = "document"
[[contributes.commands]]
id = "count"
title = "count"
-7
Переглянути файл
@@ -11,7 +11,6 @@ impl Plugin for Fixture {
let globs: Vec<_> = glob.lines().collect();
let _ = host::subscribe_paths("file-opened", &globs);
let _ = host::subscribe_paths("file-saved", &["config/*.yaml"]);
let _ = host::subscribe_paths("document-changed", &["config/*.yaml"]);
Ok(())
}
fn run_command(&mut self, id: &str, _: &Invocation, arg: Option<&str>) -> Result<Option<String>, Error> {
@@ -32,18 +31,12 @@ impl Plugin for Fixture {
Ok(None)
}
"count" => Ok(host::storage::get("count")?),
"document" => Ok(host::storage::get("document")?),
_ => Err(Error::NotFound(id.into())),
}
}
fn handle_events(&mut self, events: &[Event], _: &Invocation) {
let count = host::storage::get("count").ok().flatten().and_then(|n| n.parse::<usize>().ok()).unwrap_or(0);
host::storage::set("count", &(count + events.len()).to_string()).unwrap();
for event in events {
if let Event::DocumentChanged(change) = event {
host::storage::set("document", &change.path).unwrap();
}
}
}
}
impl HoverProvider for Fixture {
+51 -190
Переглянути файл
@@ -13,18 +13,12 @@ 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) {
@@ -115,51 +109,52 @@ struct Executable {
source: Option<String>,
}
/// `.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.
/// `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.
fn executables(src: &str) -> Vec<Executable> {
let mut out: Vec<Executable> = Vec::new();
for (start, _) in src.match_indices("addExecutable(") {
let body = call_body(src, start + "addExecutable(".len());
let (name, source) = add_executable_fields(body);
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()..]);
}
}
_ => {}
}
}
if let Some(name) = name
&& !name.is_empty()
&& !out.iter().any(|e| e.name == name)
@@ -170,109 +165,6 @@ 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);
@@ -363,7 +255,14 @@ fn test_roots(src: &str) -> Vec<(String, String)> {
tests.push((var.to_owned(), root));
}
}
let steps = step_vars(src);
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 mut out: Vec<(String, String)> = Vec::new();
for (i, _) in src.match_indices(".dependOn(&") {
let Some(step) = receiver_var(src, i + 1) else { continue };
@@ -426,7 +325,6 @@ 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);
@@ -460,11 +358,6 @@ 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" }));
@@ -507,36 +400,4 @@ 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"));
}
}
-22
Переглянути файл
@@ -992,28 +992,6 @@ pub static TOOLS: &[ToolSpec] = &[
homepage: "https://github.com/latex-lsp/texlab",
needs: &[],
},
ToolSpec {
name: "tinymist",
display: "Tinymist (Typst)",
kind: LanguageServer,
commands: &["tinymist"],
method: Method::Release {
source: ReleaseSource::GitHub { repo: "Myriad-Dreamin/tinymist" },
assets: &[
rule(Mac, Arm64, "tinymist-aarch64-apple-darwin.tar.gz"),
rule(Mac, X64, "tinymist-x86_64-apple-darwin.tar.gz"),
rule(Linux, X64, "tinymist-x86_64-unknown-linux-gnu.tar.gz"),
rule(Linux, Arm64, "tinymist-aarch64-unknown-linux-gnu.tar.gz"),
rule(Windows, X64, "tinymist-x86_64-pc-windows-msvc.zip"),
rule(Windows, Arm64, "tinymist-aarch64-pc-windows-msvc.zip"),
],
locate: &["tinymist"],
},
fallback: None,
version: ver("tinymist"),
homepage: "https://myriad-dreamin.github.io/tinymist/",
needs: &[],
},
ToolSpec {
name: "slint-lsp",
display: "Slint LSP",
+1 -8
Переглянути файл
@@ -360,10 +360,6 @@ 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.
@@ -533,12 +529,9 @@ pub enum CheckoutOutcome {
LocalChanges {
files: Vec<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).
/// These untracked files (repository-relative paths) would be overwritten.
UntrackedFiles {
files: Vec<String>,
removed: bool,
},
/// Local branch `local` has commits that remote branch `remote` does not.
LocalBranchAhead {
+1 -9
Переглянути файл
@@ -158,15 +158,7 @@ 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;
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,
});
out.push(Stash { index: index as u32, message: to_string(line.message.as_ref()), time_ms });
}
Ok(out)
}
+5 -10
Переглянути файл
@@ -771,14 +771,9 @@ 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 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))
/// 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")
}
/// The branch git refused to check out or update because another worktree has it, from
@@ -845,8 +840,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, removed)) = refused_untracked(&stderr) {
return Ok(CheckoutOutcome::UntrackedFiles { files, removed });
if let Some(files) = overwritten_untracked(&stderr) {
return Ok(CheckoutOutcome::UntrackedFiles { files });
}
let Some(files) = overwritten_files(&stderr) else {
return Err(cli::failure(&argv, &out.stderr, &out.stdout, out.code));
+1 -31
Переглянути файл
@@ -849,11 +849,6 @@ 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");
@@ -2079,37 +2074,12 @@ 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()], removed: false });
assert_eq!(outcome, CheckoutOutcome::UntrackedFiles { files: vec!["dir/new.txt".into()] });
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();
-1
Переглянути файл
@@ -846,7 +846,6 @@ mod tests {
"wrapAtMargin": false,
"disabledPluginChecks": [],
"doubleClickOpensDiff": null,
"agentInstructions": "",
})
);
}
-8
Переглянути файл
@@ -129,14 +129,6 @@ 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.
-1
Переглянути файл
@@ -172,7 +172,6 @@ The table lists every built-in language definition. Server and debugger names in
| TOML | `toml` | `.toml` | Yes | Yes | **taplo** | — |
| TypeScript | `typescript` | `.ts`, `.mts`, `.cts` | Yes | Yes | **vtsls** → **typescript-language-server** + **angular-language-server** + **oxlint** | **js-debug** |
| TypeScript JSX | `typescriptreact` | `.tsx` | Yes | Yes | **vtsls** → **typescript-language-server** + **oxlint** | **js-debug** |
| Typst | `typst` | `.typ` | — | — | **tinymist** | — |
| Vue | `vue` | `.vue` | Yes | — | **vue-language-server**, **vtsls** + **oxlint** | — |
| XML | `xml` | `.xml`, `.xsd`, `.xsl`, `.xslt`, `.svg`, … | Yes | Yes | **lemminx** | — |
| YAML | `yaml` | `.yaml`, `.yml` | Yes | Yes | **yaml-language-server** | — |
-8
Переглянути файл
@@ -129,14 +129,6 @@ 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`)和请求前脚本。处理脚本行能被识别,但会跳过。
-1
Переглянути файл
@@ -167,7 +167,6 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自
| TOML | `toml` | `.toml` | 是 | 是 | **taplo** | — |
| TypeScript | `typescript` | `.ts`, `.mts`, `.cts` | 是 | 是 | **vtsls** → **typescript-language-server** + **angular-language-server** + **oxlint** | **js-debug** |
| TypeScript JSX | `typescriptreact` | `.tsx` | 是 | 是 | **vtsls** → **typescript-language-server** + **oxlint** | **js-debug** |
| Typst | `typst` | `.typ` | — | — | **tinymist** | — |
| Vue | `vue` | `.vue` | 是 | — | **vue-language-server**, **vtsls** + **oxlint** | — |
| XML | `xml` | `.xml`, `.xsd`, `.xsl`, `.xslt`, `.svg`, … | 是 | 是 | **lemminx** | — |
| YAML | `yaml` | `.yaml`, `.yml` | 是 | 是 | **yaml-language-server** | — |
-113
Переглянути файл
@@ -1,113 +0,0 @@
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"');
});
-14
Переглянути файл
@@ -1,14 +0,0 @@
id = "typst"
name = "Typst"
extensions = ["typ"]
line-comment = "//"
block-comment = ["/*", "*/"]
indent = { tab-size = 2, insert-spaces = true }
ui-mode = "Typst"
[[language-servers]]
name = "tinymist"
command = "tinymist"
args = ["lsp"]
root-markers = ["typst.toml"]
install-hint = "cargo install --locked --git https://github.com/Myriad-Dreamin/tinymist tinymist-cli (or brew install tinymist)"
+2 -4
Переглянути файл
@@ -2217,10 +2217,8 @@ 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. 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
`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
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**
+2 -3
Переглянути файл
@@ -29,9 +29,8 @@ 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, label: String) -> IdeResult<()> {
groups::select(window.app_handle(), window.label(), &label)?;
groups::detach(window.app_handle(), &label)?;
pub async fn window_group_detach(window: WebviewWindow) -> IdeResult<()> {
groups::detach(window.app_handle(), window.label())?;
groups::persist(window.app_handle()).await
}
+3 -25
Переглянути файл
@@ -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: (label: string) => typedError<null, IdeError>(__TAURI_INVOKE("window_group_detach", { label })),
windowGroupDetach: () => typedError<null, IdeError>(__TAURI_INVOKE("window_group_detach")),
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,12 +3293,8 @@ 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 by the
* checkout; with `removed`, they would be removed by it (tracked here, absent
* from the target).
*/
{ kind: "untrackedFiles"; files: string[]; removed: boolean } |
/** These untracked files (repository-relative paths) would be overwritten. */
{ kind: "untrackedFiles"; files: string[] } |
/** Local branch `local` has commits that remote branch `remote` does not. */
{ kind: "localBranchAhead"; local: string; remote: string } |
/**
@@ -3583,8 +3579,6 @@ 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 = {
@@ -8882,8 +8876,6 @@ 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,
@@ -8918,16 +8910,6 @@ 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.
@@ -10799,10 +10781,6 @@ 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. */
+13 -18
Переглянути файл
@@ -570,24 +570,14 @@ function copyReference(reference: Promise<string>) {
}
}
/** 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;
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 { doc, selection } = view.state;
const line = doc.lineAt(selection.main.head).number;
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));
const contributed = menuGroupItems("copyPath", {
paths: [path],
line: first - 1,
@@ -613,7 +603,7 @@ function copyPathReferencePopup(view: EditorView, slot: EditorSlot) {
{
id: "editor.copyPathWithLineNumber",
label: "Path with line number",
value: pathWithLines(view.state, path),
value: `${pathToCopy("relative", path)}:${line}`,
},
];
const popup: Extract<LspPopup, { kind: "list" }> = {
@@ -1290,7 +1280,12 @@ export function registerEditorActions(): () => void {
when: TEXT_WHEN,
run: ({ arg }) => {
if (typeof arg === "string") copyEditorPath(arg);
else withView((view, slot) => copyEditorPath(pathWithLines(view.state, slot.model.path)))();
else
withView((view, slot) =>
copyEditorPath(
`${pathToCopy("relative", slot.model.path)}:${view.state.doc.lineAt(view.state.selection.main.head).number}`,
),
)();
},
},
{
+1 -184
Переглянути файл
@@ -1,10 +1,8 @@
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 { fencedCodeMode, findLanguageDescription, loadSupport } from "./languages";
import { findLanguageDescription, loadSupport } from "./languages";
describe("language modes", () => {
it("distinguishes PHP classes, method declarations and fields for imported schemes", async () => {
@@ -272,28 +270,6 @@ 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" },
@@ -333,163 +309,4 @@ 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"],
]);
}
});
it("colours Typst markup, embedded code and math", async () => {
const support = await loadSupport(findLanguageDescription("Typst", "/p/notes.typ")!);
const highlighter = tagHighlighter([
{ tag: t.keyword, class: "keyword" },
{ tag: t.comment, class: "comment" },
{ tag: t.heading, class: "heading" },
{ tag: t.strong, class: "strong" },
{ tag: t.emphasis, class: "emphasis" },
{ tag: t.string, class: "string" },
{ tag: t.number, class: "number" },
{ tag: t.function(t.variableName), class: "function" },
{ tag: t.labelName, class: "label" },
{ tag: t.monospace, class: "raw" },
{ tag: t.atom, class: "atom" },
]);
const source = [
"#set page(width: 10cm)",
"// note",
"= Intro <intro>",
"Some *bold* and _it_ in snake_case, `raw` and $x^2$ see @intro.",
"#let total = 1 + 2",
"#if true [yes]",
"```rust",
"let x = 1;",
"```",
].join("\n");
const found: string[] = [];
highlightTree(support!.language.parser.parse(source), highlighter, (from, to, cls) =>
found.push(`${source.slice(from, to)}:${cls}`),
);
expect(found).toEqual(
expect.arrayContaining([
"#set:keyword",
"page:function",
"10cm:number",
"// note:comment",
"= Intro :heading",
"<intro>:label",
"*bold*:strong",
"_it_:emphasis",
"`raw`:raw",
"$:keyword",
"@intro:label",
"#let:keyword",
"1:number",
"#if:keyword",
"true:atom",
"```rust:raw",
"let x = 1;:raw",
]),
);
expect(found.filter((f) => f.endsWith(":emphasis"))).toEqual(["_it_:emphasis"]);
expect(found).not.toContain("yes:keyword");
});
});
+3 -34
Переглянути файл
@@ -11,8 +11,6 @@ import {
LanguageDescription,
LanguageSupport,
StreamLanguage,
delimitedIndent,
indentNodeProp,
indentService,
language as languageFacet,
type StreamParser,
@@ -114,11 +112,6 @@ const OWN_MODES = [
extensions: ["rst"],
load: () => import("./restructuredtext").then((m) => new LanguageSupport(m.restructuredtextLanguage)),
}),
LanguageDescription.of({
name: "Typst",
extensions: ["typ"],
load: async () => new LanguageSupport(StreamLanguage.define((await import("./typst")).typstParser)),
}),
LanguageDescription.of({
name: "Gherkin",
extensions: ["feature"],
@@ -202,14 +195,6 @@ 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"],
@@ -428,28 +413,12 @@ 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 =
props.length && support.language instanceof LRLanguage ? support.language.configure({ props }) : support.language;
extra && support.language instanceof LRLanguage
? support.language.configure({ props: [styleTags(extra)] })
: support.language;
const result = new LanguageSupport(language, [
support.support,
docCommentTags(desc.name),
+2 -4
Переглянути файл
@@ -57,7 +57,6 @@ import { stringClipboard } from "./stringClipboard";
import { filterCopiedText } from "./clipboard";
import { LINE_INSET } from "./lineInset";
import { codeLensPositions } from "./codeLens";
import { wheelZoomStep } from "@/platform/wheelZoom";
// --- soft wraps ---------------------------------------------------------------
@@ -453,10 +452,9 @@ 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) {
const step = wheelZoomStep(e);
if (step === null) return false;
if (!e.metaKey && !e.ctrlKey) return false;
e.preventDefault();
if (step) stepConfiguredEditorsFontZoom(view, step);
stepConfiguredEditorsFontZoom(view, e.deltaY < 0 ? 1 : -1);
return true;
},
});
-38
Переглянути файл
@@ -1,38 +0,0 @@
/**
* `.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);
-337
Переглянути файл
@@ -1,337 +0,0 @@
// @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);
});
});
-160
Переглянути файл
@@ -1,160 +0,0 @@
/**
* 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: "#" } },
};
-321
Переглянути файл
@@ -1,321 +0,0 @@
/**
* Typst markup, code and math as Typst's own lexer splits them (typst-syntax `lexer.rs`): markup
* with `#` embedding a code expression, `[...]` content blocks and `$...$` math nesting in code
* and back. A `#keyword` statement lasts to the end of its line unless a bracket keeps it open.
*/
import type { StreamParser, StringStream } from "@codemirror/language";
type Frame =
/** Markup inside `[...]`; the document itself is the markup below every frame. */
| { kind: "content" }
/** Code in `(...)` or `{...}`, closed by `close`. */
| { kind: "code"; close: ")" | "}" }
/** A `#let` / `#set` / `#show` … statement, ending with its line. */
| { kind: "statement" }
/** An embedded `#name`: calls, content arguments and field accesses may follow it directly. */
| { kind: "expr" }
| { kind: "math" };
export interface TypstState {
stack: Frame[];
strong: boolean;
emph: boolean;
heading: boolean;
/** Nesting depth of an open block comment. */
comment: number;
/** The backtick fence of an open raw block. */
raw: string | null;
}
const KEYWORDS = new Set([
"let",
"set",
"show",
"context",
"if",
"else",
"for",
"in",
"while",
"break",
"continue",
"return",
"import",
"include",
"as",
"and",
"or",
"not",
]);
const ATOMS = new Set(["none", "auto", "true", "false"]);
const IDENT = /^[\p{L}_][\p{L}\p{N}_-]*/u;
const NUMBER = /^(?:0x[0-9a-fA-F]+|0o[0-7]+|0b[01]+|(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?(?:pt|mm|cm|in|em|fr|deg|rad|%)?)/;
const LABEL = /^<[\p{L}\p{N}_\-.:]+>/u;
const REF = /^@[\p{L}\p{N}_\-.:]*[\p{L}\p{N}_]/u;
const URL = /^https?:\/\/[^\s<>[\](){}"]*[^\s<>[\](){}".,;:!?'"]/;
const MARKUP_TEXT = /^[^\\#$*_`<@/[\]\nhH-]+/;
const top = (state: TypstState): Frame | undefined => state.stack[state.stack.length - 1];
function blockComment(stream: StringStream, state: TypstState): string {
while (!stream.eol()) {
if (stream.match("/*")) state.comment++;
else if (stream.match("*/")) {
if (--state.comment === 0) break;
} else stream.next();
}
return "comment";
}
function comment(stream: StringStream, state: TypstState): string | null {
if (stream.match("//")) {
stream.skipToEnd();
return "comment";
}
if (stream.match("/*")) {
state.comment = 1;
return blockComment(stream, state);
}
return null;
}
function string(stream: StringStream): string {
stream.next();
let escaped = false;
for (let ch = stream.next(); ch !== undefined; ch = stream.next()) {
if (ch === '"' && !escaped) break;
escaped = !escaped && ch === "\\";
}
return "string";
}
function raw(stream: StringStream, state: TypstState): string {
const fence = (stream.match(/^`+/) as RegExpMatchArray)[0];
if (fence.length === 2) return "monospace";
if (fence.length >= 3) {
state.raw = fence;
if (!stream.match(/^[\p{L}\p{N}_-]+/u)) return rawBody(stream, state);
return "monospace";
}
while (!stream.eol()) if (stream.next() === "`") break;
return "monospace";
}
function rawBody(stream: StringStream, state: TypstState): string {
const fence = state.raw!;
while (!stream.eol()) {
if (stream.match(fence)) {
state.raw = null;
break;
}
stream.next();
}
return "monospace";
}
/** `#` followed by a keyword, a name, or a bracketed expression. */
function embed(stream: StringStream, state: TypstState): string {
stream.next();
const word = stream.match(IDENT, false) as RegExpMatchArray | null;
if (word && KEYWORDS.has(word[0])) {
stream.pos += word[0].length;
state.stack.push({ kind: "statement" });
return "keyword";
}
if (word) {
state.stack.push({ kind: "expr" });
return name(stream);
}
const ch = stream.peek();
if (ch === "(" || ch === "{") {
stream.next();
state.stack.push({ kind: "code", close: ch === "(" ? ")" : "}" });
return "keyword";
}
if (ch === "[") {
stream.next();
state.stack.push({ kind: "content" });
return "keyword";
}
if (ch === '"') return string(stream);
return "keyword";
}
/** An identifier: a function when a call or content block follows, a value otherwise. */
function name(stream: StringStream): string {
const word = (stream.match(IDENT) as RegExpMatchArray)[0];
if (ATOMS.has(word)) return "atom";
const next = stream.peek();
return next === "(" || next === "[" ? "variableName.function" : "variableName";
}
function code(stream: StringStream, state: TypstState): string | null {
if (stream.eatSpace()) return null;
const c = comment(stream, state);
if (c) return c;
const ch = stream.peek()!;
if (ch === '"') return string(stream);
if (ch === "$") {
stream.next();
state.stack.push({ kind: "math" });
return "keyword";
}
if (ch === "(" || ch === "{") {
stream.next();
state.stack.push({ kind: "code", close: ch === "(" ? ")" : "}" });
return "bracket";
}
if (ch === "[") {
stream.next();
state.stack.push({ kind: "content" });
return "bracket";
}
const frame = top(state);
if (ch === ")" || ch === "}") {
stream.next();
if (frame?.kind === "code" && frame.close === ch) state.stack.pop();
return "bracket";
}
if (stream.match(LABEL)) return "labelName";
if (stream.match(NUMBER)) return "number";
const word = stream.match(IDENT, false) as RegExpMatchArray | null;
if (word) {
if (KEYWORDS.has(word[0])) {
stream.pos += word[0].length;
return "keyword";
}
return name(stream);
}
if (stream.match(/^(?:=>|==|!=|<=|>=|\+=|-=|\*=|\/=|\.\.|[-+*/=<>.:,;!])/)) return "operator";
stream.next();
return null;
}
/** What may directly follow an embedded name: `(args)`, `[content]` or `.field`. */
function exprTail(stream: StringStream, state: TypstState): string | null | undefined {
const ch = stream.peek();
if (ch === "(") {
stream.next();
state.stack.push({ kind: "code", close: ")" });
return "bracket";
}
if (ch === "[") {
stream.next();
state.stack.push({ kind: "content" });
return "bracket";
}
if (ch === "." && stream.match(/^\.(?=[\p{L}_])/u, false)) {
stream.next();
return name(stream);
}
state.stack.pop();
return undefined;
}
function math(stream: StringStream, state: TypstState): string | null {
if (stream.eatSpace()) return null;
const c = comment(stream, state);
if (c) return c;
const ch = stream.peek()!;
if (ch === "$") {
stream.next();
state.stack.pop();
return "keyword";
}
if (ch === "#") return embed(stream, state);
if (ch === "\\") {
stream.next();
stream.next();
return "escape";
}
if (ch === '"') return string(stream);
if (stream.match(/^\d+(?:\.\d+)?/)) return "number";
if (stream.match(/^[\p{L}][\p{L}.]+/u)) return "variableName";
if (stream.match(/^[\^_/&=<>+\-*|!']/)) return "operator";
stream.next();
return null;
}
function markup(stream: StringStream, state: TypstState): string | null {
const inline = (style: string | null): string | null => {
const extra = [state.heading && "heading", state.strong && "strong", state.emph && "emphasis"].filter(Boolean);
return [...new Set([style, ...extra].filter(Boolean))].join(" ") || null;
};
if (stream.sol()) {
state.heading = false;
if (stream.match(/^\s*=+(?=\s|$)/)) {
state.heading = true;
return "heading";
}
if (stream.match(/^\s*(?:[-+]|\d+\.)(?=\s|$)/) || stream.match(/^\s*\/(?=\s)/)) return "list";
}
const c = comment(stream, state);
if (c) return c;
const ch = stream.peek()!;
switch (ch) {
case "#":
return embed(stream, state);
case "$":
stream.next();
state.stack.push({ kind: "math" });
return "keyword";
case "`":
return raw(stream, state);
case "\\":
stream.next();
if (!stream.match(/^u\{[0-9a-fA-F]+\}/)) stream.next();
return "escape";
case "]":
stream.next();
if (top(state)?.kind === "content") state.stack.pop();
return "bracket";
case "*":
case "_": {
// Inside a word, `*` and `_` are text (`snake_case`, `2*3`).
const before = stream.string.charAt(stream.pos - 1);
const after = stream.string.charAt(stream.pos + 1);
stream.next();
if (/[\p{L}\p{N}]/u.test(before) && /[\p{L}\p{N}]/u.test(after)) return inline(null);
if (ch === "*") state.strong = !state.strong;
else state.emph = !state.emph;
return inline(ch === "*" ? "strong" : "emphasis");
}
}
if (stream.match(LABEL)) return "labelName";
if (stream.match(REF)) return "labelName";
if (stream.match(URL)) return "url";
if (stream.match(/^\/ (?=[^:]*:)/) || stream.match(/^-{2,3}|^~/)) return inline(null);
if (!stream.match(MARKUP_TEXT)) stream.next();
return inline(null);
}
export const typstParser: StreamParser<TypstState> = {
name: "typst",
startState: () => ({ stack: [], strong: false, emph: false, heading: false, comment: 0, raw: null }),
copyState: (state) => ({ ...state, stack: state.stack.slice() }),
blankLine(state) {
state.strong = state.emph = false;
},
token(stream, state) {
if (state.comment) return blockComment(stream, state);
if (state.raw) return rawBody(stream, state);
let style: string | null | undefined;
do {
const frame = top(state);
if (frame?.kind === "expr") style = exprTail(stream, state);
else if (frame?.kind === "code" || frame?.kind === "statement") style = code(stream, state);
else if (frame?.kind === "math") style = math(stream, state);
else style = markup(stream, state);
} while (style === undefined);
// A statement ends with its line once its brackets are closed.
if (stream.eol()) {
while (top(state)?.kind === "expr") state.stack.pop();
if (top(state)?.kind === "statement") state.stack.pop();
}
return style;
},
languageData: {
commentTokens: { line: "//", block: { open: "/*", close: "*/" } },
closeBrackets: { brackets: ["(", "[", "{", '"', "$"] },
},
};
-12
Переглянути файл
@@ -154,18 +154,6 @@ 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");
-12
Переглянути файл
@@ -4,7 +4,6 @@ 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);
@@ -20,7 +19,6 @@ describe("editor font zoom (active editor by default, all editors when configure
return view;
};
beforeEach(() => {
resetWheelZoomGesture();
resetAllEditorsFontZoom();
useProject.setState({ settings: null });
});
@@ -47,16 +45,6 @@ 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();
-5
Переглянути файл
@@ -406,11 +406,6 @@ 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} />
-9
Переглянути файл
@@ -112,15 +112,6 @@ 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", () => {
+2 -14
Переглянути файл
@@ -44,12 +44,7 @@ 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[],
instructions = "",
): string {
export function commitMessagePrompt(patch: string, subjectLimit: number, recentSubjects: readonly string[]): string {
const lines = [
"Write a commit message",
"",
@@ -59,8 +54,6 @@ export function commitMessagePrompt(
"- 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(
"",
@@ -257,12 +250,7 @@ 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,
commit.agentInstructions,
);
const prompt = commitMessagePrompt(changes.patch, commit.limitSubject ? commit.subjectLimit : 72, subjects);
let task: AgentTask | undefined;
let release = () => {};
try {
-5
Переглянути файл
@@ -373,11 +373,6 @@ 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);
+2 -5
Переглянути файл
@@ -3,7 +3,6 @@ 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;
@@ -75,12 +74,10 @@ export function useAgentFontZoomSurface(
if (!active || !el) return;
const step = (delta: number) => stepAgentSurfaceFontZoom(surfaceKey, delta);
const onWheel = (e: WheelEvent) => {
if (!editorPrefs().general.wheelZoom) return;
const zoom = wheelZoomStep(e);
if (zoom === null) return;
if ((!e.ctrlKey && !e.metaKey) || e.deltaY === 0 || !editorPrefs().general.wheelZoom) return;
e.preventDefault();
e.stopPropagation();
if (zoom) step(zoom);
step(e.deltaY < 0 ? 1 : -1);
};
el.addEventListener("wheel", onWheel, { capture: true, passive: false });
const release = registerFontZoomSurface(el, step, { isolated: true });
+1 -4
Переглянути файл
@@ -406,10 +406,7 @@ export function windowActions(): Action[] {
title: "Move Tab to New Window",
category: t("app.category.window"),
when: "windowGrouped",
run: async ({ arg }) => {
const label = typeof arg === "string" ? arg : useWindowGroup.getState().tabs.find((tab) => tab.current)?.label;
if (label) await call(commands.windowGroupDetach(label));
},
run: () => call(commands.windowGroupDetach()),
},
{
id: "window.selectTab",
+1 -24
Переглянути файл
@@ -33,13 +33,6 @@ 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";
@@ -141,7 +134,6 @@ async function newRequest(directory?: string) {
export function activate(): () => void {
const disposers = [
registerSpringEndpointProvider(),
registerFeignNavigation(),
registerVariableNavigation(),
registerFileNavigation(),
useProject.subscribe((s, prev) => {
@@ -151,13 +143,7 @@ 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 }),
registerEditorContribution({ id: "http.feign", order: 59, extensions: feignEditorExtension }),
registerMenuGroup({
id: "http.spring",
menus: ["editor"],
order: 40,
items: (_menu, ctx) => [...menuGroupItems(ctx), ...feignMenuItems(ctx)],
}),
registerMenuGroup({ id: "http.spring", menus: ["editor"], order: 40, items: (_menu, ctx) => menuGroupItems(ctx) }),
registerServiceView({
id: SERVICE_VIEW,
title: "HTTP Client",
@@ -175,15 +161,6 @@ 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",
-114
Переглянути файл
@@ -1,114 +0,0 @@
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);
}
});
});
-238
Переглянути файл
@@ -1,238 +0,0 @@
/** 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)))
);
}
-162
Переглянути файл
@@ -1,162 +0,0 @@
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);
});
});
-300
Переглянути файл
@@ -1,300 +0,0 @@
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,
),
}),
];
}
+7 -32
Переглянути файл
@@ -3,17 +3,7 @@ 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 { 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[];
}
import { springControllers } from "./endpoints";
export function registerSpringEndpointProvider(): () => void {
clearRouteIndex();
@@ -28,7 +18,7 @@ export function registerSpringEndpointProvider(): () => void {
};
}
let cached: { key: string; promise: Promise<RouteIndex> } | null = null;
let cached: { key: string; promise: Promise<EndpointEntry[]> } | null = null;
/** Whether `path` is a source a mapping can live in (a Java or Kotlin file). */
export function isRouteSource(path: string): boolean {
@@ -42,41 +32,26 @@ export function clearRouteIndex() {
/** The project's routes, scanned once per project and kept in memory. */
export function routeIndex(root: string | null): Promise<EndpointEntry[]> {
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: [] });
if (!root) return Promise.resolve([]);
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).catch((error: unknown) => {
if (cached?.promise === promise) cached = null;
throw error;
});
const promise = scan(root, project);
cached = { key, promise };
return promise;
}
async function scan(root: string, project: ProjectInfo | null): Promise<RouteIndex> {
async function scan(root: string, project: ProjectInfo | null): Promise<EndpointEntry[]> {
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;
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 controller of springControllers(source.text)) {
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
@@ -96,7 +71,7 @@ async function scan(root: string, project: ProjectInfo | null): Promise<RouteInd
}
}
}
return { routes, controllers };
return routes;
}
function lineCol(text: string, offset: number): { line: number; col: number } {
-144
Переглянути файл
@@ -1,144 +0,0 @@
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();
}
});
});
-125
Переглянути файл
@@ -1,125 +0,0 @@
/** 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;
}
+4 -22
Переглянути файл
@@ -22,8 +22,6 @@ 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>;
}
@@ -44,7 +42,6 @@ export interface Field {
export interface Method {
name: string;
hasBody: boolean;
annotations: Annotation[];
params: Param[];
/** Offset of the name. */
@@ -56,7 +53,6 @@ export interface Method {
export interface ClassDecl {
name: string;
kind: string;
annotations: Annotation[];
nameStart: number;
/** Whole declaration, annotations included. */
@@ -258,33 +254,27 @@ 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 !== "=") {
duplicateArgs ||= args.has(part[0]!.text);
if (part[0]!.kind === "id" && part[1]?.text === "=" && part[1].kind === "p" && part[2]?.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 });
@@ -297,10 +287,7 @@ class Reader {
}
j = close + 1;
}
return [
{ name, args, ...(qualifiedName !== name ? { qualifiedName } : {}), ...(duplicateArgs ? { duplicateArgs } : {}) },
j,
];
return [{ name, args }, j];
}
/** Splits `[from, to)` at top-level commas (brackets and generics nest). */
@@ -418,7 +405,6 @@ 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,
@@ -478,10 +464,8 @@ 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;
}
@@ -490,11 +474,10 @@ 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, hasBody, annotations, params, nameStart: t.start, start: declStart, end });
into.methods.push({ name: t.text, annotations, params, nameStart: t.start, start: declStart, end });
reset();
i = j;
continue;
@@ -577,7 +560,6 @@ export function parseSource(text: string): SourceFile {
}
const root: ClassDecl = {
name: "",
kind: "",
annotations: [],
nameStart: 0,
start: 0,
+4 -21
Переглянути файл
@@ -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} cap={c} disabled={busy || !confirmed} />
c.id === "java.agent" && <JavaAgentDetail plugin={plugin} />
)
}
>
@@ -601,31 +601,14 @@ 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, cap, disabled }: { plugin: PluginInfo; cap: CapabilityInfo; disabled: boolean }) {
const agent = plugin.javaAgent;
function JavaAgentDetail({ plugin }: { plugin: PluginInfo }) {
const agent = plugin.contributions.find((c) => c.point === "javaAgents");
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.fileName}
{agent.args ? `=${agent.args}` : ""}
{agent.label}
</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>
);
}
-43
Переглянути файл
@@ -69,7 +69,6 @@ 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,
@@ -1605,7 +1604,6 @@ describe("marketplace", () => {
},
],
contributions: [{ point: "javaAgents", label: "spring-agent.jar=port=0" }],
javaAgent: { fileName: "spring-agent.jar", args: "port=0", approved: true },
}),
]),
);
@@ -1615,47 +1613,6 @@ 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" }),
-1
Переглянути файл
@@ -453,7 +453,6 @@ function samplePlugins(): PluginInfo[] {
homepage: null,
changeNotes: null,
icon: null,
javaAgent: null,
source: "installed" as const,
enabled: true,
error: null,
+2 -4
Переглянути файл
@@ -32,7 +32,6 @@ import {
openPluginDiff,
type PluginContentEditorData,
} from "./contentTab";
import { wheelZoomStep } from "@/platform/wheelZoom";
export function pluginContentEditorTitle(input: EditorInput): string {
const s = sessions.get(input.key);
@@ -172,10 +171,9 @@ function isActionStroke(stroke: string | null, actionId: string): boolean {
const wheelZoom = EditorView.domEventHandlers({
wheel(e, view) {
const step = wheelZoomStep(e);
if (step === null) return false;
if (!e.metaKey && !e.ctrlKey) return false;
e.preventDefault();
if (step) stepFontZoom(view, step);
stepFontZoom(view, e.deltaY < 0 ? 1 : -1);
return true;
},
});
+2 -4
Переглянути файл
@@ -26,7 +26,6 @@ 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";
@@ -43,10 +42,9 @@ function isActionStroke(stroke: string | null, actionId: string): boolean {
const wheelZoom = EditorView.domEventHandlers({
wheel(e, view) {
const step = wheelZoomStep(e);
if (step === null) return false;
if (!e.metaKey && !e.ctrlKey) return false;
e.preventDefault();
if (step) stepFontZoom(view, step);
stepFontZoom(view, e.deltaY < 0 ? 1 : -1);
return true;
},
});
-16
Переглянути файл
@@ -63,7 +63,6 @@ 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";
@@ -222,21 +221,6 @@ 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;
-68
Переглянути файл
@@ -1,68 +0,0 @@
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();
});
});
-35
Переглянути файл
@@ -1,35 +0,0 @@
/**
* 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;
}
+2 -4
Переглянути файл
@@ -28,7 +28,6 @@ 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";
@@ -72,10 +71,9 @@ function isActionStroke(stroke: string | null, actionId: string): boolean {
const wheelZoom = EditorView.domEventHandlers({
wheel(e, view) {
const step = wheelZoomStep(e);
if (step === null) return false;
if (!e.metaKey && !e.ctrlKey) return false;
e.preventDefault();
if (step) stepFontZoom(view, step);
stepFontZoom(view, e.deltaY < 0 ? 1 : -1);
return true;
},
});
-70
Переглянути файл
@@ -1,70 +0,0 @@
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"]);
});
-37
Переглянути файл
@@ -1,37 +0,0 @@
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();
});
+6 -19
Переглянути файл
@@ -7,8 +7,6 @@ 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";
@@ -305,8 +303,6 @@ 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. */
@@ -316,7 +312,6 @@ export function GlobListEditor({
placeholder = "**/pattern",
emptyText = "No patterns",
itemLabel = "Pattern",
browse,
...aria
}: GlobListEditorProps) {
const [selected, setSelected] = useState<number | null>(null);
@@ -345,19 +340,6 @@ 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);
@@ -398,7 +380,12 @@ 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={() => void add()} />
<IconButton
icon="plus"
title="Add"
size="small"
onClick={() => setEditing({ index: value.length, text: "" })}
/>
<IconButton icon="minus" title="Remove" size="small" disabled={selected === null} onClick={remove} />
<IconButton
icon="edit"
-1
Переглянути файл
@@ -221,7 +221,6 @@ export function PhpPage() {
emptyText="No include paths"
itemLabel="Include path"
aria-label="Include paths"
browse={{ directory: true, title: "Choose Include Path" }}
/>
</Row>
<Row
-27
Переглянути файл
@@ -244,30 +244,3 @@
.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);
}
+6 -62
Переглянути файл
@@ -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, type MouseEvent as ReactMouseEvent } from "react";
import { useEffect, useId, useState, type KeyboardEvent } 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,7 +30,6 @@ import {
Spinner,
T,
Tabs,
type MenuItem,
} from "@/ui";
import { GlobListEditor, Row } from "../components/Form";
import { SshConfigSelect, useSshConfigs } from "../components/SshConfigSelect";
@@ -770,26 +769,6 @@ 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);
@@ -807,34 +786,6 @@ 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}>
@@ -846,7 +797,10 @@ function DeploymentServersEditor() {
size="small"
onClick={(e) => {
const r = e.currentTarget.getBoundingClientRect();
showContextMenu({ x: r.left, y: r.bottom }, addItems);
showContextMenu({ x: r.left, y: r.bottom }, [
{ label: "Server", icon: "web", run: () => add() },
{ label: "Server Group", icon: "folder", run: addGroup },
]);
}}
/>
<IconButton icon="minus" title="Remove" size="small" disabled={!current && !currentGroup} onClick={remove} />
@@ -865,15 +819,7 @@ function DeploymentServersEditor() {
onClick={() => current && setDefaultServer(current.id)}
/>
</div>
<div
className={styles.serverList}
role="listbox"
aria-label={tx("Deployment servers")}
onContextMenu={(e) => {
e.preventDefault();
showContextMenu(e, [{ label: "Add", icon: "plus", submenu: addItems }]);
}}
>
<div className={styles.serverList} role="listbox" aria-label={tx("Deployment servers")}>
{list.length === 0 && groupList.length === 0 && (
<div className={styles.empty}>
<T>No servers. Click + to add one.</T>
@@ -886,7 +832,6 @@ 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>
@@ -900,7 +845,6 @@ 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)}>
-36
Переглянути файл
@@ -277,31 +277,6 @@ 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
@@ -427,17 +402,6 @@ 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: [
+2 -5
Переглянути файл
@@ -42,7 +42,6 @@ import {
type TerminalFontSettings,
MIN_CONTRAST_RATIO,
} from "./theme";
import { wheelZoomStep } from "@/platform/wheelZoom";
export interface TerminalSearchOptions {
caseSensitive: boolean;
@@ -465,12 +464,10 @@ export class TerminalSession {
}
private onWheelZoom = (e: WheelEvent) => {
if (!editorPrefs().general.wheelZoom) return;
const zoom = wheelZoomStep(e);
if (zoom === null) return;
if ((!e.ctrlKey && !e.metaKey) || e.deltaY === 0 || !editorPrefs().general.wheelZoom) return;
e.preventDefault();
e.stopPropagation();
if (zoom) this.stepFontSize(zoom);
this.stepFontSize(e.deltaY < 0 ? 1 : -1);
};
private onMiddleClick = (e: MouseEvent) => {
+43 -121
Переглянути файл
@@ -26,6 +26,7 @@ import {
EmptyState,
Icon,
IconButton,
List,
Menu,
Select,
SplitGroup,
@@ -102,8 +103,7 @@ import {
import { DiffEditor } from "./DiffEditor";
import { KIND_COLOR, KIND_LABEL, fileCount, formatTime, stashLabel, stripSlash } from "./model";
import { call, commands } from "@/platform/ipc";
import type { Commit, FileStatus, Stash } from "@/bindings";
import { showChangesDiff, toLogChanges, type LogChange } from "./logChanges";
import type { FileStatus } from "@/bindings";
import { OperationBanner } from "./operations";
import { runOp } from "./ops";
import { ShelfPanel, loadShelves, useShelf } from "./shelf";
@@ -1334,33 +1334,18 @@ 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 [selectedKey, setSelectedKey] = useState<string | null>(null);
const [active, setActive] = useState(0);
const request = useMemo(() => ({ repos, repo, version, tick }), [repos, repo, version, tick]);
const [result, setResult] = useState<{
request: typeof request;
stashes: StashEntry[];
stashes: (import("@/bindings").Stash & { repo: string | null })[];
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;
@@ -1381,29 +1366,7 @@ export function StashesPanel() {
live = false;
};
}, [request]);
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);
};
const current = stashes[active];
return (
<div className={styles.changes}>
<div className={styles.toolbar} role="toolbar" aria-label={tx("Stashes")}>
@@ -1415,15 +1378,7 @@ export function StashesPanel() {
options={repos.map((root) => ({ value: root, label: repoName(root) }))}
/>
)}
<IconButton
icon="refresh"
title="Refresh"
size="small"
onClick={() => {
setFiles(new Map());
setTick((n) => n + 1);
}}
/>
<IconButton icon="refresh" title="Refresh" size="small" onClick={() => setTick((n) => n + 1)} />
<IconButton icon="plus" title="Stash Changes…" size="small" onClick={() => void stashChanges()} />
<span className={styles.sep} />
<IconButton
@@ -1448,77 +1403,44 @@ export function StashesPanel() {
onClick={() => current && void dropStash(current.index, current.message, current.repo)}
/>
</div>
<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>
<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}
</span>
);
}}
/>
</div>
{branch && <span className={clsx(styles.detail, styles.stashBranch)}>{branch}</span>}
<span className={clsx(styles.detail, styles.stashTime)}>{formatTime(s.timeMs)}</span>
</span>
);
}}
/>
</div>
);
}
-28
Переглянути файл
@@ -219,34 +219,6 @@ 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);
+3 -41
Переглянути файл
@@ -1,11 +1,6 @@
import { beforeEach, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen } from "@testing-library/react";
const { apply, list, files, diff } = vi.hoisted(() => ({
apply: vi.fn(),
list: vi.fn(),
files: vi.fn(),
diff: vi.fn(),
}));
const { apply, list } = vi.hoisted(() => ({ apply: vi.fn(), list: vi.fn() }));
vi.mock("@/platform/ipc", async (original) => {
const real = await original<typeof import("@/platform/ipc")>();
return {
@@ -13,7 +8,6 @@ vi.mock("@/platform/ipc", async (original) => {
commands: {
...real.commands,
vcsStashes: list,
vcsCommitFiles: files,
},
};
});
@@ -21,32 +15,15 @@ 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,
id: `${repo}-stash`,
base: `${repo}-base`,
},
],
data: [{ index: 0, message: `On main: ${repo.endsWith("front") ? "First" : "Second"}`, timeMs: 0 }],
}),
);
useVcs.setState({ root: "/p", roots: ["/p/front", "/p/back"], repo: "/p/front" });
@@ -76,24 +53,9 @@ 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, id: "n", base: "b" }] });
resolve({ status: "ok", data: [{ index: 0, message: "On main: New project", timeMs: 0 }] });
});
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" });
});
+1 -1
Переглянути файл
@@ -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, id: `s${index}`, base: "b" });
const stash = (index: number, message: string): Stash => ({ index, message, timeMs: null });
beforeEach(() => {
mocks.stashes = new Map([
+1 -7
Переглянути файл
@@ -104,17 +104,11 @@ 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,
body: tx`The following untracked working tree files would be overwritten by checkout:\n${files}\nPlease move or remove them before you switch branches.`,
});
return false;
}
+2 -5
Переглянути файл
@@ -54,7 +54,6 @@ 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>>();
@@ -381,13 +380,11 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
const root = ref.current;
if (!root) return;
const onWheel = (e: WheelEvent) => {
if (!editorPrefs().general.wheelZoom) return;
const zoom = wheelZoomStep(e);
if (zoom === null) return;
if ((!e.ctrlKey && !e.metaKey) || e.deltaY === 0 || !editorPrefs().general.wheelZoom) return;
if ((e.target as Element | null)?.closest?.('.mermaid-output[data-zoomed="true"]')) return;
e.preventDefault();
e.stopPropagation();
if (zoom) stepMarkdownPreviewFontZoom(path, root, zoom);
stepMarkdownPreviewFontZoom(path, root, e.deltaY < 0 ? 1 : -1);
};
root.addEventListener("wheel", onWheel, { capture: true, passive: false });
const release = registerFontZoomSurface(root, (delta) => stepMarkdownPreviewFontZoom(path, root, delta));
+1 -13
Переглянути файл
@@ -1,9 +1,5 @@
{
"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",
@@ -2138,7 +2134,6 @@
"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",
@@ -2375,12 +2370,5 @@
"Install IDE Copy": "Install IDE Copy",
"Not installed:": "Not installed:",
"Additional servers": "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.": "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"
"Run alongside the one above": "Run alongside the one above"
}
+1 -14
Переглянути файл
@@ -1,9 +1,5 @@
{
"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 进程",
@@ -7005,7 +7001,6 @@
"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": "已撤销变基",
@@ -8520,7 +8515,6 @@
"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…": "提取接口…",
@@ -8753,12 +8747,5 @@
"Install IDE Copy": "安装到 IDE",
"Not installed:": "未安装:",
"Additional servers": "附加服务器",
"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": "选择包含路径"
"Run alongside the one above": "与上面选中的服务器同时运行"
}
-53
Переглянути файл
@@ -1,53 +0,0 @@
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);
});
});
-59
Переглянути файл
@@ -1,59 +0,0 @@
/**
* ⌘/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;
}
-4
Переглянути файл
@@ -59,8 +59,6 @@ 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 {
@@ -276,7 +274,6 @@ export const DEFAULT_WORKFLOW: WorkflowSettings = {
wrapAtMargin: false,
disabledPluginChecks: [],
doubleClickOpensDiff: null,
agentInstructions: "",
},
confirmation: {
onCreate: "ask",
@@ -436,7 +433,6 @@ 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),
-2
Переглянути файл
@@ -180,7 +180,6 @@ const ICONS = {
"file-godot": "openidea/fileTypes/godot",
"file-gdshader": "openidea/fileTypes/gdshader",
"file-asciidoc": "openidea/fileTypes/asciidoc",
"file-typst": "openidea/fileTypes/typst",
"file-d": "openidea/fileTypes/d",
"file-gherkin": "openidea/fileTypes/gherkin",
"file-prisma": "openidea/fileTypes/prisma",
@@ -1161,7 +1160,6 @@ const EXT_ICONS = table({
"file-godot": "tscn tres godot import",
"file-gdshader": "gdshader gdshaderinc",
"file-asciidoc": "adoc asciidoc",
"file-typst": "typ",
"file-d": "d di",
"file-gherkin": "feature",
"file-prisma": "prisma",
-3
Переглянути файл
@@ -1,3 +0,0 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<g stroke-linejoin="round"><path d="M14 4C14 2.89543 13.1046 2 12 2H4C2.89543 2 2 2.89543 2 4V12C2 13.1046 2.89543 14 4 14H12C13.1046 14 14 13.1046 14 12V4Z" fill="#239DAD"/><path d="M7 4V10C7 11.1046 7.89543 12 9 12H10.5" stroke="#2B2D30" stroke-linecap="round"/><path d="M5 6.5H10.5" stroke="#2B2D30" stroke-linecap="round"/></g>
</svg>

До

Ширина:  |  Висота:  |  Розмір: 435 B

-3
Переглянути файл
@@ -1,3 +0,0 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<g stroke-linejoin="round"><path d="M14 4C14 2.89543 13.1046 2 12 2H4C2.89543 2 2 2.89543 2 4V12C2 13.1046 2.89543 14 4 14H12C13.1046 14 14 13.1046 14 12V4Z" fill="#4DB8C7"/><path d="M7 4V10C7 11.1046 7.89543 12 9 12H10.5" stroke="#2B2D30" stroke-linecap="round"/><path d="M5 6.5H10.5" stroke="#2B2D30" stroke-linecap="round"/></g>
</svg>

До

Ширина:  |  Висота:  |  Розмір: 435 B

+2 -9
Переглянути файл
@@ -86,15 +86,8 @@
pointer-events: none;
}
/* The per-tab detach button mirrors .close on the right edge, centred like it by the row. */
.detach {
position: absolute;
right: 6px;
width: 22px;
height: 22px;
opacity: 0;
}
.item:hover .detach,
.item:focus-within .detach {
opacity: 1;
right: var(--stripe-outer-padding);
top: 0;
}
-21
Переглянути файл
@@ -64,24 +64,3 @@ 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");
});
+8 -8
Переглянути файл
@@ -102,7 +102,8 @@ export function WindowGroupTabs() {
showContextMenu(e, [
{
label: "Move Tab to New Window",
run: () => executeAction("window.detachTab", tab.label),
disabled: !tab.current,
run: () => executeAction("window.detachTab"),
},
{ kind: "separator" },
{
@@ -155,16 +156,15 @@ 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>
);
}