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