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::LanguageToolchainStore;
8use language::Toolchain;
9use language::ToolchainList;
10use language::ToolchainLister;
11use language::language_settings::language_settings;
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_MODULE_NAME_TASK_VARIABLE: VariableName =
361 VariableName::Custom(Cow::Borrowed("PYTHON_MODULE_NAME"));
362
363impl ContextProvider for PythonContextProvider {
364 fn build_context(
365 &self,
366 variables: &task::TaskVariables,
367 location: &project::Location,
368 _: Option<HashMap<String, String>>,
369 toolchains: Arc<dyn LanguageToolchainStore>,
370 cx: &mut gpui::App,
371 ) -> Task<Result<task::TaskVariables>> {
372 let test_target = match selected_test_runner(location.buffer.read(cx).file(), cx) {
373 TestRunner::UNITTEST => self.build_unittest_target(variables),
374 TestRunner::PYTEST => self.build_pytest_target(variables),
375 };
376
377 let module_target = self.build_module_target(variables);
378 let worktree_id = location.buffer.read(cx).file().map(|f| f.worktree_id(cx));
379
380 cx.spawn(async move |cx| {
381 let active_toolchain = if let Some(worktree_id) = worktree_id {
382 toolchains
383 .active_toolchain(worktree_id, Arc::from("".as_ref()), "Python".into(), cx)
384 .await
385 .map_or_else(|| "python3".to_owned(), |toolchain| toolchain.path.into())
386 } else {
387 String::from("python3")
388 };
389 let toolchain = (PYTHON_ACTIVE_TOOLCHAIN_PATH, active_toolchain);
390
391 Ok(task::TaskVariables::from_iter(
392 test_target
393 .into_iter()
394 .chain(module_target.into_iter())
395 .chain([toolchain]),
396 ))
397 })
398 }
399
400 fn associated_tasks(
401 &self,
402 file: Option<Arc<dyn language::File>>,
403 cx: &App,
404 ) -> Option<TaskTemplates> {
405 let test_runner = selected_test_runner(file.as_ref(), cx);
406
407 let mut tasks = vec![
408 // Execute a selection
409 TaskTemplate {
410 label: "execute selection".to_owned(),
411 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
412 args: vec![
413 "-c".to_owned(),
414 VariableName::SelectedText.template_value_with_whitespace(),
415 ],
416 ..TaskTemplate::default()
417 },
418 // Execute an entire file
419 TaskTemplate {
420 label: format!("run '{}'", VariableName::File.template_value()),
421 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
422 args: vec![VariableName::File.template_value_with_whitespace()],
423 ..TaskTemplate::default()
424 },
425 // Execute a file as module
426 TaskTemplate {
427 label: format!("run module '{}'", VariableName::File.template_value()),
428 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
429 args: vec![
430 "-m".to_owned(),
431 PYTHON_MODULE_NAME_TASK_VARIABLE.template_value(),
432 ],
433 tags: vec!["python-module-main-method".to_owned()],
434 ..TaskTemplate::default()
435 },
436 ];
437
438 tasks.extend(match test_runner {
439 TestRunner::UNITTEST => {
440 [
441 // Run tests for an entire file
442 TaskTemplate {
443 label: format!("unittest '{}'", VariableName::File.template_value()),
444 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
445 args: vec![
446 "-m".to_owned(),
447 "unittest".to_owned(),
448 VariableName::File.template_value_with_whitespace(),
449 ],
450 ..TaskTemplate::default()
451 },
452 // Run test(s) for a specific target within a file
453 TaskTemplate {
454 label: "unittest $ZED_CUSTOM_PYTHON_TEST_TARGET".to_owned(),
455 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
456 args: vec![
457 "-m".to_owned(),
458 "unittest".to_owned(),
459 PYTHON_TEST_TARGET_TASK_VARIABLE.template_value_with_whitespace(),
460 ],
461 tags: vec![
462 "python-unittest-class".to_owned(),
463 "python-unittest-method".to_owned(),
464 ],
465 ..TaskTemplate::default()
466 },
467 ]
468 }
469 TestRunner::PYTEST => {
470 [
471 // Run tests for an entire file
472 TaskTemplate {
473 label: format!("pytest '{}'", VariableName::File.template_value()),
474 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
475 args: vec![
476 "-m".to_owned(),
477 "pytest".to_owned(),
478 VariableName::File.template_value_with_whitespace(),
479 ],
480 ..TaskTemplate::default()
481 },
482 // Run test(s) for a specific target within a file
483 TaskTemplate {
484 label: "pytest $ZED_CUSTOM_PYTHON_TEST_TARGET".to_owned(),
485 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
486 args: vec![
487 "-m".to_owned(),
488 "pytest".to_owned(),
489 PYTHON_TEST_TARGET_TASK_VARIABLE.template_value_with_whitespace(),
490 ],
491 tags: vec![
492 "python-pytest-class".to_owned(),
493 "python-pytest-method".to_owned(),
494 ],
495 ..TaskTemplate::default()
496 },
497 ]
498 }
499 });
500
501 Some(TaskTemplates(tasks))
502 }
503}
504
505fn selected_test_runner(location: Option<&Arc<dyn language::File>>, cx: &App) -> TestRunner {
506 const TEST_RUNNER_VARIABLE: &str = "TEST_RUNNER";
507 language_settings(Some(LanguageName::new("Python")), location, cx)
508 .tasks
509 .variables
510 .get(TEST_RUNNER_VARIABLE)
511 .and_then(|val| TestRunner::from_str(val).ok())
512 .unwrap_or(TestRunner::PYTEST)
513}
514
515impl PythonContextProvider {
516 fn build_unittest_target(
517 &self,
518 variables: &task::TaskVariables,
519 ) -> Option<(VariableName, String)> {
520 let python_module_name =
521 python_module_name_from_relative_path(variables.get(&VariableName::RelativeFile)?);
522
523 let unittest_class_name =
524 variables.get(&VariableName::Custom(Cow::Borrowed("_unittest_class_name")));
525
526 let unittest_method_name = variables.get(&VariableName::Custom(Cow::Borrowed(
527 "_unittest_method_name",
528 )));
529
530 let unittest_target_str = match (unittest_class_name, unittest_method_name) {
531 (Some(class_name), Some(method_name)) => {
532 format!("{python_module_name}.{class_name}.{method_name}")
533 }
534 (Some(class_name), None) => format!("{python_module_name}.{class_name}"),
535 (None, None) => python_module_name,
536 // should never happen, a TestCase class is the unit of testing
537 (None, Some(_)) => return None,
538 };
539
540 Some((
541 PYTHON_TEST_TARGET_TASK_VARIABLE.clone(),
542 unittest_target_str,
543 ))
544 }
545
546 fn build_pytest_target(
547 &self,
548 variables: &task::TaskVariables,
549 ) -> Option<(VariableName, String)> {
550 let file_path = variables.get(&VariableName::RelativeFile)?;
551
552 let pytest_class_name =
553 variables.get(&VariableName::Custom(Cow::Borrowed("_pytest_class_name")));
554
555 let pytest_method_name =
556 variables.get(&VariableName::Custom(Cow::Borrowed("_pytest_method_name")));
557
558 let pytest_target_str = match (pytest_class_name, pytest_method_name) {
559 (Some(class_name), Some(method_name)) => {
560 format!("{file_path}::{class_name}::{method_name}")
561 }
562 (Some(class_name), None) => {
563 format!("{file_path}::{class_name}")
564 }
565 (None, Some(method_name)) => {
566 format!("{file_path}::{method_name}")
567 }
568 (None, None) => file_path.to_string(),
569 };
570
571 Some((PYTHON_TEST_TARGET_TASK_VARIABLE.clone(), pytest_target_str))
572 }
573
574 fn build_module_target(
575 &self,
576 variables: &task::TaskVariables,
577 ) -> Result<(VariableName, String)> {
578 let python_module_name = python_module_name_from_relative_path(
579 variables.get(&VariableName::RelativeFile).unwrap_or(""),
580 );
581
582 let module_target = (PYTHON_MODULE_NAME_TASK_VARIABLE.clone(), python_module_name);
583
584 Ok(module_target)
585 }
586}
587
588fn python_module_name_from_relative_path(relative_path: &str) -> String {
589 let path_with_dots = relative_path.replace('/', ".");
590 path_with_dots
591 .strip_suffix(".py")
592 .unwrap_or(&path_with_dots)
593 .to_string()
594}
595
596fn python_env_kind_display(k: &PythonEnvironmentKind) -> &'static str {
597 match k {
598 PythonEnvironmentKind::Conda => "Conda",
599 PythonEnvironmentKind::Pixi => "pixi",
600 PythonEnvironmentKind::Homebrew => "Homebrew",
601 PythonEnvironmentKind::Pyenv => "global (Pyenv)",
602 PythonEnvironmentKind::GlobalPaths => "global",
603 PythonEnvironmentKind::PyenvVirtualEnv => "Pyenv",
604 PythonEnvironmentKind::Pipenv => "Pipenv",
605 PythonEnvironmentKind::Poetry => "Poetry",
606 PythonEnvironmentKind::MacPythonOrg => "global (Python.org)",
607 PythonEnvironmentKind::MacCommandLineTools => "global (Command Line Tools for Xcode)",
608 PythonEnvironmentKind::LinuxGlobal => "global",
609 PythonEnvironmentKind::MacXCode => "global (Xcode)",
610 PythonEnvironmentKind::Venv => "venv",
611 PythonEnvironmentKind::VirtualEnv => "virtualenv",
612 PythonEnvironmentKind::VirtualEnvWrapper => "virtualenvwrapper",
613 PythonEnvironmentKind::WindowsStore => "global (Windows Store)",
614 PythonEnvironmentKind::WindowsRegistry => "global (Windows Registry)",
615 }
616}
617
618pub(crate) struct PythonToolchainProvider {
619 term: SharedString,
620}
621
622impl Default for PythonToolchainProvider {
623 fn default() -> Self {
624 Self {
625 term: SharedString::new_static("Virtual Environment"),
626 }
627 }
628}
629
630static ENV_PRIORITY_LIST: &'static [PythonEnvironmentKind] = &[
631 // Prioritize non-Conda environments.
632 PythonEnvironmentKind::Poetry,
633 PythonEnvironmentKind::Pipenv,
634 PythonEnvironmentKind::VirtualEnvWrapper,
635 PythonEnvironmentKind::Venv,
636 PythonEnvironmentKind::VirtualEnv,
637 PythonEnvironmentKind::PyenvVirtualEnv,
638 PythonEnvironmentKind::Pixi,
639 PythonEnvironmentKind::Conda,
640 PythonEnvironmentKind::Pyenv,
641 PythonEnvironmentKind::GlobalPaths,
642 PythonEnvironmentKind::Homebrew,
643];
644
645fn env_priority(kind: Option<PythonEnvironmentKind>) -> usize {
646 if let Some(kind) = kind {
647 ENV_PRIORITY_LIST
648 .iter()
649 .position(|blessed_env| blessed_env == &kind)
650 .unwrap_or(ENV_PRIORITY_LIST.len())
651 } else {
652 // Unknown toolchains are less useful than non-blessed ones.
653 ENV_PRIORITY_LIST.len() + 1
654 }
655}
656
657/// Return the name of environment declared in <worktree-root/.venv.
658///
659/// https://virtualfish.readthedocs.io/en/latest/plugins.html#auto-activation-auto-activation
660fn get_worktree_venv_declaration(worktree_root: &Path) -> Option<String> {
661 fs::File::open(worktree_root.join(".venv"))
662 .and_then(|file| {
663 let mut venv_name = String::new();
664 io::BufReader::new(file).read_line(&mut venv_name)?;
665 Ok(venv_name.trim().to_string())
666 })
667 .ok()
668}
669
670#[async_trait]
671impl ToolchainLister for PythonToolchainProvider {
672 async fn list(
673 &self,
674 worktree_root: PathBuf,
675 project_env: Option<HashMap<String, String>>,
676 ) -> ToolchainList {
677 let env = project_env.unwrap_or_default();
678 let environment = EnvironmentApi::from_env(&env);
679 let locators = pet::locators::create_locators(
680 Arc::new(pet_conda::Conda::from(&environment)),
681 Arc::new(pet_poetry::Poetry::from(&environment)),
682 &environment,
683 );
684 let mut config = Configuration::default();
685 config.workspace_directories = Some(vec![worktree_root.clone()]);
686 for locator in locators.iter() {
687 locator.configure(&config);
688 }
689
690 let reporter = pet_reporter::collect::create_reporter();
691 pet::find::find_and_report_envs(&reporter, config, &locators, &environment, None);
692
693 let mut toolchains = reporter
694 .environments
695 .lock()
696 .map_or(Vec::new(), |mut guard| std::mem::take(&mut guard));
697
698 let wr = worktree_root;
699 let wr_venv = get_worktree_venv_declaration(&wr);
700 // Sort detected environments by:
701 // environment name matching activation file (<workdir>/.venv)
702 // environment project dir matching worktree_root
703 // general env priority
704 // environment path matching the CONDA_PREFIX env var
705 // executable path
706 toolchains.sort_by(|lhs, rhs| {
707 // Compare venv names against worktree .venv file
708 let venv_ordering =
709 wr_venv
710 .as_ref()
711 .map_or(Ordering::Equal, |venv| match (&lhs.name, &rhs.name) {
712 (Some(l), Some(r)) => (r == venv).cmp(&(l == venv)),
713 (Some(l), None) if l == venv => Ordering::Less,
714 (None, Some(r)) if r == venv => Ordering::Greater,
715 _ => Ordering::Equal,
716 });
717
718 // Compare project paths against worktree root
719 let proj_ordering = || match (&lhs.project, &rhs.project) {
720 (Some(l), Some(r)) => (r == &wr).cmp(&(l == &wr)),
721 (Some(l), None) if l == &wr => Ordering::Less,
722 (None, Some(r)) if r == &wr => Ordering::Greater,
723 _ => Ordering::Equal,
724 };
725
726 // Compare environment priorities
727 let priority_ordering = || env_priority(lhs.kind).cmp(&env_priority(rhs.kind));
728
729 // Compare conda prefixes
730 let conda_ordering = || {
731 if lhs.kind == Some(PythonEnvironmentKind::Conda) {
732 environment
733 .get_env_var("CONDA_PREFIX".to_string())
734 .map(|conda_prefix| {
735 let is_match = |exe: &Option<PathBuf>| {
736 exe.as_ref().map_or(false, |e| e.starts_with(&conda_prefix))
737 };
738 match (is_match(&lhs.executable), is_match(&rhs.executable)) {
739 (true, false) => Ordering::Less,
740 (false, true) => Ordering::Greater,
741 _ => Ordering::Equal,
742 }
743 })
744 .unwrap_or(Ordering::Equal)
745 } else {
746 Ordering::Equal
747 }
748 };
749
750 // Compare Python executables
751 let exe_ordering = || lhs.executable.cmp(&rhs.executable);
752
753 venv_ordering
754 .then_with(proj_ordering)
755 .then_with(priority_ordering)
756 .then_with(conda_ordering)
757 .then_with(exe_ordering)
758 });
759
760 let mut toolchains: Vec<_> = toolchains
761 .into_iter()
762 .filter_map(|toolchain| {
763 let mut name = String::from("Python");
764 if let Some(ref version) = toolchain.version {
765 _ = write!(name, " {version}");
766 }
767
768 let name_and_kind = match (&toolchain.name, &toolchain.kind) {
769 (Some(name), Some(kind)) => {
770 Some(format!("({name}; {})", python_env_kind_display(kind)))
771 }
772 (Some(name), None) => Some(format!("({name})")),
773 (None, Some(kind)) => Some(format!("({})", python_env_kind_display(kind))),
774 (None, None) => None,
775 };
776
777 if let Some(nk) = name_and_kind {
778 _ = write!(name, " {nk}");
779 }
780
781 Some(Toolchain {
782 name: name.into(),
783 path: toolchain.executable.as_ref()?.to_str()?.to_owned().into(),
784 language_name: LanguageName::new("Python"),
785 as_json: serde_json::to_value(toolchain).ok()?,
786 })
787 })
788 .collect();
789 toolchains.dedup();
790 ToolchainList {
791 toolchains,
792 default: None,
793 groups: Default::default(),
794 }
795 }
796 fn term(&self) -> SharedString {
797 self.term.clone()
798 }
799}
800
801pub struct EnvironmentApi<'a> {
802 global_search_locations: Arc<Mutex<Vec<PathBuf>>>,
803 project_env: &'a HashMap<String, String>,
804 pet_env: pet_core::os_environment::EnvironmentApi,
805}
806
807impl<'a> EnvironmentApi<'a> {
808 pub fn from_env(project_env: &'a HashMap<String, String>) -> Self {
809 let paths = project_env
810 .get("PATH")
811 .map(|p| std::env::split_paths(p).collect())
812 .unwrap_or_default();
813
814 EnvironmentApi {
815 global_search_locations: Arc::new(Mutex::new(paths)),
816 project_env,
817 pet_env: pet_core::os_environment::EnvironmentApi::new(),
818 }
819 }
820
821 fn user_home(&self) -> Option<PathBuf> {
822 self.project_env
823 .get("HOME")
824 .or_else(|| self.project_env.get("USERPROFILE"))
825 .map(|home| pet_fs::path::norm_case(PathBuf::from(home)))
826 .or_else(|| self.pet_env.get_user_home())
827 }
828}
829
830impl pet_core::os_environment::Environment for EnvironmentApi<'_> {
831 fn get_user_home(&self) -> Option<PathBuf> {
832 self.user_home()
833 }
834
835 fn get_root(&self) -> Option<PathBuf> {
836 None
837 }
838
839 fn get_env_var(&self, key: String) -> Option<String> {
840 self.project_env
841 .get(&key)
842 .cloned()
843 .or_else(|| self.pet_env.get_env_var(key))
844 }
845
846 fn get_know_global_search_locations(&self) -> Vec<PathBuf> {
847 if self.global_search_locations.lock().is_empty() {
848 let mut paths =
849 std::env::split_paths(&self.get_env_var("PATH".to_string()).unwrap_or_default())
850 .collect::<Vec<PathBuf>>();
851
852 log::trace!("Env PATH: {:?}", paths);
853 for p in self.pet_env.get_know_global_search_locations() {
854 if !paths.contains(&p) {
855 paths.push(p);
856 }
857 }
858
859 let mut paths = paths
860 .into_iter()
861 .filter(|p| p.exists())
862 .collect::<Vec<PathBuf>>();
863
864 self.global_search_locations.lock().append(&mut paths);
865 }
866 self.global_search_locations.lock().clone()
867 }
868}
869
870pub(crate) struct PyLspAdapter {
871 python_venv_base: OnceCell<Result<Arc<Path>, String>>,
872}
873impl PyLspAdapter {
874 const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("pylsp");
875 pub(crate) fn new() -> Self {
876 Self {
877 python_venv_base: OnceCell::new(),
878 }
879 }
880 async fn ensure_venv(delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>> {
881 let python_path = Self::find_base_python(delegate)
882 .await
883 .context("Could not find Python installation for PyLSP")?;
884 let work_dir = delegate
885 .language_server_download_dir(&Self::SERVER_NAME)
886 .await
887 .context("Could not get working directory for PyLSP")?;
888 let mut path = PathBuf::from(work_dir.as_ref());
889 path.push("pylsp-venv");
890 if !path.exists() {
891 util::command::new_smol_command(python_path)
892 .arg("-m")
893 .arg("venv")
894 .arg("pylsp-venv")
895 .current_dir(work_dir)
896 .spawn()?
897 .output()
898 .await?;
899 }
900
901 Ok(path.into())
902 }
903 // Find "baseline", user python version from which we'll create our own venv.
904 async fn find_base_python(delegate: &dyn LspAdapterDelegate) -> Option<PathBuf> {
905 for path in ["python3", "python"] {
906 if let Some(path) = delegate.which(path.as_ref()).await {
907 return Some(path);
908 }
909 }
910 None
911 }
912
913 async fn base_venv(&self, delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>, String> {
914 self.python_venv_base
915 .get_or_init(move || async move {
916 Self::ensure_venv(delegate)
917 .await
918 .map_err(|e| format!("{e}"))
919 })
920 .await
921 .clone()
922 }
923}
924
925const BINARY_DIR: &str = if cfg!(target_os = "windows") {
926 "Scripts"
927} else {
928 "bin"
929};
930
931#[async_trait(?Send)]
932impl LspAdapter for PyLspAdapter {
933 fn name(&self) -> LanguageServerName {
934 Self::SERVER_NAME.clone()
935 }
936
937 async fn check_if_user_installed(
938 &self,
939 delegate: &dyn LspAdapterDelegate,
940 toolchains: Arc<dyn LanguageToolchainStore>,
941 cx: &AsyncApp,
942 ) -> Option<LanguageServerBinary> {
943 if let Some(pylsp_bin) = delegate.which(Self::SERVER_NAME.as_ref()).await {
944 let env = delegate.shell_env().await;
945 Some(LanguageServerBinary {
946 path: pylsp_bin,
947 env: Some(env),
948 arguments: vec![],
949 })
950 } else {
951 let venv = toolchains
952 .active_toolchain(
953 delegate.worktree_id(),
954 Arc::from("".as_ref()),
955 LanguageName::new("Python"),
956 &mut cx.clone(),
957 )
958 .await?;
959 let pylsp_path = Path::new(venv.path.as_ref()).parent()?.join("pylsp");
960 pylsp_path.exists().then(|| LanguageServerBinary {
961 path: venv.path.to_string().into(),
962 arguments: vec![pylsp_path.into()],
963 env: None,
964 })
965 }
966 }
967
968 async fn fetch_latest_server_version(
969 &self,
970 _: &dyn LspAdapterDelegate,
971 ) -> Result<Box<dyn 'static + Any + Send>> {
972 Ok(Box::new(()) as Box<_>)
973 }
974
975 async fn fetch_server_binary(
976 &self,
977 _: Box<dyn 'static + Send + Any>,
978 _: PathBuf,
979 delegate: &dyn LspAdapterDelegate,
980 ) -> Result<LanguageServerBinary> {
981 let venv = self.base_venv(delegate).await.map_err(|e| anyhow!(e))?;
982 let pip_path = venv.join(BINARY_DIR).join("pip3");
983 ensure!(
984 util::command::new_smol_command(pip_path.as_path())
985 .arg("install")
986 .arg("python-lsp-server")
987 .arg("-U")
988 .output()
989 .await?
990 .status
991 .success(),
992 "python-lsp-server installation failed"
993 );
994 ensure!(
995 util::command::new_smol_command(pip_path.as_path())
996 .arg("install")
997 .arg("python-lsp-server[all]")
998 .arg("-U")
999 .output()
1000 .await?
1001 .status
1002 .success(),
1003 "python-lsp-server[all] installation failed"
1004 );
1005 ensure!(
1006 util::command::new_smol_command(pip_path)
1007 .arg("install")
1008 .arg("pylsp-mypy")
1009 .arg("-U")
1010 .output()
1011 .await?
1012 .status
1013 .success(),
1014 "pylsp-mypy installation failed"
1015 );
1016 let pylsp = venv.join(BINARY_DIR).join("pylsp");
1017 Ok(LanguageServerBinary {
1018 path: pylsp,
1019 env: None,
1020 arguments: vec![],
1021 })
1022 }
1023
1024 async fn cached_server_binary(
1025 &self,
1026 _: PathBuf,
1027 delegate: &dyn LspAdapterDelegate,
1028 ) -> Option<LanguageServerBinary> {
1029 let venv = self.base_venv(delegate).await.ok()?;
1030 let pylsp = venv.join(BINARY_DIR).join("pylsp");
1031 Some(LanguageServerBinary {
1032 path: pylsp,
1033 env: None,
1034 arguments: vec![],
1035 })
1036 }
1037
1038 async fn process_completions(&self, _items: &mut [lsp::CompletionItem]) {}
1039
1040 async fn label_for_completion(
1041 &self,
1042 item: &lsp::CompletionItem,
1043 language: &Arc<language::Language>,
1044 ) -> Option<language::CodeLabel> {
1045 let label = &item.label;
1046 let grammar = language.grammar()?;
1047 let highlight_id = match item.kind? {
1048 lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method")?,
1049 lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function")?,
1050 lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type")?,
1051 lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant")?,
1052 _ => return None,
1053 };
1054 Some(language::CodeLabel {
1055 text: label.clone(),
1056 runs: vec![(0..label.len(), highlight_id)],
1057 filter_range: 0..label.len(),
1058 })
1059 }
1060
1061 async fn label_for_symbol(
1062 &self,
1063 name: &str,
1064 kind: lsp::SymbolKind,
1065 language: &Arc<language::Language>,
1066 ) -> Option<language::CodeLabel> {
1067 let (text, filter_range, display_range) = match kind {
1068 lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
1069 let text = format!("def {}():\n", name);
1070 let filter_range = 4..4 + name.len();
1071 let display_range = 0..filter_range.end;
1072 (text, filter_range, display_range)
1073 }
1074 lsp::SymbolKind::CLASS => {
1075 let text = format!("class {}:", name);
1076 let filter_range = 6..6 + name.len();
1077 let display_range = 0..filter_range.end;
1078 (text, filter_range, display_range)
1079 }
1080 lsp::SymbolKind::CONSTANT => {
1081 let text = format!("{} = 0", name);
1082 let filter_range = 0..name.len();
1083 let display_range = 0..filter_range.end;
1084 (text, filter_range, display_range)
1085 }
1086 _ => return None,
1087 };
1088
1089 Some(language::CodeLabel {
1090 runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
1091 text: text[display_range].to_string(),
1092 filter_range,
1093 })
1094 }
1095
1096 async fn workspace_configuration(
1097 self: Arc<Self>,
1098 _: &dyn Fs,
1099 adapter: &Arc<dyn LspAdapterDelegate>,
1100 toolchains: Arc<dyn LanguageToolchainStore>,
1101 cx: &mut AsyncApp,
1102 ) -> Result<Value> {
1103 let toolchain = toolchains
1104 .active_toolchain(
1105 adapter.worktree_id(),
1106 Arc::from("".as_ref()),
1107 LanguageName::new("Python"),
1108 cx,
1109 )
1110 .await;
1111 cx.update(move |cx| {
1112 let mut user_settings =
1113 language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
1114 .and_then(|s| s.settings.clone())
1115 .unwrap_or_else(|| {
1116 json!({
1117 "plugins": {
1118 "pycodestyle": {"enabled": false},
1119 "rope_autoimport": {"enabled": true, "memory": true},
1120 "pylsp_mypy": {"enabled": false}
1121 },
1122 "rope": {
1123 "ropeFolder": null
1124 },
1125 })
1126 });
1127
1128 // If user did not explicitly modify their python venv, use one from picker.
1129 if let Some(toolchain) = toolchain {
1130 if user_settings.is_null() {
1131 user_settings = Value::Object(serde_json::Map::default());
1132 }
1133 let object = user_settings.as_object_mut().unwrap();
1134 if let Some(python) = object
1135 .entry("plugins")
1136 .or_insert(Value::Object(serde_json::Map::default()))
1137 .as_object_mut()
1138 {
1139 if let Some(jedi) = python
1140 .entry("jedi")
1141 .or_insert(Value::Object(serde_json::Map::default()))
1142 .as_object_mut()
1143 {
1144 jedi.entry("environment".to_string())
1145 .or_insert_with(|| Value::String(toolchain.path.clone().into()));
1146 }
1147 if let Some(pylint) = python
1148 .entry("pylsp_mypy")
1149 .or_insert(Value::Object(serde_json::Map::default()))
1150 .as_object_mut()
1151 {
1152 pylint.entry("overrides".to_string()).or_insert_with(|| {
1153 Value::Array(vec![
1154 Value::String("--python-executable".into()),
1155 Value::String(toolchain.path.into()),
1156 Value::String("--cache-dir=/dev/null".into()),
1157 Value::Bool(true),
1158 ])
1159 });
1160 }
1161 }
1162 }
1163 user_settings = Value::Object(serde_json::Map::from_iter([(
1164 "pylsp".to_string(),
1165 user_settings,
1166 )]));
1167
1168 user_settings
1169 })
1170 }
1171 fn manifest_name(&self) -> Option<ManifestName> {
1172 Some(SharedString::new_static("pyproject.toml").into())
1173 }
1174}
1175
1176#[cfg(test)]
1177mod tests {
1178 use gpui::{AppContext as _, BorrowAppContext, Context, TestAppContext};
1179 use language::{AutoindentMode, Buffer, language_settings::AllLanguageSettings};
1180 use settings::SettingsStore;
1181 use std::num::NonZeroU32;
1182
1183 #[gpui::test]
1184 async fn test_python_autoindent(cx: &mut TestAppContext) {
1185 cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
1186 let language = crate::language("python", tree_sitter_python::LANGUAGE.into());
1187 cx.update(|cx| {
1188 let test_settings = SettingsStore::test(cx);
1189 cx.set_global(test_settings);
1190 language::init(cx);
1191 cx.update_global::<SettingsStore, _>(|store, cx| {
1192 store.update_user_settings::<AllLanguageSettings>(cx, |s| {
1193 s.defaults.tab_size = NonZeroU32::new(2);
1194 });
1195 });
1196 });
1197
1198 cx.new(|cx| {
1199 let mut buffer = Buffer::local("", cx).with_language(language, cx);
1200 let append = |buffer: &mut Buffer, text: &str, cx: &mut Context<Buffer>| {
1201 let ix = buffer.len();
1202 buffer.edit([(ix..ix, text)], Some(AutoindentMode::EachLine), cx);
1203 };
1204
1205 // indent after "def():"
1206 append(&mut buffer, "def a():\n", cx);
1207 assert_eq!(buffer.text(), "def a():\n ");
1208
1209 // preserve indent after blank line
1210 append(&mut buffer, "\n ", cx);
1211 assert_eq!(buffer.text(), "def a():\n \n ");
1212
1213 // indent after "if"
1214 append(&mut buffer, "if a:\n ", cx);
1215 assert_eq!(buffer.text(), "def a():\n \n if a:\n ");
1216
1217 // preserve indent after statement
1218 append(&mut buffer, "b()\n", cx);
1219 assert_eq!(buffer.text(), "def a():\n \n if a:\n b()\n ");
1220
1221 // preserve indent after statement
1222 append(&mut buffer, "else", cx);
1223 assert_eq!(buffer.text(), "def a():\n \n if a:\n b()\n else");
1224
1225 // dedent "else""
1226 append(&mut buffer, ":", cx);
1227 assert_eq!(buffer.text(), "def a():\n \n if a:\n b()\n else:");
1228
1229 // indent lines after else
1230 append(&mut buffer, "\n", cx);
1231 assert_eq!(
1232 buffer.text(),
1233 "def a():\n \n if a:\n b()\n else:\n "
1234 );
1235
1236 // indent after an open paren. the closing paren is not indented
1237 // because there is another token before it on the same line.
1238 append(&mut buffer, "foo(\n1)", cx);
1239 assert_eq!(
1240 buffer.text(),
1241 "def a():\n \n if a:\n b()\n else:\n foo(\n 1)"
1242 );
1243
1244 // dedent the closing paren if it is shifted to the beginning of the line
1245 let argument_ix = buffer.text().find('1').unwrap();
1246 buffer.edit(
1247 [(argument_ix..argument_ix + 1, "")],
1248 Some(AutoindentMode::EachLine),
1249 cx,
1250 );
1251 assert_eq!(
1252 buffer.text(),
1253 "def a():\n \n if a:\n b()\n else:\n foo(\n )"
1254 );
1255
1256 // preserve indent after the close paren
1257 append(&mut buffer, "\n", cx);
1258 assert_eq!(
1259 buffer.text(),
1260 "def a():\n \n if a:\n b()\n else:\n foo(\n )\n "
1261 );
1262
1263 // manually outdent the last line
1264 let end_whitespace_ix = buffer.len() - 4;
1265 buffer.edit(
1266 [(end_whitespace_ix..buffer.len(), "")],
1267 Some(AutoindentMode::EachLine),
1268 cx,
1269 );
1270 assert_eq!(
1271 buffer.text(),
1272 "def a():\n \n if a:\n b()\n else:\n foo(\n )\n"
1273 );
1274
1275 // preserve the newly reduced indentation on the next newline
1276 append(&mut buffer, "\n", cx);
1277 assert_eq!(
1278 buffer.text(),
1279 "def a():\n \n if a:\n b()\n else:\n foo(\n )\n\n"
1280 );
1281
1282 // reset to a simple if statement
1283 buffer.edit([(0..buffer.len(), "if a:\n b(\n )")], None, cx);
1284
1285 // dedent "else" on the line after a closing paren
1286 append(&mut buffer, "\n else:\n", cx);
1287 assert_eq!(buffer.text(), "if a:\n b(\n )\nelse:\n");
1288
1289 buffer
1290 });
1291 }
1292}