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