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: Option<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 let mut directories = vec![worktree_root.clone()];
776 if let Some(subroot_relative_path) = subroot_relative_path {
777 debug_assert!(subroot_relative_path.is_relative());
778 directories.push(worktree_root.join(subroot_relative_path));
779 }
780
781 config.workspace_directories = Some(directories);
782 for locator in locators.iter() {
783 locator.configure(&config);
784 }
785
786 let reporter = pet_reporter::collect::create_reporter();
787 pet::find::find_and_report_envs(&reporter, config, &locators, &environment, None);
788
789 let mut toolchains = reporter
790 .environments
791 .lock()
792 .map_or(Vec::new(), |mut guard| std::mem::take(&mut guard));
793
794 let wr = worktree_root;
795 let wr_venv = get_worktree_venv_declaration(&wr).await;
796 // Sort detected environments by:
797 // environment name matching activation file (<workdir>/.venv)
798 // environment project dir matching worktree_root
799 // general env priority
800 // environment path matching the CONDA_PREFIX env var
801 // executable path
802 toolchains.sort_by(|lhs, rhs| {
803 // Compare venv names against worktree .venv file
804 let venv_ordering =
805 wr_venv
806 .as_ref()
807 .map_or(Ordering::Equal, |venv| match (&lhs.name, &rhs.name) {
808 (Some(l), Some(r)) => (r == venv).cmp(&(l == venv)),
809 (Some(l), None) if l == venv => Ordering::Less,
810 (None, Some(r)) if r == venv => Ordering::Greater,
811 _ => Ordering::Equal,
812 });
813
814 // Compare project paths against worktree root
815 let proj_ordering = || match (&lhs.project, &rhs.project) {
816 (Some(l), Some(r)) => (r == &wr).cmp(&(l == &wr)),
817 (Some(l), None) if l == &wr => Ordering::Less,
818 (None, Some(r)) if r == &wr => Ordering::Greater,
819 _ => Ordering::Equal,
820 };
821
822 // Compare environment priorities
823 let priority_ordering = || env_priority(lhs.kind).cmp(&env_priority(rhs.kind));
824
825 // Compare conda prefixes
826 let conda_ordering = || {
827 if lhs.kind == Some(PythonEnvironmentKind::Conda) {
828 environment
829 .get_env_var("CONDA_PREFIX".to_string())
830 .map(|conda_prefix| {
831 let is_match = |exe: &Option<PathBuf>| {
832 exe.as_ref().is_some_and(|e| e.starts_with(&conda_prefix))
833 };
834 match (is_match(&lhs.executable), is_match(&rhs.executable)) {
835 (true, false) => Ordering::Less,
836 (false, true) => Ordering::Greater,
837 _ => Ordering::Equal,
838 }
839 })
840 .unwrap_or(Ordering::Equal)
841 } else {
842 Ordering::Equal
843 }
844 };
845
846 // Compare Python executables
847 let exe_ordering = || lhs.executable.cmp(&rhs.executable);
848
849 venv_ordering
850 .then_with(proj_ordering)
851 .then_with(priority_ordering)
852 .then_with(conda_ordering)
853 .then_with(exe_ordering)
854 });
855
856 let mut toolchains: Vec<_> = toolchains
857 .into_iter()
858 .filter_map(|toolchain| {
859 let mut name = String::from("Python");
860 if let Some(version) = &toolchain.version {
861 _ = write!(name, " {version}");
862 }
863
864 let name_and_kind = match (&toolchain.name, &toolchain.kind) {
865 (Some(name), Some(kind)) => {
866 Some(format!("({name}; {})", python_env_kind_display(kind)))
867 }
868 (Some(name), None) => Some(format!("({name})")),
869 (None, Some(kind)) => Some(format!("({})", python_env_kind_display(kind))),
870 (None, None) => None,
871 };
872
873 if let Some(nk) = name_and_kind {
874 _ = write!(name, " {nk}");
875 }
876
877 Some(Toolchain {
878 name: name.into(),
879 path: toolchain.executable.as_ref()?.to_str()?.to_owned().into(),
880 language_name: LanguageName::new("Python"),
881 as_json: serde_json::to_value(toolchain.clone()).ok()?,
882 })
883 })
884 .collect();
885 toolchains.dedup();
886 ToolchainList {
887 toolchains,
888 default: None,
889 groups: Default::default(),
890 }
891 }
892 fn term(&self) -> SharedString {
893 self.term.clone()
894 }
895 async fn activation_script(&self, toolchain: &Toolchain, fs: &dyn Fs) -> Option<String> {
896 let toolchain = serde_json::from_value::<pet_core::python_environment::PythonEnvironment>(
897 toolchain.as_json.clone(),
898 )
899 .ok()?;
900 let mut activation_script = None;
901 if let Some(prefix) = &toolchain.prefix {
902 #[cfg(not(target_os = "windows"))]
903 let path = prefix.join(BINARY_DIR).join("activate");
904 #[cfg(target_os = "windows")]
905 let path = prefix.join(BINARY_DIR).join("activate.ps1");
906 if fs.is_file(&path).await {
907 activation_script = Some(format!(". {}", path.display()));
908 }
909 }
910 activation_script
911 }
912}
913
914pub struct EnvironmentApi<'a> {
915 global_search_locations: Arc<Mutex<Vec<PathBuf>>>,
916 project_env: &'a HashMap<String, String>,
917 pet_env: pet_core::os_environment::EnvironmentApi,
918}
919
920impl<'a> EnvironmentApi<'a> {
921 pub fn from_env(project_env: &'a HashMap<String, String>) -> Self {
922 let paths = project_env
923 .get("PATH")
924 .map(|p| std::env::split_paths(p).collect())
925 .unwrap_or_default();
926
927 EnvironmentApi {
928 global_search_locations: Arc::new(Mutex::new(paths)),
929 project_env,
930 pet_env: pet_core::os_environment::EnvironmentApi::new(),
931 }
932 }
933
934 fn user_home(&self) -> Option<PathBuf> {
935 self.project_env
936 .get("HOME")
937 .or_else(|| self.project_env.get("USERPROFILE"))
938 .map(|home| pet_fs::path::norm_case(PathBuf::from(home)))
939 .or_else(|| self.pet_env.get_user_home())
940 }
941}
942
943impl pet_core::os_environment::Environment for EnvironmentApi<'_> {
944 fn get_user_home(&self) -> Option<PathBuf> {
945 self.user_home()
946 }
947
948 fn get_root(&self) -> Option<PathBuf> {
949 None
950 }
951
952 fn get_env_var(&self, key: String) -> Option<String> {
953 self.project_env
954 .get(&key)
955 .cloned()
956 .or_else(|| self.pet_env.get_env_var(key))
957 }
958
959 fn get_know_global_search_locations(&self) -> Vec<PathBuf> {
960 if self.global_search_locations.lock().is_empty() {
961 let mut paths =
962 std::env::split_paths(&self.get_env_var("PATH".to_string()).unwrap_or_default())
963 .collect::<Vec<PathBuf>>();
964
965 log::trace!("Env PATH: {:?}", paths);
966 for p in self.pet_env.get_know_global_search_locations() {
967 if !paths.contains(&p) {
968 paths.push(p);
969 }
970 }
971
972 let mut paths = paths
973 .into_iter()
974 .filter(|p| p.exists())
975 .collect::<Vec<PathBuf>>();
976
977 self.global_search_locations.lock().append(&mut paths);
978 }
979 self.global_search_locations.lock().clone()
980 }
981}
982
983pub(crate) struct PyLspAdapter {
984 python_venv_base: OnceCell<Result<Arc<Path>, String>>,
985}
986impl PyLspAdapter {
987 const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("pylsp");
988 pub(crate) fn new() -> Self {
989 Self {
990 python_venv_base: OnceCell::new(),
991 }
992 }
993 async fn ensure_venv(delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>> {
994 let python_path = Self::find_base_python(delegate)
995 .await
996 .context("Could not find Python installation for PyLSP")?;
997 let work_dir = delegate
998 .language_server_download_dir(&Self::SERVER_NAME)
999 .await
1000 .context("Could not get working directory for PyLSP")?;
1001 let mut path = PathBuf::from(work_dir.as_ref());
1002 path.push("pylsp-venv");
1003 if !path.exists() {
1004 util::command::new_smol_command(python_path)
1005 .arg("-m")
1006 .arg("venv")
1007 .arg("pylsp-venv")
1008 .current_dir(work_dir)
1009 .spawn()?
1010 .output()
1011 .await?;
1012 }
1013
1014 Ok(path.into())
1015 }
1016 // Find "baseline", user python version from which we'll create our own venv.
1017 async fn find_base_python(delegate: &dyn LspAdapterDelegate) -> Option<PathBuf> {
1018 for path in ["python3", "python"] {
1019 if let Some(path) = delegate.which(path.as_ref()).await {
1020 return Some(path);
1021 }
1022 }
1023 None
1024 }
1025
1026 async fn base_venv(&self, delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>, String> {
1027 self.python_venv_base
1028 .get_or_init(move || async move {
1029 Self::ensure_venv(delegate)
1030 .await
1031 .map_err(|e| format!("{e}"))
1032 })
1033 .await
1034 .clone()
1035 }
1036}
1037
1038const BINARY_DIR: &str = if cfg!(target_os = "windows") {
1039 "Scripts"
1040} else {
1041 "bin"
1042};
1043
1044#[async_trait(?Send)]
1045impl LspAdapter for PyLspAdapter {
1046 fn name(&self) -> LanguageServerName {
1047 Self::SERVER_NAME
1048 }
1049
1050 async fn check_if_user_installed(
1051 &self,
1052 delegate: &dyn LspAdapterDelegate,
1053 toolchain: Option<Toolchain>,
1054 _: &AsyncApp,
1055 ) -> Option<LanguageServerBinary> {
1056 if let Some(pylsp_bin) = delegate.which(Self::SERVER_NAME.as_ref()).await {
1057 let env = delegate.shell_env().await;
1058 Some(LanguageServerBinary {
1059 path: pylsp_bin,
1060 env: Some(env),
1061 arguments: vec![],
1062 })
1063 } else {
1064 let venv = toolchain?;
1065 let pylsp_path = Path::new(venv.path.as_ref()).parent()?.join("pylsp");
1066 pylsp_path.exists().then(|| LanguageServerBinary {
1067 path: venv.path.to_string().into(),
1068 arguments: vec![pylsp_path.into()],
1069 env: None,
1070 })
1071 }
1072 }
1073
1074 async fn fetch_latest_server_version(
1075 &self,
1076 _: &dyn LspAdapterDelegate,
1077 ) -> Result<Box<dyn 'static + Any + Send>> {
1078 Ok(Box::new(()) as Box<_>)
1079 }
1080
1081 async fn fetch_server_binary(
1082 &self,
1083 _: Box<dyn 'static + Send + Any>,
1084 _: PathBuf,
1085 delegate: &dyn LspAdapterDelegate,
1086 ) -> Result<LanguageServerBinary> {
1087 let venv = self.base_venv(delegate).await.map_err(|e| anyhow!(e))?;
1088 let pip_path = venv.join(BINARY_DIR).join("pip3");
1089 ensure!(
1090 util::command::new_smol_command(pip_path.as_path())
1091 .arg("install")
1092 .arg("python-lsp-server")
1093 .arg("-U")
1094 .output()
1095 .await?
1096 .status
1097 .success(),
1098 "python-lsp-server installation failed"
1099 );
1100 ensure!(
1101 util::command::new_smol_command(pip_path.as_path())
1102 .arg("install")
1103 .arg("python-lsp-server[all]")
1104 .arg("-U")
1105 .output()
1106 .await?
1107 .status
1108 .success(),
1109 "python-lsp-server[all] installation failed"
1110 );
1111 ensure!(
1112 util::command::new_smol_command(pip_path)
1113 .arg("install")
1114 .arg("pylsp-mypy")
1115 .arg("-U")
1116 .output()
1117 .await?
1118 .status
1119 .success(),
1120 "pylsp-mypy installation failed"
1121 );
1122 let pylsp = venv.join(BINARY_DIR).join("pylsp");
1123 Ok(LanguageServerBinary {
1124 path: pylsp,
1125 env: None,
1126 arguments: vec![],
1127 })
1128 }
1129
1130 async fn cached_server_binary(
1131 &self,
1132 _: PathBuf,
1133 delegate: &dyn LspAdapterDelegate,
1134 ) -> Option<LanguageServerBinary> {
1135 let venv = self.base_venv(delegate).await.ok()?;
1136 let pylsp = venv.join(BINARY_DIR).join("pylsp");
1137 Some(LanguageServerBinary {
1138 path: pylsp,
1139 env: None,
1140 arguments: vec![],
1141 })
1142 }
1143
1144 async fn process_completions(&self, _items: &mut [lsp::CompletionItem]) {}
1145
1146 async fn label_for_completion(
1147 &self,
1148 item: &lsp::CompletionItem,
1149 language: &Arc<language::Language>,
1150 ) -> Option<language::CodeLabel> {
1151 let label = &item.label;
1152 let grammar = language.grammar()?;
1153 let highlight_id = match item.kind? {
1154 lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method")?,
1155 lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function")?,
1156 lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type")?,
1157 lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant")?,
1158 _ => return None,
1159 };
1160 let filter_range = item
1161 .filter_text
1162 .as_deref()
1163 .and_then(|filter| label.find(filter).map(|ix| ix..ix + filter.len()))
1164 .unwrap_or(0..label.len());
1165 Some(language::CodeLabel {
1166 text: label.clone(),
1167 runs: vec![(0..label.len(), highlight_id)],
1168 filter_range,
1169 })
1170 }
1171
1172 async fn label_for_symbol(
1173 &self,
1174 name: &str,
1175 kind: lsp::SymbolKind,
1176 language: &Arc<language::Language>,
1177 ) -> Option<language::CodeLabel> {
1178 let (text, filter_range, display_range) = match kind {
1179 lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
1180 let text = format!("def {}():\n", name);
1181 let filter_range = 4..4 + name.len();
1182 let display_range = 0..filter_range.end;
1183 (text, filter_range, display_range)
1184 }
1185 lsp::SymbolKind::CLASS => {
1186 let text = format!("class {}:", name);
1187 let filter_range = 6..6 + name.len();
1188 let display_range = 0..filter_range.end;
1189 (text, filter_range, display_range)
1190 }
1191 lsp::SymbolKind::CONSTANT => {
1192 let text = format!("{} = 0", name);
1193 let filter_range = 0..name.len();
1194 let display_range = 0..filter_range.end;
1195 (text, filter_range, display_range)
1196 }
1197 _ => return None,
1198 };
1199
1200 Some(language::CodeLabel {
1201 runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
1202 text: text[display_range].to_string(),
1203 filter_range,
1204 })
1205 }
1206
1207 async fn workspace_configuration(
1208 self: Arc<Self>,
1209 _: &dyn Fs,
1210 adapter: &Arc<dyn LspAdapterDelegate>,
1211 toolchain: Option<Toolchain>,
1212 cx: &mut AsyncApp,
1213 ) -> Result<Value> {
1214 cx.update(move |cx| {
1215 let mut user_settings =
1216 language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
1217 .and_then(|s| s.settings.clone())
1218 .unwrap_or_else(|| {
1219 json!({
1220 "plugins": {
1221 "pycodestyle": {"enabled": false},
1222 "rope_autoimport": {"enabled": true, "memory": true},
1223 "pylsp_mypy": {"enabled": false}
1224 },
1225 "rope": {
1226 "ropeFolder": null
1227 },
1228 })
1229 });
1230
1231 // If user did not explicitly modify their python venv, use one from picker.
1232 if let Some(toolchain) = toolchain {
1233 if user_settings.is_null() {
1234 user_settings = Value::Object(serde_json::Map::default());
1235 }
1236 let object = user_settings.as_object_mut().unwrap();
1237 if let Some(python) = object
1238 .entry("plugins")
1239 .or_insert(Value::Object(serde_json::Map::default()))
1240 .as_object_mut()
1241 {
1242 if let Some(jedi) = python
1243 .entry("jedi")
1244 .or_insert(Value::Object(serde_json::Map::default()))
1245 .as_object_mut()
1246 {
1247 jedi.entry("environment".to_string())
1248 .or_insert_with(|| Value::String(toolchain.path.clone().into()));
1249 }
1250 if let Some(pylint) = python
1251 .entry("pylsp_mypy")
1252 .or_insert(Value::Object(serde_json::Map::default()))
1253 .as_object_mut()
1254 {
1255 pylint.entry("overrides".to_string()).or_insert_with(|| {
1256 Value::Array(vec![
1257 Value::String("--python-executable".into()),
1258 Value::String(toolchain.path.into()),
1259 Value::String("--cache-dir=/dev/null".into()),
1260 Value::Bool(true),
1261 ])
1262 });
1263 }
1264 }
1265 }
1266 user_settings = Value::Object(serde_json::Map::from_iter([(
1267 "pylsp".to_string(),
1268 user_settings,
1269 )]));
1270
1271 user_settings
1272 })
1273 }
1274}
1275
1276pub(crate) struct BasedPyrightLspAdapter {
1277 python_venv_base: OnceCell<Result<Arc<Path>, String>>,
1278}
1279
1280impl BasedPyrightLspAdapter {
1281 const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("basedpyright");
1282 const BINARY_NAME: &'static str = "basedpyright-langserver";
1283
1284 pub(crate) fn new() -> Self {
1285 Self {
1286 python_venv_base: OnceCell::new(),
1287 }
1288 }
1289
1290 async fn ensure_venv(delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>> {
1291 let python_path = Self::find_base_python(delegate)
1292 .await
1293 .context("Could not find Python installation for basedpyright")?;
1294 let work_dir = delegate
1295 .language_server_download_dir(&Self::SERVER_NAME)
1296 .await
1297 .context("Could not get working directory for basedpyright")?;
1298 let mut path = PathBuf::from(work_dir.as_ref());
1299 path.push("basedpyright-venv");
1300 if !path.exists() {
1301 util::command::new_smol_command(python_path)
1302 .arg("-m")
1303 .arg("venv")
1304 .arg("basedpyright-venv")
1305 .current_dir(work_dir)
1306 .spawn()?
1307 .output()
1308 .await?;
1309 }
1310
1311 Ok(path.into())
1312 }
1313
1314 // Find "baseline", user python version from which we'll create our own venv.
1315 async fn find_base_python(delegate: &dyn LspAdapterDelegate) -> Option<PathBuf> {
1316 for path in ["python3", "python"] {
1317 if let Some(path) = delegate.which(path.as_ref()).await {
1318 return Some(path);
1319 }
1320 }
1321 None
1322 }
1323
1324 async fn base_venv(&self, delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>, String> {
1325 self.python_venv_base
1326 .get_or_init(move || async move {
1327 Self::ensure_venv(delegate)
1328 .await
1329 .map_err(|e| format!("{e}"))
1330 })
1331 .await
1332 .clone()
1333 }
1334}
1335
1336#[async_trait(?Send)]
1337impl LspAdapter for BasedPyrightLspAdapter {
1338 fn name(&self) -> LanguageServerName {
1339 Self::SERVER_NAME
1340 }
1341
1342 async fn initialization_options(
1343 self: Arc<Self>,
1344 _: &dyn Fs,
1345 _: &Arc<dyn LspAdapterDelegate>,
1346 ) -> Result<Option<Value>> {
1347 // Provide minimal initialization options
1348 // Virtual environment configuration will be handled through workspace configuration
1349 Ok(Some(json!({
1350 "python": {
1351 "analysis": {
1352 "autoSearchPaths": true,
1353 "useLibraryCodeForTypes": true,
1354 "autoImportCompletions": true
1355 }
1356 }
1357 })))
1358 }
1359
1360 async fn check_if_user_installed(
1361 &self,
1362 delegate: &dyn LspAdapterDelegate,
1363 toolchain: Option<Toolchain>,
1364 _: &AsyncApp,
1365 ) -> Option<LanguageServerBinary> {
1366 if let Some(bin) = delegate.which(Self::BINARY_NAME.as_ref()).await {
1367 let env = delegate.shell_env().await;
1368 Some(LanguageServerBinary {
1369 path: bin,
1370 env: Some(env),
1371 arguments: vec!["--stdio".into()],
1372 })
1373 } else {
1374 let path = Path::new(toolchain?.path.as_ref())
1375 .parent()?
1376 .join(Self::BINARY_NAME);
1377 path.exists().then(|| LanguageServerBinary {
1378 path,
1379 arguments: vec!["--stdio".into()],
1380 env: None,
1381 })
1382 }
1383 }
1384
1385 async fn fetch_latest_server_version(
1386 &self,
1387 _: &dyn LspAdapterDelegate,
1388 ) -> Result<Box<dyn 'static + Any + Send>> {
1389 Ok(Box::new(()) as Box<_>)
1390 }
1391
1392 async fn fetch_server_binary(
1393 &self,
1394 _latest_version: Box<dyn 'static + Send + Any>,
1395 _container_dir: PathBuf,
1396 delegate: &dyn LspAdapterDelegate,
1397 ) -> Result<LanguageServerBinary> {
1398 let venv = self.base_venv(delegate).await.map_err(|e| anyhow!(e))?;
1399 let pip_path = venv.join(BINARY_DIR).join("pip3");
1400 ensure!(
1401 util::command::new_smol_command(pip_path.as_path())
1402 .arg("install")
1403 .arg("basedpyright")
1404 .arg("-U")
1405 .output()
1406 .await?
1407 .status
1408 .success(),
1409 "basedpyright installation failed"
1410 );
1411 let pylsp = venv.join(BINARY_DIR).join(Self::BINARY_NAME);
1412 Ok(LanguageServerBinary {
1413 path: pylsp,
1414 env: None,
1415 arguments: vec!["--stdio".into()],
1416 })
1417 }
1418
1419 async fn cached_server_binary(
1420 &self,
1421 _container_dir: PathBuf,
1422 delegate: &dyn LspAdapterDelegate,
1423 ) -> Option<LanguageServerBinary> {
1424 let venv = self.base_venv(delegate).await.ok()?;
1425 let pylsp = venv.join(BINARY_DIR).join(Self::BINARY_NAME);
1426 Some(LanguageServerBinary {
1427 path: pylsp,
1428 env: None,
1429 arguments: vec!["--stdio".into()],
1430 })
1431 }
1432
1433 async fn process_completions(&self, items: &mut [lsp::CompletionItem]) {
1434 // Pyright assigns each completion item a `sortText` of the form `XX.YYYY.name`.
1435 // Where `XX` is the sorting category, `YYYY` is based on most recent usage,
1436 // and `name` is the symbol name itself.
1437 //
1438 // Because the symbol name is included, there generally are not ties when
1439 // sorting by the `sortText`, so the symbol's fuzzy match score is not taken
1440 // into account. Here, we remove the symbol name from the sortText in order
1441 // to allow our own fuzzy score to be used to break ties.
1442 //
1443 // see https://github.com/microsoft/pyright/blob/95ef4e103b9b2f129c9320427e51b73ea7cf78bd/packages/pyright-internal/src/languageService/completionProvider.ts#LL2873
1444 for item in items {
1445 let Some(sort_text) = &mut item.sort_text else {
1446 continue;
1447 };
1448 let mut parts = sort_text.split('.');
1449 let Some(first) = parts.next() else { continue };
1450 let Some(second) = parts.next() else { continue };
1451 let Some(_) = parts.next() else { continue };
1452 sort_text.replace_range(first.len() + second.len() + 1.., "");
1453 }
1454 }
1455
1456 async fn label_for_completion(
1457 &self,
1458 item: &lsp::CompletionItem,
1459 language: &Arc<language::Language>,
1460 ) -> Option<language::CodeLabel> {
1461 let label = &item.label;
1462 let grammar = language.grammar()?;
1463 let highlight_id = match item.kind? {
1464 lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method")?,
1465 lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function")?,
1466 lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type")?,
1467 lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant")?,
1468 _ => return None,
1469 };
1470 let filter_range = item
1471 .filter_text
1472 .as_deref()
1473 .and_then(|filter| label.find(filter).map(|ix| ix..ix + filter.len()))
1474 .unwrap_or(0..label.len());
1475 Some(language::CodeLabel {
1476 text: label.clone(),
1477 runs: vec![(0..label.len(), highlight_id)],
1478 filter_range,
1479 })
1480 }
1481
1482 async fn label_for_symbol(
1483 &self,
1484 name: &str,
1485 kind: lsp::SymbolKind,
1486 language: &Arc<language::Language>,
1487 ) -> Option<language::CodeLabel> {
1488 let (text, filter_range, display_range) = match kind {
1489 lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
1490 let text = format!("def {}():\n", name);
1491 let filter_range = 4..4 + name.len();
1492 let display_range = 0..filter_range.end;
1493 (text, filter_range, display_range)
1494 }
1495 lsp::SymbolKind::CLASS => {
1496 let text = format!("class {}:", name);
1497 let filter_range = 6..6 + name.len();
1498 let display_range = 0..filter_range.end;
1499 (text, filter_range, display_range)
1500 }
1501 lsp::SymbolKind::CONSTANT => {
1502 let text = format!("{} = 0", name);
1503 let filter_range = 0..name.len();
1504 let display_range = 0..filter_range.end;
1505 (text, filter_range, display_range)
1506 }
1507 _ => return None,
1508 };
1509
1510 Some(language::CodeLabel {
1511 runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
1512 text: text[display_range].to_string(),
1513 filter_range,
1514 })
1515 }
1516
1517 async fn workspace_configuration(
1518 self: Arc<Self>,
1519 _: &dyn Fs,
1520 adapter: &Arc<dyn LspAdapterDelegate>,
1521 toolchain: Option<Toolchain>,
1522 cx: &mut AsyncApp,
1523 ) -> Result<Value> {
1524 cx.update(move |cx| {
1525 let mut user_settings =
1526 language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
1527 .and_then(|s| s.settings.clone())
1528 .unwrap_or_default();
1529
1530 // If we have a detected toolchain, configure Pyright to use it
1531 if let Some(toolchain) = toolchain {
1532 if user_settings.is_null() {
1533 user_settings = Value::Object(serde_json::Map::default());
1534 }
1535 let object = user_settings.as_object_mut().unwrap();
1536
1537 let interpreter_path = toolchain.path.to_string();
1538
1539 // Detect if this is a virtual environment
1540 if let Some(interpreter_dir) = Path::new(&interpreter_path).parent()
1541 && let Some(venv_dir) = interpreter_dir.parent()
1542 {
1543 // Check if this looks like a virtual environment
1544 if venv_dir.join("pyvenv.cfg").exists()
1545 || venv_dir.join("bin/activate").exists()
1546 || venv_dir.join("Scripts/activate.bat").exists()
1547 {
1548 // Set venvPath and venv at the root level
1549 // This matches the format of a pyrightconfig.json file
1550 if let Some(parent) = venv_dir.parent() {
1551 // Use relative path if the venv is inside the workspace
1552 let venv_path = if parent == adapter.worktree_root_path() {
1553 ".".to_string()
1554 } else {
1555 parent.to_string_lossy().into_owned()
1556 };
1557 object.insert("venvPath".to_string(), Value::String(venv_path));
1558 }
1559
1560 if let Some(venv_name) = venv_dir.file_name() {
1561 object.insert(
1562 "venv".to_owned(),
1563 Value::String(venv_name.to_string_lossy().into_owned()),
1564 );
1565 }
1566 }
1567 }
1568
1569 // Always set the python interpreter path
1570 // Get or create the python section
1571 let python = object
1572 .entry("python")
1573 .or_insert(Value::Object(serde_json::Map::default()))
1574 .as_object_mut()
1575 .unwrap();
1576
1577 // Set both pythonPath and defaultInterpreterPath for compatibility
1578 python.insert(
1579 "pythonPath".to_owned(),
1580 Value::String(interpreter_path.clone()),
1581 );
1582 python.insert(
1583 "defaultInterpreterPath".to_owned(),
1584 Value::String(interpreter_path),
1585 );
1586 }
1587
1588 user_settings
1589 })
1590 }
1591}
1592
1593#[cfg(test)]
1594mod tests {
1595 use gpui::{AppContext as _, BorrowAppContext, Context, TestAppContext};
1596 use language::{AutoindentMode, Buffer, language_settings::AllLanguageSettings};
1597 use settings::SettingsStore;
1598 use std::num::NonZeroU32;
1599
1600 #[gpui::test]
1601 async fn test_python_autoindent(cx: &mut TestAppContext) {
1602 cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
1603 let language = crate::language("python", tree_sitter_python::LANGUAGE.into());
1604 cx.update(|cx| {
1605 let test_settings = SettingsStore::test(cx);
1606 cx.set_global(test_settings);
1607 language::init(cx);
1608 cx.update_global::<SettingsStore, _>(|store, cx| {
1609 store.update_user_settings::<AllLanguageSettings>(cx, |s| {
1610 s.defaults.tab_size = NonZeroU32::new(2);
1611 });
1612 });
1613 });
1614
1615 cx.new(|cx| {
1616 let mut buffer = Buffer::local("", cx).with_language(language, cx);
1617 let append = |buffer: &mut Buffer, text: &str, cx: &mut Context<Buffer>| {
1618 let ix = buffer.len();
1619 buffer.edit([(ix..ix, text)], Some(AutoindentMode::EachLine), cx);
1620 };
1621
1622 // indent after "def():"
1623 append(&mut buffer, "def a():\n", cx);
1624 assert_eq!(buffer.text(), "def a():\n ");
1625
1626 // preserve indent after blank line
1627 append(&mut buffer, "\n ", cx);
1628 assert_eq!(buffer.text(), "def a():\n \n ");
1629
1630 // indent after "if"
1631 append(&mut buffer, "if a:\n ", cx);
1632 assert_eq!(buffer.text(), "def a():\n \n if a:\n ");
1633
1634 // preserve indent after statement
1635 append(&mut buffer, "b()\n", cx);
1636 assert_eq!(buffer.text(), "def a():\n \n if a:\n b()\n ");
1637
1638 // preserve indent after statement
1639 append(&mut buffer, "else", cx);
1640 assert_eq!(buffer.text(), "def a():\n \n if a:\n b()\n else");
1641
1642 // dedent "else""
1643 append(&mut buffer, ":", cx);
1644 assert_eq!(buffer.text(), "def a():\n \n if a:\n b()\n else:");
1645
1646 // indent lines after else
1647 append(&mut buffer, "\n", cx);
1648 assert_eq!(
1649 buffer.text(),
1650 "def a():\n \n if a:\n b()\n else:\n "
1651 );
1652
1653 // indent after an open paren. the closing paren is not indented
1654 // because there is another token before it on the same line.
1655 append(&mut buffer, "foo(\n1)", cx);
1656 assert_eq!(
1657 buffer.text(),
1658 "def a():\n \n if a:\n b()\n else:\n foo(\n 1)"
1659 );
1660
1661 // dedent the closing paren if it is shifted to the beginning of the line
1662 let argument_ix = buffer.text().find('1').unwrap();
1663 buffer.edit(
1664 [(argument_ix..argument_ix + 1, "")],
1665 Some(AutoindentMode::EachLine),
1666 cx,
1667 );
1668 assert_eq!(
1669 buffer.text(),
1670 "def a():\n \n if a:\n b()\n else:\n foo(\n )"
1671 );
1672
1673 // preserve indent after the close paren
1674 append(&mut buffer, "\n", cx);
1675 assert_eq!(
1676 buffer.text(),
1677 "def a():\n \n if a:\n b()\n else:\n foo(\n )\n "
1678 );
1679
1680 // manually outdent the last line
1681 let end_whitespace_ix = buffer.len() - 4;
1682 buffer.edit(
1683 [(end_whitespace_ix..buffer.len(), "")],
1684 Some(AutoindentMode::EachLine),
1685 cx,
1686 );
1687 assert_eq!(
1688 buffer.text(),
1689 "def a():\n \n if a:\n b()\n else:\n foo(\n )\n"
1690 );
1691
1692 // preserve the newly reduced indentation on the next newline
1693 append(&mut buffer, "\n", cx);
1694 assert_eq!(
1695 buffer.text(),
1696 "def a():\n \n if a:\n b()\n else:\n foo(\n )\n\n"
1697 );
1698
1699 // reset to a simple if statement
1700 buffer.edit([(0..buffer.len(), "if a:\n b(\n )")], None, cx);
1701
1702 // dedent "else" on the line after a closing paren
1703 append(&mut buffer, "\n else:\n", cx);
1704 assert_eq!(buffer.text(), "if a:\n b(\n )\nelse:\n ");
1705
1706 buffer
1707 });
1708 }
1709}