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::Pixi) => {
896 let env = toolchain.name.as_deref().unwrap_or("default");
897 activation_script.push(format!("pixi shell -e {env}"))
898 }
899 Some(PythonEnvironmentKind::Conda) => {
900 if let Some(name) = &toolchain.name {
901 activation_script.push(format!("conda activate {name}"));
902 } else {
903 activation_script.push("conda activate".to_string());
904 }
905 }
906 Some(PythonEnvironmentKind::Venv | PythonEnvironmentKind::VirtualEnv) => {
907 if let Some(prefix) = &toolchain.prefix {
908 let activate_keyword = match shell {
909 ShellKind::Cmd => ".",
910 ShellKind::Nushell => "overlay use",
911 ShellKind::Powershell => ".",
912 ShellKind::Fish => "source",
913 ShellKind::Csh => "source",
914 ShellKind::Posix => "source",
915 };
916 let activate_script_name = match shell {
917 ShellKind::Posix => "activate",
918 ShellKind::Csh => "activate.csh",
919 ShellKind::Fish => "activate.fish",
920 ShellKind::Nushell => "activate.nu",
921 ShellKind::Powershell => "activate.ps1",
922 ShellKind::Cmd => "activate.bat",
923 };
924 let path = prefix.join(BINARY_DIR).join(activate_script_name);
925 if fs.is_file(&path).await {
926 activation_script
927 .push(format!("{activate_keyword} \"{}\"", path.display()));
928 }
929 }
930 }
931 Some(PythonEnvironmentKind::Pyenv) => {
932 let Some(manager) = toolchain.manager else {
933 return vec![];
934 };
935 let version = toolchain.version.as_deref().unwrap_or("system");
936 let pyenv = manager.executable;
937 let pyenv = pyenv.display();
938 activation_script.extend(match shell {
939 ShellKind::Fish => Some(format!("\"{pyenv}\" shell - fish {version}")),
940 ShellKind::Posix => Some(format!("\"{pyenv}\" shell - sh {version}")),
941 ShellKind::Nushell => Some(format!("\"{pyenv}\" shell - nu {version}")),
942 ShellKind::Powershell => None,
943 ShellKind::Csh => None,
944 ShellKind::Cmd => None,
945 })
946 }
947 _ => {}
948 }
949 activation_script
950 }
951}
952
953fn venv_to_toolchain(venv: PythonEnvironment) -> Option<Toolchain> {
954 let mut name = String::from("Python");
955 if let Some(ref version) = venv.version {
956 _ = write!(name, " {version}");
957 }
958
959 let name_and_kind = match (&venv.name, &venv.kind) {
960 (Some(name), Some(kind)) => Some(format!("({name}; {})", python_env_kind_display(kind))),
961 (Some(name), None) => Some(format!("({name})")),
962 (None, Some(kind)) => Some(format!("({})", python_env_kind_display(kind))),
963 (None, None) => None,
964 };
965
966 if let Some(nk) = name_and_kind {
967 _ = write!(name, " {nk}");
968 }
969
970 Some(Toolchain {
971 name: name.into(),
972 path: venv.executable.as_ref()?.to_str()?.to_owned().into(),
973 language_name: LanguageName::new("Python"),
974 as_json: serde_json::to_value(venv).ok()?,
975 })
976}
977
978pub struct EnvironmentApi<'a> {
979 global_search_locations: Arc<Mutex<Vec<PathBuf>>>,
980 project_env: &'a HashMap<String, String>,
981 pet_env: pet_core::os_environment::EnvironmentApi,
982}
983
984impl<'a> EnvironmentApi<'a> {
985 pub fn from_env(project_env: &'a HashMap<String, String>) -> Self {
986 let paths = project_env
987 .get("PATH")
988 .map(|p| std::env::split_paths(p).collect())
989 .unwrap_or_default();
990
991 EnvironmentApi {
992 global_search_locations: Arc::new(Mutex::new(paths)),
993 project_env,
994 pet_env: pet_core::os_environment::EnvironmentApi::new(),
995 }
996 }
997
998 fn user_home(&self) -> Option<PathBuf> {
999 self.project_env
1000 .get("HOME")
1001 .or_else(|| self.project_env.get("USERPROFILE"))
1002 .map(|home| pet_fs::path::norm_case(PathBuf::from(home)))
1003 .or_else(|| self.pet_env.get_user_home())
1004 }
1005}
1006
1007impl pet_core::os_environment::Environment for EnvironmentApi<'_> {
1008 fn get_user_home(&self) -> Option<PathBuf> {
1009 self.user_home()
1010 }
1011
1012 fn get_root(&self) -> Option<PathBuf> {
1013 None
1014 }
1015
1016 fn get_env_var(&self, key: String) -> Option<String> {
1017 self.project_env
1018 .get(&key)
1019 .cloned()
1020 .or_else(|| self.pet_env.get_env_var(key))
1021 }
1022
1023 fn get_know_global_search_locations(&self) -> Vec<PathBuf> {
1024 if self.global_search_locations.lock().is_empty() {
1025 let mut paths =
1026 std::env::split_paths(&self.get_env_var("PATH".to_string()).unwrap_or_default())
1027 .collect::<Vec<PathBuf>>();
1028
1029 log::trace!("Env PATH: {:?}", paths);
1030 for p in self.pet_env.get_know_global_search_locations() {
1031 if !paths.contains(&p) {
1032 paths.push(p);
1033 }
1034 }
1035
1036 let mut paths = paths
1037 .into_iter()
1038 .filter(|p| p.exists())
1039 .collect::<Vec<PathBuf>>();
1040
1041 self.global_search_locations.lock().append(&mut paths);
1042 }
1043 self.global_search_locations.lock().clone()
1044 }
1045}
1046
1047pub(crate) struct PyLspAdapter {
1048 python_venv_base: OnceCell<Result<Arc<Path>, String>>,
1049}
1050impl PyLspAdapter {
1051 const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("pylsp");
1052 pub(crate) fn new() -> Self {
1053 Self {
1054 python_venv_base: OnceCell::new(),
1055 }
1056 }
1057 async fn ensure_venv(delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>> {
1058 let python_path = Self::find_base_python(delegate)
1059 .await
1060 .context("Could not find Python installation for PyLSP")?;
1061 let work_dir = delegate
1062 .language_server_download_dir(&Self::SERVER_NAME)
1063 .await
1064 .context("Could not get working directory for PyLSP")?;
1065 let mut path = PathBuf::from(work_dir.as_ref());
1066 path.push("pylsp-venv");
1067 if !path.exists() {
1068 util::command::new_smol_command(python_path)
1069 .arg("-m")
1070 .arg("venv")
1071 .arg("pylsp-venv")
1072 .current_dir(work_dir)
1073 .spawn()?
1074 .output()
1075 .await?;
1076 }
1077
1078 Ok(path.into())
1079 }
1080 // Find "baseline", user python version from which we'll create our own venv.
1081 async fn find_base_python(delegate: &dyn LspAdapterDelegate) -> Option<PathBuf> {
1082 for path in ["python3", "python"] {
1083 if let Some(path) = delegate.which(path.as_ref()).await {
1084 return Some(path);
1085 }
1086 }
1087 None
1088 }
1089
1090 async fn base_venv(&self, delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>, String> {
1091 self.python_venv_base
1092 .get_or_init(move || async move {
1093 Self::ensure_venv(delegate)
1094 .await
1095 .map_err(|e| format!("{e}"))
1096 })
1097 .await
1098 .clone()
1099 }
1100}
1101
1102const BINARY_DIR: &str = if cfg!(target_os = "windows") {
1103 "Scripts"
1104} else {
1105 "bin"
1106};
1107
1108#[async_trait(?Send)]
1109impl LspAdapter for PyLspAdapter {
1110 fn name(&self) -> LanguageServerName {
1111 Self::SERVER_NAME
1112 }
1113
1114 async fn check_if_user_installed(
1115 &self,
1116 delegate: &dyn LspAdapterDelegate,
1117 toolchain: Option<Toolchain>,
1118 _: &AsyncApp,
1119 ) -> Option<LanguageServerBinary> {
1120 if let Some(pylsp_bin) = delegate.which(Self::SERVER_NAME.as_ref()).await {
1121 let env = delegate.shell_env().await;
1122 Some(LanguageServerBinary {
1123 path: pylsp_bin,
1124 env: Some(env),
1125 arguments: vec![],
1126 })
1127 } else {
1128 let toolchain = toolchain?;
1129 let pylsp_path = Path::new(toolchain.path.as_ref()).parent()?.join("pylsp");
1130 pylsp_path.exists().then(|| LanguageServerBinary {
1131 path: toolchain.path.to_string().into(),
1132 arguments: vec![pylsp_path.into()],
1133 env: None,
1134 })
1135 }
1136 }
1137
1138 async fn fetch_latest_server_version(
1139 &self,
1140 _: &dyn LspAdapterDelegate,
1141 _: &AsyncApp,
1142 ) -> Result<Box<dyn 'static + Any + Send>> {
1143 Ok(Box::new(()) as Box<_>)
1144 }
1145
1146 async fn fetch_server_binary(
1147 &self,
1148 _: Box<dyn 'static + Send + Any>,
1149 _: PathBuf,
1150 delegate: &dyn LspAdapterDelegate,
1151 ) -> Result<LanguageServerBinary> {
1152 let venv = self.base_venv(delegate).await.map_err(|e| anyhow!(e))?;
1153 let pip_path = venv.join(BINARY_DIR).join("pip3");
1154 ensure!(
1155 util::command::new_smol_command(pip_path.as_path())
1156 .arg("install")
1157 .arg("python-lsp-server")
1158 .arg("-U")
1159 .output()
1160 .await?
1161 .status
1162 .success(),
1163 "python-lsp-server installation failed"
1164 );
1165 ensure!(
1166 util::command::new_smol_command(pip_path.as_path())
1167 .arg("install")
1168 .arg("python-lsp-server[all]")
1169 .arg("-U")
1170 .output()
1171 .await?
1172 .status
1173 .success(),
1174 "python-lsp-server[all] installation failed"
1175 );
1176 ensure!(
1177 util::command::new_smol_command(pip_path)
1178 .arg("install")
1179 .arg("pylsp-mypy")
1180 .arg("-U")
1181 .output()
1182 .await?
1183 .status
1184 .success(),
1185 "pylsp-mypy installation failed"
1186 );
1187 let pylsp = venv.join(BINARY_DIR).join("pylsp");
1188 Ok(LanguageServerBinary {
1189 path: pylsp,
1190 env: None,
1191 arguments: vec![],
1192 })
1193 }
1194
1195 async fn cached_server_binary(
1196 &self,
1197 _: PathBuf,
1198 delegate: &dyn LspAdapterDelegate,
1199 ) -> Option<LanguageServerBinary> {
1200 let venv = self.base_venv(delegate).await.ok()?;
1201 let pylsp = venv.join(BINARY_DIR).join("pylsp");
1202 Some(LanguageServerBinary {
1203 path: pylsp,
1204 env: None,
1205 arguments: vec![],
1206 })
1207 }
1208
1209 async fn process_completions(&self, _items: &mut [lsp::CompletionItem]) {}
1210
1211 async fn label_for_completion(
1212 &self,
1213 item: &lsp::CompletionItem,
1214 language: &Arc<language::Language>,
1215 ) -> Option<language::CodeLabel> {
1216 let label = &item.label;
1217 let grammar = language.grammar()?;
1218 let highlight_id = match item.kind? {
1219 lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method")?,
1220 lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function")?,
1221 lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type")?,
1222 lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant")?,
1223 _ => return None,
1224 };
1225 let filter_range = item
1226 .filter_text
1227 .as_deref()
1228 .and_then(|filter| label.find(filter).map(|ix| ix..ix + filter.len()))
1229 .unwrap_or(0..label.len());
1230 Some(language::CodeLabel {
1231 text: label.clone(),
1232 runs: vec![(0..label.len(), highlight_id)],
1233 filter_range,
1234 })
1235 }
1236
1237 async fn label_for_symbol(
1238 &self,
1239 name: &str,
1240 kind: lsp::SymbolKind,
1241 language: &Arc<language::Language>,
1242 ) -> Option<language::CodeLabel> {
1243 let (text, filter_range, display_range) = match kind {
1244 lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
1245 let text = format!("def {}():\n", name);
1246 let filter_range = 4..4 + name.len();
1247 let display_range = 0..filter_range.end;
1248 (text, filter_range, display_range)
1249 }
1250 lsp::SymbolKind::CLASS => {
1251 let text = format!("class {}:", name);
1252 let filter_range = 6..6 + name.len();
1253 let display_range = 0..filter_range.end;
1254 (text, filter_range, display_range)
1255 }
1256 lsp::SymbolKind::CONSTANT => {
1257 let text = format!("{} = 0", name);
1258 let filter_range = 0..name.len();
1259 let display_range = 0..filter_range.end;
1260 (text, filter_range, display_range)
1261 }
1262 _ => return None,
1263 };
1264
1265 Some(language::CodeLabel {
1266 runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
1267 text: text[display_range].to_string(),
1268 filter_range,
1269 })
1270 }
1271
1272 async fn workspace_configuration(
1273 self: Arc<Self>,
1274 _: &dyn Fs,
1275 adapter: &Arc<dyn LspAdapterDelegate>,
1276 toolchain: Option<Toolchain>,
1277 cx: &mut AsyncApp,
1278 ) -> Result<Value> {
1279 cx.update(move |cx| {
1280 let mut user_settings =
1281 language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
1282 .and_then(|s| s.settings.clone())
1283 .unwrap_or_else(|| {
1284 json!({
1285 "plugins": {
1286 "pycodestyle": {"enabled": false},
1287 "rope_autoimport": {"enabled": true, "memory": true},
1288 "pylsp_mypy": {"enabled": false}
1289 },
1290 "rope": {
1291 "ropeFolder": null
1292 },
1293 })
1294 });
1295
1296 // If user did not explicitly modify their python venv, use one from picker.
1297 if let Some(toolchain) = toolchain {
1298 if user_settings.is_null() {
1299 user_settings = Value::Object(serde_json::Map::default());
1300 }
1301 let object = user_settings.as_object_mut().unwrap();
1302 if let Some(python) = object
1303 .entry("plugins")
1304 .or_insert(Value::Object(serde_json::Map::default()))
1305 .as_object_mut()
1306 {
1307 if let Some(jedi) = python
1308 .entry("jedi")
1309 .or_insert(Value::Object(serde_json::Map::default()))
1310 .as_object_mut()
1311 {
1312 jedi.entry("environment".to_string())
1313 .or_insert_with(|| Value::String(toolchain.path.clone().into()));
1314 }
1315 if let Some(pylint) = python
1316 .entry("pylsp_mypy")
1317 .or_insert(Value::Object(serde_json::Map::default()))
1318 .as_object_mut()
1319 {
1320 pylint.entry("overrides".to_string()).or_insert_with(|| {
1321 Value::Array(vec![
1322 Value::String("--python-executable".into()),
1323 Value::String(toolchain.path.into()),
1324 Value::String("--cache-dir=/dev/null".into()),
1325 Value::Bool(true),
1326 ])
1327 });
1328 }
1329 }
1330 }
1331 user_settings = Value::Object(serde_json::Map::from_iter([(
1332 "pylsp".to_string(),
1333 user_settings,
1334 )]));
1335
1336 user_settings
1337 })
1338 }
1339}
1340
1341pub(crate) struct BasedPyrightLspAdapter {
1342 python_venv_base: OnceCell<Result<Arc<Path>, String>>,
1343}
1344
1345impl BasedPyrightLspAdapter {
1346 const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("basedpyright");
1347 const BINARY_NAME: &'static str = "basedpyright-langserver";
1348
1349 pub(crate) fn new() -> Self {
1350 Self {
1351 python_venv_base: OnceCell::new(),
1352 }
1353 }
1354
1355 async fn ensure_venv(delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>> {
1356 let python_path = Self::find_base_python(delegate)
1357 .await
1358 .context("Could not find Python installation for basedpyright")?;
1359 let work_dir = delegate
1360 .language_server_download_dir(&Self::SERVER_NAME)
1361 .await
1362 .context("Could not get working directory for basedpyright")?;
1363 let mut path = PathBuf::from(work_dir.as_ref());
1364 path.push("basedpyright-venv");
1365 if !path.exists() {
1366 util::command::new_smol_command(python_path)
1367 .arg("-m")
1368 .arg("venv")
1369 .arg("basedpyright-venv")
1370 .current_dir(work_dir)
1371 .spawn()?
1372 .output()
1373 .await?;
1374 }
1375
1376 Ok(path.into())
1377 }
1378
1379 // Find "baseline", user python version from which we'll create our own venv.
1380 async fn find_base_python(delegate: &dyn LspAdapterDelegate) -> Option<PathBuf> {
1381 for path in ["python3", "python"] {
1382 if let Some(path) = delegate.which(path.as_ref()).await {
1383 return Some(path);
1384 }
1385 }
1386 None
1387 }
1388
1389 async fn base_venv(&self, delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>, String> {
1390 self.python_venv_base
1391 .get_or_init(move || async move {
1392 Self::ensure_venv(delegate)
1393 .await
1394 .map_err(|e| format!("{e}"))
1395 })
1396 .await
1397 .clone()
1398 }
1399}
1400
1401#[async_trait(?Send)]
1402impl LspAdapter for BasedPyrightLspAdapter {
1403 fn name(&self) -> LanguageServerName {
1404 Self::SERVER_NAME
1405 }
1406
1407 async fn initialization_options(
1408 self: Arc<Self>,
1409 _: &dyn Fs,
1410 _: &Arc<dyn LspAdapterDelegate>,
1411 ) -> Result<Option<Value>> {
1412 // Provide minimal initialization options
1413 // Virtual environment configuration will be handled through workspace configuration
1414 Ok(Some(json!({
1415 "python": {
1416 "analysis": {
1417 "autoSearchPaths": true,
1418 "useLibraryCodeForTypes": true,
1419 "autoImportCompletions": true
1420 }
1421 }
1422 })))
1423 }
1424
1425 async fn check_if_user_installed(
1426 &self,
1427 delegate: &dyn LspAdapterDelegate,
1428 toolchain: Option<Toolchain>,
1429 _: &AsyncApp,
1430 ) -> Option<LanguageServerBinary> {
1431 if let Some(bin) = delegate.which(Self::BINARY_NAME.as_ref()).await {
1432 let env = delegate.shell_env().await;
1433 Some(LanguageServerBinary {
1434 path: bin,
1435 env: Some(env),
1436 arguments: vec!["--stdio".into()],
1437 })
1438 } else {
1439 let path = Path::new(toolchain?.path.as_ref())
1440 .parent()?
1441 .join(Self::BINARY_NAME);
1442 path.exists().then(|| LanguageServerBinary {
1443 path,
1444 arguments: vec!["--stdio".into()],
1445 env: None,
1446 })
1447 }
1448 }
1449
1450 async fn fetch_latest_server_version(
1451 &self,
1452 _: &dyn LspAdapterDelegate,
1453 _: &AsyncApp,
1454 ) -> Result<Box<dyn 'static + Any + Send>> {
1455 Ok(Box::new(()) as Box<_>)
1456 }
1457
1458 async fn fetch_server_binary(
1459 &self,
1460 _latest_version: Box<dyn 'static + Send + Any>,
1461 _container_dir: PathBuf,
1462 delegate: &dyn LspAdapterDelegate,
1463 ) -> Result<LanguageServerBinary> {
1464 let venv = self.base_venv(delegate).await.map_err(|e| anyhow!(e))?;
1465 let pip_path = venv.join(BINARY_DIR).join("pip3");
1466 ensure!(
1467 util::command::new_smol_command(pip_path.as_path())
1468 .arg("install")
1469 .arg("basedpyright")
1470 .arg("-U")
1471 .output()
1472 .await?
1473 .status
1474 .success(),
1475 "basedpyright installation failed"
1476 );
1477 let pylsp = venv.join(BINARY_DIR).join(Self::BINARY_NAME);
1478 Ok(LanguageServerBinary {
1479 path: pylsp,
1480 env: None,
1481 arguments: vec!["--stdio".into()],
1482 })
1483 }
1484
1485 async fn cached_server_binary(
1486 &self,
1487 _container_dir: PathBuf,
1488 delegate: &dyn LspAdapterDelegate,
1489 ) -> Option<LanguageServerBinary> {
1490 let venv = self.base_venv(delegate).await.ok()?;
1491 let pylsp = venv.join(BINARY_DIR).join(Self::BINARY_NAME);
1492 Some(LanguageServerBinary {
1493 path: pylsp,
1494 env: None,
1495 arguments: vec!["--stdio".into()],
1496 })
1497 }
1498
1499 async fn process_completions(&self, items: &mut [lsp::CompletionItem]) {
1500 process_pyright_completions(items);
1501 }
1502
1503 async fn label_for_completion(
1504 &self,
1505 item: &lsp::CompletionItem,
1506 language: &Arc<language::Language>,
1507 ) -> Option<language::CodeLabel> {
1508 let label = &item.label;
1509 let grammar = language.grammar()?;
1510 let highlight_id = match item.kind? {
1511 lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method"),
1512 lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function"),
1513 lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type"),
1514 lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant"),
1515 lsp::CompletionItemKind::VARIABLE => grammar.highlight_id_for_name("variable"),
1516 _ => {
1517 return None;
1518 }
1519 };
1520 let filter_range = item
1521 .filter_text
1522 .as_deref()
1523 .and_then(|filter| label.find(filter).map(|ix| ix..ix + filter.len()))
1524 .unwrap_or(0..label.len());
1525 let mut text = label.clone();
1526 if let Some(completion_details) = item
1527 .label_details
1528 .as_ref()
1529 .and_then(|details| details.description.as_ref())
1530 {
1531 write!(&mut text, " {}", completion_details).ok();
1532 }
1533 Some(language::CodeLabel {
1534 runs: highlight_id
1535 .map(|id| (0..label.len(), id))
1536 .into_iter()
1537 .collect(),
1538 text,
1539 filter_range,
1540 })
1541 }
1542
1543 async fn label_for_symbol(
1544 &self,
1545 name: &str,
1546 kind: lsp::SymbolKind,
1547 language: &Arc<language::Language>,
1548 ) -> Option<language::CodeLabel> {
1549 let (text, filter_range, display_range) = match kind {
1550 lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
1551 let text = format!("def {}():\n", name);
1552 let filter_range = 4..4 + name.len();
1553 let display_range = 0..filter_range.end;
1554 (text, filter_range, display_range)
1555 }
1556 lsp::SymbolKind::CLASS => {
1557 let text = format!("class {}:", name);
1558 let filter_range = 6..6 + name.len();
1559 let display_range = 0..filter_range.end;
1560 (text, filter_range, display_range)
1561 }
1562 lsp::SymbolKind::CONSTANT => {
1563 let text = format!("{} = 0", name);
1564 let filter_range = 0..name.len();
1565 let display_range = 0..filter_range.end;
1566 (text, filter_range, display_range)
1567 }
1568 _ => return None,
1569 };
1570
1571 Some(language::CodeLabel {
1572 runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
1573 text: text[display_range].to_string(),
1574 filter_range,
1575 })
1576 }
1577
1578 async fn workspace_configuration(
1579 self: Arc<Self>,
1580 _: &dyn Fs,
1581 adapter: &Arc<dyn LspAdapterDelegate>,
1582 toolchain: Option<Toolchain>,
1583 cx: &mut AsyncApp,
1584 ) -> Result<Value> {
1585 cx.update(move |cx| {
1586 let mut user_settings =
1587 language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
1588 .and_then(|s| s.settings.clone())
1589 .unwrap_or_default();
1590
1591 // If we have a detected toolchain, configure Pyright to use it
1592 if let Some(toolchain) = toolchain
1593 && let Ok(env) = serde_json::from_value::<
1594 pet_core::python_environment::PythonEnvironment,
1595 >(toolchain.as_json.clone())
1596 {
1597 if user_settings.is_null() {
1598 user_settings = Value::Object(serde_json::Map::default());
1599 }
1600 let object = user_settings.as_object_mut().unwrap();
1601
1602 let interpreter_path = toolchain.path.to_string();
1603 if let Some(venv_dir) = env.prefix {
1604 // Set venvPath and venv at the root level
1605 // This matches the format of a pyrightconfig.json file
1606 if let Some(parent) = venv_dir.parent() {
1607 // Use relative path if the venv is inside the workspace
1608 let venv_path = if parent == adapter.worktree_root_path() {
1609 ".".to_string()
1610 } else {
1611 parent.to_string_lossy().into_owned()
1612 };
1613 object.insert("venvPath".to_string(), Value::String(venv_path));
1614 }
1615
1616 if let Some(venv_name) = venv_dir.file_name() {
1617 object.insert(
1618 "venv".to_owned(),
1619 Value::String(venv_name.to_string_lossy().into_owned()),
1620 );
1621 }
1622 }
1623
1624 // Set both pythonPath and defaultInterpreterPath for compatibility
1625 if let Some(python) = object
1626 .entry("python")
1627 .or_insert(Value::Object(serde_json::Map::default()))
1628 .as_object_mut()
1629 {
1630 python.insert(
1631 "pythonPath".to_owned(),
1632 Value::String(interpreter_path.clone()),
1633 );
1634 python.insert(
1635 "defaultInterpreterPath".to_owned(),
1636 Value::String(interpreter_path),
1637 );
1638 }
1639 // Basedpyright by default uses `strict` type checking, we tone it down as to not surpris users
1640 maybe!({
1641 let basedpyright = object
1642 .entry("basedpyright")
1643 .or_insert(Value::Object(serde_json::Map::default()));
1644 let analysis = basedpyright
1645 .as_object_mut()?
1646 .entry("analysis")
1647 .or_insert(Value::Object(serde_json::Map::default()));
1648 if let serde_json::map::Entry::Vacant(v) =
1649 analysis.as_object_mut()?.entry("typeCheckingMode")
1650 {
1651 v.insert(Value::String("standard".to_owned()));
1652 }
1653 Some(())
1654 });
1655 }
1656
1657 user_settings
1658 })
1659 }
1660}
1661
1662#[cfg(test)]
1663mod tests {
1664 use gpui::{AppContext as _, BorrowAppContext, Context, TestAppContext};
1665 use language::{AutoindentMode, Buffer, language_settings::AllLanguageSettings};
1666 use settings::SettingsStore;
1667 use std::num::NonZeroU32;
1668
1669 #[gpui::test]
1670 async fn test_python_autoindent(cx: &mut TestAppContext) {
1671 cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
1672 let language = crate::language("python", tree_sitter_python::LANGUAGE.into());
1673 cx.update(|cx| {
1674 let test_settings = SettingsStore::test(cx);
1675 cx.set_global(test_settings);
1676 language::init(cx);
1677 cx.update_global::<SettingsStore, _>(|store, cx| {
1678 store.update_user_settings::<AllLanguageSettings>(cx, |s| {
1679 s.defaults.tab_size = NonZeroU32::new(2);
1680 });
1681 });
1682 });
1683
1684 cx.new(|cx| {
1685 let mut buffer = Buffer::local("", cx).with_language(language, cx);
1686 let append = |buffer: &mut Buffer, text: &str, cx: &mut Context<Buffer>| {
1687 let ix = buffer.len();
1688 buffer.edit([(ix..ix, text)], Some(AutoindentMode::EachLine), cx);
1689 };
1690
1691 // indent after "def():"
1692 append(&mut buffer, "def a():\n", cx);
1693 assert_eq!(buffer.text(), "def a():\n ");
1694
1695 // preserve indent after blank line
1696 append(&mut buffer, "\n ", cx);
1697 assert_eq!(buffer.text(), "def a():\n \n ");
1698
1699 // indent after "if"
1700 append(&mut buffer, "if a:\n ", cx);
1701 assert_eq!(buffer.text(), "def a():\n \n if a:\n ");
1702
1703 // preserve indent after statement
1704 append(&mut buffer, "b()\n", cx);
1705 assert_eq!(buffer.text(), "def a():\n \n if a:\n b()\n ");
1706
1707 // preserve indent after statement
1708 append(&mut buffer, "else", cx);
1709 assert_eq!(buffer.text(), "def a():\n \n if a:\n b()\n else");
1710
1711 // dedent "else""
1712 append(&mut buffer, ":", cx);
1713 assert_eq!(buffer.text(), "def a():\n \n if a:\n b()\n else:");
1714
1715 // indent lines after else
1716 append(&mut buffer, "\n", cx);
1717 assert_eq!(
1718 buffer.text(),
1719 "def a():\n \n if a:\n b()\n else:\n "
1720 );
1721
1722 // indent after an open paren. the closing paren is not indented
1723 // because there is another token before it on the same line.
1724 append(&mut buffer, "foo(\n1)", cx);
1725 assert_eq!(
1726 buffer.text(),
1727 "def a():\n \n if a:\n b()\n else:\n foo(\n 1)"
1728 );
1729
1730 // dedent the closing paren if it is shifted to the beginning of the line
1731 let argument_ix = buffer.text().find('1').unwrap();
1732 buffer.edit(
1733 [(argument_ix..argument_ix + 1, "")],
1734 Some(AutoindentMode::EachLine),
1735 cx,
1736 );
1737 assert_eq!(
1738 buffer.text(),
1739 "def a():\n \n if a:\n b()\n else:\n foo(\n )"
1740 );
1741
1742 // preserve indent after the close paren
1743 append(&mut buffer, "\n", cx);
1744 assert_eq!(
1745 buffer.text(),
1746 "def a():\n \n if a:\n b()\n else:\n foo(\n )\n "
1747 );
1748
1749 // manually outdent the last line
1750 let end_whitespace_ix = buffer.len() - 4;
1751 buffer.edit(
1752 [(end_whitespace_ix..buffer.len(), "")],
1753 Some(AutoindentMode::EachLine),
1754 cx,
1755 );
1756 assert_eq!(
1757 buffer.text(),
1758 "def a():\n \n if a:\n b()\n else:\n foo(\n )\n"
1759 );
1760
1761 // preserve the newly reduced indentation on the next newline
1762 append(&mut buffer, "\n", cx);
1763 assert_eq!(
1764 buffer.text(),
1765 "def a():\n \n if a:\n b()\n else:\n foo(\n )\n\n"
1766 );
1767
1768 // reset to a simple if statement
1769 buffer.edit([(0..buffer.len(), "if a:\n b(\n )")], None, cx);
1770
1771 // dedent "else" on the line after a closing paren
1772 append(&mut buffer, "\n else:\n", cx);
1773 assert_eq!(buffer.text(), "if a:\n b(\n )\nelse:\n ");
1774
1775 buffer
1776 });
1777 }
1778}