python.rs

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