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