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