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