feat(python): find usages and rename for pytest fixtures (#6520)

Find Usages and Rename on a pytest fixture (its definition or a test parameter that requests it) now cover every test and fixture that requests it by parameter name, including conftest.py fixtures used across the directory tree, overrides and usefixtures markers.

Closes #6513

Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-11-28 00:15:16 +08:00
1 джерело f0db09aca5
коміт 49c917880d
12 files changed
+560 -51

No files matched your search

+59 -2
Переглянути файл
@@ -1,12 +1,12 @@
use super::blocking;
use super::pytest_fixtures::{PytestFixtureAt, fixture_at};
use super::pytest_fixtures::{PytestFixtureAt, PytestFixtureUsages, fixture_at, fixture_usages, rename_fixture};
use super::python_stubs::{
PythonStubLinks, counterpart_candidates, match_declarations, module_name, site_packages, stub_path,
};
use crate::Host;
use crate::Project;
use ide_command::command;
use ide_core::{DocId, IdeResult, IpcPath, LanguageId, Location, Pos};
use ide_core::{DocId, IdeResult, IpcPath, LanguageId, Location, Pos, RequestId, WorkspaceEdit};
use ide_index::{ExtensionCount, FileMatch, IndexStatus, SymbolFilter, SymbolMatch};
use ide_language::{CSS_VARIABLE, FileReference, WebReference};
use ide_workspace::file_refs::{self, PathCompletion};
@@ -496,6 +496,61 @@ pub async fn nav_pytest_fixtures(host: &Host, window: &str, doc: DocId, pos: Pos
.await
}
/// Find Usages of the pytest fixture at `pos` (its definition, or a place asking for it): every
/// test and fixture parameter, `usefixtures` and `getfixturevalue` string that gets it.
/// None when `pos` names no fixture. Cancellable.
#[command(trust = always)]
pub async fn nav_pytest_fixture_usages(
host: &Host,
window: &str,
doc: DocId,
pos: Pos,
request: RequestId,
) -> IdeResult<Option<PytestFixtureUsages>> {
let project = host.project(window)?;
let syntax = host.syntax();
let token = host.begin_request(request);
let result = blocking(move || {
let snap = project.documents.snapshot(doc)?;
if snap.large || snap.language.as_str() != "python" {
return Ok(None);
}
fixture_usages(&project, &syntax, &snap.path, &snap.text, pos, &|| token.is_cancelled())
})
.await;
host.end_request(request);
result
}
/// Rename of the pytest fixture at `pos`: its definition, every place that gets it and the
/// uses of those parameters in their functions. Cancellable.
#[command(trust = always)]
pub async fn nav_pytest_fixture_rename(
host: &Host,
window: &str,
doc: DocId,
pos: Pos,
new_name: String,
request: RequestId,
) -> IdeResult<WorkspaceEdit> {
let project = host.project(window)?;
let syntax = host.syntax();
let token = host.begin_request(request);
let result = blocking(move || {
let snap = project.documents.snapshot(doc)?;
let mut edit =
rename_fixture(&project, &syntax, &snap.path, &snap.text, pos, &new_name, &|| token.is_cancelled())?;
if token.is_cancelled() {
return Err(ide_core::IdeError::cancelled());
}
project.documents.prepare_workspace_edit(&mut edit)?;
Ok(edit)
})
.await;
host.end_request(request);
result
}
ide_command::domain!(
nav:
find_dirs,
@@ -509,6 +564,8 @@ ide_command::domain!(
mark_recent,
nav_index_definitions,
nav_inheritance,
nav_pytest_fixture_rename,
nav_pytest_fixture_usages,
nav_pytest_fixtures,
nav_python_stubs,
nav_resolve_module,
+244 -35
Переглянути файл
@@ -5,7 +5,7 @@
use super::python_stubs::site_packages;
use crate::Project;
use ide_core::{IpcPath, LanguageId, Location, Pos, Range};
use ide_core::{FileEdit, IdeError, IdeResult, IpcPath, LanguageId, Location, Pos, Range, TextEdit, WorkspaceEdit};
use ide_language::{PytestModule, Syntax, resolve_fixture, visible_fixtures};
use serde::{Deserialize, Serialize};
use specta::Type;
@@ -49,7 +49,7 @@ pub(crate) fn fixture_at(project: &Project, syntax: &Syntax, path: &Path, text:
if usage.is_none() && slot.is_none() {
return PytestFixtureAt::default();
}
let layers = layers(project, syntax, path, Arc::new(own));
let layers = Scope::new(project).layers(project, syntax, path, Arc::new(own));
let modules: Vec<&PytestModule> = layers.iter().map(|(_, m)| m.as_ref()).collect();
let reference = usage.map(|u| {
let found = resolve_fixture(&modules, &u.name, u.class.as_deref(), u.in_fixture.as_deref() == Some(&u.name));
@@ -83,45 +83,241 @@ fn python() -> LanguageId {
type Layer = (PathBuf, Arc<PytestModule>);
/// The modules `path` sees, nearest first, `own` being its own.
fn layers(project: &Project, syntax: &Syntax, path: &Path, own: Arc<PytestModule>) -> Vec<Layer> {
let mut out: Vec<Layer> = vec![(path.to_path_buf(), own)];
// conftest.py files from the file's folder up to the project root.
let mut dir = path.parent();
while let Some(d) = dir.filter(|d| d.starts_with(&project.root)) {
let conftest = d.join("conftest.py");
if conftest != path
&& let Some(m) = module_of(project, syntax, &conftest)
{
out.push((conftest, m));
/// What every file of the project sees after its own `conftest.py` files: the folders
/// `pytest_plugins` modules are found in, installed plugins and pytest's own modules.
struct Scope {
search: Vec<PathBuf>,
tail: Vec<PathBuf>,
}
impl Scope {
fn new(project: &Project) -> Self {
let packages = interpreter_site_packages(project);
let mut search = super::python::paths(project);
search.extend(packages.iter().cloned());
// `pytest_plugins = ["pytester"]` names pytest's own optional plugins by their short name.
search.extend(packages.iter().map(|p| p.join("_pytest")));
let mut tail = Vec::new();
for packages in &packages {
tail.extend(
entry_point_modules(packages).iter().filter_map(|m| module_file(m, std::slice::from_ref(packages))),
);
}
dir = d.parent();
for packages in &packages {
tail.extend(builtin_modules(&packages.join("_pytest")));
}
Self { search, tail }
}
let packages = interpreter_site_packages(project);
let mut search = super::python::paths(project);
search.extend(packages.iter().cloned());
// `pytest_plugins = ["pytester"]` names pytest's own optional plugins by their short name.
search.extend(packages.iter().map(|p| p.join("_pytest")));
// Modules named by `pytest_plugins` in those files.
let named: Vec<String> = out.iter().flat_map(|(_, m)| m.plugins.clone()).collect();
let mut extra: Vec<PathBuf> = named.iter().filter_map(|module| module_file(module, &search)).collect();
// Installed plugins, then pytest's own fixtures.
for packages in &packages {
extra.extend(
entry_point_modules(packages).iter().filter_map(|m| module_file(m, std::slice::from_ref(packages))),
);
/// The modules `path` sees, nearest first, `own` being its own: its `conftest.py` files up to
/// the project root, the modules their `pytest_plugins` name, then installed plugins and pytest.
fn layers(&self, project: &Project, syntax: &Syntax, path: &Path, own: Arc<PytestModule>) -> Vec<Layer> {
let mut out: Vec<Layer> = vec![(path.to_path_buf(), own)];
let mut dir = path.parent();
while let Some(d) = dir.filter(|d| d.starts_with(&project.root)) {
let conftest = d.join("conftest.py");
if conftest != path
&& let Some(m) = module_of(project, syntax, &conftest)
{
out.push((conftest, m));
}
dir = d.parent();
}
let named: Vec<String> = out.iter().flat_map(|(_, m)| m.plugins.clone()).collect();
let extra =
named.iter().filter_map(|module| module_file(module, &self.search)).chain(self.tail.iter().cloned());
for file in extra.collect::<Vec<_>>() {
if !out.iter().any(|(p, _)| *p == file)
&& let Some(m) = module_of(project, syntax, &file)
{
out.push((file, m));
}
}
out
}
for packages in &packages {
extra.extend(builtin_modules(&packages.join("_pytest")));
}
/// A fixture definition: its file and the range of its name there.
#[derive(Clone, Debug, PartialEq, Eq)]
struct Definition {
name: String,
path: PathBuf,
selection: Range,
}
/// Where pytest finds the fixture `u` asks for, seen from `layers`.
fn definition_of(layers: &[Layer], u: &ide_language::PytestFixtureUse) -> Option<Definition> {
let modules: Vec<&PytestModule> = layers.iter().map(|(_, m)| m.as_ref()).collect();
let (l, f) = resolve_fixture(&modules, &u.name, u.class.as_deref(), u.in_fixture.as_deref() == Some(&u.name))?;
Some(Definition { name: u.name.clone(), path: layers[l].0.clone(), selection: modules[l].fixtures[f].selection })
}
/// The fixture at `pos` of `path`: the one defined there, or the one a test asks for there.
fn target_at(
project: &Project,
syntax: &Syntax,
scope: &Scope,
path: &Path,
own: &Arc<PytestModule>,
pos: Pos,
) -> Option<Definition> {
if let Some(f) = own.definition_at(pos) {
let fixture = &own.fixtures[f];
return Some(Definition { name: fixture.name.clone(), path: path.to_path_buf(), selection: fixture.selection });
}
for file in extra {
if !out.iter().any(|(p, _)| *p == file)
&& let Some(m) = module_of(project, syntax, &file)
{
out.push((file, m));
let usage = own.use_at(pos)?;
definition_of(&scope.layers(project, syntax, path, own.clone()), usage)
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PytestFixtureUsages {
pub name: String,
pub definition: Location,
/// Defined in the project (not by a plugin or pytest): it may be renamed.
pub in_project: bool,
/// Every place that gets this fixture: parameters, `usefixtures` and `getfixturevalue` strings.
pub usages: Vec<Location>,
}
struct Usage {
path: PathBuf,
use_: ide_language::PytestFixtureUse,
}
/// The fixture at `pos` of the Python document `path` / `text` and every place that gets it.
pub(crate) fn fixture_usages(
project: &Project,
syntax: &Syntax,
path: &Path,
text: &str,
pos: Pos,
cancelled: &dyn Fn() -> bool,
) -> IdeResult<Option<PytestFixtureUsages>> {
let Some((target, usages)) = usages_of(project, syntax, path, text, pos, cancelled)? else { return Ok(None) };
Ok(Some(PytestFixtureUsages {
name: target.name.clone(),
in_project: is_project_file(project, &target.path),
definition: Location { path: IpcPath::from(target.path), range: target.selection, uri: None },
usages: usages
.into_iter()
.map(|u| Location { path: IpcPath::from(u.path), range: u.use_.range, uri: None })
.collect(),
}))
}
/// Rename of the fixture at `pos`: its definition (the `name=` string, else the function name),
/// every place that gets it, and the uses of a renamed parameter in its function's body.
pub(crate) fn rename_fixture(
project: &Project,
syntax: &Syntax,
path: &Path,
text: &str,
pos: Pos,
new_name: &str,
cancelled: &dyn Fn() -> bool,
) -> IdeResult<WorkspaceEdit> {
let Some((target, usages)) = usages_of(project, syntax, path, text, pos, cancelled)? else {
return Err(IdeError::invalid("No pytest fixture here"));
};
if !is_project_file(project, &target.path) {
return Err(IdeError::invalid("The fixture is defined outside the project"));
}
let mut by_file: Vec<(PathBuf, Vec<TextEdit>)> = Vec::new();
let mut edit = |file: &Path, range: Range| {
let edits = match by_file.iter_mut().find(|(p, _)| p == file) {
Some((_, edits)) => edits,
None => {
by_file.push((file.to_path_buf(), Vec::new()));
&mut by_file.last_mut().expect("just pushed").1
}
};
if !edits.iter().any(|e| e.range == range) {
edits.push(TextEdit { range, new_text: new_name.to_owned() });
}
};
edit(&target.path, target.selection);
for u in &usages {
edit(&u.path, u.use_.range);
for &r in &u.use_.body {
edit(&u.path, r);
}
}
out
let files = by_file
.into_iter()
.map(|(p, mut edits)| {
edits.sort_by_key(|e| e.range);
FileEdit::Edit { path: IpcPath::from(p), edits, version: None }
})
.collect();
Ok(WorkspaceEdit { files, preconditions: Vec::new() })
}
fn usages_of(
project: &Project,
syntax: &Syntax,
path: &Path,
text: &str,
pos: Pos,
cancelled: &dyn Fn() -> bool,
) -> IdeResult<Option<(Definition, Vec<Usage>)>> {
let own = Arc::new(syntax.pytest_module(&python(), text));
if own.definition_at(pos).is_none() && own.use_at(pos).is_none() {
return Ok(None);
}
let scope = Scope::new(project);
let Some(target) = target_at(project, syntax, &scope, path, &own, pos) else { return Ok(None) };
let mut files = candidate_files(project, &target.path);
if !files.iter().any(|f| f == path) && path.starts_with(&project.root) {
files.push(path.to_path_buf());
}
let mut usages = Vec::new();
for file in files {
if cancelled() {
return Err(IdeError::cancelled());
}
let module = if file == path { Some(own.clone()) } else { module_of(project, syntax, &file) };
let Some(module) = module else { continue };
if !module.uses.iter().any(|u| u.name == target.name) {
continue;
}
let layers = scope.layers(project, syntax, &file, module.clone());
for u in module.uses.iter().filter(|u| u.name == target.name) {
if definition_of(&layers, u).as_ref() == Some(&target) {
usages.push(Usage { path: file.clone(), use_: u.clone() });
}
}
}
Ok(Some((target, usages)))
}
/// The files that may get a fixture defined in `definition`: that test module alone, the test
/// modules and `conftest.py` files below a `conftest.py`, all of the project's for a plugin's.
fn candidate_files(project: &Project, definition: &Path) -> Vec<PathBuf> {
let in_project = is_project_file(project, definition);
let is_conftest = definition.file_name().is_some_and(|n| n == "conftest.py");
if in_project && !is_conftest {
return vec![definition.to_path_buf()];
}
let dir = if in_project { definition.parent().unwrap_or(&project.root) } else { &project.root };
let mut files = project.index.files_matching(dir, is_test_file, MAX_FILES).unwrap_or_default();
files.sort();
files
}
const MAX_FILES: usize = 20_000;
/// A file of the project's own code: below its root, not in an installed package (a
/// virtualenv inside the project holds pytest and its plugins).
fn is_project_file(project: &Project, path: &Path) -> bool {
path.starts_with(&project.root) && !path.components().any(|c| c.as_os_str() == "site-packages")
}
/// `test_*.py`, `*_test.py` and `conftest.py`: the files pytest collects or loads.
fn is_test_file(rel: &Path) -> bool {
let Some(name) = rel.file_name().and_then(|n| n.to_str()) else { return false };
let Some(stem) = name.strip_suffix(".py") else { return false };
stem == "conftest" || stem.starts_with("test_") || stem.ends_with("_test")
}
/// The `site-packages` of the project's interpreter: its virtualenv's, else its install prefix's.
@@ -234,6 +430,19 @@ fn module_of(project: &Project, syntax: &Syntax, path: &Path) -> Option<Arc<Pyte
mod tests {
use super::*;
#[test]
fn test_files_are_the_ones_pytest_loads() {
for (rel, expected) in [
("tests/test_a.py", true),
("a_test.py", true),
("pkg/conftest.py", true),
("pkg/helpers.py", false),
("test_data.json", false),
] {
assert_eq!(is_test_file(Path::new(rel)), expected, "{rel}");
}
}
#[test]
fn reads_pytest11_entry_points() {
let text =
+48 -1
Переглянути файл
@@ -44,6 +44,9 @@ pub struct PytestFixtureUse {
pub class: Option<String>,
/// The fixture whose parameter this is: `def tasks(tasks)` asks for the next `tasks` outward.
pub in_fixture: Option<String>,
/// For a parameter: the names in the function's body that read it (attribute names and
/// keyword argument names left out), which a rename of the fixture renames too.
pub body: Vec<Range>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -60,6 +63,11 @@ impl PytestModule {
self.uses.iter().find(|u| u.range.start <= pos && pos <= u.range.end)
}
/// The fixture whose name (function name or `name=` string) covers `pos`.
pub fn definition_at(&self, pos: Pos) -> Option<usize> {
self.fixtures.iter().position(|f| f.selection.start <= pos && pos <= f.selection.end)
}
/// The slot holding `pos`.
pub fn slot_at(&self, pos: Pos) -> Option<&PytestFixtureSlot> {
self.slots.iter().filter(|s| s.range.start <= pos && pos <= s.range.end).min_by_key(|s| s.range.end)
@@ -220,16 +228,39 @@ fn function(
if (i == 0 && class.is_some() && (param_name == "self" || param_name == "cls")) || skip.contains(&param_name) {
continue;
}
let body = def.child_by_field_name("body").map(|b| reads_of(b, &param_name, text, idx)).unwrap_or_default();
out.uses.push(PytestFixtureUse {
name: param_name,
range: idx.range(ident.start_byte(), ident.end_byte()),
kind: PytestFixtureUseKind::Parameter,
class: class.map(str::to_owned),
in_fixture: fixture.is_some().then(|| fixture_name.clone()),
body,
});
}
}
/// The identifiers `name` in `body`, except attribute names (`x.name`) and keyword argument
/// names (`f(name=…)`). A nested function that rebinds the name is not told apart.
fn reads_of(body: Node, name: &str, text: &str, idx: &LineIndex) -> Vec<Range> {
let mut out = Vec::new();
let mut cursor = body.walk();
visit(&mut cursor, &mut |n| {
if n.kind() != "identifier" || text.get(n.byte_range()) != Some(name) {
return;
}
let field_of = |parent: Node, field: &str| parent.child_by_field_name(field).is_some_and(|c| c.id() == n.id());
if let Some(parent) = n.parent()
&& ((parent.kind() == "attribute" && field_of(parent, "attribute"))
|| (parent.kind() == "keyword_argument" && field_of(parent, "name")))
{
return;
}
out.push(idx.range(n.start_byte(), n.end_byte()));
});
out
}
/// `Some(None)` for `@pytest.fixture` / `@fixture(...)`, `Some(Some((name, range)))` with a
/// `name="…"` argument, `None` for any other decorator.
fn fixture_decorator(decorator: Node, text: &str, idx: &LineIndex) -> Option<Option<(String, Range)>> {
@@ -314,7 +345,14 @@ fn fixture_call(call: Node, text: &str, idx: &LineIndex, out: &mut PytestModule)
let Some((name, range)) = string_content(arg, text, idx) else { continue };
out.slots.push(PytestFixtureSlot { range, class: class.clone() });
if !name.is_empty() {
out.uses.push(PytestFixtureUse { name, range, kind, class: class.clone(), in_fixture: None });
out.uses.push(PytestFixtureUse {
name,
range,
kind,
class: class.clone(),
in_fixture: None,
body: Vec::new(),
});
}
}
}
@@ -499,6 +537,15 @@ class TestTasks:
assert_eq!(visible, ["tasks", "client", "db", "tmp_path"]);
}
#[test]
fn a_parameter_knows_its_reads_in_the_body() {
let m = module("def test_a(tasks):\n tasks.add(tasks=tasks)\n other.tasks = len(tasks)\n");
let u = &m.uses[0];
let reads: Vec<(u32, u32)> = u.body.iter().map(|r| (r.start.line, r.start.col)).collect();
assert_eq!(reads, [(1, 4), (1, 20), (2, 22)]);
assert_eq!(m.definition_at(Pos::new(0, 6)), None);
}
#[test]
fn a_later_definition_replaces_an_earlier_one() {
let m = module("import pytest\n\n@pytest.fixture\ndef a():\n pass\n\n@pytest.fixture\ndef a():\n pass\n");
+2
Переглянути файл
@@ -447,6 +447,8 @@ menu_set_disabled always desktop bin
menu_set_remote_recent always desktop bindings sync
nav_index_definitions always project_host bindings async
nav_inheritance always project_host bindings async
nav_pytest_fixture_rename always project_host bindings async
nav_pytest_fixture_usages always project_host bindings async
nav_pytest_fixtures always project_host bindings async
nav_python_stubs always project_host bindings async
nav_resolve_module always project_host bindings async
+27
Переглянути файл
@@ -1221,6 +1221,24 @@ export const commands = {
* for native inheritance gutter markers.
*/
navInheritance: () => typedError<ClassInheritance[], IdeError>(__TAURI_INVOKE("nav_inheritance")),
/**
* Rename of the pytest fixture at `pos`: its definition, every place that gets it and the
* uses of those parameters in their functions. Cancellable.
*/
navPytestFixtureRename: (doc: DocId, pos: Pos, newName: string, request: RequestId) => typedError<WorkspaceEdit, IdeError>(__TAURI_INVOKE("nav_pytest_fixture_rename", { doc, pos, newName, request })),
/**
* Find Usages of the pytest fixture at `pos` (its definition, or a place asking for it): every
* test and fixture parameter, `usefixtures` and `getfixturevalue` string that gets it.
* None when `pos` names no fixture. Cancellable.
*/
navPytestFixtureUsages: (doc: DocId, pos: Pos, request: RequestId) => typedError<{
name: string,
definition: Location,
/** Defined in the project (not by a plugin or pytest): it may be renamed. */
inProject: boolean,
/** Every place that gets this fixture: parameters, `usefixtures` and `getfixturevalue` strings. */
usages: Location[],
} | null, IdeError>(__TAURI_INVOKE("nav_pytest_fixture_usages", { doc, pos, request })),
/**
* pytest fixtures at `pos` of a Python document: the definition pytest uses for the fixture
* named there (a test's parameter, a `usefixtures` / `getfixturevalue` string), and the
@@ -12226,6 +12244,15 @@ export type PytestFixtureReference = {
definition: Location | null,
};
export type PytestFixtureUsages = {
name: string,
definition: Location,
/** Defined in the project (not by a plugin or pytest): it may be renamed. */
inProject: boolean,
/** Every place that gets this fixture: parameters, `usefixtures` and `getfixturevalue` strings. */
usages: Location[],
};
/** A class definition and the methods it declares. */
export type PythonClassFacts = {
name: string,
+7
Переглянути файл
@@ -50,6 +50,13 @@ export {
type NavigationMatch,
} from "@/editor/navigationProviders";
export { registerRelatedProvider, type RelatedContext, type RelatedItem } from "@/editor/relatedProviders";
export {
contributedUsages,
registerRenameProvider,
registerUsageProvider,
type ContributedRename,
type UsageQuery,
} from "@/editor/refactorProviders";
export { offsetsToRange, offsetToPos, posToOffset, rangeToOffsets, textEditsToChanges } from "@/editor/lsp/positions";
/** Documents above this size (UTF-16 units) skip per-line decorations. */
+60 -8
Переглянути файл
@@ -43,6 +43,7 @@ import {
} from "./syntaxFallback";
import { tx } from "@/platform/i18n";
import { synchronizeDocumentIndexes } from "@/workbench/contributions";
import { contributedRename, type ContributedRename } from "@/editor/refactorProviders";
async function applyEdit(view: EditorView, edit: WorkspaceEdit) {
try {
@@ -97,6 +98,21 @@ export async function startRename(view: EditorView) {
if (!current()) return;
const head = view.state.selection.main.head;
const pos = offsetToPos(view.state.doc, head);
// Names the server doesn't connect (pytest fixtures): their provider renames them.
const own = await contributedRename(view, head);
if (!current()) return;
if (own) {
if (own.refused) return showHint(view, own.refused);
const oldName = view.state.sliceDoc(own.from, own.to);
openPopup({
kind: "symbolRename",
title: tx`Rename '${oldName}'`,
initial: oldName,
themeClasses: view.themeClasses,
onSubmit: (newName) => void finishContributedRename(view, own, oldName, newName),
});
return;
}
if (!(await prepareIndexes(view, doc.path)) || !current()) return;
let range;
try {
@@ -282,21 +298,57 @@ async function finishRename(view: EditorView, doc: EditorDocContext, pos: Pos, o
}
const { edit, incomplete } = renamed;
const note = incomplete && incompleteNote(incomplete, oldName);
await presentRename(view, edit, oldName, newName, note || null, !!renamed.preview, async () => {
if (!(await hasSyntaxErrors(doc.doc))) return false;
const plan = await syntaxPlan(view, doc, pos);
if (!plan || plan.symbol.name !== oldName) return false;
await commitSyntaxRename(view, doc, plan, newName);
return true;
});
}
async function finishContributedRename(view: EditorView, own: ContributedRename, oldName: string, newName: string) {
if (!newName || newName === oldName) return;
if (renameRequest !== null) void commands.cancelRequest(renameRequest).catch(() => {});
const request = nextRequestId();
renameRequest = request;
let edit;
try {
await whenAllSynced();
edit = await own.edit(newName, request);
if (renameRequest !== request) return;
} catch (e) {
if (renameRequest !== request || isCancelled(e)) return;
reportLspError(view, e, true);
return;
} finally {
if (renameRequest === request) renameRequest = null;
}
await presentRename(view, edit, oldName, newName, null, false, async () => false);
}
/**
* Applies a rename's edit, after a preview when it spans several files or may have missed
* usages; `fallback` gets a chance when the edit changes nothing.
*/
async function presentRename(
view: EditorView,
edit: WorkspaceEdit,
oldName: string,
newName: string,
note: string | null,
preview: boolean,
fallback: () => Promise<boolean>,
) {
const summary = summarizeWorkspaceEdit(edit);
if (!summary.files) {
if (await hasSyntaxErrors(doc.doc)) {
const plan = await syntaxPlan(view, doc, pos);
if (plan && plan.symbol.name === oldName) {
await commitSyntaxRename(view, doc, plan, newName);
return;
}
}
if (await fallback()) return;
if (note) showHint(view, note, { tone: "warning" });
else showHint(view, "Nothing to rename");
return;
}
// An edit that may leave usages behind is never applied unseen.
if (!renamed.preview && !note && !needsPreview(summary)) {
if (!preview && !note && !needsPreview(summary)) {
await applyEdit(view, edit);
return;
}
+59
Переглянути файл
@@ -0,0 +1,59 @@
/**
* Find Usages and Rename for names the language server doesn't connect (pytest fixtures and
* the tests that request them). A provider answers only for positions it owns; the first
* answer wins, and everywhere else the server's answer is used as before.
*/
import type { EditorView } from "@codemirror/view";
import type { Location, Pos, RequestId, WorkspaceEdit } from "@/platform/ipc";
export interface UsageQuery {
doc: number;
path: string;
pos: Pos;
}
/** Usages of the symbol at `query`, or null when the provider doesn't own that position. */
type UsageProvider = (query: UsageQuery, request: RequestId) => Promise<Location[] | null>;
export interface ContributedRename {
/** The name being renamed, in the editor's document. */
from: number;
to: number;
/** Why it can't be renamed (defined outside the project, …); the rename stops with this hint. */
refused?: string;
/** The edit renaming it to `newName`. */
edit: (newName: string, request: RequestId) => Promise<WorkspaceEdit>;
}
type RenameProvider = (view: EditorView, offset: number) => Promise<ContributedRename | null>;
const usageProviders = new Set<UsageProvider>();
const renameProviders = new Set<RenameProvider>();
export function registerUsageProvider(provider: UsageProvider): () => void {
usageProviders.add(provider);
return () => void usageProviders.delete(provider);
}
export function registerRenameProvider(provider: RenameProvider): () => void {
renameProviders.add(provider);
return () => void renameProviders.delete(provider);
}
export async function contributedUsages(query: UsageQuery, request: RequestId): Promise<Location[] | null> {
for (const provider of usageProviders) {
// oxlint-disable-next-line no-await-in-loop -- first owner wins
const found = await provider(query, request).catch(() => null);
if (found) return found;
}
return null;
}
export async function contributedRename(view: EditorView, offset: number): Promise<ContributedRename | null> {
for (const provider of renameProviders) {
// oxlint-disable-next-line no-await-in-loop -- first owner wins
const found = await provider(view, offset).catch(() => null);
if (found) return found;
}
return null;
}
+7 -1
Переглянути файл
@@ -2,7 +2,7 @@
import { create } from "zustand";
import { Channel } from "@tauri-apps/api/core";
import type { ClassifiedReference, ReferenceAccess, ReferenceKind, Location, References, RequestId } from "@/bindings";
import { editorsFor } from "@/editor/api";
import { contributedUsages, editorsFor } from "@/editor/api";
import { clearLineTokens } from "@/editor/lineTokens";
import { showPendingHint } from "@/editor/lsp/hint";
import { incompleteNote } from "@/editor/lsp/lsp";
@@ -245,6 +245,12 @@ export async function fetchUsages(
await caretSynced(c);
const indexed = await synchronizeDocumentIndexes(c.path, "usages");
if (c.view && c.view.state.doc !== before) throw new IpcError({ kind: "cancelled", message: "", data: null });
// Names the server doesn't connect (pytest fixtures): their provider answers instead.
const contributed = await contributedUsages({ doc: c.doc, path: c.path, pos: { line: c.line, col: c.col } }, request);
if (contributed) {
const lines = await readManyFileLines(contributed.map((l) => l.path));
return { groups: groupUsages(contributed, lines, []), note: null, librariesSkipped: false };
}
let settled = false;
const channel = new Channel<References>();
channel.onmessage = (refs) => {
+44 -4
Переглянути файл
@@ -1,8 +1,10 @@
/**
* pytest fixtures: Go to Declaration on a fixture name (a test's or fixture's parameter, a
* `usefixtures` / `getfixturevalue` string) opens the fixture pytest uses, and completion
* offers the visible fixtures there. Resolution (conftest.py files, plugins, pytest's own
* fixtures) is the backend's (`navPytestFixtures`); the language server knows none of it.
* `usefixtures` / `getfixturevalue` string) opens the fixture pytest uses, completion offers
* the visible fixtures there, and Find Usages / Rename on a fixture cover every place that
* gets it. Resolution (conftest.py files, plugins, pytest's own fixtures) is the backend's
* (`navPytestFixtures`, `navPytestFixtureUsages`, `navPytestFixtureRename`); the language
* server knows none of it.
*/
import type { CompletionContext, CompletionResult } from "@codemirror/autocomplete";
import { EditorState } from "@codemirror/state";
@@ -10,12 +12,16 @@ import type { EditorView } from "@codemirror/view";
import {
registerEditorContribution,
registerNavigationProvider,
registerRenameProvider,
registerUsageProvider,
whenSynced,
type ContributedRename,
type EditorDocContext,
} from "@/editor/api";
import { docOf } from "@/editor/lsp/lsp";
import { offsetToPos, posToOffset } from "@/editor/lsp/positions";
import { call, commands, isTauri, type PytestFixtureAt } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { call, commands, isTauri, nextRequestId, type Location, type Pos, type PytestFixtureAt } from "@/platform/ipc";
import { useProject } from "@/platform/project";
/** The fixtures at `offset`, once the backend has the editor's text; null when the text changed meanwhile. */
@@ -70,6 +76,32 @@ function completion(doc: EditorDocContext) {
};
}
const NAME = /^[A-Za-z_]\w*$/;
const contains = (l: Location, path: string, pos: Pos) =>
l.path === path &&
(l.range.start.line < pos.line || (l.range.start.line === pos.line && l.range.start.col <= pos.col)) &&
(pos.line < l.range.end.line || (pos.line === l.range.end.line && pos.col <= l.range.end.col));
/** Rename of the fixture at `offset`: from its definition or any place that gets it. */
async function fixtureRename(view: EditorView, offset: number): Promise<ContributedRename | null> {
const doc = docOf(view);
if (!doc || doc.virtual || doc.language !== "python" || !isTauri()) return null;
const text = view.state.doc;
await whenSynced(view);
if (view.state.doc !== text) return null;
const pos = offsetToPos(text, offset);
const found = await call(commands.navPytestFixtureUsages(doc.doc, pos, nextRequestId()));
const here = found && [found.definition, ...found.usages].find((l) => contains(l, doc.path, pos));
if (!found || !here || view.state.doc !== text) return null;
const span = { from: posToOffset(text, here.range.start), to: posToOffset(text, here.range.end) };
const edit = async (newName: string, request: number) => {
if (!NAME.test(newName)) throw new Error(tx`'${newName}' is not a valid fixture name`);
return call(commands.navPytestFixtureRename(doc.doc, pos, newName, request));
};
return found.inProject ? { ...span, edit } : { ...span, edit, refused: "The fixture is defined outside the project" };
}
export function activate(): () => void {
const offNavigation = registerNavigationProvider(async (view, offset) => {
const doc = docOf(view);
@@ -91,8 +123,16 @@ export function activate(): () => void {
? EditorState.languageData.of(() => [{ openideaCompletion: completion(doc) }])
: [],
});
const offUsages = registerUsageProvider(async (query, request) => {
if (!query.path.endsWith(".py") || !isTauri()) return null;
const found = await call(commands.navPytestFixtureUsages(query.doc, query.pos, request));
return found?.usages ?? null;
});
const offRename = registerRenameProvider(fixtureRename);
return () => {
offNavigation();
offCompletion();
offUsages();
offRename();
};
}
+1
Переглянути файл
@@ -277,6 +277,7 @@
"Suggested names": "Suggested names",
"Choose the Statement to Unwrap/Remove": "Choose the Statement to Unwrap/Remove",
"Choose Test for {stem} ({count} found)": "Choose Test for {stem} ({count} found)",
"'{newName}' is not a valid fixture name": "'{newName}' is not a valid fixture name",
"Create Test for {file}": "Create Test for {file}",
"Choose Test Subject for {stem} ({count} found)": "Choose Test Subject for {stem} ({count} found)",
"Code Style": "Code Style",
+2
Переглянути файл
@@ -1673,6 +1673,8 @@
"Create Branch": "创建分支",
"Create New Branch": "创建新分支",
"Create New Test…": "创建新测试…",
"'{newName}' is not a valid fixture name": "“{newName}”不是有效的 fixture 名称",
"The fixture is defined outside the project": "该 fixture 定义在项目之外",
"Create Test…": "创建测试…",
"This is a test file": "这是测试文件",
"Choose Test for {stem} ({count} found)": "选择 {stem} 的测试(找到 {count} 项)",