1use anyhow::{Context as _, ensure};
2use anyhow::{Result, anyhow};
3use async_trait::async_trait;
4use collections::HashMap;
5use futures::{AsyncBufReadExt, StreamExt as _};
6use gpui::{App, AsyncApp, SharedString, Task};
7use http_client::github::{AssetKind, GitHubLspBinaryVersion, latest_github_release};
8use language::language_settings::language_settings;
9use language::{ContextLocation, LanguageToolchainStore, LspInstaller};
10use language::{ContextProvider, LspAdapter, LspAdapterDelegate};
11use language::{LanguageName, ManifestName, ManifestProvider, ManifestQuery};
12use language::{Toolchain, ToolchainList, ToolchainLister, ToolchainMetadata};
13use lsp::LanguageServerName;
14use lsp::{LanguageServerBinary, Uri};
15use node_runtime::{NodeRuntime, VersionStrategy};
16use pet_core::Configuration;
17use pet_core::os_environment::Environment;
18use pet_core::python_environment::{PythonEnvironment, PythonEnvironmentKind};
19use pet_virtualenv::is_virtualenv_dir;
20use project::Fs;
21use project::lsp_store::language_server_settings;
22use serde::{Deserialize, Serialize};
23use serde_json::{Value, json};
24use settings::Settings;
25use smol::lock::OnceCell;
26use std::cmp::Ordering;
27use std::env::consts;
28use terminal::terminal_settings::TerminalSettings;
29use util::command::new_smol_command;
30use util::fs::{make_file_executable, remove_matching};
31use util::paths::PathStyle;
32use util::rel_path::RelPath;
33
34use http_client::github_download::{GithubBinaryMetadata, download_server_binary};
35use parking_lot::Mutex;
36use std::str::FromStr;
37use std::{
38 borrow::Cow,
39 fmt::Write,
40 path::{Path, PathBuf},
41 sync::Arc,
42};
43use task::{ShellKind, TaskTemplate, TaskTemplates, VariableName};
44use util::{ResultExt, maybe};
45
46#[derive(Debug, Serialize, Deserialize)]
47pub(crate) struct PythonToolchainData {
48 #[serde(flatten)]
49 environment: PythonEnvironment,
50 #[serde(skip_serializing_if = "Option::is_none")]
51 activation_scripts: Option<HashMap<ShellKind, PathBuf>>,
52}
53
54pub(crate) struct PyprojectTomlManifestProvider;
55
56impl ManifestProvider for PyprojectTomlManifestProvider {
57 fn name(&self) -> ManifestName {
58 SharedString::new_static("pyproject.toml").into()
59 }
60
61 fn search(
62 &self,
63 ManifestQuery {
64 path,
65 depth,
66 delegate,
67 }: ManifestQuery,
68 ) -> Option<Arc<RelPath>> {
69 for path in path.ancestors().take(depth) {
70 let p = path.join(RelPath::unix("pyproject.toml").unwrap());
71 if delegate.exists(&p, Some(false)) {
72 return Some(path.into());
73 }
74 }
75
76 None
77 }
78}
79
80enum TestRunner {
81 UNITTEST,
82 PYTEST,
83}
84
85impl FromStr for TestRunner {
86 type Err = ();
87
88 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
89 match s {
90 "unittest" => Ok(Self::UNITTEST),
91 "pytest" => Ok(Self::PYTEST),
92 _ => Err(()),
93 }
94 }
95}
96
97/// Pyright assigns each completion item a `sortText` of the form `XX.YYYY.name`.
98/// Where `XX` is the sorting category, `YYYY` is based on most recent usage,
99/// and `name` is the symbol name itself.
100///
101/// The problem with it is that Pyright adjusts the sort text based on previous resolutions (items for which we've issued `completion/resolve` call have their sortText adjusted),
102/// which - long story short - makes completion items list non-stable. Pyright probably relies on VSCode's implementation detail.
103/// see https://github.com/microsoft/pyright/blob/95ef4e103b9b2f129c9320427e51b73ea7cf78bd/packages/pyright-internal/src/languageService/completionProvider.ts#LL2873
104///
105/// upd 02.12.25:
106/// Decided to ignore Pyright's sortText() completely and to manually sort all entries
107fn process_pyright_completions(items: &mut [lsp::CompletionItem]) {
108 for item in items {
109 let is_dunder = item.label.starts_with("__") && item.label.ends_with("__");
110
111 let visibility_priority = if is_dunder {
112 '3'
113 } else if item.label.starts_with("__") {
114 '2' // private non-dunder
115 } else if item.label.starts_with('_') {
116 '1' // protected
117 } else {
118 '0' // public
119 };
120
121 // Kind priority within same visibility level
122 let kind_priority = match item.kind {
123 Some(lsp::CompletionItemKind::ENUM_MEMBER) => '0',
124 Some(lsp::CompletionItemKind::FIELD) => '1',
125 Some(lsp::CompletionItemKind::PROPERTY) => '2',
126 Some(lsp::CompletionItemKind::VARIABLE) => '3',
127 Some(lsp::CompletionItemKind::CONSTANT) => '4',
128 Some(lsp::CompletionItemKind::METHOD) => '5',
129 Some(lsp::CompletionItemKind::FUNCTION) => '5',
130 Some(lsp::CompletionItemKind::CLASS) => '6',
131 Some(lsp::CompletionItemKind::MODULE) => '7',
132 _ => '8',
133 };
134
135 item.sort_text = Some(format!(
136 "{}{}{}",
137 visibility_priority, kind_priority, item.label
138 ));
139 }
140}
141
142pub struct TyLspAdapter {
143 fs: Arc<dyn Fs>,
144}
145
146#[cfg(target_os = "macos")]
147impl TyLspAdapter {
148 const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
149 const ARCH_SERVER_NAME: &str = "apple-darwin";
150}
151
152#[cfg(target_os = "linux")]
153impl TyLspAdapter {
154 const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
155 const ARCH_SERVER_NAME: &str = "unknown-linux-gnu";
156}
157
158#[cfg(target_os = "freebsd")]
159impl TyLspAdapter {
160 const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
161 const ARCH_SERVER_NAME: &str = "unknown-freebsd";
162}
163
164#[cfg(target_os = "windows")]
165impl TyLspAdapter {
166 const GITHUB_ASSET_KIND: AssetKind = AssetKind::Zip;
167 const ARCH_SERVER_NAME: &str = "pc-windows-msvc";
168}
169
170impl TyLspAdapter {
171 const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("ty");
172
173 pub fn new(fs: Arc<dyn Fs>) -> TyLspAdapter {
174 TyLspAdapter { fs }
175 }
176
177 fn build_asset_name() -> Result<(String, String)> {
178 let arch = match consts::ARCH {
179 "x86" => "i686",
180 _ => consts::ARCH,
181 };
182 let os = Self::ARCH_SERVER_NAME;
183 let suffix = match consts::OS {
184 "windows" => "zip",
185 _ => "tar.gz",
186 };
187 let asset_name = format!("ty-{arch}-{os}.{suffix}");
188 let asset_stem = format!("ty-{arch}-{os}");
189 Ok((asset_stem, asset_name))
190 }
191}
192
193#[async_trait(?Send)]
194impl LspAdapter for TyLspAdapter {
195 fn name(&self) -> LanguageServerName {
196 Self::SERVER_NAME
197 }
198
199 async fn label_for_completion(
200 &self,
201 item: &lsp::CompletionItem,
202 language: &Arc<language::Language>,
203 ) -> Option<language::CodeLabel> {
204 let label = &item.label;
205 let label_len = label.len();
206 let grammar = language.grammar()?;
207 let highlight_id = match item.kind? {
208 lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method"),
209 lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function"),
210 lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type"),
211 lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant"),
212 lsp::CompletionItemKind::VARIABLE => grammar.highlight_id_for_name("variable"),
213 _ => {
214 return None;
215 }
216 };
217
218 let mut text = label.clone();
219 if let Some(completion_details) = item
220 .label_details
221 .as_ref()
222 .and_then(|details| details.detail.as_ref())
223 {
224 write!(&mut text, " {}", completion_details).ok();
225 }
226
227 Some(language::CodeLabel::filtered(
228 text,
229 label_len,
230 item.filter_text.as_deref(),
231 highlight_id
232 .map(|id| (0..label_len, id))
233 .into_iter()
234 .collect(),
235 ))
236 }
237
238 async fn workspace_configuration(
239 self: Arc<Self>,
240 delegate: &Arc<dyn LspAdapterDelegate>,
241 toolchain: Option<Toolchain>,
242 _: Option<Uri>,
243 cx: &mut AsyncApp,
244 ) -> Result<Value> {
245 let mut ret = cx
246 .update(|cx| {
247 language_server_settings(delegate.as_ref(), &self.name(), cx)
248 .and_then(|s| s.settings.clone())
249 })?
250 .unwrap_or_else(|| json!({}));
251 if let Some(toolchain) = toolchain.and_then(|toolchain| {
252 serde_json::from_value::<PythonToolchainData>(toolchain.as_json).ok()
253 }) {
254 _ = maybe!({
255 let uri =
256 url::Url::from_file_path(toolchain.environment.executable.as_ref()?).ok()?;
257 let sys_prefix = toolchain.environment.prefix.clone()?;
258 let environment = json!({
259 "executable": {
260 "uri": uri,
261 "sysPrefix": sys_prefix
262 }
263 });
264 ret.as_object_mut()?
265 .entry("pythonExtension")
266 .or_insert_with(|| json!({ "activeEnvironment": environment }));
267 Some(())
268 });
269 }
270 Ok(json!({"ty": ret}))
271 }
272}
273
274impl LspInstaller for TyLspAdapter {
275 type BinaryVersion = GitHubLspBinaryVersion;
276 async fn fetch_latest_server_version(
277 &self,
278 delegate: &dyn LspAdapterDelegate,
279 _: bool,
280 _: &mut AsyncApp,
281 ) -> Result<Self::BinaryVersion> {
282 let release =
283 latest_github_release("astral-sh/ty", true, true, delegate.http_client()).await?;
284 let (_, asset_name) = Self::build_asset_name()?;
285 let asset = release
286 .assets
287 .into_iter()
288 .find(|asset| asset.name == asset_name)
289 .with_context(|| format!("no asset found matching `{asset_name:?}`"))?;
290 Ok(GitHubLspBinaryVersion {
291 name: release.tag_name,
292 url: asset.browser_download_url,
293 digest: asset.digest,
294 })
295 }
296
297 async fn fetch_server_binary(
298 &self,
299 latest_version: Self::BinaryVersion,
300 container_dir: PathBuf,
301 delegate: &dyn LspAdapterDelegate,
302 ) -> Result<LanguageServerBinary> {
303 let GitHubLspBinaryVersion {
304 name,
305 url,
306 digest: expected_digest,
307 } = latest_version;
308 let destination_path = container_dir.join(format!("ty-{name}"));
309
310 async_fs::create_dir_all(&destination_path).await?;
311
312 let server_path = match Self::GITHUB_ASSET_KIND {
313 AssetKind::TarGz | AssetKind::Gz => destination_path
314 .join(Self::build_asset_name()?.0)
315 .join("ty"),
316 AssetKind::Zip => destination_path.clone().join("ty.exe"),
317 };
318
319 let binary = LanguageServerBinary {
320 path: server_path.clone(),
321 env: None,
322 arguments: vec!["server".into()],
323 };
324
325 let metadata_path = destination_path.with_extension("metadata");
326 let metadata = GithubBinaryMetadata::read_from_file(&metadata_path)
327 .await
328 .ok();
329 if let Some(metadata) = metadata {
330 let validity_check = async || {
331 delegate
332 .try_exec(LanguageServerBinary {
333 path: server_path.clone(),
334 arguments: vec!["--version".into()],
335 env: None,
336 })
337 .await
338 .inspect_err(|err| {
339 log::warn!("Unable to run {server_path:?} asset, redownloading: {err:#}",)
340 })
341 };
342 if let (Some(actual_digest), Some(expected_digest)) =
343 (&metadata.digest, &expected_digest)
344 {
345 if actual_digest == expected_digest {
346 if validity_check().await.is_ok() {
347 return Ok(binary);
348 }
349 } else {
350 log::info!(
351 "SHA-256 mismatch for {destination_path:?} asset, downloading new asset. Expected: {expected_digest}, Got: {actual_digest}"
352 );
353 }
354 } else if validity_check().await.is_ok() {
355 return Ok(binary);
356 }
357 }
358
359 download_server_binary(
360 &*delegate.http_client(),
361 &url,
362 expected_digest.as_deref(),
363 &destination_path,
364 Self::GITHUB_ASSET_KIND,
365 )
366 .await?;
367 make_file_executable(&server_path).await?;
368 remove_matching(&container_dir, |path| path != destination_path).await;
369 GithubBinaryMetadata::write_to_file(
370 &GithubBinaryMetadata {
371 metadata_version: 1,
372 digest: expected_digest,
373 },
374 &metadata_path,
375 )
376 .await?;
377
378 Ok(LanguageServerBinary {
379 path: server_path,
380 env: None,
381 arguments: vec!["server".into()],
382 })
383 }
384
385 async fn cached_server_binary(
386 &self,
387 container_dir: PathBuf,
388 _: &dyn LspAdapterDelegate,
389 ) -> Option<LanguageServerBinary> {
390 maybe!(async {
391 let mut last = None;
392 let mut entries = self.fs.read_dir(&container_dir).await?;
393 while let Some(entry) = entries.next().await {
394 let path = entry?;
395 if path.extension().is_some_and(|ext| ext == "metadata") {
396 continue;
397 }
398 last = Some(path);
399 }
400
401 let path = last.context("no cached binary")?;
402 let path = match TyLspAdapter::GITHUB_ASSET_KIND {
403 AssetKind::TarGz | AssetKind::Gz => {
404 path.join(Self::build_asset_name()?.0).join("ty")
405 }
406 AssetKind::Zip => path.join("ty.exe"),
407 };
408
409 anyhow::Ok(LanguageServerBinary {
410 path,
411 env: None,
412 arguments: vec!["server".into()],
413 })
414 })
415 .await
416 .log_err()
417 }
418}
419
420pub struct PyrightLspAdapter {
421 node: NodeRuntime,
422}
423
424impl PyrightLspAdapter {
425 const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("pyright");
426 const SERVER_PATH: &str = "node_modules/pyright/langserver.index.js";
427 const NODE_MODULE_RELATIVE_SERVER_PATH: &str = "pyright/langserver.index.js";
428
429 pub fn new(node: NodeRuntime) -> Self {
430 PyrightLspAdapter { node }
431 }
432
433 async fn get_cached_server_binary(
434 container_dir: PathBuf,
435 node: &NodeRuntime,
436 ) -> Option<LanguageServerBinary> {
437 let server_path = container_dir.join(Self::SERVER_PATH);
438 if server_path.exists() {
439 Some(LanguageServerBinary {
440 path: node.binary_path().await.log_err()?,
441 env: None,
442 arguments: vec![server_path.into(), "--stdio".into()],
443 })
444 } else {
445 log::error!("missing executable in directory {:?}", server_path);
446 None
447 }
448 }
449}
450
451#[async_trait(?Send)]
452impl LspAdapter for PyrightLspAdapter {
453 fn name(&self) -> LanguageServerName {
454 Self::SERVER_NAME
455 }
456
457 async fn initialization_options(
458 self: Arc<Self>,
459 _: &Arc<dyn LspAdapterDelegate>,
460 ) -> Result<Option<Value>> {
461 // Provide minimal initialization options
462 // Virtual environment configuration will be handled through workspace configuration
463 Ok(Some(json!({
464 "python": {
465 "analysis": {
466 "autoSearchPaths": true,
467 "useLibraryCodeForTypes": true,
468 "autoImportCompletions": true
469 }
470 }
471 })))
472 }
473
474 async fn process_completions(&self, items: &mut [lsp::CompletionItem]) {
475 process_pyright_completions(items);
476 }
477
478 async fn label_for_completion(
479 &self,
480 item: &lsp::CompletionItem,
481 language: &Arc<language::Language>,
482 ) -> Option<language::CodeLabel> {
483 let label = &item.label;
484 let label_len = label.len();
485 let grammar = language.grammar()?;
486 let highlight_id = match item.kind? {
487 lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method"),
488 lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function"),
489 lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type"),
490 lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant"),
491 lsp::CompletionItemKind::VARIABLE => grammar.highlight_id_for_name("variable"),
492 _ => {
493 return None;
494 }
495 };
496 let mut text = label.clone();
497 if let Some(completion_details) = item
498 .label_details
499 .as_ref()
500 .and_then(|details| details.description.as_ref())
501 {
502 write!(&mut text, " {}", completion_details).ok();
503 }
504 Some(language::CodeLabel::filtered(
505 text,
506 label_len,
507 item.filter_text.as_deref(),
508 highlight_id
509 .map(|id| (0..label_len, id))
510 .into_iter()
511 .collect(),
512 ))
513 }
514
515 async fn label_for_symbol(
516 &self,
517 name: &str,
518 kind: lsp::SymbolKind,
519 language: &Arc<language::Language>,
520 ) -> Option<language::CodeLabel> {
521 let (text, filter_range, display_range) = match kind {
522 lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
523 let text = format!("def {}():\n", name);
524 let filter_range = 4..4 + name.len();
525 let display_range = 0..filter_range.end;
526 (text, filter_range, display_range)
527 }
528 lsp::SymbolKind::CLASS => {
529 let text = format!("class {}:", name);
530 let filter_range = 6..6 + name.len();
531 let display_range = 0..filter_range.end;
532 (text, filter_range, display_range)
533 }
534 lsp::SymbolKind::CONSTANT => {
535 let text = format!("{} = 0", name);
536 let filter_range = 0..name.len();
537 let display_range = 0..filter_range.end;
538 (text, filter_range, display_range)
539 }
540 _ => return None,
541 };
542
543 Some(language::CodeLabel::new(
544 text[display_range.clone()].to_string(),
545 filter_range,
546 language.highlight_text(&text.as_str().into(), display_range),
547 ))
548 }
549
550 async fn workspace_configuration(
551 self: Arc<Self>,
552 adapter: &Arc<dyn LspAdapterDelegate>,
553 toolchain: Option<Toolchain>,
554 _: Option<Uri>,
555 cx: &mut AsyncApp,
556 ) -> Result<Value> {
557 cx.update(move |cx| {
558 let mut user_settings =
559 language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
560 .and_then(|s| s.settings.clone())
561 .unwrap_or_default();
562
563 // If we have a detected toolchain, configure Pyright to use it
564 if let Some(toolchain) = toolchain
565 && let Ok(env) =
566 serde_json::from_value::<PythonToolchainData>(toolchain.as_json.clone())
567 {
568 if !user_settings.is_object() {
569 user_settings = Value::Object(serde_json::Map::default());
570 }
571 let object = user_settings.as_object_mut().unwrap();
572
573 let interpreter_path = toolchain.path.to_string();
574 if let Some(venv_dir) = &env.environment.prefix {
575 // Set venvPath and venv at the root level
576 // This matches the format of a pyrightconfig.json file
577 if let Some(parent) = venv_dir.parent() {
578 // Use relative path if the venv is inside the workspace
579 let venv_path = if parent == adapter.worktree_root_path() {
580 ".".to_string()
581 } else {
582 parent.to_string_lossy().into_owned()
583 };
584 object.insert("venvPath".to_string(), Value::String(venv_path));
585 }
586
587 if let Some(venv_name) = venv_dir.file_name() {
588 object.insert(
589 "venv".to_owned(),
590 Value::String(venv_name.to_string_lossy().into_owned()),
591 );
592 }
593 }
594
595 // Always set the python interpreter path
596 // Get or create the python section
597 let python = object
598 .entry("python")
599 .and_modify(|v| {
600 if !v.is_object() {
601 *v = Value::Object(serde_json::Map::default());
602 }
603 })
604 .or_insert(Value::Object(serde_json::Map::default()));
605 let python = python.as_object_mut().unwrap();
606
607 // Set both pythonPath and defaultInterpreterPath for compatibility
608 python.insert(
609 "pythonPath".to_owned(),
610 Value::String(interpreter_path.clone()),
611 );
612 python.insert(
613 "defaultInterpreterPath".to_owned(),
614 Value::String(interpreter_path),
615 );
616 }
617
618 user_settings
619 })
620 }
621}
622
623impl LspInstaller for PyrightLspAdapter {
624 type BinaryVersion = String;
625
626 async fn fetch_latest_server_version(
627 &self,
628 _: &dyn LspAdapterDelegate,
629 _: bool,
630 _: &mut AsyncApp,
631 ) -> Result<String> {
632 self.node
633 .npm_package_latest_version(Self::SERVER_NAME.as_ref())
634 .await
635 }
636
637 async fn check_if_user_installed(
638 &self,
639 delegate: &dyn LspAdapterDelegate,
640 _: Option<Toolchain>,
641 _: &AsyncApp,
642 ) -> Option<LanguageServerBinary> {
643 if let Some(pyright_bin) = delegate.which("pyright-langserver".as_ref()).await {
644 let env = delegate.shell_env().await;
645 Some(LanguageServerBinary {
646 path: pyright_bin,
647 env: Some(env),
648 arguments: vec!["--stdio".into()],
649 })
650 } else {
651 let node = delegate.which("node".as_ref()).await?;
652 let (node_modules_path, _) = delegate
653 .npm_package_installed_version(Self::SERVER_NAME.as_ref())
654 .await
655 .log_err()??;
656
657 let path = node_modules_path.join(Self::NODE_MODULE_RELATIVE_SERVER_PATH);
658
659 let env = delegate.shell_env().await;
660 Some(LanguageServerBinary {
661 path: node,
662 env: Some(env),
663 arguments: vec![path.into(), "--stdio".into()],
664 })
665 }
666 }
667
668 async fn fetch_server_binary(
669 &self,
670 latest_version: Self::BinaryVersion,
671 container_dir: PathBuf,
672 delegate: &dyn LspAdapterDelegate,
673 ) -> Result<LanguageServerBinary> {
674 let server_path = container_dir.join(Self::SERVER_PATH);
675
676 self.node
677 .npm_install_packages(
678 &container_dir,
679 &[(Self::SERVER_NAME.as_ref(), latest_version.as_str())],
680 )
681 .await?;
682
683 let env = delegate.shell_env().await;
684 Ok(LanguageServerBinary {
685 path: self.node.binary_path().await?,
686 env: Some(env),
687 arguments: vec![server_path.into(), "--stdio".into()],
688 })
689 }
690
691 async fn check_if_version_installed(
692 &self,
693 version: &Self::BinaryVersion,
694 container_dir: &PathBuf,
695 delegate: &dyn LspAdapterDelegate,
696 ) -> Option<LanguageServerBinary> {
697 let server_path = container_dir.join(Self::SERVER_PATH);
698
699 let should_install_language_server = self
700 .node
701 .should_install_npm_package(
702 Self::SERVER_NAME.as_ref(),
703 &server_path,
704 container_dir,
705 VersionStrategy::Latest(version),
706 )
707 .await;
708
709 if should_install_language_server {
710 None
711 } else {
712 let env = delegate.shell_env().await;
713 Some(LanguageServerBinary {
714 path: self.node.binary_path().await.ok()?,
715 env: Some(env),
716 arguments: vec![server_path.into(), "--stdio".into()],
717 })
718 }
719 }
720
721 async fn cached_server_binary(
722 &self,
723 container_dir: PathBuf,
724 delegate: &dyn LspAdapterDelegate,
725 ) -> Option<LanguageServerBinary> {
726 let mut binary = Self::get_cached_server_binary(container_dir, &self.node).await?;
727 binary.env = Some(delegate.shell_env().await);
728 Some(binary)
729 }
730}
731
732pub(crate) struct PythonContextProvider;
733
734const PYTHON_TEST_TARGET_TASK_VARIABLE: VariableName =
735 VariableName::Custom(Cow::Borrowed("PYTHON_TEST_TARGET"));
736
737const PYTHON_ACTIVE_TOOLCHAIN_PATH: VariableName =
738 VariableName::Custom(Cow::Borrowed("PYTHON_ACTIVE_ZED_TOOLCHAIN"));
739
740const PYTHON_MODULE_NAME_TASK_VARIABLE: VariableName =
741 VariableName::Custom(Cow::Borrowed("PYTHON_MODULE_NAME"));
742
743impl ContextProvider for PythonContextProvider {
744 fn build_context(
745 &self,
746 variables: &task::TaskVariables,
747 location: ContextLocation<'_>,
748 _: Option<HashMap<String, String>>,
749 toolchains: Arc<dyn LanguageToolchainStore>,
750 cx: &mut gpui::App,
751 ) -> Task<Result<task::TaskVariables>> {
752 let test_target =
753 match selected_test_runner(location.file_location.buffer.read(cx).file(), cx) {
754 TestRunner::UNITTEST => self.build_unittest_target(variables),
755 TestRunner::PYTEST => self.build_pytest_target(variables),
756 };
757
758 let module_target = self.build_module_target(variables);
759 let location_file = location.file_location.buffer.read(cx).file().cloned();
760 let worktree_id = location_file.as_ref().map(|f| f.worktree_id(cx));
761
762 cx.spawn(async move |cx| {
763 let active_toolchain = if let Some(worktree_id) = worktree_id {
764 let file_path = location_file
765 .as_ref()
766 .and_then(|f| f.path().parent())
767 .map(Arc::from)
768 .unwrap_or_else(|| RelPath::empty().into());
769
770 toolchains
771 .active_toolchain(worktree_id, file_path, "Python".into(), cx)
772 .await
773 .map_or_else(
774 || String::from("python3"),
775 |toolchain| toolchain.path.to_string(),
776 )
777 } else {
778 String::from("python3")
779 };
780
781 let toolchain = (PYTHON_ACTIVE_TOOLCHAIN_PATH, active_toolchain);
782
783 Ok(task::TaskVariables::from_iter(
784 test_target
785 .into_iter()
786 .chain(module_target.into_iter())
787 .chain([toolchain]),
788 ))
789 })
790 }
791
792 fn associated_tasks(
793 &self,
794 file: Option<Arc<dyn language::File>>,
795 cx: &App,
796 ) -> Task<Option<TaskTemplates>> {
797 let test_runner = selected_test_runner(file.as_ref(), cx);
798
799 let mut tasks = vec![
800 // Execute a selection
801 TaskTemplate {
802 label: "execute selection".to_owned(),
803 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
804 args: vec![
805 "-c".to_owned(),
806 VariableName::SelectedText.template_value_with_whitespace(),
807 ],
808 cwd: Some(VariableName::WorktreeRoot.template_value()),
809 ..TaskTemplate::default()
810 },
811 // Execute an entire file
812 TaskTemplate {
813 label: format!("run '{}'", VariableName::File.template_value()),
814 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
815 args: vec![VariableName::File.template_value_with_whitespace()],
816 cwd: Some(VariableName::WorktreeRoot.template_value()),
817 ..TaskTemplate::default()
818 },
819 // Execute a file as module
820 TaskTemplate {
821 label: format!("run module '{}'", VariableName::File.template_value()),
822 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
823 args: vec![
824 "-m".to_owned(),
825 PYTHON_MODULE_NAME_TASK_VARIABLE.template_value(),
826 ],
827 cwd: Some(VariableName::WorktreeRoot.template_value()),
828 tags: vec!["python-module-main-method".to_owned()],
829 ..TaskTemplate::default()
830 },
831 ];
832
833 tasks.extend(match test_runner {
834 TestRunner::UNITTEST => {
835 [
836 // Run tests for an entire file
837 TaskTemplate {
838 label: format!("unittest '{}'", VariableName::File.template_value()),
839 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
840 args: vec![
841 "-m".to_owned(),
842 "unittest".to_owned(),
843 VariableName::File.template_value_with_whitespace(),
844 ],
845 cwd: Some(VariableName::WorktreeRoot.template_value()),
846 ..TaskTemplate::default()
847 },
848 // Run test(s) for a specific target within a file
849 TaskTemplate {
850 label: "unittest $ZED_CUSTOM_PYTHON_TEST_TARGET".to_owned(),
851 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
852 args: vec![
853 "-m".to_owned(),
854 "unittest".to_owned(),
855 PYTHON_TEST_TARGET_TASK_VARIABLE.template_value_with_whitespace(),
856 ],
857 tags: vec![
858 "python-unittest-class".to_owned(),
859 "python-unittest-method".to_owned(),
860 ],
861 cwd: Some(VariableName::WorktreeRoot.template_value()),
862 ..TaskTemplate::default()
863 },
864 ]
865 }
866 TestRunner::PYTEST => {
867 [
868 // Run tests for an entire file
869 TaskTemplate {
870 label: format!("pytest '{}'", VariableName::File.template_value()),
871 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
872 args: vec![
873 "-m".to_owned(),
874 "pytest".to_owned(),
875 VariableName::File.template_value_with_whitespace(),
876 ],
877 cwd: Some(VariableName::WorktreeRoot.template_value()),
878 ..TaskTemplate::default()
879 },
880 // Run test(s) for a specific target within a file
881 TaskTemplate {
882 label: "pytest $ZED_CUSTOM_PYTHON_TEST_TARGET".to_owned(),
883 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
884 args: vec![
885 "-m".to_owned(),
886 "pytest".to_owned(),
887 PYTHON_TEST_TARGET_TASK_VARIABLE.template_value_with_whitespace(),
888 ],
889 cwd: Some(VariableName::WorktreeRoot.template_value()),
890 tags: vec![
891 "python-pytest-class".to_owned(),
892 "python-pytest-method".to_owned(),
893 ],
894 ..TaskTemplate::default()
895 },
896 ]
897 }
898 });
899
900 Task::ready(Some(TaskTemplates(tasks)))
901 }
902}
903
904fn selected_test_runner(location: Option<&Arc<dyn language::File>>, cx: &App) -> TestRunner {
905 const TEST_RUNNER_VARIABLE: &str = "TEST_RUNNER";
906 language_settings(Some(LanguageName::new("Python")), location, cx)
907 .tasks
908 .variables
909 .get(TEST_RUNNER_VARIABLE)
910 .and_then(|val| TestRunner::from_str(val).ok())
911 .unwrap_or(TestRunner::PYTEST)
912}
913
914impl PythonContextProvider {
915 fn build_unittest_target(
916 &self,
917 variables: &task::TaskVariables,
918 ) -> Option<(VariableName, String)> {
919 let python_module_name =
920 python_module_name_from_relative_path(variables.get(&VariableName::RelativeFile)?)?;
921
922 let unittest_class_name =
923 variables.get(&VariableName::Custom(Cow::Borrowed("_unittest_class_name")));
924
925 let unittest_method_name = variables.get(&VariableName::Custom(Cow::Borrowed(
926 "_unittest_method_name",
927 )));
928
929 let unittest_target_str = match (unittest_class_name, unittest_method_name) {
930 (Some(class_name), Some(method_name)) => {
931 format!("{python_module_name}.{class_name}.{method_name}")
932 }
933 (Some(class_name), None) => format!("{python_module_name}.{class_name}"),
934 (None, None) => python_module_name,
935 // should never happen, a TestCase class is the unit of testing
936 (None, Some(_)) => return None,
937 };
938
939 Some((
940 PYTHON_TEST_TARGET_TASK_VARIABLE.clone(),
941 unittest_target_str,
942 ))
943 }
944
945 fn build_pytest_target(
946 &self,
947 variables: &task::TaskVariables,
948 ) -> Option<(VariableName, String)> {
949 let file_path = variables.get(&VariableName::RelativeFile)?;
950
951 let pytest_class_name =
952 variables.get(&VariableName::Custom(Cow::Borrowed("_pytest_class_name")));
953
954 let pytest_method_name =
955 variables.get(&VariableName::Custom(Cow::Borrowed("_pytest_method_name")));
956
957 let pytest_target_str = match (pytest_class_name, pytest_method_name) {
958 (Some(class_name), Some(method_name)) => {
959 format!("{file_path}::{class_name}::{method_name}")
960 }
961 (Some(class_name), None) => {
962 format!("{file_path}::{class_name}")
963 }
964 (None, Some(method_name)) => {
965 format!("{file_path}::{method_name}")
966 }
967 (None, None) => file_path.to_string(),
968 };
969
970 Some((PYTHON_TEST_TARGET_TASK_VARIABLE.clone(), pytest_target_str))
971 }
972
973 fn build_module_target(
974 &self,
975 variables: &task::TaskVariables,
976 ) -> Result<(VariableName, String)> {
977 let python_module_name = variables
978 .get(&VariableName::RelativeFile)
979 .and_then(|module| python_module_name_from_relative_path(module))
980 .unwrap_or_default();
981
982 let module_target = (PYTHON_MODULE_NAME_TASK_VARIABLE.clone(), python_module_name);
983
984 Ok(module_target)
985 }
986}
987
988fn python_module_name_from_relative_path(relative_path: &str) -> Option<String> {
989 let rel_path = RelPath::new(relative_path.as_ref(), PathStyle::local()).ok()?;
990 let path_with_dots = rel_path.display(PathStyle::Posix).replace('/', ".");
991 Some(
992 path_with_dots
993 .strip_suffix(".py")
994 .map(ToOwned::to_owned)
995 .unwrap_or(path_with_dots),
996 )
997}
998
999fn is_python_env_global(k: &PythonEnvironmentKind) -> bool {
1000 matches!(
1001 k,
1002 PythonEnvironmentKind::Homebrew
1003 | PythonEnvironmentKind::Pyenv
1004 | PythonEnvironmentKind::GlobalPaths
1005 | PythonEnvironmentKind::MacPythonOrg
1006 | PythonEnvironmentKind::MacCommandLineTools
1007 | PythonEnvironmentKind::LinuxGlobal
1008 | PythonEnvironmentKind::MacXCode
1009 | PythonEnvironmentKind::WindowsStore
1010 | PythonEnvironmentKind::WindowsRegistry
1011 )
1012}
1013
1014fn python_env_kind_display(k: &PythonEnvironmentKind) -> &'static str {
1015 match k {
1016 PythonEnvironmentKind::Conda => "Conda",
1017 PythonEnvironmentKind::Pixi => "pixi",
1018 PythonEnvironmentKind::Homebrew => "Homebrew",
1019 PythonEnvironmentKind::Pyenv => "global (Pyenv)",
1020 PythonEnvironmentKind::GlobalPaths => "global",
1021 PythonEnvironmentKind::PyenvVirtualEnv => "Pyenv",
1022 PythonEnvironmentKind::Pipenv => "Pipenv",
1023 PythonEnvironmentKind::Poetry => "Poetry",
1024 PythonEnvironmentKind::MacPythonOrg => "global (Python.org)",
1025 PythonEnvironmentKind::MacCommandLineTools => "global (Command Line Tools for Xcode)",
1026 PythonEnvironmentKind::LinuxGlobal => "global",
1027 PythonEnvironmentKind::MacXCode => "global (Xcode)",
1028 PythonEnvironmentKind::Venv => "venv",
1029 PythonEnvironmentKind::VirtualEnv => "virtualenv",
1030 PythonEnvironmentKind::VirtualEnvWrapper => "virtualenvwrapper",
1031 PythonEnvironmentKind::WindowsStore => "global (Windows Store)",
1032 PythonEnvironmentKind::WindowsRegistry => "global (Windows Registry)",
1033 PythonEnvironmentKind::Uv => "uv",
1034 PythonEnvironmentKind::UvWorkspace => "uv (Workspace)",
1035 }
1036}
1037
1038pub(crate) struct PythonToolchainProvider;
1039
1040static ENV_PRIORITY_LIST: &[PythonEnvironmentKind] = &[
1041 // Prioritize non-Conda environments.
1042 PythonEnvironmentKind::UvWorkspace,
1043 PythonEnvironmentKind::Uv,
1044 PythonEnvironmentKind::Poetry,
1045 PythonEnvironmentKind::Pipenv,
1046 PythonEnvironmentKind::VirtualEnvWrapper,
1047 PythonEnvironmentKind::Venv,
1048 PythonEnvironmentKind::VirtualEnv,
1049 PythonEnvironmentKind::PyenvVirtualEnv,
1050 PythonEnvironmentKind::Pixi,
1051 PythonEnvironmentKind::Conda,
1052 PythonEnvironmentKind::Pyenv,
1053 PythonEnvironmentKind::GlobalPaths,
1054 PythonEnvironmentKind::Homebrew,
1055];
1056
1057fn env_priority(kind: Option<PythonEnvironmentKind>) -> usize {
1058 if let Some(kind) = kind {
1059 ENV_PRIORITY_LIST
1060 .iter()
1061 .position(|blessed_env| blessed_env == &kind)
1062 .unwrap_or(ENV_PRIORITY_LIST.len())
1063 } else {
1064 // Unknown toolchains are less useful than non-blessed ones.
1065 ENV_PRIORITY_LIST.len() + 1
1066 }
1067}
1068
1069/// Return the name of environment declared in <worktree-root/.venv.
1070///
1071/// https://virtualfish.readthedocs.io/en/latest/plugins.html#auto-activation-auto-activation
1072async fn get_worktree_venv_declaration(worktree_root: &Path) -> Option<String> {
1073 let file = async_fs::File::open(worktree_root.join(".venv"))
1074 .await
1075 .ok()?;
1076 let mut venv_name = String::new();
1077 smol::io::BufReader::new(file)
1078 .read_line(&mut venv_name)
1079 .await
1080 .ok()?;
1081 Some(venv_name.trim().to_string())
1082}
1083
1084fn get_venv_parent_dir(env: &PythonEnvironment) -> Option<PathBuf> {
1085 // If global, we aren't a virtual environment
1086 if let Some(kind) = env.kind
1087 && is_python_env_global(&kind)
1088 {
1089 return None;
1090 }
1091
1092 // Check to be sure we are a virtual environment using pet's most generic
1093 // virtual environment type, VirtualEnv
1094 let venv = env
1095 .executable
1096 .as_ref()
1097 .and_then(|p| p.parent())
1098 .and_then(|p| p.parent())
1099 .filter(|p| is_virtualenv_dir(p))?;
1100
1101 venv.parent().map(|parent| parent.to_path_buf())
1102}
1103
1104fn wr_distance(wr: &PathBuf, venv: Option<&PathBuf>) -> usize {
1105 if let Some(venv) = venv
1106 && let Ok(p) = venv.strip_prefix(wr)
1107 {
1108 p.components().count()
1109 } else {
1110 usize::MAX
1111 }
1112}
1113
1114#[async_trait]
1115impl ToolchainLister for PythonToolchainProvider {
1116 async fn list(
1117 &self,
1118 worktree_root: PathBuf,
1119 subroot_relative_path: Arc<RelPath>,
1120 project_env: Option<HashMap<String, String>>,
1121 fs: &dyn Fs,
1122 ) -> ToolchainList {
1123 let env = project_env.unwrap_or_default();
1124 let environment = EnvironmentApi::from_env(&env);
1125 let locators = pet::locators::create_locators(
1126 Arc::new(pet_conda::Conda::from(&environment)),
1127 Arc::new(pet_poetry::Poetry::from(&environment)),
1128 &environment,
1129 );
1130 let mut config = Configuration::default();
1131
1132 // `.ancestors()` will yield at least one path, so in case of empty `subroot_relative_path`, we'll just use
1133 // worktree root as the workspace directory.
1134 config.workspace_directories = Some(
1135 subroot_relative_path
1136 .ancestors()
1137 .map(|ancestor| worktree_root.join(ancestor.as_std_path()))
1138 .collect(),
1139 );
1140 for locator in locators.iter() {
1141 locator.configure(&config);
1142 }
1143
1144 let reporter = pet_reporter::collect::create_reporter();
1145 pet::find::find_and_report_envs(&reporter, config, &locators, &environment, None);
1146
1147 let mut toolchains = reporter
1148 .environments
1149 .lock()
1150 .map_or(Vec::new(), |mut guard| std::mem::take(&mut guard));
1151
1152 let wr = worktree_root;
1153 let wr_venv = get_worktree_venv_declaration(&wr).await;
1154 // Sort detected environments by:
1155 // environment name matching activation file (<workdir>/.venv)
1156 // environment project dir matching worktree_root
1157 // general env priority
1158 // environment path matching the CONDA_PREFIX env var
1159 // executable path
1160 toolchains.sort_by(|lhs, rhs| {
1161 // Compare venv names against worktree .venv file
1162 let venv_ordering =
1163 wr_venv
1164 .as_ref()
1165 .map_or(Ordering::Equal, |venv| match (&lhs.name, &rhs.name) {
1166 (Some(l), Some(r)) => (r == venv).cmp(&(l == venv)),
1167 (Some(l), None) if l == venv => Ordering::Less,
1168 (None, Some(r)) if r == venv => Ordering::Greater,
1169 _ => Ordering::Equal,
1170 });
1171
1172 // Compare project paths against worktree root
1173 let proj_ordering = || {
1174 let lhs_project = lhs.project.clone().or_else(|| get_venv_parent_dir(lhs));
1175 let rhs_project = rhs.project.clone().or_else(|| get_venv_parent_dir(rhs));
1176 wr_distance(&wr, lhs_project.as_ref()).cmp(&wr_distance(&wr, rhs_project.as_ref()))
1177 };
1178
1179 // Compare environment priorities
1180 let priority_ordering = || env_priority(lhs.kind).cmp(&env_priority(rhs.kind));
1181
1182 // Compare conda prefixes
1183 let conda_ordering = || {
1184 if lhs.kind == Some(PythonEnvironmentKind::Conda) {
1185 environment
1186 .get_env_var("CONDA_PREFIX".to_string())
1187 .map(|conda_prefix| {
1188 let is_match = |exe: &Option<PathBuf>| {
1189 exe.as_ref().is_some_and(|e| e.starts_with(&conda_prefix))
1190 };
1191 match (is_match(&lhs.executable), is_match(&rhs.executable)) {
1192 (true, false) => Ordering::Less,
1193 (false, true) => Ordering::Greater,
1194 _ => Ordering::Equal,
1195 }
1196 })
1197 .unwrap_or(Ordering::Equal)
1198 } else {
1199 Ordering::Equal
1200 }
1201 };
1202
1203 // Compare Python executables
1204 let exe_ordering = || lhs.executable.cmp(&rhs.executable);
1205
1206 venv_ordering
1207 .then_with(proj_ordering)
1208 .then_with(priority_ordering)
1209 .then_with(conda_ordering)
1210 .then_with(exe_ordering)
1211 });
1212
1213 let mut out_toolchains = Vec::new();
1214 for toolchain in toolchains {
1215 let Some(toolchain) = venv_to_toolchain(toolchain, fs).await else {
1216 continue;
1217 };
1218 out_toolchains.push(toolchain);
1219 }
1220 out_toolchains.dedup();
1221 ToolchainList {
1222 toolchains: out_toolchains,
1223 default: None,
1224 groups: Default::default(),
1225 }
1226 }
1227 fn meta(&self) -> ToolchainMetadata {
1228 ToolchainMetadata {
1229 term: SharedString::new_static("Virtual Environment"),
1230 new_toolchain_placeholder: SharedString::new_static(
1231 "A path to the python3 executable within a virtual environment, or path to virtual environment itself",
1232 ),
1233 manifest_name: ManifestName::from(SharedString::new_static("pyproject.toml")),
1234 }
1235 }
1236
1237 async fn resolve(
1238 &self,
1239 path: PathBuf,
1240 env: Option<HashMap<String, String>>,
1241 fs: &dyn Fs,
1242 ) -> anyhow::Result<Toolchain> {
1243 let env = env.unwrap_or_default();
1244 let environment = EnvironmentApi::from_env(&env);
1245 let locators = pet::locators::create_locators(
1246 Arc::new(pet_conda::Conda::from(&environment)),
1247 Arc::new(pet_poetry::Poetry::from(&environment)),
1248 &environment,
1249 );
1250 let toolchain = pet::resolve::resolve_environment(&path, &locators, &environment)
1251 .context("Could not find a virtual environment in provided path")?;
1252 let venv = toolchain.resolved.unwrap_or(toolchain.discovered);
1253 venv_to_toolchain(venv, fs)
1254 .await
1255 .context("Could not convert a venv into a toolchain")
1256 }
1257
1258 fn activation_script(&self, toolchain: &Toolchain, shell: ShellKind, cx: &App) -> Vec<String> {
1259 let Ok(toolchain) =
1260 serde_json::from_value::<PythonToolchainData>(toolchain.as_json.clone())
1261 else {
1262 return vec![];
1263 };
1264
1265 log::debug!("(Python) Composing activation script for toolchain {toolchain:?}");
1266
1267 let mut activation_script = vec![];
1268
1269 match toolchain.environment.kind {
1270 Some(PythonEnvironmentKind::Conda) => {
1271 let settings = TerminalSettings::get_global(cx);
1272 let conda_manager = settings
1273 .detect_venv
1274 .as_option()
1275 .map(|venv| venv.conda_manager)
1276 .unwrap_or(settings::CondaManager::Auto);
1277
1278 let manager = match conda_manager {
1279 settings::CondaManager::Conda => "conda",
1280 settings::CondaManager::Mamba => "mamba",
1281 settings::CondaManager::Micromamba => "micromamba",
1282 settings::CondaManager::Auto => {
1283 // When auto, prefer the detected manager or fall back to conda
1284 toolchain
1285 .environment
1286 .manager
1287 .as_ref()
1288 .and_then(|m| m.executable.file_name())
1289 .and_then(|name| name.to_str())
1290 .filter(|name| matches!(*name, "conda" | "mamba" | "micromamba"))
1291 .unwrap_or("conda")
1292 }
1293 };
1294
1295 if let Some(name) = &toolchain.environment.name {
1296 activation_script.push(format!("{manager} activate {name}"));
1297 } else {
1298 activation_script.push(format!("{manager} activate base"));
1299 }
1300 }
1301 Some(PythonEnvironmentKind::Venv | PythonEnvironmentKind::VirtualEnv) => {
1302 if let Some(activation_scripts) = &toolchain.activation_scripts {
1303 if let Some(activate_script_path) = activation_scripts.get(&shell) {
1304 let activate_keyword = shell.activate_keyword();
1305 if let Some(quoted) =
1306 shell.try_quote(&activate_script_path.to_string_lossy())
1307 {
1308 activation_script.push(format!("{activate_keyword} {quoted}"));
1309 }
1310 }
1311 }
1312 }
1313 Some(PythonEnvironmentKind::Pyenv) => {
1314 let Some(manager) = &toolchain.environment.manager else {
1315 return vec![];
1316 };
1317 let version = toolchain.environment.version.as_deref().unwrap_or("system");
1318 let pyenv = &manager.executable;
1319 let pyenv = pyenv.display();
1320 activation_script.extend(match shell {
1321 ShellKind::Fish => Some(format!("\"{pyenv}\" shell - fish {version}")),
1322 ShellKind::Posix => Some(format!("\"{pyenv}\" shell - sh {version}")),
1323 ShellKind::Nushell => Some(format!("^\"{pyenv}\" shell - nu {version}")),
1324 ShellKind::PowerShell => None,
1325 ShellKind::Csh => None,
1326 ShellKind::Tcsh => None,
1327 ShellKind::Cmd => None,
1328 ShellKind::Rc => None,
1329 ShellKind::Xonsh => None,
1330 ShellKind::Elvish => None,
1331 })
1332 }
1333 _ => {}
1334 }
1335 activation_script
1336 }
1337}
1338
1339async fn venv_to_toolchain(venv: PythonEnvironment, fs: &dyn Fs) -> Option<Toolchain> {
1340 let mut name = String::from("Python");
1341 if let Some(ref version) = venv.version {
1342 _ = write!(name, " {version}");
1343 }
1344
1345 let name_and_kind = match (&venv.name, &venv.kind) {
1346 (Some(name), Some(kind)) => Some(format!("({name}; {})", python_env_kind_display(kind))),
1347 (Some(name), None) => Some(format!("({name})")),
1348 (None, Some(kind)) => Some(format!("({})", python_env_kind_display(kind))),
1349 (None, None) => None,
1350 };
1351
1352 if let Some(nk) = name_and_kind {
1353 _ = write!(name, " {nk}");
1354 }
1355
1356 let mut activation_scripts = HashMap::default();
1357 match venv.kind {
1358 Some(PythonEnvironmentKind::Venv | PythonEnvironmentKind::VirtualEnv) => {
1359 resolve_venv_activation_scripts(&venv, fs, &mut activation_scripts).await
1360 }
1361 _ => {}
1362 }
1363 let data = PythonToolchainData {
1364 environment: venv,
1365 activation_scripts: Some(activation_scripts),
1366 };
1367
1368 Some(Toolchain {
1369 name: name.into(),
1370 path: data
1371 .environment
1372 .executable
1373 .as_ref()?
1374 .to_str()?
1375 .to_owned()
1376 .into(),
1377 language_name: LanguageName::new("Python"),
1378 as_json: serde_json::to_value(data).ok()?,
1379 })
1380}
1381
1382async fn resolve_venv_activation_scripts(
1383 venv: &PythonEnvironment,
1384 fs: &dyn Fs,
1385 activation_scripts: &mut HashMap<ShellKind, PathBuf>,
1386) {
1387 log::debug!("(Python) Resolving activation scripts for venv toolchain {venv:?}");
1388 if let Some(prefix) = &venv.prefix {
1389 for (shell_kind, script_name) in &[
1390 (ShellKind::Posix, "activate"),
1391 (ShellKind::Rc, "activate"),
1392 (ShellKind::Csh, "activate.csh"),
1393 (ShellKind::Tcsh, "activate.csh"),
1394 (ShellKind::Fish, "activate.fish"),
1395 (ShellKind::Nushell, "activate.nu"),
1396 (ShellKind::PowerShell, "activate.ps1"),
1397 (ShellKind::Cmd, "activate.bat"),
1398 (ShellKind::Xonsh, "activate.xsh"),
1399 ] {
1400 let path = prefix.join(BINARY_DIR).join(script_name);
1401
1402 log::debug!("Trying path: {}", path.display());
1403
1404 if fs.is_file(&path).await {
1405 activation_scripts.insert(*shell_kind, path);
1406 }
1407 }
1408 }
1409}
1410
1411pub struct EnvironmentApi<'a> {
1412 global_search_locations: Arc<Mutex<Vec<PathBuf>>>,
1413 project_env: &'a HashMap<String, String>,
1414 pet_env: pet_core::os_environment::EnvironmentApi,
1415}
1416
1417impl<'a> EnvironmentApi<'a> {
1418 pub fn from_env(project_env: &'a HashMap<String, String>) -> Self {
1419 let paths = project_env
1420 .get("PATH")
1421 .map(|p| std::env::split_paths(p).collect())
1422 .unwrap_or_default();
1423
1424 EnvironmentApi {
1425 global_search_locations: Arc::new(Mutex::new(paths)),
1426 project_env,
1427 pet_env: pet_core::os_environment::EnvironmentApi::new(),
1428 }
1429 }
1430
1431 fn user_home(&self) -> Option<PathBuf> {
1432 self.project_env
1433 .get("HOME")
1434 .or_else(|| self.project_env.get("USERPROFILE"))
1435 .map(|home| pet_fs::path::norm_case(PathBuf::from(home)))
1436 .or_else(|| self.pet_env.get_user_home())
1437 }
1438}
1439
1440impl pet_core::os_environment::Environment for EnvironmentApi<'_> {
1441 fn get_user_home(&self) -> Option<PathBuf> {
1442 self.user_home()
1443 }
1444
1445 fn get_root(&self) -> Option<PathBuf> {
1446 None
1447 }
1448
1449 fn get_env_var(&self, key: String) -> Option<String> {
1450 self.project_env
1451 .get(&key)
1452 .cloned()
1453 .or_else(|| self.pet_env.get_env_var(key))
1454 }
1455
1456 fn get_know_global_search_locations(&self) -> Vec<PathBuf> {
1457 if self.global_search_locations.lock().is_empty() {
1458 let mut paths = std::env::split_paths(
1459 &self
1460 .get_env_var("PATH".to_string())
1461 .or_else(|| self.get_env_var("Path".to_string()))
1462 .unwrap_or_default(),
1463 )
1464 .collect::<Vec<PathBuf>>();
1465
1466 log::trace!("Env PATH: {:?}", paths);
1467 for p in self.pet_env.get_know_global_search_locations() {
1468 if !paths.contains(&p) {
1469 paths.push(p);
1470 }
1471 }
1472
1473 let mut paths = paths
1474 .into_iter()
1475 .filter(|p| p.exists())
1476 .collect::<Vec<PathBuf>>();
1477
1478 self.global_search_locations.lock().append(&mut paths);
1479 }
1480 self.global_search_locations.lock().clone()
1481 }
1482}
1483
1484pub(crate) struct PyLspAdapter {
1485 python_venv_base: OnceCell<Result<Arc<Path>, String>>,
1486}
1487impl PyLspAdapter {
1488 const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("pylsp");
1489 pub(crate) fn new() -> Self {
1490 Self {
1491 python_venv_base: OnceCell::new(),
1492 }
1493 }
1494 async fn ensure_venv(delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>> {
1495 let python_path = Self::find_base_python(delegate)
1496 .await
1497 .with_context(|| {
1498 let mut message = "Could not find Python installation for PyLSP".to_owned();
1499 if cfg!(windows){
1500 message.push_str(". Install Python from the Microsoft Store, or manually from https://www.python.org/downloads/windows.")
1501 }
1502 message
1503 })?;
1504 let work_dir = delegate
1505 .language_server_download_dir(&Self::SERVER_NAME)
1506 .await
1507 .context("Could not get working directory for PyLSP")?;
1508 let mut path = PathBuf::from(work_dir.as_ref());
1509 path.push("pylsp-venv");
1510 if !path.exists() {
1511 util::command::new_smol_command(python_path)
1512 .arg("-m")
1513 .arg("venv")
1514 .arg("pylsp-venv")
1515 .current_dir(work_dir)
1516 .spawn()?
1517 .output()
1518 .await?;
1519 }
1520
1521 Ok(path.into())
1522 }
1523 // Find "baseline", user python version from which we'll create our own venv.
1524 async fn find_base_python(delegate: &dyn LspAdapterDelegate) -> Option<PathBuf> {
1525 for path in ["python3", "python"] {
1526 let Some(path) = delegate.which(path.as_ref()).await else {
1527 continue;
1528 };
1529 // Try to detect situations where `python3` exists but is not a real Python interpreter.
1530 // Notably, on fresh Windows installs, `python3` is a shim that opens the Microsoft Store app
1531 // when run with no arguments, and just fails otherwise.
1532 let Some(output) = new_smol_command(&path)
1533 .args(["-c", "print(1 + 2)"])
1534 .output()
1535 .await
1536 .ok()
1537 else {
1538 continue;
1539 };
1540 if output.stdout.trim_ascii() != b"3" {
1541 continue;
1542 }
1543 return Some(path);
1544 }
1545 None
1546 }
1547
1548 async fn base_venv(&self, delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>, String> {
1549 self.python_venv_base
1550 .get_or_init(move || async move {
1551 Self::ensure_venv(delegate)
1552 .await
1553 .map_err(|e| format!("{e}"))
1554 })
1555 .await
1556 .clone()
1557 }
1558}
1559
1560const BINARY_DIR: &str = if cfg!(target_os = "windows") {
1561 "Scripts"
1562} else {
1563 "bin"
1564};
1565
1566#[async_trait(?Send)]
1567impl LspAdapter for PyLspAdapter {
1568 fn name(&self) -> LanguageServerName {
1569 Self::SERVER_NAME
1570 }
1571
1572 async fn process_completions(&self, _items: &mut [lsp::CompletionItem]) {}
1573
1574 async fn label_for_completion(
1575 &self,
1576 item: &lsp::CompletionItem,
1577 language: &Arc<language::Language>,
1578 ) -> Option<language::CodeLabel> {
1579 let label = &item.label;
1580 let label_len = label.len();
1581 let grammar = language.grammar()?;
1582 let highlight_id = match item.kind? {
1583 lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method")?,
1584 lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function")?,
1585 lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type")?,
1586 lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant")?,
1587 _ => return None,
1588 };
1589 Some(language::CodeLabel::filtered(
1590 label.clone(),
1591 label_len,
1592 item.filter_text.as_deref(),
1593 vec![(0..label.len(), highlight_id)],
1594 ))
1595 }
1596
1597 async fn label_for_symbol(
1598 &self,
1599 name: &str,
1600 kind: lsp::SymbolKind,
1601 language: &Arc<language::Language>,
1602 ) -> Option<language::CodeLabel> {
1603 let (text, filter_range, display_range) = match kind {
1604 lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
1605 let text = format!("def {}():\n", name);
1606 let filter_range = 4..4 + name.len();
1607 let display_range = 0..filter_range.end;
1608 (text, filter_range, display_range)
1609 }
1610 lsp::SymbolKind::CLASS => {
1611 let text = format!("class {}:", name);
1612 let filter_range = 6..6 + name.len();
1613 let display_range = 0..filter_range.end;
1614 (text, filter_range, display_range)
1615 }
1616 lsp::SymbolKind::CONSTANT => {
1617 let text = format!("{} = 0", name);
1618 let filter_range = 0..name.len();
1619 let display_range = 0..filter_range.end;
1620 (text, filter_range, display_range)
1621 }
1622 _ => return None,
1623 };
1624 Some(language::CodeLabel::new(
1625 text[display_range.clone()].to_string(),
1626 filter_range,
1627 language.highlight_text(&text.as_str().into(), display_range),
1628 ))
1629 }
1630
1631 async fn workspace_configuration(
1632 self: Arc<Self>,
1633 adapter: &Arc<dyn LspAdapterDelegate>,
1634 toolchain: Option<Toolchain>,
1635 _: Option<Uri>,
1636 cx: &mut AsyncApp,
1637 ) -> Result<Value> {
1638 cx.update(move |cx| {
1639 let mut user_settings =
1640 language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
1641 .and_then(|s| s.settings.clone())
1642 .unwrap_or_else(|| {
1643 json!({
1644 "plugins": {
1645 "pycodestyle": {"enabled": false},
1646 "rope_autoimport": {"enabled": true, "memory": true},
1647 "pylsp_mypy": {"enabled": false}
1648 },
1649 "rope": {
1650 "ropeFolder": null
1651 },
1652 })
1653 });
1654
1655 // If user did not explicitly modify their python venv, use one from picker.
1656 if let Some(toolchain) = toolchain {
1657 if !user_settings.is_object() {
1658 user_settings = Value::Object(serde_json::Map::default());
1659 }
1660 let object = user_settings.as_object_mut().unwrap();
1661 if let Some(python) = object
1662 .entry("plugins")
1663 .or_insert(Value::Object(serde_json::Map::default()))
1664 .as_object_mut()
1665 {
1666 if let Some(jedi) = python
1667 .entry("jedi")
1668 .or_insert(Value::Object(serde_json::Map::default()))
1669 .as_object_mut()
1670 {
1671 jedi.entry("environment".to_string())
1672 .or_insert_with(|| Value::String(toolchain.path.clone().into()));
1673 }
1674 if let Some(pylint) = python
1675 .entry("pylsp_mypy")
1676 .or_insert(Value::Object(serde_json::Map::default()))
1677 .as_object_mut()
1678 {
1679 pylint.entry("overrides".to_string()).or_insert_with(|| {
1680 Value::Array(vec![
1681 Value::String("--python-executable".into()),
1682 Value::String(toolchain.path.into()),
1683 Value::String("--cache-dir=/dev/null".into()),
1684 Value::Bool(true),
1685 ])
1686 });
1687 }
1688 }
1689 }
1690 user_settings = Value::Object(serde_json::Map::from_iter([(
1691 "pylsp".to_string(),
1692 user_settings,
1693 )]));
1694
1695 user_settings
1696 })
1697 }
1698}
1699
1700impl LspInstaller for PyLspAdapter {
1701 type BinaryVersion = ();
1702 async fn check_if_user_installed(
1703 &self,
1704 delegate: &dyn LspAdapterDelegate,
1705 toolchain: Option<Toolchain>,
1706 _: &AsyncApp,
1707 ) -> Option<LanguageServerBinary> {
1708 if let Some(pylsp_bin) = delegate.which(Self::SERVER_NAME.as_ref()).await {
1709 let env = delegate.shell_env().await;
1710 Some(LanguageServerBinary {
1711 path: pylsp_bin,
1712 env: Some(env),
1713 arguments: vec![],
1714 })
1715 } else {
1716 let toolchain = toolchain?;
1717 let pylsp_path = Path::new(toolchain.path.as_ref()).parent()?.join("pylsp");
1718 pylsp_path.exists().then(|| LanguageServerBinary {
1719 path: toolchain.path.to_string().into(),
1720 arguments: vec![pylsp_path.into()],
1721 env: None,
1722 })
1723 }
1724 }
1725
1726 async fn fetch_latest_server_version(
1727 &self,
1728 _: &dyn LspAdapterDelegate,
1729 _: bool,
1730 _: &mut AsyncApp,
1731 ) -> Result<()> {
1732 Ok(())
1733 }
1734
1735 async fn fetch_server_binary(
1736 &self,
1737 _: (),
1738 _: PathBuf,
1739 delegate: &dyn LspAdapterDelegate,
1740 ) -> Result<LanguageServerBinary> {
1741 let venv = self.base_venv(delegate).await.map_err(|e| anyhow!(e))?;
1742 let pip_path = venv.join(BINARY_DIR).join("pip3");
1743 ensure!(
1744 util::command::new_smol_command(pip_path.as_path())
1745 .arg("install")
1746 .arg("python-lsp-server[all]")
1747 .arg("--upgrade")
1748 .output()
1749 .await?
1750 .status
1751 .success(),
1752 "python-lsp-server[all] installation failed"
1753 );
1754 ensure!(
1755 util::command::new_smol_command(pip_path)
1756 .arg("install")
1757 .arg("pylsp-mypy")
1758 .arg("--upgrade")
1759 .output()
1760 .await?
1761 .status
1762 .success(),
1763 "pylsp-mypy installation failed"
1764 );
1765 let pylsp = venv.join(BINARY_DIR).join("pylsp");
1766 ensure!(
1767 delegate.which(pylsp.as_os_str()).await.is_some(),
1768 "pylsp installation was incomplete"
1769 );
1770 Ok(LanguageServerBinary {
1771 path: pylsp,
1772 env: None,
1773 arguments: vec![],
1774 })
1775 }
1776
1777 async fn cached_server_binary(
1778 &self,
1779 _: PathBuf,
1780 delegate: &dyn LspAdapterDelegate,
1781 ) -> Option<LanguageServerBinary> {
1782 let venv = self.base_venv(delegate).await.ok()?;
1783 let pylsp = venv.join(BINARY_DIR).join("pylsp");
1784 delegate.which(pylsp.as_os_str()).await?;
1785 Some(LanguageServerBinary {
1786 path: pylsp,
1787 env: None,
1788 arguments: vec![],
1789 })
1790 }
1791}
1792
1793pub(crate) struct BasedPyrightLspAdapter {
1794 node: NodeRuntime,
1795}
1796
1797impl BasedPyrightLspAdapter {
1798 const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("basedpyright");
1799 const BINARY_NAME: &'static str = "basedpyright-langserver";
1800 const SERVER_PATH: &str = "node_modules/basedpyright/langserver.index.js";
1801 const NODE_MODULE_RELATIVE_SERVER_PATH: &str = "basedpyright/langserver.index.js";
1802
1803 pub(crate) fn new(node: NodeRuntime) -> Self {
1804 BasedPyrightLspAdapter { node }
1805 }
1806
1807 async fn get_cached_server_binary(
1808 container_dir: PathBuf,
1809 node: &NodeRuntime,
1810 ) -> Option<LanguageServerBinary> {
1811 let server_path = container_dir.join(Self::SERVER_PATH);
1812 if server_path.exists() {
1813 Some(LanguageServerBinary {
1814 path: node.binary_path().await.log_err()?,
1815 env: None,
1816 arguments: vec![server_path.into(), "--stdio".into()],
1817 })
1818 } else {
1819 log::error!("missing executable in directory {:?}", server_path);
1820 None
1821 }
1822 }
1823}
1824
1825#[async_trait(?Send)]
1826impl LspAdapter for BasedPyrightLspAdapter {
1827 fn name(&self) -> LanguageServerName {
1828 Self::SERVER_NAME
1829 }
1830
1831 async fn initialization_options(
1832 self: Arc<Self>,
1833 _: &Arc<dyn LspAdapterDelegate>,
1834 ) -> Result<Option<Value>> {
1835 // Provide minimal initialization options
1836 // Virtual environment configuration will be handled through workspace configuration
1837 Ok(Some(json!({
1838 "python": {
1839 "analysis": {
1840 "autoSearchPaths": true,
1841 "useLibraryCodeForTypes": true,
1842 "autoImportCompletions": true
1843 }
1844 }
1845 })))
1846 }
1847
1848 async fn process_completions(&self, items: &mut [lsp::CompletionItem]) {
1849 process_pyright_completions(items);
1850 }
1851
1852 async fn label_for_completion(
1853 &self,
1854 item: &lsp::CompletionItem,
1855 language: &Arc<language::Language>,
1856 ) -> Option<language::CodeLabel> {
1857 let label = &item.label;
1858 let label_len = label.len();
1859 let grammar = language.grammar()?;
1860 let highlight_id = match item.kind? {
1861 lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method"),
1862 lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function"),
1863 lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type"),
1864 lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant"),
1865 lsp::CompletionItemKind::VARIABLE => grammar.highlight_id_for_name("variable"),
1866 _ => {
1867 return None;
1868 }
1869 };
1870 let mut text = label.clone();
1871 if let Some(completion_details) = item
1872 .label_details
1873 .as_ref()
1874 .and_then(|details| details.description.as_ref())
1875 {
1876 write!(&mut text, " {}", completion_details).ok();
1877 }
1878 Some(language::CodeLabel::filtered(
1879 text,
1880 label_len,
1881 item.filter_text.as_deref(),
1882 highlight_id
1883 .map(|id| (0..label.len(), id))
1884 .into_iter()
1885 .collect(),
1886 ))
1887 }
1888
1889 async fn label_for_symbol(
1890 &self,
1891 name: &str,
1892 kind: lsp::SymbolKind,
1893 language: &Arc<language::Language>,
1894 ) -> Option<language::CodeLabel> {
1895 let (text, filter_range, display_range) = match kind {
1896 lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
1897 let text = format!("def {}():\n", name);
1898 let filter_range = 4..4 + name.len();
1899 let display_range = 0..filter_range.end;
1900 (text, filter_range, display_range)
1901 }
1902 lsp::SymbolKind::CLASS => {
1903 let text = format!("class {}:", name);
1904 let filter_range = 6..6 + name.len();
1905 let display_range = 0..filter_range.end;
1906 (text, filter_range, display_range)
1907 }
1908 lsp::SymbolKind::CONSTANT => {
1909 let text = format!("{} = 0", name);
1910 let filter_range = 0..name.len();
1911 let display_range = 0..filter_range.end;
1912 (text, filter_range, display_range)
1913 }
1914 _ => return None,
1915 };
1916 Some(language::CodeLabel::new(
1917 text[display_range.clone()].to_string(),
1918 filter_range,
1919 language.highlight_text(&text.as_str().into(), display_range),
1920 ))
1921 }
1922
1923 async fn workspace_configuration(
1924 self: Arc<Self>,
1925 adapter: &Arc<dyn LspAdapterDelegate>,
1926 toolchain: Option<Toolchain>,
1927 _: Option<Uri>,
1928 cx: &mut AsyncApp,
1929 ) -> Result<Value> {
1930 cx.update(move |cx| {
1931 let mut user_settings =
1932 language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
1933 .and_then(|s| s.settings.clone())
1934 .unwrap_or_default();
1935
1936 // If we have a detected toolchain, configure Pyright to use it
1937 if let Some(toolchain) = toolchain
1938 && let Ok(env) = serde_json::from_value::<
1939 pet_core::python_environment::PythonEnvironment,
1940 >(toolchain.as_json.clone())
1941 {
1942 if !user_settings.is_object() {
1943 user_settings = Value::Object(serde_json::Map::default());
1944 }
1945 let object = user_settings.as_object_mut().unwrap();
1946
1947 let interpreter_path = toolchain.path.to_string();
1948 if let Some(venv_dir) = env.prefix {
1949 // Set venvPath and venv at the root level
1950 // This matches the format of a pyrightconfig.json file
1951 if let Some(parent) = venv_dir.parent() {
1952 // Use relative path if the venv is inside the workspace
1953 let venv_path = if parent == adapter.worktree_root_path() {
1954 ".".to_string()
1955 } else {
1956 parent.to_string_lossy().into_owned()
1957 };
1958 object.insert("venvPath".to_string(), Value::String(venv_path));
1959 }
1960
1961 if let Some(venv_name) = venv_dir.file_name() {
1962 object.insert(
1963 "venv".to_owned(),
1964 Value::String(venv_name.to_string_lossy().into_owned()),
1965 );
1966 }
1967 }
1968
1969 // Set both pythonPath and defaultInterpreterPath for compatibility
1970 if let Some(python) = object
1971 .entry("python")
1972 .or_insert(Value::Object(serde_json::Map::default()))
1973 .as_object_mut()
1974 {
1975 python.insert(
1976 "pythonPath".to_owned(),
1977 Value::String(interpreter_path.clone()),
1978 );
1979 python.insert(
1980 "defaultInterpreterPath".to_owned(),
1981 Value::String(interpreter_path),
1982 );
1983 }
1984 // Basedpyright by default uses `strict` type checking, we tone it down as to not surpris users
1985 maybe!({
1986 let analysis = object
1987 .entry("basedpyright.analysis")
1988 .or_insert(Value::Object(serde_json::Map::default()));
1989 if let serde_json::map::Entry::Vacant(v) =
1990 analysis.as_object_mut()?.entry("typeCheckingMode")
1991 {
1992 v.insert(Value::String("standard".to_owned()));
1993 }
1994 Some(())
1995 });
1996 }
1997
1998 user_settings
1999 })
2000 }
2001}
2002
2003impl LspInstaller for BasedPyrightLspAdapter {
2004 type BinaryVersion = String;
2005
2006 async fn fetch_latest_server_version(
2007 &self,
2008 _: &dyn LspAdapterDelegate,
2009 _: bool,
2010 _: &mut AsyncApp,
2011 ) -> Result<String> {
2012 self.node
2013 .npm_package_latest_version(Self::SERVER_NAME.as_ref())
2014 .await
2015 }
2016
2017 async fn check_if_user_installed(
2018 &self,
2019 delegate: &dyn LspAdapterDelegate,
2020 _: Option<Toolchain>,
2021 _: &AsyncApp,
2022 ) -> Option<LanguageServerBinary> {
2023 if let Some(path) = delegate.which(Self::BINARY_NAME.as_ref()).await {
2024 let env = delegate.shell_env().await;
2025 Some(LanguageServerBinary {
2026 path,
2027 env: Some(env),
2028 arguments: vec!["--stdio".into()],
2029 })
2030 } else {
2031 // TODO shouldn't this be self.node.binary_path()?
2032 let node = delegate.which("node".as_ref()).await?;
2033 let (node_modules_path, _) = delegate
2034 .npm_package_installed_version(Self::SERVER_NAME.as_ref())
2035 .await
2036 .log_err()??;
2037
2038 let path = node_modules_path.join(Self::NODE_MODULE_RELATIVE_SERVER_PATH);
2039
2040 let env = delegate.shell_env().await;
2041 Some(LanguageServerBinary {
2042 path: node,
2043 env: Some(env),
2044 arguments: vec![path.into(), "--stdio".into()],
2045 })
2046 }
2047 }
2048
2049 async fn fetch_server_binary(
2050 &self,
2051 latest_version: Self::BinaryVersion,
2052 container_dir: PathBuf,
2053 delegate: &dyn LspAdapterDelegate,
2054 ) -> Result<LanguageServerBinary> {
2055 let server_path = container_dir.join(Self::SERVER_PATH);
2056
2057 self.node
2058 .npm_install_packages(
2059 &container_dir,
2060 &[(Self::SERVER_NAME.as_ref(), latest_version.as_str())],
2061 )
2062 .await?;
2063
2064 let env = delegate.shell_env().await;
2065 Ok(LanguageServerBinary {
2066 path: self.node.binary_path().await?,
2067 env: Some(env),
2068 arguments: vec![server_path.into(), "--stdio".into()],
2069 })
2070 }
2071
2072 async fn check_if_version_installed(
2073 &self,
2074 version: &Self::BinaryVersion,
2075 container_dir: &PathBuf,
2076 delegate: &dyn LspAdapterDelegate,
2077 ) -> Option<LanguageServerBinary> {
2078 let server_path = container_dir.join(Self::SERVER_PATH);
2079
2080 let should_install_language_server = self
2081 .node
2082 .should_install_npm_package(
2083 Self::SERVER_NAME.as_ref(),
2084 &server_path,
2085 container_dir,
2086 VersionStrategy::Latest(version),
2087 )
2088 .await;
2089
2090 if should_install_language_server {
2091 None
2092 } else {
2093 let env = delegate.shell_env().await;
2094 Some(LanguageServerBinary {
2095 path: self.node.binary_path().await.ok()?,
2096 env: Some(env),
2097 arguments: vec![server_path.into(), "--stdio".into()],
2098 })
2099 }
2100 }
2101
2102 async fn cached_server_binary(
2103 &self,
2104 container_dir: PathBuf,
2105 delegate: &dyn LspAdapterDelegate,
2106 ) -> Option<LanguageServerBinary> {
2107 let mut binary = Self::get_cached_server_binary(container_dir, &self.node).await?;
2108 binary.env = Some(delegate.shell_env().await);
2109 Some(binary)
2110 }
2111}
2112
2113pub(crate) struct RuffLspAdapter {
2114 fs: Arc<dyn Fs>,
2115}
2116
2117#[cfg(target_os = "macos")]
2118impl RuffLspAdapter {
2119 const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
2120 const ARCH_SERVER_NAME: &str = "apple-darwin";
2121}
2122
2123#[cfg(target_os = "linux")]
2124impl RuffLspAdapter {
2125 const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
2126 const ARCH_SERVER_NAME: &str = "unknown-linux-gnu";
2127}
2128
2129#[cfg(target_os = "freebsd")]
2130impl RuffLspAdapter {
2131 const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
2132 const ARCH_SERVER_NAME: &str = "unknown-freebsd";
2133}
2134
2135#[cfg(target_os = "windows")]
2136impl RuffLspAdapter {
2137 const GITHUB_ASSET_KIND: AssetKind = AssetKind::Zip;
2138 const ARCH_SERVER_NAME: &str = "pc-windows-msvc";
2139}
2140
2141impl RuffLspAdapter {
2142 const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("ruff");
2143
2144 pub fn new(fs: Arc<dyn Fs>) -> RuffLspAdapter {
2145 RuffLspAdapter { fs }
2146 }
2147
2148 fn build_asset_name() -> Result<(String, String)> {
2149 let arch = match consts::ARCH {
2150 "x86" => "i686",
2151 _ => consts::ARCH,
2152 };
2153 let os = Self::ARCH_SERVER_NAME;
2154 let suffix = match consts::OS {
2155 "windows" => "zip",
2156 _ => "tar.gz",
2157 };
2158 let asset_name = format!("ruff-{arch}-{os}.{suffix}");
2159 let asset_stem = format!("ruff-{arch}-{os}");
2160 Ok((asset_stem, asset_name))
2161 }
2162}
2163
2164#[async_trait(?Send)]
2165impl LspAdapter for RuffLspAdapter {
2166 fn name(&self) -> LanguageServerName {
2167 Self::SERVER_NAME
2168 }
2169}
2170
2171impl LspInstaller for RuffLspAdapter {
2172 type BinaryVersion = GitHubLspBinaryVersion;
2173 async fn check_if_user_installed(
2174 &self,
2175 delegate: &dyn LspAdapterDelegate,
2176 toolchain: Option<Toolchain>,
2177 _: &AsyncApp,
2178 ) -> Option<LanguageServerBinary> {
2179 let ruff_in_venv = if let Some(toolchain) = toolchain
2180 && toolchain.language_name.as_ref() == "Python"
2181 {
2182 Path::new(toolchain.path.as_str())
2183 .parent()
2184 .map(|path| path.join("ruff"))
2185 } else {
2186 None
2187 };
2188
2189 for path in ruff_in_venv.into_iter().chain(["ruff".into()]) {
2190 if let Some(ruff_bin) = delegate.which(path.as_os_str()).await {
2191 let env = delegate.shell_env().await;
2192 return Some(LanguageServerBinary {
2193 path: ruff_bin,
2194 env: Some(env),
2195 arguments: vec!["server".into()],
2196 });
2197 }
2198 }
2199
2200 None
2201 }
2202
2203 async fn fetch_latest_server_version(
2204 &self,
2205 delegate: &dyn LspAdapterDelegate,
2206 _: bool,
2207 _: &mut AsyncApp,
2208 ) -> Result<GitHubLspBinaryVersion> {
2209 let release =
2210 latest_github_release("astral-sh/ruff", true, false, delegate.http_client()).await?;
2211 let (_, asset_name) = Self::build_asset_name()?;
2212 let asset = release
2213 .assets
2214 .into_iter()
2215 .find(|asset| asset.name == asset_name)
2216 .with_context(|| format!("no asset found matching `{asset_name:?}`"))?;
2217 Ok(GitHubLspBinaryVersion {
2218 name: release.tag_name,
2219 url: asset.browser_download_url,
2220 digest: asset.digest,
2221 })
2222 }
2223
2224 async fn fetch_server_binary(
2225 &self,
2226 latest_version: GitHubLspBinaryVersion,
2227 container_dir: PathBuf,
2228 delegate: &dyn LspAdapterDelegate,
2229 ) -> Result<LanguageServerBinary> {
2230 let GitHubLspBinaryVersion {
2231 name,
2232 url,
2233 digest: expected_digest,
2234 } = latest_version;
2235 let destination_path = container_dir.join(format!("ruff-{name}"));
2236 let server_path = match Self::GITHUB_ASSET_KIND {
2237 AssetKind::TarGz | AssetKind::Gz => destination_path
2238 .join(Self::build_asset_name()?.0)
2239 .join("ruff"),
2240 AssetKind::Zip => destination_path.clone().join("ruff.exe"),
2241 };
2242
2243 let binary = LanguageServerBinary {
2244 path: server_path.clone(),
2245 env: None,
2246 arguments: vec!["server".into()],
2247 };
2248
2249 let metadata_path = destination_path.with_extension("metadata");
2250 let metadata = GithubBinaryMetadata::read_from_file(&metadata_path)
2251 .await
2252 .ok();
2253 if let Some(metadata) = metadata {
2254 let validity_check = async || {
2255 delegate
2256 .try_exec(LanguageServerBinary {
2257 path: server_path.clone(),
2258 arguments: vec!["--version".into()],
2259 env: None,
2260 })
2261 .await
2262 .inspect_err(|err| {
2263 log::warn!("Unable to run {server_path:?} asset, redownloading: {err:#}",)
2264 })
2265 };
2266 if let (Some(actual_digest), Some(expected_digest)) =
2267 (&metadata.digest, &expected_digest)
2268 {
2269 if actual_digest == expected_digest {
2270 if validity_check().await.is_ok() {
2271 return Ok(binary);
2272 }
2273 } else {
2274 log::info!(
2275 "SHA-256 mismatch for {destination_path:?} asset, downloading new asset. Expected: {expected_digest}, Got: {actual_digest}"
2276 );
2277 }
2278 } else if validity_check().await.is_ok() {
2279 return Ok(binary);
2280 }
2281 }
2282
2283 download_server_binary(
2284 &*delegate.http_client(),
2285 &url,
2286 expected_digest.as_deref(),
2287 &destination_path,
2288 Self::GITHUB_ASSET_KIND,
2289 )
2290 .await?;
2291 make_file_executable(&server_path).await?;
2292 remove_matching(&container_dir, |path| path != destination_path).await;
2293 GithubBinaryMetadata::write_to_file(
2294 &GithubBinaryMetadata {
2295 metadata_version: 1,
2296 digest: expected_digest,
2297 },
2298 &metadata_path,
2299 )
2300 .await?;
2301
2302 Ok(LanguageServerBinary {
2303 path: server_path,
2304 env: None,
2305 arguments: vec!["server".into()],
2306 })
2307 }
2308
2309 async fn cached_server_binary(
2310 &self,
2311 container_dir: PathBuf,
2312 _: &dyn LspAdapterDelegate,
2313 ) -> Option<LanguageServerBinary> {
2314 maybe!(async {
2315 let mut last = None;
2316 let mut entries = self.fs.read_dir(&container_dir).await?;
2317 while let Some(entry) = entries.next().await {
2318 let path = entry?;
2319 if path.extension().is_some_and(|ext| ext == "metadata") {
2320 continue;
2321 }
2322 last = Some(path);
2323 }
2324
2325 let path = last.context("no cached binary")?;
2326 let path = match Self::GITHUB_ASSET_KIND {
2327 AssetKind::TarGz | AssetKind::Gz => {
2328 path.join(Self::build_asset_name()?.0).join("ruff")
2329 }
2330 AssetKind::Zip => path.join("ruff.exe"),
2331 };
2332
2333 anyhow::Ok(LanguageServerBinary {
2334 path,
2335 env: None,
2336 arguments: vec!["server".into()],
2337 })
2338 })
2339 .await
2340 .log_err()
2341 }
2342}
2343
2344#[cfg(test)]
2345mod tests {
2346 use gpui::{AppContext as _, BorrowAppContext, Context, TestAppContext};
2347 use language::{AutoindentMode, Buffer};
2348 use settings::SettingsStore;
2349 use std::num::NonZeroU32;
2350
2351 use crate::python::python_module_name_from_relative_path;
2352
2353 #[gpui::test]
2354 async fn test_python_autoindent(cx: &mut TestAppContext) {
2355 cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
2356 let language = crate::language("python", tree_sitter_python::LANGUAGE.into());
2357 cx.update(|cx| {
2358 let test_settings = SettingsStore::test(cx);
2359 cx.set_global(test_settings);
2360 cx.update_global::<SettingsStore, _>(|store, cx| {
2361 store.update_user_settings(cx, |s| {
2362 s.project.all_languages.defaults.tab_size = NonZeroU32::new(2);
2363 });
2364 });
2365 });
2366
2367 cx.new(|cx| {
2368 let mut buffer = Buffer::local("", cx).with_language(language, cx);
2369 let append = |buffer: &mut Buffer, text: &str, cx: &mut Context<Buffer>| {
2370 let ix = buffer.len();
2371 buffer.edit([(ix..ix, text)], Some(AutoindentMode::EachLine), cx);
2372 };
2373
2374 // indent after "def():"
2375 append(&mut buffer, "def a():\n", cx);
2376 assert_eq!(buffer.text(), "def a():\n ");
2377
2378 // preserve indent after blank line
2379 append(&mut buffer, "\n ", cx);
2380 assert_eq!(buffer.text(), "def a():\n \n ");
2381
2382 // indent after "if"
2383 append(&mut buffer, "if a:\n ", cx);
2384 assert_eq!(buffer.text(), "def a():\n \n if a:\n ");
2385
2386 // preserve indent after statement
2387 append(&mut buffer, "b()\n", cx);
2388 assert_eq!(buffer.text(), "def a():\n \n if a:\n b()\n ");
2389
2390 // preserve indent after statement
2391 append(&mut buffer, "else", cx);
2392 assert_eq!(buffer.text(), "def a():\n \n if a:\n b()\n else");
2393
2394 // dedent "else""
2395 append(&mut buffer, ":", cx);
2396 assert_eq!(buffer.text(), "def a():\n \n if a:\n b()\n else:");
2397
2398 // indent lines after else
2399 append(&mut buffer, "\n", cx);
2400 assert_eq!(
2401 buffer.text(),
2402 "def a():\n \n if a:\n b()\n else:\n "
2403 );
2404
2405 // indent after an open paren. the closing paren is not indented
2406 // because there is another token before it on the same line.
2407 append(&mut buffer, "foo(\n1)", cx);
2408 assert_eq!(
2409 buffer.text(),
2410 "def a():\n \n if a:\n b()\n else:\n foo(\n 1)"
2411 );
2412
2413 // dedent the closing paren if it is shifted to the beginning of the line
2414 let argument_ix = buffer.text().find('1').unwrap();
2415 buffer.edit(
2416 [(argument_ix..argument_ix + 1, "")],
2417 Some(AutoindentMode::EachLine),
2418 cx,
2419 );
2420 assert_eq!(
2421 buffer.text(),
2422 "def a():\n \n if a:\n b()\n else:\n foo(\n )"
2423 );
2424
2425 // preserve indent after the close paren
2426 append(&mut buffer, "\n", cx);
2427 assert_eq!(
2428 buffer.text(),
2429 "def a():\n \n if a:\n b()\n else:\n foo(\n )\n "
2430 );
2431
2432 // manually outdent the last line
2433 let end_whitespace_ix = buffer.len() - 4;
2434 buffer.edit(
2435 [(end_whitespace_ix..buffer.len(), "")],
2436 Some(AutoindentMode::EachLine),
2437 cx,
2438 );
2439 assert_eq!(
2440 buffer.text(),
2441 "def a():\n \n if a:\n b()\n else:\n foo(\n )\n"
2442 );
2443
2444 // preserve the newly reduced indentation on the next newline
2445 append(&mut buffer, "\n", cx);
2446 assert_eq!(
2447 buffer.text(),
2448 "def a():\n \n if a:\n b()\n else:\n foo(\n )\n\n"
2449 );
2450
2451 // reset to a for loop statement
2452 let statement = "for i in range(10):\n print(i)\n";
2453 buffer.edit([(0..buffer.len(), statement)], None, cx);
2454
2455 // insert single line comment after each line
2456 let eol_ixs = statement
2457 .char_indices()
2458 .filter_map(|(ix, c)| if c == '\n' { Some(ix) } else { None })
2459 .collect::<Vec<usize>>();
2460 let editions = eol_ixs
2461 .iter()
2462 .enumerate()
2463 .map(|(i, &eol_ix)| (eol_ix..eol_ix, format!(" # comment {}", i + 1)))
2464 .collect::<Vec<(std::ops::Range<usize>, String)>>();
2465 buffer.edit(editions, Some(AutoindentMode::EachLine), cx);
2466 assert_eq!(
2467 buffer.text(),
2468 "for i in range(10): # comment 1\n print(i) # comment 2\n"
2469 );
2470
2471 // reset to a simple if statement
2472 buffer.edit([(0..buffer.len(), "if a:\n b(\n )")], None, cx);
2473
2474 // dedent "else" on the line after a closing paren
2475 append(&mut buffer, "\n else:\n", cx);
2476 assert_eq!(buffer.text(), "if a:\n b(\n )\nelse:\n ");
2477
2478 buffer
2479 });
2480 }
2481
2482 #[test]
2483 fn test_python_module_name_from_relative_path() {
2484 assert_eq!(
2485 python_module_name_from_relative_path("foo/bar.py"),
2486 Some("foo.bar".to_string())
2487 );
2488 assert_eq!(
2489 python_module_name_from_relative_path("foo/bar"),
2490 Some("foo.bar".to_string())
2491 );
2492 if cfg!(windows) {
2493 assert_eq!(
2494 python_module_name_from_relative_path("foo\\bar.py"),
2495 Some("foo.bar".to_string())
2496 );
2497 assert_eq!(
2498 python_module_name_from_relative_path("foo\\bar"),
2499 Some("foo.bar".to_string())
2500 );
2501 } else {
2502 assert_eq!(
2503 python_module_name_from_relative_path("foo\\bar.py"),
2504 Some("foo\\bar".to_string())
2505 );
2506 assert_eq!(
2507 python_module_name_from_relative_path("foo\\bar"),
2508 Some("foo\\bar".to_string())
2509 );
2510 }
2511 }
2512}