python.rs

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