python.rs

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