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