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};
  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 std::process::Stdio;
  34
  35use util::command::new_smol_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::{PosixShell, 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        name: &str,
 554        kind: lsp::SymbolKind,
 555        language: &Arc<language::Language>,
 556    ) -> Option<language::CodeLabel> {
 557        let (text, filter_range, display_range) = match 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: Option<ShellKind>) -> &'static str {
1172    match kind {
1173        Some(ShellKind::Csh) => "csh",
1174        Some(ShellKind::Fish) => "fish",
1175        Some(ShellKind::Nushell) => "nu",
1176        Some(ShellKind::PowerShell) | Some(ShellKind::Pwsh) => "powershell",
1177        Some(ShellKind::Cmd) => "cmd.exe",
1178        #[cfg(windows)]
1179        None => "powershell",
1180        // default / catch-all:
1181        _ => "posix",
1182    }
1183}
1184
1185#[async_trait]
1186impl ToolchainLister for PythonToolchainProvider {
1187    async fn list(
1188        &self,
1189        worktree_root: PathBuf,
1190        subroot_relative_path: Arc<RelPath>,
1191        project_env: Option<HashMap<String, String>>,
1192        fs: &dyn Fs,
1193    ) -> ToolchainList {
1194        let env = project_env.unwrap_or_default();
1195        let environment = EnvironmentApi::from_env(&env);
1196        let locators = pet::locators::create_locators(
1197            Arc::new(pet_conda::Conda::from(&environment)),
1198            Arc::new(pet_poetry::Poetry::from(&environment)),
1199            &environment,
1200        );
1201        let mut config = Configuration::default();
1202
1203        // `.ancestors()` will yield at least one path, so in case of empty `subroot_relative_path`, we'll just use
1204        // worktree root as the workspace directory.
1205        config.workspace_directories = Some(
1206            subroot_relative_path
1207                .ancestors()
1208                .map(|ancestor| {
1209                    // remove trailing separator as it alters the environment name hash used by Poetry.
1210                    let path = worktree_root.join(ancestor.as_std_path());
1211                    let path_str = path.to_string_lossy();
1212                    if path_str.ends_with(std::path::MAIN_SEPARATOR) && path_str.len() > 1 {
1213                        PathBuf::from(path_str.trim_end_matches(std::path::MAIN_SEPARATOR))
1214                    } else {
1215                        path
1216                    }
1217                })
1218                .collect(),
1219        );
1220        for locator in locators.iter() {
1221            locator.configure(&config);
1222        }
1223
1224        let reporter = pet_reporter::collect::create_reporter();
1225        pet::find::find_and_report_envs(&reporter, config, &locators, &environment, None);
1226
1227        let mut toolchains = reporter
1228            .environments
1229            .lock()
1230            .map_or(Vec::new(), |mut guard| std::mem::take(&mut guard));
1231
1232        let wr = worktree_root;
1233        let wr_venv = get_worktree_venv_declaration(&wr).await;
1234        // Sort detected environments by:
1235        //     environment name matching activation file (<workdir>/.venv)
1236        //     environment project dir matching worktree_root
1237        //     general env priority
1238        //     environment path matching the CONDA_PREFIX env var
1239        //     executable path
1240        toolchains.sort_by(|lhs, rhs| {
1241            // Compare venv names against worktree .venv file
1242            let venv_ordering =
1243                wr_venv
1244                    .as_ref()
1245                    .map_or(Ordering::Equal, |venv| match (&lhs.name, &rhs.name) {
1246                        (Some(l), Some(r)) => (r == venv).cmp(&(l == venv)),
1247                        (Some(l), None) if l == venv => Ordering::Less,
1248                        (None, Some(r)) if r == venv => Ordering::Greater,
1249                        _ => Ordering::Equal,
1250                    });
1251
1252            // Compare project paths against worktree root
1253            let proj_ordering =
1254                || {
1255                    let lhs_project = lhs.project.clone().or_else(|| get_venv_parent_dir(lhs));
1256                    let rhs_project = rhs.project.clone().or_else(|| get_venv_parent_dir(rhs));
1257                    wr_distance(&wr, &subroot_relative_path, lhs_project.as_ref()).cmp(
1258                        &wr_distance(&wr, &subroot_relative_path, rhs_project.as_ref()),
1259                    )
1260                };
1261
1262            // Compare environment priorities
1263            let priority_ordering = || env_priority(lhs.kind).cmp(&env_priority(rhs.kind));
1264
1265            // Compare conda prefixes
1266            let conda_ordering = || {
1267                if lhs.kind == Some(PythonEnvironmentKind::Conda) {
1268                    environment
1269                        .get_env_var("CONDA_PREFIX".to_string())
1270                        .map(|conda_prefix| {
1271                            let is_match = |exe: &Option<PathBuf>| {
1272                                exe.as_ref().is_some_and(|e| e.starts_with(&conda_prefix))
1273                            };
1274                            match (is_match(&lhs.executable), is_match(&rhs.executable)) {
1275                                (true, false) => Ordering::Less,
1276                                (false, true) => Ordering::Greater,
1277                                _ => Ordering::Equal,
1278                            }
1279                        })
1280                        .unwrap_or(Ordering::Equal)
1281                } else {
1282                    Ordering::Equal
1283                }
1284            };
1285
1286            // Compare Python executables
1287            let exe_ordering = || lhs.executable.cmp(&rhs.executable);
1288
1289            venv_ordering
1290                .then_with(proj_ordering)
1291                .then_with(priority_ordering)
1292                .then_with(conda_ordering)
1293                .then_with(exe_ordering)
1294        });
1295
1296        let mut out_toolchains = Vec::new();
1297        for toolchain in toolchains {
1298            let Some(toolchain) = venv_to_toolchain(toolchain, fs).await else {
1299                continue;
1300            };
1301            out_toolchains.push(toolchain);
1302        }
1303        out_toolchains.dedup();
1304        ToolchainList {
1305            toolchains: out_toolchains,
1306            default: None,
1307            groups: Default::default(),
1308        }
1309    }
1310    fn meta(&self) -> ToolchainMetadata {
1311        ToolchainMetadata {
1312            term: SharedString::new_static("Virtual Environment"),
1313            new_toolchain_placeholder: SharedString::new_static(
1314                "A path to the python3 executable within a virtual environment, or path to virtual environment itself",
1315            ),
1316            manifest_name: ManifestName::from(SharedString::new_static("pyproject.toml")),
1317        }
1318    }
1319
1320    async fn resolve(
1321        &self,
1322        path: PathBuf,
1323        env: Option<HashMap<String, String>>,
1324        fs: &dyn Fs,
1325    ) -> anyhow::Result<Toolchain> {
1326        let env = env.unwrap_or_default();
1327        let environment = EnvironmentApi::from_env(&env);
1328        let locators = pet::locators::create_locators(
1329            Arc::new(pet_conda::Conda::from(&environment)),
1330            Arc::new(pet_poetry::Poetry::from(&environment)),
1331            &environment,
1332        );
1333        let toolchain = pet::resolve::resolve_environment(&path, &locators, &environment)
1334            .context("Could not find a virtual environment in provided path")?;
1335        let venv = toolchain.resolved.unwrap_or(toolchain.discovered);
1336        venv_to_toolchain(venv, fs)
1337            .await
1338            .context("Could not convert a venv into a toolchain")
1339    }
1340
1341    fn activation_script(
1342        &self,
1343        toolchain: &Toolchain,
1344        shell: Option<ShellKind>,
1345        cx: &App,
1346    ) -> BoxFuture<'static, Vec<String>> {
1347        let settings = TerminalSettings::get_global(cx);
1348        let conda_manager = settings
1349            .detect_venv
1350            .as_option()
1351            .map(|venv| venv.conda_manager)
1352            .unwrap_or(settings::CondaManager::Auto);
1353
1354        let toolchain_clone = toolchain.clone();
1355        Box::pin(async move {
1356            let Ok(toolchain) =
1357                serde_json::from_value::<PythonToolchainData>(toolchain_clone.as_json.clone())
1358            else {
1359                return vec![];
1360            };
1361
1362            log::debug!("(Python) Composing activation script for toolchain {toolchain:?}");
1363
1364            let mut activation_script = vec![];
1365
1366            match toolchain.environment.kind {
1367                Some(PythonEnvironmentKind::Conda) => {
1368                    let Some(manager_info) = &toolchain.environment.manager else {
1369                        return vec![];
1370                    };
1371                    if smol::fs::metadata(&manager_info.executable).await.is_err() {
1372                        return vec![];
1373                    }
1374
1375                    let manager = match conda_manager {
1376                        settings::CondaManager::Conda => "conda",
1377                        settings::CondaManager::Mamba => "mamba",
1378                        settings::CondaManager::Micromamba => "micromamba",
1379                        settings::CondaManager::Auto => toolchain
1380                            .environment
1381                            .manager
1382                            .as_ref()
1383                            .and_then(|m| m.executable.file_name())
1384                            .and_then(|name| name.to_str())
1385                            .filter(|name| matches!(*name, "conda" | "mamba" | "micromamba"))
1386                            .unwrap_or("conda"),
1387                    };
1388
1389                    // Activate micromamba shell in the child shell
1390                    // [required for micromamba]
1391                    if manager == "micromamba" {
1392                        let shell = micromamba_shell_name(shell);
1393                        activation_script
1394                            .push(format!(r#"eval "$({manager} shell hook --shell {shell})""#));
1395                    }
1396
1397                    if let Some(name) = &toolchain.environment.name {
1398                        activation_script.push(format!("{manager} activate {name}"));
1399                    } else {
1400                        activation_script.push(format!("{manager} activate base"));
1401                    }
1402                }
1403                Some(
1404                    PythonEnvironmentKind::Venv
1405                    | PythonEnvironmentKind::VirtualEnv
1406                    | PythonEnvironmentKind::Uv
1407                    | PythonEnvironmentKind::UvWorkspace
1408                    | PythonEnvironmentKind::Poetry,
1409                ) => {
1410                    if let Some(activation_scripts) = &toolchain.activation_scripts {
1411                        // For unknown shells, fall back to platform-appropriate defaults:
1412                        // POSIX (sh) on Unix, PowerShell on Windows
1413                        #[cfg(unix)]
1414                        let fallback_shell = ShellKind::Posix(PosixShell::Sh);
1415                        #[cfg(windows)]
1416                        let fallback_shell = ShellKind::PowerShell;
1417
1418                        let shell_kind = shell.unwrap_or(fallback_shell);
1419                        // Use activation_script_key() to normalize POSIX shells (e.g., Bash, Zsh)
1420                        // to Posix(Sh) for lookup, since activation scripts are stored with Posix(Sh) key
1421                        let lookup_key = shell_kind.activation_script_key();
1422                        if let Some(activate_script_path) = activation_scripts.get(&lookup_key) {
1423                            let activate_keyword = shell_kind.activate_keyword();
1424                            if let Some(quoted) =
1425                                shell_kind.try_quote(&activate_script_path.to_string_lossy())
1426                            {
1427                                activation_script.push(format!("{activate_keyword} {quoted}"));
1428                            }
1429                        }
1430                    }
1431                }
1432                Some(PythonEnvironmentKind::Pyenv) => {
1433                    let Some(manager) = &toolchain.environment.manager else {
1434                        return vec![];
1435                    };
1436                    let version = toolchain.environment.version.as_deref().unwrap_or("system");
1437                    let pyenv = &manager.executable;
1438                    let pyenv = pyenv.display();
1439                    let pyenv_sh_activation = format!("\"{pyenv}\" shell - sh {version}");
1440                    activation_script.extend(match shell {
1441                        Some(ShellKind::Fish) => {
1442                            Some(format!("\"{pyenv}\" shell - fish {version}"))
1443                        }
1444                        Some(ShellKind::Posix(_)) => Some(pyenv_sh_activation),
1445                        #[cfg(unix)]
1446                        None => Some(pyenv_sh_activation),
1447                        Some(ShellKind::Nushell) => {
1448                            Some(format!("^\"{pyenv}\" shell - nu {version}"))
1449                        }
1450                        Some(ShellKind::PowerShell)
1451                        | Some(ShellKind::Pwsh)
1452                        | Some(ShellKind::Csh)
1453                        | Some(ShellKind::Tcsh)
1454                        | Some(ShellKind::Cmd)
1455                        | Some(ShellKind::Rc)
1456                        | Some(ShellKind::Xonsh)
1457                        | Some(ShellKind::Elvish) => None,
1458                        #[cfg(windows)]
1459                        None => None,
1460                    })
1461                }
1462                _ => {}
1463            }
1464            activation_script
1465        })
1466    }
1467}
1468
1469async fn venv_to_toolchain(venv: PythonEnvironment, fs: &dyn Fs) -> Option<Toolchain> {
1470    let mut name = String::from("Python");
1471    if let Some(ref version) = venv.version {
1472        _ = write!(name, " {version}");
1473    }
1474
1475    let name_and_kind = match (&venv.name, &venv.kind) {
1476        (Some(name), Some(kind)) => Some(format!("({name}; {})", python_env_kind_display(kind))),
1477        (Some(name), None) => Some(format!("({name})")),
1478        (None, Some(kind)) => Some(format!("({})", python_env_kind_display(kind))),
1479        (None, None) => None,
1480    };
1481
1482    if let Some(nk) = name_and_kind {
1483        _ = write!(name, " {nk}");
1484    }
1485
1486    let mut activation_scripts = HashMap::default();
1487    match venv.kind {
1488        Some(
1489            PythonEnvironmentKind::Venv
1490            | PythonEnvironmentKind::VirtualEnv
1491            | PythonEnvironmentKind::Uv
1492            | PythonEnvironmentKind::UvWorkspace
1493            | PythonEnvironmentKind::Poetry,
1494        ) => resolve_venv_activation_scripts(&venv, fs, &mut activation_scripts).await,
1495        _ => {}
1496    }
1497    let data = PythonToolchainData {
1498        environment: venv,
1499        activation_scripts: Some(activation_scripts),
1500    };
1501
1502    Some(Toolchain {
1503        name: name.into(),
1504        path: data
1505            .environment
1506            .executable
1507            .as_ref()?
1508            .to_str()?
1509            .to_owned()
1510            .into(),
1511        language_name: LanguageName::new_static("Python"),
1512        as_json: serde_json::to_value(data).ok()?,
1513    })
1514}
1515
1516async fn resolve_venv_activation_scripts(
1517    venv: &PythonEnvironment,
1518    fs: &dyn Fs,
1519    activation_scripts: &mut HashMap<ShellKind, PathBuf>,
1520) {
1521    log::debug!("(Python) Resolving activation scripts for venv toolchain {venv:?}");
1522    if let Some(prefix) = &venv.prefix {
1523        // TODO: Consider using the user's actual shell instead of hardcoding "sh"
1524        for (shell_kind, script_name) in &[
1525            (ShellKind::Posix(PosixShell::Sh), "activate"),
1526            (ShellKind::Rc, "activate"),
1527            (ShellKind::Csh, "activate.csh"),
1528            (ShellKind::Tcsh, "activate.csh"),
1529            (ShellKind::Fish, "activate.fish"),
1530            (ShellKind::Nushell, "activate.nu"),
1531            (ShellKind::PowerShell, "activate.ps1"),
1532            (ShellKind::Pwsh, "activate.ps1"),
1533            (ShellKind::Cmd, "activate.bat"),
1534            (ShellKind::Xonsh, "activate.xsh"),
1535        ] {
1536            let path = prefix.join(BINARY_DIR).join(script_name);
1537
1538            log::debug!("Trying path: {}", path.display());
1539
1540            if fs.is_file(&path).await {
1541                activation_scripts.insert(*shell_kind, path);
1542            }
1543        }
1544    }
1545}
1546
1547pub struct EnvironmentApi<'a> {
1548    global_search_locations: Arc<Mutex<Vec<PathBuf>>>,
1549    project_env: &'a HashMap<String, String>,
1550    pet_env: pet_core::os_environment::EnvironmentApi,
1551}
1552
1553impl<'a> EnvironmentApi<'a> {
1554    pub fn from_env(project_env: &'a HashMap<String, String>) -> Self {
1555        let paths = project_env
1556            .get("PATH")
1557            .map(|p| std::env::split_paths(p).collect())
1558            .unwrap_or_default();
1559
1560        EnvironmentApi {
1561            global_search_locations: Arc::new(Mutex::new(paths)),
1562            project_env,
1563            pet_env: pet_core::os_environment::EnvironmentApi::new(),
1564        }
1565    }
1566
1567    fn user_home(&self) -> Option<PathBuf> {
1568        self.project_env
1569            .get("HOME")
1570            .or_else(|| self.project_env.get("USERPROFILE"))
1571            .map(|home| pet_fs::path::norm_case(PathBuf::from(home)))
1572            .or_else(|| self.pet_env.get_user_home())
1573    }
1574}
1575
1576impl pet_core::os_environment::Environment for EnvironmentApi<'_> {
1577    fn get_user_home(&self) -> Option<PathBuf> {
1578        self.user_home()
1579    }
1580
1581    fn get_root(&self) -> Option<PathBuf> {
1582        None
1583    }
1584
1585    fn get_env_var(&self, key: String) -> Option<String> {
1586        self.project_env
1587            .get(&key)
1588            .cloned()
1589            .or_else(|| self.pet_env.get_env_var(key))
1590    }
1591
1592    fn get_know_global_search_locations(&self) -> Vec<PathBuf> {
1593        if self.global_search_locations.lock().is_empty() {
1594            let mut paths = std::env::split_paths(
1595                &self
1596                    .get_env_var("PATH".to_string())
1597                    .or_else(|| self.get_env_var("Path".to_string()))
1598                    .unwrap_or_default(),
1599            )
1600            .collect::<Vec<PathBuf>>();
1601
1602            log::trace!("Env PATH: {:?}", paths);
1603            for p in self.pet_env.get_know_global_search_locations() {
1604                if !paths.contains(&p) {
1605                    paths.push(p);
1606                }
1607            }
1608
1609            let mut paths = paths
1610                .into_iter()
1611                .filter(|p| p.exists())
1612                .collect::<Vec<PathBuf>>();
1613
1614            self.global_search_locations.lock().append(&mut paths);
1615        }
1616        self.global_search_locations.lock().clone()
1617    }
1618}
1619
1620pub(crate) struct PyLspAdapter {
1621    python_venv_base: OnceCell<Result<Arc<Path>, String>>,
1622}
1623impl PyLspAdapter {
1624    const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("pylsp");
1625    pub(crate) fn new() -> Self {
1626        Self {
1627            python_venv_base: OnceCell::new(),
1628        }
1629    }
1630    async fn ensure_venv(delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>> {
1631        let python_path = Self::find_base_python(delegate)
1632            .await
1633            .with_context(|| {
1634                let mut message = "Could not find Python installation for PyLSP".to_owned();
1635                if cfg!(windows){
1636                    message.push_str(". Install Python from the Microsoft Store, or manually from https://www.python.org/downloads/windows.")
1637                }
1638                message
1639            })?;
1640        let work_dir = delegate
1641            .language_server_download_dir(&Self::SERVER_NAME)
1642            .await
1643            .context("Could not get working directory for PyLSP")?;
1644        let mut path = PathBuf::from(work_dir.as_ref());
1645        path.push("pylsp-venv");
1646        if !path.exists() {
1647            util::command::new_smol_command(python_path)
1648                .arg("-m")
1649                .arg("venv")
1650                .arg("pylsp-venv")
1651                .current_dir(work_dir)
1652                .spawn()?
1653                .output()
1654                .await?;
1655        }
1656
1657        Ok(path.into())
1658    }
1659    // Find "baseline", user python version from which we'll create our own venv.
1660    async fn find_base_python(delegate: &dyn LspAdapterDelegate) -> Option<PathBuf> {
1661        for path in ["python3", "python"] {
1662            let Some(path) = delegate.which(path.as_ref()).await else {
1663                continue;
1664            };
1665            // Try to detect situations where `python3` exists but is not a real Python interpreter.
1666            // Notably, on fresh Windows installs, `python3` is a shim that opens the Microsoft Store app
1667            // when run with no arguments, and just fails otherwise.
1668            let Some(output) = new_smol_command(&path)
1669                .args(["-c", "print(1 + 2)"])
1670                .output()
1671                .await
1672                .ok()
1673            else {
1674                continue;
1675            };
1676            if output.stdout.trim_ascii() != b"3" {
1677                continue;
1678            }
1679            return Some(path);
1680        }
1681        None
1682    }
1683
1684    async fn base_venv(&self, delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>, String> {
1685        self.python_venv_base
1686            .get_or_init(move || async move {
1687                Self::ensure_venv(delegate)
1688                    .await
1689                    .map_err(|e| format!("{e}"))
1690            })
1691            .await
1692            .clone()
1693    }
1694}
1695
1696const BINARY_DIR: &str = if cfg!(target_os = "windows") {
1697    "Scripts"
1698} else {
1699    "bin"
1700};
1701
1702#[async_trait(?Send)]
1703impl LspAdapter for PyLspAdapter {
1704    fn name(&self) -> LanguageServerName {
1705        Self::SERVER_NAME
1706    }
1707
1708    async fn process_completions(&self, _items: &mut [lsp::CompletionItem]) {}
1709
1710    async fn label_for_completion(
1711        &self,
1712        item: &lsp::CompletionItem,
1713        language: &Arc<language::Language>,
1714    ) -> Option<language::CodeLabel> {
1715        let label = &item.label;
1716        let label_len = label.len();
1717        let grammar = language.grammar()?;
1718        let highlight_id = match item.kind? {
1719            lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method")?,
1720            lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function")?,
1721            lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type")?,
1722            lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant")?,
1723            _ => return None,
1724        };
1725        Some(language::CodeLabel::filtered(
1726            label.clone(),
1727            label_len,
1728            item.filter_text.as_deref(),
1729            vec![(0..label.len(), highlight_id)],
1730        ))
1731    }
1732
1733    async fn label_for_symbol(
1734        &self,
1735        name: &str,
1736        kind: lsp::SymbolKind,
1737        language: &Arc<language::Language>,
1738    ) -> Option<language::CodeLabel> {
1739        let (text, filter_range, display_range) = match kind {
1740            lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
1741                let text = format!("def {}():\n", name);
1742                let filter_range = 4..4 + name.len();
1743                let display_range = 0..filter_range.end;
1744                (text, filter_range, display_range)
1745            }
1746            lsp::SymbolKind::CLASS => {
1747                let text = format!("class {}:", name);
1748                let filter_range = 6..6 + name.len();
1749                let display_range = 0..filter_range.end;
1750                (text, filter_range, display_range)
1751            }
1752            lsp::SymbolKind::CONSTANT => {
1753                let text = format!("{} = 0", name);
1754                let filter_range = 0..name.len();
1755                let display_range = 0..filter_range.end;
1756                (text, filter_range, display_range)
1757            }
1758            _ => return None,
1759        };
1760        Some(language::CodeLabel::new(
1761            text[display_range.clone()].to_string(),
1762            filter_range,
1763            language.highlight_text(&text.as_str().into(), display_range),
1764        ))
1765    }
1766
1767    async fn workspace_configuration(
1768        self: Arc<Self>,
1769        adapter: &Arc<dyn LspAdapterDelegate>,
1770        toolchain: Option<Toolchain>,
1771        _: Option<Uri>,
1772        cx: &mut AsyncApp,
1773    ) -> Result<Value> {
1774        Ok(cx.update(move |cx| {
1775            let mut user_settings =
1776                language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
1777                    .and_then(|s| s.settings.clone())
1778                    .unwrap_or_else(|| {
1779                        json!({
1780                            "plugins": {
1781                                "pycodestyle": {"enabled": false},
1782                                "rope_autoimport": {"enabled": true, "memory": true},
1783                                "pylsp_mypy": {"enabled": false}
1784                            },
1785                            "rope": {
1786                                "ropeFolder": null
1787                            },
1788                        })
1789                    });
1790
1791            // If user did not explicitly modify their python venv, use one from picker.
1792            if let Some(toolchain) = toolchain {
1793                if !user_settings.is_object() {
1794                    user_settings = Value::Object(serde_json::Map::default());
1795                }
1796                let object = user_settings.as_object_mut().unwrap();
1797                if let Some(python) = object
1798                    .entry("plugins")
1799                    .or_insert(Value::Object(serde_json::Map::default()))
1800                    .as_object_mut()
1801                {
1802                    if let Some(jedi) = python
1803                        .entry("jedi")
1804                        .or_insert(Value::Object(serde_json::Map::default()))
1805                        .as_object_mut()
1806                    {
1807                        jedi.entry("environment".to_string())
1808                            .or_insert_with(|| Value::String(toolchain.path.clone().into()));
1809                    }
1810                    if let Some(pylint) = python
1811                        .entry("pylsp_mypy")
1812                        .or_insert(Value::Object(serde_json::Map::default()))
1813                        .as_object_mut()
1814                    {
1815                        pylint.entry("overrides".to_string()).or_insert_with(|| {
1816                            Value::Array(vec![
1817                                Value::String("--python-executable".into()),
1818                                Value::String(toolchain.path.into()),
1819                                Value::String("--cache-dir=/dev/null".into()),
1820                                Value::Bool(true),
1821                            ])
1822                        });
1823                    }
1824                }
1825            }
1826            user_settings = Value::Object(serde_json::Map::from_iter([(
1827                "pylsp".to_string(),
1828                user_settings,
1829            )]));
1830
1831            user_settings
1832        }))
1833    }
1834}
1835
1836impl LspInstaller for PyLspAdapter {
1837    type BinaryVersion = ();
1838    async fn check_if_user_installed(
1839        &self,
1840        delegate: &dyn LspAdapterDelegate,
1841        toolchain: Option<Toolchain>,
1842        _: &AsyncApp,
1843    ) -> Option<LanguageServerBinary> {
1844        if let Some(pylsp_bin) = delegate.which(Self::SERVER_NAME.as_ref()).await {
1845            let env = delegate.shell_env().await;
1846            Some(LanguageServerBinary {
1847                path: pylsp_bin,
1848                env: Some(env),
1849                arguments: vec![],
1850            })
1851        } else {
1852            let toolchain = toolchain?;
1853            let pylsp_path = Path::new(toolchain.path.as_ref()).parent()?.join("pylsp");
1854            pylsp_path.exists().then(|| LanguageServerBinary {
1855                path: toolchain.path.to_string().into(),
1856                arguments: vec![pylsp_path.into()],
1857                env: None,
1858            })
1859        }
1860    }
1861
1862    async fn fetch_latest_server_version(
1863        &self,
1864        _: &dyn LspAdapterDelegate,
1865        _: bool,
1866        _: &mut AsyncApp,
1867    ) -> Result<()> {
1868        Ok(())
1869    }
1870
1871    async fn fetch_server_binary(
1872        &self,
1873        _: (),
1874        _: PathBuf,
1875        delegate: &dyn LspAdapterDelegate,
1876    ) -> Result<LanguageServerBinary> {
1877        let venv = self.base_venv(delegate).await.map_err(|e| anyhow!(e))?;
1878        let pip_path = venv.join(BINARY_DIR).join("pip3");
1879        ensure!(
1880            util::command::new_smol_command(pip_path.as_path())
1881                .arg("install")
1882                .arg("python-lsp-server[all]")
1883                .arg("--upgrade")
1884                .output()
1885                .await?
1886                .status
1887                .success(),
1888            "python-lsp-server[all] installation failed"
1889        );
1890        ensure!(
1891            util::command::new_smol_command(pip_path)
1892                .arg("install")
1893                .arg("pylsp-mypy")
1894                .arg("--upgrade")
1895                .output()
1896                .await?
1897                .status
1898                .success(),
1899            "pylsp-mypy installation failed"
1900        );
1901        let pylsp = venv.join(BINARY_DIR).join("pylsp");
1902        ensure!(
1903            delegate.which(pylsp.as_os_str()).await.is_some(),
1904            "pylsp installation was incomplete"
1905        );
1906        Ok(LanguageServerBinary {
1907            path: pylsp,
1908            env: None,
1909            arguments: vec![],
1910        })
1911    }
1912
1913    async fn cached_server_binary(
1914        &self,
1915        _: PathBuf,
1916        delegate: &dyn LspAdapterDelegate,
1917    ) -> Option<LanguageServerBinary> {
1918        let venv = self.base_venv(delegate).await.ok()?;
1919        let pylsp = venv.join(BINARY_DIR).join("pylsp");
1920        delegate.which(pylsp.as_os_str()).await?;
1921        Some(LanguageServerBinary {
1922            path: pylsp,
1923            env: None,
1924            arguments: vec![],
1925        })
1926    }
1927}
1928
1929pub(crate) struct BasedPyrightLspAdapter {
1930    node: NodeRuntime,
1931}
1932
1933impl BasedPyrightLspAdapter {
1934    const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("basedpyright");
1935    const BINARY_NAME: &'static str = "basedpyright-langserver";
1936    const SERVER_PATH: &str = "node_modules/basedpyright/langserver.index.js";
1937    const NODE_MODULE_RELATIVE_SERVER_PATH: &str = "basedpyright/langserver.index.js";
1938
1939    pub(crate) fn new(node: NodeRuntime) -> Self {
1940        BasedPyrightLspAdapter { node }
1941    }
1942
1943    async fn get_cached_server_binary(
1944        container_dir: PathBuf,
1945        node: &NodeRuntime,
1946    ) -> Option<LanguageServerBinary> {
1947        let server_path = container_dir.join(Self::SERVER_PATH);
1948        if server_path.exists() {
1949            Some(LanguageServerBinary {
1950                path: node.binary_path().await.log_err()?,
1951                env: None,
1952                arguments: vec![server_path.into(), "--stdio".into()],
1953            })
1954        } else {
1955            log::error!("missing executable in directory {:?}", server_path);
1956            None
1957        }
1958    }
1959}
1960
1961#[async_trait(?Send)]
1962impl LspAdapter for BasedPyrightLspAdapter {
1963    fn name(&self) -> LanguageServerName {
1964        Self::SERVER_NAME
1965    }
1966
1967    async fn initialization_options(
1968        self: Arc<Self>,
1969        _: &Arc<dyn LspAdapterDelegate>,
1970    ) -> Result<Option<Value>> {
1971        // Provide minimal initialization options
1972        // Virtual environment configuration will be handled through workspace configuration
1973        Ok(Some(json!({
1974            "python": {
1975                "analysis": {
1976                    "autoSearchPaths": true,
1977                    "useLibraryCodeForTypes": true,
1978                    "autoImportCompletions": true
1979                }
1980            }
1981        })))
1982    }
1983
1984    async fn process_completions(&self, items: &mut [lsp::CompletionItem]) {
1985        process_pyright_completions(items);
1986    }
1987
1988    async fn label_for_completion(
1989        &self,
1990        item: &lsp::CompletionItem,
1991        language: &Arc<language::Language>,
1992    ) -> Option<language::CodeLabel> {
1993        let label = &item.label;
1994        let label_len = label.len();
1995        let grammar = language.grammar()?;
1996        let highlight_id = match item.kind? {
1997            lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method"),
1998            lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function"),
1999            lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type"),
2000            lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant"),
2001            lsp::CompletionItemKind::VARIABLE => grammar.highlight_id_for_name("variable"),
2002            _ => {
2003                return None;
2004            }
2005        };
2006        let mut text = label.clone();
2007        if let Some(completion_details) = item
2008            .label_details
2009            .as_ref()
2010            .and_then(|details| details.description.as_ref())
2011        {
2012            write!(&mut text, " {}", completion_details).ok();
2013        }
2014        Some(language::CodeLabel::filtered(
2015            text,
2016            label_len,
2017            item.filter_text.as_deref(),
2018            highlight_id
2019                .map(|id| (0..label.len(), id))
2020                .into_iter()
2021                .collect(),
2022        ))
2023    }
2024
2025    async fn label_for_symbol(
2026        &self,
2027        name: &str,
2028        kind: lsp::SymbolKind,
2029        language: &Arc<language::Language>,
2030    ) -> Option<language::CodeLabel> {
2031        let (text, filter_range, display_range) = match kind {
2032            lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
2033                let text = format!("def {}():\n", name);
2034                let filter_range = 4..4 + name.len();
2035                let display_range = 0..filter_range.end;
2036                (text, filter_range, display_range)
2037            }
2038            lsp::SymbolKind::CLASS => {
2039                let text = format!("class {}:", name);
2040                let filter_range = 6..6 + name.len();
2041                let display_range = 0..filter_range.end;
2042                (text, filter_range, display_range)
2043            }
2044            lsp::SymbolKind::CONSTANT => {
2045                let text = format!("{} = 0", name);
2046                let filter_range = 0..name.len();
2047                let display_range = 0..filter_range.end;
2048                (text, filter_range, display_range)
2049            }
2050            _ => return None,
2051        };
2052        Some(language::CodeLabel::new(
2053            text[display_range.clone()].to_string(),
2054            filter_range,
2055            language.highlight_text(&text.as_str().into(), display_range),
2056        ))
2057    }
2058
2059    async fn workspace_configuration(
2060        self: Arc<Self>,
2061        adapter: &Arc<dyn LspAdapterDelegate>,
2062        toolchain: Option<Toolchain>,
2063        _: Option<Uri>,
2064        cx: &mut AsyncApp,
2065    ) -> Result<Value> {
2066        Ok(cx.update(move |cx| {
2067            let mut user_settings =
2068                language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
2069                    .and_then(|s| s.settings.clone())
2070                    .unwrap_or_default();
2071
2072            // If we have a detected toolchain, configure Pyright to use it
2073            if let Some(toolchain) = toolchain
2074                && let Ok(env) = serde_json::from_value::<
2075                    pet_core::python_environment::PythonEnvironment,
2076                >(toolchain.as_json.clone())
2077            {
2078                if !user_settings.is_object() {
2079                    user_settings = Value::Object(serde_json::Map::default());
2080                }
2081                let object = user_settings.as_object_mut().unwrap();
2082
2083                let interpreter_path = toolchain.path.to_string();
2084                if let Some(venv_dir) = env.prefix {
2085                    // Set venvPath and venv at the root level
2086                    // This matches the format of a pyrightconfig.json file
2087                    if let Some(parent) = venv_dir.parent() {
2088                        // Use relative path if the venv is inside the workspace
2089                        let venv_path = if parent == adapter.worktree_root_path() {
2090                            ".".to_string()
2091                        } else {
2092                            parent.to_string_lossy().into_owned()
2093                        };
2094                        object.insert("venvPath".to_string(), Value::String(venv_path));
2095                    }
2096
2097                    if let Some(venv_name) = venv_dir.file_name() {
2098                        object.insert(
2099                            "venv".to_owned(),
2100                            Value::String(venv_name.to_string_lossy().into_owned()),
2101                        );
2102                    }
2103                }
2104
2105                // Set both pythonPath and defaultInterpreterPath for compatibility
2106                if let Some(python) = object
2107                    .entry("python")
2108                    .or_insert(Value::Object(serde_json::Map::default()))
2109                    .as_object_mut()
2110                {
2111                    python.insert(
2112                        "pythonPath".to_owned(),
2113                        Value::String(interpreter_path.clone()),
2114                    );
2115                    python.insert(
2116                        "defaultInterpreterPath".to_owned(),
2117                        Value::String(interpreter_path),
2118                    );
2119                }
2120                // Basedpyright by default uses `strict` type checking, we tone it down as to not surpris users
2121                maybe!({
2122                    let analysis = object
2123                        .entry("basedpyright.analysis")
2124                        .or_insert(Value::Object(serde_json::Map::default()));
2125                    if let serde_json::map::Entry::Vacant(v) =
2126                        analysis.as_object_mut()?.entry("typeCheckingMode")
2127                    {
2128                        v.insert(Value::String("standard".to_owned()));
2129                    }
2130                    Some(())
2131                });
2132                // Disable basedpyright's organizeImports so ruff handles it instead
2133                if let serde_json::map::Entry::Vacant(v) =
2134                    object.entry("basedpyright.disableOrganizeImports")
2135                {
2136                    v.insert(Value::Bool(true));
2137                }
2138            }
2139
2140            user_settings
2141        }))
2142    }
2143}
2144
2145impl LspInstaller for BasedPyrightLspAdapter {
2146    type BinaryVersion = Version;
2147
2148    async fn fetch_latest_server_version(
2149        &self,
2150        _: &dyn LspAdapterDelegate,
2151        _: bool,
2152        _: &mut AsyncApp,
2153    ) -> Result<Self::BinaryVersion> {
2154        self.node
2155            .npm_package_latest_version(Self::SERVER_NAME.as_ref())
2156            .await
2157    }
2158
2159    async fn check_if_user_installed(
2160        &self,
2161        delegate: &dyn LspAdapterDelegate,
2162        _: Option<Toolchain>,
2163        _: &AsyncApp,
2164    ) -> Option<LanguageServerBinary> {
2165        if let Some(path) = delegate.which(Self::BINARY_NAME.as_ref()).await {
2166            let env = delegate.shell_env().await;
2167            Some(LanguageServerBinary {
2168                path,
2169                env: Some(env),
2170                arguments: vec!["--stdio".into()],
2171            })
2172        } else {
2173            // TODO shouldn't this be self.node.binary_path()?
2174            let node = delegate.which("node".as_ref()).await?;
2175            let (node_modules_path, _) = delegate
2176                .npm_package_installed_version(Self::SERVER_NAME.as_ref())
2177                .await
2178                .log_err()??;
2179
2180            let path = node_modules_path.join(Self::NODE_MODULE_RELATIVE_SERVER_PATH);
2181
2182            let env = delegate.shell_env().await;
2183            Some(LanguageServerBinary {
2184                path: node,
2185                env: Some(env),
2186                arguments: vec![path.into(), "--stdio".into()],
2187            })
2188        }
2189    }
2190
2191    async fn fetch_server_binary(
2192        &self,
2193        latest_version: Self::BinaryVersion,
2194        container_dir: PathBuf,
2195        delegate: &dyn LspAdapterDelegate,
2196    ) -> Result<LanguageServerBinary> {
2197        let server_path = container_dir.join(Self::SERVER_PATH);
2198        let latest_version = latest_version.to_string();
2199
2200        self.node
2201            .npm_install_packages(
2202                &container_dir,
2203                &[(Self::SERVER_NAME.as_ref(), latest_version.as_str())],
2204            )
2205            .await?;
2206
2207        let env = delegate.shell_env().await;
2208        Ok(LanguageServerBinary {
2209            path: self.node.binary_path().await?,
2210            env: Some(env),
2211            arguments: vec![server_path.into(), "--stdio".into()],
2212        })
2213    }
2214
2215    async fn check_if_version_installed(
2216        &self,
2217        version: &Self::BinaryVersion,
2218        container_dir: &PathBuf,
2219        delegate: &dyn LspAdapterDelegate,
2220    ) -> Option<LanguageServerBinary> {
2221        let server_path = container_dir.join(Self::SERVER_PATH);
2222
2223        let should_install_language_server = self
2224            .node
2225            .should_install_npm_package(
2226                Self::SERVER_NAME.as_ref(),
2227                &server_path,
2228                container_dir,
2229                VersionStrategy::Latest(version),
2230            )
2231            .await;
2232
2233        if should_install_language_server {
2234            None
2235        } else {
2236            let env = delegate.shell_env().await;
2237            Some(LanguageServerBinary {
2238                path: self.node.binary_path().await.ok()?,
2239                env: Some(env),
2240                arguments: vec![server_path.into(), "--stdio".into()],
2241            })
2242        }
2243    }
2244
2245    async fn cached_server_binary(
2246        &self,
2247        container_dir: PathBuf,
2248        delegate: &dyn LspAdapterDelegate,
2249    ) -> Option<LanguageServerBinary> {
2250        let mut binary = Self::get_cached_server_binary(container_dir, &self.node).await?;
2251        binary.env = Some(delegate.shell_env().await);
2252        Some(binary)
2253    }
2254}
2255
2256pub(crate) struct RuffLspAdapter {
2257    fs: Arc<dyn Fs>,
2258}
2259
2260impl RuffLspAdapter {
2261    fn convert_ruff_schema(raw_schema: &serde_json::Value) -> serde_json::Value {
2262        let Some(schema_object) = raw_schema.as_object() else {
2263            return raw_schema.clone();
2264        };
2265
2266        let mut root_properties = serde_json::Map::new();
2267
2268        for (key, value) in schema_object {
2269            let parts: Vec<&str> = key.split('.').collect();
2270
2271            if parts.is_empty() {
2272                continue;
2273            }
2274
2275            let mut current = &mut root_properties;
2276
2277            for (i, part) in parts.iter().enumerate() {
2278                let is_last = i == parts.len() - 1;
2279
2280                if is_last {
2281                    let mut schema_entry = serde_json::Map::new();
2282
2283                    if let Some(doc) = value.get("doc").and_then(|d| d.as_str()) {
2284                        schema_entry.insert(
2285                            "markdownDescription".to_string(),
2286                            serde_json::Value::String(doc.to_string()),
2287                        );
2288                    }
2289
2290                    if let Some(default_val) = value.get("default") {
2291                        schema_entry.insert("default".to_string(), default_val.clone());
2292                    }
2293
2294                    if let Some(value_type) = value.get("value_type").and_then(|v| v.as_str()) {
2295                        if value_type.contains('|') {
2296                            let enum_values: Vec<serde_json::Value> = value_type
2297                                .split('|')
2298                                .map(|s| s.trim().trim_matches('"'))
2299                                .filter(|s| !s.is_empty())
2300                                .map(|s| serde_json::Value::String(s.to_string()))
2301                                .collect();
2302
2303                            if !enum_values.is_empty() {
2304                                schema_entry
2305                                    .insert("type".to_string(), serde_json::json!("string"));
2306                                schema_entry.insert(
2307                                    "enum".to_string(),
2308                                    serde_json::Value::Array(enum_values),
2309                                );
2310                            }
2311                        } else if value_type.starts_with("list[") {
2312                            schema_entry.insert("type".to_string(), serde_json::json!("array"));
2313                            if let Some(item_type) = value_type
2314                                .strip_prefix("list[")
2315                                .and_then(|s| s.strip_suffix(']'))
2316                            {
2317                                let json_type = match item_type {
2318                                    "str" => "string",
2319                                    "int" => "integer",
2320                                    "bool" => "boolean",
2321                                    _ => "string",
2322                                };
2323                                schema_entry.insert(
2324                                    "items".to_string(),
2325                                    serde_json::json!({"type": json_type}),
2326                                );
2327                            }
2328                        } else if value_type.starts_with("dict[") {
2329                            schema_entry.insert("type".to_string(), serde_json::json!("object"));
2330                        } else {
2331                            let json_type = match value_type {
2332                                "bool" => "boolean",
2333                                "int" | "usize" => "integer",
2334                                "str" => "string",
2335                                _ => "string",
2336                            };
2337                            schema_entry.insert(
2338                                "type".to_string(),
2339                                serde_json::Value::String(json_type.to_string()),
2340                            );
2341                        }
2342                    }
2343
2344                    current.insert(part.to_string(), serde_json::Value::Object(schema_entry));
2345                } else {
2346                    let next_current = current
2347                        .entry(part.to_string())
2348                        .or_insert_with(|| {
2349                            serde_json::json!({
2350                                "type": "object",
2351                                "properties": {}
2352                            })
2353                        })
2354                        .as_object_mut()
2355                        .expect("should be an object")
2356                        .entry("properties")
2357                        .or_insert_with(|| serde_json::json!({}))
2358                        .as_object_mut()
2359                        .expect("properties should be an object");
2360
2361                    current = next_current;
2362                }
2363            }
2364        }
2365
2366        serde_json::json!({
2367            "type": "object",
2368            "properties": root_properties
2369        })
2370    }
2371}
2372
2373#[cfg(target_os = "macos")]
2374impl RuffLspAdapter {
2375    const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
2376    const ARCH_SERVER_NAME: &str = "apple-darwin";
2377}
2378
2379#[cfg(target_os = "linux")]
2380impl RuffLspAdapter {
2381    const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
2382    const ARCH_SERVER_NAME: &str = "unknown-linux-gnu";
2383}
2384
2385#[cfg(target_os = "freebsd")]
2386impl RuffLspAdapter {
2387    const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
2388    const ARCH_SERVER_NAME: &str = "unknown-freebsd";
2389}
2390
2391#[cfg(target_os = "windows")]
2392impl RuffLspAdapter {
2393    const GITHUB_ASSET_KIND: AssetKind = AssetKind::Zip;
2394    const ARCH_SERVER_NAME: &str = "pc-windows-msvc";
2395}
2396
2397impl RuffLspAdapter {
2398    const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("ruff");
2399
2400    pub fn new(fs: Arc<dyn Fs>) -> RuffLspAdapter {
2401        RuffLspAdapter { fs }
2402    }
2403
2404    fn build_asset_name() -> Result<(String, String)> {
2405        let arch = match consts::ARCH {
2406            "x86" => "i686",
2407            _ => consts::ARCH,
2408        };
2409        let os = Self::ARCH_SERVER_NAME;
2410        let suffix = match consts::OS {
2411            "windows" => "zip",
2412            _ => "tar.gz",
2413        };
2414        let asset_name = format!("ruff-{arch}-{os}.{suffix}");
2415        let asset_stem = format!("ruff-{arch}-{os}");
2416        Ok((asset_stem, asset_name))
2417    }
2418}
2419
2420#[async_trait(?Send)]
2421impl LspAdapter for RuffLspAdapter {
2422    fn name(&self) -> LanguageServerName {
2423        Self::SERVER_NAME
2424    }
2425
2426    async fn initialization_options_schema(
2427        self: Arc<Self>,
2428        delegate: &Arc<dyn LspAdapterDelegate>,
2429        cached_binary: OwnedMutexGuard<Option<(bool, LanguageServerBinary)>>,
2430        cx: &mut AsyncApp,
2431    ) -> Option<serde_json::Value> {
2432        let binary = self
2433            .get_language_server_command(
2434                delegate.clone(),
2435                None,
2436                LanguageServerBinaryOptions {
2437                    allow_path_lookup: true,
2438                    allow_binary_download: false,
2439                    pre_release: false,
2440                },
2441                cached_binary,
2442                cx.clone(),
2443            )
2444            .await
2445            .0
2446            .ok()?;
2447
2448        let mut command = util::command::new_smol_command(&binary.path);
2449        command
2450            .args(&["config", "--output-format", "json"])
2451            .stdout(Stdio::piped())
2452            .stderr(Stdio::piped());
2453        let cmd = command
2454            .spawn()
2455            .map_err(|e| log::debug!("failed to spawn command {command:?}: {e}"))
2456            .ok()?;
2457        let output = cmd
2458            .output()
2459            .await
2460            .map_err(|e| log::debug!("failed to execute command {command:?}: {e}"))
2461            .ok()?;
2462        if !output.status.success() {
2463            return None;
2464        }
2465
2466        let raw_schema: serde_json::Value = serde_json::from_slice(output.stdout.as_slice())
2467            .map_err(|e| log::debug!("failed to parse ruff's JSON schema output: {e}"))
2468            .ok()?;
2469
2470        let converted_schema = Self::convert_ruff_schema(&raw_schema);
2471        Some(converted_schema)
2472    }
2473}
2474
2475impl LspInstaller for RuffLspAdapter {
2476    type BinaryVersion = GitHubLspBinaryVersion;
2477    async fn check_if_user_installed(
2478        &self,
2479        delegate: &dyn LspAdapterDelegate,
2480        toolchain: Option<Toolchain>,
2481        _: &AsyncApp,
2482    ) -> Option<LanguageServerBinary> {
2483        let ruff_in_venv = if let Some(toolchain) = toolchain
2484            && toolchain.language_name.as_ref() == "Python"
2485        {
2486            Path::new(toolchain.path.as_str())
2487                .parent()
2488                .map(|path| path.join("ruff"))
2489        } else {
2490            None
2491        };
2492
2493        for path in ruff_in_venv.into_iter().chain(["ruff".into()]) {
2494            if let Some(ruff_bin) = delegate.which(path.as_os_str()).await {
2495                let env = delegate.shell_env().await;
2496                return Some(LanguageServerBinary {
2497                    path: ruff_bin,
2498                    env: Some(env),
2499                    arguments: vec!["server".into()],
2500                });
2501            }
2502        }
2503
2504        None
2505    }
2506
2507    async fn fetch_latest_server_version(
2508        &self,
2509        delegate: &dyn LspAdapterDelegate,
2510        _: bool,
2511        _: &mut AsyncApp,
2512    ) -> Result<GitHubLspBinaryVersion> {
2513        let release =
2514            latest_github_release("astral-sh/ruff", true, false, delegate.http_client()).await?;
2515        let (_, asset_name) = Self::build_asset_name()?;
2516        let asset = release
2517            .assets
2518            .into_iter()
2519            .find(|asset| asset.name == asset_name)
2520            .with_context(|| format!("no asset found matching `{asset_name:?}`"))?;
2521        Ok(GitHubLspBinaryVersion {
2522            name: release.tag_name,
2523            url: asset.browser_download_url,
2524            digest: asset.digest,
2525        })
2526    }
2527
2528    async fn fetch_server_binary(
2529        &self,
2530        latest_version: GitHubLspBinaryVersion,
2531        container_dir: PathBuf,
2532        delegate: &dyn LspAdapterDelegate,
2533    ) -> Result<LanguageServerBinary> {
2534        let GitHubLspBinaryVersion {
2535            name,
2536            url,
2537            digest: expected_digest,
2538        } = latest_version;
2539        let destination_path = container_dir.join(format!("ruff-{name}"));
2540        let server_path = match Self::GITHUB_ASSET_KIND {
2541            AssetKind::TarGz | AssetKind::Gz => destination_path
2542                .join(Self::build_asset_name()?.0)
2543                .join("ruff"),
2544            AssetKind::Zip => destination_path.clone().join("ruff.exe"),
2545        };
2546
2547        let binary = LanguageServerBinary {
2548            path: server_path.clone(),
2549            env: None,
2550            arguments: vec!["server".into()],
2551        };
2552
2553        let metadata_path = destination_path.with_extension("metadata");
2554        let metadata = GithubBinaryMetadata::read_from_file(&metadata_path)
2555            .await
2556            .ok();
2557        if let Some(metadata) = metadata {
2558            let validity_check = async || {
2559                delegate
2560                    .try_exec(LanguageServerBinary {
2561                        path: server_path.clone(),
2562                        arguments: vec!["--version".into()],
2563                        env: None,
2564                    })
2565                    .await
2566                    .inspect_err(|err| {
2567                        log::warn!("Unable to run {server_path:?} asset, redownloading: {err:#}",)
2568                    })
2569            };
2570            if let (Some(actual_digest), Some(expected_digest)) =
2571                (&metadata.digest, &expected_digest)
2572            {
2573                if actual_digest == expected_digest {
2574                    if validity_check().await.is_ok() {
2575                        return Ok(binary);
2576                    }
2577                } else {
2578                    log::info!(
2579                        "SHA-256 mismatch for {destination_path:?} asset, downloading new asset. Expected: {expected_digest}, Got: {actual_digest}"
2580                    );
2581                }
2582            } else if validity_check().await.is_ok() {
2583                return Ok(binary);
2584            }
2585        }
2586
2587        download_server_binary(
2588            &*delegate.http_client(),
2589            &url,
2590            expected_digest.as_deref(),
2591            &destination_path,
2592            Self::GITHUB_ASSET_KIND,
2593        )
2594        .await?;
2595        make_file_executable(&server_path).await?;
2596        remove_matching(&container_dir, |path| path != destination_path).await;
2597        GithubBinaryMetadata::write_to_file(
2598            &GithubBinaryMetadata {
2599                metadata_version: 1,
2600                digest: expected_digest,
2601            },
2602            &metadata_path,
2603        )
2604        .await?;
2605
2606        Ok(LanguageServerBinary {
2607            path: server_path,
2608            env: None,
2609            arguments: vec!["server".into()],
2610        })
2611    }
2612
2613    async fn cached_server_binary(
2614        &self,
2615        container_dir: PathBuf,
2616        _: &dyn LspAdapterDelegate,
2617    ) -> Option<LanguageServerBinary> {
2618        maybe!(async {
2619            let mut last = None;
2620            let mut entries = self.fs.read_dir(&container_dir).await?;
2621            while let Some(entry) = entries.next().await {
2622                let path = entry?;
2623                if path.extension().is_some_and(|ext| ext == "metadata") {
2624                    continue;
2625                }
2626                last = Some(path);
2627            }
2628
2629            let path = last.context("no cached binary")?;
2630            let path = match Self::GITHUB_ASSET_KIND {
2631                AssetKind::TarGz | AssetKind::Gz => {
2632                    path.join(Self::build_asset_name()?.0).join("ruff")
2633                }
2634                AssetKind::Zip => path.join("ruff.exe"),
2635            };
2636
2637            anyhow::Ok(LanguageServerBinary {
2638                path,
2639                env: None,
2640                arguments: vec!["server".into()],
2641            })
2642        })
2643        .await
2644        .log_err()
2645    }
2646}
2647
2648#[cfg(test)]
2649mod tests {
2650    use gpui::{AppContext as _, BorrowAppContext, Context, TestAppContext};
2651    use language::{AutoindentMode, Buffer};
2652    use settings::SettingsStore;
2653    use std::num::NonZeroU32;
2654
2655    use crate::python::python_module_name_from_relative_path;
2656
2657    #[gpui::test]
2658    async fn test_python_autoindent(cx: &mut TestAppContext) {
2659        cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
2660        let language = crate::language("python", tree_sitter_python::LANGUAGE.into());
2661        cx.update(|cx| {
2662            let test_settings = SettingsStore::test(cx);
2663            cx.set_global(test_settings);
2664            cx.update_global::<SettingsStore, _>(|store, cx| {
2665                store.update_user_settings(cx, |s| {
2666                    s.project.all_languages.defaults.tab_size = NonZeroU32::new(2);
2667                });
2668            });
2669        });
2670
2671        cx.new(|cx| {
2672            let mut buffer = Buffer::local("", cx).with_language(language, cx);
2673            let append = |buffer: &mut Buffer, text: &str, cx: &mut Context<Buffer>| {
2674                let ix = buffer.len();
2675                buffer.edit([(ix..ix, text)], Some(AutoindentMode::EachLine), cx);
2676            };
2677
2678            // indent after "def():"
2679            append(&mut buffer, "def a():\n", cx);
2680            assert_eq!(buffer.text(), "def a():\n  ");
2681
2682            // preserve indent after blank line
2683            append(&mut buffer, "\n  ", cx);
2684            assert_eq!(buffer.text(), "def a():\n  \n  ");
2685
2686            // indent after "if"
2687            append(&mut buffer, "if a:\n  ", cx);
2688            assert_eq!(buffer.text(), "def a():\n  \n  if a:\n    ");
2689
2690            // preserve indent after statement
2691            append(&mut buffer, "b()\n", cx);
2692            assert_eq!(buffer.text(), "def a():\n  \n  if a:\n    b()\n    ");
2693
2694            // preserve indent after statement
2695            append(&mut buffer, "else", cx);
2696            assert_eq!(buffer.text(), "def a():\n  \n  if a:\n    b()\n    else");
2697
2698            // dedent "else""
2699            append(&mut buffer, ":", cx);
2700            assert_eq!(buffer.text(), "def a():\n  \n  if a:\n    b()\n  else:");
2701
2702            // indent lines after else
2703            append(&mut buffer, "\n", cx);
2704            assert_eq!(
2705                buffer.text(),
2706                "def a():\n  \n  if a:\n    b()\n  else:\n    "
2707            );
2708
2709            // indent after an open paren. the closing paren is not indented
2710            // because there is another token before it on the same line.
2711            append(&mut buffer, "foo(\n1)", cx);
2712            assert_eq!(
2713                buffer.text(),
2714                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n      1)"
2715            );
2716
2717            // dedent the closing paren if it is shifted to the beginning of the line
2718            let argument_ix = buffer.text().find('1').unwrap();
2719            buffer.edit(
2720                [(argument_ix..argument_ix + 1, "")],
2721                Some(AutoindentMode::EachLine),
2722                cx,
2723            );
2724            assert_eq!(
2725                buffer.text(),
2726                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n    )"
2727            );
2728
2729            // preserve indent after the close paren
2730            append(&mut buffer, "\n", cx);
2731            assert_eq!(
2732                buffer.text(),
2733                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n    )\n    "
2734            );
2735
2736            // manually outdent the last line
2737            let end_whitespace_ix = buffer.len() - 4;
2738            buffer.edit(
2739                [(end_whitespace_ix..buffer.len(), "")],
2740                Some(AutoindentMode::EachLine),
2741                cx,
2742            );
2743            assert_eq!(
2744                buffer.text(),
2745                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n    )\n"
2746            );
2747
2748            // preserve the newly reduced indentation on the next newline
2749            append(&mut buffer, "\n", cx);
2750            assert_eq!(
2751                buffer.text(),
2752                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n    )\n\n"
2753            );
2754
2755            // reset to a for loop statement
2756            let statement = "for i in range(10):\n  print(i)\n";
2757            buffer.edit([(0..buffer.len(), statement)], None, cx);
2758
2759            // insert single line comment after each line
2760            let eol_ixs = statement
2761                .char_indices()
2762                .filter_map(|(ix, c)| if c == '\n' { Some(ix) } else { None })
2763                .collect::<Vec<usize>>();
2764            let editions = eol_ixs
2765                .iter()
2766                .enumerate()
2767                .map(|(i, &eol_ix)| (eol_ix..eol_ix, format!(" # comment {}", i + 1)))
2768                .collect::<Vec<(std::ops::Range<usize>, String)>>();
2769            buffer.edit(editions, Some(AutoindentMode::EachLine), cx);
2770            assert_eq!(
2771                buffer.text(),
2772                "for i in range(10): # comment 1\n  print(i) # comment 2\n"
2773            );
2774
2775            // reset to a simple if statement
2776            buffer.edit([(0..buffer.len(), "if a:\n  b(\n  )")], None, cx);
2777
2778            // dedent "else" on the line after a closing paren
2779            append(&mut buffer, "\n  else:\n", cx);
2780            assert_eq!(buffer.text(), "if a:\n  b(\n  )\nelse:\n  ");
2781
2782            buffer
2783        });
2784    }
2785
2786    #[test]
2787    fn test_python_module_name_from_relative_path() {
2788        assert_eq!(
2789            python_module_name_from_relative_path("foo/bar.py"),
2790            Some("foo.bar".to_string())
2791        );
2792        assert_eq!(
2793            python_module_name_from_relative_path("foo/bar"),
2794            Some("foo.bar".to_string())
2795        );
2796        if cfg!(windows) {
2797            assert_eq!(
2798                python_module_name_from_relative_path("foo\\bar.py"),
2799                Some("foo.bar".to_string())
2800            );
2801            assert_eq!(
2802                python_module_name_from_relative_path("foo\\bar"),
2803                Some("foo.bar".to_string())
2804            );
2805        } else {
2806            assert_eq!(
2807                python_module_name_from_relative_path("foo\\bar.py"),
2808                Some("foo\\bar".to_string())
2809            );
2810            assert_eq!(
2811                python_module_name_from_relative_path("foo\\bar"),
2812                Some("foo\\bar".to_string())
2813            );
2814        }
2815    }
2816
2817    #[test]
2818    fn test_convert_ruff_schema() {
2819        use super::RuffLspAdapter;
2820
2821        let raw_schema = serde_json::json!({
2822            "line-length": {
2823                "doc": "The line length to use when enforcing long-lines violations",
2824                "default": "88",
2825                "value_type": "int",
2826                "scope": null,
2827                "example": "line-length = 120",
2828                "deprecated": null
2829            },
2830            "lint.select": {
2831                "doc": "A list of rule codes or prefixes to enable",
2832                "default": "[\"E4\", \"E7\", \"E9\", \"F\"]",
2833                "value_type": "list[RuleSelector]",
2834                "scope": null,
2835                "example": "select = [\"E4\", \"E7\", \"E9\", \"F\", \"B\", \"Q\"]",
2836                "deprecated": null
2837            },
2838            "lint.isort.case-sensitive": {
2839                "doc": "Sort imports taking into account case sensitivity.",
2840                "default": "false",
2841                "value_type": "bool",
2842                "scope": null,
2843                "example": "case-sensitive = true",
2844                "deprecated": null
2845            },
2846            "format.quote-style": {
2847                "doc": "Configures the preferred quote character for strings.",
2848                "default": "\"double\"",
2849                "value_type": "\"double\" | \"single\" | \"preserve\"",
2850                "scope": null,
2851                "example": "quote-style = \"single\"",
2852                "deprecated": null
2853            }
2854        });
2855
2856        let converted = RuffLspAdapter::convert_ruff_schema(&raw_schema);
2857
2858        assert!(converted.is_object());
2859        assert_eq!(
2860            converted.get("type").and_then(|v| v.as_str()),
2861            Some("object")
2862        );
2863
2864        let properties = converted
2865            .get("properties")
2866            .expect("should have properties")
2867            .as_object()
2868            .expect("properties should be an object");
2869
2870        assert!(properties.contains_key("line-length"));
2871        assert!(properties.contains_key("lint"));
2872        assert!(properties.contains_key("format"));
2873
2874        let line_length = properties
2875            .get("line-length")
2876            .expect("should have line-length")
2877            .as_object()
2878            .expect("line-length should be an object");
2879
2880        assert_eq!(
2881            line_length.get("type").and_then(|v| v.as_str()),
2882            Some("integer")
2883        );
2884        assert_eq!(
2885            line_length.get("default").and_then(|v| v.as_str()),
2886            Some("88")
2887        );
2888
2889        let lint = properties
2890            .get("lint")
2891            .expect("should have lint")
2892            .as_object()
2893            .expect("lint should be an object");
2894
2895        let lint_props = lint
2896            .get("properties")
2897            .expect("lint should have properties")
2898            .as_object()
2899            .expect("lint properties should be an object");
2900
2901        assert!(lint_props.contains_key("select"));
2902        assert!(lint_props.contains_key("isort"));
2903
2904        let select = lint_props.get("select").expect("should have select");
2905        assert_eq!(select.get("type").and_then(|v| v.as_str()), Some("array"));
2906
2907        let isort = lint_props
2908            .get("isort")
2909            .expect("should have isort")
2910            .as_object()
2911            .expect("isort should be an object");
2912
2913        let isort_props = isort
2914            .get("properties")
2915            .expect("isort should have properties")
2916            .as_object()
2917            .expect("isort properties should be an object");
2918
2919        let case_sensitive = isort_props
2920            .get("case-sensitive")
2921            .expect("should have case-sensitive");
2922
2923        assert_eq!(
2924            case_sensitive.get("type").and_then(|v| v.as_str()),
2925            Some("boolean")
2926        );
2927        assert!(case_sensitive.get("markdownDescription").is_some());
2928
2929        let format = properties
2930            .get("format")
2931            .expect("should have format")
2932            .as_object()
2933            .expect("format should be an object");
2934
2935        let format_props = format
2936            .get("properties")
2937            .expect("format should have properties")
2938            .as_object()
2939            .expect("format properties should be an object");
2940
2941        let quote_style = format_props
2942            .get("quote-style")
2943            .expect("should have quote-style");
2944
2945        assert_eq!(
2946            quote_style.get("type").and_then(|v| v.as_str()),
2947            Some("string")
2948        );
2949
2950        let enum_values = quote_style
2951            .get("enum")
2952            .expect("should have enum")
2953            .as_array()
2954            .expect("enum should be an array");
2955
2956        assert_eq!(enum_values.len(), 3);
2957        assert!(enum_values.contains(&serde_json::json!("double")));
2958        assert!(enum_values.contains(&serde_json::json!("single")));
2959        assert!(enum_values.contains(&serde_json::json!("preserve")));
2960    }
2961}