дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-26 11:18:20 +02:00
Порівняти коміти
7
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
04696c00c6 | ||
|
|
33c5627bdb | ||
|
|
3a22a2d0f0 | ||
|
|
c169b8ab3c | ||
|
|
0dbce5d09e | ||
|
|
7fe6f5f58d | ||
|
|
abf904553d |
No files matched your search
@@ -159,6 +159,15 @@ 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>> {
|
||||
@@ -208,6 +217,7 @@ 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
|
||||
});
|
||||
|
||||
@@ -28,6 +28,7 @@ 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)]
|
||||
|
||||
@@ -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 = node.child_by_field_name("superclasses").map(|args| base_names(args, text)).unwrap_or_default();
|
||||
let bases = class_base_names(node, text);
|
||||
out.push(ClassBases { name, line: range.start.line, col: range.start.col, bases });
|
||||
});
|
||||
out
|
||||
@@ -67,6 +67,11 @@ 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();
|
||||
|
||||
@@ -10,6 +10,7 @@ mod inheritance;
|
||||
pub(crate) mod lines;
|
||||
mod literals;
|
||||
mod outline;
|
||||
mod python_facts;
|
||||
mod rst;
|
||||
mod selection;
|
||||
mod sfc;
|
||||
@@ -27,6 +28,7 @@ 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;
|
||||
|
||||
@@ -0,0 +1,438 @@
|
||||
//! 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);
|
||||
}
|
||||
}
|
||||
@@ -134,6 +134,17 @@ 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>> {
|
||||
|
||||
@@ -209,6 +209,7 @@ 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,
|
||||
|
||||
@@ -799,6 +799,9 @@ 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,
|
||||
@@ -2318,6 +2321,8 @@ mod tests {
|
||||
"view.quickSwitchScheme",
|
||||
"code.cleanup",
|
||||
"runAnything.show",
|
||||
"layout.saveCurrent",
|
||||
"layout.restoreCurrent",
|
||||
"layout.save",
|
||||
"layout.restoreDefault",
|
||||
"layout.rename",
|
||||
|
||||
@@ -351,6 +351,8 @@ 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;
|
||||
@@ -7567,6 +7569,15 @@ 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,
|
||||
@@ -8776,12 +8787,44 @@ 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,
|
||||
|
||||
@@ -269,25 +269,69 @@ export async function baseDeclarations(index: InheritanceIndex, cls: ClassInheri
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* 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)`.
|
||||
*/
|
||||
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[]> {
|
||||
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;
|
||||
return (await ancestryResolution(index, cls, depth)).ancestors.map((node) => node.decl);
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
/**
|
||||
* Code analysis: Inspect Code (batch language-server diagnostics), Locate
|
||||
* Duplicates and Search / Replace Structurally.
|
||||
* Duplicates and Search / Replace Structurally, and the Python inheritance
|
||||
* inspections the IDE computes from its own graph.
|
||||
*/
|
||||
import { registerEditorContribution } from "@/editor/api";
|
||||
import { registerActions } from "@/platform/actions";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { registerOverlay, registerToolWindow } from "@/workbench/contributions";
|
||||
@@ -14,12 +16,14 @@ 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;
|
||||
|
||||
@@ -0,0 +1,366 @@
|
||||
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([]);
|
||||
});
|
||||
@@ -0,0 +1,490 @@
|
||||
/**
|
||||
* 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, []);
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -64,6 +64,7 @@ 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";
|
||||
@@ -446,6 +447,7 @@ 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"],
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
@@ -21,13 +21,15 @@ 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 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.
|
||||
* 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.
|
||||
*/
|
||||
export function scriptEntries(text: string): ScriptEntry[] {
|
||||
export function objectEntries(text: string, section: string): ScriptEntry[] {
|
||||
const entries: ScriptEntry[] = [];
|
||||
let i = 0;
|
||||
let line = 0;
|
||||
@@ -132,7 +134,7 @@ export function scriptEntries(text: string): ScriptEntry[] {
|
||||
if (text[i] !== ":") break;
|
||||
i++;
|
||||
ws();
|
||||
if (key === "scripts" && text[i] === "{") {
|
||||
if (key === section && text[i] === "{") {
|
||||
i++;
|
||||
ws();
|
||||
if (text[i] !== "}") {
|
||||
@@ -153,7 +155,7 @@ export function scriptEntries(text: string): ScriptEntry[] {
|
||||
break;
|
||||
}
|
||||
}
|
||||
i++; // the closing `}` of `scripts`
|
||||
i++; // the closing `}` of the section
|
||||
} else {
|
||||
value();
|
||||
}
|
||||
@@ -302,19 +304,13 @@ interface Placed extends ScriptEntry {
|
||||
|
||||
const setEntries = StateEffect.define<Placed[]>();
|
||||
|
||||
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 }));
|
||||
},
|
||||
});
|
||||
type EntryMenu = (entry: ScriptEntry, path: string, content: string) => Promise<MenuItem[]>;
|
||||
|
||||
class ScriptMarker extends GutterMarker {
|
||||
constructor(
|
||||
readonly entry: ScriptEntry,
|
||||
readonly path: string,
|
||||
readonly menu: EntryMenu,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
@@ -330,7 +326,7 @@ class ScriptMarker extends GutterMarker {
|
||||
el.innerHTML = gutterIconMarkup("gutter-run") ?? "";
|
||||
el.addEventListener("click", () => {
|
||||
const rect = el.getBoundingClientRect();
|
||||
void scriptMenuItems(this.entry, this.path, view.state.doc.toString()).then((items) =>
|
||||
void this.menu(this.entry, this.path, view.state.doc.toString()).then((items) =>
|
||||
showContextMenu({ x: rect.left, y: rect.bottom + 2 }, items),
|
||||
);
|
||||
});
|
||||
@@ -343,8 +339,29 @@ 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 || !/(^|\/)package\.json$/.test(path) || !useProject.getState().project?.root) return [];
|
||||
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 }));
|
||||
},
|
||||
});
|
||||
const detector = ViewPlugin.fromClass(
|
||||
class {
|
||||
timer: ReturnType<typeof setTimeout> | undefined;
|
||||
@@ -358,10 +375,10 @@ export function npmGutter(ctx: EditorDocContext): Extension {
|
||||
clearTimeout(this.timer);
|
||||
this.timer = setTimeout(() => {
|
||||
const view = this.view;
|
||||
const entries = scriptEntries(view.state.doc.toString())
|
||||
const found = entries(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(entries) });
|
||||
view.dispatch({ effects: setEntries.of(found) });
|
||||
}, delay);
|
||||
}
|
||||
destroy() {
|
||||
@@ -377,7 +394,7 @@ export function npmGutter(ctx: EditorDocContext): Extension {
|
||||
class: `${styles.runGutter} cm-openidea-gutter-run`,
|
||||
markers: (view) =>
|
||||
RangeSet.of(
|
||||
view.state.field(entriesField).map((e) => new ScriptMarker(e, path).range(e.pos)),
|
||||
view.state.field(entriesField).map((e) => new ScriptMarker(e, path, menu).range(e.pos)),
|
||||
true,
|
||||
),
|
||||
// Reserve width only while the file has scripts, like the run gutter.
|
||||
|
||||
@@ -116,7 +116,15 @@ describe("inspections tree", () => {
|
||||
"Version control",
|
||||
]);
|
||||
const python = find(tree, "group:Python")!;
|
||||
expect(python.children.map((n) => n.id)).toEqual(["lsp:basedpyright", "lsp:ruff"]);
|
||||
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[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"]);
|
||||
|
||||
@@ -123,7 +123,9 @@ describe("current line decoration", () => {
|
||||
expect(hint()?.textContent).toContain("Bob Jones");
|
||||
v.dispatch({ selection: { anchor: 0 } });
|
||||
expect(hint()).toBeNull();
|
||||
await tick();
|
||||
// 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);
|
||||
expect(hint()?.textContent).toContain("Alice Smith");
|
||||
expect(mocks.blame).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.file).toHaveBeenCalledTimes(1);
|
||||
@@ -137,6 +139,17 @@ 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) });
|
||||
|
||||
@@ -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"] });
|
||||
useVcs.setState({ available: true, roots: ["/p", "/p/lib"], status: [] });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -164,6 +164,34 @@ 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 the repositories again when the set of roots changes", async () => {
|
||||
enable(true);
|
||||
dispose = installRootSync();
|
||||
|
||||
@@ -69,19 +69,30 @@ 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.pending = load();
|
||||
this.lines = undefined;
|
||||
this.pending = load().then((lines) => {
|
||||
if (this.doc === doc) this.lines = lines;
|
||||
return lines;
|
||||
});
|
||||
}
|
||||
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
|
||||
@@ -265,7 +276,15 @@ export function inlineBlame(ctx: EditorDocContext): Extension {
|
||||
if (update.docChanged) this.cache.clear();
|
||||
if (update.docChanged || update.selectionSet) {
|
||||
this.line = undefined;
|
||||
this.schedule();
|
||||
// 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import type { BranchInfo } from "@/bindings";
|
||||
import type { BranchInfo, FileStatus } 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 } from "./store";
|
||||
|
||||
const PROVIDER = "vcs-root-sync";
|
||||
@@ -20,7 +21,13 @@ const styled = (attr: string, extra: Pick<DecorationSegment, "text"> & Decoratio
|
||||
...extra,
|
||||
});
|
||||
|
||||
export function rootSyncSuffix(info: BranchInfo): DecorationSegment[] | null {
|
||||
/** 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 {
|
||||
const { head, upstream, ahead, behind } = info;
|
||||
if (!head) return null;
|
||||
const branchAttr = upstream
|
||||
@@ -32,7 +39,7 @@ export function rootSyncSuffix(info: BranchInfo): DecorationSegment[] | null {
|
||||
: "local-branch";
|
||||
const branchColor = `var(--git-${branchAttr}, var(--accent))`;
|
||||
const branch: DecorationSegment = styled(branchAttr, { text: head, color: branchColor });
|
||||
if (!upstream) return [branch];
|
||||
if (!upstream) return [branch, ...changedFiles(changed)];
|
||||
const counts: DecorationSegment[] = [];
|
||||
if (ahead > 0)
|
||||
counts.push(
|
||||
@@ -61,7 +68,23 @@ export function rootSyncSuffix(info: BranchInfo): DecorationSegment[] | null {
|
||||
color: "var(--git-head-tags, var(--accent))",
|
||||
}),
|
||||
);
|
||||
return [branch, styled("head-tags", { text: "/", color: "var(--git-head-tags, var(--accent))" }), ...counts];
|
||||
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;
|
||||
}
|
||||
|
||||
async function branchInfoOf(root: string): Promise<[string, BranchInfo] | null> {
|
||||
@@ -83,6 +106,7 @@ 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;
|
||||
@@ -94,12 +118,27 @@ 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, FileDecoration>();
|
||||
const next = new Map<string, BranchInfo>();
|
||||
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 });
|
||||
// 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;
|
||||
if (suffix) next.set(root, { suffix, suffixColor: SUFFIX_COLOR });
|
||||
}
|
||||
publish(next);
|
||||
};
|
||||
|
||||
@@ -129,6 +168,8 @@ export function installRootSync(): () => void {
|
||||
|
||||
const unsubVcs = useVcs.subscribe((s, prev) => {
|
||||
if (s.available !== prev.available || s.roots.join("\n") !== prev.roots.join("\n")) schedule();
|
||||
// The changed-file counts follow the working tree as the status refreshes, without asking git.
|
||||
else if (s.status !== prev.status) render();
|
||||
});
|
||||
const offGit = onIdeEvent("vcsChanged", scheduleSoon);
|
||||
const offSettings = onWorkflowSettingsChange((s) => s.vcs.git.showBranchInProjectView, schedule);
|
||||
|
||||
@@ -240,6 +240,16 @@ 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",
|
||||
@@ -310,6 +320,42 @@ 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",
|
||||
|
||||
@@ -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.restoreDefault", ["Shift+F12"], ["Shift+F12"]],
|
||||
["layout.restoreCurrent", ["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"]],
|
||||
|
||||
@@ -237,7 +237,8 @@ export const intellijMacos: Record<string, string[]> = {
|
||||
"toolwindow.resizeRight": ["Ctrl+Alt+Right"],
|
||||
"toolwindow.resizeUp": ["Ctrl+Alt+Up"],
|
||||
"toolwindow.resizeDown": ["Ctrl+Alt+Down"],
|
||||
"layout.restoreDefault": ["Shift+F12"],
|
||||
"layout.restoreCurrent": ["Shift+F12"],
|
||||
"layout.restoreDefault": [],
|
||||
"toolwindow.jumpToLast": ["F12"],
|
||||
"toolwindow.hideActive": ["Shift+Escape"],
|
||||
"toolwindow.focusEditor": ["Escape"],
|
||||
|
||||
@@ -234,7 +234,8 @@ export const intellijWindows: Record<string, string[]> = {
|
||||
"toolwindow.terminal": ["Alt+F12"],
|
||||
"toolwindow.hideAll": ["Ctrl+Shift+F12"],
|
||||
"toolwindow.maximize": ["Ctrl+Shift+'"],
|
||||
"layout.restoreDefault": ["Shift+F12"],
|
||||
"layout.restoreCurrent": ["Shift+F12"],
|
||||
"layout.restoreDefault": [],
|
||||
"toolwindow.jumpToLast": ["F12"],
|
||||
"toolwindow.hideActive": ["Shift+Escape"],
|
||||
"toolwindow.focusEditor": ["Escape"],
|
||||
|
||||
@@ -65,6 +65,7 @@ export const vscodeMacos: Record<string, string[]> = {
|
||||
"toolwindow.resizeRight": [],
|
||||
"toolwindow.resizeUp": [],
|
||||
"toolwindow.resizeDown": [],
|
||||
"layout.restoreCurrent": [],
|
||||
"layout.restoreDefault": [],
|
||||
"workbench.stopBackgroundProcesses": [],
|
||||
"navigate.typeHierarchy": [],
|
||||
|
||||
@@ -457,6 +457,8 @@
|
||||
"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…",
|
||||
|
||||
@@ -1753,5 +1753,17 @@
|
||||
"YAML File": "YAML File",
|
||||
"TOML File": "TOML File",
|
||||
"EditorConfig File": "EditorConfig File",
|
||||
".gitignore File": ".gitignore 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}'"
|
||||
}
|
||||
@@ -1775,6 +1775,7 @@
|
||||
"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 项",
|
||||
@@ -2389,6 +2390,9 @@
|
||||
"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": "恢复大小",
|
||||
@@ -8140,5 +8144,17 @@
|
||||
"YAML File": "YAML 文件",
|
||||
"TOML File": "TOML 文件",
|
||||
"EditorConfig File": "EditorConfig 文件",
|
||||
".gitignore File": ".gitignore 文件"
|
||||
".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}'"
|
||||
}
|
||||
@@ -457,6 +457,8 @@
|
||||
"menu.runAnything.show": "运行任何内容…",
|
||||
"menu.localHistory.putLabel": "添加标签…",
|
||||
"menu.toolWindowLayouts": "工具窗口布局",
|
||||
"menu.layout.saveCurrent": "保存对当前布局的更改",
|
||||
"menu.layout.restoreCurrent": "恢复当前布局",
|
||||
"menu.layout.save": "将当前布局另存为…",
|
||||
"menu.layout.restoreDefault": "恢复默认布局",
|
||||
"menu.layout.rename": "重命名布局…",
|
||||
|
||||
@@ -10,8 +10,10 @@ import {
|
||||
deleteLayout,
|
||||
layoutNames,
|
||||
renameLayout,
|
||||
restoreCurrentLayout,
|
||||
restoreDefaultLayout,
|
||||
restoreLayout,
|
||||
saveCurrentLayout,
|
||||
saveLayout,
|
||||
useToolWindowLayouts,
|
||||
} from "./layouts";
|
||||
@@ -93,6 +95,28 @@ 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",
|
||||
@@ -175,7 +199,11 @@ export function installToolWindowActions(): () => void {
|
||||
const unsubscribe = useContributions.subscribe((s, prev) => {
|
||||
if (s.toolWindows !== prev.toolWindows) sync();
|
||||
});
|
||||
const publishLayouts = () => setContext("toolWindowLayoutsSaved", useToolWindowLayouts.getState().layouts.length > 0);
|
||||
const publishLayouts = () => {
|
||||
const { layouts, active } = useToolWindowLayouts.getState();
|
||||
setContext("toolWindowLayoutsSaved", layouts.length > 0);
|
||||
setContext("toolWindowLayoutActive", !!active);
|
||||
};
|
||||
publishLayouts();
|
||||
const unsubscribeLayouts = useToolWindowLayouts.subscribe(publishLayouts);
|
||||
/** The window an Options menu names, else the active one. */
|
||||
|
||||
@@ -43,6 +43,32 @@ 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");
|
||||
|
||||
@@ -72,6 +72,20 @@ 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 });
|
||||
|
||||
Reference in new issue
Заблокувати користувача