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, true, 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("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
1134#[async_trait]
1135impl ToolchainLister for PythonToolchainProvider {
1136    async fn list(
1137        &self,
1138        worktree_root: PathBuf,
1139        subroot_relative_path: Arc<RelPath>,
1140        project_env: Option<HashMap<String, String>>,
1141        fs: &dyn Fs,
1142    ) -> ToolchainList {
1143        let env = project_env.unwrap_or_default();
1144        let environment = EnvironmentApi::from_env(&env);
1145        let locators = pet::locators::create_locators(
1146            Arc::new(pet_conda::Conda::from(&environment)),
1147            Arc::new(pet_poetry::Poetry::from(&environment)),
1148            &environment,
1149        );
1150        let mut config = Configuration::default();
1151
1152        // `.ancestors()` will yield at least one path, so in case of empty `subroot_relative_path`, we'll just use
1153        // worktree root as the workspace directory.
1154        config.workspace_directories = Some(
1155            subroot_relative_path
1156                .ancestors()
1157                .map(|ancestor| worktree_root.join(ancestor.as_std_path()))
1158                .collect(),
1159        );
1160        for locator in locators.iter() {
1161            locator.configure(&config);
1162        }
1163
1164        let reporter = pet_reporter::collect::create_reporter();
1165        pet::find::find_and_report_envs(&reporter, config, &locators, &environment, None);
1166
1167        let mut toolchains = reporter
1168            .environments
1169            .lock()
1170            .map_or(Vec::new(), |mut guard| std::mem::take(&mut guard));
1171
1172        let wr = worktree_root;
1173        let wr_venv = get_worktree_venv_declaration(&wr).await;
1174        // Sort detected environments by:
1175        //     environment name matching activation file (<workdir>/.venv)
1176        //     environment project dir matching worktree_root
1177        //     general env priority
1178        //     environment path matching the CONDA_PREFIX env var
1179        //     executable path
1180        toolchains.sort_by(|lhs, rhs| {
1181            // Compare venv names against worktree .venv file
1182            let venv_ordering =
1183                wr_venv
1184                    .as_ref()
1185                    .map_or(Ordering::Equal, |venv| match (&lhs.name, &rhs.name) {
1186                        (Some(l), Some(r)) => (r == venv).cmp(&(l == venv)),
1187                        (Some(l), None) if l == venv => Ordering::Less,
1188                        (None, Some(r)) if r == venv => Ordering::Greater,
1189                        _ => Ordering::Equal,
1190                    });
1191
1192            // Compare project paths against worktree root
1193            let proj_ordering =
1194                || {
1195                    let lhs_project = lhs.project.clone().or_else(|| get_venv_parent_dir(lhs));
1196                    let rhs_project = rhs.project.clone().or_else(|| get_venv_parent_dir(rhs));
1197                    wr_distance(&wr, &subroot_relative_path, lhs_project.as_ref()).cmp(
1198                        &wr_distance(&wr, &subroot_relative_path, rhs_project.as_ref()),
1199                    )
1200                };
1201
1202            // Compare environment priorities
1203            let priority_ordering = || env_priority(lhs.kind).cmp(&env_priority(rhs.kind));
1204
1205            // Compare conda prefixes
1206            let conda_ordering = || {
1207                if lhs.kind == Some(PythonEnvironmentKind::Conda) {
1208                    environment
1209                        .get_env_var("CONDA_PREFIX".to_string())
1210                        .map(|conda_prefix| {
1211                            let is_match = |exe: &Option<PathBuf>| {
1212                                exe.as_ref().is_some_and(|e| e.starts_with(&conda_prefix))
1213                            };
1214                            match (is_match(&lhs.executable), is_match(&rhs.executable)) {
1215                                (true, false) => Ordering::Less,
1216                                (false, true) => Ordering::Greater,
1217                                _ => Ordering::Equal,
1218                            }
1219                        })
1220                        .unwrap_or(Ordering::Equal)
1221                } else {
1222                    Ordering::Equal
1223                }
1224            };
1225
1226            // Compare Python executables
1227            let exe_ordering = || lhs.executable.cmp(&rhs.executable);
1228
1229            venv_ordering
1230                .then_with(proj_ordering)
1231                .then_with(priority_ordering)
1232                .then_with(conda_ordering)
1233                .then_with(exe_ordering)
1234        });
1235
1236        let mut out_toolchains = Vec::new();
1237        for toolchain in toolchains {
1238            let Some(toolchain) = venv_to_toolchain(toolchain, fs).await else {
1239                continue;
1240            };
1241            out_toolchains.push(toolchain);
1242        }
1243        out_toolchains.dedup();
1244        ToolchainList {
1245            toolchains: out_toolchains,
1246            default: None,
1247            groups: Default::default(),
1248        }
1249    }
1250    fn meta(&self) -> ToolchainMetadata {
1251        ToolchainMetadata {
1252            term: SharedString::new_static("Virtual Environment"),
1253            new_toolchain_placeholder: SharedString::new_static(
1254                "A path to the python3 executable within a virtual environment, or path to virtual environment itself",
1255            ),
1256            manifest_name: ManifestName::from(SharedString::new_static("pyproject.toml")),
1257        }
1258    }
1259
1260    async fn resolve(
1261        &self,
1262        path: PathBuf,
1263        env: Option<HashMap<String, String>>,
1264        fs: &dyn Fs,
1265    ) -> anyhow::Result<Toolchain> {
1266        let env = env.unwrap_or_default();
1267        let environment = EnvironmentApi::from_env(&env);
1268        let locators = pet::locators::create_locators(
1269            Arc::new(pet_conda::Conda::from(&environment)),
1270            Arc::new(pet_poetry::Poetry::from(&environment)),
1271            &environment,
1272        );
1273        let toolchain = pet::resolve::resolve_environment(&path, &locators, &environment)
1274            .context("Could not find a virtual environment in provided path")?;
1275        let venv = toolchain.resolved.unwrap_or(toolchain.discovered);
1276        venv_to_toolchain(venv, fs)
1277            .await
1278            .context("Could not convert a venv into a toolchain")
1279    }
1280
1281    fn activation_script(&self, toolchain: &Toolchain, shell: ShellKind, cx: &App) -> Vec<String> {
1282        let Ok(toolchain) =
1283            serde_json::from_value::<PythonToolchainData>(toolchain.as_json.clone())
1284        else {
1285            return vec![];
1286        };
1287
1288        log::debug!("(Python) Composing activation script for toolchain {toolchain:?}");
1289
1290        let mut activation_script = vec![];
1291
1292        match toolchain.environment.kind {
1293            Some(PythonEnvironmentKind::Conda) => {
1294                let settings = TerminalSettings::get_global(cx);
1295                let conda_manager = settings
1296                    .detect_venv
1297                    .as_option()
1298                    .map(|venv| venv.conda_manager)
1299                    .unwrap_or(settings::CondaManager::Auto);
1300
1301                let manager = match conda_manager {
1302                    settings::CondaManager::Conda => "conda",
1303                    settings::CondaManager::Mamba => "mamba",
1304                    settings::CondaManager::Micromamba => "micromamba",
1305                    settings::CondaManager::Auto => {
1306                        // When auto, prefer the detected manager or fall back to conda
1307                        toolchain
1308                            .environment
1309                            .manager
1310                            .as_ref()
1311                            .and_then(|m| m.executable.file_name())
1312                            .and_then(|name| name.to_str())
1313                            .filter(|name| matches!(*name, "conda" | "mamba" | "micromamba"))
1314                            .unwrap_or("conda")
1315                    }
1316                };
1317
1318                if let Some(name) = &toolchain.environment.name {
1319                    activation_script.push(format!("{manager} activate {name}"));
1320                } else {
1321                    activation_script.push(format!("{manager} activate base"));
1322                }
1323            }
1324            Some(PythonEnvironmentKind::Venv | PythonEnvironmentKind::VirtualEnv) => {
1325                if let Some(activation_scripts) = &toolchain.activation_scripts {
1326                    if let Some(activate_script_path) = activation_scripts.get(&shell) {
1327                        let activate_keyword = shell.activate_keyword();
1328                        if let Some(quoted) =
1329                            shell.try_quote(&activate_script_path.to_string_lossy())
1330                        {
1331                            activation_script.push(format!("{activate_keyword} {quoted}"));
1332                        }
1333                    }
1334                }
1335            }
1336            Some(PythonEnvironmentKind::Pyenv) => {
1337                let Some(manager) = &toolchain.environment.manager else {
1338                    return vec![];
1339                };
1340                let version = toolchain.environment.version.as_deref().unwrap_or("system");
1341                let pyenv = &manager.executable;
1342                let pyenv = pyenv.display();
1343                activation_script.extend(match shell {
1344                    ShellKind::Fish => Some(format!("\"{pyenv}\" shell - fish {version}")),
1345                    ShellKind::Posix => Some(format!("\"{pyenv}\" shell - sh {version}")),
1346                    ShellKind::Nushell => Some(format!("^\"{pyenv}\" shell - nu {version}")),
1347                    ShellKind::PowerShell => None,
1348                    ShellKind::Csh => None,
1349                    ShellKind::Tcsh => None,
1350                    ShellKind::Cmd => None,
1351                    ShellKind::Rc => None,
1352                    ShellKind::Xonsh => None,
1353                    ShellKind::Elvish => None,
1354                })
1355            }
1356            _ => {}
1357        }
1358        activation_script
1359    }
1360}
1361
1362async fn venv_to_toolchain(venv: PythonEnvironment, fs: &dyn Fs) -> Option<Toolchain> {
1363    let mut name = String::from("Python");
1364    if let Some(ref version) = venv.version {
1365        _ = write!(name, " {version}");
1366    }
1367
1368    let name_and_kind = match (&venv.name, &venv.kind) {
1369        (Some(name), Some(kind)) => Some(format!("({name}; {})", python_env_kind_display(kind))),
1370        (Some(name), None) => Some(format!("({name})")),
1371        (None, Some(kind)) => Some(format!("({})", python_env_kind_display(kind))),
1372        (None, None) => None,
1373    };
1374
1375    if let Some(nk) = name_and_kind {
1376        _ = write!(name, " {nk}");
1377    }
1378
1379    let mut activation_scripts = HashMap::default();
1380    match venv.kind {
1381        Some(PythonEnvironmentKind::Venv | PythonEnvironmentKind::VirtualEnv) => {
1382            resolve_venv_activation_scripts(&venv, fs, &mut activation_scripts).await
1383        }
1384        _ => {}
1385    }
1386    let data = PythonToolchainData {
1387        environment: venv,
1388        activation_scripts: Some(activation_scripts),
1389    };
1390
1391    Some(Toolchain {
1392        name: name.into(),
1393        path: data
1394            .environment
1395            .executable
1396            .as_ref()?
1397            .to_str()?
1398            .to_owned()
1399            .into(),
1400        language_name: LanguageName::new("Python"),
1401        as_json: serde_json::to_value(data).ok()?,
1402    })
1403}
1404
1405async fn resolve_venv_activation_scripts(
1406    venv: &PythonEnvironment,
1407    fs: &dyn Fs,
1408    activation_scripts: &mut HashMap<ShellKind, PathBuf>,
1409) {
1410    log::debug!("(Python) Resolving activation scripts for venv toolchain {venv:?}");
1411    if let Some(prefix) = &venv.prefix {
1412        for (shell_kind, script_name) in &[
1413            (ShellKind::Posix, "activate"),
1414            (ShellKind::Rc, "activate"),
1415            (ShellKind::Csh, "activate.csh"),
1416            (ShellKind::Tcsh, "activate.csh"),
1417            (ShellKind::Fish, "activate.fish"),
1418            (ShellKind::Nushell, "activate.nu"),
1419            (ShellKind::PowerShell, "activate.ps1"),
1420            (ShellKind::Cmd, "activate.bat"),
1421            (ShellKind::Xonsh, "activate.xsh"),
1422        ] {
1423            let path = prefix.join(BINARY_DIR).join(script_name);
1424
1425            log::debug!("Trying path: {}", path.display());
1426
1427            if fs.is_file(&path).await {
1428                activation_scripts.insert(*shell_kind, path);
1429            }
1430        }
1431    }
1432}
1433
1434pub struct EnvironmentApi<'a> {
1435    global_search_locations: Arc<Mutex<Vec<PathBuf>>>,
1436    project_env: &'a HashMap<String, String>,
1437    pet_env: pet_core::os_environment::EnvironmentApi,
1438}
1439
1440impl<'a> EnvironmentApi<'a> {
1441    pub fn from_env(project_env: &'a HashMap<String, String>) -> Self {
1442        let paths = project_env
1443            .get("PATH")
1444            .map(|p| std::env::split_paths(p).collect())
1445            .unwrap_or_default();
1446
1447        EnvironmentApi {
1448            global_search_locations: Arc::new(Mutex::new(paths)),
1449            project_env,
1450            pet_env: pet_core::os_environment::EnvironmentApi::new(),
1451        }
1452    }
1453
1454    fn user_home(&self) -> Option<PathBuf> {
1455        self.project_env
1456            .get("HOME")
1457            .or_else(|| self.project_env.get("USERPROFILE"))
1458            .map(|home| pet_fs::path::norm_case(PathBuf::from(home)))
1459            .or_else(|| self.pet_env.get_user_home())
1460    }
1461}
1462
1463impl pet_core::os_environment::Environment for EnvironmentApi<'_> {
1464    fn get_user_home(&self) -> Option<PathBuf> {
1465        self.user_home()
1466    }
1467
1468    fn get_root(&self) -> Option<PathBuf> {
1469        None
1470    }
1471
1472    fn get_env_var(&self, key: String) -> Option<String> {
1473        self.project_env
1474            .get(&key)
1475            .cloned()
1476            .or_else(|| self.pet_env.get_env_var(key))
1477    }
1478
1479    fn get_know_global_search_locations(&self) -> Vec<PathBuf> {
1480        if self.global_search_locations.lock().is_empty() {
1481            let mut paths = std::env::split_paths(
1482                &self
1483                    .get_env_var("PATH".to_string())
1484                    .or_else(|| self.get_env_var("Path".to_string()))
1485                    .unwrap_or_default(),
1486            )
1487            .collect::<Vec<PathBuf>>();
1488
1489            log::trace!("Env PATH: {:?}", paths);
1490            for p in self.pet_env.get_know_global_search_locations() {
1491                if !paths.contains(&p) {
1492                    paths.push(p);
1493                }
1494            }
1495
1496            let mut paths = paths
1497                .into_iter()
1498                .filter(|p| p.exists())
1499                .collect::<Vec<PathBuf>>();
1500
1501            self.global_search_locations.lock().append(&mut paths);
1502        }
1503        self.global_search_locations.lock().clone()
1504    }
1505}
1506
1507pub(crate) struct PyLspAdapter {
1508    python_venv_base: OnceCell<Result<Arc<Path>, String>>,
1509}
1510impl PyLspAdapter {
1511    const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("pylsp");
1512    pub(crate) fn new() -> Self {
1513        Self {
1514            python_venv_base: OnceCell::new(),
1515        }
1516    }
1517    async fn ensure_venv(delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>> {
1518        let python_path = Self::find_base_python(delegate)
1519            .await
1520            .with_context(|| {
1521                let mut message = "Could not find Python installation for PyLSP".to_owned();
1522                if cfg!(windows){
1523                    message.push_str(". Install Python from the Microsoft Store, or manually from https://www.python.org/downloads/windows.")
1524                }
1525                message
1526            })?;
1527        let work_dir = delegate
1528            .language_server_download_dir(&Self::SERVER_NAME)
1529            .await
1530            .context("Could not get working directory for PyLSP")?;
1531        let mut path = PathBuf::from(work_dir.as_ref());
1532        path.push("pylsp-venv");
1533        if !path.exists() {
1534            util::command::new_smol_command(python_path)
1535                .arg("-m")
1536                .arg("venv")
1537                .arg("pylsp-venv")
1538                .current_dir(work_dir)
1539                .spawn()?
1540                .output()
1541                .await?;
1542        }
1543
1544        Ok(path.into())
1545    }
1546    // Find "baseline", user python version from which we'll create our own venv.
1547    async fn find_base_python(delegate: &dyn LspAdapterDelegate) -> Option<PathBuf> {
1548        for path in ["python3", "python"] {
1549            let Some(path) = delegate.which(path.as_ref()).await else {
1550                continue;
1551            };
1552            // Try to detect situations where `python3` exists but is not a real Python interpreter.
1553            // Notably, on fresh Windows installs, `python3` is a shim that opens the Microsoft Store app
1554            // when run with no arguments, and just fails otherwise.
1555            let Some(output) = new_smol_command(&path)
1556                .args(["-c", "print(1 + 2)"])
1557                .output()
1558                .await
1559                .ok()
1560            else {
1561                continue;
1562            };
1563            if output.stdout.trim_ascii() != b"3" {
1564                continue;
1565            }
1566            return Some(path);
1567        }
1568        None
1569    }
1570
1571    async fn base_venv(&self, delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>, String> {
1572        self.python_venv_base
1573            .get_or_init(move || async move {
1574                Self::ensure_venv(delegate)
1575                    .await
1576                    .map_err(|e| format!("{e}"))
1577            })
1578            .await
1579            .clone()
1580    }
1581}
1582
1583const BINARY_DIR: &str = if cfg!(target_os = "windows") {
1584    "Scripts"
1585} else {
1586    "bin"
1587};
1588
1589#[async_trait(?Send)]
1590impl LspAdapter for PyLspAdapter {
1591    fn name(&self) -> LanguageServerName {
1592        Self::SERVER_NAME
1593    }
1594
1595    async fn process_completions(&self, _items: &mut [lsp::CompletionItem]) {}
1596
1597    async fn label_for_completion(
1598        &self,
1599        item: &lsp::CompletionItem,
1600        language: &Arc<language::Language>,
1601    ) -> Option<language::CodeLabel> {
1602        let label = &item.label;
1603        let label_len = label.len();
1604        let grammar = language.grammar()?;
1605        let highlight_id = match item.kind? {
1606            lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method")?,
1607            lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function")?,
1608            lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type")?,
1609            lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant")?,
1610            _ => return None,
1611        };
1612        Some(language::CodeLabel::filtered(
1613            label.clone(),
1614            label_len,
1615            item.filter_text.as_deref(),
1616            vec![(0..label.len(), highlight_id)],
1617        ))
1618    }
1619
1620    async fn label_for_symbol(
1621        &self,
1622        name: &str,
1623        kind: lsp::SymbolKind,
1624        language: &Arc<language::Language>,
1625    ) -> Option<language::CodeLabel> {
1626        let (text, filter_range, display_range) = match kind {
1627            lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
1628                let text = format!("def {}():\n", name);
1629                let filter_range = 4..4 + name.len();
1630                let display_range = 0..filter_range.end;
1631                (text, filter_range, display_range)
1632            }
1633            lsp::SymbolKind::CLASS => {
1634                let text = format!("class {}:", name);
1635                let filter_range = 6..6 + name.len();
1636                let display_range = 0..filter_range.end;
1637                (text, filter_range, display_range)
1638            }
1639            lsp::SymbolKind::CONSTANT => {
1640                let text = format!("{} = 0", name);
1641                let filter_range = 0..name.len();
1642                let display_range = 0..filter_range.end;
1643                (text, filter_range, display_range)
1644            }
1645            _ => return None,
1646        };
1647        Some(language::CodeLabel::new(
1648            text[display_range.clone()].to_string(),
1649            filter_range,
1650            language.highlight_text(&text.as_str().into(), display_range),
1651        ))
1652    }
1653
1654    async fn workspace_configuration(
1655        self: Arc<Self>,
1656        adapter: &Arc<dyn LspAdapterDelegate>,
1657        toolchain: Option<Toolchain>,
1658        _: Option<Uri>,
1659        cx: &mut AsyncApp,
1660    ) -> Result<Value> {
1661        cx.update(move |cx| {
1662            let mut user_settings =
1663                language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
1664                    .and_then(|s| s.settings.clone())
1665                    .unwrap_or_else(|| {
1666                        json!({
1667                            "plugins": {
1668                                "pycodestyle": {"enabled": false},
1669                                "rope_autoimport": {"enabled": true, "memory": true},
1670                                "pylsp_mypy": {"enabled": false}
1671                            },
1672                            "rope": {
1673                                "ropeFolder": null
1674                            },
1675                        })
1676                    });
1677
1678            // If user did not explicitly modify their python venv, use one from picker.
1679            if let Some(toolchain) = toolchain {
1680                if !user_settings.is_object() {
1681                    user_settings = Value::Object(serde_json::Map::default());
1682                }
1683                let object = user_settings.as_object_mut().unwrap();
1684                if let Some(python) = object
1685                    .entry("plugins")
1686                    .or_insert(Value::Object(serde_json::Map::default()))
1687                    .as_object_mut()
1688                {
1689                    if let Some(jedi) = python
1690                        .entry("jedi")
1691                        .or_insert(Value::Object(serde_json::Map::default()))
1692                        .as_object_mut()
1693                    {
1694                        jedi.entry("environment".to_string())
1695                            .or_insert_with(|| Value::String(toolchain.path.clone().into()));
1696                    }
1697                    if let Some(pylint) = python
1698                        .entry("pylsp_mypy")
1699                        .or_insert(Value::Object(serde_json::Map::default()))
1700                        .as_object_mut()
1701                    {
1702                        pylint.entry("overrides".to_string()).or_insert_with(|| {
1703                            Value::Array(vec![
1704                                Value::String("--python-executable".into()),
1705                                Value::String(toolchain.path.into()),
1706                                Value::String("--cache-dir=/dev/null".into()),
1707                                Value::Bool(true),
1708                            ])
1709                        });
1710                    }
1711                }
1712            }
1713            user_settings = Value::Object(serde_json::Map::from_iter([(
1714                "pylsp".to_string(),
1715                user_settings,
1716            )]));
1717
1718            user_settings
1719        })
1720    }
1721}
1722
1723impl LspInstaller for PyLspAdapter {
1724    type BinaryVersion = ();
1725    async fn check_if_user_installed(
1726        &self,
1727        delegate: &dyn LspAdapterDelegate,
1728        toolchain: Option<Toolchain>,
1729        _: &AsyncApp,
1730    ) -> Option<LanguageServerBinary> {
1731        if let Some(pylsp_bin) = delegate.which(Self::SERVER_NAME.as_ref()).await {
1732            let env = delegate.shell_env().await;
1733            Some(LanguageServerBinary {
1734                path: pylsp_bin,
1735                env: Some(env),
1736                arguments: vec![],
1737            })
1738        } else {
1739            let toolchain = toolchain?;
1740            let pylsp_path = Path::new(toolchain.path.as_ref()).parent()?.join("pylsp");
1741            pylsp_path.exists().then(|| LanguageServerBinary {
1742                path: toolchain.path.to_string().into(),
1743                arguments: vec![pylsp_path.into()],
1744                env: None,
1745            })
1746        }
1747    }
1748
1749    async fn fetch_latest_server_version(
1750        &self,
1751        _: &dyn LspAdapterDelegate,
1752        _: bool,
1753        _: &mut AsyncApp,
1754    ) -> Result<()> {
1755        Ok(())
1756    }
1757
1758    async fn fetch_server_binary(
1759        &self,
1760        _: (),
1761        _: PathBuf,
1762        delegate: &dyn LspAdapterDelegate,
1763    ) -> Result<LanguageServerBinary> {
1764        let venv = self.base_venv(delegate).await.map_err(|e| anyhow!(e))?;
1765        let pip_path = venv.join(BINARY_DIR).join("pip3");
1766        ensure!(
1767            util::command::new_smol_command(pip_path.as_path())
1768                .arg("install")
1769                .arg("python-lsp-server[all]")
1770                .arg("--upgrade")
1771                .output()
1772                .await?
1773                .status
1774                .success(),
1775            "python-lsp-server[all] installation failed"
1776        );
1777        ensure!(
1778            util::command::new_smol_command(pip_path)
1779                .arg("install")
1780                .arg("pylsp-mypy")
1781                .arg("--upgrade")
1782                .output()
1783                .await?
1784                .status
1785                .success(),
1786            "pylsp-mypy installation failed"
1787        );
1788        let pylsp = venv.join(BINARY_DIR).join("pylsp");
1789        ensure!(
1790            delegate.which(pylsp.as_os_str()).await.is_some(),
1791            "pylsp installation was incomplete"
1792        );
1793        Ok(LanguageServerBinary {
1794            path: pylsp,
1795            env: None,
1796            arguments: vec![],
1797        })
1798    }
1799
1800    async fn cached_server_binary(
1801        &self,
1802        _: PathBuf,
1803        delegate: &dyn LspAdapterDelegate,
1804    ) -> Option<LanguageServerBinary> {
1805        let venv = self.base_venv(delegate).await.ok()?;
1806        let pylsp = venv.join(BINARY_DIR).join("pylsp");
1807        delegate.which(pylsp.as_os_str()).await?;
1808        Some(LanguageServerBinary {
1809            path: pylsp,
1810            env: None,
1811            arguments: vec![],
1812        })
1813    }
1814}
1815
1816pub(crate) struct BasedPyrightLspAdapter {
1817    node: NodeRuntime,
1818}
1819
1820impl BasedPyrightLspAdapter {
1821    const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("basedpyright");
1822    const BINARY_NAME: &'static str = "basedpyright-langserver";
1823    const SERVER_PATH: &str = "node_modules/basedpyright/langserver.index.js";
1824    const NODE_MODULE_RELATIVE_SERVER_PATH: &str = "basedpyright/langserver.index.js";
1825
1826    pub(crate) fn new(node: NodeRuntime) -> Self {
1827        BasedPyrightLspAdapter { node }
1828    }
1829
1830    async fn get_cached_server_binary(
1831        container_dir: PathBuf,
1832        node: &NodeRuntime,
1833    ) -> Option<LanguageServerBinary> {
1834        let server_path = container_dir.join(Self::SERVER_PATH);
1835        if server_path.exists() {
1836            Some(LanguageServerBinary {
1837                path: node.binary_path().await.log_err()?,
1838                env: None,
1839                arguments: vec![server_path.into(), "--stdio".into()],
1840            })
1841        } else {
1842            log::error!("missing executable in directory {:?}", server_path);
1843            None
1844        }
1845    }
1846}
1847
1848#[async_trait(?Send)]
1849impl LspAdapter for BasedPyrightLspAdapter {
1850    fn name(&self) -> LanguageServerName {
1851        Self::SERVER_NAME
1852    }
1853
1854    async fn initialization_options(
1855        self: Arc<Self>,
1856        _: &Arc<dyn LspAdapterDelegate>,
1857    ) -> Result<Option<Value>> {
1858        // Provide minimal initialization options
1859        // Virtual environment configuration will be handled through workspace configuration
1860        Ok(Some(json!({
1861            "python": {
1862                "analysis": {
1863                    "autoSearchPaths": true,
1864                    "useLibraryCodeForTypes": true,
1865                    "autoImportCompletions": true
1866                }
1867            }
1868        })))
1869    }
1870
1871    async fn process_completions(&self, items: &mut [lsp::CompletionItem]) {
1872        process_pyright_completions(items);
1873    }
1874
1875    async fn label_for_completion(
1876        &self,
1877        item: &lsp::CompletionItem,
1878        language: &Arc<language::Language>,
1879    ) -> Option<language::CodeLabel> {
1880        let label = &item.label;
1881        let label_len = label.len();
1882        let grammar = language.grammar()?;
1883        let highlight_id = match item.kind? {
1884            lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method"),
1885            lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function"),
1886            lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type"),
1887            lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant"),
1888            lsp::CompletionItemKind::VARIABLE => grammar.highlight_id_for_name("variable"),
1889            _ => {
1890                return None;
1891            }
1892        };
1893        let mut text = label.clone();
1894        if let Some(completion_details) = item
1895            .label_details
1896            .as_ref()
1897            .and_then(|details| details.description.as_ref())
1898        {
1899            write!(&mut text, " {}", completion_details).ok();
1900        }
1901        Some(language::CodeLabel::filtered(
1902            text,
1903            label_len,
1904            item.filter_text.as_deref(),
1905            highlight_id
1906                .map(|id| (0..label.len(), id))
1907                .into_iter()
1908                .collect(),
1909        ))
1910    }
1911
1912    async fn label_for_symbol(
1913        &self,
1914        name: &str,
1915        kind: lsp::SymbolKind,
1916        language: &Arc<language::Language>,
1917    ) -> Option<language::CodeLabel> {
1918        let (text, filter_range, display_range) = match kind {
1919            lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
1920                let text = format!("def {}():\n", name);
1921                let filter_range = 4..4 + name.len();
1922                let display_range = 0..filter_range.end;
1923                (text, filter_range, display_range)
1924            }
1925            lsp::SymbolKind::CLASS => {
1926                let text = format!("class {}:", name);
1927                let filter_range = 6..6 + name.len();
1928                let display_range = 0..filter_range.end;
1929                (text, filter_range, display_range)
1930            }
1931            lsp::SymbolKind::CONSTANT => {
1932                let text = format!("{} = 0", name);
1933                let filter_range = 0..name.len();
1934                let display_range = 0..filter_range.end;
1935                (text, filter_range, display_range)
1936            }
1937            _ => return None,
1938        };
1939        Some(language::CodeLabel::new(
1940            text[display_range.clone()].to_string(),
1941            filter_range,
1942            language.highlight_text(&text.as_str().into(), display_range),
1943        ))
1944    }
1945
1946    async fn workspace_configuration(
1947        self: Arc<Self>,
1948        adapter: &Arc<dyn LspAdapterDelegate>,
1949        toolchain: Option<Toolchain>,
1950        _: Option<Uri>,
1951        cx: &mut AsyncApp,
1952    ) -> Result<Value> {
1953        cx.update(move |cx| {
1954            let mut user_settings =
1955                language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
1956                    .and_then(|s| s.settings.clone())
1957                    .unwrap_or_default();
1958
1959            // If we have a detected toolchain, configure Pyright to use it
1960            if let Some(toolchain) = toolchain
1961                && let Ok(env) = serde_json::from_value::<
1962                    pet_core::python_environment::PythonEnvironment,
1963                >(toolchain.as_json.clone())
1964            {
1965                if !user_settings.is_object() {
1966                    user_settings = Value::Object(serde_json::Map::default());
1967                }
1968                let object = user_settings.as_object_mut().unwrap();
1969
1970                let interpreter_path = toolchain.path.to_string();
1971                if let Some(venv_dir) = env.prefix {
1972                    // Set venvPath and venv at the root level
1973                    // This matches the format of a pyrightconfig.json file
1974                    if let Some(parent) = venv_dir.parent() {
1975                        // Use relative path if the venv is inside the workspace
1976                        let venv_path = if parent == adapter.worktree_root_path() {
1977                            ".".to_string()
1978                        } else {
1979                            parent.to_string_lossy().into_owned()
1980                        };
1981                        object.insert("venvPath".to_string(), Value::String(venv_path));
1982                    }
1983
1984                    if let Some(venv_name) = venv_dir.file_name() {
1985                        object.insert(
1986                            "venv".to_owned(),
1987                            Value::String(venv_name.to_string_lossy().into_owned()),
1988                        );
1989                    }
1990                }
1991
1992                // Set both pythonPath and defaultInterpreterPath for compatibility
1993                if let Some(python) = object
1994                    .entry("python")
1995                    .or_insert(Value::Object(serde_json::Map::default()))
1996                    .as_object_mut()
1997                {
1998                    python.insert(
1999                        "pythonPath".to_owned(),
2000                        Value::String(interpreter_path.clone()),
2001                    );
2002                    python.insert(
2003                        "defaultInterpreterPath".to_owned(),
2004                        Value::String(interpreter_path),
2005                    );
2006                }
2007                // Basedpyright by default uses `strict` type checking, we tone it down as to not surpris users
2008                maybe!({
2009                    let analysis = object
2010                        .entry("basedpyright.analysis")
2011                        .or_insert(Value::Object(serde_json::Map::default()));
2012                    if let serde_json::map::Entry::Vacant(v) =
2013                        analysis.as_object_mut()?.entry("typeCheckingMode")
2014                    {
2015                        v.insert(Value::String("standard".to_owned()));
2016                    }
2017                    Some(())
2018                });
2019            }
2020
2021            user_settings
2022        })
2023    }
2024}
2025
2026impl LspInstaller for BasedPyrightLspAdapter {
2027    type BinaryVersion = String;
2028
2029    async fn fetch_latest_server_version(
2030        &self,
2031        _: &dyn LspAdapterDelegate,
2032        _: bool,
2033        _: &mut AsyncApp,
2034    ) -> Result<String> {
2035        self.node
2036            .npm_package_latest_version(Self::SERVER_NAME.as_ref())
2037            .await
2038    }
2039
2040    async fn check_if_user_installed(
2041        &self,
2042        delegate: &dyn LspAdapterDelegate,
2043        _: Option<Toolchain>,
2044        _: &AsyncApp,
2045    ) -> Option<LanguageServerBinary> {
2046        if let Some(path) = delegate.which(Self::BINARY_NAME.as_ref()).await {
2047            let env = delegate.shell_env().await;
2048            Some(LanguageServerBinary {
2049                path,
2050                env: Some(env),
2051                arguments: vec!["--stdio".into()],
2052            })
2053        } else {
2054            // TODO shouldn't this be self.node.binary_path()?
2055            let node = delegate.which("node".as_ref()).await?;
2056            let (node_modules_path, _) = delegate
2057                .npm_package_installed_version(Self::SERVER_NAME.as_ref())
2058                .await
2059                .log_err()??;
2060
2061            let path = node_modules_path.join(Self::NODE_MODULE_RELATIVE_SERVER_PATH);
2062
2063            let env = delegate.shell_env().await;
2064            Some(LanguageServerBinary {
2065                path: node,
2066                env: Some(env),
2067                arguments: vec![path.into(), "--stdio".into()],
2068            })
2069        }
2070    }
2071
2072    async fn fetch_server_binary(
2073        &self,
2074        latest_version: Self::BinaryVersion,
2075        container_dir: PathBuf,
2076        delegate: &dyn LspAdapterDelegate,
2077    ) -> Result<LanguageServerBinary> {
2078        let server_path = container_dir.join(Self::SERVER_PATH);
2079
2080        self.node
2081            .npm_install_packages(
2082                &container_dir,
2083                &[(Self::SERVER_NAME.as_ref(), latest_version.as_str())],
2084            )
2085            .await?;
2086
2087        let env = delegate.shell_env().await;
2088        Ok(LanguageServerBinary {
2089            path: self.node.binary_path().await?,
2090            env: Some(env),
2091            arguments: vec![server_path.into(), "--stdio".into()],
2092        })
2093    }
2094
2095    async fn check_if_version_installed(
2096        &self,
2097        version: &Self::BinaryVersion,
2098        container_dir: &PathBuf,
2099        delegate: &dyn LspAdapterDelegate,
2100    ) -> Option<LanguageServerBinary> {
2101        let server_path = container_dir.join(Self::SERVER_PATH);
2102
2103        let should_install_language_server = self
2104            .node
2105            .should_install_npm_package(
2106                Self::SERVER_NAME.as_ref(),
2107                &server_path,
2108                container_dir,
2109                VersionStrategy::Latest(version),
2110            )
2111            .await;
2112
2113        if should_install_language_server {
2114            None
2115        } else {
2116            let env = delegate.shell_env().await;
2117            Some(LanguageServerBinary {
2118                path: self.node.binary_path().await.ok()?,
2119                env: Some(env),
2120                arguments: vec![server_path.into(), "--stdio".into()],
2121            })
2122        }
2123    }
2124
2125    async fn cached_server_binary(
2126        &self,
2127        container_dir: PathBuf,
2128        delegate: &dyn LspAdapterDelegate,
2129    ) -> Option<LanguageServerBinary> {
2130        let mut binary = Self::get_cached_server_binary(container_dir, &self.node).await?;
2131        binary.env = Some(delegate.shell_env().await);
2132        Some(binary)
2133    }
2134}
2135
2136pub(crate) struct RuffLspAdapter {
2137    fs: Arc<dyn Fs>,
2138}
2139
2140#[cfg(target_os = "macos")]
2141impl RuffLspAdapter {
2142    const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
2143    const ARCH_SERVER_NAME: &str = "apple-darwin";
2144}
2145
2146#[cfg(target_os = "linux")]
2147impl RuffLspAdapter {
2148    const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
2149    const ARCH_SERVER_NAME: &str = "unknown-linux-gnu";
2150}
2151
2152#[cfg(target_os = "freebsd")]
2153impl RuffLspAdapter {
2154    const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
2155    const ARCH_SERVER_NAME: &str = "unknown-freebsd";
2156}
2157
2158#[cfg(target_os = "windows")]
2159impl RuffLspAdapter {
2160    const GITHUB_ASSET_KIND: AssetKind = AssetKind::Zip;
2161    const ARCH_SERVER_NAME: &str = "pc-windows-msvc";
2162}
2163
2164impl RuffLspAdapter {
2165    const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("ruff");
2166
2167    pub fn new(fs: Arc<dyn Fs>) -> RuffLspAdapter {
2168        RuffLspAdapter { fs }
2169    }
2170
2171    fn build_asset_name() -> Result<(String, String)> {
2172        let arch = match consts::ARCH {
2173            "x86" => "i686",
2174            _ => consts::ARCH,
2175        };
2176        let os = Self::ARCH_SERVER_NAME;
2177        let suffix = match consts::OS {
2178            "windows" => "zip",
2179            _ => "tar.gz",
2180        };
2181        let asset_name = format!("ruff-{arch}-{os}.{suffix}");
2182        let asset_stem = format!("ruff-{arch}-{os}");
2183        Ok((asset_stem, asset_name))
2184    }
2185}
2186
2187#[async_trait(?Send)]
2188impl LspAdapter for RuffLspAdapter {
2189    fn name(&self) -> LanguageServerName {
2190        Self::SERVER_NAME
2191    }
2192}
2193
2194impl LspInstaller for RuffLspAdapter {
2195    type BinaryVersion = GitHubLspBinaryVersion;
2196    async fn check_if_user_installed(
2197        &self,
2198        delegate: &dyn LspAdapterDelegate,
2199        toolchain: Option<Toolchain>,
2200        _: &AsyncApp,
2201    ) -> Option<LanguageServerBinary> {
2202        let ruff_in_venv = if let Some(toolchain) = toolchain
2203            && toolchain.language_name.as_ref() == "Python"
2204        {
2205            Path::new(toolchain.path.as_str())
2206                .parent()
2207                .map(|path| path.join("ruff"))
2208        } else {
2209            None
2210        };
2211
2212        for path in ruff_in_venv.into_iter().chain(["ruff".into()]) {
2213            if let Some(ruff_bin) = delegate.which(path.as_os_str()).await {
2214                let env = delegate.shell_env().await;
2215                return Some(LanguageServerBinary {
2216                    path: ruff_bin,
2217                    env: Some(env),
2218                    arguments: vec!["server".into()],
2219                });
2220            }
2221        }
2222
2223        None
2224    }
2225
2226    async fn fetch_latest_server_version(
2227        &self,
2228        delegate: &dyn LspAdapterDelegate,
2229        _: bool,
2230        _: &mut AsyncApp,
2231    ) -> Result<GitHubLspBinaryVersion> {
2232        let release =
2233            latest_github_release("astral-sh/ruff", true, false, delegate.http_client()).await?;
2234        let (_, asset_name) = Self::build_asset_name()?;
2235        let asset = release
2236            .assets
2237            .into_iter()
2238            .find(|asset| asset.name == asset_name)
2239            .with_context(|| format!("no asset found matching `{asset_name:?}`"))?;
2240        Ok(GitHubLspBinaryVersion {
2241            name: release.tag_name,
2242            url: asset.browser_download_url,
2243            digest: asset.digest,
2244        })
2245    }
2246
2247    async fn fetch_server_binary(
2248        &self,
2249        latest_version: GitHubLspBinaryVersion,
2250        container_dir: PathBuf,
2251        delegate: &dyn LspAdapterDelegate,
2252    ) -> Result<LanguageServerBinary> {
2253        let GitHubLspBinaryVersion {
2254            name,
2255            url,
2256            digest: expected_digest,
2257        } = latest_version;
2258        let destination_path = container_dir.join(format!("ruff-{name}"));
2259        let server_path = match Self::GITHUB_ASSET_KIND {
2260            AssetKind::TarGz | AssetKind::Gz => destination_path
2261                .join(Self::build_asset_name()?.0)
2262                .join("ruff"),
2263            AssetKind::Zip => destination_path.clone().join("ruff.exe"),
2264        };
2265
2266        let binary = LanguageServerBinary {
2267            path: server_path.clone(),
2268            env: None,
2269            arguments: vec!["server".into()],
2270        };
2271
2272        let metadata_path = destination_path.with_extension("metadata");
2273        let metadata = GithubBinaryMetadata::read_from_file(&metadata_path)
2274            .await
2275            .ok();
2276        if let Some(metadata) = metadata {
2277            let validity_check = async || {
2278                delegate
2279                    .try_exec(LanguageServerBinary {
2280                        path: server_path.clone(),
2281                        arguments: vec!["--version".into()],
2282                        env: None,
2283                    })
2284                    .await
2285                    .inspect_err(|err| {
2286                        log::warn!("Unable to run {server_path:?} asset, redownloading: {err:#}",)
2287                    })
2288            };
2289            if let (Some(actual_digest), Some(expected_digest)) =
2290                (&metadata.digest, &expected_digest)
2291            {
2292                if actual_digest == expected_digest {
2293                    if validity_check().await.is_ok() {
2294                        return Ok(binary);
2295                    }
2296                } else {
2297                    log::info!(
2298                        "SHA-256 mismatch for {destination_path:?} asset, downloading new asset. Expected: {expected_digest}, Got: {actual_digest}"
2299                    );
2300                }
2301            } else if validity_check().await.is_ok() {
2302                return Ok(binary);
2303            }
2304        }
2305
2306        download_server_binary(
2307            &*delegate.http_client(),
2308            &url,
2309            expected_digest.as_deref(),
2310            &destination_path,
2311            Self::GITHUB_ASSET_KIND,
2312        )
2313        .await?;
2314        make_file_executable(&server_path).await?;
2315        remove_matching(&container_dir, |path| path != destination_path).await;
2316        GithubBinaryMetadata::write_to_file(
2317            &GithubBinaryMetadata {
2318                metadata_version: 1,
2319                digest: expected_digest,
2320            },
2321            &metadata_path,
2322        )
2323        .await?;
2324
2325        Ok(LanguageServerBinary {
2326            path: server_path,
2327            env: None,
2328            arguments: vec!["server".into()],
2329        })
2330    }
2331
2332    async fn cached_server_binary(
2333        &self,
2334        container_dir: PathBuf,
2335        _: &dyn LspAdapterDelegate,
2336    ) -> Option<LanguageServerBinary> {
2337        maybe!(async {
2338            let mut last = None;
2339            let mut entries = self.fs.read_dir(&container_dir).await?;
2340            while let Some(entry) = entries.next().await {
2341                let path = entry?;
2342                if path.extension().is_some_and(|ext| ext == "metadata") {
2343                    continue;
2344                }
2345                last = Some(path);
2346            }
2347
2348            let path = last.context("no cached binary")?;
2349            let path = match Self::GITHUB_ASSET_KIND {
2350                AssetKind::TarGz | AssetKind::Gz => {
2351                    path.join(Self::build_asset_name()?.0).join("ruff")
2352                }
2353                AssetKind::Zip => path.join("ruff.exe"),
2354            };
2355
2356            anyhow::Ok(LanguageServerBinary {
2357                path,
2358                env: None,
2359                arguments: vec!["server".into()],
2360            })
2361        })
2362        .await
2363        .log_err()
2364    }
2365}
2366
2367#[cfg(test)]
2368mod tests {
2369    use gpui::{AppContext as _, BorrowAppContext, Context, TestAppContext};
2370    use language::{AutoindentMode, Buffer};
2371    use settings::SettingsStore;
2372    use std::num::NonZeroU32;
2373
2374    use crate::python::python_module_name_from_relative_path;
2375
2376    #[gpui::test]
2377    async fn test_python_autoindent(cx: &mut TestAppContext) {
2378        cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
2379        let language = crate::language("python", tree_sitter_python::LANGUAGE.into());
2380        cx.update(|cx| {
2381            let test_settings = SettingsStore::test(cx);
2382            cx.set_global(test_settings);
2383            cx.update_global::<SettingsStore, _>(|store, cx| {
2384                store.update_user_settings(cx, |s| {
2385                    s.project.all_languages.defaults.tab_size = NonZeroU32::new(2);
2386                });
2387            });
2388        });
2389
2390        cx.new(|cx| {
2391            let mut buffer = Buffer::local("", cx).with_language(language, cx);
2392            let append = |buffer: &mut Buffer, text: &str, cx: &mut Context<Buffer>| {
2393                let ix = buffer.len();
2394                buffer.edit([(ix..ix, text)], Some(AutoindentMode::EachLine), cx);
2395            };
2396
2397            // indent after "def():"
2398            append(&mut buffer, "def a():\n", cx);
2399            assert_eq!(buffer.text(), "def a():\n  ");
2400
2401            // preserve indent after blank line
2402            append(&mut buffer, "\n  ", cx);
2403            assert_eq!(buffer.text(), "def a():\n  \n  ");
2404
2405            // indent after "if"
2406            append(&mut buffer, "if a:\n  ", cx);
2407            assert_eq!(buffer.text(), "def a():\n  \n  if a:\n    ");
2408
2409            // preserve indent after statement
2410            append(&mut buffer, "b()\n", cx);
2411            assert_eq!(buffer.text(), "def a():\n  \n  if a:\n    b()\n    ");
2412
2413            // preserve indent after statement
2414            append(&mut buffer, "else", cx);
2415            assert_eq!(buffer.text(), "def a():\n  \n  if a:\n    b()\n    else");
2416
2417            // dedent "else""
2418            append(&mut buffer, ":", cx);
2419            assert_eq!(buffer.text(), "def a():\n  \n  if a:\n    b()\n  else:");
2420
2421            // indent lines after else
2422            append(&mut buffer, "\n", cx);
2423            assert_eq!(
2424                buffer.text(),
2425                "def a():\n  \n  if a:\n    b()\n  else:\n    "
2426            );
2427
2428            // indent after an open paren. the closing paren is not indented
2429            // because there is another token before it on the same line.
2430            append(&mut buffer, "foo(\n1)", cx);
2431            assert_eq!(
2432                buffer.text(),
2433                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n      1)"
2434            );
2435
2436            // dedent the closing paren if it is shifted to the beginning of the line
2437            let argument_ix = buffer.text().find('1').unwrap();
2438            buffer.edit(
2439                [(argument_ix..argument_ix + 1, "")],
2440                Some(AutoindentMode::EachLine),
2441                cx,
2442            );
2443            assert_eq!(
2444                buffer.text(),
2445                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n    )"
2446            );
2447
2448            // preserve indent after the close paren
2449            append(&mut buffer, "\n", cx);
2450            assert_eq!(
2451                buffer.text(),
2452                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n    )\n    "
2453            );
2454
2455            // manually outdent the last line
2456            let end_whitespace_ix = buffer.len() - 4;
2457            buffer.edit(
2458                [(end_whitespace_ix..buffer.len(), "")],
2459                Some(AutoindentMode::EachLine),
2460                cx,
2461            );
2462            assert_eq!(
2463                buffer.text(),
2464                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n    )\n"
2465            );
2466
2467            // preserve the newly reduced indentation on the next newline
2468            append(&mut buffer, "\n", cx);
2469            assert_eq!(
2470                buffer.text(),
2471                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n    )\n\n"
2472            );
2473
2474            // reset to a for loop statement
2475            let statement = "for i in range(10):\n  print(i)\n";
2476            buffer.edit([(0..buffer.len(), statement)], None, cx);
2477
2478            // insert single line comment after each line
2479            let eol_ixs = statement
2480                .char_indices()
2481                .filter_map(|(ix, c)| if c == '\n' { Some(ix) } else { None })
2482                .collect::<Vec<usize>>();
2483            let editions = eol_ixs
2484                .iter()
2485                .enumerate()
2486                .map(|(i, &eol_ix)| (eol_ix..eol_ix, format!(" # comment {}", i + 1)))
2487                .collect::<Vec<(std::ops::Range<usize>, String)>>();
2488            buffer.edit(editions, Some(AutoindentMode::EachLine), cx);
2489            assert_eq!(
2490                buffer.text(),
2491                "for i in range(10): # comment 1\n  print(i) # comment 2\n"
2492            );
2493
2494            // reset to a simple if statement
2495            buffer.edit([(0..buffer.len(), "if a:\n  b(\n  )")], None, cx);
2496
2497            // dedent "else" on the line after a closing paren
2498            append(&mut buffer, "\n  else:\n", cx);
2499            assert_eq!(buffer.text(), "if a:\n  b(\n  )\nelse:\n  ");
2500
2501            buffer
2502        });
2503    }
2504
2505    #[test]
2506    fn test_python_module_name_from_relative_path() {
2507        assert_eq!(
2508            python_module_name_from_relative_path("foo/bar.py"),
2509            Some("foo.bar".to_string())
2510        );
2511        assert_eq!(
2512            python_module_name_from_relative_path("foo/bar"),
2513            Some("foo.bar".to_string())
2514        );
2515        if cfg!(windows) {
2516            assert_eq!(
2517                python_module_name_from_relative_path("foo\\bar.py"),
2518                Some("foo.bar".to_string())
2519            );
2520            assert_eq!(
2521                python_module_name_from_relative_path("foo\\bar"),
2522                Some("foo.bar".to_string())
2523            );
2524        } else {
2525            assert_eq!(
2526                python_module_name_from_relative_path("foo\\bar.py"),
2527                Some("foo\\bar".to_string())
2528            );
2529            assert_eq!(
2530                python_module_name_from_relative_path("foo\\bar"),
2531                Some("foo\\bar".to_string())
2532            );
2533        }
2534    }
2535}