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