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

..
Автор SHA1 Повідомлення Дата
l0ng-ai 5bf25391d5 fix(run): read .NET launch profiles from a launchSettings.json with a byte order mark
Visual Studio saves launchSettings.json with a UTF-8 byte order mark, which
serde_json rejects, so a project's launch profiles came out empty: none were
offered or detected, and a configuration naming one failed with "launch
profile is missing". jsonc::strip now drops a leading byte order mark, which
also covers the other JSONC files read through it (devcontainer.json,
.vscode/launch.json, tsconfig.json).
2026-11-15 00:47:28 +08:00
83 змінених файлів з 251 додано та 3104 видалено

No files matched your search

+1 -51
Переглянути файл
@@ -53,8 +53,6 @@ pub enum BuildSystem {
TypeScript,
#[serde(rename = "cmake")]
CMake,
#[serde(rename = "dotnet")]
Dotnet,
}
/// One command of a build.
@@ -167,8 +165,6 @@ fn detect_dir(dir: &Path, model: &BuildModel, root: &Path) -> Option<BuildSystem
|| has(dir, &["build.gradle", "build.gradle.kts", "settings.gradle", "settings.gradle.kts"])
{
Some(BuildSystem::Gradle)
} else if dotnet_target(dir).is_some() {
Some(BuildSystem::Dotnet)
} else if has(dir, &["Cargo.toml"]) {
Some(BuildSystem::Cargo)
} else if has(dir, &["go.mod", "go.work"]) {
@@ -229,7 +225,7 @@ pub fn plan(
.or((!model.gradle.is_empty()).then_some(BuildSystem::Gradle))
.or_else(|| model.maven.as_ref().filter(|m| !m.projects.is_empty()).map(|_| BuildSystem::Maven))
.ok_or_else(|| {
IdeError::not_found("no supported build system (Maven, Gradle, .NET, Cargo, Go, TypeScript, CMake) found")
IdeError::not_found("no supported build system (Maven, Gradle, Cargo, Go, TypeScript, CMake) found")
})?;
let module = module_dir.as_deref().filter(|d| *d != root);
let title = match module {
@@ -248,7 +244,6 @@ pub fn plan(
BuildSystem::Go => go_steps(file.and_then(Path::parent).unwrap_or(&dir), kind)?,
BuildSystem::TypeScript => ts_steps(&dir, kind),
BuildSystem::CMake => cmake_steps(&dir, kind, cmake.and_then(<[_]>::first)),
BuildSystem::Dotnet => dotnet_steps(&dir, kind)?,
};
Ok(BuildPlan { system, title, steps })
}
@@ -456,33 +451,6 @@ fn has_build_script(dir: &Path) -> bool {
.is_some_and(|v| v.pointer("/scripts/build").is_some_and(serde_json::Value::is_string))
}
/// The solution (`.sln` / `.slnx`) or project (`.csproj` / `.fsproj` / `.vbproj`) file `dir`
/// builds: a solution first, then a project; the first by name when there are several.
fn dotnet_target(dir: &Path) -> Option<PathBuf> {
let mut files: Vec<PathBuf> =
std::fs::read_dir(dir).ok()?.flatten().map(|e| e.path()).filter(|p| p.is_file()).collect();
files.sort();
let ext = |p: &Path| p.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
let solution = files.iter().find(|p| matches!(ext(p).as_str(), "sln" | "slnx"));
solution.or_else(|| files.iter().find(|p| matches!(ext(p).as_str(), "csproj" | "fsproj" | "vbproj"))).cloned()
}
/// `dotnet build` of the directory's solution or project; Rebuild skips incremental builds,
/// Build Artifacts publishes. The summary that repeats every message is left out.
fn dotnet_steps(dir: &Path, kind: BuildKind) -> IdeResult<Vec<BuildStep>> {
let target = dotnet_target(dir).ok_or_else(|| IdeError::not_found("no .NET solution or project found"))?;
let target = target.file_name().map_or_else(String::new, |n| n.to_string_lossy().into_owned());
let verb = if kind == BuildKind::Artifacts { "publish" } else { "build" };
let mut step = BuildStep::new("dotnet", &[verb, &target, "-nologo", "-clp:NoSummary"], dir, Format::Msbuild);
if kind == BuildKind::Rebuild {
step.args.push("--no-incremental".into());
}
// The classic console logger prints the canonical `file(line,col): error` lines; the
// terminal logger (.NET 8+) only appears on a terminal, but rules it out for older SDKs too.
step.env.insert("MSBUILDTERMINALLOGGER".into(), "off".into());
Ok(vec![step])
}
fn ts_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
let script = has_build_script(dir);
if script && (kind == BuildKind::Artifacts || !dir.join("tsconfig.json").is_file()) {
@@ -1173,24 +1141,6 @@ mod tests {
("pnpm", &["run".to_owned(), "build".to_owned()][..])
);
// .NET: the solution, else the project; a module build is the file's project. An ASP.NET
// project's package.json (its front end) doesn't make it a TypeScript build.
let net = tmp.path().join("net");
write(&net, "App.sln", "");
write(&net, "src/Api/Api.csproj", "<Project/>");
write(&net, "src/Api/package.json", "{}");
write(&net, "src/Api/Program.cs", "");
let p = plan(&net, &BuildModel::default(), BuildKind::Build, None, None).unwrap();
assert_eq!(p.system, BuildSystem::Dotnet);
assert_eq!(p.steps[0].args, ["build", "App.sln", "-nologo", "-clp:NoSummary"]);
assert_eq!(p.steps[0].env["MSBUILDTERMINALLOGGER"], "off");
let p = plan(&net, &BuildModel::default(), BuildKind::Rebuild, Some(&net.join("src/Api/Program.cs")), None)
.unwrap();
assert_eq!(p.steps[0].args, ["build", "Api.csproj", "-nologo", "-clp:NoSummary", "--no-incremental"]);
assert_eq!(p.steps[0].cwd, net.join("src/Api"));
let p = plan(&net, &BuildModel::default(), BuildKind::Artifacts, None, None).unwrap();
assert_eq!(p.steps[0].args[0], "publish");
let cm = tmp.path().join("cm");
write(&cm, "CMakeLists.txt", "project(app)");
let args = |p: &BuildPlan| p.steps.iter().map(|s| s.args.join(" ")).collect::<Vec<_>>();
-61
Переглянути файл
@@ -25,8 +25,6 @@ pub(crate) enum Format {
Go,
/// GCC / Clang (through `cmake --build`): `src/a.cpp:12:5: error: msg`.
Gcc,
/// MSBuild (`dotnet build`): `C:\p\A.cs(12,5): error CS1002: msg [C:\p\App.csproj]`.
Msbuild,
}
/// What a printed column counts.
@@ -270,43 +268,6 @@ fn tsc_line(line: &str) -> Option<RawMessage> {
Some(m)
}
/// MSBuild's canonical form: `path(12,5): error CS1002: msg [project]`, `path(12,5,12,9): …`,
/// or `path : error NU1101: msg [project]` for a project-level message (no position).
/// The path may contain spaces (`C:\Users\Jane Doe\…`); "error" / "warning" are never localized.
fn msbuild_line(line: &str) -> Option<RawMessage> {
let line = line.trim();
// The project the message came from, appended by the console logger.
let line = match line.rfind(" [") {
Some(i) if line.ends_with(']') => &line[..i],
_ => line,
};
let (head, severity, rest) =
[(" error ", Severity::Error), (" warning ", Severity::Warning)].into_iter().find_map(|(word, severity)| {
let i = line.find(&format!(":{word}"))?;
Some((&line[..i], severity, &line[i + word.len() + 1..]))
})?;
let (code, msg) = rest.split_once(':')?;
let code = code.trim();
if code.is_empty() || code.contains(' ') {
return None;
}
let head = head.trim_end();
let (path, pos) = match head.strip_suffix(')').and_then(|h| h.rsplit_once('(')) {
Some((path, pos)) => (path, pos.split(',').map(num).collect::<Vec<_>>()),
None => (head, Vec::new()),
};
let at = |i: usize| pos.get(i).copied().flatten();
// `MSBUILD : error MSB1009` and the like name no file.
let file = path.rsplit(['/', '\\']).next().is_some_and(|n| n.contains('.'));
let mut m = RawMessage::new(severity, msg.trim(), ColUnit::Utf16);
if file {
m.path = Some(path.trim().to_owned());
(m.line, m.col, m.end_line, m.end_col) = (at(0), at(1), at(2), at(3));
}
m.code = Some(code.to_owned());
Some(m)
}
/// go: `./a.go:12:5: msg` (errors only; `go vet` style `a.go:12: msg` too).
fn go_line(line: &str) -> Option<RawMessage> {
let (path, ln, col, rest) = path_line_col(line)?;
@@ -443,7 +404,6 @@ impl OutputParser {
Format::Tsc => tsc_line(&line),
Format::Go => go_line(&line),
Format::Gcc => gcc_line(&line),
Format::Msbuild => msbuild_line(&line),
Format::Cargo => None,
};
if let Some(msg) = parsed {
@@ -591,27 +551,6 @@ mod tests {
assert!(plain.messages.is_empty() && plain.console.is_none());
}
#[test]
fn msbuild_canonical_messages() {
let out = parse(
Format::Msbuild,
" Determining projects to restore...\n\
C:\\Users\\Jane Doe\\App\\Program.cs(12,5): error CS1002: ; expected [C:\\Users\\Jane Doe\\App\\App.csproj]\n\
/p/App/Models/User.cs(3,8,3,12): warning CS0168: The variable 'e' is declared but never used [/p/App/App.csproj]\n\
/p/App/App.csproj : error NU1101: Unable to find package Foo. [/p/App/App.csproj]\n\
MSBUILD : error MSB1009: Project file does not exist.\n\
Build FAILED.\n",
);
assert_eq!(out.len(), 4, "{out:?}");
assert_eq!(pos(&out[0]), (Severity::Error, "C:\\Users\\Jane Doe\\App\\Program.cs", 12, Some(5)));
assert_eq!((out[0].code.as_deref(), out[0].text.as_str()), (Some("CS1002"), "; expected"));
assert_eq!(pos(&out[1]), (Severity::Warning, "/p/App/Models/User.cs", 3, Some(8)));
assert_eq!((out[1].end_line, out[1].end_col), (Some(3), Some(12)));
assert_eq!((out[2].path.as_deref(), out[2].line), (Some("/p/App/App.csproj"), None));
assert_eq!(out[2].text, "Unable to find package Foo.");
assert_eq!((out[3].path.as_deref(), out[3].code.as_deref()), (None, Some("MSB1009")));
}
#[test]
fn tsc_plain_and_pretty() {
let out = parse(
-10
Переглянути файл
@@ -159,15 +159,6 @@ pub async fn doc_highlights(host: &Host, window: &str, doc: DocId) -> IdeResult<
.await
}
/// Python class facts the inheritance inspections read: base names as written, a method's
/// parameters, decorator semantics and its body shape. Tree-sitter answers; no LSP.
pub async fn doc_python_facts(host: &Host, window: &str, doc: DocId) -> IdeResult<ide_language::PythonFacts> {
let project = host.project(window)?;
let syntax = host.syntax();
let snap = project.documents.text_snapshot(doc)?;
blocking(move || Ok(syntax.python_facts(&snap.language, &snap.text))).await
}
/// Extend Selection (⌥↑): syntax ranges around `offset`, innermost first.
/// Large documents fall back to word / line / document ranges.
pub async fn doc_selection_ranges(host: &Host, window: &str, doc: DocId, offset: u32) -> IdeResult<Vec<Range>> {
@@ -217,7 +208,6 @@ pub(crate) fn register(d: &mut Dispatcher) {
d.add("doc_outline", |c| async move { doc_outline(&c.host, &c.window, c.arg("doc")?).await });
d.add("doc_folding", |c| async move { doc_folding(&c.host, &c.window, c.arg("doc")?).await });
d.add("doc_highlights", |c| async move { doc_highlights(&c.host, &c.window, c.arg("doc")?).await });
d.add("doc_python_facts", |c| async move { doc_python_facts(&c.host, &c.window, c.arg("doc")?).await });
d.add("doc_selection_ranges", |c| async move {
doc_selection_ranges(&c.host, &c.window, c.arg("doc")?, c.arg("offset")?).await
});
-12
Переглянути файл
@@ -1472,15 +1472,6 @@ pub async fn lsp_type_hierarchy(
host.project(window)?.lsp.type_hierarchy(doc, pos, direction).await
}
pub async fn lsp_prepare_type_hierarchy(
host: &Host,
window: &str,
doc: DocId,
pos: Pos,
) -> IdeResult<Option<HierarchyItem>> {
host.project(window)?.lsp.prepare_type_hierarchy(doc, pos).await
}
pub fn lsp_servers(host: &Host, window: &str) -> IdeResult<Vec<ServerInfo>> {
Ok(host.project(window)?.lsp.servers())
}
@@ -1865,9 +1856,6 @@ pub(crate) fn register(d: &mut Dispatcher) {
d.add("lsp_type_hierarchy", |c| async move {
lsp_type_hierarchy(&c.host, &c.window, c.arg("doc")?, c.arg("pos")?, c.arg("direction")?).await
});
d.add("lsp_prepare_type_hierarchy", |c| async move {
lsp_prepare_type_hierarchy(&c.host, &c.window, c.arg("doc")?, c.arg("pos")?).await
});
d.add("lsp_servers", |c| async move { lsp_servers(&c.host, &c.window) });
d.add("lsp_resend_diagnostics", |c| async move { lsp_resend_diagnostics(&c.host, &c.window) });
d.add("lsp_restart", |c| async move { lsp_restart(&c.host, &c.window, c.arg("server")?).await });
+1 -6
Переглянути файл
@@ -1458,7 +1458,7 @@ fn content_root_watcher(
) -> Option<Watcher> {
let (kotlin_bridge, phpstan) = (kotlin_bridge.cloned(), phpstan.cloned());
let (index, documents, history, lsp) = (index.clone(), documents.clone(), history.clone(), lsp.clone());
let (root, events) = (dir.to_path_buf(), sink.clone());
let root = dir.to_path_buf();
Watcher::start(
dir,
excludes.to_vec(),
@@ -1480,11 +1480,6 @@ fn content_root_watcher(
}
documents.on_disk_changed(&[&changed[..], &ignored].concat());
record_external_changes(&history, &changed, &batch.removed);
// A member outside the project folder: its repository changes (commit, checkout,
// fetch, pull) reach the UI only through this watcher.
if batch.vcs.iter().any(|p| vcs_path_changed(p)) {
events.emit(IdeEvent::VcsChanged { root: root.clone().into() });
}
}),
)
.map_err(|e| tracing::warn!("content root watcher {}: {e}", dir.display()))
-22
Переглянути файл
@@ -599,28 +599,6 @@ impl Store {
txn.commit().map_err(err)
}
/// [`Self::apply`] for records already serialized (by the parse pool).
pub(crate) fn apply_raw(&self, puts: &[(String, Vec<u8>)], deletes: &[String], durable: bool) -> Result<()> {
self.ensure_db()?;
let db = self.db.read();
let mut txn = db.as_ref().expect("ensured").begin_write().map_err(err)?;
if !durable {
txn.set_durability(Durability::None).map_err(err)?;
}
{
let mut table = txn.open_table(FILES).map_err(err)?;
for (rel, bytes) in puts {
table.insert(rel.as_str(), bytes.as_slice()).map_err(err)?;
}
for rel in deletes {
table.remove(rel.as_str()).map_err(err)?;
}
}
// Any file change makes the columnar start-up snapshot stale.
let _ = std::fs::remove_file(&self.snapshot);
txn.commit().map_err(err)
}
/// Reclaims free pages in the database file; `true` if anything was compacted.
pub(crate) fn compact(&self) -> Result<bool> {
self.ensure_db()?;
+48 -164
Переглянути файл
@@ -17,8 +17,6 @@ use std::time::{Duration, Instant, SystemTime};
/// Files larger than this are listed but not parsed for symbols.
pub const MAX_SYMBOL_FILE: u64 = 2 * 1024 * 1024;
const CHUNK: usize = 512;
/// Insert/persist batch of the initial scan's streaming pass.
const SCAN_BATCH: usize = 2048;
const PROGRESS_EVERY: Duration = Duration::from_millis(250);
#[cfg(not(test))]
const SNAPSHOT_DELAY: Duration = Duration::from_secs(2);
@@ -438,13 +436,10 @@ impl Shared {
});
let filter = self.filter();
let walk_started = Instant::now();
let found = prewalked.unwrap_or_else(|| self.walk_roots(dirs));
let walk = walk_started.elapsed();
if self.is_cancelled() {
return self.end_scan(task);
}
let classify_started = Instant::now();
let seen: HashSet<&Path> = found.iter().map(|f| f.path.as_path()).collect();
let (todo, stale): (Vec<&Found>, Vec<PathBuf>) = {
let d = self.data.read();
@@ -457,7 +452,6 @@ impl Shared {
.collect();
(todo, stale)
};
let classify = classify_started.elapsed();
if !stale.is_empty() {
let mut d = self.data.write();
for path in &stale {
@@ -468,76 +462,33 @@ impl Shared {
self.persist(&[], &stale, false);
let total = todo.len();
let mut laps = ChunkLaps::default();
{
// One streaming parallel pass: parse on the rayon pool without
// per-chunk joins (a straggler file at a join's tail idles every
// other core), while parsed files flow to this thread to be
// inserted and persisted in batches. `filter` moves into the
// parse thread; this thread keeps the outer one.
let filter = self.filter();
// Bounded: when inserting and persisting fall behind, the parse waits instead
// of holding the whole project's records (and their bytes) in the channel.
let (tx, rx) = std::sync::mpsc::sync_channel::<ParsedFile>(2 * SCAN_BATCH);
let cancelled = &self.cancelled;
let mut done = 0usize;
let mut last_progress = Instant::now();
let pass_started = Instant::now();
std::thread::scope(|scope| -> () {
scope.spawn(move || {
todo.par_iter().for_each(|f| {
if cancelled.load(Ordering::Relaxed) {
return;
}
let Some(out) = self.parse_found(f, &filter, false) else { return };
let _ = tx.send(out);
});
// `tx` drops here: the consumer's loop ends with the channel.
let mut done = 0usize;
let mut last_progress = Instant::now();
for chunk in todo.chunks(CHUNK) {
if self.is_cancelled() {
return self.end_scan(task);
}
self.index_files(chunk.iter().copied(), false);
done += chunk.len();
if last_progress.elapsed() >= PROGRESS_EVERY {
last_progress = Instant::now();
self.sink.emit(IdeEvent::Task {
id: task,
title: "Indexing".into(),
message: Some(format!("{done} / {total} files")),
fraction: Some(done as f32 / total.max(1) as f32),
done: false,
cancellable: false,
});
let mut batch: Vec<ParsedFile> = Vec::with_capacity(SCAN_BATCH);
for out in rx {
if self.is_cancelled() {
break;
}
batch.push(out);
if batch.len() < SCAN_BATCH {
continue;
}
done += batch.len();
laps.add(self.publish(batch.drain(..)));
if last_progress.elapsed() >= PROGRESS_EVERY {
last_progress = Instant::now();
self.sink.emit(IdeEvent::Task {
id: task,
title: "Indexing".into(),
message: Some(format!("{done} / {total} files")),
fraction: Some(done as f32 / total.max(1) as f32),
done: false,
cancellable: false,
});
}
}
if !batch.is_empty() && !self.is_cancelled() {
done += batch.len();
laps.add(self.publish(batch.drain(..)));
}
});
laps.extract = pass_started.elapsed();
}
}
if self.is_cancelled() {
return self.end_scan(task);
}
let durable_started = Instant::now();
self.persist(&[], &[], true);
let durable = durable_started.elapsed();
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();
let snapshot_started = Instant::now();
if let Err(e) = store.save_snapshot(&d, &filter, guard) {
tracing::warn!("index snapshot: {e}");
}
tracing::info!("index snapshot: written in {:?}", snapshot_started.elapsed());
if let Err(e) = store.save_recent_file(&recent) {
tracing::warn!("index recent snapshot: {e}");
}
@@ -555,85 +506,54 @@ impl Shared {
self.emit_state();
let d = self.data.read();
tracing::info!(
"indexed {} files ({} parsed, {} symbols) in {:?} (walk {:?}, classify {:?}, extract {:?}, insert {:?}, persist {:?}, durable {:?})",
"indexed {} files ({} parsed, {} symbols) in {:?}",
d.file_count,
total,
d.symbol_count,
started.elapsed(),
walk,
classify,
laps.extract,
laps.insert,
laps.persist,
durable
started.elapsed()
);
}
/// Extracts records in parallel, then publishes them to memory and disk.
/// `force` re-parses files whose content is unchanged (their language changed).
fn index_files<'a>(&self, files: impl Iterator<Item = &'a Found>, force: bool) -> ChunkLaps {
let mut laps = ChunkLaps::default();
fn index_files<'a>(&self, files: impl Iterator<Item = &'a Found>, force: bool) {
let files: Vec<&Found> = files.collect();
let filter = self.filter();
let started = Instant::now();
let extracted: Vec<ParsedFile> = files.par_iter().filter_map(|f| self.parse_found(f, &filter, force)).collect();
laps.extract = started.elapsed();
let extracted: Vec<(String, FileRecord, PathBuf)> = files
.par_iter()
.filter_map(|f| {
if self.is_cancelled() {
return None;
}
let rel = filter.rel(&f.path)?;
let prev_hash = if force { None } else { self.data.read().get(&f.path).map(|e| e.hash) };
match self.extract(f, prev_hash) {
Extracted::Unchanged => {
// Same content, new mtime: keep the symbols, refresh metadata.
let mut rec = self.data.read().record_of(&f.path)?;
rec.mtime = f.mtime;
rec.size = f.size;
rec.ignored = f.ignored;
Some((rel, rec, f.path.clone()))
}
Extracted::New(rec) => Some((rel, rec, f.path.clone())),
}
})
.collect();
if extracted.is_empty() {
return laps;
}
laps.add(self.publish(extracted.into_iter()));
laps
}
/// Reads and parses one file (parallel-safe), serializing its record for
/// the cache alongside the parse. `None` when the file is outside the
/// scope or the scan was cancelled.
fn parse_found(&self, f: &Found, filter: &std::sync::Arc<PathFilter>, force: bool) -> Option<ParsedFile> {
if self.is_cancelled() {
return None;
}
let rel = filter.rel(&f.path)?;
let prev_hash = if force { None } else { self.data.read().get(&f.path).map(|e| e.hash) };
let rec = match self.extract(f, prev_hash) {
Extracted::Unchanged => {
// Same content, new mtime: keep the symbols, refresh metadata.
let mut rec = self.data.read().record_of(&f.path)?;
rec.mtime = f.mtime;
rec.size = f.size;
rec.ignored = f.ignored;
rec
}
Extracted::New(rec) => rec,
};
let key = filter.store_key(&f.path);
let bytes = postcard::to_allocvec(&rec).ok();
Some(ParsedFile { rel, rec, key, bytes, path: f.path.clone() })
}
/// Inserts a parsed batch into the in-memory index and persists the records.
fn publish(&self, batch: impl Iterator<Item = ParsedFile>) -> ChunkLaps {
let mut laps = ChunkLaps::default();
let started = Instant::now();
let mut entries: Vec<(FileEntry, Vec<StoredSymbol>)> = Vec::new();
let mut puts: Vec<(String, Vec<u8>)> = Vec::new();
for out in batch {
let ParsedFile { rel, rec, key, bytes, path } = out;
if let (Some(key), Some(bytes)) = (key, bytes) {
puts.push((key, bytes));
}
entries.push(FileEntry::new(path, rel, rec));
return;
}
let puts: Vec<(String, FileRecord)> =
extracted.iter().filter_map(|(_, rec, path)| Some((filter.store_key(path)?, rec.clone()))).collect();
{
let entries: Vec<(FileEntry, Vec<StoredSymbol>)> =
extracted.into_iter().map(|(rel, rec, path)| FileEntry::new(path, rel, rec)).collect();
let mut d = self.data.write();
for (e, symbols) in entries {
d.insert(e, symbols);
}
}
laps.insert = started.elapsed();
let started = Instant::now();
self.persist_raw(&puts, &[], false);
laps.persist = started.elapsed();
laps
self.persist(&puts, &[], false);
}
fn schedule_snapshot(&self) {
@@ -674,15 +594,6 @@ impl Shared {
}
}
/// [`Self::persist`] for records already serialized by the parse pool.
fn persist_raw(&self, puts: &[(String, Vec<u8>)], deletes: &[String], durable: bool) {
if let Some(store) = &self.store
&& let Err(e) = store.apply_raw(puts, deletes, durable)
{
tracing::warn!("index cache write failed: {e}");
}
}
fn extract(&self, f: &Found, prev_hash: Option<[u8; 32]>) -> Extracted {
let mut rec = FileRecord { mtime: f.mtime, size: f.size, ignored: f.ignored, ..Default::default() };
if f.ignored || f.size > MAX_SYMBOL_FILE {
@@ -882,33 +793,6 @@ enum Extracted {
New(FileRecord),
}
/// Wall-time laps of one `index_files` chunk, accumulated by the scan.
#[derive(Default)]
struct ChunkLaps {
extract: Duration,
insert: Duration,
persist: Duration,
}
impl ChunkLaps {
fn add(&mut self, other: ChunkLaps) {
self.extract += other.extract;
self.insert += other.insert;
self.persist += other.persist;
}
}
/// One file parsed off the index thread: its record ready to publish, already
/// serialized for the cache (in parallel with the parse).
struct ParsedFile {
rel: String,
rec: FileRecord,
/// Cache key and postcard bytes; `None` when outside the persisted root.
key: Option<String>,
bytes: Option<Vec<u8>>,
path: PathBuf,
}
#[cfg(test)]
mod tests {
use crate::data::safe_rel;
-1
Переглянути файл
@@ -28,7 +28,6 @@ pub use syntax::{
VueComponentImport, VueRefAccess, VueRefElement, WebReference, WebReferenceKind, merge_visibility,
set_external_syntax, shift_pos, shift_range,
};
pub use syntax::{MethodBody, PythonClassFacts, PythonFacts, PythonMethodFacts};
/// Parsed form of `languages/<id>.toml`. Backend-only; the UI gets [`LanguageInfo`].
#[derive(Clone, Debug, Serialize, Deserialize)]
+1 -6
Переглянути файл
@@ -43,7 +43,7 @@ fn extract(tree: &Tree, text: &str) -> Vec<ClassBases> {
// Selection-range start of the class: its name identifier (`class Foo`
// -> `Foo`), matching `outline.rs` and the gutter marker candidates.
let range = idx.range(name_node.start_byte(), name_node.end_byte());
let bases = class_base_names(node, text);
let bases = node.child_by_field_name("superclasses").map(|args| base_names(args, text)).unwrap_or_default();
out.push(ClassBases { name, line: range.start.line, col: range.start.col, bases });
});
out
@@ -67,11 +67,6 @@ fn visit(cursor: &mut tree_sitter::TreeCursor, f: &mut impl FnMut(Node)) {
}
}
/// The bare base names a `class_definition` node writes (keyword arguments left out).
pub(super) fn class_base_names(node: Node, text: &str) -> Vec<String> {
node.child_by_field_name("superclasses").map(|args| base_names(args, text)).unwrap_or_default()
}
fn base_names(args: Node, text: &str) -> Vec<String> {
let mut out = Vec::new();
let mut cursor = args.walk();
-2
Переглянути файл
@@ -10,7 +10,6 @@ mod inheritance;
pub(crate) mod lines;
mod literals;
mod outline;
mod python_facts;
mod rst;
mod selection;
mod sfc;
@@ -28,7 +27,6 @@ pub use inheritance::ClassBases;
pub use lines::{shift_pos, shift_range};
pub use literals::{Literal, LiteralKind, SpellingKind, SpellingRegion};
pub use outline::merge_visibility;
pub use python_facts::{MethodBody, PythonClassFacts, PythonFacts, PythonMethodFacts};
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::OnceLock;
-438
Переглянути файл
@@ -1,438 +0,0 @@
//! Python class facts the inheritance inspections need: base names as written, parameter
//! lists, decorator semantics and what a method body does. They come from the syntax tree in
//! one pass, so the frontend reasons about the inheritance graph without parsing source text.
//!
//! Deliberately small: a fact exists here only when a check can decide it without guessing.
use super::lines::LineIndex;
use crate::{LanguageId, Syntax};
use serde::{Deserialize, Serialize};
use specta::Type;
use tree_sitter::{Node, Tree};
/// One Python module's classes, in source order.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PythonFacts {
pub classes: Vec<PythonClassFacts>,
}
/// A class definition and the methods it declares.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PythonClassFacts {
pub name: String,
/// The class name identifier (selection range).
pub selection: crate::Range,
/// Base names as written, a qualified name reduced to its last segment.
pub bases: Vec<String>,
pub methods: Vec<PythonMethodFacts>,
}
/// A method definition the inspections can reason about.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PythonMethodFacts {
pub name: String,
/// The method name identifier (selection range).
pub selection: crate::Range,
/// Parameter names in order; `None` for a form whose forwarding cannot be compared
/// (`*args`, `**kwargs`, keyword-only, positional-only).
pub params: Option<Vec<String>>,
/// Decorated with `abstractmethod` (`abc.abstractmethod` included).
pub abstract_method: bool,
/// Decorated with `override` from `typing` / `typing_extensions`.
pub override_decorated: bool,
pub body: MethodBody,
}
/// What a method body does, for the shapes a check can decide without guessing.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", tag = "kind")]
pub enum MethodBody {
/// `pass`, `...`, a docstring, or nothing at all.
Empty,
/// Exactly one `super().name(args)` call, optionally `return`ed.
SuperCall { returns: bool, target: String, args: Vec<String> },
/// Anything else.
Other,
}
impl Syntax {
/// The classes of a Python `text` with the facts the inheritance checks need.
/// Every other language returns an empty result.
pub fn python_facts(&self, lang: &LanguageId, text: &str) -> PythonFacts {
self.analyze(lang, text, |g, tree, text| (g.spec.name == "python").then(|| extract(tree, text)))
.unwrap_or_default()
}
}
fn extract(tree: &Tree, text: &str) -> PythonFacts {
let idx = LineIndex::new(text);
let imports = ImportBindings::collect(tree, text);
let mut classes = Vec::new();
let mut cursor = tree.walk();
visit(&mut cursor, &mut |node| {
if node.kind() != "class_definition" {
return;
}
let Some(name_node) = node.child_by_field_name("name") else { return };
let name = text_of(name_node, text);
if name.is_empty() {
return;
}
classes.push(PythonClassFacts {
name,
selection: idx.range(name_node.start_byte(), name_node.end_byte()),
bases: super::inheritance::class_base_names(node, text),
methods: methods_of(node, text, &idx, &imports),
});
});
PythonFacts { classes }
}
/// The methods declared directly in `class`.
fn methods_of(class: Node, text: &str, idx: &LineIndex, imports: &ImportBindings) -> Vec<PythonMethodFacts> {
let Some(body) = class.child_by_field_name("body") else { return Vec::new() };
let mut out = Vec::new();
let mut cursor = body.walk();
for member in body.named_children(&mut cursor) {
// A decorated method is a `decorated_definition` wrapping the `function_definition`.
let method = match member.kind() {
"function_definition" => member,
"decorated_definition" => match member.child_by_field_name("definition") {
Some(inner) if inner.kind() == "function_definition" => inner,
_ => continue,
},
_ => continue,
};
let Some(name_node) = method.child_by_field_name("name") else { continue };
let name = text_of(name_node, text);
if name.is_empty() {
continue;
}
let decorators = decorators_of(method, text);
out.push(PythonMethodFacts {
name,
selection: idx.range(name_node.start_byte(), name_node.end_byte()),
params: parameters_of(method, text),
abstract_method: decorators.iter().any(|d| last_segment(d) == "abstractmethod"),
override_decorated: decorators.iter().any(|d| imports.is_typing_override(d)),
body: body_of(method, text),
});
}
out
}
/// The parameter names of a `function_definition`, or `None` when the signature contains a
/// form whose forwarding cannot be compared without guessing.
fn parameters_of(function: Node, text: &str) -> Option<Vec<String>> {
let params = function.child_by_field_name("parameters")?;
let mut names = Vec::new();
let mut cursor = params.walk();
for param in params.named_children(&mut cursor) {
let name = match param.kind() {
"identifier" => text_of(param, text),
"typed_parameter" | "default_parameter" | "typed_default_parameter" => {
let named = param
.child_by_field_name("name")
.or_else(|| param.child_by_field_name("pattern"))
.or_else(|| param.named_child(0))?;
if named.kind() != "identifier" {
return None;
}
text_of(named, text)
}
// `*args`, `**kwargs`, `/`, `*`: the call form cannot be compared textually.
_ => return None,
};
if !name.is_empty() {
names.push(name);
}
}
Some(names)
}
/// A `function_definition`'s body, classified into the shapes a check can decide.
fn body_of(function: Node, text: &str) -> MethodBody {
let Some(body) = function.child_by_field_name("body") else { return MethodBody::Empty };
// A docstring is not a statement the checks care about.
let statements: Vec<Node> = statements_of(body).into_iter().filter(|s| !is_string(*s)).collect();
if statements.is_empty() || statements.iter().all(|s| is_noop(*s)) {
return MethodBody::Empty;
}
let [only] = statements.as_slice() else { return MethodBody::Other };
let call = match only.kind() {
"expression_statement" => (only.named_child(0), false),
"return_statement" => (only.named_child(0), true),
_ => (None, false),
};
match call {
(Some(call), returns) if is_super_call(call, text) => {
let target = call
.child_by_field_name("function")
.and_then(|f| f.child_by_field_name("attribute"))
.map(|a| text_of(a, text))
.unwrap_or_default();
let args = call
.child_by_field_name("arguments")
.map(|args| {
let mut cursor = args.walk();
args.named_children(&mut cursor).map(|a| text_of(a, text)).collect()
})
.unwrap_or_default();
MethodBody::SuperCall { returns, target, args }
}
_ => MethodBody::Other,
}
}
/// Whether `node` is a `super().name(...)` call.
fn is_super_call(node: Node, text: &str) -> bool {
if node.kind() != "call" {
return false;
}
let Some(function) = node.child_by_field_name("function") else { return false };
if function.kind() != "attribute" {
return false;
}
function.child_by_field_name("object").is_some_and(|object| {
object.kind() == "call"
&& object
.child_by_field_name("function")
.is_some_and(|f| f.kind() == "identifier" && text_of(f, text) == "super")
})
}
/// Whether `statement` is `pass` or a bare `...`.
fn is_noop(statement: Node) -> bool {
match statement.kind() {
"pass_statement" => true,
"expression_statement" => statement.named_child(0).is_some_and(|child| child.kind() == "ellipsis"),
_ => false,
}
}
/// A string expression statement: a docstring.
fn is_string(statement: Node) -> bool {
statement.kind() == "expression_statement" && statement.named_child(0).is_some_and(|child| child.kind() == "string")
}
/// The statements of a `block`, comments excluded.
fn statements_of(block: Node) -> Vec<Node> {
let mut cursor = block.walk();
block.named_children(&mut cursor).filter(|child| child.kind() != "comment").collect()
}
/// The decorators written on a definition, without the `@` or the call arguments.
fn decorators_of(definition: Node, text: &str) -> Vec<String> {
let Some(parent) = definition.parent() else { return Vec::new() };
if parent.kind() != "decorated_definition" {
return Vec::new();
}
let mut out = Vec::new();
let mut cursor = parent.walk();
for decorator in parent.named_children(&mut cursor) {
if decorator.kind() != "decorator" {
continue;
}
let Some(inner) = decorator.named_child(0) else { continue };
let target =
if inner.kind() == "call" { inner.child_by_field_name("function").unwrap_or(inner) } else { inner };
let name = text_of(target, text).trim().to_owned();
if !name.is_empty() {
out.push(name);
}
}
out
}
/// The last segment of a dotted name (`typing.override` -> `override`).
fn last_segment(name: &str) -> &str {
name.rsplit('.').next().unwrap_or(name)
}
fn text_of(node: Node, text: &str) -> String {
text.get(node.byte_range()).unwrap_or_default().to_owned()
}
/// The module-level `from ... import ...` bindings, so `override` can be told apart from a
/// same-named decorator of another library.
struct ImportBindings {
/// (local name, module, exported name)
bindings: Vec<(String, String, String)>,
}
impl ImportBindings {
fn collect(tree: &Tree, text: &str) -> Self {
let mut bindings = Vec::new();
let mut cursor = tree.walk();
visit(&mut cursor, &mut |node| {
if node.kind() != "import_from_statement" {
return;
}
let Some(module) = node.child_by_field_name("module_name") else { return };
let module = text_of(module, text);
let mut names = node.walk();
for name in node.children_by_field_name("name", &mut names) {
let (local, exported) = match name.kind() {
"aliased_import" => (
name.child_by_field_name("alias").map(|n| text_of(n, text)),
name.child_by_field_name("name").map(|n| text_of(n, text)),
),
_ => {
let written = text_of(name, text);
(Some(written.clone()), Some(written))
}
};
if let (Some(local), Some(exported)) = (local, exported) {
bindings.push((local, module.clone(), exported));
}
}
});
Self { bindings }
}
/// Whether `decorator` names `override` from `typing` / `typing_extensions`.
fn is_typing_override(&self, decorator: &str) -> bool {
const MODULES: [&str; 2] = ["typing", "typing_extensions"];
let segments: Vec<&str> = decorator.split('.').filter(|s| !s.is_empty()).collect();
match segments.as_slice() {
// `@typing.override`, or `@t.override` after `import typing as t`.
[prefix, "override"] => {
MODULES.contains(prefix)
|| self
.bindings
.iter()
.find(|(local, _, _)| local == prefix)
.is_some_and(|(_, module, _)| MODULES.contains(&module.as_str()))
}
// `@override`, or `@ov` after `from typing import override as ov`.
[local] => match self.bindings.iter().find(|(bound, _, _)| bound == local) {
Some((_, module, exported)) => exported == "override" && MODULES.contains(&module.as_str()),
// Nothing contradicts a bare `@override`: the usual `from typing import *`.
None => *local == "override",
},
_ => false,
}
}
}
/// Depth-first pre-order traversal of all descendants of `cursor`'s node.
fn visit(cursor: &mut tree_sitter::TreeCursor, f: &mut impl FnMut(Node)) {
loop {
f(cursor.node());
if cursor.goto_first_child() {
continue;
}
loop {
if cursor.goto_next_sibling() {
break;
}
if !cursor.goto_parent() {
return;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
static SYNTAX: std::sync::OnceLock<Syntax> = std::sync::OnceLock::new();
fn facts(src: &str) -> PythonFacts {
SYNTAX.get_or_init(Syntax::new).python_facts(&LanguageId::new("python"), src)
}
fn method<'a>(facts: &'a PythonFacts, class: &str, method: &str) -> &'a PythonMethodFacts {
facts
.classes
.iter()
.find(|c| c.name == class)
.and_then(|c| c.methods.iter().find(|m| m.name == method))
.expect("method not found")
}
#[test]
fn classes_carry_bases_and_methods() {
let f = facts(
"class Base(ABC):\n pass\n\nclass Child(Base, pkg.Mixin):\n def run(self, x=1):\n pass\n",
);
assert_eq!(f.classes.len(), 2);
assert_eq!(f.classes[0].name, "Base");
assert_eq!(f.classes[0].bases, ["ABC"]);
assert_eq!(f.classes[1].bases, ["Base", "Mixin"]);
assert_eq!(f.classes[1].methods.len(), 1);
assert_eq!(f.classes[1].selection.start.line, 3);
assert_eq!(f.classes[1].selection.start.col, 6);
}
#[test]
fn parameters_are_names_in_order_and_none_for_splats() {
let f = facts(
"class C:\n def a(self, x: int, y=2):\n pass\n\n def b(self, *args):\n pass\n\n def c(self, *, x):\n pass\n",
);
assert_eq!(
method(&f, "C", "a").params.as_deref(),
Some(["self".to_string(), "x".to_string(), "y".to_string()].as_slice())
);
assert_eq!(method(&f, "C", "b").params, None);
assert_eq!(method(&f, "C", "c").params, None);
}
#[test]
fn body_shapes_are_classified() {
let f = facts(
"class C:\n def noop(self):\n pass\n\n def dots(self):\n ...\n\n def doc(self):\n \"\"\"text\"\"\"\n\n def forward(self, x):\n return super().run(x)\n\n def call(self):\n super().run()\n\n def other(self):\n return 1\n",
);
assert_eq!(method(&f, "C", "noop").body, MethodBody::Empty);
assert_eq!(method(&f, "C", "dots").body, MethodBody::Empty);
assert_eq!(method(&f, "C", "doc").body, MethodBody::Empty);
assert_eq!(
method(&f, "C", "forward").body,
MethodBody::SuperCall { returns: true, target: "run".into(), args: vec!["x".into()] }
);
assert_eq!(
method(&f, "C", "call").body,
MethodBody::SuperCall { returns: false, target: "run".into(), args: vec![] }
);
assert_eq!(method(&f, "C", "other").body, MethodBody::Other);
}
#[test]
fn decorators_are_their_names_and_semantics() {
let f = facts(
"from abc import abstractmethod\nfrom typing import override\n\nclass C:\n @abstractmethod\n def a(self):\n pass\n\n @override\n def b(self):\n pass\n\n @functools.cache\n def c(self):\n pass\n",
);
assert!(method(&f, "C", "a").abstract_method);
assert!(!method(&f, "C", "a").override_decorated);
assert!(method(&f, "C", "b").override_decorated);
assert!(!method(&f, "C", "c").override_decorated);
}
#[test]
fn override_of_another_library_is_not_typing_override() {
let f = facts("from mylib import override\n\nclass C:\n @override\n def a(self):\n pass\n");
assert!(!method(&f, "C", "a").override_decorated);
}
#[test]
fn aliased_override_and_qualified_forms_are_recognised() {
let f = facts(
"from typing import override as ov\n\nclass C:\n @ov\n def a(self):\n pass\n\nclass D:\n @typing_extensions.override\n def b(self):\n pass\n",
);
assert!(method(&f, "C", "a").override_decorated);
assert!(method(&f, "D", "b").override_decorated);
}
#[test]
fn nested_classes_and_other_languages() {
let f = facts("class Outer:\n class Inner:\n def m(self):\n pass\n");
let names: Vec<&str> = f.classes.iter().map(|c| c.name.as_str()).collect();
assert_eq!(names, ["Outer", "Inner"]);
let other = SYNTAX.get_or_init(Syntax::new).python_facts(&LanguageId::new("rust"), "class C {}");
assert_eq!(other.classes.len(), 0);
}
}
-15
Переглянути файл
@@ -3097,21 +3097,6 @@ impl LspManager {
Ok(CallHierarchy { items: out, incomplete })
}
/// The type at `pos` as the server's type hierarchy names it (with its `detail`, the
/// package for Java); `None` when there is no type there.
pub async fn prepare_type_hierarchy(&self, doc: DocId, pos: Pos) -> IdeResult<Option<HierarchyItem>> {
let (snap, targets) = self.doc_targets(doc, "type hierarchy", |c| c.has("typeHierarchyProvider")).await?;
let t = &targets[0];
let items: Option<Vec<serde_json::Value>> =
self.call(t, "textDocument/prepareTypeHierarchy", snap.pos_params(t, pos), None, DEFAULT_TIMEOUT).await?;
let conv = self.conv(t.enc());
Ok(items
.unwrap_or_default()
.iter()
.filter_map(convert::type_item_from_json)
.find_map(|i| convert::type_item(&conv, &i)))
}
pub async fn type_hierarchy(
&self,
doc: DocId,
+3 -242
Переглянути файл
@@ -17,7 +17,6 @@
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::{HashMap, HashSet};
use std::time::{Duration, Instant};
/// One row of a process listing.
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -105,21 +104,16 @@ pub struct MemoryRoot {
}
/// Memory of one row of the breakdown.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct ProcessMemory {
pub category: MemoryCategory,
pub label: String,
/// Project, run kind or similar.
pub detail: Option<String>,
/// The row's top process (the language server, run or terminal shell).
pub pid: u32,
/// Number of processes counted in this row.
pub processes: u32,
pub bytes: Option<u64>,
/// CPU use since the previous measurement, in percent of one core (Activity
/// Monitor's "% CPU"); `None` on the first measurement of every process.
pub cpu_percent: Option<f32>,
}
/// Recognises WebView helpers that are our children (WebKitGTK, WebView2).
@@ -143,21 +137,17 @@ pub fn attribute(
self_pid: u32,
roots: &[MemoryRoot],
footprint: impl Fn(u32) -> Option<u64>,
mut cpu: impl FnMut(u32) -> Option<f32>,
) -> Vec<ProcessMemory> {
let mut claimed = HashSet::from([self_pid]);
let mut out = Vec::new();
let mut push = |category, label: String, detail, pids: Vec<u32>| {
let sizes: Vec<u64> = pids.iter().filter_map(|&p| footprint(p)).collect();
let loads: Vec<f32> = pids.iter().filter_map(|&p| cpu(p)).collect();
out.push(ProcessMemory {
category,
label,
detail,
pid: pids[0],
processes: pids.len() as u32,
bytes: (!sizes.is_empty()).then(|| sizes.iter().sum()),
cpu_percent: (!loads.is_empty()).then(|| loads.iter().sum()),
});
};
push(MemoryCategory::App, "Backend".into(), None, vec![self_pid]);
@@ -190,84 +180,6 @@ pub fn attribute(
out
}
/// CPU load per process from the change of its CPU time between measurements.
#[derive(Debug, Default)]
pub struct CpuSampler {
last: HashMap<u32, CpuSample>,
}
#[derive(Clone, Copy, Debug)]
struct CpuSample {
time: Duration,
at: Instant,
percent: Option<f32>,
}
/// Shorter gaps (several windows polling at once) keep the previous value
/// instead of measuring over a few milliseconds.
const MIN_CPU_INTERVAL: Duration = Duration::from_millis(500);
impl CpuSampler {
/// Percent of one core used by `pid` since its previous sample.
pub fn percent(&mut self, pid: u32) -> Option<f32> {
self.record(pid, cpu_time(pid)?, Instant::now())
}
fn record(&mut self, pid: u32, time: Duration, at: Instant) -> Option<f32> {
let percent = match self.last.get(&pid) {
Some(prev) if at.duration_since(prev.at) < MIN_CPU_INTERVAL => return prev.percent,
// A reused pid restarts its CPU time.
Some(prev) if time >= prev.time => {
Some((time - prev.time).as_secs_f32() / at.duration_since(prev.at).as_secs_f32() * 100.0)
}
_ => None,
};
self.last.insert(pid, CpuSample { time, at, percent });
percent
}
/// Forgets processes that are no longer listed.
pub fn retain(&mut self, table: &ProcessTable) {
if !table.entries.is_empty() {
self.last.retain(|pid, _| table.get(*pid).is_some());
}
}
}
/// CPU time (user + system) `pid` has used so far.
pub fn cpu_time(pid: u32) -> Option<Duration> {
imp::cpu_time(pid)
}
/// Ends `pid` and every process it started, children first: a polite request
/// (`SIGTERM`), then a forced kill after `grace` for whatever is still running.
/// Refuses (returns false) unless `pid` descends from `self_pid`.
pub fn end_process_tree(self_pid: u32, pid: u32, grace: Duration) -> bool {
let table = ProcessTable::snapshot();
if pid == self_pid || !table.tree(self_pid).contains(&pid) {
return false;
}
let pids: Vec<u32> = table.tree(pid).into_iter().rev().collect();
for &p in &pids {
imp::terminate(p, false);
}
let deadline = Instant::now() + grace;
loop {
let now = ProcessTable::snapshot();
let left: Vec<u32> = pids.iter().copied().filter(|p| now.get(*p).is_some()).collect();
if left.is_empty() {
return true;
}
if Instant::now() >= deadline {
for p in left {
imp::terminate(p, true);
}
return true;
}
std::thread::sleep(Duration::from_millis(50));
}
}
/// Bytes the OS attributes to `pid` (see the module docs); `None` when the
/// process is gone or not readable.
pub fn footprint_bytes(pid: u32) -> Option<u64> {
@@ -350,15 +262,6 @@ mod imp {
fn proc_pidinfo(pid: i32, flavor: i32, arg: u64, buffer: *mut c_void, size: i32) -> i32;
fn proc_pid_rusage(pid: i32, flavor: i32, buffer: *mut c_void) -> i32;
fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
fn mach_timebase_info(info: *mut MachTimebaseInfo) -> i32;
fn kill(pid: i32, signal: i32) -> i32;
}
#[repr(C)]
#[derive(Default)]
struct MachTimebaseInfo {
numer: u32,
denom: u32,
}
#[link(name = "objc")]
@@ -414,27 +317,6 @@ mod imp {
(rc == 0).then_some(info[PHYS_FOOTPRINT_WORD])
}
/// `ri_user_time + ri_system_time` (words 2 and 3), in Mach absolute time units.
pub fn cpu_time(pid: u32) -> Option<std::time::Duration> {
static TIMEBASE: std::sync::OnceLock<(u64, u64)> = std::sync::OnceLock::new();
let &(numer, denom) = TIMEBASE.get_or_init(|| {
let mut tb = MachTimebaseInfo::default();
// SAFETY: `tb` is a writable mach_timebase_info_data_t.
let ok = unsafe { mach_timebase_info(&mut tb) } == 0 && tb.denom != 0;
if ok { (tb.numer as u64, tb.denom as u64) } else { (1, 1) }
});
let mut info = [0u64; 64];
// SAFETY: `info` (512 bytes) is larger than `rusage_info_v4`.
let rc = unsafe { proc_pid_rusage(pid as i32, RUSAGE_INFO_V4, info.as_mut_ptr().cast()) };
let ticks = (rc == 0).then(|| info[2].saturating_add(info[3]))?;
Some(std::time::Duration::from_nanos((ticks as u128 * numer as u128 / denom as u128) as u64))
}
pub fn terminate(pid: u32, force: bool) {
// SAFETY: plain syscall.
unsafe { kill(pid as i32, if force { 9 } else { 15 }) };
}
/// `responsibility_get_pid_responsible_for_pid` (libsystem SPI used by
/// Activity Monitor), looked up at run time so a missing symbol only
/// disables the fallback.
@@ -524,39 +406,6 @@ mod imp {
None
}
unsafe extern "C" {
fn sysconf(name: i32) -> i64;
fn kill(pid: i32, signal: i32) -> i32;
}
const SC_CLK_TCK: i32 = 2;
/// `utime + stime` of `/proc/<pid>/stat` (fields 14 and 15, in clock ticks).
fn stat_ticks(text: &str) -> Option<u64> {
let mut rest = text.get(text.rfind(')')? + 1..)?.split_whitespace().skip(11);
Some(rest.next()?.parse::<u64>().ok()? + rest.next()?.parse::<u64>().ok()?)
}
pub fn cpu_time(pid: u32) -> Option<std::time::Duration> {
static HZ: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
// SAFETY: plain libc call.
let hz =
*HZ.get_or_init(|| u64::try_from(unsafe { sysconf(SC_CLK_TCK) }).ok().filter(|&h| h > 0).unwrap_or(100));
let ticks = stat_ticks(&std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?)?;
Some(std::time::Duration::from_nanos(ticks * 1_000_000_000 / hz))
}
pub fn terminate(pid: u32, force: bool) {
// SAFETY: plain syscall.
unsafe { kill(pid as i32, if force { 9 } else { 15 }) };
}
#[cfg(test)]
#[test]
fn reads_cpu_ticks_from_stat() {
let text = "7 (a (b) c) S 3 7 7 0 -1 4194560 100 0 0 0 250 50 0 0 20 0 1 0";
assert_eq!(stat_ticks(text), Some(300));
}
#[cfg(test)]
#[test]
fn parses_stat_with_parens_in_name() {
@@ -614,18 +463,8 @@ mod imp {
fn CloseHandle(handle: *mut c_void) -> i32;
fn OpenProcess(access: u32, inherit: i32, pid: u32) -> *mut c_void;
fn K32GetProcessMemoryInfo(process: *mut c_void, counters: *mut c_void, cb: u32) -> i32;
fn GetProcessTimes(
process: *mut c_void,
creation: *mut u64,
exit: *mut u64,
kernel: *mut u64,
user: *mut u64,
) -> i32;
fn TerminateProcess(process: *mut c_void, code: u32) -> i32;
}
const PROCESS_TERMINATE: u32 = 0x1;
pub fn list_processes() -> Vec<ProcEntry> {
// SAFETY: plain Win32 call; the handle is closed below.
let snap = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) };
@@ -668,34 +507,6 @@ mod imp {
(ok != 0).then_some(c.PrivateUsage as u64)
}
/// Kernel + user time from `GetProcessTimes` (100 ns units).
pub fn cpu_time(pid: u32) -> Option<std::time::Duration> {
// SAFETY: plain Win32 call; the handle is closed below.
let h = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
if h.is_null() {
return None;
}
let (mut creation, mut exit, mut kernel, mut user) = (0u64, 0u64, 0u64, 0u64);
// SAFETY: `h` is a process handle; the FILETIMEs are written as u64s.
let ok = unsafe { GetProcessTimes(h, &mut creation, &mut exit, &mut kernel, &mut user) };
// SAFETY: `h` came from OpenProcess.
unsafe { CloseHandle(h) };
(ok != 0).then(|| std::time::Duration::from_nanos(kernel.saturating_add(user).saturating_mul(100)))
}
/// Windows has no polite request for a console process; both steps terminate it.
pub fn terminate(pid: u32, _force: bool) {
// SAFETY: plain Win32 call; the handle is closed below.
let h = unsafe { OpenProcess(PROCESS_TERMINATE, 0, pid) };
if h.is_null() {
return;
}
// SAFETY: `h` is a process handle opened with PROCESS_TERMINATE.
unsafe { TerminateProcess(h, 1) };
// SAFETY: `h` came from OpenProcess.
unsafe { CloseHandle(h) };
}
pub fn responsible_pid(_pid: u32) -> Option<u32> {
None
}
@@ -711,10 +522,6 @@ mod imp {
pub fn footprint_bytes(_pid: u32) -> Option<u64> {
None
}
pub fn cpu_time(_pid: u32) -> Option<std::time::Duration> {
None
}
pub fn terminate(_pid: u32, _force: bool) {}
pub fn responsible_pid(_pid: u32) -> Option<u32> {
None
}
@@ -782,7 +589,7 @@ mod tests {
// Already counted under rust-analyzer: no row.
root(301, MemoryCategory::Process, "dup", true),
];
let rows = attribute(&t, 100, &roots, mb, |pid| (pid == 300 || pid == 301).then_some(25.0));
let rows = attribute(&t, 100, &roots, mb);
let summary: Vec<(MemoryCategory, &str, u32, Option<u64>)> =
rows.iter().map(|r| (r.category, r.label.as_str(), r.processes, r.bytes)).collect();
assert_eq!(
@@ -799,56 +606,17 @@ mod tests {
]
);
assert_eq!(rows[2].detail.as_deref(), Some("idea"));
let pids: Vec<u32> = rows.iter().map(|r| r.pid).collect();
assert_eq!(pids, vec![100, 700, 200, 300, 400, 500, 600]);
assert_eq!(rows[3].cpu_percent, Some(50.0));
assert_eq!(rows[2].cpu_percent, None);
assert!(!rows.iter().any(|r| r.label == "Safari"));
}
#[test]
fn unreadable_rows_have_no_bytes() {
let t = table();
let rows = attribute(&t, 100, &[root(401, MemoryCategory::Process, "cargo", false)], mb, |_| None);
let rows = attribute(&t, 100, &[root(401, MemoryCategory::Process, "cargo", false)], mb);
let cargo = rows.iter().find(|r| r.label == "cargo").unwrap();
assert_eq!((cargo.processes, cargo.bytes), (1, None));
}
#[test]
fn cpu_percent_comes_from_the_change_in_cpu_time() {
let mut s = CpuSampler::default();
let t0 = Instant::now();
let ms = Duration::from_millis;
assert_eq!(s.record(7, ms(1000), t0), None, "first sample has nothing to compare with");
assert_eq!(s.record(7, ms(1500), t0 + ms(1000)), Some(50.0));
assert_eq!(s.record(7, ms(1900), t0 + ms(1100)), Some(50.0), "too soon: previous value");
assert_eq!(s.record(7, ms(3500), t0 + ms(2000)), Some(200.0), "two busy cores");
assert_eq!(s.record(7, ms(10), t0 + ms(3000)), None, "pid reused by a new process");
s.retain(&ProcessTable::from_entries([e(8, 1, "other")]));
assert_eq!(s.record(7, ms(500), t0 + ms(4000)), None, "forgotten once unlisted");
}
#[test]
fn ends_only_descendants() {
let me = std::process::id();
assert!(!end_process_tree(me, me, Duration::ZERO));
assert!(!end_process_tree(me, 1, Duration::ZERO));
}
#[cfg(unix)]
#[test]
fn ends_a_child_and_its_children() {
let mut child = std::process::Command::new("sh").args(["-c", "sleep 30 & wait"]).spawn().unwrap();
let deadline = Instant::now() + Duration::from_secs(5);
while ProcessTable::snapshot().children(child.id()).is_empty() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(20));
}
let sleeper = ProcessTable::snapshot().children(child.id())[0];
assert!(end_process_tree(std::process::id(), child.id(), Duration::from_secs(2)));
assert!(child.wait().is_ok());
assert!(ProcessTable::snapshot().get(sleeper).is_none(), "grandchild ended too");
}
#[test]
fn measures_this_process() {
if cfg!(any(target_os = "macos", target_os = "linux", windows)) {
@@ -857,13 +625,6 @@ mod tests {
assert!(t.get(me).is_some(), "own pid listed");
let bytes = footprint_bytes(me).expect("own footprint");
assert!(bytes > 1 << 16 && bytes < 1 << 40, "{bytes}");
let before = cpu_time(me).expect("own CPU time");
let spin = Instant::now();
while spin.elapsed() < Duration::from_millis(50) {
std::hint::black_box(spin.elapsed());
}
let used = cpu_time(me).unwrap() - before;
assert!(used > Duration::from_millis(10) && used < Duration::from_secs(5), "{used:?}");
}
if cfg!(target_os = "macos") {
assert!(imp::responsible_pid(std::process::id()).is_some(), "responsibility SPI resolved");
-3
Переглянути файл
@@ -1,3 +0,0 @@
# Per-user IDE state
/shelf/
/changelists.json
-11
Переглянути файл
@@ -134,17 +134,6 @@ pub async fn doc_outline(window: Window, state: State<'_, AppState>, doc: DocId)
ide_host::ops::doc::doc_outline(&state.host, window.label(), doc).await
}
/// Python class facts for the inheritance inspections: tree-sitter, no language server.
#[tauri::command]
#[specta::specta]
pub async fn doc_python_facts(
window: Window,
state: State<'_, AppState>,
doc: DocId,
) -> IdeResult<ide_language::PythonFacts> {
ide_host::ops::doc::doc_python_facts(&state.host, window.label(), doc).await
}
#[tauri::command]
#[specta::specta]
pub async fn doc_folding(window: Window, state: State<'_, AppState>, doc: DocId) -> IdeResult<Vec<FoldRange>> {
-11
Переглянути файл
@@ -380,17 +380,6 @@ pub async fn lsp_call_hierarchy(
ide_host::ops::lsp::lsp_call_hierarchy(&state.host, window.label(), request, doc, pos, direction).await
}
#[tauri::command]
#[specta::specta]
pub async fn lsp_prepare_type_hierarchy(
window: Window,
state: State<'_, AppState>,
doc: DocId,
pos: Pos,
) -> IdeResult<Option<HierarchyItem>> {
ide_host::ops::lsp::lsp_prepare_type_hierarchy(&state.host, window.label(), doc, pos).await
}
#[tauri::command]
#[specta::specta]
pub async fn lsp_type_hierarchy(
-3
Переглянути файл
@@ -209,7 +209,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
doc::doc_set_bom,
doc::doc_set_line_ending,
doc::doc_outline,
doc::doc_python_facts,
doc::doc_folding,
doc::doc_highlights,
doc::doc_selection_ranges,
@@ -293,7 +292,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
lsp::lsp_code_lens,
lsp::lsp_document_links,
lsp::lsp_call_hierarchy,
lsp::lsp_prepare_type_hierarchy,
lsp::lsp_type_hierarchy,
lsp::lsp_servers,
lsp::lsp_resend_diagnostics,
@@ -637,7 +635,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
plugin::plugin_set_theme_frame,
perf::app_metrics,
perf::clear_caches,
perf::end_process,
analysis::inspect_code,
analysis::analysis_locate_duplicates,
analysis::structural_languages,
+2 -17
Переглянути файл
@@ -5,10 +5,9 @@ use crate::state::AppState;
use ide_core::IdeResult;
use ide_core::event::ServerStatus;
use ide_language::SyntaxCacheStats;
use ide_workspace::memory::{self, CpuSampler, MemoryCategory, MemoryRoot, ProcessMemory, ProcessTable};
use ide_workspace::memory::{self, MemoryCategory, MemoryRoot, ProcessMemory, ProcessTable};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::sync::{LazyLock, Mutex};
use tauri::{AppHandle, State, Window};
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
@@ -56,9 +55,6 @@ fn ms(d: std::time::Duration) -> f64 {
d.as_secs_f64() * 1000.0
}
/// CPU time of every measured process at the previous `app_metrics` call, shared by all windows.
static CPU: LazyLock<Mutex<CpuSampler>> = LazyLock::new(Default::default);
/// Snapshot of process memory and subsystem sizes, summed over all projects.
/// Async: the process walk runs on the blocking pool, not the main thread.
#[tauri::command]
@@ -133,9 +129,7 @@ pub async fn app_metrics(app: AppHandle, state: State<'_, AppState>) -> IdeResul
.map(|(pid, label)| openidea_root(pid, label.into(), None)),
);
}
let mut cpu = CPU.lock().unwrap_or_else(|e| e.into_inner());
cpu.retain(&table);
Ok(memory::attribute(&table, me, &roots, memory::footprint_bytes, |pid| cpu.percent(pid)))
Ok(memory::attribute(&table, me, &roots, memory::footprint_bytes))
})
.await?;
Ok(m)
@@ -225,15 +219,6 @@ pub struct ClearCachesResult {
/// "Clear caches": drops syntax trees and EditorConfig files of the window's
/// project, shrinks the in-memory index and compacts its on-disk cache.
/// Ends a process OpenIDEA started (a row of the memory breakdown) and its
/// children; its owner (language server, run, terminal) sees it exit. Returns
/// false for a process that isn't ours.
#[tauri::command]
#[specta::specta]
pub async fn end_process(pid: u32) -> IdeResult<bool> {
blocking(move || Ok(memory::end_process_tree(std::process::id(), pid, std::time::Duration::from_secs(3)))).await
}
#[tauri::command]
#[specta::specta]
pub async fn clear_caches(window: Window, state: State<'_, AppState>) -> IdeResult<ClearCachesResult> {
-5
Переглянути файл
@@ -799,9 +799,6 @@ pub fn spec(os: Os) -> Vec<Entry> {
"toolWindowLayouts",
"Tool Window Layouts",
vec![
act("layout.saveCurrent", "Save Changes in Current Layout"),
act("layout.restoreCurrent", "Restore Current Layout"),
SEP,
act("layout.save", "Save Current Layout as…"),
act("layout.restoreDefault", "Restore Default Layout"),
SEP,
@@ -2321,8 +2318,6 @@ mod tests {
"view.quickSwitchScheme",
"code.cleanup",
"runAnything.show",
"layout.saveCurrent",
"layout.restoreCurrent",
"layout.save",
"layout.restoreDefault",
"layout.rename",
+2 -69
Переглянути файл
@@ -351,8 +351,6 @@ export const commands = {
* re-parse); large documents get no syntax structure.
*/
docOutline: (doc: DocId) => typedError<OutlineItem[], IdeError>(__TAURI_INVOKE("doc_outline", { doc })),
/** Python class facts for the inheritance inspections: tree-sitter, no language server. */
docPythonFacts: (doc: DocId) => typedError<PythonFacts, IdeError>(__TAURI_INVOKE("doc_python_facts", { doc })),
docFolding: (doc: DocId) => typedError<FoldRange[], IdeError>(__TAURI_INVOKE("doc_folding", { doc })),
/**
* Tree-sitter highlighting for languages the UI has no CodeMirror mode for;
@@ -607,19 +605,6 @@ export const commands = {
/** Links in a document (`href`s, Markdown links, `#include`s…) from its language servers. */
lspDocumentLinks: (doc: DocId) => typedError<DocumentLink[], IdeError>(__TAURI_INVOKE("lsp_document_links", { doc })),
lspCallHierarchy: (request: RequestId, doc: DocId, pos: Pos, direction: HierarchyDirection) => typedError<CallHierarchy, IdeError>(__TAURI_INVOKE("lsp_call_hierarchy", { request, doc, pos, direction })),
lspPrepareTypeHierarchy: (doc: DocId, pos: Pos) => typedError<{
name: string,
kind: SymbolKind,
detail: string | null,
/** File path, or the URI of a virtual document (see `uri`). */
path: IpcPath,
/** Set for non-`file:` items (library classes). */
uri?: string | null,
range: Range,
selectionRange: Range,
/** Call sites, for call hierarchy. */
fromRanges: Range[],
} | null, IdeError>(__TAURI_INVOKE("lsp_prepare_type_hierarchy", { doc, pos })),
lspTypeHierarchy: (doc: DocId, pos: Pos, direction: HierarchyDirection) => typedError<HierarchyItem[], IdeError>(__TAURI_INVOKE("lsp_type_hierarchy", { doc, pos, direction })),
lspServers: () => typedError<ServerInfo[], IdeError>(__TAURI_INVOKE("lsp_servers")),
/** Re-emits the language servers' current diagnostics (the UI loaded after they arrived). */
@@ -1545,15 +1530,11 @@ export const commands = {
* Async: the process walk runs on the blocking pool, not the main thread.
*/
appMetrics: () => typedError<AppMetrics, IdeError>(__TAURI_INVOKE("app_metrics")),
clearCaches: () => typedError<ClearCachesResult, IdeError>(__TAURI_INVOKE("clear_caches")),
/**
* "Clear caches": drops syntax trees and EditorConfig files of the window's
* project, shrinks the in-memory index and compacts its on-disk cache.
* Ends a process OpenIDEA started (a row of the memory breakdown) and its
* children; its owner (language server, run, terminal) sees it exit. Returns
* false for a process that isn't ours.
*/
endProcess: (pid: number) => typedError<boolean, IdeError>(__TAURI_INVOKE("end_process", { pid })),
clearCaches: () => typedError<ClearCachesResult, IdeError>(__TAURI_INVOKE("clear_caches")),
/**
* Inspect Code: diagnostics of every file in `scope` that a language server
* serves. Files stream through `on_event` as they finish; ends with `Done`.
@@ -2820,7 +2801,7 @@ export type BuildResult = {
messages: BuildMessage[],
};
export type BuildSystem = "maven" | "gradle" | "cargo" | "go" | "typescript" | "cmake" | "dotnet";
export type BuildSystem = "maven" | "gradle" | "cargo" | "go" | "typescript" | "cmake";
export type BuildTool = "maven" | "gradle";
@@ -7586,15 +7567,6 @@ export type MergeVersions = {
merged: string | null,
};
/** What a method body does, for the shapes a check can decide without guessing. */
export type MethodBody =
/** `pass`, `...`, a docstring, or nothing at all. */
{ kind: "empty" } |
/** Exactly one `super().name(args)` call, optionally `return`ed. */
{ kind: "superCall"; returns: boolean; target: string; args: string[] } |
/** Anything else. */
{ kind: "other" };
/** Per-function totals (a recursive function's samples count once in `total`). */
export type MethodStat = {
frame: number,
@@ -8538,16 +8510,9 @@ export type ProcessMemory = {
label: string,
/** Project, run kind or similar. */
detail: string | null,
/** The row's top process (the language server, run or terminal shell). */
pid: number,
/** Number of processes counted in this row. */
processes: number,
bytes: number | null,
/**
* CPU use since the previous measurement, in percent of one core (Activity
* Monitor's "% CPU"); `None` on the first measurement of every process.
*/
cpuPercent: number | null,
};
export type Profile = {
@@ -8811,44 +8776,12 @@ export type PullRequestSummary = {
/** Push dialog › Push tags: every tag, or only annotated tags on the pushed commits. */
export type PushTags = "all" | "currentBranch";
/** A class definition and the methods it declares. */
export type PythonClassFacts = {
name: string,
/** The class name identifier (selection range). */
selection: Range,
/** Base names as written, a qualified name reduced to its last segment. */
bases: string[],
methods: PythonMethodFacts[],
};
/** Python Debugger (debugpy launch options). */
export type PythonDebuggerSettings = {
attachSubprocess?: boolean,
gevent?: boolean,
};
/** One Python module's classes, in source order. */
export type PythonFacts = {
classes: PythonClassFacts[],
};
/** A method definition the inspections can reason about. */
export type PythonMethodFacts = {
name: string,
/** The method name identifier (selection range). */
selection: Range,
/**
* Parameter names in order; `None` for a form whose forwarding cannot be compared
* (`*args`, `**kwargs`, keyword-only, positional-only).
*/
params: string[] | null,
/** Decorated with `abstractmethod` (`abc.abstractmethod` included). */
abstractMethod: boolean,
/** Decorated with `override` from `typing` / `typing_extensions`. */
overrideDecorated: boolean,
body: MethodBody,
};
export type PythonPackage = {
name: string,
version: string,
+1 -1
Переглянути файл
@@ -619,7 +619,7 @@ export function _saveParticipants(): SaveParticipant[] {
export async function revealRange(
path: string,
range: { start: { line: number; col: number }; end?: { line: number; col: number } },
options: { preview?: boolean; focus?: boolean; external?: boolean } = {},
options: { preview?: boolean; focus?: boolean } = {},
): Promise<void> {
const service = maybeEditorService();
if (!service) return;
+1 -1
Переглянути файл
@@ -387,7 +387,7 @@ describe("EditorController", () => {
"vcs.showHistoryForSelection",
"vcs.rollback",
],
["vcs.push", "vcs.pull", "vcs.fetch"],
["vcs.push", "vcs.update", "vcs.fetch"],
["vcs.merge", "vcs.rebase"],
["vcs.branches", "vcs.newBranch", "vcs.newTag", "vcs.resetHead"],
["vcs.stash", "vcs.unstash"],
+4 -5
Переглянути файл
@@ -27,7 +27,6 @@ import {
menuGroupItems,
notifications,
openFileExternally,
opensExternally,
resolveFileEditor,
textEditorWrapperFor,
uriOpenerFor,
@@ -1086,7 +1085,7 @@ export class EditorController implements SlotHost {
// Files opened with another application, then images/binary/huge files in a
// contributed viewer, unless already open as text.
if (!o.asText && !findTab(useTabs.getState(), fileKey(path))) {
if (o.external === false ? opensExternally(path) : await openFileExternally(path)) return;
if (await openFileExternally(path)) return;
const viewer = await resolveFileEditor(path);
if (viewer) {
try {
@@ -2068,11 +2067,11 @@ function gitMenu(path: string): MenuItem {
{ kind: "action", action: "vcs.rollback", arg: [path], label: "Rollback…" },
{ kind: "separator" },
{ kind: "action", action: "vcs.push", label: "Push…" },
{ kind: "action", action: "vcs.pull", arg: [path], label: "Pull…" },
{ kind: "action", action: "vcs.update", label: "Pull…" },
{ kind: "action", action: "vcs.fetch", label: "Fetch" },
{ kind: "separator" },
{ kind: "action", action: "vcs.merge", arg: [path] },
{ kind: "action", action: "vcs.rebase", arg: [path] },
{ kind: "action", action: "vcs.merge" },
{ kind: "action", action: "vcs.rebase" },
{ kind: "separator" },
{ kind: "action", action: "vcs.branches", label: "Branches…" },
{ kind: "action", action: "vcs.newBranch" },
+1 -12
Переглянути файл
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { registerExternalFileOpenHandler, registerFileEditorProvider } from "@/workbench/contributions";
import { registerFileEditorProvider } from "@/workbench/contributions";
import { EditorController, openFilePaths, useTabs } from "./controller";
import { createMemoryBackend } from "./backend";
import { storeSession } from "./model/session";
@@ -64,17 +64,6 @@ function tabFor(path: string) {
}
describe("file open order", () => {
it("leaves a file for another application unopened when external opens are off", async () => {
const open = vi.fn(() => true);
dispose = registerExternalFileOpenHandler({ id: "ext", matches: (p) => p === "/p/a.ts", open });
const controller = setup();
await controller.openFile("/p/a.ts", { focus: false, external: false });
expect(open).not.toHaveBeenCalled();
expect(openFilePaths(useTabs.getState())).toEqual([]);
await controller.openFile("/p/a.ts", { focus: false });
expect(open).toHaveBeenCalledWith("/p/a.ts");
});
it("keeps the caret and activation of a file opened while the project's session restores", async () => {
const before = setup();
before.restoreSession("/p");
+15 -59
Переглянути файл
@@ -269,69 +269,25 @@ export async function baseDeclarations(index: InheritanceIndex, cls: ClassInheri
}
/**
* Standard bases that declare no method a project class could override or implement (only
* dunders), so a chain ending in them is still fully known: `class Shape(ABC)`.
* Every ancestor of `cls`, nearest first (breadth-first, each declaration once), up to
* `depth` levels. The order within a level follows the source's base order.
*/
const EMPTY_BASES: ReadonlySet<string> = new Set(["object", "ABC", "Generic", "Protocol"]);
/** One class `cls` inherits from, and how far up it sits (its direct bases are depth 1). */
export interface AncestorNode {
decl: ClassInheritance;
depth: number;
}
/** Ancestors of `cls`, and how deep the first base the project does not declare sits. */
export interface AncestryResolution {
/** The declarations `cls` inherits from, nearest first. */
ancestors: AncestorNode[];
/**
* Depth of the shallowest base name that names no class of the project (`dict`, a library
* class), or `Infinity` when the chain resolved completely. A rule may trust the chain up
* to that depth only: a foreign base can declare or implement anything.
*/
firstUnresolvedDepth: number;
}
/**
* Walks `cls`'s ancestry nearest first (breadth-first, each declaration once) and reports
* at which depth the chain leaves the project. A rule that reasons about an ancestor at
* depth `d` is sound exactly while `firstUnresolvedDepth > d`.
*/
export async function ancestryResolution(
index: InheritanceIndex,
cls: ClassInheritance,
depth = 8,
): Promise<AncestryResolution> {
const seen = new Set<string>([declarationKey(cls)]);
const out: AncestorNode[] = [];
let firstUnresolvedDepth = Infinity;
let level: ClassInheritance[] = [cls];
for (let d = 1; d <= depth && level.length; d++) {
const next: ClassInheritance[] = [];
for (const current of level) {
for (const base of current.bases) {
const found = await index.resolve(base, current.path);
if (!found.length) {
if (!EMPTY_BASES.has(base)) firstUnresolvedDepth = Math.min(firstUnresolvedDepth, d);
continue;
}
for (const parent of found) {
if (!seen.add(declarationKey(parent))) continue;
out.push({ decl: parent, depth: d });
next.push(parent);
}
}
}
level = next;
}
return { ancestors: out, firstUnresolvedDepth };
}
/** Every ancestor of `cls`, nearest first, up to `depth` levels. */
export async function ancestors(
index: InheritanceIndex,
cls: ClassInheritance,
depth = 8,
): Promise<ClassInheritance[]> {
return (await ancestryResolution(index, cls, depth)).ancestors.map((node) => node.decl);
const seen = new Set<string>([declarationKey(cls)]);
const out: ClassInheritance[] = [];
let level = await baseDeclarations(index, cls);
for (let d = 0; d < depth && level.length; d++) {
const next: ClassInheritance[] = [];
for (const parent of level) {
if (!seen.add(declarationKey(parent))) continue;
out.push(parent);
next.push(...(await baseDeclarations(index, parent)));
}
level = next;
}
return out;
}
+1 -5
Переглянути файл
@@ -1,9 +1,7 @@
/**
* Code analysis: Inspect Code (batch language-server diagnostics), Locate
* Duplicates and Search / Replace Structurally, and the Python inheritance
* inspections the IDE computes from its own graph.
* Duplicates and Search / Replace Structurally.
*/
import { registerEditorContribution } from "@/editor/api";
import { registerActions } from "@/platform/actions";
import { useProject } from "@/platform/project";
import { registerOverlay, registerToolWindow } from "@/workbench/contributions";
@@ -16,14 +14,12 @@ import {
import { AnalysisDialogHost } from "./dialogs";
import { resetDuplicates } from "./duplicates";
import { DuplicatesHeaderActions, DuplicatesView } from "./DuplicatesView";
import { pythonInheritanceExtension } from "./inheritanceInspections";
import { installInspectionProfileSync, resetInspection, runInspection } from "./inspect";
import { defaultScope } from "./scope";
import { InspectionHeaderActions, InspectionView, useInspectionHeaderMenu } from "./InspectionView";
export function activate(): () => void {
const disposers = [
registerEditorContribution({ id: "analysis.python-inheritance", extensions: pythonInheritanceExtension }),
installInspectionProfileSync(),
useProject.subscribe((s, prev) => {
if (s.project?.root === prev.project?.root) return;
-366
Переглянути файл
@@ -1,366 +0,0 @@
import { expect, it } from "vitest";
import type {
ClassInheritance,
Diagnostic,
MethodBody,
OutlineItem,
PythonClassFacts,
PythonFacts,
PythonMethodFacts,
Range,
} from "@/platform/ipc";
import { inheritanceIndex } from "@/editor/navigation/inheritanceGraph";
import { inheritanceDiagnostics, pythonInheritanceExtension } from "./inheritanceInspections";
interface MethodSpec {
name: string;
line: number;
col?: number;
params?: string[] | null;
abstract?: boolean;
override?: boolean;
body?: MethodBody;
}
interface ClassSpec {
name: string;
line: number;
col?: number;
/** The bases the *index* saw (defaults to `bases`). */
indexedBases?: string[];
bases: string[];
methods?: MethodSpec[];
/** Extra members (fields, properties, nested classes) the class declares. */
members?: string[];
}
const range = (line: number, col: number): Range => ({ start: { line, col }, end: { line, col: col + 1 } });
const EMPTY: MethodBody = { kind: "empty" };
const OTHER: MethodBody = { kind: "other" };
const forward = (target: string, args: string[], returns = false): MethodBody => ({
kind: "superCall",
returns,
target,
args,
});
const methodFacts = (spec: MethodSpec): PythonMethodFacts => ({
name: spec.name,
selection: range(spec.line, spec.col ?? 8),
params: spec.params === undefined ? ["self"] : spec.params,
abstractMethod: spec.abstract ?? false,
overrideDecorated: spec.override ?? false,
body: spec.body ?? EMPTY,
});
const classItem = (spec: ClassSpec, col: number, methods: PythonMethodFacts[]): OutlineItem => ({
name: spec.name,
detail: null,
kind: "class",
range: range(spec.line, 0),
selection_range: range(spec.line, col),
children: [
...methods.map((m): OutlineItem => ({
name: m.name,
detail: null,
kind: "method",
range: m.selection,
selection_range: m.selection,
children: [],
visibility: null,
})),
...(spec.members ?? []).map((name): OutlineItem => ({
name,
detail: null,
kind: "field",
range: range(spec.line, 0),
selection_range: range(spec.line, 0),
children: [],
visibility: null,
})),
],
visibility: null,
});
/** A project held as the facts, outlines and graph the inspections read. */
class Fixture {
private facts = new Map<string, PythonFacts>();
private outlines = new Map<string, OutlineItem[]>();
private graph: ClassInheritance[] = [];
constructor(private readonly current: string) {}
add(path: string, classes: readonly ClassSpec[]): this {
const classFacts: PythonClassFacts[] = [];
for (const spec of classes) {
const col = spec.col ?? 6;
const methods = (spec.methods ?? []).map(methodFacts);
classFacts.push({ name: spec.name, selection: range(spec.line, col), bases: spec.bases, methods });
this.graph.push({ path, line: spec.line, col, name: spec.name, bases: spec.indexedBases ?? spec.bases });
this.outlines.set(path, [...(this.outlines.get(path) ?? []), classItem(spec, col, methods)]);
}
this.facts.set(path, { classes: [...(this.facts.get(path)?.classes ?? []), ...classFacts] });
return this;
}
async run(enabled?: ReadonlySet<string>): Promise<Diagnostic[]> {
const facts = this.facts.get(this.current);
if (!facts) throw new Error(`no fixture for ${this.current}`);
return inheritanceDiagnostics({
path: this.current,
outline: this.outlines.get(this.current) ?? [],
facts,
index: inheritanceIndex(this.graph, { readFiles: async () => new Map() }),
factsOf: async (path) => this.facts.get(path) ?? null,
outlineOf: async (path) => this.outlines.get(path) ?? [],
enabled,
});
}
}
const codes = (diagnostics: readonly Diagnostic[]) => diagnostics.map((d) => [d.code, d.severity, d.range.start.line]);
/** `/p/base.py` declares the bases; `/p/a.py` holds the class under test. */
const withBase = (child: ClassSpec, base: ClassSpec[], basePath = "/p/base.py") =>
new Fixture("/p/a.py").add(basePath, base).add("/p/a.py", [child]);
it("reports circular inheritance", async () => {
const project = new Fixture("/p/a.py").add("/p/a.py", [
{ name: "First", line: 0, bases: ["Second"] },
{ name: "Second", line: 4, bases: ["First"] },
]);
expect(codes(await project.run())).toEqual([
["builtin:python-circular-bases", "error", 0],
["builtin:python-circular-bases", "error", 4],
]);
});
it("accepts a legal diamond", async () => {
const project = new Fixture("/p/a.py")
.add("/p/base.py", [
{ name: "Root", line: 0, bases: [] },
{ name: "Left", line: 3, bases: ["Root"] },
{ name: "Right", line: 6, bases: ["Root"] },
])
.add("/p/a.py", [{ name: "Leaf", line: 0, bases: ["Left", "Right"] }]);
expect(await project.run()).toEqual([]);
});
it("reports an @override no ancestor declares", async () => {
const project = withBase(
{ name: "C", line: 0, bases: ["Base"], methods: [{ name: "run", line: 1, override: true }] },
[{ name: "Base", line: 0, bases: [], methods: [{ name: "other", line: 1 }] }],
);
expect(codes(await project.run())).toEqual([["builtin:python-override", "warning", 1]]);
});
it("accepts an @override of a method, a field or a property", async () => {
const project = withBase(
{
name: "C",
line: 0,
bases: ["Base"],
methods: [
{ name: "run", line: 1, override: true, body: OTHER },
{ name: "limit", line: 3, override: true },
{ name: "label", line: 5, override: true },
],
},
[{ name: "Base", line: 0, bases: [], methods: [{ name: "run", line: 1 }], members: ["limit", "label"] }],
);
expect(await project.run()).toEqual([]);
});
it("never reports @override on a dunder", async () => {
const project = withBase(
{ name: "C", line: 0, bases: ["Base"], methods: [{ name: "__eq__", line: 1, override: true }] },
[{ name: "Base", line: 0, bases: [] }],
);
expect(await project.run()).toEqual([]);
});
it("stays silent when a base is outside the project", async () => {
// `dict` is not in the graph: it may declare or implement anything.
const project = withBase(
{
name: "C",
line: 0,
bases: ["dict"],
methods: [
{ name: "run", line: 1, override: true },
{ name: "go", line: 3, abstract: true },
],
},
[],
);
expect(await project.run()).toEqual([]);
});
it("knows a chain that ends in ABC or object", async () => {
// `ABC` declares nothing a method could override, so `@override` on a method no class of
// the chain declares is still a mistake.
const project = withBase(
{ name: "Circle", line: 0, bases: ["Shape"], methods: [{ name: "describ", line: 1, override: true }] },
[{ name: "Shape", line: 0, bases: ["ABC", "object"], methods: [{ name: "describe", line: 1 }] }],
);
expect(codes(await project.run())).toEqual([["builtin:python-override", "warning", 1]]);
});
it("reports an unimplemented abstract method", async () => {
const project = withBase({ name: "Half", line: 0, bases: ["Base"] }, [
{ name: "Base", line: 0, bases: [], methods: [{ name: "dispatch", line: 1, abstract: true }] },
]);
expect(codes(await project.run())).toEqual([["builtin:python-abstract-method", "warning", 0]]);
});
it("still reports an abstract method whose declarer has a foreign base", async () => {
// `class TokenDispatcher(ABC)` in an attached project: `ABC` is outside the graph, but
// that cannot hide the abstract method the declarer does define.
const project = withBase({ name: "Half", line: 0, bases: ["Base"] }, [
{ name: "Base", line: 0, bases: ["ABC"], methods: [{ name: "dispatch", line: 1, abstract: true }] },
]);
expect(codes(await project.run())).toEqual([["builtin:python-abstract-method", "warning", 0]]);
});
it("accepts a class that is itself abstract", async () => {
const base = { name: "Base", line: 0, bases: [], methods: [{ name: "dispatch", line: 1, abstract: true }] };
const declaresOwn = withBase(
{ name: "Middle", line: 0, bases: ["Base"], methods: [{ name: "sides", line: 1, abstract: true }] },
[base],
);
expect(await declaresOwn.run()).toEqual([]);
expect(await withBase({ name: "Middle", line: 0, bases: ["Base", "ABC"] }, [base]).run()).toEqual([]);
});
it("accepts a class that implements the abstract method", async () => {
const project = withBase({ name: "Done", line: 0, bases: ["Base"], methods: [{ name: "dispatch", line: 1 }] }, [
{ name: "Base", line: 0, bases: [], methods: [{ name: "dispatch", line: 1, abstract: true }] },
]);
expect(await project.run()).toEqual([]);
});
it("accepts a property that implements the abstract method", async () => {
const project = withBase({ name: "Done", line: 0, bases: ["Base"], members: ["dispatch"] }, [
{ name: "Base", line: 0, bases: [], methods: [{ name: "dispatch", line: 1, abstract: true }] },
]);
expect(await project.run()).toEqual([]);
});
it("accepts an abstract method an intermediate ancestor implements", async () => {
const project = new Fixture("/p/a.py")
.add("/p/base.py", [{ name: "Base", line: 0, bases: [], methods: [{ name: "run", line: 1, abstract: true }] }])
.add("/p/mid.py", [{ name: "Mid", line: 0, bases: ["Base"], methods: [{ name: "run", line: 1 }] }])
.add("/p/a.py", [{ name: "Leaf", line: 0, bases: ["Mid"] }]);
expect(await project.run()).toEqual([]);
});
it("reports a redundant pass over a pass", async () => {
const project = withBase({ name: "C", line: 0, bases: ["Base"], methods: [{ name: "run", line: 1 }] }, [
{ name: "Base", line: 0, bases: [], methods: [{ name: "run", line: 1 }] },
]);
expect(codes(await project.run())).toEqual([["builtin:python-redundant-override", "info", 1]]);
});
it("reports a redundant returned super() forward with the same arguments", async () => {
const project = withBase(
{
name: "C",
line: 0,
bases: ["Base"],
methods: [{ name: "run", line: 1, params: ["self", "speed"], body: forward("run", ["speed"], true) }],
},
[{ name: "Base", line: 0, bases: [], methods: [{ name: "run", line: 1, params: ["self", "speed"], body: OTHER }] }],
);
expect(codes(await project.run())).toEqual([["builtin:python-redundant-override", "info", 1]]);
});
it("still reports a redundant forward whose declarer has a foreign base", async () => {
// The declarer inherits from `ABC` outside the graph; it still decides what runs.
const project = withBase(
{
name: "C",
line: 0,
bases: ["Base"],
methods: [{ name: "run", line: 1, params: ["self", "x"], body: forward("run", ["x"], true) }],
},
[
{
name: "Base",
line: 0,
bases: ["ABC"],
methods: [{ name: "run", line: 1, params: ["self", "x"] }],
},
],
);
expect(codes(await project.run())).toEqual([["builtin:python-redundant-override", "info", 1]]);
});
it("keeps a bare super() forward over a base that returns a value", async () => {
// Dropping the override would return the base's value instead of None.
const project = withBase(
{
name: "C",
line: 0,
bases: ["Base"],
methods: [{ name: "run", line: 1, params: ["self", "speed"], body: forward("run", ["speed"]) }],
},
[{ name: "Base", line: 0, bases: [], methods: [{ name: "run", line: 1, params: ["self", "speed"], body: OTHER }] }],
);
expect(await project.run()).toEqual([]);
});
it("accepts a bare super() forward over a base that returns nothing", async () => {
const project = withBase(
{
name: "C",
line: 0,
bases: ["Base"],
methods: [{ name: "run", line: 1, params: ["self", "speed"], body: forward("run", ["speed"]) }],
},
[{ name: "Base", line: 0, bases: [], methods: [{ name: "run", line: 1, params: ["self", "speed"] }] }],
);
expect(codes(await project.run())).toEqual([["builtin:python-redundant-override", "info", 1]]);
});
it("keeps an override whose base method does other work", async () => {
const project = withBase({ name: "C", line: 0, bases: ["Base"], methods: [{ name: "run", line: 1, body: OTHER }] }, [
{ name: "Base", line: 0, bases: [], methods: [{ name: "run", line: 1, body: OTHER }] },
]);
expect(await project.run()).toEqual([]);
});
it("keeps an override that changes the arguments it forwards", async () => {
const project = withBase(
{
name: "C",
line: 0,
bases: ["Base"],
methods: [{ name: "run", line: 1, params: ["self", "speed"], body: forward("run", ["speed", "1"], true) }],
},
[{ name: "Base", line: 0, bases: [], methods: [{ name: "run", line: 1, params: ["self", "speed"], body: OTHER }] }],
);
expect(await project.run()).toEqual([]);
});
it("skips a class whose header no longer matches the indexed graph", async () => {
// The graph was indexed when the class read `Base`; the document now reads `Other`.
const project = withBase({ name: "C", line: 0, bases: ["Other"], indexedBases: ["Base"] }, [
{ name: "Base", line: 0, bases: [] },
]);
expect(await project.run()).toEqual([]);
});
it("runs only the producers that are enabled", async () => {
const project = new Fixture("/p/a.py").add("/p/a.py", [
{ name: "First", line: 0, bases: ["Second"] },
{ name: "Second", line: 4, bases: ["First"] },
]);
expect(await project.run(new Set())).toEqual([]);
expect((await project.run()).length).toBe(2);
});
it("installs the inspections for Python documents only", () => {
const ctx = (language: string) => ({ doc: 1, path: "/p/a.py", language, uiMode: null, readOnly: false });
expect(pythonInheritanceExtension(ctx("typescript"))).toEqual([]);
expect(pythonInheritanceExtension(ctx("python"))).not.toEqual([]);
});
-490
Переглянути файл
@@ -1,490 +0,0 @@
/**
* Python inheritance inspections: circular inheritance, `@override` consistency, abstract
* methods a class leaves unimplemented, and overrides that only forward to the base.
*
* The rules read the IDE's inheritance graph (`inheritanceGraph.ts`) plus the facts the
* Python parser reports for a document (`docPythonFacts`). Nothing here parses source text,
* and a rule stays silent whenever the graph cannot decide: a base the project does not
* contain (`dict`, a library class) may declare or implement anything, and a missing
* warning is cheaper than a wrong one.
*/
import type { Extension } from "@codemirror/state";
import { ViewPlugin, type EditorView } from "@codemirror/view";
import type { EditorDocContext } from "@/editor/api";
import { onServerSettled } from "@/editor/lsp/availability";
import { setFileDiagnostics } from "@/editor/lsp/diagnostics";
import { withDocument } from "@/editor/lsp/files";
import { lspRequest } from "@/editor/lsp/lsp";
import {
ancestryResolution,
declarationKey,
forgetInheritanceGraph,
projectPythonIndex,
type AncestryResolution,
type InheritanceIndex,
} from "@/editor/navigation/inheritanceGraph";
import { tx } from "@/platform/i18n";
import {
PYTHON_ABSTRACT_METHOD_INSPECTION,
PYTHON_ABSTRACT_METHOD_PRODUCER,
PYTHON_CIRCULAR_BASES_INSPECTION,
PYTHON_CIRCULAR_BASES_PRODUCER,
PYTHON_OVERRIDE_INSPECTION,
PYTHON_OVERRIDE_PRODUCER,
PYTHON_REDUNDANT_OVERRIDE_INSPECTION,
PYTHON_REDUNDANT_OVERRIDE_PRODUCER,
applyProfile,
enabledByDefault,
inspectionProfile,
producerInspectionId,
} from "@/platform/inspections";
import {
commands,
isCancelled,
isTauri,
onIdeEvent,
type ClassInheritance,
type Diagnostic,
type OutlineItem,
type PythonClassFacts,
type PythonFacts,
type PythonMethodFacts,
type Range,
} from "@/platform/ipc";
/** The inspection producers, one per rule. */
const PRODUCERS = [
PYTHON_CIRCULAR_BASES_PRODUCER,
PYTHON_OVERRIDE_PRODUCER,
PYTHON_ABSTRACT_METHOD_PRODUCER,
PYTHON_REDUNDANT_OVERRIDE_PRODUCER,
];
/** What the rules read for one document: its own facts and a way to read another file's. */
export interface InheritanceInspectionDeps {
path: string;
outline: readonly OutlineItem[];
facts: PythonFacts;
index: InheritanceIndex;
factsOf: (path: string) => Promise<PythonFacts | null>;
outlineOf: (path: string) => Promise<readonly OutlineItem[]>;
/** Producers whose inspection is on; missing means every rule runs. */
enabled?: ReadonlySet<string>;
}
const isDunder = (name: string) => name.startsWith("__") && name.endsWith("__");
const baseName = (name: string) => name.replace(/\s*[(<].*$/, "");
const sameNames = (a: readonly string[], b: readonly string[]) =>
a.length === b.length && a.every((name, i) => name === b[i]);
/** One class of the document: its graph declaration, its facts and its members. */
interface ClassView {
decl: ClassInheritance;
facts: PythonClassFacts;
/** Names the class itself declares: methods, fields, properties, nested types. */
members: ReadonlySet<string>;
/** How deep the ancestry stays inside the project (`Infinity`: all of it). */
firstUnresolvedDepth: number;
}
/** Everything the rules need for one document, with every project read memoised. */
class ProjectView {
private facts = new Map<string, Promise<PythonFacts | null>>();
private outlines = new Map<string, Promise<readonly OutlineItem[]>>();
private ancestry = new Map<string, Promise<AncestryResolution>>();
constructor(private readonly deps: InheritanceInspectionDeps) {}
/** The document's classes, in declaration order, skipping ones the graph does not match. */
async classes(): Promise<ClassView[]> {
const out: ClassView[] = [];
for (const facts of this.deps.facts.classes) {
const decl = this.declarationOf(facts);
if (!decl) continue;
const item = classItem(this.deps.outline, facts);
const { firstUnresolvedDepth } = await this.ancestryOf(decl);
out.push({ decl, facts, members: memberNames(item), firstUnresolvedDepth });
}
return out;
}
/** The ancestors of `cls`, with the depth each sits at. */
ancestors(cls: ClassView): Promise<AncestryResolution["ancestors"]> {
return this.ancestryOf(cls.decl).then((r) => r.ancestors);
}
/** Whether the whole chain resolved inside the project. */
complete(cls: ClassView): boolean {
return cls.firstUnresolvedDepth === Infinity;
}
/** Whether the chain is trustworthy at `depth`: no foreign base sits above it. */
knownTo(cls: ClassView, depth: number): boolean {
return cls.firstUnresolvedDepth > depth;
}
async methodsOf(decl: ClassInheritance): Promise<PythonMethodFacts[]> {
const facts = await this.factsOf(decl.path);
return facts?.classes.find((c) => sameDeclaration(c, decl))?.methods ?? [];
}
async membersOf(decl: ClassInheritance): Promise<ReadonlySet<string>> {
const outline = await this.outlineOf(decl.path);
const item = outline.find(
(i) =>
i.kind === "class" && i.selection_range.start.line === decl.line && i.selection_range.start.col === decl.col,
);
return memberNames(item ?? null);
}
private declarationOf(facts: PythonClassFacts): ClassInheritance | null {
const found = this.deps.index.byName.get(facts.name) ?? [];
return (
found.find(
(c) =>
c.path === this.deps.path && c.line === facts.selection.start.line && c.col === facts.selection.start.col,
) ?? null
);
}
private factsOf(path: string): Promise<PythonFacts | null> {
return memo(this.facts, path, () => this.deps.factsOf(path));
}
private outlineOf(path: string): Promise<readonly OutlineItem[]> {
return memo(this.outlines, path, () => this.deps.outlineOf(path));
}
private ancestryOf(decl: ClassInheritance): Promise<AncestryResolution> {
return memo(this.ancestry, declarationKey(decl), () => ancestryResolution(this.deps.index, decl));
}
}
function memo<T>(cache: Map<string, Promise<T>>, key: string, read: () => Promise<T>): Promise<T> {
let pending = cache.get(key);
if (!pending) {
pending = read();
cache.set(key, pending);
}
return pending;
}
/** The names a class declares: methods, fields, properties, nested types. */
function memberNames(item: OutlineItem | null): ReadonlySet<string> {
return new Set((item?.children ?? []).map((child) => baseName(child.name)));
}
function classItem(outline: readonly OutlineItem[], cls: PythonClassFacts): OutlineItem | null {
const find = (items: readonly OutlineItem[]): OutlineItem | null => {
for (const item of items) {
if (
item.kind === "class" &&
item.selection_range.start.line === cls.selection.start.line &&
item.selection_range.start.col === cls.selection.start.col
) {
return item;
}
const deeper = find(item.children);
if (deeper) return deeper;
}
return null;
};
return find(outline);
}
function sameDeclaration(cls: PythonClassFacts, decl: ClassInheritance): boolean {
return cls.selection.start.line === decl.line && cls.selection.start.col === decl.col;
}
/** Everything the four rules produce for one document. */
export async function inheritanceDiagnostics(deps: InheritanceInspectionDeps): Promise<Diagnostic[]> {
const view = new ProjectView(deps);
const runs = (producer: string) => deps.enabled?.has(producer) ?? true;
const out: Diagnostic[] = [];
for (const cls of await view.classes()) {
// A class whose header changed since the graph was indexed is skipped: every rule
// below would reason about a parent the source no longer names.
if (!sameNames(cls.facts.bases, cls.decl.bases)) continue;
if (runs(PYTHON_CIRCULAR_BASES_PRODUCER)) out.push(...(await circularInheritance(view, cls)));
// A method may live on any ancestor: only a fully known chain can say it does not.
if (runs(PYTHON_OVERRIDE_PRODUCER) && view.complete(cls)) out.push(...(await unusedOverride(view, cls)));
if (runs(PYTHON_REDUNDANT_OVERRIDE_PRODUCER)) out.push(...(await redundantOverride(view, cls)));
if (runs(PYTHON_ABSTRACT_METHOD_PRODUCER)) out.push(...(await missingAbstractMethods(view, cls)));
}
return out;
}
/** A class that (transitively) inherits from itself: Python raises at import time. */
async function circularInheritance(view: ProjectView, cls: ClassView): Promise<Diagnostic[]> {
const ancestors = await view.ancestors(cls);
if (!ancestors.some((a) => declarationKey(a.decl) === declarationKey(cls.decl))) return [];
return [
problem(
cls.facts.selection,
PYTHON_CIRCULAR_BASES_INSPECTION,
"error",
tx`Circular inheritance: '${cls.facts.name}' inherits from itself`,
),
];
}
/** `@override` on a method no ancestor declares: a typo, or a base that changed name. */
async function unusedOverride(view: ProjectView, cls: ClassView): Promise<Diagnostic[]> {
const out: Diagnostic[] = [];
for (const method of cls.facts.methods) {
if (!method.overrideDecorated || isDunder(method.name)) continue;
if (await declaredInAncestry(view, cls, method.name)) continue;
out.push(
problem(
method.selection,
PYTHON_OVERRIDE_INSPECTION,
"warning",
tx`Method '${method.name}' is marked @override but no base class declares it`,
),
);
}
return out;
}
/** Abstract methods of the ancestry that no class on the way down implements. */
async function missingAbstractMethods(view: ProjectView, cls: ClassView): Promise<Diagnostic[]> {
// A class that is itself abstract (it declares abstract methods, or names `ABC` or
// `Protocol` as a base) leaves the implementing to its subclasses.
if (cls.facts.methods.some((m) => m.abstractMethod) || cls.facts.bases.some((b) => b === "ABC" || b === "Protocol"))
return [];
const out: Diagnostic[] = [];
const reported = new Set<string>();
for (const ancestor of await view.ancestors(cls)) {
// A foreign base above the declarer cannot override it: Python's MRO puts it later.
if (!view.knownTo(cls, ancestor.depth - 1)) continue;
for (const method of await view.methodsOf(ancestor.decl)) {
const name = method.name;
if (!method.abstractMethod || reported.has(name) || cls.members.has(name)) continue;
if (await implementedAbove(view, cls, ancestor.depth, name)) continue;
reported.add(name);
out.push(
problem(
cls.facts.selection,
PYTHON_ABSTRACT_METHOD_INSPECTION,
"warning",
tx`Class '${cls.facts.name}' does not implement abstract method '${name}'`,
),
);
}
}
return out;
}
/** Whether an ancestor nearer than `declarer` implements `name` concretely. */
async function implementedAbove(
view: ProjectView,
cls: ClassView,
declarerDepth: number,
name: string,
): Promise<boolean> {
for (const ancestor of await view.ancestors(cls)) {
if (ancestor.depth >= declarerDepth) return false;
if (!view.knownTo(cls, ancestor.depth - 1)) return true;
const method = (await view.methodsOf(ancestor.decl)).find((m) => m.name === name);
if (method) return !method.abstractMethod;
if ((await view.membersOf(ancestor.decl)).has(name)) return true;
}
return false;
}
/** A method whose body the inherited method already provides. */
async function redundantOverride(view: ProjectView, cls: ClassView): Promise<Diagnostic[]> {
const out: Diagnostic[] = [];
for (const method of cls.facts.methods) {
const inherited = await inheritedMethod(view, cls, method.name);
// A foreign base below the declarer cannot change which method runs: MRO puts it later.
if (!inherited || !view.knownTo(cls, inherited.depth)) continue;
if (inherited.method.abstractMethod || !redundantBody(method, inherited.method)) continue;
out.push(
problem(
method.selection,
PYTHON_REDUNDANT_OVERRIDE_INSPECTION,
"info",
tx`Redundant override of '${method.name}'`,
),
);
}
return out;
}
/**
* Whether deleting `override` keeps what it does: it is a no-op over a no-op, or it forwards
* exactly its own parameters to the inherited method (a bare call only when the inherited
* method returns nothing, so discarding its value changes nothing).
*/
function redundantBody(override: PythonMethodFacts, base: PythonMethodFacts): boolean {
if (override.body.kind === "empty") return base.body.kind === "empty";
if (override.body.kind !== "superCall") return false;
if (override.body.target !== override.name) return false;
if (!override.params || !base.params) return false;
if (!sameNames(base.params, override.params)) return false;
// `super().m()` forwards every parameter but the receiver.
if (!sameNames(override.body.args, override.params.slice(1))) return false;
return override.body.returns || base.body.kind === "empty";
}
/** The nearest ancestor's method `name`. */
async function inheritedMethod(
view: ProjectView,
cls: ClassView,
name: string,
): Promise<{ method: PythonMethodFacts; depth: number } | null> {
for (const ancestor of await view.ancestors(cls)) {
const found = (await view.methodsOf(ancestor.decl)).find((m) => m.name === name);
if (found) return { method: found, depth: ancestor.depth };
}
return null;
}
/** Whether any ancestor declares `name`, as a member or a method. */
async function declaredInAncestry(view: ProjectView, cls: ClassView, name: string): Promise<boolean> {
for (const ancestor of await view.ancestors(cls)) {
if ((await view.membersOf(ancestor.decl)).has(name)) return true;
if ((await view.methodsOf(ancestor.decl)).some((m) => m.name === name)) return true;
}
return false;
}
const problem = (range: Range, producer: string, severity: Diagnostic["severity"], message: string): Diagnostic => ({
range,
severity,
message,
source: "Python",
code: producer,
});
// --- the editor plugin -------------------------------------------------------
const DEBOUNCE_MS = 500;
const SOURCE = "Python";
const refreshables = new Set<() => void>();
let watching = false;
/** Python files are the ones that change this inheritance graph. */
const isPythonFile = (path: string) => path.endsWith(".py") || path.endsWith(".pyi");
/** One subscription per window: the graph's inputs changed, so re-run every open document. */
function watchChanges() {
if (watching) return;
watching = true;
const refreshAll = () => {
forgetInheritanceGraph();
for (const refresh of refreshables) refresh();
};
onIdeEvent("fsChanged", (e) => {
if ([...e.created, ...e.modified, ...e.removed].some(isPythonFile)) refreshAll();
});
onServerSettled(refreshAll);
}
/** The producers whose inspection is on in the profile in effect. */
function enabledProducers(): Set<string> {
const profile = inspectionProfile();
return new Set(
PRODUCERS.filter((producer) => {
const id = producerInspectionId(producer);
return profile[id]?.enabled ?? enabledByDefault(id);
}),
);
}
/** The inspection id -> producer, for applying the profile to what the rules produced. */
const PRODUCER_OF = new Map(PRODUCERS.map((producer) => [producerInspectionId(producer), producer]));
/** Applies the profile in effect to `diagnostics` (their `code` is the inspection id). */
function applyProfileTo(diagnostics: readonly Diagnostic[]): Diagnostic[] {
const profile = inspectionProfile();
const grouped = new Map<string, Diagnostic[]>();
for (const diagnostic of diagnostics) {
const id = diagnostic.code ?? "";
grouped.set(id, [...(grouped.get(id) ?? []), diagnostic]);
}
return [...grouped].flatMap(([id, items]) => [
...(applyProfile(profile, PRODUCER_OF.get(id) ?? id, items) as readonly Diagnostic[]),
]);
}
const viewers = new Map<string, number>();
const hasClass = (items: readonly OutlineItem[]): boolean =>
items.some((item) => item.kind === "class" || hasClass(item.children));
/** Runs the inspections on Python documents and publishes them as local diagnostics. */
export function pythonInheritanceExtension(ctx: EditorDocContext): Extension {
if (ctx.language !== "python" || ctx.virtual || ctx.doc < 0) return [];
watchChanges();
return ViewPlugin.define((view: EditorView) => {
if (!isTauri()) return {};
viewers.set(ctx.path, (viewers.get(ctx.path) ?? 0) + 1);
let timer: ReturnType<typeof setTimeout> | undefined;
let sequence = 0;
let disposed = false;
const run = async () => {
const enabled = enabledProducers();
if (!enabled.size) {
setFileDiagnostics(ctx.path, SOURCE, []);
return;
}
const mine = ++sequence;
const text = view.state.doc;
try {
const outline = await lspRequest(() => commands.docOutline(ctx.doc));
// Every rule is about a class: no class, nothing to fetch the graph for.
if (!hasClass(outline)) {
setFileDiagnostics(ctx.path, SOURCE, []);
return;
}
const [facts, project] = await Promise.all([
lspRequest(() => commands.docPythonFacts(ctx.doc)),
projectPythonIndex(),
]);
const found = await inheritanceDiagnostics({
path: ctx.path,
outline,
facts,
index: project.index,
enabled,
factsOf: (path) =>
withDocument(path, (doc) => lspRequest(() => commands.docPythonFacts(doc))).catch(() => null),
outlineOf: (path) => withDocument(path, (doc) => lspRequest(() => commands.docOutline(doc))).catch(() => []),
});
if (disposed || mine !== sequence || view.state.doc !== text) return;
// The profile decides what is shown and how strongly.
setFileDiagnostics(ctx.path, SOURCE, applyProfileTo(found));
} catch (e) {
if (!isCancelled(e)) console.debug("[inheritanceInspections]", e);
}
};
const schedule = () => {
clearTimeout(timer);
sequence++;
timer = setTimeout(() => void run(), DEBOUNCE_MS);
};
const refresh = () => schedule();
refreshables.add(refresh);
schedule();
return {
update: (update) => {
if (update.docChanged) schedule();
},
destroy: () => {
disposed = true;
clearTimeout(timer);
refreshables.delete(refresh);
const left = (viewers.get(ctx.path) ?? 1) - 1;
if (left > 0) {
viewers.set(ctx.path, left);
return;
}
viewers.delete(ctx.path);
setFileDiagnostics(ctx.path, SOURCE, []);
},
};
});
}
-1
Переглянути файл
@@ -160,7 +160,6 @@ export function HierarchyView() {
<span className={styles.row}>
<SymbolBadge kind={mode === "call" ? "function" : "class"} />
<span className={styles.name}>{root.name}</span>
{root.detail && <span className={styles.detail}>{root.detail}</span>}
<span className={styles.muted}>
{basename(root.path)}:{root.line + 1}
</span>
-17
Переглянути файл
@@ -39,8 +39,6 @@ export interface HierarchyRoot {
path: string;
line: number;
col: number;
/** The server's detail for the root type (its package for Java), shown beside the name. */
detail?: string | null;
}
interface HierarchyState {
@@ -227,20 +225,6 @@ function setChildren(
type RootResult = "loaded" | "noTarget" | "failed" | "stale";
/** The root type's detail (Java: its package), like the nodes below it show theirs. */
async function loadRootDetail(generation: number, root: HierarchyRoot) {
try {
const item = await withDocument(root.path, (doc) =>
call(commands.lspPrepareTypeHierarchy(doc, { line: root.line, col: root.col })),
);
const s = useHierarchy.getState();
if (s.generation !== generation || s.root !== root || !item?.detail) return;
useHierarchy.setState({ root: { ...root, detail: item.detail } });
} catch {
// Older servers (remote) and servers without type hierarchy: the name alone.
}
}
/** Loads the root's level. `quiet`: a position without a symbol isn't reported (the caller retries). */
async function loadRoot(quiet = false): Promise<RootResult> {
const s = useHierarchy.getState();
@@ -255,7 +239,6 @@ async function loadRoot(quiet = false): Promise<RootResult> {
);
setChildren(generation, ROOT_ID, [rootKey(root)], items, incomplete && incompleteNote(incomplete, root.name));
prefetchLevels(useHierarchy.getState().children.get(ROOT_ID) ?? []);
if (s.mode === "type") void loadRootDetail(generation, root);
return "loaded";
} catch (e) {
if (useHierarchy.getState().generation !== generation) return "stale";
+14 -52
Переглянути файл
@@ -6,11 +6,11 @@
*/
import { useEffect, useRef } from "react";
import clsx from "clsx";
import { BarButton, Button, IconButton, Popup, T } from "@/ui";
import { BarButton, Button, Popup, T } from "@/ui";
import { executeAction } from "@/platform/actions";
import { call, commands, isTauri, type AppMetrics } from "@/platform/ipc";
import { isTauri, type AppMetrics } from "@/platform/ipc";
import { formatBytes, formatCount, formatMs, formatSize, formatUptime } from "./format";
import { indicatorLabel, indicatorTooltip, memorySections, summarizeMemory, type BreakdownRow } from "./memory";
import { indicatorLabel, indicatorTooltip, memorySections, summarizeMemory } from "./memory";
import { startPolling } from "./poll";
import { METRICS_INTERVAL_MS, refreshMetrics, usePerf } from "./store";
import styles from "./perf.module.css";
@@ -82,40 +82,6 @@ function Row({ label, detail, value, title, indented }: RowProps) {
);
}
async function endProcess(pid: number) {
const error = await call(commands.endProcess(pid)).then(
() => null,
(e: unknown) => String(e),
);
await refreshMetrics();
if (error) usePerf.setState({ error });
}
function ProcessRow({ row }: { row: BreakdownRow }) {
const title = row.processes > 1 ? tx`PID ${row.pid} · ${row.processes} processes` : tx`PID ${row.pid}`;
return (
<div className={clsx(styles.row, styles.indented, styles.processRow)} title={title}>
<span className={styles.label}>
{row.label}
{row.detail && <span className={styles.detail}>{row.detail}</span>}
</span>
<span className={clsx(styles.value, styles.cpu)}>{row.cpu}</span>
<span className={clsx(styles.value, styles.memory)}>{row.value}</span>
<span className={styles.end}>
{row.endable && (
<IconButton
icon="close"
size="small"
iconSize={14}
title={tx`End Process ${row.label}`}
onClick={() => void endProcess(row.pid)}
/>
)}
</span>
</div>
);
}
export function MemoryDetails({ metrics: m }: { metrics: AppMetrics }) {
const error = usePerf((s) => s.error);
const s = m.syntax;
@@ -123,26 +89,22 @@ export function MemoryDetails({ metrics: m }: { metrics: AppMetrics }) {
const sections = memorySections(m.memory ?? []);
return (
<div className={styles.panel}>
<div className={clsx(styles.header, styles.columns)}>
<span className={styles.groupTitle}>{tx("Memory & Diagnostics")}</span>
<span className={styles.cpu}>
<T>CPU</T>
</span>
<span className={styles.memory}>
<T>Memory</T>
</span>
<span className={styles.end} />
</div>
<div className={styles.header}>{tx("Memory & Diagnostics")}</div>
{sections.map((sec) => (
<div key={sec.title} className={styles.section} aria-label={sec.title} role="group">
<div className={clsx(styles.groupRow, styles.processRow)}>
<div className={styles.groupRow}>
<span className={styles.groupTitle}>{sec.title}</span>
<span className={clsx(styles.value, styles.cpu)}>{sec.cpu}</span>
<span className={clsx(styles.value, styles.memory)}>{sec.total}</span>
<span className={styles.end} />
<span className={styles.value}>{sec.total}</span>
</div>
{sec.rows.map((r) => (
<ProcessRow key={r.key} row={r} />
<Row
key={r.key}
label={r.label}
detail={r.detail}
value={r.value}
title={r.processes > 1 ? tx`${r.processes} processes` : undefined}
indented
/>
))}
</div>
))}
+2 -16
Переглянути файл
@@ -141,15 +141,7 @@ describe("polling", () => {
});
const row = (category: ProcessMemory["category"], label: string, mb: number | null, detail: string | null = null) =>
({
category,
label,
detail,
pid: 1,
processes: 1,
bytes: mb == null ? null : mb * MB,
cpuPercent: null,
}) satisfies ProcessMemory;
({ category, label, detail, processes: 1, bytes: mb == null ? null : mb * MB }) satisfies ProcessMemory;
describe("memory breakdown", () => {
const rows: ProcessMemory[] = [
@@ -158,7 +150,7 @@ describe("memory breakdown", () => {
row("app", "GPU", 40),
row("app", "Networking", 20),
row("languageServer", "jdtls", 900, "idea"),
{ ...row("languageServer", "rust-analyzer", 226, "idea"), pid: 300, processes: 2, cpuPercent: 12.4 },
{ ...row("languageServer", "rust-analyzer", 226, "idea"), processes: 2 },
row("process", "zsh", null, "Terminal"),
];
@@ -187,14 +179,8 @@ describe("memory breakdown", () => {
label: "rust-analyzer",
detail: "idea",
value: "226 MB",
cpu: "12%",
pid: 300,
processes: 2,
endable: true,
});
expect(sections[1]!.cpu).toBe("12%");
expect(sections[0]!.cpu).toBe("–");
expect(sections[0]!.rows.every((r) => !r.endable)).toBe(true);
expect(memorySections([])).toEqual([]);
});
});
+5 -34
Переглянути файл
@@ -1,5 +1,4 @@
import { act, fireEvent, render, screen } from "@testing-library/react";
import { clearMocks, mockIPC } from "@tauri-apps/api/mocks";
import { act, render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import type { AppMetrics } from "@/platform/ipc";
import { MemoryDetails } from "../MemoryStatus";
@@ -23,18 +22,10 @@ const metrics: AppMetrics = {
languageServers: 2,
syntax: { documents: 4, trees: 2, treeTextBytes: 2 * MB, hits: 10, incrementalParses: 5, fullParses: 2 },
memory: [
{ category: "app", label: "Backend", detail: null, pid: 10, processes: 1, bytes: 60 * MB, cpuPercent: 4.25 },
{ category: "app", label: "Web content", detail: "idea", pid: 11, processes: 1, bytes: 300 * MB, cpuPercent: 1 },
{
category: "languageServer",
label: "jdtls",
detail: "idea",
pid: 20,
processes: 2,
bytes: 900 * MB,
cpuPercent: 0,
},
{ category: "process", label: "codelldb", detail: null, pid: 30, processes: 1, bytes: 30 * MB, cpuPercent: null },
{ category: "app", label: "Backend", detail: null, processes: 1, bytes: 60 * MB },
{ category: "app", label: "Web content", detail: "idea", processes: 1, bytes: 300 * MB },
{ category: "languageServer", label: "jdtls", detail: "idea", processes: 1, bytes: 900 * MB },
{ category: "process", label: "codelldb", detail: null, processes: 1, bytes: 30 * MB },
],
};
@@ -58,26 +49,6 @@ describe("perf views", () => {
expect(screen.getByText("Backend malloc in use")).toBeTruthy();
expect(screen.getByText("40 ms")).toBeTruthy();
expect(screen.getByRole("button", { name: /Clear caches/ })).toBeTruthy();
expect(openidea.textContent).toContain("5.3%");
expect(servers.textContent).toContain("0%");
expect(screen.getByTitle("PID 20 · 2 processes")).toBeTruthy();
});
it("ends language servers and processes, never OpenIDEA's own", async () => {
const calls: [string, unknown][] = [];
mockIPC((cmd, args) => {
calls.push([cmd, args]);
if (cmd === "end_process") return true;
if (cmd === "app_metrics") return metrics;
});
render(<MemoryDetails metrics={metrics} />);
expect(screen.queryByRole("button", { name: "End Process Backend" })).toBeNull();
expect(screen.queryByRole("button", { name: "End Process Web content" })).toBeNull();
expect(screen.getByRole("button", { name: "End Process codelldb" })).toBeTruthy();
await act(async () => fireEvent.click(screen.getByRole("button", { name: "End Process jdtls" })));
expect(calls[0]).toEqual(["end_process", { pid: 20 }]);
expect(calls.some(([cmd]) => cmd === "app_metrics")).toBe(true);
clearMocks();
});
it("overlay is off by default and degrades without PerformanceObserver", async () => {
-7
Переглянути файл
@@ -29,13 +29,6 @@ export function formatSize(bytes: number | null | undefined): string {
return `${trim(bytes / GB)} GB`;
}
/** `0%`, `3.2%`, `45%`, `180%` (percent of one core, so several busy cores exceed 100). */
export function formatPercent(p: number | null | undefined): string {
if (p == null || !Number.isFinite(p) || p < 0) return "–";
if (p < 0.05) return "0%";
return p < 10 ? `${trim(p)}%` : `${Math.round(p)}%`;
}
/** `0.4 ms`, `16 ms`, `2.3 s`. */
export function formatMs(ms: number | null | undefined): string {
if (ms == null || !Number.isFinite(ms)) return "–";
+1 -15
Переглянути файл
@@ -1,6 +1,6 @@
/** Memory breakdown from `AppMetrics.memory`: totals per group and the popup sections. */
import type { AppMetrics, MemoryCategory, ProcessMemory } from "@/platform/ipc";
import { formatBytes, formatPercent, formatSize } from "./format";
import { formatBytes, formatSize } from "./format";
export interface MemorySummary {
/** Backend + its WebView processes. */
@@ -45,25 +45,15 @@ export interface BreakdownRow {
/** Project, windows, run kind… */
detail: string | null;
value: string;
cpu: string;
pid: number;
processes: number;
/** A language server, run, terminal or other child the user may end (never OpenIDEA's own processes). */
endable: boolean;
}
export interface BreakdownSection {
title: string;
total: string;
cpu: string;
rows: BreakdownRow[];
}
function cpuSum(rows: ProcessMemory[]): number | null {
const known = rows.filter((r) => r.cpuPercent != null);
return known.length ? known.reduce((n, r) => n + r.cpuPercent!, 0) : null;
}
const SECTIONS: Array<{ category: MemoryCategory; title: string }> = [
{ category: "app", title: "OpenIDEA" },
{ category: "languageServer", title: "Language servers" },
@@ -79,16 +69,12 @@ export function memorySections(rows: ProcessMemory[]): BreakdownSection[] {
{
title,
total: formatSize(sum(items)),
cpu: formatPercent(cpuSum(items)),
rows: items.map((r, i) => ({
key: `${category}:${i}:${r.label}`,
label: r.label,
detail: r.detail,
value: formatSize(r.bytes),
cpu: formatPercent(r.cpuPercent),
pid: r.pid,
processes: r.processes,
endable: category !== "app",
})),
},
];
+1 -42
Переглянути файл
@@ -2,7 +2,7 @@
gap: 6px;
}
.panel {
width: 380px;
width: 340px;
padding: 6px 0;
font-family: var(--font-ui);
font-size: var(--fs-ui);
@@ -61,47 +61,6 @@
color: var(--fg-emphasis);
white-space: nowrap;
}
.columns {
display: flex;
align-items: center;
gap: 8px;
}
.columns .groupTitle {
color: var(--fg-subtle);
}
.processRow {
padding-right: 4px;
}
.columns {
padding-right: 4px;
}
.cpu,
.memory {
flex: none;
text-align: right;
}
.cpu {
width: 44px;
}
.memory {
width: 60px;
}
.processRow .value {
margin-left: 0;
}
.end {
flex: none;
display: flex;
justify-content: center;
width: 20px;
}
.end button {
opacity: 0;
}
.processRow:hover .end button,
.end button:focus-visible {
opacity: 1;
}
.error {
padding: 2px 12px;
color: var(--danger);
-14
Переглянути файл
@@ -613,20 +613,6 @@ describe("Show Members", () => {
},
);
it("autoscrolls to source without handing files to another application", async () => {
const { rows, row } = setup();
act(() => {
setViewOption("autoscrollToSource", true);
setViewOption("singleClickOpen", false);
setViewOption("previewTab", false);
});
await waitFor(() => expect(rows()).toContain("README.md"));
fireEvent.mouseDown(row("README.md"));
await waitFor(() =>
expect(openFile).toHaveBeenLastCalledWith("/w/acme/README.md", expect.objectContaining({ external: false })),
);
});
it("honours member single-click options and double-click focus", async () => {
ipc.docOpen.mockResolvedValue(ok({ id: 7 }));
ipc.docClose.mockResolvedValue(ok(null));
+2 -2
Переглянути файл
@@ -566,9 +566,9 @@ export function ProjectView() {
void revealRange(
lead.path,
{ start: lead.member.selection_range.start },
{ preview: o.previewTab, focus: false, external: false },
{ preview: o.previewTab, focus: false },
);
} else void openFile(lead.path, { preview: o.previewTab, focus: false, external: false });
} else void openFile(lead.path, { preview: o.previewTab, focus: false });
}, []);
const onActivate = useCallback((node: ProjectNode) => {
+3 -3
Переглянути файл
@@ -376,10 +376,10 @@ export function contextMenuItems(nodes: ProjectNode[]): MenuItem[] {
act("vcs.rollback", arg, "Rollback…"),
{ kind: "separator" },
act("vcs.push", undefined, "Push…"),
act("vcs.pull", arg, "Pull…"),
act("vcs.update", undefined, "Pull…"),
act("vcs.fetch", undefined, "Fetch"),
act("vcs.merge", arg, "Merge…"),
act("vcs.rebase", arg, "Rebase…"),
act("vcs.merge", undefined, "Merge…"),
act("vcs.rebase", undefined, "Rebase…"),
{ kind: "separator" },
act("vcs.branches", undefined, "Branches…"),
act("vcs.newBranch", undefined, "New Branch…"),
+2 -2
Переглянути файл
@@ -127,14 +127,14 @@ function expandFolder(path: string) {
// ---------------------------------------------------------------------------
// Open
export async function openFile(path: string, opts: { preview?: boolean; focus?: boolean; external?: boolean } = {}) {
export async function openFile(path: string, opts: { preview?: boolean; focus?: boolean } = {}) {
const editor = maybeEditorService();
if (!editor) {
notifications().notify({ level: "warning", title: "No editor available", body: path, key: "project.noEditor" });
return;
}
try {
await editor.openFile(path, { preview: opts.preview, focus: opts.focus ?? true, external: opts.external });
await editor.openFile(path, { preview: opts.preview, focus: opts.focus ?? true });
} catch (e) {
fail(`Cannot open ${nameOf(path)}`, e);
}
+3 -7
Переглянути файл
@@ -4,7 +4,7 @@
*/
import { useProject } from "@/platform/project";
import { buildCMake, isCMakeBuild } from "./cmake";
import { dotnetProjectFile } from "./dotnetTypes";
import { dotnetBuildConfig } from "./dotnetTypes";
import { useBuildPresentation } from "@/platform/projectPresentation";
import { buildTask } from "./buildTask";
import { moduleTaskError } from "./configs";
@@ -84,12 +84,8 @@ async function runTask(
): Promise<string | null> {
const target = task.target ?? "";
switch (task.kind) {
case "dotnetBuild": {
// In the Build tool window, like Build Project: its messages link to the sources.
const project = dotnetProjectFile(config);
if (!project) return "Select a .NET project";
return buildTask("build.buildModule", { target: project, activate: false, wait: true });
}
case "dotnetBuild":
return (await runToEnd(dotnetBuildConfig(config), chain, show)) ? null : "Build failed";
case "build": {
if (target) return buildCMake(target, show === true);
const error = await buildTask(BUILD_ACTION, { activate: false });
+10 -6
Переглянути файл
@@ -3,7 +3,7 @@ import { fireEvent, render, screen } from "@testing-library/react";
import { commands } from "@/platform/ipc";
import type { RunConfig } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { dotnetProjectFile, dotnetProjectType, dotnetTestType } from "./dotnetTypes";
import { dotnetBuildConfig, dotnetProjectType, dotnetTestType } from "./dotnetTypes";
import { ConfigForm } from "./ConfigForm";
import { validateConfig } from "./configs";
import { formParams, newConfigOfType, registerBuiltinTypes, withParams } from "./types";
@@ -99,12 +99,16 @@ describe(".NET configurations", () => {
expect(formParams({ ...typed, args: ["build", "A"] }, dotnetProjectType)).toBeNull();
});
it("builds the edited project from the open root instead of a profile cwd", () => {
it("builds edited project/framework from the open root instead of a profile cwd", () => {
useProject.setState({ project: { root: "/repo" } as never });
const c = withParams({ ...config(), cwd: "profile/work" }, { ...params, project: "other/App.csproj" });
expect(dotnetProjectFile(c)).toBe("/repo/other/App.csproj");
expect(dotnetProjectFile(withParams(c, { ...params, project: "C:\\src\\App.csproj" }))).toBe("C:\\src\\App.csproj");
expect(dotnetProjectFile(withParams(c, { ...params, project: "" }))).toBeNull();
const c = withParams(
{ ...config(), cwd: "profile/work" },
{ ...params, project: "other/App.csproj", framework: "net9.0" },
);
const build = dotnetBuildConfig(c);
expect(build.args).toEqual(["build", "other/App.csproj", "--configuration", "Debug", "--framework", "net9.0"]);
expect(build.cwd).toBe("/repo");
expect(build.beforeLaunch).toEqual([]);
});
it("edits project, framework, profile, arguments and environment in the shared form", () => {
+18 -7
Переглянути файл
@@ -61,13 +61,24 @@ function dotnetRunParams(c: RunConfig): Record<string, string> | null {
return { project: "", ...p };
}
/** The configuration's project file as a path the Build tool window builds (its own project, not the profile's cwd). */
export function dotnetProjectFile(config: RunConfig): string | null {
const project = config.params?.project?.trim();
if (!project) return null;
if (/^(?:[A-Za-z]:[\\/]|\/)/.test(project)) return project;
const root = useProject.getState().project?.root;
return root ? `${root}/${project}` : null;
/** Build the current project/framework, independently of the run's profile working directory. */
export function dotnetBuildConfig(config: RunConfig): RunConfig {
const p = config.params ?? {};
return {
...config,
id: `dotnet-build:${config.id}`,
name: `dotnet build (${p.project || ""})`,
kind: "shell",
args: ["build", p.project || "", "--configuration", "Debug", ...(p.framework ? ["--framework", p.framework] : [])],
cwd: useProject.getState().project?.root ?? null,
env: {},
params: {},
isTest: false,
debugAdapter: null,
beforeLaunch: [],
emulateTerminal: false,
stdinFile: undefined,
};
}
export const dotnetProjectType: RunConfigTypeContribution = {
-2
Переглянути файл
@@ -64,7 +64,6 @@ import { isDebugOnly, registerBuiltinTypes } from "./types";
import { junitType } from "./junitType";
import { listenForApplicationDeactivation, showApplicationUpdate, updatableSessions } from "./applicationUpdate";
import { npmGutter } from "./npmGutter";
import { launchSettingsGutter } from "./launchSettingsGutter";
import { runGutter } from "./runGutter";
import { gradleDelegation } from "./gradleRun";
import { activateStackTrace, useStackTraces } from "./stackTrace";
@@ -447,7 +446,6 @@ export function activate(): () => void {
}),
registerEditorContribution({ id: "run.targets", order: 55, extensions: runGutter }),
registerEditorContribution({ id: "run.npmScripts", order: 58, extensions: npmGutter }),
registerEditorContribution({ id: "run.launchSettings", order: 58, extensions: launchSettingsGutter }),
registerMenuGroup({
id: "run.context",
menus: ["editor", "projectView", "editorTab"],
-70
Переглянути файл
@@ -1,70 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import type { RunConfig } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { profileConfig, projectProfiles } from "./launchSettingsGutter";
const SETTINGS = `{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"http": {
"commandName": "Project",
"applicationUrl": "http://localhost:5170"
},
"IIS Express": {
"commandName": "IISExpress"
},
"https": {
"commandName": "Project"
}
}
}`;
const config = (id: string, name: string, launchProfile: string): RunConfig =>
({
id,
name,
kind: "dotnet",
command: "dotnet",
args: ["run", "--project", "src/Api/Api.csproj"],
params: { project: "src/Api/Api.csproj", framework: "net9.0", launchProfile },
}) as unknown as RunConfig;
afterEach(() => useProject.setState({ project: null }));
describe("launchSettings.json run icons", () => {
it("mark the profiles a run can use, on their lines", () => {
expect(projectProfiles(SETTINGS)).toEqual([
{ name: "http", line: 3 },
{ name: "https", line: 10 },
]);
// While the file doesn't parse, every profile keeps its icon.
expect(projectProfiles(SETTINGS.replace('"https": {', '"https": {,')).map((e) => e.name)).toEqual([
"http",
"IIS Express",
]);
});
it("run the project's configuration for the profile, or a temporary copy of it", () => {
useProject.setState({ project: { root: "/repo" } as never });
const path = "/repo/src/Api/Properties/launchSettings.json";
const configs = [
config("dotnet:src/Api/Api.csproj:run:", "Api (.NET Project)", ""),
config("dotnet:src/Api/Api.csproj:run:http", "Api: http", "http"),
];
expect(profileConfig(configs, path, "http")).toEqual({ config: configs[1], saved: true });
const added = profileConfig(configs, path, "https")!;
expect(added.saved).toBe(false);
expect(added.config.name).toBe("Api: https");
expect(added.config.params?.launchProfile).toBe("https");
expect(added.config.args).toEqual([
"run",
"--project",
"src/Api/Api.csproj",
"--framework",
"net9.0",
"--launch-profile",
"https",
]);
expect(profileConfig(configs, "/repo/src/Other/Properties/launchSettings.json", "http")).toBeNull();
});
});
-103
Переглянути файл
@@ -1,103 +0,0 @@
/**
* Gutter ▶ icons on the profiles of a .NET project's `Properties/launchSettings.json`:
* Run / Debug launch the project's configuration for that profile.
*/
import type { Extension } from "@codemirror/state";
import type { EditorDocContext } from "@/editor/api";
import { executeAction } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import type { RunConfig } from "@/platform/ipc";
import { shortcutLabel } from "@/platform/keymap";
import { useProject } from "@/platform/project";
import type { MenuItem } from "@/ui";
import { dotnetCommand } from "./dotnetTypes";
import { entryGutter, objectEntries, type ScriptEntry } from "./npmGutter";
import { loadConfigs, useRun } from "./store";
const FILE = /(^|\/)Properties\/launchSettings\.json$/;
/** The project directory of a `launchSettings.json`, relative to the project root when inside it. */
function projectDir(path: string): string {
const dir = path.replace(FILE, "");
const root = useProject.getState().project?.root;
return root && dir.startsWith(`${root}/`) ? dir.slice(root.length + 1) : root === dir ? "" : dir;
}
const dirOf = (project: string) => project.replace(/\\/g, "/").replace(/\/?[^/]*$/, "");
/**
* The project's configuration for `profile`: the one already set to it, else a temporary copy of
* the project's configuration with that launch profile (a profile added since detection ran).
*/
export function profileConfig(
configs: readonly RunConfig[],
path: string,
profile: string,
): { config: RunConfig; saved: boolean } | null {
const dir = projectDir(path);
const ofProject = configs.filter((c) => c.kind === "dotnet" && dirOf(c.params?.project ?? "") === dir);
const saved = ofProject.find((c) => c.params?.launchProfile === profile);
if (saved) return { config: saved, saved: true };
const base = ofProject.find((c) => !c.params?.launchProfile) ?? ofProject[0];
if (!base) return null;
const params = { ...base.params, launchProfile: profile };
return {
config: {
...base,
id: `context:dotnet:${base.params?.project ?? dir}:${profile}`,
name: `${base.name.replace(/ \(.NET Project\)$|: .*$/, "")}: ${profile}`,
args: dotnetCommand(params).args,
params,
},
saved: false,
};
}
/**
* The profiles a run can use: `commandName: "Project"` (IIS and Docker profiles are run by other
* tools). While the text doesn't parse, every profile key keeps its icon.
*/
export function projectProfiles(text: string): ScriptEntry[] {
const entries = objectEntries(text, "profiles");
type Profiles = Record<string, { commandName?: unknown } | undefined>;
let profiles: Profiles;
try {
profiles = (JSON.parse(text.replace(/^\uFEFF/, "")) as { profiles?: Profiles }).profiles ?? {};
} catch {
return entries;
}
return entries.filter((e) => profiles[e.name]?.commandName === "Project");
}
async function profileMenu(entry: ScriptEntry, path: string): Promise<MenuItem[]> {
try {
// Detection reads the disk: a profile added moments ago is already there.
await loadConfigs();
} catch {
// Use what is loaded.
}
const found = profileConfig(useRun.getState().configs, path, entry.name);
if (!found) return [{ label: tx`No .NET run configuration for this project`, disabled: true }];
const { config, saved } = found;
return [
{
label: tx`Run '${config.name}'`,
icon: "run",
shortcut: shortcutLabel("run.runContext"),
run: () =>
saved
? void executeAction("run.runConfig", config.id)
: void executeAction("run.runConfig", { config, temporary: true }),
},
{
label: tx`Debug '${config.name}'`,
icon: "debug",
shortcut: shortcutLabel("run.debugContext"),
run: () => void executeAction("run.debugConfig", config),
},
];
}
export function launchSettingsGutter(ctx: EditorDocContext): Extension {
return entryGutter(ctx, FILE, projectProfiles, profileMenu);
}
+20 -37
Переглянути файл
@@ -21,15 +21,13 @@ export interface ScriptEntry {
line: number;
}
/** The top-level `scripts` entries of `package.json` text, in document order. */
export const scriptEntries = (text: string): ScriptEntry[] => objectEntries(text, "scripts");
/**
* The keys of the top-level object `section` of JSON text, in document order
* (a small JSON scanner: values may contain braces, colons, escapes). Entries
* parsed so far survive malformed text, so a trailing comma keeps earlier ones visible.
* The top-level `scripts` entries of `package.json` text, in document order
* (a small JSON scanner: script values may contain braces, colons, escapes).
* Entries parsed so far survive malformed text, so a trailing comma keeps
* earlier scripts visible.
*/
export function objectEntries(text: string, section: string): ScriptEntry[] {
export function scriptEntries(text: string): ScriptEntry[] {
const entries: ScriptEntry[] = [];
let i = 0;
let line = 0;
@@ -134,7 +132,7 @@ export function objectEntries(text: string, section: string): ScriptEntry[] {
if (text[i] !== ":") break;
i++;
ws();
if (key === section && text[i] === "{") {
if (key === "scripts" && text[i] === "{") {
i++;
ws();
if (text[i] !== "}") {
@@ -155,7 +153,7 @@ export function objectEntries(text: string, section: string): ScriptEntry[] {
break;
}
}
i++; // the closing `}` of the section
i++; // the closing `}` of `scripts`
} else {
value();
}
@@ -304,13 +302,19 @@ interface Placed extends ScriptEntry {
const setEntries = StateEffect.define<Placed[]>();
type EntryMenu = (entry: ScriptEntry, path: string, content: string) => Promise<MenuItem[]>;
const entriesField = StateField.define<Placed[]>({
create: () => [],
update(value, tr) {
for (const e of tr.effects) if (e.is(setEntries)) return e.value;
if (!tr.docChanged) return value;
return value.map((p) => ({ ...p, pos: tr.state.doc.lineAt(tr.changes.mapPos(p.pos, -1)).from }));
},
});
class ScriptMarker extends GutterMarker {
constructor(
readonly entry: ScriptEntry,
readonly path: string,
readonly menu: EntryMenu,
) {
super();
}
@@ -326,7 +330,7 @@ class ScriptMarker extends GutterMarker {
el.innerHTML = gutterIconMarkup("gutter-run") ?? "";
el.addEventListener("click", () => {
const rect = el.getBoundingClientRect();
void this.menu(this.entry, this.path, view.state.doc.toString()).then((items) =>
void scriptMenuItems(this.entry, this.path, view.state.doc.toString()).then((items) =>
showContextMenu({ x: rect.left, y: rect.bottom + 2 }, items),
);
});
@@ -339,29 +343,8 @@ const scriptSpacer = gutterSpacer(styles.runMarker ?? "");
const DEBOUNCE = 300;
export function npmGutter(ctx: EditorDocContext): Extension {
return entryGutter(ctx, /(^|\/)package\.json$/, scriptEntries, scriptMenuItems);
}
/**
* Run ▶ icons on the entries `entries` finds in files matching `file`; a click opens `menu`.
* Shared by `package.json` scripts and `launchSettings.json` profiles.
*/
export function entryGutter(
ctx: EditorDocContext,
file: RegExp,
entries: (text: string) => ScriptEntry[],
menu: EntryMenu,
): Extension {
const path = ctx.path;
if (ctx.virtual || !file.test(path) || !useProject.getState().project?.root) return [];
const entriesField = StateField.define<Placed[]>({
create: () => [],
update(value, tr) {
for (const e of tr.effects) if (e.is(setEntries)) return e.value;
if (!tr.docChanged) return value;
return value.map((p) => ({ ...p, pos: tr.state.doc.lineAt(tr.changes.mapPos(p.pos, -1)).from }));
},
});
if (ctx.virtual || !/(^|\/)package\.json$/.test(path) || !useProject.getState().project?.root) return [];
const detector = ViewPlugin.fromClass(
class {
timer: ReturnType<typeof setTimeout> | undefined;
@@ -375,10 +358,10 @@ export function entryGutter(
clearTimeout(this.timer);
this.timer = setTimeout(() => {
const view = this.view;
const found = entries(view.state.doc.toString())
const entries = scriptEntries(view.state.doc.toString())
.filter((e) => e.line < view.state.doc.lines)
.map((e) => ({ ...e, pos: view.state.doc.line(e.line + 1).from }));
view.dispatch({ effects: setEntries.of(found) });
view.dispatch({ effects: setEntries.of(entries) });
}, delay);
}
destroy() {
@@ -394,7 +377,7 @@ export function entryGutter(
class: `${styles.runGutter} cm-openidea-gutter-run`,
markers: (view) =>
RangeSet.of(
view.state.field(entriesField).map((e) => new ScriptMarker(e, path, menu).range(e.pos)),
view.state.field(entriesField).map((e) => new ScriptMarker(e, path).range(e.pos)),
true,
),
// Reserve width only while the file has scripts, like the run gutter.
+1 -9
Переглянути файл
@@ -116,15 +116,7 @@ describe("inspections tree", () => {
"Version control",
]);
const python = find(tree, "group:Python")!;
expect(python.children.map((n) => n.id)).toEqual([
"lsp:basedpyright",
"lsp:ruff",
// The Python built-ins the IDE decides itself (no server checks class rules).
"builtin:python-circular-bases",
"builtin:python-override",
"builtin:python-abstract-method",
"builtin:python-redundant-override",
]);
expect(python.children.map((n) => n.id)).toEqual(["lsp:basedpyright", "lsp:ruff"]);
expect(python.children[1]!.children.map((n) => n.id)).toEqual(["lsp:ruff:E501", "lsp:ruff:F401"]);
expect(find(tree, "Python/lsp:ruff:F401")!.description).toContain("imported but unused");
expect(find(tree, "group:Other")!.children.map((n) => n.id)).toEqual(["lsp:custom-ls"]);
+3 -14
Переглянути файл
@@ -26,17 +26,6 @@ import { useProject } from "@/platform/project";
import { DEFAULT_SETTINGS } from "../model/schema";
import { openProjectStructure, useSettingsDialog } from "../model/staging";
import { ProjectStructureDialog } from "../languages/ProjectStructurePage";
import { useContextMenuStore } from "@/ui/Menu";
/** The Modules toolbar's + menu, then its `label` entry. */
function addMenuItem(label: string) {
fireEvent.click(screen.getByRole("button", { name: "Add" }));
const item = useContextMenuStore.getState().menu?.items.find((i) => "label" in i && i.label === label) as
| { run?: () => void }
| undefined;
expect(item?.run).toBeDefined();
item!.run!();
}
let disposeAction: () => void = () => {};
@@ -70,7 +59,7 @@ describe("Project Structure module overrides", () => {
it("keeps an outside directory out of module overrides and names the import action", async () => {
open.mockResolvedValue("/sibling/B");
await act(async () => {
addMenuItem("Add Module Overrides…");
fireEvent.click(screen.getByRole("button", { name: "Add Module Overrides" }));
});
expect(open).toHaveBeenCalledWith(
expect.objectContaining({ directory: true, title: "Select Module Directory", defaultPath: "/project" }),
@@ -84,7 +73,7 @@ describe("Project Structure module overrides", () => {
it("still stores an in-project directory as a module override", async () => {
open.mockResolvedValue("/project/mod");
await act(async () => {
addMenuItem("Add Module Overrides…");
fireEvent.click(screen.getByRole("button", { name: "Add Module Overrides" }));
});
expect(screen.queryByText(/Module overrides only apply/)).not.toBeInTheDocument();
expect(screen.getAllByText("mod").length).toBeGreaterThan(0);
@@ -92,7 +81,7 @@ describe("Project Structure module overrides", () => {
it("imports an external Maven project from this page without the directory override picker", async () => {
await act(async () => {
addMenuItem("Import Module from Existing Sources…");
fireEvent.click(screen.getByRole("button", { name: "Import Module from Existing Sources" }));
});
expect(imported).toHaveBeenCalledOnce();
expect(open).not.toHaveBeenCalled();
+15 -43
Переглянути файл
@@ -16,7 +16,6 @@ import {
Select,
Tree,
folderIconName,
showContextMenu,
type DialogButton,
type FolderKind,
type IconName,
@@ -872,22 +871,13 @@ function ModulesSection() {
<div className={styles.splitLayout}>
<div className={styles.sideList}>
<div className={styles.tableToolbar}>
<IconButton
icon="plus"
size="small"
title="Add"
onClick={(e) => {
const r = e.currentTarget.getBoundingClientRect();
showContextMenu({ x: r.left, y: r.bottom + 2 }, [
{ label: tx("Add Module Overrides…"), icon: "module", run: () => void addModule() },
{
label: tx("Import Module from Existing Sources…"),
icon: "folder-open",
run: () => void executeAction("maven.importExternal"),
},
]);
}}
/>
<Button size="small" variant="ghost" icon="plus" onClick={() => void addModule()}>
<T>Add Module Overrides</T>
</Button>
<Button size="small" variant="ghost" icon="plus" onClick={() => void executeAction("maven.importExternal")}>
<T>Import Module from Existing Sources</T>
</Button>
<span className={styles.spacer} />
<IconButton
icon="minus"
size="small"
@@ -1120,17 +1110,6 @@ function LibrariesSection() {
setSelectedIdx(next.length - 1);
};
/** IDEA's Copy: a duplicate named "<name> (copy)", selected for editing. */
const copySelectedLibrary = () => {
if (!current) return;
const names = new Set(libs.map((l) => l.name));
let name = tx`${current.name} (copy)`;
for (let n = 2; names.has(name); n++) name = tx`${current.name} (copy ${n})`;
const next = [...libs, { ...current, name }];
setRawLibs(next);
setSelectedIdx(next.length - 1);
};
const removeSelectedLibrary = () => {
if (activeIdx < 0) return;
const next = libs.filter((_, idx) => idx !== activeIdx);
@@ -1156,14 +1135,14 @@ function LibrariesSection() {
<IconButton
icon="plus"
size="small"
title="New Project Library"
onClick={(e) => {
const r = e.currentTarget.getBoundingClientRect();
showContextMenu({ x: r.left, y: r.bottom + 2 }, [
{ label: tx("JAR or Directory…"), icon: "file-archive", run: () => void addLibraryFromJar(false) },
{ label: tx("Classes Folder…"), icon: "folder-open", run: () => void addLibraryFromJar(true) },
]);
}}
title="Add JAR or Directory…"
onClick={() => void addLibraryFromJar(false)}
/>
<IconButton
icon="folder-open"
size="small"
title="Add Classes Folder…"
onClick={() => void addLibraryFromJar(true)}
/>
<IconButton
icon="minus"
@@ -1172,13 +1151,6 @@ function LibrariesSection() {
disabled={activeIdx < 0}
onClick={removeSelectedLibrary}
/>
<IconButton
icon="copy"
size="small"
title="Copy Library"
disabled={activeIdx < 0}
onClick={copySelectedLibrary}
/>
</div>
<div className={styles.sideItems}>
{libs.length === 0 && (
+1 -14
Переглянути файл
@@ -123,9 +123,7 @@ describe("current line decoration", () => {
expect(hint()?.textContent).toContain("Bob Jones");
v.dispatch({ selection: { anchor: 0 } });
expect(hint()).toBeNull();
// The document's blame is already loaded, so the new line shows without the
// 300 ms debounce that protects a git call (#3396).
await vi.advanceTimersByTimeAsync(0);
await tick();
expect(hint()?.textContent).toContain("Alice Smith");
expect(mocks.blame).toHaveBeenCalledTimes(1);
expect(mocks.file).toHaveBeenCalledTimes(1);
@@ -139,17 +137,6 @@ describe("current line decoration", () => {
expect(mocks.action).toHaveBeenCalledWith("vcs.showCommit", alice.commit);
});
it("still debounces the git call after an edit (#3396)", async () => {
const v = editor();
await tick();
mocks.blame.mockClear();
v.dispatch({ changes: { from: 0, insert: "x" } });
await vi.advanceTimersByTimeAsync(299);
expect(mocks.blame).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(1);
expect(mocks.blame).toHaveBeenCalledTimes(1);
});
it("uses only the primary selection and hides multiline selections", async () => {
const v = editor();
v.dispatch({ selection: EditorSelection.create([EditorSelection.cursor(0), EditorSelection.cursor(4)], 1) });
-13
Переглянути файл
@@ -254,19 +254,6 @@ describe("commit navigation", () => {
expect(api.log.mock.lastCall?.[1]).toMatchObject({ branches: ["main"], range: null, ranges: ["a..b", "c..d"] });
});
it("opens a new Update Info tab per update, each repository limited to its own range", async () => {
useVcs.setState({ roots: ["/a", "/b", "/c"] });
const ranges = { "/a": "a1..a2", "/b": "b1..b2" };
const first = openLogTab("update", "14:32", "toolWindow", Object.keys(ranges), { repoRanges: ranges });
await vi.waitFor(() => expect(api.log).toHaveBeenCalledTimes(2));
const byRepo = Object.fromEntries(
api.log.mock.calls.map((call) => [call[0] as string, (call[1] as LogQuery).ranges]),
);
expect(byRepo).toEqual({ "/a": ["a1..a2"], "/b": ["b1..b2"] });
expect(openLogTab("update", "14:32", "toolWindow", ["/a"], { repoRanges: { "/a": "a2..a3" } })).not.toBe(first);
expect(useGitLog.getState().logTabs.filter((t) => t.kind === "update")).toHaveLength(2);
});
it("offers both merge parents and selects the chosen repository-scoped commit", async () => {
const commits = [c("merge", ["main", "side"]), c("main"), c("side")].map((c) => ({ ...c, repo: "/repo" }));
useGitLog.setState({ commits, done: true });
-47
Переглянути файл
@@ -1,47 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { setContext } from "@/platform/context";
import { operationRepo } from "../actions";
import { useVcs } from "../store";
const ctx = vi.hoisted(() => ({ selection: [] as string[], active: null as string | null }));
vi.mock("@/workbench/contributions", async (original) => ({
...(await original<typeof import("@/workbench/contributions")>()),
projectViewSelection: () => ctx.selection,
maybeEditorService: () => ({ activePath: () => ctx.active }),
}));
const vcs = useVcs.getState();
beforeEach(() => {
ctx.selection = [];
ctx.active = null;
setContext("activeToolWindow", "");
useVcs.setState({ root: "/ws", roots: ["/ws/a", "/ws/b"], repo: "/ws/b" });
});
afterEach(() => {
setContext("activeToolWindow", "");
useVcs.setState(vcs);
});
describe("operationRepo", () => {
it("starts on the repository of the action's files (context menus)", () => {
expect(operationRepo(["/ws/a/src/x.ts"])).toBe("/ws/a");
expect(operationRepo("/ws/a")).toBe("/ws/a");
expect(operationRepo({ repo: "/ws/a" })).toBe("/ws/a");
});
it("from the keyboard, uses the focused Project view's selection, else the active editor's file", () => {
ctx.selection = ["/ws/a/lib"];
ctx.active = "/ws/b/main.ts";
expect(operationRepo(undefined)).toBe("/ws/b");
setContext("activeToolWindow", "project");
expect(operationRepo(undefined)).toBe("/ws/a");
});
it("falls back to the selected repository", () => {
useVcs.setState({ repo: "/ws/a" });
expect(operationRepo(undefined)).toBe("/ws/a");
expect(operationRepo(["/elsewhere/file"])).toBe("/ws/a");
});
});
+1 -46
Переглянути файл
@@ -113,7 +113,7 @@ describe("installRootSync", () => {
status: "ok",
data: root === "/p" ? info("main", "origin/main", 1, 0) : info("dev", null),
}));
useVcs.setState({ available: true, roots: ["/p", "/p/lib"], status: [] });
useVcs.setState({ available: true, roots: ["/p", "/p/lib"] });
});
afterEach(() => {
@@ -164,51 +164,6 @@ describe("installRootSync", () => {
expect(ipc.branchInfo).toHaveBeenCalledTimes(2);
});
it("counts the changed files of each repository and follows the status without asking git", async () => {
enable(true);
dispose = installRootSync();
await vi.waitFor(() => expect(ipc.branchInfo).toHaveBeenCalledTimes(2));
const file = (path: string, unstaged: string) =>
({ path, relPath: path, staged: null, unstaged, renamedFrom: null }) as never;
useVcs.setState({
status: [
file("/p/a.ts", "modified"),
file("/p/b.ts", "untracked"),
file("/p/lib/c.ts", "added"),
file("/p/d.log", "ignored"),
],
});
await vi.waitFor(() =>
expect(getFileDecoration("/p")?.suffix?.at(-1)).toEqual({
text: "2",
icon: "edit",
label: "2 changed files",
color: "var(--vcs-modified)",
}),
);
expect(getFileDecoration("/p/lib")?.suffix?.map((s) => s.text)).toEqual(["dev", "1"]);
useVcs.setState({ status: [] });
await vi.waitFor(() => expect(getFileDecoration("/p")?.suffix?.map((s) => s.text)).toEqual(["main", "/", "1"]));
expect(ipc.branchInfo).toHaveBeenCalledTimes(2);
});
it("queries again when a HEAD moves or a fetch / pull / push finishes, without a .git event", async () => {
enable(true);
useVcs.setState({ heads: { "/p": { head: "main", headCommit: "a" } }, remoteBusy: null });
dispose = installRootSync();
await vi.waitFor(() => expect(ipc.branchInfo).toHaveBeenCalledTimes(2));
useVcs.setState({ remoteBusy: "Fetching…" });
await settle();
expect(ipc.branchInfo).toHaveBeenCalledTimes(2);
useVcs.setState({ remoteBusy: null });
await vi.waitFor(() => expect(ipc.branchInfo).toHaveBeenCalledTimes(4));
useVcs.setState({ heads: { "/p": { head: "main", headCommit: "a" } } });
await settle();
expect(ipc.branchInfo).toHaveBeenCalledTimes(4);
useVcs.setState({ heads: { "/p": { head: "main", headCommit: "b" } } });
await vi.waitFor(() => expect(ipc.branchInfo).toHaveBeenCalledTimes(6));
});
it("queries the repositories again when the set of roots changes", async () => {
enable(true);
dispose = installRootSync();
+3 -18
Переглянути файл
@@ -145,21 +145,6 @@ function selectedPaths(arg: unknown): string[] {
return project.length ? project : contextPaths(arg);
}
/**
* The repository a repository-wide dialog (Pull, Merge, Rebase) starts on: the one holding the
* action's file, else the Project view's selection while it has focus, else the active editor's
* file, else the selected repository.
*/
export function operationRepo(arg: unknown): string | null {
const roots = useVcs.getState().roots;
if (arg && typeof arg === "object" && "repo" in arg) return (arg as { repo: string | null }).repo;
const inContext = (paths: readonly string[] | undefined) =>
paths?.map((p) => repoOf(p, roots)).find((r) => r != null) ?? null;
const fromProject = getContext().activeToolWindow === "project" ? projectViewSelection() : undefined;
const active = maybeEditorService()?.activePath();
return inContext(argPaths(arg)) ?? inContext(fromProject) ?? inContext(active ? [active] : []) ?? currentRepo();
}
function showGitWindow() {
toolWindowService().show("git", true);
}
@@ -304,7 +289,7 @@ export function registerVcsActions(): () => void {
category: "Git",
icon: "git-pull",
when: VCS,
run: ({ arg }) => showPullDialog(operationRepo(arg)),
run: showPullDialog,
},
{
id: "vcs.merge",
@@ -312,7 +297,7 @@ export function registerVcsActions(): () => void {
category: "Git",
when: VCS,
keywords: ["merge branch"],
run: ({ arg }) => showMergeDialog(operationRepo(arg)),
run: showMergeDialog,
},
{
id: "vcs.rebase",
@@ -320,7 +305,7 @@ export function registerVcsActions(): () => void {
category: "Git",
when: VCS,
keywords: ["rebase branch"],
run: ({ arg }) => showRebaseDialog(operationRepo(arg)),
run: showRebaseDialog,
},
{
id: "vcs.manageRemotes",
+12 -15
Переглянути файл
@@ -129,9 +129,8 @@ export function remoteBranchesOf(branches: readonly Branch[], remote: string): s
// --- Pull -------------------------------------------------------------------
/** `repo`: the repository it starts on (the context's), else the selected one. */
export function showPullDialog(repo?: string | null) {
openDialog((close) => <PullDialog initialRepo={repo} onClose={close} />);
export function showPullDialog() {
openDialog((close) => <PullDialog onClose={close} />);
}
/** IDEA's Git Root choice: shown only when the project holds several repositories. */
@@ -166,8 +165,8 @@ function useBranchInfo(repo: string | null) {
return loaded?.repo === repo ? loaded.info : null;
}
function PullDialog({ initialRepo, onClose }: { initialRepo?: string | null; onClose: () => void }) {
const [repo, setRepo] = useState(() => (initialRepo === undefined ? currentRepo() : initialRepo));
function PullDialog({ onClose }: { onClose: () => void }) {
const [repo, setRepo] = useState(currentRepo);
const info = useBranchInfo(repo);
const branches = useBranches(repo);
const [remotes, setRemotes] = useState<Remote[] | null>(null);
@@ -280,13 +279,12 @@ function PullDialog({ initialRepo, onClose }: { initialRepo?: string | null; onC
// --- Merge ------------------------------------------------------------------
/** `repo`: the repository it starts on (the context's), else the selected one. */
export function showMergeDialog(repo?: string | null) {
openDialog((close) => <MergeDialog initialRepo={repo} onClose={close} />);
export function showMergeDialog() {
openDialog((close) => <MergeDialog onClose={close} />);
}
function MergeDialog({ initialRepo, onClose }: { initialRepo?: string | null; onClose: () => void }) {
const [repo, setRepo] = useState(() => (initialRepo === undefined ? currentRepo() : initialRepo));
function MergeDialog({ onClose }: { onClose: () => void }) {
const [repo, setRepo] = useState(currentRepo);
const head = useBranchInfo(repo)?.head ?? null;
const branches = useBranches(repo);
const [branch, setBranch] = useState<string | null>(null);
@@ -360,13 +358,12 @@ function MergeDialog({ initialRepo, onClose }: { initialRepo?: string | null; on
// --- Rebase -----------------------------------------------------------------
/** `repo`: the repository it starts on (the context's), else the selected one. */
export function showRebaseDialog(repo?: string | null) {
openDialog((close) => <RebaseDialog initialRepo={repo} onClose={close} />);
export function showRebaseDialog() {
openDialog((close) => <RebaseDialog onClose={close} />);
}
function RebaseDialog({ initialRepo, onClose }: { initialRepo?: string | null; onClose: () => void }) {
const [repo, setRepo] = useState(() => (initialRepo === undefined ? currentRepo() : initialRepo));
function RebaseDialog({ onClose }: { onClose: () => void }) {
const [repo, setRepo] = useState(currentRepo);
const head = useBranchInfo(repo)?.head ?? null;
const branches = useBranches(repo);
const [upstream, setUpstream] = useState<string | null>(null);
-1
Переглянути файл
@@ -41,7 +41,6 @@ export function stashTabs({ combine, shelfCount, stashCount, tab }: StashTabsInp
/** Title of a log tab of its own. */
export function logTabLabel(t: LogTab): string {
if (t.kind === "update") return tx`Update Info: ${t.target}`;
return t.kind === "history" ? tx`History: ${baseName(t.target)}` : tx`Log: ${t.target}`;
}
+2 -21
Переглянути файл
@@ -69,30 +69,19 @@ export function inlineBlameSegments(line: BlameLine, now = Date.now()): BlameSeg
class BlameCache {
private doc: Text | undefined;
private pending: Promise<BlameLine[]> | undefined;
private lines: BlameLine[] | undefined;
clear() {
this.doc = undefined;
this.pending = undefined;
this.lines = undefined;
}
get(doc: Text, load: () => Promise<BlameLine[]>): Promise<BlameLine[]> {
if (doc !== this.doc || !this.pending) {
this.doc = doc;
this.lines = undefined;
this.pending = load().then((lines) => {
if (this.doc === doc) this.lines = lines;
return lines;
});
this.pending = load();
}
return this.pending;
}
/** The resolved blame for `doc`, when it is already loaded. */
peek(doc: Text): BlameLine[] | undefined {
return doc === this.doc ? this.lines : undefined;
}
}
/** An element's own custom property in px (its anchor offset), or 0. Inherited custom
@@ -276,15 +265,7 @@ export function inlineBlame(ctx: EditorDocContext): Extension {
if (update.docChanged) this.cache.clear();
if (update.docChanged || update.selectionSet) {
this.line = undefined;
// A caret move in a document whose blame is already loaded needs no git
// call, so show it without the debounce that protects that call (#3396).
if (!update.docChanged && this.cache.peek(update.state.doc) !== undefined) {
clearTimeout(this.timer);
++this.generation;
void this.refresh();
} else {
this.schedule();
}
this.schedule();
}
}
+3 -16
Переглянути файл
@@ -41,8 +41,6 @@ export interface LogFilters {
path: string | null;
paths?: string[];
range?: string | null;
/** Revision ranges per repository root, instead of `range` (Update Info: what an update brought in). */
repoRanges?: Record<string, string>;
date: LogDateFilter | null;
}
@@ -96,7 +94,7 @@ function parseFragments(value: unknown): LogFragments {
/** A log tab of its own (IDEA's "History: file" / "Log: branch" tabs): its own filters and view. */
export interface LogTab {
id: string;
kind: "history" | "branch" | "log" | "external" | "update";
kind: "history" | "branch" | "log" | "external";
/** What it shows (the file path or the branch); opening the same again selects the tab. */
target: string;
repo?: string | null;
@@ -407,7 +405,6 @@ export function openLogTab(
target: string,
location: LogTab["location"] = "toolWindow",
repositories?: string[],
initialFilters?: Partial<LogFilters>,
): string {
const active = useGitLog.getState().logTabs.find((t) => t.id === useGitLog.getState().shownLog);
repositories ??=
@@ -424,7 +421,6 @@ export function openLogTab(
: (active?.repo ?? (kind === "log" ? null : currentRepoRoot()));
const existing =
kind !== "log" &&
kind !== "update" &&
useGitLog
.getState()
.logTabs.find(
@@ -446,7 +442,6 @@ export function openLogTab(
: {
...emptyFilters(),
...(kind === "history" ? { path: target } : kind === "branch" ? { branches: [target] } : {}),
...initialFilters,
};
parked.set(id, freshView(filters));
useGitLog.setState((s) => ({
@@ -571,13 +566,6 @@ function parseFilters(value: unknown): LogFilters {
text: typeof raw.text === "string" ? raw.text : "",
path: typeof raw.path === "string" ? raw.path : null,
range: typeof raw.range === "string" ? raw.range : null,
...(raw.repoRanges && typeof raw.repoRanges === "object"
? {
repoRanges: Object.fromEntries(
Object.entries(raw.repoRanges).filter((e): e is [string, string] => typeof e[1] === "string"),
),
}
: {}),
regex: raw.regex === true,
matchCase: raw.matchCase === true,
};
@@ -637,7 +625,7 @@ function restoreLogSession(root: string | null) {
typeof tab === "object" &&
typeof tab.id === "string" &&
typeof tab.target === "string" &&
["history", "branch", "log", "external", "update"].includes(tab.kind) &&
["history", "branch", "log", "external"].includes(tab.kind) &&
(tab.repo == null || typeof tab.repo === "string"),
)
: [];
@@ -919,7 +907,6 @@ function loadPage(replace: boolean, id: string, before = false): Promise<void> {
!f.path &&
!f.paths?.length &&
!f.range &&
!f.repoRanges &&
!f.date &&
!o.noMerges &&
!o.firstParent
@@ -945,7 +932,7 @@ function loadPage(replace: boolean, id: string, before = false): Promise<void> {
textRegex: f.regex,
textMatchCase: f.matchCase,
range: null,
ranges: ((repo && f.repoRanges?.[repo]) || f.range)?.split(/\s+/).filter(Boolean) ?? [],
ranges: f.range?.split(/\s+/).filter(Boolean) ?? [],
request,
summaryOnly: true,
stopAt,
+5 -25
Переглянути файл
@@ -9,12 +9,7 @@ import { executeAction } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import { call, commands, isCancelled, nextRequestId } from "@/platform/ipc";
import { attachDocument, editorsFor } from "@/editor/api";
import {
maybeEditorService,
notifications,
toolWindowService,
type NotificationService,
} from "@/workbench/contributions";
import { maybeEditorService, notifications, type NotificationService } from "@/workbench/contributions";
import { cancelTask, upsertTaskSoon, useTasks } from "@/workbench/tasks";
import { progressFraction } from "./model";
import { saveDiffWindows } from "./diffWindowSave";
@@ -334,24 +329,6 @@ const commitsText = (n: number) => (n === 1 ? tx`${n} commit` : tx`${n} commits`
const pushedTitle = (n: number, to: string) =>
n === 1 ? tx`Pushed ${n} commit to ${to}` : tx`Pushed ${n} commits to ${to}`;
/**
* View Commits: an Update Info tab in the Git tool window, the Log of each updated repository
* limited to the commits the update brought in. Each update opens a tab of its own.
*/
async function openUpdateInfo(updated: readonly UpdatedRange[]) {
const { roots, root } = useVcs.getState();
const repoRanges = Object.fromEntries(
updated.flatMap(({ repo, from, to }) => {
const r = repo ?? roots[0] ?? root;
return r ? [[r, `${from}..${to}`]] : [];
}),
);
const time = new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
const { openLogTab } = await import("./logStore");
openLogTab("update", time, "toolWindow", Object.keys(repoRanges), { repoRanges });
toolWindowService().show("git", true);
}
/** IDEA's Update Project result: "N files updated in M commits" with View Commits. */
async function notifyUpdated(updated: readonly UpdatedRange[]) {
if (!updated.length) {
@@ -387,7 +364,10 @@ async function notifyUpdated(updated: readonly UpdatedRange[]) {
actions: [
{
label: "View Commits",
run: () => void openUpdateInfo(updated),
run: () => {
const { repo, from, to } = updated.find((u) => u.repo === currentRepo()) ?? updated[0]!;
void import("./CompareBranches").then((m) => m.showCommitRange("Update Info", from, to, repo));
},
},
],
});
+10 -70
Переглянути файл
@@ -1,10 +1,9 @@
import type { BranchInfo, FileStatus } from "@/bindings";
import type { BranchInfo } from "@/bindings";
import { call, commands, onIdeEvent } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { onWorkflowSettingsChange, workflowSettings } from "@/platform/workflowSettings";
import { setFileDecorations, type DecorationSegment, type FileDecoration } from "@/workbench/contributions";
import { rootOf } from "./model";
import { useVcs, type RepoHead } from "./store";
import { useVcs } from "./store";
const PROVIDER = "vcs-root-sync";
const GIT_CHANGE_DELAY_MS = 250;
@@ -21,13 +20,7 @@ const styled = (attr: string, extra: Pick<DecorationSegment, "text"> & Decoratio
...extra,
});
/** How many files of the working tree changed (staged, unstaged or untracked): nothing when clean. */
function changedFiles(count: number): DecorationSegment[] {
if (count <= 0) return [];
return [{ text: String(count), icon: "edit", label: tx`${count} changed files`, color: "var(--vcs-modified)" }];
}
export function rootSyncSuffix(info: BranchInfo, changed = 0): DecorationSegment[] | null {
export function rootSyncSuffix(info: BranchInfo): DecorationSegment[] | null {
const { head, upstream, ahead, behind } = info;
if (!head) return null;
const branchAttr = upstream
@@ -39,7 +32,7 @@ export function rootSyncSuffix(info: BranchInfo, changed = 0): DecorationSegment
: "local-branch";
const branchColor = `var(--git-${branchAttr}, var(--accent))`;
const branch: DecorationSegment = styled(branchAttr, { text: head, color: branchColor });
if (!upstream) return [branch, ...changedFiles(changed)];
if (!upstream) return [branch];
const counts: DecorationSegment[] = [];
if (ahead > 0)
counts.push(
@@ -68,23 +61,7 @@ export function rootSyncSuffix(info: BranchInfo, changed = 0): DecorationSegment
color: "var(--git-head-tags, var(--accent))",
}),
);
return [
branch,
styled("head-tags", { text: "/", color: "var(--git-head-tags, var(--accent))" }),
...counts,
...changedFiles(changed),
];
}
/** Changed files per repository root (each file counted once, in its innermost repository). */
export function changedByRoot(status: readonly FileStatus[], roots: readonly string[]): Map<string, number> {
const out = new Map<string, number>();
for (const f of status) {
if (f.staged === "ignored" || f.unstaged === "ignored") continue;
const root = rootOf(f.path, roots);
if (root) out.set(root, (out.get(root) ?? 0) + 1);
}
return out;
return [branch, styled("head-tags", { text: "/", color: "var(--git-head-tags, var(--accent))" }), ...counts];
}
async function branchInfoOf(root: string): Promise<[string, BranchInfo] | null> {
@@ -95,18 +72,6 @@ async function branchInfoOf(root: string): Promise<[string, BranchInfo] | null>
}
}
/** Whether a repository's branch or HEAD commit differs between two refreshes. */
export function headsMoved(a: Readonly<Record<string, RepoHead>>, b: Readonly<Record<string, RepoHead>>): boolean {
if (a === b) return false;
const roots = new Set([...Object.keys(a), ...Object.keys(b)]);
for (const root of roots) {
const x = a[root];
const y = b[root];
if (x?.head !== y?.head || x?.headCommit !== y?.headCommit) return true;
}
return false;
}
function sameDecorations(a: ReadonlyMap<string, FileDecoration>, b: ReadonlyMap<string, FileDecoration>): boolean {
if (a.size !== b.size) return false;
for (const [root, d] of a) if (JSON.stringify(d) !== JSON.stringify(b.get(root))) return false;
@@ -118,7 +83,6 @@ export function installRootSync(): () => void {
let running = false;
let pending = false;
let shown: ReadonlyMap<string, FileDecoration> = new Map();
let branches = new Map<string, BranchInfo>();
const publish = (next: ReadonlyMap<string, FileDecoration>) => {
if (disposed || sameDecorations(next, shown)) return;
@@ -130,27 +94,12 @@ export function installRootSync(): () => void {
const { available, roots } = useVcs.getState();
if (!available || !workflowSettings().vcs.git.showBranchInProjectView) return publish(new Map());
const infos = await Promise.all(roots.map(branchInfoOf));
const next = new Map<string, BranchInfo>();
roots.forEach((root, i) => {
// A repository whose branch can't be read now keeps what it showed.
const info = infos[i]?.[1] ?? branches.get(root);
if (info) next.set(root, info);
});
branches = next;
render();
};
/** The suffixes from the branches last read and the current working tree status (no git query). */
const render = () => {
const { available, roots, status } = useVcs.getState();
if (!available || !workflowSettings().vcs.git.showBranchInProjectView) return publish(new Map());
const changed = changedByRoot(status, roots);
const next = new Map<string, FileDecoration>();
for (const root of roots) {
const info = branches.get(root);
const suffix = info ? rootSyncSuffix(info, changed.get(root) ?? 0) : null;
roots.forEach((root, i) => {
const entry = infos[i];
const suffix = entry ? rootSyncSuffix(entry[1]) : shown.get(root)?.suffix;
if (suffix) next.set(root, { suffix, suffixColor: SUFFIX_COLOR });
}
});
publish(next);
};
@@ -179,16 +128,7 @@ export function installRootSync(): () => void {
};
const unsubVcs = useVcs.subscribe((s, prev) => {
if (
s.available !== prev.available ||
s.roots.join("\n") !== prev.roots.join("\n") ||
// A commit, checkout or update moved a HEAD; a fetch or push finished.
headsMoved(s.heads, prev.heads) ||
(prev.remoteBusy && !s.remoteBusy)
)
schedule();
// The changed-file counts follow the working tree as the status refreshes, without asking git.
else if (s.status !== prev.status) render();
if (s.available !== prev.available || s.roots.join("\n") !== prev.roots.join("\n")) schedule();
});
const offGit = onIdeEvent("vcsChanged", scheduleSoon);
const offSettings = onWorkflowSettingsChange((s) => s.vcs.git.showBranchInProjectView, schedule);
+4 -3
Переглянути файл
@@ -90,9 +90,10 @@ export function activate(): () => void {
registerExternalFileOpenHandler({
id: "viewers.associatedApps",
order: 1,
matches: (path) =>
associatedApplication(path, useProject.getState().settings?.files?.associatedApplications ?? []),
open: openWithSystemApp,
open: (path) => {
const patterns = useProject.getState().settings?.files?.associatedApplications ?? [];
return associatedApplication(path, patterns) ? openWithSystemApp(path) : false;
},
}),
registerEditorKind({ kind: IMAGE_KIND, component: ImageViewer, title: titleOf, icon: iconOf }),
registerEditorKind({ kind: BINARY_KIND, component: HexViewer, title: titleOf, icon: iconOf }),
-46
Переглянути файл
@@ -240,16 +240,6 @@ export const DEPENDENCY_INSPECTION = "builtin:dependency-versions";
export const CONFLICT_MARKERS_PRODUCER = "merge-conflict-markers";
export const CONFLICT_MARKERS_INSPECTION = "builtin:merge-conflict-markers";
/** Python inheritance checks the IDE computes from its own inheritance graph (no server offers one). */
export const PYTHON_CIRCULAR_BASES_PRODUCER = "python-circular-bases";
export const PYTHON_CIRCULAR_BASES_INSPECTION = "builtin:python-circular-bases";
export const PYTHON_OVERRIDE_PRODUCER = "python-override";
export const PYTHON_OVERRIDE_INSPECTION = "builtin:python-override";
export const PYTHON_ABSTRACT_METHOD_PRODUCER = "python-abstract-method";
export const PYTHON_ABSTRACT_METHOD_INSPECTION = "builtin:python-abstract-method";
export const PYTHON_REDUNDANT_OVERRIDE_PRODUCER = "python-redundant-override";
export const PYTHON_REDUNDANT_OVERRIDE_INSPECTION = "builtin:python-redundant-override";
/** IDEA's Typo options: which parts of source files are checked (plain text always is). */
export const SPELLING_OPTIONS = {
code: "processCode",
@@ -320,42 +310,6 @@ export const BUILTIN_INSPECTIONS: readonly BuiltinInspection[] = [
defaultLevel: "warning",
byCode: true,
},
{
id: PYTHON_CIRCULAR_BASES_INSPECTION,
producer: PYTHON_CIRCULAR_BASES_PRODUCER,
name: "Circular inheritance",
group: "Python",
description:
"Reports a Python class that ends up among its own ancestors: Python raises 'Cannot create a consistent MRO' when the module is imported.",
defaultLevel: "error",
},
{
id: PYTHON_OVERRIDE_INSPECTION,
producer: PYTHON_OVERRIDE_PRODUCER,
name: "Inconsistent '@override'",
group: "Python",
description:
"Reports a method marked typing.override that no base class declares. Only hierarchies the IDE's index knows completely are checked: a base outside the project may declare the method, so those are left alone.",
defaultLevel: "warning",
},
{
id: PYTHON_ABSTRACT_METHOD_INSPECTION,
producer: PYTHON_ABSTRACT_METHOD_PRODUCER,
name: "Abstract method not implemented",
group: "Python",
description:
"Reports a class that leaves a base class's @abstractmethod unimplemented, in a hierarchy the IDE's index knows completely. A class that declares an abstract method of its own is abstract, so it is not reported.",
defaultLevel: "warning",
},
{
id: PYTHON_REDUNDANT_OVERRIDE_INSPECTION,
producer: PYTHON_REDUNDANT_OVERRIDE_PRODUCER,
name: "Redundant override",
group: "Python",
description:
"Reports a method whose body only repeats the inherited one — 'pass' over a method that does nothing, or calling 'super()' with the same arguments — so the override can be removed.",
defaultLevel: "weakWarning",
},
{
id: "builtin:sql",
producer: "sql-inspections",
+1 -1
Переглянути файл
@@ -78,7 +78,7 @@ describe("IDEA keymap parity", () => {
["editor.nextSplitter", ["Alt+Tab"], ["Alt+Tab"]],
["toolwindow.resizeLeft", ["Ctrl+Alt+Left"], ["Ctrl+Alt+Shift+Left"]],
["toolwindow.closeContent", ["Meta+W", "Ctrl+Shift+F4"], ["Ctrl+F4", "Ctrl+Shift+F4"]],
["layout.restoreCurrent", ["Shift+F12"], ["Shift+F12"]],
["layout.restoreDefault", ["Shift+F12"], ["Shift+F12"]],
["workbench.stopBackgroundProcesses", ["Meta+Shift+F2"], ["Ctrl+Shift+F2"]],
["navigate.back", ["Meta+[", "Meta+Alt+Left", "Button4", "SwipeRight"], ["Ctrl+Alt+Left", "Button4"]],
["navigate.forward", ["Meta+]", "Meta+Alt+Right", "Button5", "SwipeLeft"], ["Ctrl+Alt+Right", "Button5"]],
+1 -2
Переглянути файл
@@ -237,8 +237,7 @@ export const intellijMacos: Record<string, string[]> = {
"toolwindow.resizeRight": ["Ctrl+Alt+Right"],
"toolwindow.resizeUp": ["Ctrl+Alt+Up"],
"toolwindow.resizeDown": ["Ctrl+Alt+Down"],
"layout.restoreCurrent": ["Shift+F12"],
"layout.restoreDefault": [],
"layout.restoreDefault": ["Shift+F12"],
"toolwindow.jumpToLast": ["F12"],
"toolwindow.hideActive": ["Shift+Escape"],
"toolwindow.focusEditor": ["Escape"],
+1 -2
Переглянути файл
@@ -234,8 +234,7 @@ export const intellijWindows: Record<string, string[]> = {
"toolwindow.terminal": ["Alt+F12"],
"toolwindow.hideAll": ["Ctrl+Shift+F12"],
"toolwindow.maximize": ["Ctrl+Shift+'"],
"layout.restoreCurrent": ["Shift+F12"],
"layout.restoreDefault": [],
"layout.restoreDefault": ["Shift+F12"],
"toolwindow.jumpToLast": ["F12"],
"toolwindow.hideActive": ["Shift+Escape"],
"toolwindow.focusEditor": ["Escape"],
-1
Переглянути файл
@@ -65,7 +65,6 @@ export const vscodeMacos: Record<string, string[]> = {
"toolwindow.resizeRight": [],
"toolwindow.resizeUp": [],
"toolwindow.resizeDown": [],
"layout.restoreCurrent": [],
"layout.restoreDefault": [],
"workbench.stopBackgroundProcesses": [],
"navigate.typeHierarchy": [],
-2
Переглянути файл
@@ -457,8 +457,6 @@
"menu.runAnything.show": "Run Anything…",
"menu.localHistory.putLabel": "Put Label…",
"menu.toolWindowLayouts": "Tool Window Layouts",
"menu.layout.saveCurrent": "Save Changes in Current Layout",
"menu.layout.restoreCurrent": "Restore Current Layout",
"menu.layout.save": "Save Current Layout as…",
"menu.layout.restoreDefault": "Restore Default Layout",
"menu.layout.rename": "Rename Layout…",
+4 -16
Переглянути файл
@@ -532,8 +532,8 @@
"Library": "Library",
"Select Classes Directory": "Select Classes Directory",
"Select Library JAR": "Select Library JAR",
"JAR or Directory…": "JAR or Directory…",
"Classes Folder…": "Classes Folder…",
"Add JAR or Directory…": "Add JAR or Directory…",
"Add Classes Folder…": "Add Classes Folder…",
"Remove Library": "Remove Library",
"No project libraries added.": "No project libraries added.",
"Library Details": "Library Details",
@@ -586,7 +586,7 @@
"Project Structure sections": "Project Structure sections",
"Custom test output paths are not supported yet. Maven and Gradle manage their own test output.": "Custom test output paths are not supported yet. Maven and Gradle manage their own test output.",
"Custom artifact packaging is not supported yet. Build and deploy artifacts defined by Maven or Gradle.": "Custom artifact packaging is not supported yet. Build and deploy artifacts defined by Maven or Gradle.",
"Add Module Overrides…": "Add Module Overrides…",
"Add Module Overrides": "Add Module Overrides",
"Import Module from Existing Sources": "Import Module from Existing Sources",
"Module overrides only apply to a directory inside the opened project. To import an existing module from outside it, use Import Module from Existing Sources.": "Module overrides only apply to a directory inside the opened project. To import an existing module from outside it, use Import Module from Existing Sources.",
"Directory for production classes, relative to the project root and inside this module.": "Directory for production classes, relative to the project root and inside this module.",
@@ -1753,17 +1753,5 @@
"YAML File": "YAML File",
"TOML File": "TOML File",
"EditorConfig File": "EditorConfig File",
".gitignore File": ".gitignore File",
"Circular inheritance": "Circular inheritance",
"Inconsistent '@override'": "Inconsistent '@override'",
"Abstract method not implemented": "Abstract method not implemented",
"Redundant override": "Redundant override",
"Reports a Python class that ends up among its own ancestors: Python raises 'Cannot create a consistent MRO' when the module is imported.": "Reports a Python class that ends up among its own ancestors: Python raises 'Cannot create a consistent MRO' when the module is imported.",
"Reports a method marked typing.override that no base class declares. Only hierarchies the IDE's index knows completely are checked: a base outside the project may declare the method, so those are left alone.": "Reports a method marked typing.override that no base class declares. Only hierarchies the IDE's index knows completely are checked: a base outside the project may declare the method, so those are left alone.",
"Reports a class that leaves a base class's @abstractmethod unimplemented, in a hierarchy the IDE's index knows completely. A class that declares an abstract method of its own is abstract, so it is not reported.": "Reports a class that leaves a base class's @abstractmethod unimplemented, in a hierarchy the IDE's index knows completely. A class that declares an abstract method of its own is abstract, so it is not reported.",
"Reports a method whose body only repeats the inherited one — 'pass' over a method that does nothing, or calling 'super()' with the same arguments — so the override can be removed.": "Reports a method whose body only repeats the inherited one — 'pass' over a method that does nothing, or calling 'super()' with the same arguments — so the override can be removed.",
"Circular inheritance: '{name}' inherits from itself": "Circular inheritance: '{name}' inherits from itself",
"Method '{name}' is marked @override but no base class declares it": "Method '{name}' is marked @override but no base class declares it",
"Class '{name}' does not implement abstract method '{method}'": "Class '{name}' does not implement abstract method '{method}'",
"Redundant override of '{name}'": "Redundant override of '{name}'"
".gitignore File": ".gitignore File"
}
+2 -1
Переглянути файл
@@ -2604,7 +2604,7 @@
"Restored branch {name}": "Rama {name} restaurada",
"Commits of {name}": "Confirmaciones de {name}",
"All files are up-to-date": "Todos los archivos están actualizados",
"Update Info: {target}": "Información de actualización: {target}",
"Update Info": "Información de actualización",
"Press again to go to the next file": "Presiona de nuevo para ir al siguiente archivo",
"Press again to go to the previous file": "Presiona de nuevo para ir al archivo anterior",
"Include in commit": "Incluir en la confirmación",
@@ -4040,6 +4040,7 @@
"Headers ({count})": "Encabezados ({count})",
"Headers": "Encabezados",
"Delete the macro '{name}'?": "¿Eliminar la macro '{name}'?",
"{count} processes": "{count} procesos",
"Memory: {usage}": "Memoria: {usage}",
" Memory {before} → {after}.": " Memoria {before} → {after}.",
"{count} syntax tree dropped, index compacted.{memory}": "{count} árbol sintáctico descartado, índice compactado.{memory}",
+2 -1
Переглянути файл
@@ -2505,7 +2505,7 @@
"Restored branch {name}": "Branche {name} restaurée",
"Commits of {name}": "Commits de {name}",
"All files are up-to-date": "Tous les fichiers sont à jour",
"Update Info: {target}": "Informations de mise à jour: {target}",
"Update Info": "Informations de mise à jour",
"Press again to go to the next file": "Appuyez à nouveau pour aller au fichier suivant",
"Press again to go to the previous file": "Appuyez à nouveau pour aller au fichier précédent",
"Include in commit": "Inclure dans le commit",
@@ -3904,6 +3904,7 @@
"Headers ({count})": "En-têtes ({count})",
"Headers": "En-têtes",
"Delete the macro '{name}'?": "Supprimer la macro '{name}' ?",
"{count} processes": "{count} processus",
"Memory: {usage}": "Mémoire : {usage}",
" Memory {before} → {after}.": " Mémoire {before} → {after}.",
"{count} syntax tree dropped, index compacted.{memory}": "{count} arbre syntaxique supprimé, index compacté.{memory}",
+2 -1
Переглянути файл
@@ -2654,7 +2654,7 @@
"Restored branch {name}": "{name} 브랜치를 복원했습니다",
"Commits of {name}": "{name}의 커밋",
"All files are up-to-date": "모든 파일이 최신 상태입니다",
"Update Info: {target}": "업데이트 정보: {target}",
"Update Info": "업데이트 정보",
"Press again to go to the next file": "다음 파일로 이동하려면 다시 누르세요",
"Press again to go to the previous file": "이전 파일로 이동하려면 다시 누르세요",
"Include in commit": "커밋에 포함",
@@ -4101,6 +4101,7 @@
"Headers ({count})": "헤더({count})",
"Headers": "헤더",
"Delete the macro '{name}'?": "매크로 '{name}'을(를) 삭제하시겠습니까?",
"{count} processes": "프로세스 {count}개",
"Memory: {usage}": "메모리: {usage}",
" Memory {before} → {after}.": " 메모리 {before} → {after}.",
"{count} syntax tree dropped, index compacted.{memory}": "구문 트리 {count}개를 삭제하고 색인을 압축했습니다.{memory}",
+2 -1
Переглянути файл
@@ -2581,7 +2581,7 @@
"Restored branch {name}": "Przywrócono gałąź {name}",
"Commits of {name}": "Zatwierdzenia dla {name}",
"All files are up-to-date": "Wszystkie pliki są aktualne",
"Update Info: {target}": "Informacje o aktualizacji: {target}",
"Update Info": "Informacje o aktualizacji",
"Press again to go to the next file": "Naciśnij ponownie, aby przejść do następnego pliku",
"Press again to go to the previous file": "Naciśnij ponownie, aby przejść do poprzedniego pliku",
"Include in commit": "Dołącz do zatwierdzenia",
@@ -3999,6 +3999,7 @@
"Headers ({count})": "Nagłówki ({count})",
"Headers": "Nagłówki",
"Delete the macro '{name}'?": "Usunąć makro '{name}'?",
"{count} processes": "Liczba procesów: {count}",
"Memory: {usage}": "Pamięć: {usage}",
" Memory {before} → {after}.": " Pamięć {before} → {after}.",
"{count} syntax tree dropped, index compacted.{memory}": "Odrzucono drzewo składniowe ({count}), indeks skompresowany.{memory}",
+2 -1
Переглянути файл
@@ -2582,7 +2582,7 @@
"Restored branch {name}": "Branch {name} restaurada",
"Commits of {name}": "Commits de {name}",
"All files are up-to-date": "Todos os arquivos estão atualizados",
"Update Info: {target}": "Informações de atualização: {target}",
"Update Info": "Informações de atualização",
"Press again to go to the next file": "Pressione novamente para ir para o próximo arquivo",
"Press again to go to the previous file": "Pressione novamente para ir para o arquivo anterior",
"Include in commit": "Incluir no commit",
@@ -4005,6 +4005,7 @@
"Headers ({count})": "Cabeçalhos ({count})",
"Headers": "Cabeçalhos",
"Delete the macro '{name}'?": "Excluir a macro '{name}'?",
"{count} processes": "{count} processos",
"Memory: {usage}": "Memória: {usage}",
" Memory {before} → {after}.": " Memória {before} → {after}.",
"{count} syntax tree dropped, index compacted.{memory}": "{count} árvore sintática descartada, índice compactado.{memory}",
+6 -29
Переглянути файл
@@ -1775,7 +1775,6 @@
"No Maven projects": "没有 Maven 项目",
"No profile for '{name}'": "没有 '{name}' 的分析数据",
"No Python found": "未找到 Python",
"No .NET run configuration for this project": "此项目没有 .NET 运行配置",
"No recent repository URLs": "没有最近使用的仓库 URL",
"No recent searches": "无最近搜索",
"No TODO items found": "未找到 TODO 项",
@@ -2098,8 +2097,8 @@
"Library": "库",
"Select Classes Directory": "选择类目录",
"Select Library JAR": "选择库 JAR",
"JAR or Directory…": "JAR 或目录…",
"Classes Folder…": "类文件夹…",
"Add JAR or Directory…": "添加 JAR 或目录…",
"Add Classes Folder…": "添加类文件夹…",
"Remove Library": "移除库",
"No project libraries added.": "尚未添加项目库。",
"Library Details": "库详情",
@@ -2390,9 +2389,6 @@
"Restart is only available in the desktop app": "只有桌面应用可以重启",
"Restore Default": "恢复默认值",
"Restore Default Layout": "恢复默认布局",
"Restore Current Layout": "恢复当前布局",
"Save Changes in Current Layout": "保存对当前布局的更改",
"Restores the active saved layout, or the default layout when none is active.": "恢复当前选中的已保存布局;没有选中的布局时恢复默认布局。",
"Restore Defaults": "恢复默认值",
"Restore Rows": "恢复行",
"Restore Size": "恢复大小",
@@ -3232,7 +3228,7 @@
"Restored branch {name}": "已恢复分支 {name}",
"Commits of {name}": "{name} 的提交",
"All files are up-to-date": "所有文件都是最新的",
"Update Info: {target}": "更新信息: {target}",
"Update Info": "更新信息",
"Press again to go to the next file": "再按一次转到下一个文件",
"Press again to go to the previous file": "再按一次转到上一个文件",
"Include in commit": "包含在提交中",
@@ -4718,6 +4714,7 @@
"Headers ({count})": "标头 ({count})",
"Headers": "标头",
"Delete the macro '{name}'?": "是否删除宏 '{name}'?",
"{count} processes": "{count} 个进程",
"Memory: {usage}": "内存:{usage}",
" Memory {before} → {after}.": " 内存 {before} → {after}。",
"{count} syntax tree dropped, index compacted.{memory}": "已丢弃 {count} 个语法树,已压缩索引。{memory}",
@@ -7008,7 +7005,7 @@
"The check could not run: {reason}": "检查无法运行:{reason}",
"Custom test output paths are not supported yet. Maven and Gradle manage their own test output.": "暂不支持自定义测试输出路径。测试输出由 Maven 和 Gradle 管理。",
"Custom artifact packaging is not supported yet. Build and deploy artifacts defined by Maven or Gradle.": "暂不支持自定义制品打包。请构建和部署 Maven 或 Gradle 定义的制品。",
"Add Module Overrides…": "添加模块覆盖设置…",
"Add Module Overrides": "添加模块覆盖设置",
"Module overrides only apply to a directory inside the opened project. To import an existing module from outside it, use Import Module from Existing Sources.": "模块覆盖设置只适用于当前打开项目内的目录。要从外部导入已有模块,请使用「导入已有模块」。",
"Directory for production classes, relative to the project root and inside this module.": "生产类文件目录,相对于项目根目录,且必须位于当前模块内。",
"Scope controls Run/Debug only. JARs are also available to Java code assistance.": "作用域仅控制运行和调试。JAR 库也可用于 Java 代码辅助。",
@@ -8143,25 +8140,5 @@
"YAML File": "YAML 文件",
"TOML File": "TOML 文件",
"EditorConfig File": "EditorConfig 文件",
".gitignore File": ".gitignore 文件",
"Circular inheritance": "循环继承",
"Inconsistent '@override'": "不一致的 '@override'",
"Abstract method not implemented": "未实现抽象方法",
"Redundant override": "冗余的重写",
"Reports a Python class that ends up among its own ancestors: Python raises 'Cannot create a consistent MRO' when the module is imported.": "报告最终成为自身祖先的 Python 类:导入该模块时 Python 会抛出 'Cannot create a consistent MRO'。",
"Reports a method marked typing.override that no base class declares. Only hierarchies the IDE's index knows completely are checked: a base outside the project may declare the method, so those are left alone.": "报告标记了 typing.override 但没有任何基类声明该方法的方法。只检查 IDE 索引完整已知的继承层次:项目之外的基类可能声明了该方法,因此这些情况不做报告。",
"Reports a class that leaves a base class's @abstractmethod unimplemented, in a hierarchy the IDE's index knows completely. A class that declares an abstract method of its own is abstract, so it is not reported.": "报告在 IDE 索引完整已知的继承层次中未实现基类 @abstractmethod 的类。自身声明了抽象方法的类本身就是抽象类,因此不做报告。",
"Reports a method whose body only repeats the inherited one — 'pass' over a method that does nothing, or calling 'super()' with the same arguments — so the override can be removed.": "报告方法体只是重复继承来的方法(对什么都不做的方法使用 'pass',或以相同参数调用 'super()')的重写,这类重写可以删除。",
"Circular inheritance: '{name}' inherits from itself": "循环继承:'{name}' 继承了自身",
"Method '{name}' is marked @override but no base class declares it": "方法 '{name}' 标记了 @override,但没有任何基类声明该方法",
"Class '{name}' does not implement abstract method '{method}'": "类 '{name}' 未实现抽象方法 '{method}'",
"Redundant override of '{name}'": "冗余的重写:'{name}'",
"Import Module from Existing Sources…": "导入已有模块…",
"{name} (copy)": "{name}(副本)",
"{name} (copy {n})": "{name}(副本 {n})",
"New Project Library": "新建项目库",
"Copy Library": "复制库",
"PID {pid}": "PID {pid}",
"PID {pid} · {count} processes": "PID {pid} · {count} 个进程",
"End Process {label}": "结束进程 {label}"
".gitignore File": ".gitignore 文件"
}
-2
Переглянути файл
@@ -457,8 +457,6 @@
"menu.runAnything.show": "运行任何内容…",
"menu.localHistory.putLabel": "添加标签…",
"menu.toolWindowLayouts": "工具窗口布局",
"menu.layout.saveCurrent": "保存对当前布局的更改",
"menu.layout.restoreCurrent": "恢复当前布局",
"menu.layout.save": "将当前布局另存为…",
"menu.layout.restoreDefault": "恢复默认布局",
"menu.layout.rename": "重命名布局…",
-12
Переглянути файл
@@ -162,18 +162,6 @@ describe("Tree keyboard navigation", () => {
expect(lead()).toBe("src");
});
it("collapsing a node collapses everything expanded below it", () => {
const onExpandedChange = vi.fn();
const { tree, key } = setup({ defaultExpanded: ["src", "main"], onExpandedChange });
expect(labels(tree)).toEqual(["src", "main", "App.tsx", "index.ts", "util.ts", "README.md"]);
key("Home");
key("ArrowLeft");
expect(labels(tree)).toEqual(["src", "README.md"]);
expect([...onExpandedChange.mock.calls[0]![0]]).toEqual([]);
key("ArrowRight");
expect(labels(tree)).toEqual(["src", "main", "util.ts", "README.md"]);
});
it("Enter toggles folders and activates leaves", () => {
const { tree, lead, key, onActivate } = setup();
key("ArrowDown");
+1 -10
Переглянути файл
@@ -395,16 +395,7 @@ export function Tree<T>(props: TreeProps<T>) {
if (!row.expandable || row.expanded === open) return;
const next = new Set(expanded);
if (open) next.add(row.key);
else {
// Collapsing a node also collapses everything expanded below it, so expanding it again
// shows only its direct children.
next.delete(row.key);
const stack = [...(getChildren(row.node) ?? [])];
while (next.size && stack.length) {
const n = stack.pop()!;
if (next.delete(getKey(n)) || isExpandable(n)) stack.push(...(getChildren(n) ?? []));
}
}
else next.delete(row.key);
if (!expandedControlled) setExpandedInner(next);
props.onExpandedChange?.(next, row.node, open);
if (open && getChildren(row.node) === undefined) void loadChildren?.(row.node);
+1 -10
Переглянути файл
@@ -531,8 +531,6 @@ export interface ExternalFileOpenHandler {
id: string;
/** Lower asks first. Default 100. */
order?: number;
/** Whether `path` goes to another application. */
matches(path: string): boolean;
/** Opens `path` outside the IDE; true when it was handed over. */
open(path: string): boolean | Promise<boolean>;
}
@@ -546,11 +544,6 @@ export function registerExternalFileOpenHandler(handler: ExternalFileOpenHandler
};
}
/** Whether opening `path` would hand it to another application. */
export function opensExternally(path: string): boolean {
return [...externalFileOpenHandlers.values()].some((h) => h.matches(path));
}
/** Opens `path` with another application; false when no handler took it. Handler failures fall through. */
export async function openFileExternally(path: string): Promise<boolean> {
const handlers = [...externalFileOpenHandlers.values()].sort(
@@ -558,7 +551,7 @@ export async function openFileExternally(path: string): Promise<boolean> {
);
for (const handler of handlers) {
try {
if (handler.matches(path) && (await handler.open(path))) return true;
if (await handler.open(path)) return true;
} catch (e) {
console.warn(`external file opener ${handler.id} failed`, e);
}
@@ -626,8 +619,6 @@ export interface OpenOptions {
focus?: boolean;
/** Open in the text editor even when a file editor provider claims the file (SVG as text). */
asText?: boolean;
/** False: leave files that go to another application unopened (autoscroll must not launch apps). */
external?: boolean;
}
export interface OpenEditorTab {
+3 -17
Переглянути файл
@@ -1,15 +1,10 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import {
openFileExternally,
opensExternally,
registerExternalFileOpenHandler,
type ExternalFileOpenHandler,
} from "./contributions";
import { openFileExternally, registerExternalFileOpenHandler, type ExternalFileOpenHandler } from "./contributions";
const disposers: Array<() => void> = [];
function register(handler: Omit<ExternalFileOpenHandler, "matches"> & Partial<ExternalFileOpenHandler>) {
const dispose = registerExternalFileOpenHandler({ matches: () => true, ...handler });
function register(handler: ExternalFileOpenHandler) {
const dispose = registerExternalFileOpenHandler(handler);
disposers.push(dispose);
return dispose;
}
@@ -62,15 +57,6 @@ describe("external file openers", () => {
expect(await openFileExternally("/p/a.ts")).toBe(false);
});
it("skips handlers that do not match and reports whether one would", async () => {
const open = vi.fn(() => true);
register({ id: "pdf", matches: (p) => p.endsWith(".pdf"), open });
expect(opensExternally("/p/a.pdf")).toBe(true);
expect(opensExternally("/p/a.ts")).toBe(false);
expect(await openFileExternally("/p/a.ts")).toBe(false);
expect(open).not.toHaveBeenCalled();
});
it("disposal removes a handler", async () => {
const dispose = register({ id: "only", open: () => true });
expect(await openFileExternally("/p/a.xlsx")).toBe(true);
+1 -29
Переглянути файл
@@ -10,10 +10,8 @@ import {
deleteLayout,
layoutNames,
renameLayout,
restoreCurrentLayout,
restoreDefaultLayout,
restoreLayout,
saveCurrentLayout,
saveLayout,
useToolWindowLayouts,
} from "./layouts";
@@ -95,28 +93,6 @@ function layoutActions(): Action[] {
if (name) restoreLayout(name);
},
},
{
id: "layout.restoreCurrent",
title: "Restore Current Layout",
description: "Restores the active saved layout, or the default layout when none is active.",
category: "Window",
keywords: ["tool window layout", "reset"],
when: "projectOpen",
run: () => {
exitDistractionFree();
restoreCurrentLayout();
},
},
{
id: "layout.saveCurrent",
title: "Save Changes in Current Layout",
category: "Window",
keywords: ["tool window layout", "store layout"],
when: "projectOpen && toolWindowLayoutActive",
run: () => {
saveCurrentLayout();
},
},
{
id: "layout.restoreDefault",
title: "Restore Default Layout",
@@ -199,11 +175,7 @@ export function installToolWindowActions(): () => void {
const unsubscribe = useContributions.subscribe((s, prev) => {
if (s.toolWindows !== prev.toolWindows) sync();
});
const publishLayouts = () => {
const { layouts, active } = useToolWindowLayouts.getState();
setContext("toolWindowLayoutsSaved", layouts.length > 0);
setContext("toolWindowLayoutActive", !!active);
};
const publishLayouts = () => setContext("toolWindowLayoutsSaved", useToolWindowLayouts.getState().layouts.length > 0);
publishLayouts();
const unsubscribeLayouts = useToolWindowLayouts.subscribe(publishLayouts);
/** The window an Options menu names, else the active one. */
-26
Переглянути файл
@@ -43,32 +43,6 @@ beforeEach(() => {
afterEach(() => disposers.forEach((d) => d()));
describe("tool window layouts", () => {
it("restores the current layout, and saves changes into it", async () => {
setContext("projectOpen", true);
setToolWindowSize("bottom", 400);
saveLayout("Custom 1");
setToolWindowSize("bottom", 200);
await executeAction("layout.restoreCurrent");
expect(useToolWindowLayout.getState().sizes.bottom).toBe(400);
expect(getContext().toolWindowLayoutActive).toBe(true);
setToolWindowSize("bottom", 300);
await executeAction("layout.saveCurrent");
setToolWindowSize("bottom", 200);
await executeAction("layout.restoreCurrent");
expect(useToolWindowLayout.getState().sizes.bottom).toBe(300);
expect(layoutNames()).toEqual(["Custom 1"]);
// With no active layout it is the default one.
restoreDefaultLayout();
expect(getContext().toolWindowLayoutActive).toBe(false);
const defaultBottom = useToolWindowLayout.getState().sizes.bottom;
setToolWindowSize("bottom", 350);
await executeAction("layout.restoreCurrent");
expect(useToolWindowLayout.getState().sizes.bottom).toBe(defaultBottom);
setContext("projectOpen", false);
});
it("saves and restores visible windows and sizes by name", () => {
showToolWindow("structure");
showToolWindow("terminal");
-14
Переглянути файл
@@ -72,20 +72,6 @@ export function restoreLayout(name: string): boolean {
return true;
}
/** Restore Current Layout: the active saved layout again, or the default one when none is active. */
export function restoreCurrentLayout() {
const { active } = useToolWindowLayouts.getState();
if (!active || !restoreLayout(active)) restoreDefaultLayout();
}
/** Save Changes in Current Layout: the active saved layout takes the windows as they are now. */
export function saveCurrentLayout(): boolean {
const { active } = useToolWindowLayouts.getState();
if (!active) return false;
saveLayout(active);
return true;
}
export function restoreDefaultLayout() {
applyToolWindowLayout(defaultLayoutSnapshot());
write({ ...useToolWindowLayouts.getState(), active: null });