python.rs

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