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