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