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