python.rs

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