python.rs

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