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