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