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