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