python.rs

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