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