python.rs

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