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