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