1use anyhow::{Context as _, ensure};
2use anyhow::{Result, anyhow};
3use async_trait::async_trait;
4use collections::HashMap;
5use gpui::{App, Task};
6use gpui::{AsyncApp, SharedString};
7use language::Toolchain;
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 lsp::LanguageServerBinary;
15use lsp::LanguageServerName;
16use node_runtime::NodeRuntime;
17use pet_core::Configuration;
18use pet_core::os_environment::Environment;
19use pet_core::python_environment::PythonEnvironmentKind;
20use project::Fs;
21use project::lsp_store::language_server_settings;
22use serde_json::{Value, json};
23use smol::lock::OnceCell;
24use std::cmp::Ordering;
25
26use parking_lot::Mutex;
27use std::str::FromStr;
28use std::{
29 any::Any,
30 borrow::Cow,
31 ffi::OsString,
32 fmt::Write,
33 fs,
34 io::{self, BufRead},
35 path::{Path, PathBuf},
36 sync::Arc,
37};
38use task::{TaskTemplate, TaskTemplates, VariableName};
39use util::ResultExt;
40
41pub(crate) struct PyprojectTomlManifestProvider;
42
43impl ManifestProvider for PyprojectTomlManifestProvider {
44 fn name(&self) -> ManifestName {
45 SharedString::new_static("pyproject.toml").into()
46 }
47
48 fn search(
49 &self,
50 ManifestQuery {
51 path,
52 depth,
53 delegate,
54 }: ManifestQuery,
55 ) -> Option<Arc<Path>> {
56 for path in path.ancestors().take(depth) {
57 let p = path.join("pyproject.toml");
58 if delegate.exists(&p, Some(false)) {
59 return Some(path.into());
60 }
61 }
62
63 None
64 }
65}
66
67const SERVER_PATH: &str = "node_modules/pyright/langserver.index.js";
68const NODE_MODULE_RELATIVE_SERVER_PATH: &str = "pyright/langserver.index.js";
69
70enum TestRunner {
71 UNITTEST,
72 PYTEST,
73}
74
75impl FromStr for TestRunner {
76 type Err = ();
77
78 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
79 match s {
80 "unittest" => Ok(Self::UNITTEST),
81 "pytest" => Ok(Self::PYTEST),
82 _ => Err(()),
83 }
84 }
85}
86
87fn server_binary_arguments(server_path: &Path) -> Vec<OsString> {
88 vec![server_path.into(), "--stdio".into()]
89}
90
91pub struct PythonLspAdapter {
92 node: NodeRuntime,
93}
94
95impl PythonLspAdapter {
96 const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("pyright");
97
98 pub fn new(node: NodeRuntime) -> Self {
99 PythonLspAdapter { node }
100 }
101}
102
103#[async_trait(?Send)]
104impl LspAdapter for PythonLspAdapter {
105 fn name(&self) -> LanguageServerName {
106 Self::SERVER_NAME.clone()
107 }
108
109 async fn check_if_user_installed(
110 &self,
111 delegate: &dyn LspAdapterDelegate,
112 _: Arc<dyn LanguageToolchainStore>,
113 _: &AsyncApp,
114 ) -> Option<LanguageServerBinary> {
115 if let Some(pyright_bin) = delegate.which("pyright-langserver".as_ref()).await {
116 let env = delegate.shell_env().await;
117 Some(LanguageServerBinary {
118 path: pyright_bin,
119 env: Some(env),
120 arguments: vec!["--stdio".into()],
121 })
122 } else {
123 let node = delegate.which("node".as_ref()).await?;
124 let (node_modules_path, _) = delegate
125 .npm_package_installed_version(Self::SERVER_NAME.as_ref())
126 .await
127 .log_err()??;
128
129 let path = node_modules_path.join(NODE_MODULE_RELATIVE_SERVER_PATH);
130
131 Some(LanguageServerBinary {
132 path: node,
133 env: None,
134 arguments: server_binary_arguments(&path),
135 })
136 }
137 }
138
139 async fn fetch_latest_server_version(
140 &self,
141 _: &dyn LspAdapterDelegate,
142 ) -> Result<Box<dyn 'static + Any + Send>> {
143 Ok(Box::new(
144 self.node
145 .npm_package_latest_version(Self::SERVER_NAME.as_ref())
146 .await?,
147 ) as Box<_>)
148 }
149
150 async fn fetch_server_binary(
151 &self,
152 latest_version: Box<dyn 'static + Send + Any>,
153 container_dir: PathBuf,
154 _: &dyn LspAdapterDelegate,
155 ) -> Result<LanguageServerBinary> {
156 let latest_version = latest_version.downcast::<String>().unwrap();
157 let server_path = container_dir.join(SERVER_PATH);
158
159 self.node
160 .npm_install_packages(
161 &container_dir,
162 &[(Self::SERVER_NAME.as_ref(), latest_version.as_str())],
163 )
164 .await?;
165
166 Ok(LanguageServerBinary {
167 path: self.node.binary_path().await?,
168 env: None,
169 arguments: server_binary_arguments(&server_path),
170 })
171 }
172
173 async fn check_if_version_installed(
174 &self,
175 version: &(dyn 'static + Send + Any),
176 container_dir: &PathBuf,
177 _: &dyn LspAdapterDelegate,
178 ) -> Option<LanguageServerBinary> {
179 let version = version.downcast_ref::<String>().unwrap();
180 let server_path = container_dir.join(SERVER_PATH);
181
182 let should_install_language_server = self
183 .node
184 .should_install_npm_package(
185 Self::SERVER_NAME.as_ref(),
186 &server_path,
187 &container_dir,
188 &version,
189 )
190 .await;
191
192 if should_install_language_server {
193 None
194 } else {
195 Some(LanguageServerBinary {
196 path: self.node.binary_path().await.ok()?,
197 env: None,
198 arguments: server_binary_arguments(&server_path),
199 })
200 }
201 }
202
203 async fn cached_server_binary(
204 &self,
205 container_dir: PathBuf,
206 _: &dyn LspAdapterDelegate,
207 ) -> Option<LanguageServerBinary> {
208 get_cached_server_binary(container_dir, &self.node).await
209 }
210
211 async fn process_completions(&self, items: &mut [lsp::CompletionItem]) {
212 // Pyright assigns each completion item a `sortText` of the form `XX.YYYY.name`.
213 // Where `XX` is the sorting category, `YYYY` is based on most recent usage,
214 // and `name` is the symbol name itself.
215 //
216 // Because the symbol name is included, there generally are not ties when
217 // sorting by the `sortText`, so the symbol's fuzzy match score is not taken
218 // into account. Here, we remove the symbol name from the sortText in order
219 // to allow our own fuzzy score to be used to break ties.
220 //
221 // see https://github.com/microsoft/pyright/blob/95ef4e103b9b2f129c9320427e51b73ea7cf78bd/packages/pyright-internal/src/languageService/completionProvider.ts#LL2873
222 for item in items {
223 let Some(sort_text) = &mut item.sort_text else {
224 continue;
225 };
226 let mut parts = sort_text.split('.');
227 let Some(first) = parts.next() else { continue };
228 let Some(second) = parts.next() else { continue };
229 let Some(_) = parts.next() else { continue };
230 sort_text.replace_range(first.len() + second.len() + 1.., "");
231 }
232 }
233
234 async fn label_for_completion(
235 &self,
236 item: &lsp::CompletionItem,
237 language: &Arc<language::Language>,
238 ) -> Option<language::CodeLabel> {
239 let label = &item.label;
240 let grammar = language.grammar()?;
241 let highlight_id = match item.kind? {
242 lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method")?,
243 lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function")?,
244 lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type")?,
245 lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant")?,
246 _ => return None,
247 };
248 Some(language::CodeLabel {
249 text: label.clone(),
250 runs: vec![(0..label.len(), highlight_id)],
251 filter_range: 0..label.len(),
252 })
253 }
254
255 async fn label_for_symbol(
256 &self,
257 name: &str,
258 kind: lsp::SymbolKind,
259 language: &Arc<language::Language>,
260 ) -> Option<language::CodeLabel> {
261 let (text, filter_range, display_range) = match kind {
262 lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
263 let text = format!("def {}():\n", name);
264 let filter_range = 4..4 + name.len();
265 let display_range = 0..filter_range.end;
266 (text, filter_range, display_range)
267 }
268 lsp::SymbolKind::CLASS => {
269 let text = format!("class {}:", name);
270 let filter_range = 6..6 + name.len();
271 let display_range = 0..filter_range.end;
272 (text, filter_range, display_range)
273 }
274 lsp::SymbolKind::CONSTANT => {
275 let text = format!("{} = 0", name);
276 let filter_range = 0..name.len();
277 let display_range = 0..filter_range.end;
278 (text, filter_range, display_range)
279 }
280 _ => return None,
281 };
282
283 Some(language::CodeLabel {
284 runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
285 text: text[display_range].to_string(),
286 filter_range,
287 })
288 }
289
290 async fn workspace_configuration(
291 self: Arc<Self>,
292 _: &dyn Fs,
293 adapter: &Arc<dyn LspAdapterDelegate>,
294 toolchains: Arc<dyn LanguageToolchainStore>,
295 cx: &mut AsyncApp,
296 ) -> Result<Value> {
297 let toolchain = toolchains
298 .active_toolchain(
299 adapter.worktree_id(),
300 Arc::from("".as_ref()),
301 LanguageName::new("Python"),
302 cx,
303 )
304 .await;
305 cx.update(move |cx| {
306 let mut user_settings =
307 language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
308 .and_then(|s| s.settings.clone())
309 .unwrap_or_default();
310
311 // If python.pythonPath is not set in user config, do so using our toolchain picker.
312 if let Some(toolchain) = toolchain {
313 if user_settings.is_null() {
314 user_settings = Value::Object(serde_json::Map::default());
315 }
316 let object = user_settings.as_object_mut().unwrap();
317 if let Some(python) = object
318 .entry("python")
319 .or_insert(Value::Object(serde_json::Map::default()))
320 .as_object_mut()
321 {
322 python
323 .entry("pythonPath")
324 .or_insert(Value::String(toolchain.path.into()));
325 }
326 }
327 user_settings
328 })
329 }
330 fn manifest_name(&self) -> Option<ManifestName> {
331 Some(SharedString::new_static("pyproject.toml").into())
332 }
333}
334
335async fn get_cached_server_binary(
336 container_dir: PathBuf,
337 node: &NodeRuntime,
338) -> Option<LanguageServerBinary> {
339 let server_path = container_dir.join(SERVER_PATH);
340 if server_path.exists() {
341 Some(LanguageServerBinary {
342 path: node.binary_path().await.log_err()?,
343 env: None,
344 arguments: server_binary_arguments(&server_path),
345 })
346 } else {
347 log::error!("missing executable in directory {:?}", server_path);
348 None
349 }
350}
351
352pub(crate) struct PythonContextProvider;
353
354const PYTHON_TEST_TARGET_TASK_VARIABLE: VariableName =
355 VariableName::Custom(Cow::Borrowed("PYTHON_TEST_TARGET"));
356
357const PYTHON_ACTIVE_TOOLCHAIN_PATH: VariableName =
358 VariableName::Custom(Cow::Borrowed("PYTHON_ACTIVE_ZED_TOOLCHAIN"));
359
360const PYTHON_ACTIVE_TOOLCHAIN_PATH_RAW: VariableName =
361 VariableName::Custom(Cow::Borrowed("PYTHON_ACTIVE_ZED_TOOLCHAIN_RAW"));
362
363const PYTHON_MODULE_NAME_TASK_VARIABLE: VariableName =
364 VariableName::Custom(Cow::Borrowed("PYTHON_MODULE_NAME"));
365
366impl ContextProvider for PythonContextProvider {
367 fn build_context(
368 &self,
369 variables: &task::TaskVariables,
370 location: ContextLocation<'_>,
371 _: Option<HashMap<String, String>>,
372 toolchains: Arc<dyn LanguageToolchainStore>,
373 cx: &mut gpui::App,
374 ) -> Task<Result<task::TaskVariables>> {
375 let test_target =
376 match selected_test_runner(location.file_location.buffer.read(cx).file(), cx) {
377 TestRunner::UNITTEST => self.build_unittest_target(variables),
378 TestRunner::PYTEST => self.build_pytest_target(variables),
379 };
380
381 let module_target = self.build_module_target(variables);
382 let worktree_id = location
383 .file_location
384 .buffer
385 .read(cx)
386 .file()
387 .map(|f| f.worktree_id(cx));
388
389 cx.spawn(async move |cx| {
390 let raw_toolchain = if let Some(worktree_id) = worktree_id {
391 toolchains
392 .active_toolchain(worktree_id, Arc::from("".as_ref()), "Python".into(), cx)
393 .await
394 .map_or_else(
395 || String::from("python3"),
396 |toolchain| toolchain.path.to_string(),
397 )
398 } else {
399 String::from("python3")
400 };
401 let active_toolchain = format!("\"{raw_toolchain}\"");
402 let toolchain = (PYTHON_ACTIVE_TOOLCHAIN_PATH, active_toolchain);
403 let raw_toolchain = (PYTHON_ACTIVE_TOOLCHAIN_PATH_RAW, raw_toolchain);
404 Ok(task::TaskVariables::from_iter(
405 test_target
406 .into_iter()
407 .chain(module_target.into_iter())
408 .chain([toolchain, raw_toolchain]),
409 ))
410 })
411 }
412
413 fn associated_tasks(
414 &self,
415 file: Option<Arc<dyn language::File>>,
416 cx: &App,
417 ) -> Option<TaskTemplates> {
418 let test_runner = selected_test_runner(file.as_ref(), cx);
419
420 let mut tasks = vec![
421 // Execute a selection
422 TaskTemplate {
423 label: "execute selection".to_owned(),
424 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
425 args: vec![
426 "-c".to_owned(),
427 VariableName::SelectedText.template_value_with_whitespace(),
428 ],
429 cwd: Some("$ZED_WORKTREE_ROOT".into()),
430 ..TaskTemplate::default()
431 },
432 // Execute an entire file
433 TaskTemplate {
434 label: format!("run '{}'", VariableName::File.template_value()),
435 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
436 args: vec![VariableName::File.template_value_with_whitespace()],
437 cwd: Some("$ZED_WORKTREE_ROOT".into()),
438 ..TaskTemplate::default()
439 },
440 // Execute a file as module
441 TaskTemplate {
442 label: format!("run module '{}'", VariableName::File.template_value()),
443 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
444 args: vec![
445 "-m".to_owned(),
446 PYTHON_MODULE_NAME_TASK_VARIABLE.template_value(),
447 ],
448 cwd: Some("$ZED_WORKTREE_ROOT".into()),
449 tags: vec!["python-module-main-method".to_owned()],
450 ..TaskTemplate::default()
451 },
452 ];
453
454 tasks.extend(match test_runner {
455 TestRunner::UNITTEST => {
456 [
457 // Run tests for an entire file
458 TaskTemplate {
459 label: format!("unittest '{}'", VariableName::File.template_value()),
460 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
461 args: vec![
462 "-m".to_owned(),
463 "unittest".to_owned(),
464 VariableName::File.template_value_with_whitespace(),
465 ],
466 cwd: Some("$ZED_WORKTREE_ROOT".into()),
467 ..TaskTemplate::default()
468 },
469 // Run test(s) for a specific target within a file
470 TaskTemplate {
471 label: "unittest $ZED_CUSTOM_PYTHON_TEST_TARGET".to_owned(),
472 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
473 args: vec![
474 "-m".to_owned(),
475 "unittest".to_owned(),
476 PYTHON_TEST_TARGET_TASK_VARIABLE.template_value_with_whitespace(),
477 ],
478 tags: vec![
479 "python-unittest-class".to_owned(),
480 "python-unittest-method".to_owned(),
481 ],
482 cwd: Some("$ZED_WORKTREE_ROOT".into()),
483 ..TaskTemplate::default()
484 },
485 ]
486 }
487 TestRunner::PYTEST => {
488 [
489 // Run tests for an entire file
490 TaskTemplate {
491 label: format!("pytest '{}'", VariableName::File.template_value()),
492 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
493 args: vec![
494 "-m".to_owned(),
495 "pytest".to_owned(),
496 VariableName::File.template_value_with_whitespace(),
497 ],
498 cwd: Some("$ZED_WORKTREE_ROOT".into()),
499 ..TaskTemplate::default()
500 },
501 // Run test(s) for a specific target within a file
502 TaskTemplate {
503 label: "pytest $ZED_CUSTOM_PYTHON_TEST_TARGET".to_owned(),
504 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
505 args: vec![
506 "-m".to_owned(),
507 "pytest".to_owned(),
508 PYTHON_TEST_TARGET_TASK_VARIABLE.template_value_with_whitespace(),
509 ],
510 cwd: Some("$ZED_WORKTREE_ROOT".into()),
511 tags: vec![
512 "python-pytest-class".to_owned(),
513 "python-pytest-method".to_owned(),
514 ],
515 ..TaskTemplate::default()
516 },
517 ]
518 }
519 });
520
521 Some(TaskTemplates(tasks))
522 }
523}
524
525fn selected_test_runner(location: Option<&Arc<dyn language::File>>, cx: &App) -> TestRunner {
526 const TEST_RUNNER_VARIABLE: &str = "TEST_RUNNER";
527 language_settings(Some(LanguageName::new("Python")), location, cx)
528 .tasks
529 .variables
530 .get(TEST_RUNNER_VARIABLE)
531 .and_then(|val| TestRunner::from_str(val).ok())
532 .unwrap_or(TestRunner::PYTEST)
533}
534
535impl PythonContextProvider {
536 fn build_unittest_target(
537 &self,
538 variables: &task::TaskVariables,
539 ) -> Option<(VariableName, String)> {
540 let python_module_name =
541 python_module_name_from_relative_path(variables.get(&VariableName::RelativeFile)?);
542
543 let unittest_class_name =
544 variables.get(&VariableName::Custom(Cow::Borrowed("_unittest_class_name")));
545
546 let unittest_method_name = variables.get(&VariableName::Custom(Cow::Borrowed(
547 "_unittest_method_name",
548 )));
549
550 let unittest_target_str = match (unittest_class_name, unittest_method_name) {
551 (Some(class_name), Some(method_name)) => {
552 format!("{python_module_name}.{class_name}.{method_name}")
553 }
554 (Some(class_name), None) => format!("{python_module_name}.{class_name}"),
555 (None, None) => python_module_name,
556 // should never happen, a TestCase class is the unit of testing
557 (None, Some(_)) => return None,
558 };
559
560 Some((
561 PYTHON_TEST_TARGET_TASK_VARIABLE.clone(),
562 unittest_target_str,
563 ))
564 }
565
566 fn build_pytest_target(
567 &self,
568 variables: &task::TaskVariables,
569 ) -> Option<(VariableName, String)> {
570 let file_path = variables.get(&VariableName::RelativeFile)?;
571
572 let pytest_class_name =
573 variables.get(&VariableName::Custom(Cow::Borrowed("_pytest_class_name")));
574
575 let pytest_method_name =
576 variables.get(&VariableName::Custom(Cow::Borrowed("_pytest_method_name")));
577
578 let pytest_target_str = match (pytest_class_name, pytest_method_name) {
579 (Some(class_name), Some(method_name)) => {
580 format!("{file_path}::{class_name}::{method_name}")
581 }
582 (Some(class_name), None) => {
583 format!("{file_path}::{class_name}")
584 }
585 (None, Some(method_name)) => {
586 format!("{file_path}::{method_name}")
587 }
588 (None, None) => file_path.to_string(),
589 };
590
591 Some((PYTHON_TEST_TARGET_TASK_VARIABLE.clone(), pytest_target_str))
592 }
593
594 fn build_module_target(
595 &self,
596 variables: &task::TaskVariables,
597 ) -> Result<(VariableName, String)> {
598 let python_module_name = python_module_name_from_relative_path(
599 variables.get(&VariableName::RelativeFile).unwrap_or(""),
600 );
601
602 let module_target = (PYTHON_MODULE_NAME_TASK_VARIABLE.clone(), python_module_name);
603
604 Ok(module_target)
605 }
606}
607
608fn python_module_name_from_relative_path(relative_path: &str) -> String {
609 let path_with_dots = relative_path.replace('/', ".");
610 path_with_dots
611 .strip_suffix(".py")
612 .unwrap_or(&path_with_dots)
613 .to_string()
614}
615
616fn python_env_kind_display(k: &PythonEnvironmentKind) -> &'static str {
617 match k {
618 PythonEnvironmentKind::Conda => "Conda",
619 PythonEnvironmentKind::Pixi => "pixi",
620 PythonEnvironmentKind::Homebrew => "Homebrew",
621 PythonEnvironmentKind::Pyenv => "global (Pyenv)",
622 PythonEnvironmentKind::GlobalPaths => "global",
623 PythonEnvironmentKind::PyenvVirtualEnv => "Pyenv",
624 PythonEnvironmentKind::Pipenv => "Pipenv",
625 PythonEnvironmentKind::Poetry => "Poetry",
626 PythonEnvironmentKind::MacPythonOrg => "global (Python.org)",
627 PythonEnvironmentKind::MacCommandLineTools => "global (Command Line Tools for Xcode)",
628 PythonEnvironmentKind::LinuxGlobal => "global",
629 PythonEnvironmentKind::MacXCode => "global (Xcode)",
630 PythonEnvironmentKind::Venv => "venv",
631 PythonEnvironmentKind::VirtualEnv => "virtualenv",
632 PythonEnvironmentKind::VirtualEnvWrapper => "virtualenvwrapper",
633 PythonEnvironmentKind::WindowsStore => "global (Windows Store)",
634 PythonEnvironmentKind::WindowsRegistry => "global (Windows Registry)",
635 }
636}
637
638pub(crate) struct PythonToolchainProvider {
639 term: SharedString,
640}
641
642impl Default for PythonToolchainProvider {
643 fn default() -> Self {
644 Self {
645 term: SharedString::new_static("Virtual Environment"),
646 }
647 }
648}
649
650static ENV_PRIORITY_LIST: &'static [PythonEnvironmentKind] = &[
651 // Prioritize non-Conda environments.
652 PythonEnvironmentKind::Poetry,
653 PythonEnvironmentKind::Pipenv,
654 PythonEnvironmentKind::VirtualEnvWrapper,
655 PythonEnvironmentKind::Venv,
656 PythonEnvironmentKind::VirtualEnv,
657 PythonEnvironmentKind::PyenvVirtualEnv,
658 PythonEnvironmentKind::Pixi,
659 PythonEnvironmentKind::Conda,
660 PythonEnvironmentKind::Pyenv,
661 PythonEnvironmentKind::GlobalPaths,
662 PythonEnvironmentKind::Homebrew,
663];
664
665fn env_priority(kind: Option<PythonEnvironmentKind>) -> usize {
666 if let Some(kind) = kind {
667 ENV_PRIORITY_LIST
668 .iter()
669 .position(|blessed_env| blessed_env == &kind)
670 .unwrap_or(ENV_PRIORITY_LIST.len())
671 } else {
672 // Unknown toolchains are less useful than non-blessed ones.
673 ENV_PRIORITY_LIST.len() + 1
674 }
675}
676
677/// Return the name of environment declared in <worktree-root/.venv.
678///
679/// https://virtualfish.readthedocs.io/en/latest/plugins.html#auto-activation-auto-activation
680fn get_worktree_venv_declaration(worktree_root: &Path) -> Option<String> {
681 fs::File::open(worktree_root.join(".venv"))
682 .and_then(|file| {
683 let mut venv_name = String::new();
684 io::BufReader::new(file).read_line(&mut venv_name)?;
685 Ok(venv_name.trim().to_string())
686 })
687 .ok()
688}
689
690#[async_trait]
691impl ToolchainLister for PythonToolchainProvider {
692 async fn list(
693 &self,
694 worktree_root: PathBuf,
695 project_env: Option<HashMap<String, String>>,
696 ) -> ToolchainList {
697 let env = project_env.unwrap_or_default();
698 let environment = EnvironmentApi::from_env(&env);
699 let locators = pet::locators::create_locators(
700 Arc::new(pet_conda::Conda::from(&environment)),
701 Arc::new(pet_poetry::Poetry::from(&environment)),
702 &environment,
703 );
704 let mut config = Configuration::default();
705 config.workspace_directories = Some(vec![worktree_root.clone()]);
706 for locator in locators.iter() {
707 locator.configure(&config);
708 }
709
710 let reporter = pet_reporter::collect::create_reporter();
711 pet::find::find_and_report_envs(&reporter, config, &locators, &environment, None);
712
713 let mut toolchains = reporter
714 .environments
715 .lock()
716 .map_or(Vec::new(), |mut guard| std::mem::take(&mut guard));
717
718 let wr = worktree_root;
719 let wr_venv = get_worktree_venv_declaration(&wr);
720 // Sort detected environments by:
721 // environment name matching activation file (<workdir>/.venv)
722 // environment project dir matching worktree_root
723 // general env priority
724 // environment path matching the CONDA_PREFIX env var
725 // executable path
726 toolchains.sort_by(|lhs, rhs| {
727 // Compare venv names against worktree .venv file
728 let venv_ordering =
729 wr_venv
730 .as_ref()
731 .map_or(Ordering::Equal, |venv| match (&lhs.name, &rhs.name) {
732 (Some(l), Some(r)) => (r == venv).cmp(&(l == venv)),
733 (Some(l), None) if l == venv => Ordering::Less,
734 (None, Some(r)) if r == venv => Ordering::Greater,
735 _ => Ordering::Equal,
736 });
737
738 // Compare project paths against worktree root
739 let proj_ordering = || match (&lhs.project, &rhs.project) {
740 (Some(l), Some(r)) => (r == &wr).cmp(&(l == &wr)),
741 (Some(l), None) if l == &wr => Ordering::Less,
742 (None, Some(r)) if r == &wr => Ordering::Greater,
743 _ => Ordering::Equal,
744 };
745
746 // Compare environment priorities
747 let priority_ordering = || env_priority(lhs.kind).cmp(&env_priority(rhs.kind));
748
749 // Compare conda prefixes
750 let conda_ordering = || {
751 if lhs.kind == Some(PythonEnvironmentKind::Conda) {
752 environment
753 .get_env_var("CONDA_PREFIX".to_string())
754 .map(|conda_prefix| {
755 let is_match = |exe: &Option<PathBuf>| {
756 exe.as_ref().map_or(false, |e| e.starts_with(&conda_prefix))
757 };
758 match (is_match(&lhs.executable), is_match(&rhs.executable)) {
759 (true, false) => Ordering::Less,
760 (false, true) => Ordering::Greater,
761 _ => Ordering::Equal,
762 }
763 })
764 .unwrap_or(Ordering::Equal)
765 } else {
766 Ordering::Equal
767 }
768 };
769
770 // Compare Python executables
771 let exe_ordering = || lhs.executable.cmp(&rhs.executable);
772
773 venv_ordering
774 .then_with(proj_ordering)
775 .then_with(priority_ordering)
776 .then_with(conda_ordering)
777 .then_with(exe_ordering)
778 });
779
780 let mut toolchains: Vec<_> = toolchains
781 .into_iter()
782 .filter_map(|toolchain| {
783 let mut name = String::from("Python");
784 if let Some(ref version) = toolchain.version {
785 _ = write!(name, " {version}");
786 }
787
788 let name_and_kind = match (&toolchain.name, &toolchain.kind) {
789 (Some(name), Some(kind)) => {
790 Some(format!("({name}; {})", python_env_kind_display(kind)))
791 }
792 (Some(name), None) => Some(format!("({name})")),
793 (None, Some(kind)) => Some(format!("({})", python_env_kind_display(kind))),
794 (None, None) => None,
795 };
796
797 if let Some(nk) = name_and_kind {
798 _ = write!(name, " {nk}");
799 }
800
801 Some(Toolchain {
802 name: name.into(),
803 path: toolchain.executable.as_ref()?.to_str()?.to_owned().into(),
804 language_name: LanguageName::new("Python"),
805 as_json: serde_json::to_value(toolchain).ok()?,
806 })
807 })
808 .collect();
809 toolchains.dedup();
810 ToolchainList {
811 toolchains,
812 default: None,
813 groups: Default::default(),
814 }
815 }
816 fn term(&self) -> SharedString {
817 self.term.clone()
818 }
819}
820
821pub struct EnvironmentApi<'a> {
822 global_search_locations: Arc<Mutex<Vec<PathBuf>>>,
823 project_env: &'a HashMap<String, String>,
824 pet_env: pet_core::os_environment::EnvironmentApi,
825}
826
827impl<'a> EnvironmentApi<'a> {
828 pub fn from_env(project_env: &'a HashMap<String, String>) -> Self {
829 let paths = project_env
830 .get("PATH")
831 .map(|p| std::env::split_paths(p).collect())
832 .unwrap_or_default();
833
834 EnvironmentApi {
835 global_search_locations: Arc::new(Mutex::new(paths)),
836 project_env,
837 pet_env: pet_core::os_environment::EnvironmentApi::new(),
838 }
839 }
840
841 fn user_home(&self) -> Option<PathBuf> {
842 self.project_env
843 .get("HOME")
844 .or_else(|| self.project_env.get("USERPROFILE"))
845 .map(|home| pet_fs::path::norm_case(PathBuf::from(home)))
846 .or_else(|| self.pet_env.get_user_home())
847 }
848}
849
850impl pet_core::os_environment::Environment for EnvironmentApi<'_> {
851 fn get_user_home(&self) -> Option<PathBuf> {
852 self.user_home()
853 }
854
855 fn get_root(&self) -> Option<PathBuf> {
856 None
857 }
858
859 fn get_env_var(&self, key: String) -> Option<String> {
860 self.project_env
861 .get(&key)
862 .cloned()
863 .or_else(|| self.pet_env.get_env_var(key))
864 }
865
866 fn get_know_global_search_locations(&self) -> Vec<PathBuf> {
867 if self.global_search_locations.lock().is_empty() {
868 let mut paths =
869 std::env::split_paths(&self.get_env_var("PATH".to_string()).unwrap_or_default())
870 .collect::<Vec<PathBuf>>();
871
872 log::trace!("Env PATH: {:?}", paths);
873 for p in self.pet_env.get_know_global_search_locations() {
874 if !paths.contains(&p) {
875 paths.push(p);
876 }
877 }
878
879 let mut paths = paths
880 .into_iter()
881 .filter(|p| p.exists())
882 .collect::<Vec<PathBuf>>();
883
884 self.global_search_locations.lock().append(&mut paths);
885 }
886 self.global_search_locations.lock().clone()
887 }
888}
889
890pub(crate) struct PyLspAdapter {
891 python_venv_base: OnceCell<Result<Arc<Path>, String>>,
892}
893impl PyLspAdapter {
894 const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("pylsp");
895 pub(crate) fn new() -> Self {
896 Self {
897 python_venv_base: OnceCell::new(),
898 }
899 }
900 async fn ensure_venv(delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>> {
901 let python_path = Self::find_base_python(delegate)
902 .await
903 .context("Could not find Python installation for PyLSP")?;
904 let work_dir = delegate
905 .language_server_download_dir(&Self::SERVER_NAME)
906 .await
907 .context("Could not get working directory for PyLSP")?;
908 let mut path = PathBuf::from(work_dir.as_ref());
909 path.push("pylsp-venv");
910 if !path.exists() {
911 util::command::new_smol_command(python_path)
912 .arg("-m")
913 .arg("venv")
914 .arg("pylsp-venv")
915 .current_dir(work_dir)
916 .spawn()?
917 .output()
918 .await?;
919 }
920
921 Ok(path.into())
922 }
923 // Find "baseline", user python version from which we'll create our own venv.
924 async fn find_base_python(delegate: &dyn LspAdapterDelegate) -> Option<PathBuf> {
925 for path in ["python3", "python"] {
926 if let Some(path) = delegate.which(path.as_ref()).await {
927 return Some(path);
928 }
929 }
930 None
931 }
932
933 async fn base_venv(&self, delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>, String> {
934 self.python_venv_base
935 .get_or_init(move || async move {
936 Self::ensure_venv(delegate)
937 .await
938 .map_err(|e| format!("{e}"))
939 })
940 .await
941 .clone()
942 }
943}
944
945const BINARY_DIR: &str = if cfg!(target_os = "windows") {
946 "Scripts"
947} else {
948 "bin"
949};
950
951#[async_trait(?Send)]
952impl LspAdapter for PyLspAdapter {
953 fn name(&self) -> LanguageServerName {
954 Self::SERVER_NAME.clone()
955 }
956
957 async fn check_if_user_installed(
958 &self,
959 delegate: &dyn LspAdapterDelegate,
960 toolchains: Arc<dyn LanguageToolchainStore>,
961 cx: &AsyncApp,
962 ) -> Option<LanguageServerBinary> {
963 if let Some(pylsp_bin) = delegate.which(Self::SERVER_NAME.as_ref()).await {
964 let env = delegate.shell_env().await;
965 Some(LanguageServerBinary {
966 path: pylsp_bin,
967 env: Some(env),
968 arguments: vec![],
969 })
970 } else {
971 let venv = toolchains
972 .active_toolchain(
973 delegate.worktree_id(),
974 Arc::from("".as_ref()),
975 LanguageName::new("Python"),
976 &mut cx.clone(),
977 )
978 .await?;
979 let pylsp_path = Path::new(venv.path.as_ref()).parent()?.join("pylsp");
980 pylsp_path.exists().then(|| LanguageServerBinary {
981 path: venv.path.to_string().into(),
982 arguments: vec![pylsp_path.into()],
983 env: None,
984 })
985 }
986 }
987
988 async fn fetch_latest_server_version(
989 &self,
990 _: &dyn LspAdapterDelegate,
991 ) -> Result<Box<dyn 'static + Any + Send>> {
992 Ok(Box::new(()) as Box<_>)
993 }
994
995 async fn fetch_server_binary(
996 &self,
997 _: Box<dyn 'static + Send + Any>,
998 _: PathBuf,
999 delegate: &dyn LspAdapterDelegate,
1000 ) -> Result<LanguageServerBinary> {
1001 let venv = self.base_venv(delegate).await.map_err(|e| anyhow!(e))?;
1002 let pip_path = venv.join(BINARY_DIR).join("pip3");
1003 ensure!(
1004 util::command::new_smol_command(pip_path.as_path())
1005 .arg("install")
1006 .arg("python-lsp-server")
1007 .arg("-U")
1008 .output()
1009 .await?
1010 .status
1011 .success(),
1012 "python-lsp-server installation failed"
1013 );
1014 ensure!(
1015 util::command::new_smol_command(pip_path.as_path())
1016 .arg("install")
1017 .arg("python-lsp-server[all]")
1018 .arg("-U")
1019 .output()
1020 .await?
1021 .status
1022 .success(),
1023 "python-lsp-server[all] installation failed"
1024 );
1025 ensure!(
1026 util::command::new_smol_command(pip_path)
1027 .arg("install")
1028 .arg("pylsp-mypy")
1029 .arg("-U")
1030 .output()
1031 .await?
1032 .status
1033 .success(),
1034 "pylsp-mypy installation failed"
1035 );
1036 let pylsp = venv.join(BINARY_DIR).join("pylsp");
1037 Ok(LanguageServerBinary {
1038 path: pylsp,
1039 env: None,
1040 arguments: vec![],
1041 })
1042 }
1043
1044 async fn cached_server_binary(
1045 &self,
1046 _: PathBuf,
1047 delegate: &dyn LspAdapterDelegate,
1048 ) -> Option<LanguageServerBinary> {
1049 let venv = self.base_venv(delegate).await.ok()?;
1050 let pylsp = venv.join(BINARY_DIR).join("pylsp");
1051 Some(LanguageServerBinary {
1052 path: pylsp,
1053 env: None,
1054 arguments: vec![],
1055 })
1056 }
1057
1058 async fn process_completions(&self, _items: &mut [lsp::CompletionItem]) {}
1059
1060 async fn label_for_completion(
1061 &self,
1062 item: &lsp::CompletionItem,
1063 language: &Arc<language::Language>,
1064 ) -> Option<language::CodeLabel> {
1065 let label = &item.label;
1066 let grammar = language.grammar()?;
1067 let highlight_id = match item.kind? {
1068 lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method")?,
1069 lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function")?,
1070 lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type")?,
1071 lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant")?,
1072 _ => return None,
1073 };
1074 Some(language::CodeLabel {
1075 text: label.clone(),
1076 runs: vec![(0..label.len(), highlight_id)],
1077 filter_range: 0..label.len(),
1078 })
1079 }
1080
1081 async fn label_for_symbol(
1082 &self,
1083 name: &str,
1084 kind: lsp::SymbolKind,
1085 language: &Arc<language::Language>,
1086 ) -> Option<language::CodeLabel> {
1087 let (text, filter_range, display_range) = match kind {
1088 lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
1089 let text = format!("def {}():\n", name);
1090 let filter_range = 4..4 + name.len();
1091 let display_range = 0..filter_range.end;
1092 (text, filter_range, display_range)
1093 }
1094 lsp::SymbolKind::CLASS => {
1095 let text = format!("class {}:", name);
1096 let filter_range = 6..6 + name.len();
1097 let display_range = 0..filter_range.end;
1098 (text, filter_range, display_range)
1099 }
1100 lsp::SymbolKind::CONSTANT => {
1101 let text = format!("{} = 0", name);
1102 let filter_range = 0..name.len();
1103 let display_range = 0..filter_range.end;
1104 (text, filter_range, display_range)
1105 }
1106 _ => return None,
1107 };
1108
1109 Some(language::CodeLabel {
1110 runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
1111 text: text[display_range].to_string(),
1112 filter_range,
1113 })
1114 }
1115
1116 async fn workspace_configuration(
1117 self: Arc<Self>,
1118 _: &dyn Fs,
1119 adapter: &Arc<dyn LspAdapterDelegate>,
1120 toolchains: Arc<dyn LanguageToolchainStore>,
1121 cx: &mut AsyncApp,
1122 ) -> Result<Value> {
1123 let toolchain = toolchains
1124 .active_toolchain(
1125 adapter.worktree_id(),
1126 Arc::from("".as_ref()),
1127 LanguageName::new("Python"),
1128 cx,
1129 )
1130 .await;
1131 cx.update(move |cx| {
1132 let mut user_settings =
1133 language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
1134 .and_then(|s| s.settings.clone())
1135 .unwrap_or_else(|| {
1136 json!({
1137 "plugins": {
1138 "pycodestyle": {"enabled": false},
1139 "rope_autoimport": {"enabled": true, "memory": true},
1140 "pylsp_mypy": {"enabled": false}
1141 },
1142 "rope": {
1143 "ropeFolder": null
1144 },
1145 })
1146 });
1147
1148 // If user did not explicitly modify their python venv, use one from picker.
1149 if let Some(toolchain) = toolchain {
1150 if user_settings.is_null() {
1151 user_settings = Value::Object(serde_json::Map::default());
1152 }
1153 let object = user_settings.as_object_mut().unwrap();
1154 if let Some(python) = object
1155 .entry("plugins")
1156 .or_insert(Value::Object(serde_json::Map::default()))
1157 .as_object_mut()
1158 {
1159 if let Some(jedi) = python
1160 .entry("jedi")
1161 .or_insert(Value::Object(serde_json::Map::default()))
1162 .as_object_mut()
1163 {
1164 jedi.entry("environment".to_string())
1165 .or_insert_with(|| Value::String(toolchain.path.clone().into()));
1166 }
1167 if let Some(pylint) = python
1168 .entry("pylsp_mypy")
1169 .or_insert(Value::Object(serde_json::Map::default()))
1170 .as_object_mut()
1171 {
1172 pylint.entry("overrides".to_string()).or_insert_with(|| {
1173 Value::Array(vec![
1174 Value::String("--python-executable".into()),
1175 Value::String(toolchain.path.into()),
1176 Value::String("--cache-dir=/dev/null".into()),
1177 Value::Bool(true),
1178 ])
1179 });
1180 }
1181 }
1182 }
1183 user_settings = Value::Object(serde_json::Map::from_iter([(
1184 "pylsp".to_string(),
1185 user_settings,
1186 )]));
1187
1188 user_settings
1189 })
1190 }
1191 fn manifest_name(&self) -> Option<ManifestName> {
1192 Some(SharedString::new_static("pyproject.toml").into())
1193 }
1194}
1195
1196#[cfg(test)]
1197mod tests {
1198 use gpui::{AppContext as _, BorrowAppContext, Context, TestAppContext};
1199 use language::{AutoindentMode, Buffer, language_settings::AllLanguageSettings};
1200 use settings::SettingsStore;
1201 use std::num::NonZeroU32;
1202
1203 #[gpui::test]
1204 async fn test_python_autoindent(cx: &mut TestAppContext) {
1205 cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
1206 let language = crate::language("python", tree_sitter_python::LANGUAGE.into());
1207 cx.update(|cx| {
1208 let test_settings = SettingsStore::test(cx);
1209 cx.set_global(test_settings);
1210 language::init(cx);
1211 cx.update_global::<SettingsStore, _>(|store, cx| {
1212 store.update_user_settings::<AllLanguageSettings>(cx, |s| {
1213 s.defaults.tab_size = NonZeroU32::new(2);
1214 });
1215 });
1216 });
1217
1218 cx.new(|cx| {
1219 let mut buffer = Buffer::local("", cx).with_language(language, cx);
1220 let append = |buffer: &mut Buffer, text: &str, cx: &mut Context<Buffer>| {
1221 let ix = buffer.len();
1222 buffer.edit([(ix..ix, text)], Some(AutoindentMode::EachLine), cx);
1223 };
1224
1225 // indent after "def():"
1226 append(&mut buffer, "def a():\n", cx);
1227 assert_eq!(buffer.text(), "def a():\n ");
1228
1229 // preserve indent after blank line
1230 append(&mut buffer, "\n ", cx);
1231 assert_eq!(buffer.text(), "def a():\n \n ");
1232
1233 // indent after "if"
1234 append(&mut buffer, "if a:\n ", cx);
1235 assert_eq!(buffer.text(), "def a():\n \n if a:\n ");
1236
1237 // preserve indent after statement
1238 append(&mut buffer, "b()\n", cx);
1239 assert_eq!(buffer.text(), "def a():\n \n if a:\n b()\n ");
1240
1241 // preserve indent after statement
1242 append(&mut buffer, "else", cx);
1243 assert_eq!(buffer.text(), "def a():\n \n if a:\n b()\n else");
1244
1245 // dedent "else""
1246 append(&mut buffer, ":", cx);
1247 assert_eq!(buffer.text(), "def a():\n \n if a:\n b()\n else:");
1248
1249 // indent lines after else
1250 append(&mut buffer, "\n", cx);
1251 assert_eq!(
1252 buffer.text(),
1253 "def a():\n \n if a:\n b()\n else:\n "
1254 );
1255
1256 // indent after an open paren. the closing paren is not indented
1257 // because there is another token before it on the same line.
1258 append(&mut buffer, "foo(\n1)", cx);
1259 assert_eq!(
1260 buffer.text(),
1261 "def a():\n \n if a:\n b()\n else:\n foo(\n 1)"
1262 );
1263
1264 // dedent the closing paren if it is shifted to the beginning of the line
1265 let argument_ix = buffer.text().find('1').unwrap();
1266 buffer.edit(
1267 [(argument_ix..argument_ix + 1, "")],
1268 Some(AutoindentMode::EachLine),
1269 cx,
1270 );
1271 assert_eq!(
1272 buffer.text(),
1273 "def a():\n \n if a:\n b()\n else:\n foo(\n )"
1274 );
1275
1276 // preserve indent after the close paren
1277 append(&mut buffer, "\n", cx);
1278 assert_eq!(
1279 buffer.text(),
1280 "def a():\n \n if a:\n b()\n else:\n foo(\n )\n "
1281 );
1282
1283 // manually outdent the last line
1284 let end_whitespace_ix = buffer.len() - 4;
1285 buffer.edit(
1286 [(end_whitespace_ix..buffer.len(), "")],
1287 Some(AutoindentMode::EachLine),
1288 cx,
1289 );
1290 assert_eq!(
1291 buffer.text(),
1292 "def a():\n \n if a:\n b()\n else:\n foo(\n )\n"
1293 );
1294
1295 // preserve the newly reduced indentation on the next newline
1296 append(&mut buffer, "\n", cx);
1297 assert_eq!(
1298 buffer.text(),
1299 "def a():\n \n if a:\n b()\n else:\n foo(\n )\n\n"
1300 );
1301
1302 // reset to a simple if statement
1303 buffer.edit([(0..buffer.len(), "if a:\n b(\n )")], None, cx);
1304
1305 // dedent "else" on the line after a closing paren
1306 append(&mut buffer, "\n else:\n", cx);
1307 assert_eq!(buffer.text(), "if a:\n b(\n )\nelse:\n");
1308
1309 buffer
1310 });
1311 }
1312}