python.rs

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