python.rs

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