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