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::command::new_smol_command;
  27use util::fs::{make_file_executable, remove_matching};
  28use util::rel_path::RelPath;
  29
  30use http_client::github_download::{GithubBinaryMetadata, download_server_binary};
  31use parking_lot::Mutex;
  32use std::str::FromStr;
  33use std::{
  34    borrow::Cow,
  35    fmt::Write,
  36    path::{Path, PathBuf},
  37    sync::Arc,
  38};
  39use task::{ShellKind, TaskTemplate, TaskTemplates, VariableName};
  40use util::{ResultExt, maybe};
  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.http_client(),
 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 = shell.activate_keyword();
1185                    let activate_script_name = match shell {
1186                        ShellKind::Posix | ShellKind::Rc => "activate",
1187                        ShellKind::Csh => "activate.csh",
1188                        ShellKind::Tcsh => "activate.csh",
1189                        ShellKind::Fish => "activate.fish",
1190                        ShellKind::Nushell => "activate.nu",
1191                        ShellKind::PowerShell => "activate.ps1",
1192                        ShellKind::Cmd => "activate.bat",
1193                        ShellKind::Xonsh => "activate.xsh",
1194                    };
1195                    let path = prefix.join(BINARY_DIR).join(activate_script_name);
1196
1197                    if let Some(quoted) = shell.try_quote(&path.to_string_lossy())
1198                        && fs.is_file(&path).await
1199                    {
1200                        activation_script.push(format!("{activate_keyword} {quoted}"));
1201                    }
1202                }
1203            }
1204            Some(PythonEnvironmentKind::Pyenv) => {
1205                let Some(manager) = toolchain.manager else {
1206                    return vec![];
1207                };
1208                let version = toolchain.version.as_deref().unwrap_or("system");
1209                let pyenv = manager.executable;
1210                let pyenv = pyenv.display();
1211                activation_script.extend(match shell {
1212                    ShellKind::Fish => Some(format!("\"{pyenv}\" shell - fish {version}")),
1213                    ShellKind::Posix => Some(format!("\"{pyenv}\" shell - sh {version}")),
1214                    ShellKind::Nushell => Some(format!("\"{pyenv}\" shell - nu {version}")),
1215                    ShellKind::PowerShell => None,
1216                    ShellKind::Csh => None,
1217                    ShellKind::Tcsh => None,
1218                    ShellKind::Cmd => None,
1219                    ShellKind::Rc => None,
1220                    ShellKind::Xonsh => None,
1221                })
1222            }
1223            _ => {}
1224        }
1225        activation_script
1226    }
1227}
1228
1229fn venv_to_toolchain(venv: PythonEnvironment) -> Option<Toolchain> {
1230    let mut name = String::from("Python");
1231    if let Some(ref version) = venv.version {
1232        _ = write!(name, " {version}");
1233    }
1234
1235    let name_and_kind = match (&venv.name, &venv.kind) {
1236        (Some(name), Some(kind)) => Some(format!("({name}; {})", python_env_kind_display(kind))),
1237        (Some(name), None) => Some(format!("({name})")),
1238        (None, Some(kind)) => Some(format!("({})", python_env_kind_display(kind))),
1239        (None, None) => None,
1240    };
1241
1242    if let Some(nk) = name_and_kind {
1243        _ = write!(name, " {nk}");
1244    }
1245
1246    Some(Toolchain {
1247        name: name.into(),
1248        path: venv.executable.as_ref()?.to_str()?.to_owned().into(),
1249        language_name: LanguageName::new("Python"),
1250        as_json: serde_json::to_value(venv).ok()?,
1251    })
1252}
1253
1254pub struct EnvironmentApi<'a> {
1255    global_search_locations: Arc<Mutex<Vec<PathBuf>>>,
1256    project_env: &'a HashMap<String, String>,
1257    pet_env: pet_core::os_environment::EnvironmentApi,
1258}
1259
1260impl<'a> EnvironmentApi<'a> {
1261    pub fn from_env(project_env: &'a HashMap<String, String>) -> Self {
1262        let paths = project_env
1263            .get("PATH")
1264            .map(|p| std::env::split_paths(p).collect())
1265            .unwrap_or_default();
1266
1267        EnvironmentApi {
1268            global_search_locations: Arc::new(Mutex::new(paths)),
1269            project_env,
1270            pet_env: pet_core::os_environment::EnvironmentApi::new(),
1271        }
1272    }
1273
1274    fn user_home(&self) -> Option<PathBuf> {
1275        self.project_env
1276            .get("HOME")
1277            .or_else(|| self.project_env.get("USERPROFILE"))
1278            .map(|home| pet_fs::path::norm_case(PathBuf::from(home)))
1279            .or_else(|| self.pet_env.get_user_home())
1280    }
1281}
1282
1283impl pet_core::os_environment::Environment for EnvironmentApi<'_> {
1284    fn get_user_home(&self) -> Option<PathBuf> {
1285        self.user_home()
1286    }
1287
1288    fn get_root(&self) -> Option<PathBuf> {
1289        None
1290    }
1291
1292    fn get_env_var(&self, key: String) -> Option<String> {
1293        self.project_env
1294            .get(&key)
1295            .cloned()
1296            .or_else(|| self.pet_env.get_env_var(key))
1297    }
1298
1299    fn get_know_global_search_locations(&self) -> Vec<PathBuf> {
1300        if self.global_search_locations.lock().is_empty() {
1301            let mut paths =
1302                std::env::split_paths(&self.get_env_var("PATH".to_string()).unwrap_or_default())
1303                    .collect::<Vec<PathBuf>>();
1304
1305            log::trace!("Env PATH: {:?}", paths);
1306            for p in self.pet_env.get_know_global_search_locations() {
1307                if !paths.contains(&p) {
1308                    paths.push(p);
1309                }
1310            }
1311
1312            let mut paths = paths
1313                .into_iter()
1314                .filter(|p| p.exists())
1315                .collect::<Vec<PathBuf>>();
1316
1317            self.global_search_locations.lock().append(&mut paths);
1318        }
1319        self.global_search_locations.lock().clone()
1320    }
1321}
1322
1323pub(crate) struct PyLspAdapter {
1324    python_venv_base: OnceCell<Result<Arc<Path>, String>>,
1325}
1326impl PyLspAdapter {
1327    const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("pylsp");
1328    pub(crate) fn new() -> Self {
1329        Self {
1330            python_venv_base: OnceCell::new(),
1331        }
1332    }
1333    async fn ensure_venv(delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>> {
1334        let python_path = Self::find_base_python(delegate)
1335            .await
1336            .with_context(|| {
1337                let mut message = "Could not find Python installation for PyLSP".to_owned();
1338                if cfg!(windows){
1339                    message.push_str(". Install Python from the Microsoft Store, or manually from https://www.python.org/downloads/windows.")
1340                }
1341                message
1342            })?;
1343        let work_dir = delegate
1344            .language_server_download_dir(&Self::SERVER_NAME)
1345            .await
1346            .context("Could not get working directory for PyLSP")?;
1347        let mut path = PathBuf::from(work_dir.as_ref());
1348        path.push("pylsp-venv");
1349        if !path.exists() {
1350            util::command::new_smol_command(python_path)
1351                .arg("-m")
1352                .arg("venv")
1353                .arg("pylsp-venv")
1354                .current_dir(work_dir)
1355                .spawn()?
1356                .output()
1357                .await?;
1358        }
1359
1360        Ok(path.into())
1361    }
1362    // Find "baseline", user python version from which we'll create our own venv.
1363    async fn find_base_python(delegate: &dyn LspAdapterDelegate) -> Option<PathBuf> {
1364        for path in ["python3", "python"] {
1365            let Some(path) = delegate.which(path.as_ref()).await else {
1366                continue;
1367            };
1368            // Try to detect situations where `python3` exists but is not a real Python interpreter.
1369            // Notably, on fresh Windows installs, `python3` is a shim that opens the Microsoft Store app
1370            // when run with no arguments, and just fails otherwise.
1371            let Some(output) = new_smol_command(&path)
1372                .args(["-c", "print(1 + 2)"])
1373                .output()
1374                .await
1375                .ok()
1376            else {
1377                continue;
1378            };
1379            if output.stdout.trim_ascii() != b"3" {
1380                continue;
1381            }
1382            return Some(path);
1383        }
1384        None
1385    }
1386
1387    async fn base_venv(&self, delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>, String> {
1388        self.python_venv_base
1389            .get_or_init(move || async move {
1390                Self::ensure_venv(delegate)
1391                    .await
1392                    .map_err(|e| format!("{e}"))
1393            })
1394            .await
1395            .clone()
1396    }
1397}
1398
1399const BINARY_DIR: &str = if cfg!(target_os = "windows") {
1400    "Scripts"
1401} else {
1402    "bin"
1403};
1404
1405#[async_trait(?Send)]
1406impl LspAdapter for PyLspAdapter {
1407    fn name(&self) -> LanguageServerName {
1408        Self::SERVER_NAME
1409    }
1410
1411    async fn process_completions(&self, _items: &mut [lsp::CompletionItem]) {}
1412
1413    async fn label_for_completion(
1414        &self,
1415        item: &lsp::CompletionItem,
1416        language: &Arc<language::Language>,
1417    ) -> Option<language::CodeLabel> {
1418        let label = &item.label;
1419        let grammar = language.grammar()?;
1420        let highlight_id = match item.kind? {
1421            lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method")?,
1422            lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function")?,
1423            lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type")?,
1424            lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant")?,
1425            _ => return None,
1426        };
1427        let filter_range = item
1428            .filter_text
1429            .as_deref()
1430            .and_then(|filter| label.find(filter).map(|ix| ix..ix + filter.len()))
1431            .unwrap_or(0..label.len());
1432        Some(language::CodeLabel {
1433            text: label.clone(),
1434            runs: vec![(0..label.len(), highlight_id)],
1435            filter_range,
1436        })
1437    }
1438
1439    async fn label_for_symbol(
1440        &self,
1441        name: &str,
1442        kind: lsp::SymbolKind,
1443        language: &Arc<language::Language>,
1444    ) -> Option<language::CodeLabel> {
1445        let (text, filter_range, display_range) = match kind {
1446            lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
1447                let text = format!("def {}():\n", name);
1448                let filter_range = 4..4 + name.len();
1449                let display_range = 0..filter_range.end;
1450                (text, filter_range, display_range)
1451            }
1452            lsp::SymbolKind::CLASS => {
1453                let text = format!("class {}:", name);
1454                let filter_range = 6..6 + name.len();
1455                let display_range = 0..filter_range.end;
1456                (text, filter_range, display_range)
1457            }
1458            lsp::SymbolKind::CONSTANT => {
1459                let text = format!("{} = 0", name);
1460                let filter_range = 0..name.len();
1461                let display_range = 0..filter_range.end;
1462                (text, filter_range, display_range)
1463            }
1464            _ => return None,
1465        };
1466
1467        Some(language::CodeLabel {
1468            runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
1469            text: text[display_range].to_string(),
1470            filter_range,
1471        })
1472    }
1473
1474    async fn workspace_configuration(
1475        self: Arc<Self>,
1476        adapter: &Arc<dyn LspAdapterDelegate>,
1477        toolchain: Option<Toolchain>,
1478        cx: &mut AsyncApp,
1479    ) -> Result<Value> {
1480        cx.update(move |cx| {
1481            let mut user_settings =
1482                language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
1483                    .and_then(|s| s.settings.clone())
1484                    .unwrap_or_else(|| {
1485                        json!({
1486                            "plugins": {
1487                                "pycodestyle": {"enabled": false},
1488                                "rope_autoimport": {"enabled": true, "memory": true},
1489                                "pylsp_mypy": {"enabled": false}
1490                            },
1491                            "rope": {
1492                                "ropeFolder": null
1493                            },
1494                        })
1495                    });
1496
1497            // If user did not explicitly modify their python venv, use one from picker.
1498            if let Some(toolchain) = toolchain {
1499                if !user_settings.is_object() {
1500                    user_settings = Value::Object(serde_json::Map::default());
1501                }
1502                let object = user_settings.as_object_mut().unwrap();
1503                if let Some(python) = object
1504                    .entry("plugins")
1505                    .or_insert(Value::Object(serde_json::Map::default()))
1506                    .as_object_mut()
1507                {
1508                    if let Some(jedi) = python
1509                        .entry("jedi")
1510                        .or_insert(Value::Object(serde_json::Map::default()))
1511                        .as_object_mut()
1512                    {
1513                        jedi.entry("environment".to_string())
1514                            .or_insert_with(|| Value::String(toolchain.path.clone().into()));
1515                    }
1516                    if let Some(pylint) = python
1517                        .entry("pylsp_mypy")
1518                        .or_insert(Value::Object(serde_json::Map::default()))
1519                        .as_object_mut()
1520                    {
1521                        pylint.entry("overrides".to_string()).or_insert_with(|| {
1522                            Value::Array(vec![
1523                                Value::String("--python-executable".into()),
1524                                Value::String(toolchain.path.into()),
1525                                Value::String("--cache-dir=/dev/null".into()),
1526                                Value::Bool(true),
1527                            ])
1528                        });
1529                    }
1530                }
1531            }
1532            user_settings = Value::Object(serde_json::Map::from_iter([(
1533                "pylsp".to_string(),
1534                user_settings,
1535            )]));
1536
1537            user_settings
1538        })
1539    }
1540}
1541
1542impl LspInstaller for PyLspAdapter {
1543    type BinaryVersion = ();
1544    async fn check_if_user_installed(
1545        &self,
1546        delegate: &dyn LspAdapterDelegate,
1547        toolchain: Option<Toolchain>,
1548        _: &AsyncApp,
1549    ) -> Option<LanguageServerBinary> {
1550        if let Some(pylsp_bin) = delegate.which(Self::SERVER_NAME.as_ref()).await {
1551            let env = delegate.shell_env().await;
1552            Some(LanguageServerBinary {
1553                path: pylsp_bin,
1554                env: Some(env),
1555                arguments: vec![],
1556            })
1557        } else {
1558            let toolchain = toolchain?;
1559            let pylsp_path = Path::new(toolchain.path.as_ref()).parent()?.join("pylsp");
1560            pylsp_path.exists().then(|| LanguageServerBinary {
1561                path: toolchain.path.to_string().into(),
1562                arguments: vec![pylsp_path.into()],
1563                env: None,
1564            })
1565        }
1566    }
1567
1568    async fn fetch_latest_server_version(
1569        &self,
1570        _: &dyn LspAdapterDelegate,
1571        _: bool,
1572        _: &mut AsyncApp,
1573    ) -> Result<()> {
1574        Ok(())
1575    }
1576
1577    async fn fetch_server_binary(
1578        &self,
1579        _: (),
1580        _: PathBuf,
1581        delegate: &dyn LspAdapterDelegate,
1582    ) -> Result<LanguageServerBinary> {
1583        let venv = self.base_venv(delegate).await.map_err(|e| anyhow!(e))?;
1584        let pip_path = venv.join(BINARY_DIR).join("pip3");
1585        ensure!(
1586            util::command::new_smol_command(pip_path.as_path())
1587                .arg("install")
1588                .arg("python-lsp-server[all]")
1589                .arg("--upgrade")
1590                .output()
1591                .await?
1592                .status
1593                .success(),
1594            "python-lsp-server[all] installation failed"
1595        );
1596        ensure!(
1597            util::command::new_smol_command(pip_path)
1598                .arg("install")
1599                .arg("pylsp-mypy")
1600                .arg("--upgrade")
1601                .output()
1602                .await?
1603                .status
1604                .success(),
1605            "pylsp-mypy installation failed"
1606        );
1607        let pylsp = venv.join(BINARY_DIR).join("pylsp");
1608        ensure!(
1609            delegate.which(pylsp.as_os_str()).await.is_some(),
1610            "pylsp installation was incomplete"
1611        );
1612        Ok(LanguageServerBinary {
1613            path: pylsp,
1614            env: None,
1615            arguments: vec![],
1616        })
1617    }
1618
1619    async fn cached_server_binary(
1620        &self,
1621        _: PathBuf,
1622        delegate: &dyn LspAdapterDelegate,
1623    ) -> Option<LanguageServerBinary> {
1624        let venv = self.base_venv(delegate).await.ok()?;
1625        let pylsp = venv.join(BINARY_DIR).join("pylsp");
1626        delegate.which(pylsp.as_os_str()).await?;
1627        Some(LanguageServerBinary {
1628            path: pylsp,
1629            env: None,
1630            arguments: vec![],
1631        })
1632    }
1633}
1634
1635pub(crate) struct BasedPyrightLspAdapter {
1636    node: NodeRuntime,
1637}
1638
1639impl BasedPyrightLspAdapter {
1640    const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("basedpyright");
1641    const BINARY_NAME: &'static str = "basedpyright-langserver";
1642    const SERVER_PATH: &str = "node_modules/basedpyright/langserver.index.js";
1643    const NODE_MODULE_RELATIVE_SERVER_PATH: &str = "basedpyright/langserver.index.js";
1644
1645    pub(crate) fn new(node: NodeRuntime) -> Self {
1646        BasedPyrightLspAdapter { node }
1647    }
1648
1649    async fn get_cached_server_binary(
1650        container_dir: PathBuf,
1651        node: &NodeRuntime,
1652    ) -> Option<LanguageServerBinary> {
1653        let server_path = container_dir.join(Self::SERVER_PATH);
1654        if server_path.exists() {
1655            Some(LanguageServerBinary {
1656                path: node.binary_path().await.log_err()?,
1657                env: None,
1658                arguments: vec![server_path.into(), "--stdio".into()],
1659            })
1660        } else {
1661            log::error!("missing executable in directory {:?}", server_path);
1662            None
1663        }
1664    }
1665}
1666
1667#[async_trait(?Send)]
1668impl LspAdapter for BasedPyrightLspAdapter {
1669    fn name(&self) -> LanguageServerName {
1670        Self::SERVER_NAME
1671    }
1672
1673    async fn initialization_options(
1674        self: Arc<Self>,
1675        _: &Arc<dyn LspAdapterDelegate>,
1676    ) -> Result<Option<Value>> {
1677        // Provide minimal initialization options
1678        // Virtual environment configuration will be handled through workspace configuration
1679        Ok(Some(json!({
1680            "python": {
1681                "analysis": {
1682                    "autoSearchPaths": true,
1683                    "useLibraryCodeForTypes": true,
1684                    "autoImportCompletions": true
1685                }
1686            }
1687        })))
1688    }
1689
1690    async fn process_completions(&self, items: &mut [lsp::CompletionItem]) {
1691        process_pyright_completions(items);
1692    }
1693
1694    async fn label_for_completion(
1695        &self,
1696        item: &lsp::CompletionItem,
1697        language: &Arc<language::Language>,
1698    ) -> Option<language::CodeLabel> {
1699        let label = &item.label;
1700        let grammar = language.grammar()?;
1701        let highlight_id = match item.kind? {
1702            lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method"),
1703            lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function"),
1704            lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type"),
1705            lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant"),
1706            lsp::CompletionItemKind::VARIABLE => grammar.highlight_id_for_name("variable"),
1707            _ => {
1708                return None;
1709            }
1710        };
1711        let filter_range = item
1712            .filter_text
1713            .as_deref()
1714            .and_then(|filter| label.find(filter).map(|ix| ix..ix + filter.len()))
1715            .unwrap_or(0..label.len());
1716        let mut text = label.clone();
1717        if let Some(completion_details) = item
1718            .label_details
1719            .as_ref()
1720            .and_then(|details| details.description.as_ref())
1721        {
1722            write!(&mut text, " {}", completion_details).ok();
1723        }
1724        Some(language::CodeLabel {
1725            runs: highlight_id
1726                .map(|id| (0..label.len(), id))
1727                .into_iter()
1728                .collect(),
1729            text,
1730            filter_range,
1731        })
1732    }
1733
1734    async fn label_for_symbol(
1735        &self,
1736        name: &str,
1737        kind: lsp::SymbolKind,
1738        language: &Arc<language::Language>,
1739    ) -> Option<language::CodeLabel> {
1740        let (text, filter_range, display_range) = match kind {
1741            lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
1742                let text = format!("def {}():\n", name);
1743                let filter_range = 4..4 + name.len();
1744                let display_range = 0..filter_range.end;
1745                (text, filter_range, display_range)
1746            }
1747            lsp::SymbolKind::CLASS => {
1748                let text = format!("class {}:", name);
1749                let filter_range = 6..6 + name.len();
1750                let display_range = 0..filter_range.end;
1751                (text, filter_range, display_range)
1752            }
1753            lsp::SymbolKind::CONSTANT => {
1754                let text = format!("{} = 0", name);
1755                let filter_range = 0..name.len();
1756                let display_range = 0..filter_range.end;
1757                (text, filter_range, display_range)
1758            }
1759            _ => return None,
1760        };
1761
1762        Some(language::CodeLabel {
1763            runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
1764            text: text[display_range].to_string(),
1765            filter_range,
1766        })
1767    }
1768
1769    async fn workspace_configuration(
1770        self: Arc<Self>,
1771        adapter: &Arc<dyn LspAdapterDelegate>,
1772        toolchain: Option<Toolchain>,
1773        cx: &mut AsyncApp,
1774    ) -> Result<Value> {
1775        cx.update(move |cx| {
1776            let mut user_settings =
1777                language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
1778                    .and_then(|s| s.settings.clone())
1779                    .unwrap_or_default();
1780
1781            // If we have a detected toolchain, configure Pyright to use it
1782            if let Some(toolchain) = toolchain
1783                && let Ok(env) = serde_json::from_value::<
1784                    pet_core::python_environment::PythonEnvironment,
1785                >(toolchain.as_json.clone())
1786            {
1787                if !user_settings.is_object() {
1788                    user_settings = Value::Object(serde_json::Map::default());
1789                }
1790                let object = user_settings.as_object_mut().unwrap();
1791
1792                let interpreter_path = toolchain.path.to_string();
1793                if let Some(venv_dir) = env.prefix {
1794                    // Set venvPath and venv at the root level
1795                    // This matches the format of a pyrightconfig.json file
1796                    if let Some(parent) = venv_dir.parent() {
1797                        // Use relative path if the venv is inside the workspace
1798                        let venv_path = if parent == adapter.worktree_root_path() {
1799                            ".".to_string()
1800                        } else {
1801                            parent.to_string_lossy().into_owned()
1802                        };
1803                        object.insert("venvPath".to_string(), Value::String(venv_path));
1804                    }
1805
1806                    if let Some(venv_name) = venv_dir.file_name() {
1807                        object.insert(
1808                            "venv".to_owned(),
1809                            Value::String(venv_name.to_string_lossy().into_owned()),
1810                        );
1811                    }
1812                }
1813
1814                // Set both pythonPath and defaultInterpreterPath for compatibility
1815                if let Some(python) = object
1816                    .entry("python")
1817                    .or_insert(Value::Object(serde_json::Map::default()))
1818                    .as_object_mut()
1819                {
1820                    python.insert(
1821                        "pythonPath".to_owned(),
1822                        Value::String(interpreter_path.clone()),
1823                    );
1824                    python.insert(
1825                        "defaultInterpreterPath".to_owned(),
1826                        Value::String(interpreter_path),
1827                    );
1828                }
1829                // Basedpyright by default uses `strict` type checking, we tone it down as to not surpris users
1830                maybe!({
1831                    let basedpyright = object
1832                        .entry("basedpyright")
1833                        .or_insert(Value::Object(serde_json::Map::default()));
1834                    let analysis = basedpyright
1835                        .as_object_mut()?
1836                        .entry("analysis")
1837                        .or_insert(Value::Object(serde_json::Map::default()));
1838                    if let serde_json::map::Entry::Vacant(v) =
1839                        analysis.as_object_mut()?.entry("typeCheckingMode")
1840                    {
1841                        v.insert(Value::String("standard".to_owned()));
1842                    }
1843                    Some(())
1844                });
1845            }
1846
1847            user_settings
1848        })
1849    }
1850}
1851
1852impl LspInstaller for BasedPyrightLspAdapter {
1853    type BinaryVersion = String;
1854
1855    async fn fetch_latest_server_version(
1856        &self,
1857        _: &dyn LspAdapterDelegate,
1858        _: bool,
1859        _: &mut AsyncApp,
1860    ) -> Result<String> {
1861        self.node
1862            .npm_package_latest_version(Self::SERVER_NAME.as_ref())
1863            .await
1864    }
1865
1866    async fn check_if_user_installed(
1867        &self,
1868        delegate: &dyn LspAdapterDelegate,
1869        _: Option<Toolchain>,
1870        _: &AsyncApp,
1871    ) -> Option<LanguageServerBinary> {
1872        if let Some(path) = delegate.which(Self::BINARY_NAME.as_ref()).await {
1873            let env = delegate.shell_env().await;
1874            Some(LanguageServerBinary {
1875                path,
1876                env: Some(env),
1877                arguments: vec!["--stdio".into()],
1878            })
1879        } else {
1880            // TODO shouldn't this be self.node.binary_path()?
1881            let node = delegate.which("node".as_ref()).await?;
1882            let (node_modules_path, _) = delegate
1883                .npm_package_installed_version(Self::SERVER_NAME.as_ref())
1884                .await
1885                .log_err()??;
1886
1887            let path = node_modules_path.join(Self::NODE_MODULE_RELATIVE_SERVER_PATH);
1888
1889            let env = delegate.shell_env().await;
1890            Some(LanguageServerBinary {
1891                path: node,
1892                env: Some(env),
1893                arguments: vec![path.into(), "--stdio".into()],
1894            })
1895        }
1896    }
1897
1898    async fn fetch_server_binary(
1899        &self,
1900        latest_version: Self::BinaryVersion,
1901        container_dir: PathBuf,
1902        delegate: &dyn LspAdapterDelegate,
1903    ) -> Result<LanguageServerBinary> {
1904        let server_path = container_dir.join(Self::SERVER_PATH);
1905
1906        self.node
1907            .npm_install_packages(
1908                &container_dir,
1909                &[(Self::SERVER_NAME.as_ref(), latest_version.as_str())],
1910            )
1911            .await?;
1912
1913        let env = delegate.shell_env().await;
1914        Ok(LanguageServerBinary {
1915            path: self.node.binary_path().await?,
1916            env: Some(env),
1917            arguments: vec![server_path.into(), "--stdio".into()],
1918        })
1919    }
1920
1921    async fn check_if_version_installed(
1922        &self,
1923        version: &Self::BinaryVersion,
1924        container_dir: &PathBuf,
1925        delegate: &dyn LspAdapterDelegate,
1926    ) -> Option<LanguageServerBinary> {
1927        let server_path = container_dir.join(Self::SERVER_PATH);
1928
1929        let should_install_language_server = self
1930            .node
1931            .should_install_npm_package(
1932                Self::SERVER_NAME.as_ref(),
1933                &server_path,
1934                container_dir,
1935                VersionStrategy::Latest(version),
1936            )
1937            .await;
1938
1939        if should_install_language_server {
1940            None
1941        } else {
1942            let env = delegate.shell_env().await;
1943            Some(LanguageServerBinary {
1944                path: self.node.binary_path().await.ok()?,
1945                env: Some(env),
1946                arguments: vec![server_path.into(), "--stdio".into()],
1947            })
1948        }
1949    }
1950
1951    async fn cached_server_binary(
1952        &self,
1953        container_dir: PathBuf,
1954        delegate: &dyn LspAdapterDelegate,
1955    ) -> Option<LanguageServerBinary> {
1956        let mut binary = Self::get_cached_server_binary(container_dir, &self.node).await?;
1957        binary.env = Some(delegate.shell_env().await);
1958        Some(binary)
1959    }
1960}
1961
1962pub(crate) struct RuffLspAdapter {
1963    fs: Arc<dyn Fs>,
1964}
1965
1966#[cfg(target_os = "macos")]
1967impl RuffLspAdapter {
1968    const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
1969    const ARCH_SERVER_NAME: &str = "apple-darwin";
1970}
1971
1972#[cfg(target_os = "linux")]
1973impl RuffLspAdapter {
1974    const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
1975    const ARCH_SERVER_NAME: &str = "unknown-linux-gnu";
1976}
1977
1978#[cfg(target_os = "freebsd")]
1979impl RuffLspAdapter {
1980    const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
1981    const ARCH_SERVER_NAME: &str = "unknown-freebsd";
1982}
1983
1984#[cfg(target_os = "windows")]
1985impl RuffLspAdapter {
1986    const GITHUB_ASSET_KIND: AssetKind = AssetKind::Zip;
1987    const ARCH_SERVER_NAME: &str = "pc-windows-msvc";
1988}
1989
1990impl RuffLspAdapter {
1991    const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("ruff");
1992
1993    pub fn new(fs: Arc<dyn Fs>) -> RuffLspAdapter {
1994        RuffLspAdapter { fs }
1995    }
1996
1997    fn build_asset_name() -> Result<(String, String)> {
1998        let arch = match consts::ARCH {
1999            "x86" => "i686",
2000            _ => consts::ARCH,
2001        };
2002        let os = Self::ARCH_SERVER_NAME;
2003        let suffix = match consts::OS {
2004            "windows" => "zip",
2005            _ => "tar.gz",
2006        };
2007        let asset_name = format!("ruff-{arch}-{os}.{suffix}");
2008        let asset_stem = format!("ruff-{arch}-{os}");
2009        Ok((asset_stem, asset_name))
2010    }
2011}
2012
2013#[async_trait(?Send)]
2014impl LspAdapter for RuffLspAdapter {
2015    fn name(&self) -> LanguageServerName {
2016        Self::SERVER_NAME
2017    }
2018}
2019
2020impl LspInstaller for RuffLspAdapter {
2021    type BinaryVersion = GitHubLspBinaryVersion;
2022    async fn check_if_user_installed(
2023        &self,
2024        delegate: &dyn LspAdapterDelegate,
2025        toolchain: Option<Toolchain>,
2026        _: &AsyncApp,
2027    ) -> Option<LanguageServerBinary> {
2028        let ruff_in_venv = if let Some(toolchain) = toolchain
2029            && toolchain.language_name.as_ref() == "Python"
2030        {
2031            Path::new(toolchain.path.as_str())
2032                .parent()
2033                .map(|path| path.join("ruff"))
2034        } else {
2035            None
2036        };
2037
2038        for path in ruff_in_venv.into_iter().chain(["ruff".into()]) {
2039            if let Some(ruff_bin) = delegate.which(path.as_os_str()).await {
2040                let env = delegate.shell_env().await;
2041                return Some(LanguageServerBinary {
2042                    path: ruff_bin,
2043                    env: Some(env),
2044                    arguments: vec!["server".into()],
2045                });
2046            }
2047        }
2048
2049        None
2050    }
2051
2052    async fn fetch_latest_server_version(
2053        &self,
2054        delegate: &dyn LspAdapterDelegate,
2055        _: bool,
2056        _: &mut AsyncApp,
2057    ) -> Result<GitHubLspBinaryVersion> {
2058        let release =
2059            latest_github_release("astral-sh/ruff", true, false, delegate.http_client()).await?;
2060        let (_, asset_name) = Self::build_asset_name()?;
2061        let asset = release
2062            .assets
2063            .into_iter()
2064            .find(|asset| asset.name == asset_name)
2065            .with_context(|| format!("no asset found matching `{asset_name:?}`"))?;
2066        Ok(GitHubLspBinaryVersion {
2067            name: release.tag_name,
2068            url: asset.browser_download_url,
2069            digest: asset.digest,
2070        })
2071    }
2072
2073    async fn fetch_server_binary(
2074        &self,
2075        latest_version: GitHubLspBinaryVersion,
2076        container_dir: PathBuf,
2077        delegate: &dyn LspAdapterDelegate,
2078    ) -> Result<LanguageServerBinary> {
2079        let GitHubLspBinaryVersion {
2080            name,
2081            url,
2082            digest: expected_digest,
2083        } = latest_version;
2084        let destination_path = container_dir.join(format!("ruff-{name}"));
2085        let server_path = match Self::GITHUB_ASSET_KIND {
2086            AssetKind::TarGz | AssetKind::Gz => destination_path
2087                .join(Self::build_asset_name()?.0)
2088                .join("ruff"),
2089            AssetKind::Zip => destination_path.clone().join("ruff.exe"),
2090        };
2091
2092        let binary = LanguageServerBinary {
2093            path: server_path.clone(),
2094            env: None,
2095            arguments: vec!["server".into()],
2096        };
2097
2098        let metadata_path = destination_path.with_extension("metadata");
2099        let metadata = GithubBinaryMetadata::read_from_file(&metadata_path)
2100            .await
2101            .ok();
2102        if let Some(metadata) = metadata {
2103            let validity_check = async || {
2104                delegate
2105                    .try_exec(LanguageServerBinary {
2106                        path: server_path.clone(),
2107                        arguments: vec!["--version".into()],
2108                        env: None,
2109                    })
2110                    .await
2111                    .inspect_err(|err| {
2112                        log::warn!("Unable to run {server_path:?} asset, redownloading: {err}",)
2113                    })
2114            };
2115            if let (Some(actual_digest), Some(expected_digest)) =
2116                (&metadata.digest, &expected_digest)
2117            {
2118                if actual_digest == expected_digest {
2119                    if validity_check().await.is_ok() {
2120                        return Ok(binary);
2121                    }
2122                } else {
2123                    log::info!(
2124                        "SHA-256 mismatch for {destination_path:?} asset, downloading new asset. Expected: {expected_digest}, Got: {actual_digest}"
2125                    );
2126                }
2127            } else if validity_check().await.is_ok() {
2128                return Ok(binary);
2129            }
2130        }
2131
2132        download_server_binary(
2133            &*delegate.http_client(),
2134            &url,
2135            expected_digest.as_deref(),
2136            &destination_path,
2137            Self::GITHUB_ASSET_KIND,
2138        )
2139        .await?;
2140        make_file_executable(&server_path).await?;
2141        remove_matching(&container_dir, |path| path != destination_path).await;
2142        GithubBinaryMetadata::write_to_file(
2143            &GithubBinaryMetadata {
2144                metadata_version: 1,
2145                digest: expected_digest,
2146            },
2147            &metadata_path,
2148        )
2149        .await?;
2150
2151        Ok(LanguageServerBinary {
2152            path: server_path,
2153            env: None,
2154            arguments: vec!["server".into()],
2155        })
2156    }
2157
2158    async fn cached_server_binary(
2159        &self,
2160        container_dir: PathBuf,
2161        _: &dyn LspAdapterDelegate,
2162    ) -> Option<LanguageServerBinary> {
2163        maybe!(async {
2164            let mut last = None;
2165            let mut entries = self.fs.read_dir(&container_dir).await?;
2166            while let Some(entry) = entries.next().await {
2167                let path = entry?;
2168                if path.extension().is_some_and(|ext| ext == "metadata") {
2169                    continue;
2170                }
2171                last = Some(path);
2172            }
2173
2174            let path = last.context("no cached binary")?;
2175            let path = match Self::GITHUB_ASSET_KIND {
2176                AssetKind::TarGz | AssetKind::Gz => {
2177                    path.join(Self::build_asset_name()?.0).join("ruff")
2178                }
2179                AssetKind::Zip => path.join("ruff.exe"),
2180            };
2181
2182            anyhow::Ok(LanguageServerBinary {
2183                path,
2184                env: None,
2185                arguments: vec!["server".into()],
2186            })
2187        })
2188        .await
2189        .log_err()
2190    }
2191}
2192
2193#[cfg(test)]
2194mod tests {
2195    use gpui::{AppContext as _, BorrowAppContext, Context, TestAppContext};
2196    use language::{AutoindentMode, Buffer};
2197    use settings::SettingsStore;
2198    use std::num::NonZeroU32;
2199
2200    #[gpui::test]
2201    async fn test_python_autoindent(cx: &mut TestAppContext) {
2202        cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
2203        let language = crate::language("python", tree_sitter_python::LANGUAGE.into());
2204        cx.update(|cx| {
2205            let test_settings = SettingsStore::test(cx);
2206            cx.set_global(test_settings);
2207            language::init(cx);
2208            cx.update_global::<SettingsStore, _>(|store, cx| {
2209                store.update_user_settings(cx, |s| {
2210                    s.project.all_languages.defaults.tab_size = NonZeroU32::new(2);
2211                });
2212            });
2213        });
2214
2215        cx.new(|cx| {
2216            let mut buffer = Buffer::local("", cx).with_language(language, cx);
2217            let append = |buffer: &mut Buffer, text: &str, cx: &mut Context<Buffer>| {
2218                let ix = buffer.len();
2219                buffer.edit([(ix..ix, text)], Some(AutoindentMode::EachLine), cx);
2220            };
2221
2222            // indent after "def():"
2223            append(&mut buffer, "def a():\n", cx);
2224            assert_eq!(buffer.text(), "def a():\n  ");
2225
2226            // preserve indent after blank line
2227            append(&mut buffer, "\n  ", cx);
2228            assert_eq!(buffer.text(), "def a():\n  \n  ");
2229
2230            // indent after "if"
2231            append(&mut buffer, "if a:\n  ", cx);
2232            assert_eq!(buffer.text(), "def a():\n  \n  if a:\n    ");
2233
2234            // preserve indent after statement
2235            append(&mut buffer, "b()\n", cx);
2236            assert_eq!(buffer.text(), "def a():\n  \n  if a:\n    b()\n    ");
2237
2238            // preserve indent after statement
2239            append(&mut buffer, "else", cx);
2240            assert_eq!(buffer.text(), "def a():\n  \n  if a:\n    b()\n    else");
2241
2242            // dedent "else""
2243            append(&mut buffer, ":", cx);
2244            assert_eq!(buffer.text(), "def a():\n  \n  if a:\n    b()\n  else:");
2245
2246            // indent lines after else
2247            append(&mut buffer, "\n", cx);
2248            assert_eq!(
2249                buffer.text(),
2250                "def a():\n  \n  if a:\n    b()\n  else:\n    "
2251            );
2252
2253            // indent after an open paren. the closing paren is not indented
2254            // because there is another token before it on the same line.
2255            append(&mut buffer, "foo(\n1)", cx);
2256            assert_eq!(
2257                buffer.text(),
2258                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n      1)"
2259            );
2260
2261            // dedent the closing paren if it is shifted to the beginning of the line
2262            let argument_ix = buffer.text().find('1').unwrap();
2263            buffer.edit(
2264                [(argument_ix..argument_ix + 1, "")],
2265                Some(AutoindentMode::EachLine),
2266                cx,
2267            );
2268            assert_eq!(
2269                buffer.text(),
2270                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n    )"
2271            );
2272
2273            // preserve indent after the close paren
2274            append(&mut buffer, "\n", cx);
2275            assert_eq!(
2276                buffer.text(),
2277                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n    )\n    "
2278            );
2279
2280            // manually outdent the last line
2281            let end_whitespace_ix = buffer.len() - 4;
2282            buffer.edit(
2283                [(end_whitespace_ix..buffer.len(), "")],
2284                Some(AutoindentMode::EachLine),
2285                cx,
2286            );
2287            assert_eq!(
2288                buffer.text(),
2289                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n    )\n"
2290            );
2291
2292            // preserve the newly reduced indentation on the next newline
2293            append(&mut buffer, "\n", cx);
2294            assert_eq!(
2295                buffer.text(),
2296                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n    )\n\n"
2297            );
2298
2299            // reset to a for loop statement
2300            let statement = "for i in range(10):\n  print(i)\n";
2301            buffer.edit([(0..buffer.len(), statement)], None, cx);
2302
2303            // insert single line comment after each line
2304            let eol_ixs = statement
2305                .char_indices()
2306                .filter_map(|(ix, c)| if c == '\n' { Some(ix) } else { None })
2307                .collect::<Vec<usize>>();
2308            let editions = eol_ixs
2309                .iter()
2310                .enumerate()
2311                .map(|(i, &eol_ix)| (eol_ix..eol_ix, format!(" # comment {}", i + 1)))
2312                .collect::<Vec<(std::ops::Range<usize>, String)>>();
2313            buffer.edit(editions, Some(AutoindentMode::EachLine), cx);
2314            assert_eq!(
2315                buffer.text(),
2316                "for i in range(10): # comment 1\n  print(i) # comment 2\n"
2317            );
2318
2319            // reset to a simple if statement
2320            buffer.edit([(0..buffer.len(), "if a:\n  b(\n  )")], None, cx);
2321
2322            // dedent "else" on the line after a closing paren
2323            append(&mut buffer, "\n  else:\n", cx);
2324            assert_eq!(buffer.text(), "if a:\n  b(\n  )\nelse:\n  ");
2325
2326            buffer
2327        });
2328    }
2329}