python.rs

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