python.rs

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