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