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