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