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