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