Compare commits

...
Author SHA1 Message Date
l0ng-ai d6e3d358c6 feat(python): Extract Method, Inline and Introduce Parameter through pylsp-rope
pylsp with pylsp-rope runs next to the Python type checker for refactorings
only: its code actions are kept for the refactor kinds, every other pylsp
capability and plugin is off. Extract Method, Inline (variable, method,
parameter), Introduce Parameter and module-level Introduce Constant now work
in Python files, with rope's "including similar statements" variants as the
all-occurrences choice.

pylsp-rope is a managed tool (pip virtualenv). Being a companion server, it
is not offered for install when missing; the Language Servers page lists it.
rope's .ropeproject folder is in the default ignored names.

Refs #901
2026-11-16 12:39:02 +08:00
16 changed files with 119 additions and 6 deletions

No files matched your search

+3 -1
View File
@@ -14,7 +14,8 @@ pub fn inside_git_repo(dir: &Path) -> bool {
dir.ancestors().any(|d| d.join(".git").exists() || d.join(".jj").exists())
}
/// IDEA's default list, plus `.jj` and the Windows shell files.
/// IDEA's default list, plus `.jj`, rope's `.ropeproject` (pylsp-rope creates it in the
/// project root) and the Windows shell files.
pub const DEFAULT_IGNORED_NAMES: &[&str] = &[
"*.pyc",
"*.pyo",
@@ -25,6 +26,7 @@ pub const DEFAULT_IGNORED_NAMES: &[&str] = &[
".git",
".hg",
".jj",
".ropeproject",
".svn",
"CVS",
"__pycache__",
+15 -2
View File
@@ -679,7 +679,7 @@ mod tests {
let got: Vec<(&str, bool)> = cfg
.language_servers
.iter()
.filter(|s| !s.require_root_marker)
.filter(|s| !s.require_root_marker && s.features.is_empty())
.map(|s| (s.name.as_str(), s.fallback))
.collect();
let expected: Vec<(&str, bool)> = servers.iter().enumerate().map(|(i, name)| (*name, i > 0)).collect();
@@ -779,13 +779,26 @@ mod tests {
assert_eq!(served("lib/src/Parser.php"), None);
}
#[test]
fn pylsp_adds_only_rope_refactorings_to_python() {
let reg = reg();
let cfg = reg.get(&LanguageId::new("python")).unwrap();
let pylsp = cfg.language_servers.iter().find(|s| s.name == "pylsp").unwrap();
assert!(!pylsp.fallback && !pylsp.require_root_marker);
assert_eq!(pylsp.features, ["code-action"]);
assert_eq!(pylsp.code_action_kinds, ["refactor"]);
let plugins = pylsp.initialization_options.as_ref().unwrap()["pylsp"]["plugins"].as_table().unwrap();
assert_eq!(plugins["jedi_completion"]["enabled"].as_bool(), Some(false));
assert!(plugins.values().all(|p| p["enabled"].as_bool() == Some(false)));
}
#[test]
fn ruff_serves_python_files_only_below_its_config() {
let reg = reg();
let cfg = reg.get(&LanguageId::new("python")).unwrap();
let names: Vec<&str> = cfg.language_servers.iter().map(|s| s.name.as_str()).collect();
// After the fallbacks: hover, rename and symbols stay with the type checker.
assert_eq!(names, ["basedpyright", "pyright", "ty", "pyrefly", "ruff"]);
assert_eq!(names, ["basedpyright", "pyright", "ty", "pyrefly", "ruff", "pylsp"]);
let ruff = cfg.language_servers.iter().find(|s| s.name == "ruff").unwrap();
assert_eq!((ruff.command.as_str(), ruff.args.as_slice()), ("ruff", ["server".to_string()].as_slice()));
assert!(ruff.require_root_marker && !ruff.fallback);
+12
View File
@@ -92,6 +92,10 @@ pub struct ToolInfo {
/// The interchangeable servers this one belongs to, in preference order: a
/// server and the `fallback` ones after it. Empty when it has none.
pub alternatives: Vec<String>,
/// A language server used for part of what its languages need (`features` in its
/// definition: pylsp-rope's refactorings next to basedpyright). Not offered for install
/// when missing; the Language Servers page lists it.
pub companion: bool,
}
/// Streamed install progress.
@@ -331,6 +335,7 @@ struct Usage {
args: Vec<String>,
initialization_options: Option<String>,
alternatives: Vec<String>,
companion: bool,
}
fn usages(langs: &[LanguageConfig]) -> BTreeMap<String, Usage> {
@@ -364,6 +369,11 @@ fn usages(langs: &[LanguageConfig]) -> BTreeMap<String, Usage> {
add(name, &d.command, ToolKind::Debugger, d.install_hint.as_ref(), &l.name);
}
}
for s in langs.iter().flat_map(|l| &l.language_servers).filter(|s| !s.features.is_empty()) {
if let Some(u) = map.get_mut(&s.name) {
u.companion = true;
}
}
for (plugin, host) in registry::PLUGIN_HOSTS {
let languages = map.get(*host).map(|u| u.languages.clone()).unwrap_or_default();
map.entry(plugin.to_string()).or_default().languages = languages;
@@ -749,6 +759,7 @@ impl Tools {
default_args: u.args.clone(),
default_initialization_options: u.initialization_options.clone(),
alternatives: u.alternatives.clone(),
companion: u.companion,
})
.map(|info| self.apply_custom(info, None));
};
@@ -775,6 +786,7 @@ impl Tools {
default_args: usage.map(|u| u.args.clone()).unwrap_or_default(),
default_initialization_options: usage.and_then(|u| u.initialization_options.clone()),
alternatives: usage.map(|u| u.alternatives.clone()).unwrap_or_default(),
companion: usage.is_some_and(|u| u.companion),
})
.map(|info| self.apply_custom(info, Some(spec)))
}
+11
View File
@@ -289,6 +289,17 @@ pub static TOOLS: &[ToolSpec] = &[
homepage: "https://docs.astral.sh/ty/",
needs: &[],
},
ToolSpec {
name: "pylsp",
display: "pylsp-rope (Python refactorings)",
kind: LanguageServer,
commands: &["pylsp"],
method: Method::PipVenv { package: "pylsp-rope" },
fallback: None,
version: ver("pylsp"),
homepage: "https://github.com/python-rope/pylsp-rope",
needs: &[],
},
ToolSpec {
name: "pyrefly",
display: "Pyrefly (Python)",
+1
View File
@@ -380,6 +380,7 @@ fn install_joined_after_it_finished_returns_the_result() {
default_args: vec![],
default_initialization_options: None,
alternatives: vec![],
companion: false,
};
release_install_slot("marksman", &slot);
slot.finish(Ok(ok));
+33
View File
@@ -59,6 +59,39 @@ root-markers = ["ruff.toml", ".ruff.toml", "pyproject.toml#tool.ruff"]
require-root-marker = true
install-hint = "pip install ruff (or: uv tool install ruff)"
# Refactorings only (Extract Method / Variable, Inline, Introduce Parameter) from rope,
# next to the type checker: pylsp's own completion, hover, linting and formatting
# stay off, and its other code actions (quick fixes on every line) are dropped.
[[language-servers]]
name = "pylsp"
command = "pylsp"
features = ["code-action"]
code-action-kinds = ["refactor"]
root-markers = ["pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", "Pipfile"]
install-hint = "pip install pylsp-rope (or: uv tool install python-lsp-server --with pylsp-rope)"
[language-servers.initialization-options.pylsp.plugins]
autopep8 = { enabled = false }
flake8 = { enabled = false }
folding = { enabled = false }
jedi_completion = { enabled = false }
jedi_definition = { enabled = false }
jedi_highlight = { enabled = false }
jedi_hover = { enabled = false }
jedi_references = { enabled = false }
jedi_rename = { enabled = false }
jedi_signature_help = { enabled = false }
jedi_symbols = { enabled = false }
mccabe = { enabled = false }
preload = { enabled = false }
pycodestyle = { enabled = false }
pydocstyle = { enabled = false }
pyflakes = { enabled = false }
pylint = { enabled = false }
rope_autoimport = { enabled = false }
rope_completion = { enabled = false }
yapf = { enabled = false }
[debugger]
adapter = "debugpy"
command = "python3"
+6
View File
@@ -10747,6 +10747,12 @@ export type ToolInfo = {
* server and the `fallback` ones after it. Empty when it has none.
*/
alternatives: string[],
/**
* A language server used for part of what its languages need (`features` in its
* definition: pylsp-rope's refactorings next to basedpyright). Not offered for install
* when missing; the Language Servers page lists it.
*/
companion: boolean,
};
export type ToolKind = "languageServer" | "debugger" |
+3
View File
@@ -146,6 +146,9 @@ export function classifyAction(action: Pick<CodeAction, "kind" | "title">): Refa
)
)
return null;
// rope: a module-level method has no IDEA counterpart; a module-level variable is a constant.
if (/\bglobal method\b/i.test(title)) return null;
if (/\bglobal variable\b/i.test(title)) return "extractConstant";
if (is(/function|method/i)) return "extractMethod";
if (is(/field|member|property/i)) return "extractField";
if (is(/parameter|argument/i)) return "extractParameter";
+8
View File
@@ -153,6 +153,14 @@ describe("catalog", () => {
expect(c("Move to a new file", "refactor")).toBe("move");
expect(c("Inline variable", "refactor")).toBe("inline");
expect(c("Convert to template string", "refactor")).toBeNull();
// pylsp-rope (Python).
expect(c("Extract method including similar statements", "refactor.extract")).toBe("extractMethod");
expect(c("Extract global method", "refactor.extract")).toBeNull();
expect(c("Extract variable", "refactor.extract")).toBe("extractVariable");
expect(c("Extract global variable including similar statements", "refactor.extract")).toBe("extractConstant");
expect(c("Inline method/variable/parameter", "refactor.inline")).toBe("inline");
expect(c("Introduce parameter", "refactor")).toBe("extractParameter");
expect(c("To method object", "refactor.rewrite")).toBeNull();
});
it("knows which kinds an advertised list can produce", () => {
@@ -69,6 +69,10 @@ describe("occurrenceVariants", () => {
expect(occurrenceVariants([one, all])).toEqual({ one, all });
expect(occurrenceVariants([one])).toBeNull();
expect(occurrenceVariants([one, action("Extract to field"), all])).toBeNull();
// rope's "similar statements" are the other occurrences.
const rope = action("Extract variable");
const similar = action("Extract variable including similar statements");
expect(occurrenceVariants([similar, rope])).toEqual({ one: rope, all: similar });
});
});
+1 -1
View File
@@ -102,7 +102,7 @@ export async function chooseExpressionFirst(view: EditorView, then: () => unknow
// ---------------------------------------------------------------------------
// Occurrences chooser
const ALL_OCCURRENCES = /\b(all|every) (the )?occurrences?\b|\breplace all\b/i;
const ALL_OCCURRENCES = /\b(all|every) (the )?occurrences?\b|\breplace all\b|\bincluding similar statements\b/i;
/** The single-occurrence / all-occurrences pair among a refactoring's actions, if the server offers both. */
export function occurrenceVariants(actions: readonly CodeAction[]): { one: CodeAction; all: CodeAction } | null {
@@ -128,6 +128,7 @@ function pendingTool(name: string, entry: ServerEntry, languages: string[]): Too
defaultArgs: [],
defaultInitializationOptions: null,
alternatives: [],
companion: false,
};
}
@@ -225,6 +225,7 @@ describe("missing language server prompt", () => {
installMethod: "uv (virtualenv)",
languages: ["Python"],
alternatives: [],
companion: false,
});
await promptInstall("ruff", true, new Set(), true);
expect(notes.at(-1)).toMatchObject({
@@ -234,6 +235,22 @@ describe("missing language server prompt", () => {
});
});
it("doesn't offer a companion server (refactorings only) when it is missing", async () => {
const template = sampleTools()[0]!;
backend.tools.push({
...template,
name: "pylsp",
displayName: "pylsp-rope (Python refactorings)",
command: "pylsp",
status: "missing",
languages: ["Rope Only"],
alternatives: [],
companion: true,
});
expect(await promptInstall("pylsp")).toBe(false);
expect(notes).toEqual([]);
});
it("stays silent when an installed alternative serves the same languages", async () => {
const off = installMissingServerPrompts();
// typescript-language-server (on PATH) covers vtsls' languages.
+1
View File
@@ -72,6 +72,7 @@ function tool(partial: Partial<ToolInfo> & Pick<ToolInfo, "name" | "languages">)
defaultArgs: [],
defaultInitializationOptions: null,
alternatives: [],
companion: false,
...partial,
};
}
+2 -2
View File
@@ -15,7 +15,7 @@ export const missingKey = (name: string) => `lsp-missing-${name}`;
/**
* `offered`: servers already offered for install. A fallback of one of them (pyright
* after basedpyright) stays quiet: installing the first is enough, and the Language
* Servers… page offers the others.
* Servers… page offers the others. So does a companion server (pylsp-rope's refactorings).
*/
export async function promptInstall(
name: string,
@@ -25,7 +25,7 @@ export async function promptInstall(
): Promise<boolean> {
if (!useTools.getState().loaded) await refreshTools();
const tool = toolByName(name);
if (!tool || !tool.canInstall || tool.status !== "missing") return false;
if (!tool || !tool.canInstall || tool.status !== "missing" || tool.companion) return false;
const position = tool.alternatives.indexOf(name);
if (position > 0 && tool.alternatives.slice(0, position).some((n) => offered.has(n))) return false;
formatter ||= tool.kind === "formatter";
+1
View File
@@ -12,6 +12,7 @@ export const DEFAULT_IGNORED_NAMES: readonly string[] = [
".git",
".hg",
".jj",
".ropeproject",
".svn",
"CVS",
"__pycache__",