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