1use anyhow::{Context as _, ensure};
2use anyhow::{Result, anyhow};
3use async_trait::async_trait;
4use collections::HashMap;
5use futures::AsyncBufReadExt;
6use gpui::{App, Task};
7use gpui::{AsyncApp, SharedString};
8use language::Toolchain;
9use language::ToolchainList;
10use language::ToolchainLister;
11use language::language_settings::language_settings;
12use language::{ContextLocation, LanguageToolchainStore};
13use language::{ContextProvider, LspAdapter, LspAdapterDelegate};
14use language::{LanguageName, ManifestName, ManifestProvider, ManifestQuery};
15use lsp::LanguageServerBinary;
16use lsp::LanguageServerName;
17use node_runtime::{NodeRuntime, VersionStrategy};
18use pet_core::Configuration;
19use pet_core::os_environment::Environment;
20use pet_core::python_environment::PythonEnvironmentKind;
21use project::Fs;
22use project::lsp_store::language_server_settings;
23use serde_json::{Value, json};
24use smol::lock::OnceCell;
25use std::cmp::Ordering;
26
27use parking_lot::Mutex;
28use std::str::FromStr;
29use std::{
30 any::Any,
31 borrow::Cow,
32 ffi::OsString,
33 fmt::Write,
34 path::{Path, PathBuf},
35 sync::Arc,
36};
37use task::{TaskTemplate, TaskTemplates, VariableName};
38use util::ResultExt;
39
40pub(crate) struct PyprojectTomlManifestProvider;
41
42impl ManifestProvider for PyprojectTomlManifestProvider {
43 fn name(&self) -> ManifestName {
44 SharedString::new_static("pyproject.toml").into()
45 }
46
47 fn search(
48 &self,
49 ManifestQuery {
50 path,
51 depth,
52 delegate,
53 }: ManifestQuery,
54 ) -> Option<Arc<Path>> {
55 for path in path.ancestors().take(depth) {
56 let p = path.join("pyproject.toml");
57 if delegate.exists(&p, Some(false)) {
58 return Some(path.into());
59 }
60 }
61
62 None
63 }
64}
65
66const SERVER_PATH: &str = "node_modules/pyright/langserver.index.js";
67const NODE_MODULE_RELATIVE_SERVER_PATH: &str = "pyright/langserver.index.js";
68
69enum TestRunner {
70 UNITTEST,
71 PYTEST,
72}
73
74impl FromStr for TestRunner {
75 type Err = ();
76
77 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
78 match s {
79 "unittest" => Ok(Self::UNITTEST),
80 "pytest" => Ok(Self::PYTEST),
81 _ => Err(()),
82 }
83 }
84}
85
86fn server_binary_arguments(server_path: &Path) -> Vec<OsString> {
87 vec![server_path.into(), "--stdio".into()]
88}
89
90pub struct PythonLspAdapter {
91 node: NodeRuntime,
92}
93
94impl PythonLspAdapter {
95 const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("pyright");
96
97 pub fn new(node: NodeRuntime) -> Self {
98 PythonLspAdapter { node }
99 }
100}
101
102#[async_trait(?Send)]
103impl LspAdapter for PythonLspAdapter {
104 fn name(&self) -> LanguageServerName {
105 Self::SERVER_NAME
106 }
107
108 async fn initialization_options(
109 self: Arc<Self>,
110 _: &dyn Fs,
111 _: &Arc<dyn LspAdapterDelegate>,
112 ) -> Result<Option<Value>> {
113 // Provide minimal initialization options
114 // Virtual environment configuration will be handled through workspace configuration
115 Ok(Some(json!({
116 "python": {
117 "analysis": {
118 "autoSearchPaths": true,
119 "useLibraryCodeForTypes": true,
120 "autoImportCompletions": true
121 }
122 }
123 })))
124 }
125
126 async fn check_if_user_installed(
127 &self,
128 delegate: &dyn LspAdapterDelegate,
129 _: Option<Toolchain>,
130 _: &AsyncApp,
131 ) -> Option<LanguageServerBinary> {
132 if let Some(pyright_bin) = delegate.which("pyright-langserver".as_ref()).await {
133 let env = delegate.shell_env().await;
134 Some(LanguageServerBinary {
135 path: pyright_bin,
136 env: Some(env),
137 arguments: vec!["--stdio".into()],
138 })
139 } else {
140 let node = delegate.which("node".as_ref()).await?;
141 let (node_modules_path, _) = delegate
142 .npm_package_installed_version(Self::SERVER_NAME.as_ref())
143 .await
144 .log_err()??;
145
146 let path = node_modules_path.join(NODE_MODULE_RELATIVE_SERVER_PATH);
147
148 let env = delegate.shell_env().await;
149 Some(LanguageServerBinary {
150 path: node,
151 env: Some(env),
152 arguments: server_binary_arguments(&path),
153 })
154 }
155 }
156
157 async fn fetch_latest_server_version(
158 &self,
159 _: &dyn LspAdapterDelegate,
160 ) -> Result<Box<dyn 'static + Any + Send>> {
161 Ok(Box::new(
162 self.node
163 .npm_package_latest_version(Self::SERVER_NAME.as_ref())
164 .await?,
165 ) as Box<_>)
166 }
167
168 async fn fetch_server_binary(
169 &self,
170 latest_version: Box<dyn 'static + Send + Any>,
171 container_dir: PathBuf,
172 delegate: &dyn LspAdapterDelegate,
173 ) -> Result<LanguageServerBinary> {
174 let latest_version = latest_version.downcast::<String>().unwrap();
175 let server_path = container_dir.join(SERVER_PATH);
176
177 self.node
178 .npm_install_packages(
179 &container_dir,
180 &[(Self::SERVER_NAME.as_ref(), latest_version.as_str())],
181 )
182 .await?;
183
184 let env = delegate.shell_env().await;
185 Ok(LanguageServerBinary {
186 path: self.node.binary_path().await?,
187 env: Some(env),
188 arguments: server_binary_arguments(&server_path),
189 })
190 }
191
192 async fn check_if_version_installed(
193 &self,
194 version: &(dyn 'static + Send + Any),
195 container_dir: &PathBuf,
196 delegate: &dyn LspAdapterDelegate,
197 ) -> Option<LanguageServerBinary> {
198 let version = version.downcast_ref::<String>().unwrap();
199 let server_path = container_dir.join(SERVER_PATH);
200
201 let should_install_language_server = self
202 .node
203 .should_install_npm_package(
204 Self::SERVER_NAME.as_ref(),
205 &server_path,
206 container_dir,
207 VersionStrategy::Latest(version),
208 )
209 .await;
210
211 if should_install_language_server {
212 None
213 } else {
214 let env = delegate.shell_env().await;
215 Some(LanguageServerBinary {
216 path: self.node.binary_path().await.ok()?,
217 env: Some(env),
218 arguments: server_binary_arguments(&server_path),
219 })
220 }
221 }
222
223 async fn cached_server_binary(
224 &self,
225 container_dir: PathBuf,
226 delegate: &dyn LspAdapterDelegate,
227 ) -> Option<LanguageServerBinary> {
228 let mut binary = get_cached_server_binary(container_dir, &self.node).await?;
229 binary.env = Some(delegate.shell_env().await);
230 Some(binary)
231 }
232
233 async fn process_completions(&self, items: &mut [lsp::CompletionItem]) {
234 // Pyright assigns each completion item a `sortText` of the form `XX.YYYY.name`.
235 // Where `XX` is the sorting category, `YYYY` is based on most recent usage,
236 // and `name` is the symbol name itself.
237 //
238 // Because the symbol name is included, there generally are not ties when
239 // sorting by the `sortText`, so the symbol's fuzzy match score is not taken
240 // into account. Here, we remove the symbol name from the sortText in order
241 // to allow our own fuzzy score to be used to break ties.
242 //
243 // see https://github.com/microsoft/pyright/blob/95ef4e103b9b2f129c9320427e51b73ea7cf78bd/packages/pyright-internal/src/languageService/completionProvider.ts#LL2873
244 for item in items {
245 let Some(sort_text) = &mut item.sort_text else {
246 continue;
247 };
248 let mut parts = sort_text.split('.');
249 let Some(first) = parts.next() else { continue };
250 let Some(second) = parts.next() else { continue };
251 let Some(_) = parts.next() else { continue };
252 sort_text.replace_range(first.len() + second.len() + 1.., "");
253 }
254 }
255
256 async fn label_for_completion(
257 &self,
258 item: &lsp::CompletionItem,
259 language: &Arc<language::Language>,
260 ) -> Option<language::CodeLabel> {
261 let label = &item.label;
262 let grammar = language.grammar()?;
263 let highlight_id = match item.kind? {
264 lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method")?,
265 lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function")?,
266 lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type")?,
267 lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant")?,
268 _ => return None,
269 };
270 let filter_range = item
271 .filter_text
272 .as_deref()
273 .and_then(|filter| label.find(filter).map(|ix| ix..ix + filter.len()))
274 .unwrap_or(0..label.len());
275 Some(language::CodeLabel {
276 text: label.clone(),
277 runs: vec![(0..label.len(), highlight_id)],
278 filter_range,
279 })
280 }
281
282 async fn label_for_symbol(
283 &self,
284 name: &str,
285 kind: lsp::SymbolKind,
286 language: &Arc<language::Language>,
287 ) -> Option<language::CodeLabel> {
288 let (text, filter_range, display_range) = match kind {
289 lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
290 let text = format!("def {}():\n", name);
291 let filter_range = 4..4 + name.len();
292 let display_range = 0..filter_range.end;
293 (text, filter_range, display_range)
294 }
295 lsp::SymbolKind::CLASS => {
296 let text = format!("class {}:", name);
297 let filter_range = 6..6 + name.len();
298 let display_range = 0..filter_range.end;
299 (text, filter_range, display_range)
300 }
301 lsp::SymbolKind::CONSTANT => {
302 let text = format!("{} = 0", name);
303 let filter_range = 0..name.len();
304 let display_range = 0..filter_range.end;
305 (text, filter_range, display_range)
306 }
307 _ => return None,
308 };
309
310 Some(language::CodeLabel {
311 runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
312 text: text[display_range].to_string(),
313 filter_range,
314 })
315 }
316
317 async fn workspace_configuration(
318 self: Arc<Self>,
319 _: &dyn Fs,
320 adapter: &Arc<dyn LspAdapterDelegate>,
321 toolchain: Option<Toolchain>,
322 cx: &mut AsyncApp,
323 ) -> Result<Value> {
324 cx.update(move |cx| {
325 let mut user_settings =
326 language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
327 .and_then(|s| s.settings.clone())
328 .unwrap_or_default();
329
330 // If we have a detected toolchain, configure Pyright to use it
331 if let Some(toolchain) = toolchain {
332 if user_settings.is_null() {
333 user_settings = Value::Object(serde_json::Map::default());
334 }
335 let object = user_settings.as_object_mut().unwrap();
336
337 let interpreter_path = toolchain.path.to_string();
338
339 // Detect if this is a virtual environment
340 if let Some(interpreter_dir) = Path::new(&interpreter_path).parent()
341 && let Some(venv_dir) = interpreter_dir.parent()
342 {
343 // Check if this looks like a virtual environment
344 if venv_dir.join("pyvenv.cfg").exists()
345 || venv_dir.join("bin/activate").exists()
346 || venv_dir.join("Scripts/activate.bat").exists()
347 {
348 // Set venvPath and venv at the root level
349 // This matches the format of a pyrightconfig.json file
350 if let Some(parent) = venv_dir.parent() {
351 // Use relative path if the venv is inside the workspace
352 let venv_path = if parent == adapter.worktree_root_path() {
353 ".".to_string()
354 } else {
355 parent.to_string_lossy().into_owned()
356 };
357 object.insert("venvPath".to_string(), Value::String(venv_path));
358 }
359
360 if let Some(venv_name) = venv_dir.file_name() {
361 object.insert(
362 "venv".to_owned(),
363 Value::String(venv_name.to_string_lossy().into_owned()),
364 );
365 }
366 }
367 }
368
369 // Always set the python interpreter path
370 // Get or create the python section
371 let python = object
372 .entry("python")
373 .or_insert(Value::Object(serde_json::Map::default()))
374 .as_object_mut()
375 .unwrap();
376
377 // Set both pythonPath and defaultInterpreterPath for compatibility
378 python.insert(
379 "pythonPath".to_owned(),
380 Value::String(interpreter_path.clone()),
381 );
382 python.insert(
383 "defaultInterpreterPath".to_owned(),
384 Value::String(interpreter_path),
385 );
386 }
387
388 user_settings
389 })
390 }
391}
392
393async fn get_cached_server_binary(
394 container_dir: PathBuf,
395 node: &NodeRuntime,
396) -> Option<LanguageServerBinary> {
397 let server_path = container_dir.join(SERVER_PATH);
398 if server_path.exists() {
399 Some(LanguageServerBinary {
400 path: node.binary_path().await.log_err()?,
401 env: None,
402 arguments: server_binary_arguments(&server_path),
403 })
404 } else {
405 log::error!("missing executable in directory {:?}", server_path);
406 None
407 }
408}
409
410pub(crate) struct PythonContextProvider;
411
412const PYTHON_TEST_TARGET_TASK_VARIABLE: VariableName =
413 VariableName::Custom(Cow::Borrowed("PYTHON_TEST_TARGET"));
414
415const PYTHON_ACTIVE_TOOLCHAIN_PATH: VariableName =
416 VariableName::Custom(Cow::Borrowed("PYTHON_ACTIVE_ZED_TOOLCHAIN"));
417
418const PYTHON_ACTIVE_TOOLCHAIN_PATH_RAW: VariableName =
419 VariableName::Custom(Cow::Borrowed("PYTHON_ACTIVE_ZED_TOOLCHAIN_RAW"));
420
421const PYTHON_MODULE_NAME_TASK_VARIABLE: VariableName =
422 VariableName::Custom(Cow::Borrowed("PYTHON_MODULE_NAME"));
423
424impl ContextProvider for PythonContextProvider {
425 fn build_context(
426 &self,
427 variables: &task::TaskVariables,
428 location: ContextLocation<'_>,
429 _: Option<HashMap<String, String>>,
430 toolchains: Arc<dyn LanguageToolchainStore>,
431 cx: &mut gpui::App,
432 ) -> Task<Result<task::TaskVariables>> {
433 let test_target =
434 match selected_test_runner(location.file_location.buffer.read(cx).file(), cx) {
435 TestRunner::UNITTEST => self.build_unittest_target(variables),
436 TestRunner::PYTEST => self.build_pytest_target(variables),
437 };
438
439 let module_target = self.build_module_target(variables);
440 let location_file = location.file_location.buffer.read(cx).file().cloned();
441 let worktree_id = location_file.as_ref().map(|f| f.worktree_id(cx));
442
443 cx.spawn(async move |cx| {
444 let raw_toolchain = if let Some(worktree_id) = worktree_id {
445 let file_path = location_file
446 .as_ref()
447 .and_then(|f| f.path().parent())
448 .map(Arc::from)
449 .unwrap_or_else(|| Arc::from("".as_ref()));
450
451 toolchains
452 .active_toolchain(worktree_id, file_path, "Python".into(), cx)
453 .await
454 .map_or_else(
455 || String::from("python3"),
456 |toolchain| toolchain.path.to_string(),
457 )
458 } else {
459 String::from("python3")
460 };
461
462 let active_toolchain = format!("\"{raw_toolchain}\"");
463 let toolchain = (PYTHON_ACTIVE_TOOLCHAIN_PATH, active_toolchain);
464 let raw_toolchain_var = (PYTHON_ACTIVE_TOOLCHAIN_PATH_RAW, raw_toolchain);
465
466 Ok(task::TaskVariables::from_iter(
467 test_target
468 .into_iter()
469 .chain(module_target.into_iter())
470 .chain([toolchain, raw_toolchain_var]),
471 ))
472 })
473 }
474
475 fn associated_tasks(
476 &self,
477 _: Arc<dyn Fs>,
478 file: Option<Arc<dyn language::File>>,
479 cx: &App,
480 ) -> Task<Option<TaskTemplates>> {
481 let test_runner = selected_test_runner(file.as_ref(), cx);
482
483 let mut tasks = vec![
484 // Execute a selection
485 TaskTemplate {
486 label: "execute selection".to_owned(),
487 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
488 args: vec![
489 "-c".to_owned(),
490 VariableName::SelectedText.template_value_with_whitespace(),
491 ],
492 cwd: Some("$ZED_WORKTREE_ROOT".into()),
493 ..TaskTemplate::default()
494 },
495 // Execute an entire file
496 TaskTemplate {
497 label: format!("run '{}'", VariableName::File.template_value()),
498 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
499 args: vec![VariableName::File.template_value_with_whitespace()],
500 cwd: Some("$ZED_WORKTREE_ROOT".into()),
501 ..TaskTemplate::default()
502 },
503 // Execute a file as module
504 TaskTemplate {
505 label: format!("run module '{}'", VariableName::File.template_value()),
506 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
507 args: vec![
508 "-m".to_owned(),
509 PYTHON_MODULE_NAME_TASK_VARIABLE.template_value(),
510 ],
511 cwd: Some("$ZED_WORKTREE_ROOT".into()),
512 tags: vec!["python-module-main-method".to_owned()],
513 ..TaskTemplate::default()
514 },
515 ];
516
517 tasks.extend(match test_runner {
518 TestRunner::UNITTEST => {
519 [
520 // Run tests for an entire file
521 TaskTemplate {
522 label: format!("unittest '{}'", VariableName::File.template_value()),
523 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
524 args: vec![
525 "-m".to_owned(),
526 "unittest".to_owned(),
527 VariableName::File.template_value_with_whitespace(),
528 ],
529 cwd: Some("$ZED_WORKTREE_ROOT".into()),
530 ..TaskTemplate::default()
531 },
532 // Run test(s) for a specific target within a file
533 TaskTemplate {
534 label: "unittest $ZED_CUSTOM_PYTHON_TEST_TARGET".to_owned(),
535 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
536 args: vec![
537 "-m".to_owned(),
538 "unittest".to_owned(),
539 PYTHON_TEST_TARGET_TASK_VARIABLE.template_value_with_whitespace(),
540 ],
541 tags: vec![
542 "python-unittest-class".to_owned(),
543 "python-unittest-method".to_owned(),
544 ],
545 cwd: Some("$ZED_WORKTREE_ROOT".into()),
546 ..TaskTemplate::default()
547 },
548 ]
549 }
550 TestRunner::PYTEST => {
551 [
552 // Run tests for an entire file
553 TaskTemplate {
554 label: format!("pytest '{}'", VariableName::File.template_value()),
555 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
556 args: vec![
557 "-m".to_owned(),
558 "pytest".to_owned(),
559 VariableName::File.template_value_with_whitespace(),
560 ],
561 cwd: Some("$ZED_WORKTREE_ROOT".into()),
562 ..TaskTemplate::default()
563 },
564 // Run test(s) for a specific target within a file
565 TaskTemplate {
566 label: "pytest $ZED_CUSTOM_PYTHON_TEST_TARGET".to_owned(),
567 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
568 args: vec![
569 "-m".to_owned(),
570 "pytest".to_owned(),
571 PYTHON_TEST_TARGET_TASK_VARIABLE.template_value_with_whitespace(),
572 ],
573 cwd: Some("$ZED_WORKTREE_ROOT".into()),
574 tags: vec![
575 "python-pytest-class".to_owned(),
576 "python-pytest-method".to_owned(),
577 ],
578 ..TaskTemplate::default()
579 },
580 ]
581 }
582 });
583
584 Task::ready(Some(TaskTemplates(tasks)))
585 }
586}
587
588fn selected_test_runner(location: Option<&Arc<dyn language::File>>, cx: &App) -> TestRunner {
589 const TEST_RUNNER_VARIABLE: &str = "TEST_RUNNER";
590 language_settings(Some(LanguageName::new("Python")), location, cx)
591 .tasks
592 .variables
593 .get(TEST_RUNNER_VARIABLE)
594 .and_then(|val| TestRunner::from_str(val).ok())
595 .unwrap_or(TestRunner::PYTEST)
596}
597
598impl PythonContextProvider {
599 fn build_unittest_target(
600 &self,
601 variables: &task::TaskVariables,
602 ) -> Option<(VariableName, String)> {
603 let python_module_name =
604 python_module_name_from_relative_path(variables.get(&VariableName::RelativeFile)?);
605
606 let unittest_class_name =
607 variables.get(&VariableName::Custom(Cow::Borrowed("_unittest_class_name")));
608
609 let unittest_method_name = variables.get(&VariableName::Custom(Cow::Borrowed(
610 "_unittest_method_name",
611 )));
612
613 let unittest_target_str = match (unittest_class_name, unittest_method_name) {
614 (Some(class_name), Some(method_name)) => {
615 format!("{python_module_name}.{class_name}.{method_name}")
616 }
617 (Some(class_name), None) => format!("{python_module_name}.{class_name}"),
618 (None, None) => python_module_name,
619 // should never happen, a TestCase class is the unit of testing
620 (None, Some(_)) => return None,
621 };
622
623 Some((
624 PYTHON_TEST_TARGET_TASK_VARIABLE.clone(),
625 unittest_target_str,
626 ))
627 }
628
629 fn build_pytest_target(
630 &self,
631 variables: &task::TaskVariables,
632 ) -> Option<(VariableName, String)> {
633 let file_path = variables.get(&VariableName::RelativeFile)?;
634
635 let pytest_class_name =
636 variables.get(&VariableName::Custom(Cow::Borrowed("_pytest_class_name")));
637
638 let pytest_method_name =
639 variables.get(&VariableName::Custom(Cow::Borrowed("_pytest_method_name")));
640
641 let pytest_target_str = match (pytest_class_name, pytest_method_name) {
642 (Some(class_name), Some(method_name)) => {
643 format!("{file_path}::{class_name}::{method_name}")
644 }
645 (Some(class_name), None) => {
646 format!("{file_path}::{class_name}")
647 }
648 (None, Some(method_name)) => {
649 format!("{file_path}::{method_name}")
650 }
651 (None, None) => file_path.to_string(),
652 };
653
654 Some((PYTHON_TEST_TARGET_TASK_VARIABLE.clone(), pytest_target_str))
655 }
656
657 fn build_module_target(
658 &self,
659 variables: &task::TaskVariables,
660 ) -> Result<(VariableName, String)> {
661 let python_module_name = python_module_name_from_relative_path(
662 variables.get(&VariableName::RelativeFile).unwrap_or(""),
663 );
664
665 let module_target = (PYTHON_MODULE_NAME_TASK_VARIABLE.clone(), python_module_name);
666
667 Ok(module_target)
668 }
669}
670
671fn python_module_name_from_relative_path(relative_path: &str) -> String {
672 let path_with_dots = relative_path.replace('/', ".");
673 path_with_dots
674 .strip_suffix(".py")
675 .unwrap_or(&path_with_dots)
676 .to_string()
677}
678
679fn python_env_kind_display(k: &PythonEnvironmentKind) -> &'static str {
680 match k {
681 PythonEnvironmentKind::Conda => "Conda",
682 PythonEnvironmentKind::Pixi => "pixi",
683 PythonEnvironmentKind::Homebrew => "Homebrew",
684 PythonEnvironmentKind::Pyenv => "global (Pyenv)",
685 PythonEnvironmentKind::GlobalPaths => "global",
686 PythonEnvironmentKind::PyenvVirtualEnv => "Pyenv",
687 PythonEnvironmentKind::Pipenv => "Pipenv",
688 PythonEnvironmentKind::Poetry => "Poetry",
689 PythonEnvironmentKind::MacPythonOrg => "global (Python.org)",
690 PythonEnvironmentKind::MacCommandLineTools => "global (Command Line Tools for Xcode)",
691 PythonEnvironmentKind::LinuxGlobal => "global",
692 PythonEnvironmentKind::MacXCode => "global (Xcode)",
693 PythonEnvironmentKind::Venv => "venv",
694 PythonEnvironmentKind::VirtualEnv => "virtualenv",
695 PythonEnvironmentKind::VirtualEnvWrapper => "virtualenvwrapper",
696 PythonEnvironmentKind::WindowsStore => "global (Windows Store)",
697 PythonEnvironmentKind::WindowsRegistry => "global (Windows Registry)",
698 }
699}
700
701pub(crate) struct PythonToolchainProvider {
702 term: SharedString,
703}
704
705impl Default for PythonToolchainProvider {
706 fn default() -> Self {
707 Self {
708 term: SharedString::new_static("Virtual Environment"),
709 }
710 }
711}
712
713static ENV_PRIORITY_LIST: &[PythonEnvironmentKind] = &[
714 // Prioritize non-Conda environments.
715 PythonEnvironmentKind::Poetry,
716 PythonEnvironmentKind::Pipenv,
717 PythonEnvironmentKind::VirtualEnvWrapper,
718 PythonEnvironmentKind::Venv,
719 PythonEnvironmentKind::VirtualEnv,
720 PythonEnvironmentKind::PyenvVirtualEnv,
721 PythonEnvironmentKind::Pixi,
722 PythonEnvironmentKind::Conda,
723 PythonEnvironmentKind::Pyenv,
724 PythonEnvironmentKind::GlobalPaths,
725 PythonEnvironmentKind::Homebrew,
726];
727
728fn env_priority(kind: Option<PythonEnvironmentKind>) -> usize {
729 if let Some(kind) = kind {
730 ENV_PRIORITY_LIST
731 .iter()
732 .position(|blessed_env| blessed_env == &kind)
733 .unwrap_or(ENV_PRIORITY_LIST.len())
734 } else {
735 // Unknown toolchains are less useful than non-blessed ones.
736 ENV_PRIORITY_LIST.len() + 1
737 }
738}
739
740/// Return the name of environment declared in <worktree-root/.venv.
741///
742/// https://virtualfish.readthedocs.io/en/latest/plugins.html#auto-activation-auto-activation
743async fn get_worktree_venv_declaration(worktree_root: &Path) -> Option<String> {
744 let file = async_fs::File::open(worktree_root.join(".venv"))
745 .await
746 .ok()?;
747 let mut venv_name = String::new();
748 smol::io::BufReader::new(file)
749 .read_line(&mut venv_name)
750 .await
751 .ok()?;
752 Some(venv_name.trim().to_string())
753}
754
755#[async_trait]
756impl ToolchainLister for PythonToolchainProvider {
757 fn manifest_name(&self) -> language::ManifestName {
758 ManifestName::from(SharedString::new_static("pyproject.toml"))
759 }
760 async fn list(
761 &self,
762 worktree_root: PathBuf,
763 subroot_relative_path: Arc<Path>,
764 project_env: Option<HashMap<String, String>>,
765 ) -> ToolchainList {
766 let env = project_env.unwrap_or_default();
767 let environment = EnvironmentApi::from_env(&env);
768 let locators = pet::locators::create_locators(
769 Arc::new(pet_conda::Conda::from(&environment)),
770 Arc::new(pet_poetry::Poetry::from(&environment)),
771 &environment,
772 );
773 let mut config = Configuration::default();
774
775 debug_assert!(subroot_relative_path.is_relative());
776 // `.ancestors()` will yield at least one path, so in case of empty `subroot_relative_path`, we'll just use
777 // worktree root as the workspace directory.
778 config.workspace_directories = Some(
779 subroot_relative_path
780 .ancestors()
781 .map(|ancestor| worktree_root.join(ancestor))
782 .collect(),
783 );
784 for locator in locators.iter() {
785 locator.configure(&config);
786 }
787
788 let reporter = pet_reporter::collect::create_reporter();
789 pet::find::find_and_report_envs(&reporter, config, &locators, &environment, None);
790
791 let mut toolchains = reporter
792 .environments
793 .lock()
794 .map_or(Vec::new(), |mut guard| std::mem::take(&mut guard));
795
796 let wr = worktree_root;
797 let wr_venv = get_worktree_venv_declaration(&wr).await;
798 // Sort detected environments by:
799 // environment name matching activation file (<workdir>/.venv)
800 // environment project dir matching worktree_root
801 // general env priority
802 // environment path matching the CONDA_PREFIX env var
803 // executable path
804 toolchains.sort_by(|lhs, rhs| {
805 // Compare venv names against worktree .venv file
806 let venv_ordering =
807 wr_venv
808 .as_ref()
809 .map_or(Ordering::Equal, |venv| match (&lhs.name, &rhs.name) {
810 (Some(l), Some(r)) => (r == venv).cmp(&(l == venv)),
811 (Some(l), None) if l == venv => Ordering::Less,
812 (None, Some(r)) if r == venv => Ordering::Greater,
813 _ => Ordering::Equal,
814 });
815
816 // Compare project paths against worktree root
817 let proj_ordering = || match (&lhs.project, &rhs.project) {
818 (Some(l), Some(r)) => (r == &wr).cmp(&(l == &wr)),
819 (Some(l), None) if l == &wr => Ordering::Less,
820 (None, Some(r)) if r == &wr => Ordering::Greater,
821 _ => Ordering::Equal,
822 };
823
824 // Compare environment priorities
825 let priority_ordering = || env_priority(lhs.kind).cmp(&env_priority(rhs.kind));
826
827 // Compare conda prefixes
828 let conda_ordering = || {
829 if lhs.kind == Some(PythonEnvironmentKind::Conda) {
830 environment
831 .get_env_var("CONDA_PREFIX".to_string())
832 .map(|conda_prefix| {
833 let is_match = |exe: &Option<PathBuf>| {
834 exe.as_ref().is_some_and(|e| e.starts_with(&conda_prefix))
835 };
836 match (is_match(&lhs.executable), is_match(&rhs.executable)) {
837 (true, false) => Ordering::Less,
838 (false, true) => Ordering::Greater,
839 _ => Ordering::Equal,
840 }
841 })
842 .unwrap_or(Ordering::Equal)
843 } else {
844 Ordering::Equal
845 }
846 };
847
848 // Compare Python executables
849 let exe_ordering = || lhs.executable.cmp(&rhs.executable);
850
851 venv_ordering
852 .then_with(proj_ordering)
853 .then_with(priority_ordering)
854 .then_with(conda_ordering)
855 .then_with(exe_ordering)
856 });
857
858 let mut toolchains: Vec<_> = toolchains
859 .into_iter()
860 .filter_map(|toolchain| {
861 let mut name = String::from("Python");
862 if let Some(version) = &toolchain.version {
863 _ = write!(name, " {version}");
864 }
865
866 let name_and_kind = match (&toolchain.name, &toolchain.kind) {
867 (Some(name), Some(kind)) => {
868 Some(format!("({name}; {})", python_env_kind_display(kind)))
869 }
870 (Some(name), None) => Some(format!("({name})")),
871 (None, Some(kind)) => Some(format!("({})", python_env_kind_display(kind))),
872 (None, None) => None,
873 };
874
875 if let Some(nk) = name_and_kind {
876 _ = write!(name, " {nk}");
877 }
878
879 Some(Toolchain {
880 name: name.into(),
881 path: toolchain.executable.as_ref()?.to_str()?.to_owned().into(),
882 language_name: LanguageName::new("Python"),
883 as_json: serde_json::to_value(toolchain.clone()).ok()?,
884 })
885 })
886 .collect();
887 toolchains.dedup();
888 ToolchainList {
889 toolchains,
890 default: None,
891 groups: Default::default(),
892 }
893 }
894 fn term(&self) -> SharedString {
895 self.term.clone()
896 }
897 async fn activation_script(&self, toolchain: &Toolchain, fs: &dyn Fs) -> Option<String> {
898 let toolchain = serde_json::from_value::<pet_core::python_environment::PythonEnvironment>(
899 toolchain.as_json.clone(),
900 )
901 .ok()?;
902 let mut activation_script = None;
903 if let Some(prefix) = &toolchain.prefix {
904 #[cfg(not(target_os = "windows"))]
905 let path = prefix.join(BINARY_DIR).join("activate");
906 #[cfg(target_os = "windows")]
907 let path = prefix.join(BINARY_DIR).join("activate.ps1");
908 if fs.is_file(&path).await {
909 activation_script = Some(format!(". {}", path.display()));
910 }
911 }
912 activation_script
913 }
914}
915
916pub struct EnvironmentApi<'a> {
917 global_search_locations: Arc<Mutex<Vec<PathBuf>>>,
918 project_env: &'a HashMap<String, String>,
919 pet_env: pet_core::os_environment::EnvironmentApi,
920}
921
922impl<'a> EnvironmentApi<'a> {
923 pub fn from_env(project_env: &'a HashMap<String, String>) -> Self {
924 let paths = project_env
925 .get("PATH")
926 .map(|p| std::env::split_paths(p).collect())
927 .unwrap_or_default();
928
929 EnvironmentApi {
930 global_search_locations: Arc::new(Mutex::new(paths)),
931 project_env,
932 pet_env: pet_core::os_environment::EnvironmentApi::new(),
933 }
934 }
935
936 fn user_home(&self) -> Option<PathBuf> {
937 self.project_env
938 .get("HOME")
939 .or_else(|| self.project_env.get("USERPROFILE"))
940 .map(|home| pet_fs::path::norm_case(PathBuf::from(home)))
941 .or_else(|| self.pet_env.get_user_home())
942 }
943}
944
945impl pet_core::os_environment::Environment for EnvironmentApi<'_> {
946 fn get_user_home(&self) -> Option<PathBuf> {
947 self.user_home()
948 }
949
950 fn get_root(&self) -> Option<PathBuf> {
951 None
952 }
953
954 fn get_env_var(&self, key: String) -> Option<String> {
955 self.project_env
956 .get(&key)
957 .cloned()
958 .or_else(|| self.pet_env.get_env_var(key))
959 }
960
961 fn get_know_global_search_locations(&self) -> Vec<PathBuf> {
962 if self.global_search_locations.lock().is_empty() {
963 let mut paths =
964 std::env::split_paths(&self.get_env_var("PATH".to_string()).unwrap_or_default())
965 .collect::<Vec<PathBuf>>();
966
967 log::trace!("Env PATH: {:?}", paths);
968 for p in self.pet_env.get_know_global_search_locations() {
969 if !paths.contains(&p) {
970 paths.push(p);
971 }
972 }
973
974 let mut paths = paths
975 .into_iter()
976 .filter(|p| p.exists())
977 .collect::<Vec<PathBuf>>();
978
979 self.global_search_locations.lock().append(&mut paths);
980 }
981 self.global_search_locations.lock().clone()
982 }
983}
984
985pub(crate) struct PyLspAdapter {
986 python_venv_base: OnceCell<Result<Arc<Path>, String>>,
987}
988impl PyLspAdapter {
989 const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("pylsp");
990 pub(crate) fn new() -> Self {
991 Self {
992 python_venv_base: OnceCell::new(),
993 }
994 }
995 async fn ensure_venv(delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>> {
996 let python_path = Self::find_base_python(delegate)
997 .await
998 .context("Could not find Python installation for PyLSP")?;
999 let work_dir = delegate
1000 .language_server_download_dir(&Self::SERVER_NAME)
1001 .await
1002 .context("Could not get working directory for PyLSP")?;
1003 let mut path = PathBuf::from(work_dir.as_ref());
1004 path.push("pylsp-venv");
1005 if !path.exists() {
1006 util::command::new_smol_command(python_path)
1007 .arg("-m")
1008 .arg("venv")
1009 .arg("pylsp-venv")
1010 .current_dir(work_dir)
1011 .spawn()?
1012 .output()
1013 .await?;
1014 }
1015
1016 Ok(path.into())
1017 }
1018 // Find "baseline", user python version from which we'll create our own venv.
1019 async fn find_base_python(delegate: &dyn LspAdapterDelegate) -> Option<PathBuf> {
1020 for path in ["python3", "python"] {
1021 if let Some(path) = delegate.which(path.as_ref()).await {
1022 return Some(path);
1023 }
1024 }
1025 None
1026 }
1027
1028 async fn base_venv(&self, delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>, String> {
1029 self.python_venv_base
1030 .get_or_init(move || async move {
1031 Self::ensure_venv(delegate)
1032 .await
1033 .map_err(|e| format!("{e}"))
1034 })
1035 .await
1036 .clone()
1037 }
1038}
1039
1040const BINARY_DIR: &str = if cfg!(target_os = "windows") {
1041 "Scripts"
1042} else {
1043 "bin"
1044};
1045
1046#[async_trait(?Send)]
1047impl LspAdapter for PyLspAdapter {
1048 fn name(&self) -> LanguageServerName {
1049 Self::SERVER_NAME
1050 }
1051
1052 async fn check_if_user_installed(
1053 &self,
1054 delegate: &dyn LspAdapterDelegate,
1055 toolchain: Option<Toolchain>,
1056 _: &AsyncApp,
1057 ) -> Option<LanguageServerBinary> {
1058 if let Some(pylsp_bin) = delegate.which(Self::SERVER_NAME.as_ref()).await {
1059 let env = delegate.shell_env().await;
1060 Some(LanguageServerBinary {
1061 path: pylsp_bin,
1062 env: Some(env),
1063 arguments: vec![],
1064 })
1065 } else {
1066 let venv = toolchain?;
1067 let pylsp_path = Path::new(venv.path.as_ref()).parent()?.join("pylsp");
1068 pylsp_path.exists().then(|| LanguageServerBinary {
1069 path: venv.path.to_string().into(),
1070 arguments: vec![pylsp_path.into()],
1071 env: None,
1072 })
1073 }
1074 }
1075
1076 async fn fetch_latest_server_version(
1077 &self,
1078 _: &dyn LspAdapterDelegate,
1079 ) -> Result<Box<dyn 'static + Any + Send>> {
1080 Ok(Box::new(()) as Box<_>)
1081 }
1082
1083 async fn fetch_server_binary(
1084 &self,
1085 _: Box<dyn 'static + Send + Any>,
1086 _: PathBuf,
1087 delegate: &dyn LspAdapterDelegate,
1088 ) -> Result<LanguageServerBinary> {
1089 let venv = self.base_venv(delegate).await.map_err(|e| anyhow!(e))?;
1090 let pip_path = venv.join(BINARY_DIR).join("pip3");
1091 ensure!(
1092 util::command::new_smol_command(pip_path.as_path())
1093 .arg("install")
1094 .arg("python-lsp-server")
1095 .arg("-U")
1096 .output()
1097 .await?
1098 .status
1099 .success(),
1100 "python-lsp-server installation failed"
1101 );
1102 ensure!(
1103 util::command::new_smol_command(pip_path.as_path())
1104 .arg("install")
1105 .arg("python-lsp-server[all]")
1106 .arg("-U")
1107 .output()
1108 .await?
1109 .status
1110 .success(),
1111 "python-lsp-server[all] installation failed"
1112 );
1113 ensure!(
1114 util::command::new_smol_command(pip_path)
1115 .arg("install")
1116 .arg("pylsp-mypy")
1117 .arg("-U")
1118 .output()
1119 .await?
1120 .status
1121 .success(),
1122 "pylsp-mypy installation failed"
1123 );
1124 let pylsp = venv.join(BINARY_DIR).join("pylsp");
1125 Ok(LanguageServerBinary {
1126 path: pylsp,
1127 env: None,
1128 arguments: vec![],
1129 })
1130 }
1131
1132 async fn cached_server_binary(
1133 &self,
1134 _: PathBuf,
1135 delegate: &dyn LspAdapterDelegate,
1136 ) -> Option<LanguageServerBinary> {
1137 let venv = self.base_venv(delegate).await.ok()?;
1138 let pylsp = venv.join(BINARY_DIR).join("pylsp");
1139 Some(LanguageServerBinary {
1140 path: pylsp,
1141 env: None,
1142 arguments: vec![],
1143 })
1144 }
1145
1146 async fn process_completions(&self, _items: &mut [lsp::CompletionItem]) {}
1147
1148 async fn label_for_completion(
1149 &self,
1150 item: &lsp::CompletionItem,
1151 language: &Arc<language::Language>,
1152 ) -> Option<language::CodeLabel> {
1153 let label = &item.label;
1154 let grammar = language.grammar()?;
1155 let highlight_id = match item.kind? {
1156 lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method")?,
1157 lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function")?,
1158 lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type")?,
1159 lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant")?,
1160 _ => return None,
1161 };
1162 let filter_range = item
1163 .filter_text
1164 .as_deref()
1165 .and_then(|filter| label.find(filter).map(|ix| ix..ix + filter.len()))
1166 .unwrap_or(0..label.len());
1167 Some(language::CodeLabel {
1168 text: label.clone(),
1169 runs: vec![(0..label.len(), highlight_id)],
1170 filter_range,
1171 })
1172 }
1173
1174 async fn label_for_symbol(
1175 &self,
1176 name: &str,
1177 kind: lsp::SymbolKind,
1178 language: &Arc<language::Language>,
1179 ) -> Option<language::CodeLabel> {
1180 let (text, filter_range, display_range) = match kind {
1181 lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
1182 let text = format!("def {}():\n", name);
1183 let filter_range = 4..4 + name.len();
1184 let display_range = 0..filter_range.end;
1185 (text, filter_range, display_range)
1186 }
1187 lsp::SymbolKind::CLASS => {
1188 let text = format!("class {}:", name);
1189 let filter_range = 6..6 + name.len();
1190 let display_range = 0..filter_range.end;
1191 (text, filter_range, display_range)
1192 }
1193 lsp::SymbolKind::CONSTANT => {
1194 let text = format!("{} = 0", name);
1195 let filter_range = 0..name.len();
1196 let display_range = 0..filter_range.end;
1197 (text, filter_range, display_range)
1198 }
1199 _ => return None,
1200 };
1201
1202 Some(language::CodeLabel {
1203 runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
1204 text: text[display_range].to_string(),
1205 filter_range,
1206 })
1207 }
1208
1209 async fn workspace_configuration(
1210 self: Arc<Self>,
1211 _: &dyn Fs,
1212 adapter: &Arc<dyn LspAdapterDelegate>,
1213 toolchain: Option<Toolchain>,
1214 cx: &mut AsyncApp,
1215 ) -> Result<Value> {
1216 cx.update(move |cx| {
1217 let mut user_settings =
1218 language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
1219 .and_then(|s| s.settings.clone())
1220 .unwrap_or_else(|| {
1221 json!({
1222 "plugins": {
1223 "pycodestyle": {"enabled": false},
1224 "rope_autoimport": {"enabled": true, "memory": true},
1225 "pylsp_mypy": {"enabled": false}
1226 },
1227 "rope": {
1228 "ropeFolder": null
1229 },
1230 })
1231 });
1232
1233 // If user did not explicitly modify their python venv, use one from picker.
1234 if let Some(toolchain) = toolchain {
1235 if user_settings.is_null() {
1236 user_settings = Value::Object(serde_json::Map::default());
1237 }
1238 let object = user_settings.as_object_mut().unwrap();
1239 if let Some(python) = object
1240 .entry("plugins")
1241 .or_insert(Value::Object(serde_json::Map::default()))
1242 .as_object_mut()
1243 {
1244 if let Some(jedi) = python
1245 .entry("jedi")
1246 .or_insert(Value::Object(serde_json::Map::default()))
1247 .as_object_mut()
1248 {
1249 jedi.entry("environment".to_string())
1250 .or_insert_with(|| Value::String(toolchain.path.clone().into()));
1251 }
1252 if let Some(pylint) = python
1253 .entry("pylsp_mypy")
1254 .or_insert(Value::Object(serde_json::Map::default()))
1255 .as_object_mut()
1256 {
1257 pylint.entry("overrides".to_string()).or_insert_with(|| {
1258 Value::Array(vec![
1259 Value::String("--python-executable".into()),
1260 Value::String(toolchain.path.into()),
1261 Value::String("--cache-dir=/dev/null".into()),
1262 Value::Bool(true),
1263 ])
1264 });
1265 }
1266 }
1267 }
1268 user_settings = Value::Object(serde_json::Map::from_iter([(
1269 "pylsp".to_string(),
1270 user_settings,
1271 )]));
1272
1273 user_settings
1274 })
1275 }
1276}
1277
1278pub(crate) struct BasedPyrightLspAdapter {
1279 python_venv_base: OnceCell<Result<Arc<Path>, String>>,
1280}
1281
1282impl BasedPyrightLspAdapter {
1283 const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("basedpyright");
1284 const BINARY_NAME: &'static str = "basedpyright-langserver";
1285
1286 pub(crate) fn new() -> Self {
1287 Self {
1288 python_venv_base: OnceCell::new(),
1289 }
1290 }
1291
1292 async fn ensure_venv(delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>> {
1293 let python_path = Self::find_base_python(delegate)
1294 .await
1295 .context("Could not find Python installation for basedpyright")?;
1296 let work_dir = delegate
1297 .language_server_download_dir(&Self::SERVER_NAME)
1298 .await
1299 .context("Could not get working directory for basedpyright")?;
1300 let mut path = PathBuf::from(work_dir.as_ref());
1301 path.push("basedpyright-venv");
1302 if !path.exists() {
1303 util::command::new_smol_command(python_path)
1304 .arg("-m")
1305 .arg("venv")
1306 .arg("basedpyright-venv")
1307 .current_dir(work_dir)
1308 .spawn()?
1309 .output()
1310 .await?;
1311 }
1312
1313 Ok(path.into())
1314 }
1315
1316 // Find "baseline", user python version from which we'll create our own venv.
1317 async fn find_base_python(delegate: &dyn LspAdapterDelegate) -> Option<PathBuf> {
1318 for path in ["python3", "python"] {
1319 if let Some(path) = delegate.which(path.as_ref()).await {
1320 return Some(path);
1321 }
1322 }
1323 None
1324 }
1325
1326 async fn base_venv(&self, delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>, String> {
1327 self.python_venv_base
1328 .get_or_init(move || async move {
1329 Self::ensure_venv(delegate)
1330 .await
1331 .map_err(|e| format!("{e}"))
1332 })
1333 .await
1334 .clone()
1335 }
1336}
1337
1338#[async_trait(?Send)]
1339impl LspAdapter for BasedPyrightLspAdapter {
1340 fn name(&self) -> LanguageServerName {
1341 Self::SERVER_NAME
1342 }
1343
1344 async fn initialization_options(
1345 self: Arc<Self>,
1346 _: &dyn Fs,
1347 _: &Arc<dyn LspAdapterDelegate>,
1348 ) -> Result<Option<Value>> {
1349 // Provide minimal initialization options
1350 // Virtual environment configuration will be handled through workspace configuration
1351 Ok(Some(json!({
1352 "python": {
1353 "analysis": {
1354 "autoSearchPaths": true,
1355 "useLibraryCodeForTypes": true,
1356 "autoImportCompletions": true
1357 }
1358 }
1359 })))
1360 }
1361
1362 async fn check_if_user_installed(
1363 &self,
1364 delegate: &dyn LspAdapterDelegate,
1365 toolchain: Option<Toolchain>,
1366 _: &AsyncApp,
1367 ) -> Option<LanguageServerBinary> {
1368 if let Some(bin) = delegate.which(Self::BINARY_NAME.as_ref()).await {
1369 let env = delegate.shell_env().await;
1370 Some(LanguageServerBinary {
1371 path: bin,
1372 env: Some(env),
1373 arguments: vec!["--stdio".into()],
1374 })
1375 } else {
1376 let path = Path::new(toolchain?.path.as_ref())
1377 .parent()?
1378 .join(Self::BINARY_NAME);
1379 path.exists().then(|| LanguageServerBinary {
1380 path,
1381 arguments: vec!["--stdio".into()],
1382 env: None,
1383 })
1384 }
1385 }
1386
1387 async fn fetch_latest_server_version(
1388 &self,
1389 _: &dyn LspAdapterDelegate,
1390 ) -> Result<Box<dyn 'static + Any + Send>> {
1391 Ok(Box::new(()) as Box<_>)
1392 }
1393
1394 async fn fetch_server_binary(
1395 &self,
1396 _latest_version: Box<dyn 'static + Send + Any>,
1397 _container_dir: PathBuf,
1398 delegate: &dyn LspAdapterDelegate,
1399 ) -> Result<LanguageServerBinary> {
1400 let venv = self.base_venv(delegate).await.map_err(|e| anyhow!(e))?;
1401 let pip_path = venv.join(BINARY_DIR).join("pip3");
1402 ensure!(
1403 util::command::new_smol_command(pip_path.as_path())
1404 .arg("install")
1405 .arg("basedpyright")
1406 .arg("-U")
1407 .output()
1408 .await?
1409 .status
1410 .success(),
1411 "basedpyright installation failed"
1412 );
1413 let pylsp = venv.join(BINARY_DIR).join(Self::BINARY_NAME);
1414 Ok(LanguageServerBinary {
1415 path: pylsp,
1416 env: None,
1417 arguments: vec!["--stdio".into()],
1418 })
1419 }
1420
1421 async fn cached_server_binary(
1422 &self,
1423 _container_dir: PathBuf,
1424 delegate: &dyn LspAdapterDelegate,
1425 ) -> Option<LanguageServerBinary> {
1426 let venv = self.base_venv(delegate).await.ok()?;
1427 let pylsp = venv.join(BINARY_DIR).join(Self::BINARY_NAME);
1428 Some(LanguageServerBinary {
1429 path: pylsp,
1430 env: None,
1431 arguments: vec!["--stdio".into()],
1432 })
1433 }
1434
1435 async fn process_completions(&self, items: &mut [lsp::CompletionItem]) {
1436 // Pyright assigns each completion item a `sortText` of the form `XX.YYYY.name`.
1437 // Where `XX` is the sorting category, `YYYY` is based on most recent usage,
1438 // and `name` is the symbol name itself.
1439 //
1440 // Because the symbol name is included, there generally are not ties when
1441 // sorting by the `sortText`, so the symbol's fuzzy match score is not taken
1442 // into account. Here, we remove the symbol name from the sortText in order
1443 // to allow our own fuzzy score to be used to break ties.
1444 //
1445 // see https://github.com/microsoft/pyright/blob/95ef4e103b9b2f129c9320427e51b73ea7cf78bd/packages/pyright-internal/src/languageService/completionProvider.ts#LL2873
1446 for item in items {
1447 let Some(sort_text) = &mut item.sort_text else {
1448 continue;
1449 };
1450 let mut parts = sort_text.split('.');
1451 let Some(first) = parts.next() else { continue };
1452 let Some(second) = parts.next() else { continue };
1453 let Some(_) = parts.next() else { continue };
1454 sort_text.replace_range(first.len() + second.len() + 1.., "");
1455 }
1456 }
1457
1458 async fn label_for_completion(
1459 &self,
1460 item: &lsp::CompletionItem,
1461 language: &Arc<language::Language>,
1462 ) -> Option<language::CodeLabel> {
1463 let label = &item.label;
1464 let grammar = language.grammar()?;
1465 let highlight_id = match item.kind? {
1466 lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method")?,
1467 lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function")?,
1468 lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type")?,
1469 lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant")?,
1470 _ => return None,
1471 };
1472 let filter_range = item
1473 .filter_text
1474 .as_deref()
1475 .and_then(|filter| label.find(filter).map(|ix| ix..ix + filter.len()))
1476 .unwrap_or(0..label.len());
1477 Some(language::CodeLabel {
1478 text: label.clone(),
1479 runs: vec![(0..label.len(), highlight_id)],
1480 filter_range,
1481 })
1482 }
1483
1484 async fn label_for_symbol(
1485 &self,
1486 name: &str,
1487 kind: lsp::SymbolKind,
1488 language: &Arc<language::Language>,
1489 ) -> Option<language::CodeLabel> {
1490 let (text, filter_range, display_range) = match kind {
1491 lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
1492 let text = format!("def {}():\n", name);
1493 let filter_range = 4..4 + name.len();
1494 let display_range = 0..filter_range.end;
1495 (text, filter_range, display_range)
1496 }
1497 lsp::SymbolKind::CLASS => {
1498 let text = format!("class {}:", name);
1499 let filter_range = 6..6 + name.len();
1500 let display_range = 0..filter_range.end;
1501 (text, filter_range, display_range)
1502 }
1503 lsp::SymbolKind::CONSTANT => {
1504 let text = format!("{} = 0", name);
1505 let filter_range = 0..name.len();
1506 let display_range = 0..filter_range.end;
1507 (text, filter_range, display_range)
1508 }
1509 _ => return None,
1510 };
1511
1512 Some(language::CodeLabel {
1513 runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
1514 text: text[display_range].to_string(),
1515 filter_range,
1516 })
1517 }
1518
1519 async fn workspace_configuration(
1520 self: Arc<Self>,
1521 _: &dyn Fs,
1522 adapter: &Arc<dyn LspAdapterDelegate>,
1523 toolchain: Option<Toolchain>,
1524 cx: &mut AsyncApp,
1525 ) -> Result<Value> {
1526 cx.update(move |cx| {
1527 let mut user_settings =
1528 language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
1529 .and_then(|s| s.settings.clone())
1530 .unwrap_or_default();
1531
1532 // If we have a detected toolchain, configure Pyright to use it
1533 if let Some(toolchain) = toolchain {
1534 if user_settings.is_null() {
1535 user_settings = Value::Object(serde_json::Map::default());
1536 }
1537 let object = user_settings.as_object_mut().unwrap();
1538
1539 let interpreter_path = toolchain.path.to_string();
1540
1541 // Detect if this is a virtual environment
1542 if let Some(interpreter_dir) = Path::new(&interpreter_path).parent()
1543 && let Some(venv_dir) = interpreter_dir.parent()
1544 {
1545 // Check if this looks like a virtual environment
1546 if venv_dir.join("pyvenv.cfg").exists()
1547 || venv_dir.join("bin/activate").exists()
1548 || venv_dir.join("Scripts/activate.bat").exists()
1549 {
1550 // Set venvPath and venv at the root level
1551 // This matches the format of a pyrightconfig.json file
1552 if let Some(parent) = venv_dir.parent() {
1553 // Use relative path if the venv is inside the workspace
1554 let venv_path = if parent == adapter.worktree_root_path() {
1555 ".".to_string()
1556 } else {
1557 parent.to_string_lossy().into_owned()
1558 };
1559 object.insert("venvPath".to_string(), Value::String(venv_path));
1560 }
1561
1562 if let Some(venv_name) = venv_dir.file_name() {
1563 object.insert(
1564 "venv".to_owned(),
1565 Value::String(venv_name.to_string_lossy().into_owned()),
1566 );
1567 }
1568 }
1569 }
1570
1571 // Always set the python interpreter path
1572 // Get or create the python section
1573 let python = object
1574 .entry("python")
1575 .or_insert(Value::Object(serde_json::Map::default()))
1576 .as_object_mut()
1577 .unwrap();
1578
1579 // Set both pythonPath and defaultInterpreterPath for compatibility
1580 python.insert(
1581 "pythonPath".to_owned(),
1582 Value::String(interpreter_path.clone()),
1583 );
1584 python.insert(
1585 "defaultInterpreterPath".to_owned(),
1586 Value::String(interpreter_path),
1587 );
1588 }
1589
1590 user_settings
1591 })
1592 }
1593}
1594
1595#[cfg(test)]
1596mod tests {
1597 use gpui::{AppContext as _, BorrowAppContext, Context, TestAppContext};
1598 use language::{AutoindentMode, Buffer, language_settings::AllLanguageSettings};
1599 use settings::SettingsStore;
1600 use std::num::NonZeroU32;
1601
1602 #[gpui::test]
1603 async fn test_python_autoindent(cx: &mut TestAppContext) {
1604 cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
1605 let language = crate::language("python", tree_sitter_python::LANGUAGE.into());
1606 cx.update(|cx| {
1607 let test_settings = SettingsStore::test(cx);
1608 cx.set_global(test_settings);
1609 language::init(cx);
1610 cx.update_global::<SettingsStore, _>(|store, cx| {
1611 store.update_user_settings::<AllLanguageSettings>(cx, |s| {
1612 s.defaults.tab_size = NonZeroU32::new(2);
1613 });
1614 });
1615 });
1616
1617 cx.new(|cx| {
1618 let mut buffer = Buffer::local("", cx).with_language(language, cx);
1619 let append = |buffer: &mut Buffer, text: &str, cx: &mut Context<Buffer>| {
1620 let ix = buffer.len();
1621 buffer.edit([(ix..ix, text)], Some(AutoindentMode::EachLine), cx);
1622 };
1623
1624 // indent after "def():"
1625 append(&mut buffer, "def a():\n", cx);
1626 assert_eq!(buffer.text(), "def a():\n ");
1627
1628 // preserve indent after blank line
1629 append(&mut buffer, "\n ", cx);
1630 assert_eq!(buffer.text(), "def a():\n \n ");
1631
1632 // indent after "if"
1633 append(&mut buffer, "if a:\n ", cx);
1634 assert_eq!(buffer.text(), "def a():\n \n if a:\n ");
1635
1636 // preserve indent after statement
1637 append(&mut buffer, "b()\n", cx);
1638 assert_eq!(buffer.text(), "def a():\n \n if a:\n b()\n ");
1639
1640 // preserve indent after statement
1641 append(&mut buffer, "else", cx);
1642 assert_eq!(buffer.text(), "def a():\n \n if a:\n b()\n else");
1643
1644 // dedent "else""
1645 append(&mut buffer, ":", cx);
1646 assert_eq!(buffer.text(), "def a():\n \n if a:\n b()\n else:");
1647
1648 // indent lines after else
1649 append(&mut buffer, "\n", cx);
1650 assert_eq!(
1651 buffer.text(),
1652 "def a():\n \n if a:\n b()\n else:\n "
1653 );
1654
1655 // indent after an open paren. the closing paren is not indented
1656 // because there is another token before it on the same line.
1657 append(&mut buffer, "foo(\n1)", cx);
1658 assert_eq!(
1659 buffer.text(),
1660 "def a():\n \n if a:\n b()\n else:\n foo(\n 1)"
1661 );
1662
1663 // dedent the closing paren if it is shifted to the beginning of the line
1664 let argument_ix = buffer.text().find('1').unwrap();
1665 buffer.edit(
1666 [(argument_ix..argument_ix + 1, "")],
1667 Some(AutoindentMode::EachLine),
1668 cx,
1669 );
1670 assert_eq!(
1671 buffer.text(),
1672 "def a():\n \n if a:\n b()\n else:\n foo(\n )"
1673 );
1674
1675 // preserve indent after the close paren
1676 append(&mut buffer, "\n", cx);
1677 assert_eq!(
1678 buffer.text(),
1679 "def a():\n \n if a:\n b()\n else:\n foo(\n )\n "
1680 );
1681
1682 // manually outdent the last line
1683 let end_whitespace_ix = buffer.len() - 4;
1684 buffer.edit(
1685 [(end_whitespace_ix..buffer.len(), "")],
1686 Some(AutoindentMode::EachLine),
1687 cx,
1688 );
1689 assert_eq!(
1690 buffer.text(),
1691 "def a():\n \n if a:\n b()\n else:\n foo(\n )\n"
1692 );
1693
1694 // preserve the newly reduced indentation on the next newline
1695 append(&mut buffer, "\n", cx);
1696 assert_eq!(
1697 buffer.text(),
1698 "def a():\n \n if a:\n b()\n else:\n foo(\n )\n\n"
1699 );
1700
1701 // reset to a simple if statement
1702 buffer.edit([(0..buffer.len(), "if a:\n b(\n )")], None, cx);
1703
1704 // dedent "else" on the line after a closing paren
1705 append(&mut buffer, "\n else:\n", cx);
1706 assert_eq!(buffer.text(), "if a:\n b(\n )\nelse:\n ");
1707
1708 buffer
1709 });
1710 }
1711}