python.rs

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