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("--upgrade")
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("--upgrade")
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("--upgrade")
1585                .output()
1586                .await?
1587                .status
1588                .success(),
1589            "pylsp-mypy installation failed"
1590        );
1591        let pylsp = venv.join(BINARY_DIR).join("pylsp");
1592        ensure!(
1593            delegate.which(pylsp.as_os_str()).await.is_some(),
1594            "pylsp installation was incomplete"
1595        );
1596        Ok(LanguageServerBinary {
1597            path: pylsp,
1598            env: None,
1599            arguments: vec![],
1600        })
1601    }
1602
1603    async fn cached_server_binary(
1604        &self,
1605        _: PathBuf,
1606        delegate: &dyn LspAdapterDelegate,
1607    ) -> Option<LanguageServerBinary> {
1608        let venv = self.base_venv(delegate).await.ok()?;
1609        let pylsp = venv.join(BINARY_DIR).join("pylsp");
1610        delegate.which(pylsp.as_os_str()).await?;
1611        Some(LanguageServerBinary {
1612            path: pylsp,
1613            env: None,
1614            arguments: vec![],
1615        })
1616    }
1617}
1618
1619pub(crate) struct BasedPyrightLspAdapter {
1620    python_venv_base: OnceCell<Result<Arc<Path>, String>>,
1621}
1622
1623impl BasedPyrightLspAdapter {
1624    const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("basedpyright");
1625    const BINARY_NAME: &'static str = "basedpyright-langserver";
1626
1627    pub(crate) fn new() -> Self {
1628        Self {
1629            python_venv_base: OnceCell::new(),
1630        }
1631    }
1632
1633    async fn ensure_venv(delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>> {
1634        let python_path = Self::find_base_python(delegate)
1635            .await
1636            .context("Could not find Python installation for basedpyright")?;
1637        let work_dir = delegate
1638            .language_server_download_dir(&Self::SERVER_NAME)
1639            .await
1640            .context("Could not get working directory for basedpyright")?;
1641        let mut path = PathBuf::from(work_dir.as_ref());
1642        path.push("basedpyright-venv");
1643        if !path.exists() {
1644            util::command::new_smol_command(python_path)
1645                .arg("-m")
1646                .arg("venv")
1647                .arg("basedpyright-venv")
1648                .current_dir(work_dir)
1649                .spawn()
1650                .context("spawning child")?
1651                .output()
1652                .await
1653                .context("getting child output")?;
1654        }
1655
1656        Ok(path.into())
1657    }
1658
1659    // Find "baseline", user python version from which we'll create our own venv.
1660    async fn find_base_python(delegate: &dyn LspAdapterDelegate) -> Option<PathBuf> {
1661        for path in ["python3", "python"] {
1662            if let Some(path) = delegate.which(path.as_ref()).await {
1663                return Some(path);
1664            }
1665        }
1666        None
1667    }
1668
1669    async fn base_venv(&self, delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>, String> {
1670        self.python_venv_base
1671            .get_or_init(move || async move {
1672                Self::ensure_venv(delegate)
1673                    .await
1674                    .map_err(|e| format!("{e}"))
1675            })
1676            .await
1677            .clone()
1678    }
1679}
1680
1681#[async_trait(?Send)]
1682impl LspAdapter for BasedPyrightLspAdapter {
1683    fn name(&self) -> LanguageServerName {
1684        Self::SERVER_NAME
1685    }
1686
1687    async fn initialization_options(
1688        self: Arc<Self>,
1689        _: &Arc<dyn LspAdapterDelegate>,
1690    ) -> Result<Option<Value>> {
1691        // Provide minimal initialization options
1692        // Virtual environment configuration will be handled through workspace configuration
1693        Ok(Some(json!({
1694            "python": {
1695                "analysis": {
1696                    "autoSearchPaths": true,
1697                    "useLibraryCodeForTypes": true,
1698                    "autoImportCompletions": true
1699                }
1700            }
1701        })))
1702    }
1703
1704    async fn process_completions(&self, items: &mut [lsp::CompletionItem]) {
1705        process_pyright_completions(items);
1706    }
1707
1708    async fn label_for_completion(
1709        &self,
1710        item: &lsp::CompletionItem,
1711        language: &Arc<language::Language>,
1712    ) -> Option<language::CodeLabel> {
1713        let label = &item.label;
1714        let grammar = language.grammar()?;
1715        let highlight_id = match item.kind? {
1716            lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method"),
1717            lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function"),
1718            lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type"),
1719            lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant"),
1720            lsp::CompletionItemKind::VARIABLE => grammar.highlight_id_for_name("variable"),
1721            _ => {
1722                return None;
1723            }
1724        };
1725        let filter_range = item
1726            .filter_text
1727            .as_deref()
1728            .and_then(|filter| label.find(filter).map(|ix| ix..ix + filter.len()))
1729            .unwrap_or(0..label.len());
1730        let mut text = label.clone();
1731        if let Some(completion_details) = item
1732            .label_details
1733            .as_ref()
1734            .and_then(|details| details.description.as_ref())
1735        {
1736            write!(&mut text, " {}", completion_details).ok();
1737        }
1738        Some(language::CodeLabel {
1739            runs: highlight_id
1740                .map(|id| (0..label.len(), id))
1741                .into_iter()
1742                .collect(),
1743            text,
1744            filter_range,
1745        })
1746    }
1747
1748    async fn label_for_symbol(
1749        &self,
1750        name: &str,
1751        kind: lsp::SymbolKind,
1752        language: &Arc<language::Language>,
1753    ) -> Option<language::CodeLabel> {
1754        let (text, filter_range, display_range) = match kind {
1755            lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
1756                let text = format!("def {}():\n", name);
1757                let filter_range = 4..4 + name.len();
1758                let display_range = 0..filter_range.end;
1759                (text, filter_range, display_range)
1760            }
1761            lsp::SymbolKind::CLASS => {
1762                let text = format!("class {}:", name);
1763                let filter_range = 6..6 + name.len();
1764                let display_range = 0..filter_range.end;
1765                (text, filter_range, display_range)
1766            }
1767            lsp::SymbolKind::CONSTANT => {
1768                let text = format!("{} = 0", name);
1769                let filter_range = 0..name.len();
1770                let display_range = 0..filter_range.end;
1771                (text, filter_range, display_range)
1772            }
1773            _ => return None,
1774        };
1775
1776        Some(language::CodeLabel {
1777            runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
1778            text: text[display_range].to_string(),
1779            filter_range,
1780        })
1781    }
1782
1783    async fn workspace_configuration(
1784        self: Arc<Self>,
1785        adapter: &Arc<dyn LspAdapterDelegate>,
1786        toolchain: Option<Toolchain>,
1787        cx: &mut AsyncApp,
1788    ) -> Result<Value> {
1789        cx.update(move |cx| {
1790            let mut user_settings =
1791                language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
1792                    .and_then(|s| s.settings.clone())
1793                    .unwrap_or_default();
1794
1795            // If we have a detected toolchain, configure Pyright to use it
1796            if let Some(toolchain) = toolchain
1797                && let Ok(env) = serde_json::from_value::<
1798                    pet_core::python_environment::PythonEnvironment,
1799                >(toolchain.as_json.clone())
1800            {
1801                if !user_settings.is_object() {
1802                    user_settings = Value::Object(serde_json::Map::default());
1803                }
1804                let object = user_settings.as_object_mut().unwrap();
1805
1806                let interpreter_path = toolchain.path.to_string();
1807                if let Some(venv_dir) = env.prefix {
1808                    // Set venvPath and venv at the root level
1809                    // This matches the format of a pyrightconfig.json file
1810                    if let Some(parent) = venv_dir.parent() {
1811                        // Use relative path if the venv is inside the workspace
1812                        let venv_path = if parent == adapter.worktree_root_path() {
1813                            ".".to_string()
1814                        } else {
1815                            parent.to_string_lossy().into_owned()
1816                        };
1817                        object.insert("venvPath".to_string(), Value::String(venv_path));
1818                    }
1819
1820                    if let Some(venv_name) = venv_dir.file_name() {
1821                        object.insert(
1822                            "venv".to_owned(),
1823                            Value::String(venv_name.to_string_lossy().into_owned()),
1824                        );
1825                    }
1826                }
1827
1828                // Set both pythonPath and defaultInterpreterPath for compatibility
1829                if let Some(python) = object
1830                    .entry("python")
1831                    .or_insert(Value::Object(serde_json::Map::default()))
1832                    .as_object_mut()
1833                {
1834                    python.insert(
1835                        "pythonPath".to_owned(),
1836                        Value::String(interpreter_path.clone()),
1837                    );
1838                    python.insert(
1839                        "defaultInterpreterPath".to_owned(),
1840                        Value::String(interpreter_path),
1841                    );
1842                }
1843                // Basedpyright by default uses `strict` type checking, we tone it down as to not surpris users
1844                maybe!({
1845                    let basedpyright = object
1846                        .entry("basedpyright")
1847                        .or_insert(Value::Object(serde_json::Map::default()));
1848                    let analysis = basedpyright
1849                        .as_object_mut()?
1850                        .entry("analysis")
1851                        .or_insert(Value::Object(serde_json::Map::default()));
1852                    if let serde_json::map::Entry::Vacant(v) =
1853                        analysis.as_object_mut()?.entry("typeCheckingMode")
1854                    {
1855                        v.insert(Value::String("standard".to_owned()));
1856                    }
1857                    Some(())
1858                });
1859            }
1860
1861            user_settings
1862        })
1863    }
1864}
1865
1866impl LspInstaller for BasedPyrightLspAdapter {
1867    type BinaryVersion = ();
1868
1869    async fn fetch_latest_server_version(
1870        &self,
1871        _: &dyn LspAdapterDelegate,
1872        _: bool,
1873        _: &mut AsyncApp,
1874    ) -> Result<()> {
1875        Ok(())
1876    }
1877
1878    async fn check_if_user_installed(
1879        &self,
1880        delegate: &dyn LspAdapterDelegate,
1881        toolchain: Option<Toolchain>,
1882        _: &AsyncApp,
1883    ) -> Option<LanguageServerBinary> {
1884        if let Some(bin) = delegate.which(Self::BINARY_NAME.as_ref()).await {
1885            let env = delegate.shell_env().await;
1886            Some(LanguageServerBinary {
1887                path: bin,
1888                env: Some(env),
1889                arguments: vec!["--stdio".into()],
1890            })
1891        } else {
1892            let path = Path::new(toolchain?.path.as_ref())
1893                .parent()?
1894                .join(Self::BINARY_NAME);
1895            delegate
1896                .which(path.as_os_str())
1897                .await
1898                .map(|_| LanguageServerBinary {
1899                    path,
1900                    arguments: vec!["--stdio".into()],
1901                    env: None,
1902                })
1903        }
1904    }
1905
1906    async fn fetch_server_binary(
1907        &self,
1908        _latest_version: (),
1909        _container_dir: PathBuf,
1910        delegate: &dyn LspAdapterDelegate,
1911    ) -> Result<LanguageServerBinary> {
1912        let venv = self.base_venv(delegate).await.map_err(|e| anyhow!(e))?;
1913        let pip_path = venv.join(BINARY_DIR).join("pip3");
1914        ensure!(
1915            util::command::new_smol_command(pip_path.as_path())
1916                .arg("install")
1917                .arg("basedpyright")
1918                .arg("--upgrade")
1919                .output()
1920                .await
1921                .context("getting pip install output")?
1922                .status
1923                .success(),
1924            "basedpyright installation failed"
1925        );
1926        let path = venv.join(BINARY_DIR).join(Self::BINARY_NAME);
1927        ensure!(
1928            delegate.which(path.as_os_str()).await.is_some(),
1929            "basedpyright installation was incomplete"
1930        );
1931        Ok(LanguageServerBinary {
1932            path,
1933            env: None,
1934            arguments: vec!["--stdio".into()],
1935        })
1936    }
1937
1938    async fn cached_server_binary(
1939        &self,
1940        _container_dir: PathBuf,
1941        delegate: &dyn LspAdapterDelegate,
1942    ) -> Option<LanguageServerBinary> {
1943        let venv = self.base_venv(delegate).await.ok()?;
1944        let path = venv.join(BINARY_DIR).join(Self::BINARY_NAME);
1945        delegate.which(path.as_os_str()).await?;
1946        Some(LanguageServerBinary {
1947            path,
1948            env: None,
1949            arguments: vec!["--stdio".into()],
1950        })
1951    }
1952}
1953
1954pub(crate) struct RuffLspAdapter {
1955    fs: Arc<dyn Fs>,
1956}
1957
1958#[cfg(target_os = "macos")]
1959impl RuffLspAdapter {
1960    const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
1961    const ARCH_SERVER_NAME: &str = "apple-darwin";
1962}
1963
1964#[cfg(target_os = "linux")]
1965impl RuffLspAdapter {
1966    const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
1967    const ARCH_SERVER_NAME: &str = "unknown-linux-gnu";
1968}
1969
1970#[cfg(target_os = "freebsd")]
1971impl RuffLspAdapter {
1972    const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
1973    const ARCH_SERVER_NAME: &str = "unknown-freebsd";
1974}
1975
1976#[cfg(target_os = "windows")]
1977impl RuffLspAdapter {
1978    const GITHUB_ASSET_KIND: AssetKind = AssetKind::Zip;
1979    const ARCH_SERVER_NAME: &str = "pc-windows-msvc";
1980}
1981
1982impl RuffLspAdapter {
1983    const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("ruff");
1984
1985    pub fn new(fs: Arc<dyn Fs>) -> RuffLspAdapter {
1986        RuffLspAdapter { fs }
1987    }
1988
1989    fn build_asset_name() -> Result<(String, String)> {
1990        let arch = match consts::ARCH {
1991            "x86" => "i686",
1992            _ => consts::ARCH,
1993        };
1994        let os = Self::ARCH_SERVER_NAME;
1995        let suffix = match consts::OS {
1996            "windows" => "zip",
1997            _ => "tar.gz",
1998        };
1999        let asset_name = format!("ruff-{arch}-{os}.{suffix}");
2000        let asset_stem = format!("ruff-{arch}-{os}");
2001        Ok((asset_stem, asset_name))
2002    }
2003}
2004
2005#[async_trait(?Send)]
2006impl LspAdapter for RuffLspAdapter {
2007    fn name(&self) -> LanguageServerName {
2008        Self::SERVER_NAME
2009    }
2010}
2011
2012impl LspInstaller for RuffLspAdapter {
2013    type BinaryVersion = GitHubLspBinaryVersion;
2014    async fn check_if_user_installed(
2015        &self,
2016        delegate: &dyn LspAdapterDelegate,
2017        toolchain: Option<Toolchain>,
2018        _: &AsyncApp,
2019    ) -> Option<LanguageServerBinary> {
2020        let ruff_in_venv = if let Some(toolchain) = toolchain
2021            && toolchain.language_name.as_ref() == "Python"
2022        {
2023            Path::new(toolchain.path.as_str())
2024                .parent()
2025                .map(|path| path.join("ruff"))
2026        } else {
2027            None
2028        };
2029
2030        for path in ruff_in_venv.into_iter().chain(["ruff".into()]) {
2031            if let Some(ruff_bin) = delegate.which(path.as_os_str()).await {
2032                let env = delegate.shell_env().await;
2033                return Some(LanguageServerBinary {
2034                    path: ruff_bin,
2035                    env: Some(env),
2036                    arguments: vec!["server".into()],
2037                });
2038            }
2039        }
2040
2041        None
2042    }
2043
2044    async fn fetch_latest_server_version(
2045        &self,
2046        delegate: &dyn LspAdapterDelegate,
2047        _: bool,
2048        _: &mut AsyncApp,
2049    ) -> Result<GitHubLspBinaryVersion> {
2050        let release =
2051            latest_github_release("astral-sh/ruff", true, false, delegate.http_client()).await?;
2052        let (_, asset_name) = Self::build_asset_name()?;
2053        let asset = release
2054            .assets
2055            .into_iter()
2056            .find(|asset| asset.name == asset_name)
2057            .with_context(|| format!("no asset found matching `{asset_name:?}`"))?;
2058        Ok(GitHubLspBinaryVersion {
2059            name: release.tag_name,
2060            url: asset.browser_download_url,
2061            digest: asset.digest,
2062        })
2063    }
2064
2065    async fn fetch_server_binary(
2066        &self,
2067        latest_version: GitHubLspBinaryVersion,
2068        container_dir: PathBuf,
2069        delegate: &dyn LspAdapterDelegate,
2070    ) -> Result<LanguageServerBinary> {
2071        let GitHubLspBinaryVersion {
2072            name,
2073            url,
2074            digest: expected_digest,
2075        } = latest_version;
2076        let destination_path = container_dir.join(format!("ruff-{name}"));
2077        let server_path = match Self::GITHUB_ASSET_KIND {
2078            AssetKind::TarGz | AssetKind::Gz => destination_path
2079                .join(Self::build_asset_name()?.0)
2080                .join("ruff"),
2081            AssetKind::Zip => destination_path.clone().join("ruff.exe"),
2082        };
2083
2084        let binary = LanguageServerBinary {
2085            path: server_path.clone(),
2086            env: None,
2087            arguments: vec!["server".into()],
2088        };
2089
2090        let metadata_path = destination_path.with_extension("metadata");
2091        let metadata = GithubBinaryMetadata::read_from_file(&metadata_path)
2092            .await
2093            .ok();
2094        if let Some(metadata) = metadata {
2095            let validity_check = async || {
2096                delegate
2097                    .try_exec(LanguageServerBinary {
2098                        path: server_path.clone(),
2099                        arguments: vec!["--version".into()],
2100                        env: None,
2101                    })
2102                    .await
2103                    .inspect_err(|err| {
2104                        log::warn!("Unable to run {server_path:?} asset, redownloading: {err}",)
2105                    })
2106            };
2107            if let (Some(actual_digest), Some(expected_digest)) =
2108                (&metadata.digest, &expected_digest)
2109            {
2110                if actual_digest == expected_digest {
2111                    if validity_check().await.is_ok() {
2112                        return Ok(binary);
2113                    }
2114                } else {
2115                    log::info!(
2116                        "SHA-256 mismatch for {destination_path:?} asset, downloading new asset. Expected: {expected_digest}, Got: {actual_digest}"
2117                    );
2118                }
2119            } else if validity_check().await.is_ok() {
2120                return Ok(binary);
2121            }
2122        }
2123
2124        download_server_binary(
2125            delegate,
2126            &url,
2127            expected_digest.as_deref(),
2128            &destination_path,
2129            Self::GITHUB_ASSET_KIND,
2130        )
2131        .await?;
2132        make_file_executable(&server_path).await?;
2133        remove_matching(&container_dir, |path| path != destination_path).await;
2134        GithubBinaryMetadata::write_to_file(
2135            &GithubBinaryMetadata {
2136                metadata_version: 1,
2137                digest: expected_digest,
2138            },
2139            &metadata_path,
2140        )
2141        .await?;
2142
2143        Ok(LanguageServerBinary {
2144            path: server_path,
2145            env: None,
2146            arguments: vec!["server".into()],
2147        })
2148    }
2149
2150    async fn cached_server_binary(
2151        &self,
2152        container_dir: PathBuf,
2153        _: &dyn LspAdapterDelegate,
2154    ) -> Option<LanguageServerBinary> {
2155        maybe!(async {
2156            let mut last = None;
2157            let mut entries = self.fs.read_dir(&container_dir).await?;
2158            while let Some(entry) = entries.next().await {
2159                let path = entry?;
2160                if path.extension().is_some_and(|ext| ext == "metadata") {
2161                    continue;
2162                }
2163                last = Some(path);
2164            }
2165
2166            let path = last.context("no cached binary")?;
2167            let path = match Self::GITHUB_ASSET_KIND {
2168                AssetKind::TarGz | AssetKind::Gz => {
2169                    path.join(Self::build_asset_name()?.0).join("ruff")
2170                }
2171                AssetKind::Zip => path.join("ruff.exe"),
2172            };
2173
2174            anyhow::Ok(LanguageServerBinary {
2175                path,
2176                env: None,
2177                arguments: vec!["server".into()],
2178            })
2179        })
2180        .await
2181        .log_err()
2182    }
2183}
2184
2185#[cfg(test)]
2186mod tests {
2187    use gpui::{AppContext as _, BorrowAppContext, Context, TestAppContext};
2188    use language::{AutoindentMode, Buffer, language_settings::AllLanguageSettings};
2189    use settings::SettingsStore;
2190    use std::num::NonZeroU32;
2191
2192    #[gpui::test]
2193    async fn test_python_autoindent(cx: &mut TestAppContext) {
2194        cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
2195        let language = crate::language("python", tree_sitter_python::LANGUAGE.into());
2196        cx.update(|cx| {
2197            let test_settings = SettingsStore::test(cx);
2198            cx.set_global(test_settings);
2199            language::init(cx);
2200            cx.update_global::<SettingsStore, _>(|store, cx| {
2201                store.update_user_settings::<AllLanguageSettings>(cx, |s| {
2202                    s.defaults.tab_size = NonZeroU32::new(2);
2203                });
2204            });
2205        });
2206
2207        cx.new(|cx| {
2208            let mut buffer = Buffer::local("", cx).with_language(language, cx);
2209            let append = |buffer: &mut Buffer, text: &str, cx: &mut Context<Buffer>| {
2210                let ix = buffer.len();
2211                buffer.edit([(ix..ix, text)], Some(AutoindentMode::EachLine), cx);
2212            };
2213
2214            // indent after "def():"
2215            append(&mut buffer, "def a():\n", cx);
2216            assert_eq!(buffer.text(), "def a():\n  ");
2217
2218            // preserve indent after blank line
2219            append(&mut buffer, "\n  ", cx);
2220            assert_eq!(buffer.text(), "def a():\n  \n  ");
2221
2222            // indent after "if"
2223            append(&mut buffer, "if a:\n  ", cx);
2224            assert_eq!(buffer.text(), "def a():\n  \n  if a:\n    ");
2225
2226            // preserve indent after statement
2227            append(&mut buffer, "b()\n", cx);
2228            assert_eq!(buffer.text(), "def a():\n  \n  if a:\n    b()\n    ");
2229
2230            // preserve indent after statement
2231            append(&mut buffer, "else", cx);
2232            assert_eq!(buffer.text(), "def a():\n  \n  if a:\n    b()\n    else");
2233
2234            // dedent "else""
2235            append(&mut buffer, ":", cx);
2236            assert_eq!(buffer.text(), "def a():\n  \n  if a:\n    b()\n  else:");
2237
2238            // indent lines after else
2239            append(&mut buffer, "\n", cx);
2240            assert_eq!(
2241                buffer.text(),
2242                "def a():\n  \n  if a:\n    b()\n  else:\n    "
2243            );
2244
2245            // indent after an open paren. the closing paren is not indented
2246            // because there is another token before it on the same line.
2247            append(&mut buffer, "foo(\n1)", cx);
2248            assert_eq!(
2249                buffer.text(),
2250                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n      1)"
2251            );
2252
2253            // dedent the closing paren if it is shifted to the beginning of the line
2254            let argument_ix = buffer.text().find('1').unwrap();
2255            buffer.edit(
2256                [(argument_ix..argument_ix + 1, "")],
2257                Some(AutoindentMode::EachLine),
2258                cx,
2259            );
2260            assert_eq!(
2261                buffer.text(),
2262                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n    )"
2263            );
2264
2265            // preserve indent after the close paren
2266            append(&mut buffer, "\n", cx);
2267            assert_eq!(
2268                buffer.text(),
2269                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n    )\n    "
2270            );
2271
2272            // manually outdent the last line
2273            let end_whitespace_ix = buffer.len() - 4;
2274            buffer.edit(
2275                [(end_whitespace_ix..buffer.len(), "")],
2276                Some(AutoindentMode::EachLine),
2277                cx,
2278            );
2279            assert_eq!(
2280                buffer.text(),
2281                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n    )\n"
2282            );
2283
2284            // preserve the newly reduced indentation on the next newline
2285            append(&mut buffer, "\n", cx);
2286            assert_eq!(
2287                buffer.text(),
2288                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n    )\n\n"
2289            );
2290
2291            // reset to a for loop statement
2292            let statement = "for i in range(10):\n  print(i)\n";
2293            buffer.edit([(0..buffer.len(), statement)], None, cx);
2294
2295            // insert single line comment after each line
2296            let eol_ixs = statement
2297                .char_indices()
2298                .filter_map(|(ix, c)| if c == '\n' { Some(ix) } else { None })
2299                .collect::<Vec<usize>>();
2300            let editions = eol_ixs
2301                .iter()
2302                .enumerate()
2303                .map(|(i, &eol_ix)| (eol_ix..eol_ix, format!(" # comment {}", i + 1)))
2304                .collect::<Vec<(std::ops::Range<usize>, String)>>();
2305            buffer.edit(editions, Some(AutoindentMode::EachLine), cx);
2306            assert_eq!(
2307                buffer.text(),
2308                "for i in range(10): # comment 1\n  print(i) # comment 2\n"
2309            );
2310
2311            // reset to a simple if statement
2312            buffer.edit([(0..buffer.len(), "if a:\n  b(\n  )")], None, cx);
2313
2314            // dedent "else" on the line after a closing paren
2315            append(&mut buffer, "\n  else:\n", cx);
2316            assert_eq!(buffer.text(), "if a:\n  b(\n  )\nelse:\n  ");
2317
2318            buffer
2319        });
2320    }
2321}