python.rs

   1use anyhow::{Context as _, ensure};
   2use anyhow::{Result, anyhow};
   3use async_trait::async_trait;
   4use collections::HashMap;
   5use futures::future::BoxFuture;
   6use futures::lock::OwnedMutexGuard;
   7use futures::{AsyncBufReadExt, StreamExt as _};
   8use gpui::{App, AsyncApp, SharedString, Task};
   9use http_client::github::{AssetKind, GitHubLspBinaryVersion, latest_github_release};
  10use language::language_settings::language_settings;
  11use language::{ContextLocation, DynLspInstaller, LanguageToolchainStore, LspInstaller};
  12use language::{ContextProvider, LspAdapter, LspAdapterDelegate};
  13use language::{LanguageName, ManifestName, ManifestProvider, ManifestQuery};
  14use language::{Toolchain, ToolchainList, ToolchainLister, ToolchainMetadata};
  15use lsp::{LanguageServerBinary, Uri};
  16use lsp::{LanguageServerBinaryOptions, LanguageServerName};
  17use node_runtime::{NodeRuntime, VersionStrategy};
  18use pet_core::Configuration;
  19use pet_core::os_environment::Environment;
  20use pet_core::python_environment::{PythonEnvironment, PythonEnvironmentKind};
  21use pet_virtualenv::is_virtualenv_dir;
  22use project::Fs;
  23use project::lsp_store::language_server_settings;
  24use semver::Version;
  25use serde::{Deserialize, Serialize};
  26use serde_json::{Value, json};
  27use settings::Settings;
  28use terminal::terminal_settings::TerminalSettings;
  29
  30use smol::lock::OnceCell;
  31use std::cmp::{Ordering, Reverse};
  32use std::env::consts;
  33use std::process::Stdio;
  34
  35use util::command::new_smol_command;
  36use util::fs::{make_file_executable, remove_matching};
  37use util::paths::PathStyle;
  38use util::rel_path::RelPath;
  39
  40use http_client::github_download::{GithubBinaryMetadata, download_server_binary};
  41use parking_lot::Mutex;
  42use std::str::FromStr;
  43use std::{
  44    borrow::Cow,
  45    fmt::Write,
  46    path::{Path, PathBuf},
  47    sync::Arc,
  48};
  49use task::{ShellKind, TaskTemplate, TaskTemplates, VariableName};
  50use util::{ResultExt, maybe};
  51
  52#[derive(Debug, Serialize, Deserialize)]
  53pub(crate) struct PythonToolchainData {
  54    #[serde(flatten)]
  55    environment: PythonEnvironment,
  56    #[serde(skip_serializing_if = "Option::is_none")]
  57    activation_scripts: Option<HashMap<ShellKind, PathBuf>>,
  58}
  59
  60pub(crate) struct PyprojectTomlManifestProvider;
  61
  62impl ManifestProvider for PyprojectTomlManifestProvider {
  63    fn name(&self) -> ManifestName {
  64        SharedString::new_static("pyproject.toml").into()
  65    }
  66
  67    fn search(
  68        &self,
  69        ManifestQuery {
  70            path,
  71            depth,
  72            delegate,
  73        }: ManifestQuery,
  74    ) -> Option<Arc<RelPath>> {
  75        for path in path.ancestors().take(depth) {
  76            let p = path.join(RelPath::unix("pyproject.toml").unwrap());
  77            if delegate.exists(&p, Some(false)) {
  78                return Some(path.into());
  79            }
  80        }
  81
  82        None
  83    }
  84}
  85
  86enum TestRunner {
  87    UNITTEST,
  88    PYTEST,
  89}
  90
  91impl FromStr for TestRunner {
  92    type Err = ();
  93
  94    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
  95        match s {
  96            "unittest" => Ok(Self::UNITTEST),
  97            "pytest" => Ok(Self::PYTEST),
  98            _ => Err(()),
  99        }
 100    }
 101}
 102
 103/// Pyright assigns each completion item a `sortText` of the form `XX.YYYY.name`.
 104/// Where `XX` is the sorting category, `YYYY` is based on most recent usage,
 105/// and `name` is the symbol name itself.
 106///
 107/// 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),
 108/// which - long story short - makes completion items list non-stable. Pyright probably relies on VSCode's implementation detail.
 109/// see https://github.com/microsoft/pyright/blob/95ef4e103b9b2f129c9320427e51b73ea7cf78bd/packages/pyright-internal/src/languageService/completionProvider.ts#LL2873
 110///
 111/// upd 02.12.25:
 112/// Decided to ignore Pyright's sortText() completely and to manually sort all entries
 113fn process_pyright_completions(items: &mut [lsp::CompletionItem]) {
 114    for item in items {
 115        let is_dunder = item.label.starts_with("__") && item.label.ends_with("__");
 116
 117        let visibility_priority = if is_dunder {
 118            '3'
 119        } else if item.label.starts_with("__") {
 120            '2' // private non-dunder
 121        } else if item.label.starts_with('_') {
 122            '1' // protected
 123        } else {
 124            '0' // public
 125        };
 126
 127        // Kind priority within same visibility level
 128        let kind_priority = match item.kind {
 129            Some(lsp::CompletionItemKind::ENUM_MEMBER) => '0',
 130            Some(lsp::CompletionItemKind::FIELD) => '1',
 131            Some(lsp::CompletionItemKind::PROPERTY) => '2',
 132            Some(lsp::CompletionItemKind::VARIABLE) => '3',
 133            Some(lsp::CompletionItemKind::CONSTANT) => '4',
 134            Some(lsp::CompletionItemKind::METHOD) => '5',
 135            Some(lsp::CompletionItemKind::FUNCTION) => '5',
 136            Some(lsp::CompletionItemKind::CLASS) => '6',
 137            Some(lsp::CompletionItemKind::MODULE) => '7',
 138            _ => '8',
 139        };
 140
 141        item.sort_text = Some(format!(
 142            "{}{}{}",
 143            visibility_priority, kind_priority, item.label
 144        ));
 145    }
 146}
 147
 148pub struct TyLspAdapter {
 149    fs: Arc<dyn Fs>,
 150}
 151
 152#[cfg(target_os = "macos")]
 153impl TyLspAdapter {
 154    const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
 155    const ARCH_SERVER_NAME: &str = "apple-darwin";
 156}
 157
 158#[cfg(target_os = "linux")]
 159impl TyLspAdapter {
 160    const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
 161    const ARCH_SERVER_NAME: &str = "unknown-linux-gnu";
 162}
 163
 164#[cfg(target_os = "freebsd")]
 165impl TyLspAdapter {
 166    const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
 167    const ARCH_SERVER_NAME: &str = "unknown-freebsd";
 168}
 169
 170#[cfg(target_os = "windows")]
 171impl TyLspAdapter {
 172    const GITHUB_ASSET_KIND: AssetKind = AssetKind::Zip;
 173    const ARCH_SERVER_NAME: &str = "pc-windows-msvc";
 174}
 175
 176impl TyLspAdapter {
 177    const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("ty");
 178
 179    pub fn new(fs: Arc<dyn Fs>) -> TyLspAdapter {
 180        TyLspAdapter { fs }
 181    }
 182
 183    fn build_asset_name() -> Result<(String, String)> {
 184        let arch = match consts::ARCH {
 185            "x86" => "i686",
 186            _ => consts::ARCH,
 187        };
 188        let os = Self::ARCH_SERVER_NAME;
 189        let suffix = match consts::OS {
 190            "windows" => "zip",
 191            _ => "tar.gz",
 192        };
 193        let asset_name = format!("ty-{arch}-{os}.{suffix}");
 194        let asset_stem = format!("ty-{arch}-{os}");
 195        Ok((asset_stem, asset_name))
 196    }
 197}
 198
 199#[async_trait(?Send)]
 200impl LspAdapter for TyLspAdapter {
 201    fn name(&self) -> LanguageServerName {
 202        Self::SERVER_NAME
 203    }
 204
 205    async fn label_for_completion(
 206        &self,
 207        item: &lsp::CompletionItem,
 208        language: &Arc<language::Language>,
 209    ) -> Option<language::CodeLabel> {
 210        let label = &item.label;
 211        let label_len = label.len();
 212        let grammar = language.grammar()?;
 213        let highlight_id = match item.kind? {
 214            lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method"),
 215            lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function"),
 216            lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type"),
 217            lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant"),
 218            lsp::CompletionItemKind::VARIABLE => grammar.highlight_id_for_name("variable"),
 219            _ => {
 220                return None;
 221            }
 222        };
 223
 224        let mut text = label.clone();
 225        if let Some(completion_details) = item
 226            .label_details
 227            .as_ref()
 228            .and_then(|details| details.detail.as_ref())
 229        {
 230            write!(&mut text, " {}", completion_details).ok();
 231        }
 232
 233        Some(language::CodeLabel::filtered(
 234            text,
 235            label_len,
 236            item.filter_text.as_deref(),
 237            highlight_id
 238                .map(|id| (0..label_len, id))
 239                .into_iter()
 240                .collect(),
 241        ))
 242    }
 243
 244    async fn workspace_configuration(
 245        self: Arc<Self>,
 246        delegate: &Arc<dyn LspAdapterDelegate>,
 247        toolchain: Option<Toolchain>,
 248        _: Option<Uri>,
 249        cx: &mut AsyncApp,
 250    ) -> Result<Value> {
 251        let mut ret = cx
 252            .update(|cx| {
 253                language_server_settings(delegate.as_ref(), &self.name(), cx)
 254                    .and_then(|s| s.settings.clone())
 255            })
 256            .unwrap_or_else(|| json!({}));
 257        if let Some(toolchain) = toolchain.and_then(|toolchain| {
 258            serde_json::from_value::<PythonToolchainData>(toolchain.as_json).ok()
 259        }) {
 260            _ = maybe!({
 261                let uri =
 262                    url::Url::from_file_path(toolchain.environment.executable.as_ref()?).ok()?;
 263                let sys_prefix = toolchain.environment.prefix.clone()?;
 264                let environment = json!({
 265                    "executable": {
 266                        "uri": uri,
 267                        "sysPrefix": sys_prefix
 268                    }
 269                });
 270                ret.as_object_mut()?
 271                    .entry("pythonExtension")
 272                    .or_insert_with(|| json!({ "activeEnvironment": environment }));
 273                Some(())
 274            });
 275        }
 276        Ok(json!({"ty": ret}))
 277    }
 278}
 279
 280impl LspInstaller for TyLspAdapter {
 281    type BinaryVersion = GitHubLspBinaryVersion;
 282    async fn fetch_latest_server_version(
 283        &self,
 284        delegate: &dyn LspAdapterDelegate,
 285        _: bool,
 286        _: &mut AsyncApp,
 287    ) -> Result<Self::BinaryVersion> {
 288        let release =
 289            latest_github_release("astral-sh/ty", true, false, delegate.http_client()).await?;
 290        let (_, asset_name) = Self::build_asset_name()?;
 291        let asset = release
 292            .assets
 293            .into_iter()
 294            .find(|asset| asset.name == asset_name)
 295            .with_context(|| format!("no asset found matching `{asset_name:?}`"))?;
 296        Ok(GitHubLspBinaryVersion {
 297            name: release.tag_name,
 298            url: asset.browser_download_url,
 299            digest: asset.digest,
 300        })
 301    }
 302
 303    async fn check_if_user_installed(
 304        &self,
 305        delegate: &dyn LspAdapterDelegate,
 306        toolchain: Option<Toolchain>,
 307        _: &AsyncApp,
 308    ) -> Option<LanguageServerBinary> {
 309        let ty_in_venv = if let Some(toolchain) = toolchain
 310            && toolchain.language_name.as_ref() == "Python"
 311        {
 312            Path::new(toolchain.path.as_str())
 313                .parent()
 314                .map(|path| path.join("ty"))
 315        } else {
 316            None
 317        };
 318
 319        for path in ty_in_venv.into_iter().chain(["ty".into()]) {
 320            if let Some(ty_bin) = delegate.which(path.as_os_str()).await {
 321                let env = delegate.shell_env().await;
 322                return Some(LanguageServerBinary {
 323                    path: ty_bin,
 324                    env: Some(env),
 325                    arguments: vec!["server".into()],
 326                });
 327            }
 328        }
 329
 330        None
 331    }
 332
 333    async fn fetch_server_binary(
 334        &self,
 335        latest_version: Self::BinaryVersion,
 336        container_dir: PathBuf,
 337        delegate: &dyn LspAdapterDelegate,
 338    ) -> Result<LanguageServerBinary> {
 339        let GitHubLspBinaryVersion {
 340            name,
 341            url,
 342            digest: expected_digest,
 343        } = latest_version;
 344        let destination_path = container_dir.join(format!("ty-{name}"));
 345
 346        async_fs::create_dir_all(&destination_path).await?;
 347
 348        let server_path = match Self::GITHUB_ASSET_KIND {
 349            AssetKind::TarGz | AssetKind::Gz => destination_path
 350                .join(Self::build_asset_name()?.0)
 351                .join("ty"),
 352            AssetKind::Zip => destination_path.clone().join("ty.exe"),
 353        };
 354
 355        let binary = LanguageServerBinary {
 356            path: server_path.clone(),
 357            env: None,
 358            arguments: vec!["server".into()],
 359        };
 360
 361        let metadata_path = destination_path.with_extension("metadata");
 362        let metadata = GithubBinaryMetadata::read_from_file(&metadata_path)
 363            .await
 364            .ok();
 365        if let Some(metadata) = metadata {
 366            let validity_check = async || {
 367                delegate
 368                    .try_exec(LanguageServerBinary {
 369                        path: server_path.clone(),
 370                        arguments: vec!["--version".into()],
 371                        env: None,
 372                    })
 373                    .await
 374                    .inspect_err(|err| {
 375                        log::warn!("Unable to run {server_path:?} asset, redownloading: {err:#}",)
 376                    })
 377            };
 378            if let (Some(actual_digest), Some(expected_digest)) =
 379                (&metadata.digest, &expected_digest)
 380            {
 381                if actual_digest == expected_digest {
 382                    if validity_check().await.is_ok() {
 383                        return Ok(binary);
 384                    }
 385                } else {
 386                    log::info!(
 387                        "SHA-256 mismatch for {destination_path:?} asset, downloading new asset. Expected: {expected_digest}, Got: {actual_digest}"
 388                    );
 389                }
 390            } else if validity_check().await.is_ok() {
 391                return Ok(binary);
 392            }
 393        }
 394
 395        download_server_binary(
 396            &*delegate.http_client(),
 397            &url,
 398            expected_digest.as_deref(),
 399            &destination_path,
 400            Self::GITHUB_ASSET_KIND,
 401        )
 402        .await?;
 403        make_file_executable(&server_path).await?;
 404        remove_matching(&container_dir, |path| path != destination_path).await;
 405        GithubBinaryMetadata::write_to_file(
 406            &GithubBinaryMetadata {
 407                metadata_version: 1,
 408                digest: expected_digest,
 409            },
 410            &metadata_path,
 411        )
 412        .await?;
 413
 414        Ok(LanguageServerBinary {
 415            path: server_path,
 416            env: None,
 417            arguments: vec!["server".into()],
 418        })
 419    }
 420
 421    async fn cached_server_binary(
 422        &self,
 423        container_dir: PathBuf,
 424        _: &dyn LspAdapterDelegate,
 425    ) -> Option<LanguageServerBinary> {
 426        maybe!(async {
 427            let mut last = None;
 428            let mut entries = self.fs.read_dir(&container_dir).await?;
 429            while let Some(entry) = entries.next().await {
 430                let path = entry?;
 431                if path.extension().is_some_and(|ext| ext == "metadata") {
 432                    continue;
 433                }
 434                last = Some(path);
 435            }
 436
 437            let path = last.context("no cached binary")?;
 438            let path = match TyLspAdapter::GITHUB_ASSET_KIND {
 439                AssetKind::TarGz | AssetKind::Gz => {
 440                    path.join(Self::build_asset_name()?.0).join("ty")
 441                }
 442                AssetKind::Zip => path.join("ty.exe"),
 443            };
 444
 445            anyhow::Ok(LanguageServerBinary {
 446                path,
 447                env: None,
 448                arguments: vec!["server".into()],
 449            })
 450        })
 451        .await
 452        .log_err()
 453    }
 454}
 455
 456pub struct PyrightLspAdapter {
 457    node: NodeRuntime,
 458}
 459
 460impl PyrightLspAdapter {
 461    const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("pyright");
 462    const SERVER_PATH: &str = "node_modules/pyright/langserver.index.js";
 463    const NODE_MODULE_RELATIVE_SERVER_PATH: &str = "pyright/langserver.index.js";
 464
 465    pub fn new(node: NodeRuntime) -> Self {
 466        PyrightLspAdapter { node }
 467    }
 468
 469    async fn get_cached_server_binary(
 470        container_dir: PathBuf,
 471        node: &NodeRuntime,
 472    ) -> Option<LanguageServerBinary> {
 473        let server_path = container_dir.join(Self::SERVER_PATH);
 474        if server_path.exists() {
 475            Some(LanguageServerBinary {
 476                path: node.binary_path().await.log_err()?,
 477                env: None,
 478                arguments: vec![server_path.into(), "--stdio".into()],
 479            })
 480        } else {
 481            log::error!("missing executable in directory {:?}", server_path);
 482            None
 483        }
 484    }
 485}
 486
 487#[async_trait(?Send)]
 488impl LspAdapter for PyrightLspAdapter {
 489    fn name(&self) -> LanguageServerName {
 490        Self::SERVER_NAME
 491    }
 492
 493    async fn initialization_options(
 494        self: Arc<Self>,
 495        _: &Arc<dyn LspAdapterDelegate>,
 496    ) -> Result<Option<Value>> {
 497        // Provide minimal initialization options
 498        // Virtual environment configuration will be handled through workspace configuration
 499        Ok(Some(json!({
 500            "python": {
 501                "analysis": {
 502                    "autoSearchPaths": true,
 503                    "useLibraryCodeForTypes": true,
 504                    "autoImportCompletions": true
 505                }
 506            }
 507        })))
 508    }
 509
 510    async fn process_completions(&self, items: &mut [lsp::CompletionItem]) {
 511        process_pyright_completions(items);
 512    }
 513
 514    async fn label_for_completion(
 515        &self,
 516        item: &lsp::CompletionItem,
 517        language: &Arc<language::Language>,
 518    ) -> Option<language::CodeLabel> {
 519        let label = &item.label;
 520        let label_len = label.len();
 521        let grammar = language.grammar()?;
 522        let highlight_id = match item.kind? {
 523            lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method"),
 524            lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function"),
 525            lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type"),
 526            lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant"),
 527            lsp::CompletionItemKind::VARIABLE => grammar.highlight_id_for_name("variable"),
 528            _ => {
 529                return None;
 530            }
 531        };
 532        let mut text = label.clone();
 533        if let Some(completion_details) = item
 534            .label_details
 535            .as_ref()
 536            .and_then(|details| details.description.as_ref())
 537        {
 538            write!(&mut text, " {}", completion_details).ok();
 539        }
 540        Some(language::CodeLabel::filtered(
 541            text,
 542            label_len,
 543            item.filter_text.as_deref(),
 544            highlight_id
 545                .map(|id| (0..label_len, id))
 546                .into_iter()
 547                .collect(),
 548        ))
 549    }
 550
 551    async fn label_for_symbol(
 552        &self,
 553        name: &str,
 554        kind: lsp::SymbolKind,
 555        language: &Arc<language::Language>,
 556    ) -> Option<language::CodeLabel> {
 557        let (text, filter_range, display_range) = match kind {
 558            lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
 559                let text = format!("def {}():\n", name);
 560                let filter_range = 4..4 + name.len();
 561                let display_range = 0..filter_range.end;
 562                (text, filter_range, display_range)
 563            }
 564            lsp::SymbolKind::CLASS => {
 565                let text = format!("class {}:", name);
 566                let filter_range = 6..6 + name.len();
 567                let display_range = 0..filter_range.end;
 568                (text, filter_range, display_range)
 569            }
 570            lsp::SymbolKind::CONSTANT => {
 571                let text = format!("{} = 0", name);
 572                let filter_range = 0..name.len();
 573                let display_range = 0..filter_range.end;
 574                (text, filter_range, display_range)
 575            }
 576            _ => return None,
 577        };
 578
 579        Some(language::CodeLabel::new(
 580            text[display_range.clone()].to_string(),
 581            filter_range,
 582            language.highlight_text(&text.as_str().into(), display_range),
 583        ))
 584    }
 585
 586    async fn workspace_configuration(
 587        self: Arc<Self>,
 588        adapter: &Arc<dyn LspAdapterDelegate>,
 589        toolchain: Option<Toolchain>,
 590        _: Option<Uri>,
 591        cx: &mut AsyncApp,
 592    ) -> Result<Value> {
 593        Ok(cx.update(move |cx| {
 594            let mut user_settings =
 595                language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
 596                    .and_then(|s| s.settings.clone())
 597                    .unwrap_or_default();
 598
 599            // If we have a detected toolchain, configure Pyright to use it
 600            if let Some(toolchain) = toolchain
 601                && let Ok(env) =
 602                    serde_json::from_value::<PythonToolchainData>(toolchain.as_json.clone())
 603            {
 604                if !user_settings.is_object() {
 605                    user_settings = Value::Object(serde_json::Map::default());
 606                }
 607                let object = user_settings.as_object_mut().unwrap();
 608
 609                let interpreter_path = toolchain.path.to_string();
 610                if let Some(venv_dir) = &env.environment.prefix {
 611                    // Set venvPath and venv at the root level
 612                    // This matches the format of a pyrightconfig.json file
 613                    if let Some(parent) = venv_dir.parent() {
 614                        // Use relative path if the venv is inside the workspace
 615                        let venv_path = if parent == adapter.worktree_root_path() {
 616                            ".".to_string()
 617                        } else {
 618                            parent.to_string_lossy().into_owned()
 619                        };
 620                        object.insert("venvPath".to_string(), Value::String(venv_path));
 621                    }
 622
 623                    if let Some(venv_name) = venv_dir.file_name() {
 624                        object.insert(
 625                            "venv".to_owned(),
 626                            Value::String(venv_name.to_string_lossy().into_owned()),
 627                        );
 628                    }
 629                }
 630
 631                // Always set the python interpreter path
 632                // Get or create the python section
 633                let python = object
 634                    .entry("python")
 635                    .and_modify(|v| {
 636                        if !v.is_object() {
 637                            *v = Value::Object(serde_json::Map::default());
 638                        }
 639                    })
 640                    .or_insert(Value::Object(serde_json::Map::default()));
 641                let python = python.as_object_mut().unwrap();
 642
 643                // Set both pythonPath and defaultInterpreterPath for compatibility
 644                python.insert(
 645                    "pythonPath".to_owned(),
 646                    Value::String(interpreter_path.clone()),
 647                );
 648                python.insert(
 649                    "defaultInterpreterPath".to_owned(),
 650                    Value::String(interpreter_path),
 651                );
 652            }
 653
 654            user_settings
 655        }))
 656    }
 657}
 658
 659impl LspInstaller for PyrightLspAdapter {
 660    type BinaryVersion = Version;
 661
 662    async fn fetch_latest_server_version(
 663        &self,
 664        _: &dyn LspAdapterDelegate,
 665        _: bool,
 666        _: &mut AsyncApp,
 667    ) -> Result<Self::BinaryVersion> {
 668        self.node
 669            .npm_package_latest_version(Self::SERVER_NAME.as_ref())
 670            .await
 671    }
 672
 673    async fn check_if_user_installed(
 674        &self,
 675        delegate: &dyn LspAdapterDelegate,
 676        _: Option<Toolchain>,
 677        _: &AsyncApp,
 678    ) -> Option<LanguageServerBinary> {
 679        if let Some(pyright_bin) = delegate.which("pyright-langserver".as_ref()).await {
 680            let env = delegate.shell_env().await;
 681            Some(LanguageServerBinary {
 682                path: pyright_bin,
 683                env: Some(env),
 684                arguments: vec!["--stdio".into()],
 685            })
 686        } else {
 687            let node = delegate.which("node".as_ref()).await?;
 688            let (node_modules_path, _) = delegate
 689                .npm_package_installed_version(Self::SERVER_NAME.as_ref())
 690                .await
 691                .log_err()??;
 692
 693            let path = node_modules_path.join(Self::NODE_MODULE_RELATIVE_SERVER_PATH);
 694
 695            let env = delegate.shell_env().await;
 696            Some(LanguageServerBinary {
 697                path: node,
 698                env: Some(env),
 699                arguments: vec![path.into(), "--stdio".into()],
 700            })
 701        }
 702    }
 703
 704    async fn fetch_server_binary(
 705        &self,
 706        latest_version: Self::BinaryVersion,
 707        container_dir: PathBuf,
 708        delegate: &dyn LspAdapterDelegate,
 709    ) -> Result<LanguageServerBinary> {
 710        let server_path = container_dir.join(Self::SERVER_PATH);
 711        let latest_version = latest_version.to_string();
 712
 713        self.node
 714            .npm_install_packages(
 715                &container_dir,
 716                &[(Self::SERVER_NAME.as_ref(), latest_version.as_str())],
 717            )
 718            .await?;
 719
 720        let env = delegate.shell_env().await;
 721        Ok(LanguageServerBinary {
 722            path: self.node.binary_path().await?,
 723            env: Some(env),
 724            arguments: vec![server_path.into(), "--stdio".into()],
 725        })
 726    }
 727
 728    async fn check_if_version_installed(
 729        &self,
 730        version: &Self::BinaryVersion,
 731        container_dir: &PathBuf,
 732        delegate: &dyn LspAdapterDelegate,
 733    ) -> Option<LanguageServerBinary> {
 734        let server_path = container_dir.join(Self::SERVER_PATH);
 735
 736        let should_install_language_server = self
 737            .node
 738            .should_install_npm_package(
 739                Self::SERVER_NAME.as_ref(),
 740                &server_path,
 741                container_dir,
 742                VersionStrategy::Latest(version),
 743            )
 744            .await;
 745
 746        if should_install_language_server {
 747            None
 748        } else {
 749            let env = delegate.shell_env().await;
 750            Some(LanguageServerBinary {
 751                path: self.node.binary_path().await.ok()?,
 752                env: Some(env),
 753                arguments: vec![server_path.into(), "--stdio".into()],
 754            })
 755        }
 756    }
 757
 758    async fn cached_server_binary(
 759        &self,
 760        container_dir: PathBuf,
 761        delegate: &dyn LspAdapterDelegate,
 762    ) -> Option<LanguageServerBinary> {
 763        let mut binary = Self::get_cached_server_binary(container_dir, &self.node).await?;
 764        binary.env = Some(delegate.shell_env().await);
 765        Some(binary)
 766    }
 767}
 768
 769pub(crate) struct PythonContextProvider;
 770
 771const PYTHON_TEST_TARGET_TASK_VARIABLE: VariableName =
 772    VariableName::Custom(Cow::Borrowed("PYTHON_TEST_TARGET"));
 773
 774const PYTHON_ACTIVE_TOOLCHAIN_PATH: VariableName =
 775    VariableName::Custom(Cow::Borrowed("PYTHON_ACTIVE_ZED_TOOLCHAIN"));
 776
 777const PYTHON_MODULE_NAME_TASK_VARIABLE: VariableName =
 778    VariableName::Custom(Cow::Borrowed("PYTHON_MODULE_NAME"));
 779
 780impl ContextProvider for PythonContextProvider {
 781    fn build_context(
 782        &self,
 783        variables: &task::TaskVariables,
 784        location: ContextLocation<'_>,
 785        _: Option<HashMap<String, String>>,
 786        toolchains: Arc<dyn LanguageToolchainStore>,
 787        cx: &mut gpui::App,
 788    ) -> Task<Result<task::TaskVariables>> {
 789        let test_target =
 790            match selected_test_runner(location.file_location.buffer.read(cx).file(), cx) {
 791                TestRunner::UNITTEST => self.build_unittest_target(variables),
 792                TestRunner::PYTEST => self.build_pytest_target(variables),
 793            };
 794
 795        let module_target = self.build_module_target(variables);
 796        let location_file = location.file_location.buffer.read(cx).file().cloned();
 797        let worktree_id = location_file.as_ref().map(|f| f.worktree_id(cx));
 798
 799        cx.spawn(async move |cx| {
 800            let active_toolchain = if let Some(worktree_id) = worktree_id {
 801                let file_path = location_file
 802                    .as_ref()
 803                    .and_then(|f| f.path().parent())
 804                    .map(Arc::from)
 805                    .unwrap_or_else(|| RelPath::empty().into());
 806
 807                toolchains
 808                    .active_toolchain(worktree_id, file_path, "Python".into(), cx)
 809                    .await
 810                    .map_or_else(
 811                        || String::from("python3"),
 812                        |toolchain| toolchain.path.to_string(),
 813                    )
 814            } else {
 815                String::from("python3")
 816            };
 817
 818            let toolchain = (PYTHON_ACTIVE_TOOLCHAIN_PATH, active_toolchain);
 819
 820            Ok(task::TaskVariables::from_iter(
 821                test_target
 822                    .into_iter()
 823                    .chain(module_target.into_iter())
 824                    .chain([toolchain]),
 825            ))
 826        })
 827    }
 828
 829    fn associated_tasks(
 830        &self,
 831        file: Option<Arc<dyn language::File>>,
 832        cx: &App,
 833    ) -> Task<Option<TaskTemplates>> {
 834        let test_runner = selected_test_runner(file.as_ref(), cx);
 835
 836        let mut tasks = vec![
 837            // Execute a selection
 838            TaskTemplate {
 839                label: "execute selection".to_owned(),
 840                command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
 841                args: vec![
 842                    "-c".to_owned(),
 843                    VariableName::SelectedText.template_value_with_whitespace(),
 844                ],
 845                cwd: Some(VariableName::WorktreeRoot.template_value()),
 846                ..TaskTemplate::default()
 847            },
 848            // Execute an entire file
 849            TaskTemplate {
 850                label: format!("run '{}'", VariableName::File.template_value()),
 851                command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
 852                args: vec![VariableName::File.template_value_with_whitespace()],
 853                cwd: Some(VariableName::WorktreeRoot.template_value()),
 854                ..TaskTemplate::default()
 855            },
 856            // Execute a file as module
 857            TaskTemplate {
 858                label: format!("run module '{}'", VariableName::File.template_value()),
 859                command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
 860                args: vec![
 861                    "-m".to_owned(),
 862                    PYTHON_MODULE_NAME_TASK_VARIABLE.template_value(),
 863                ],
 864                cwd: Some(VariableName::WorktreeRoot.template_value()),
 865                tags: vec!["python-module-main-method".to_owned()],
 866                ..TaskTemplate::default()
 867            },
 868        ];
 869
 870        tasks.extend(match test_runner {
 871            TestRunner::UNITTEST => {
 872                [
 873                    // Run tests for an entire file
 874                    TaskTemplate {
 875                        label: format!("unittest '{}'", VariableName::File.template_value()),
 876                        command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
 877                        args: vec![
 878                            "-m".to_owned(),
 879                            "unittest".to_owned(),
 880                            VariableName::File.template_value_with_whitespace(),
 881                        ],
 882                        cwd: Some(VariableName::WorktreeRoot.template_value()),
 883                        ..TaskTemplate::default()
 884                    },
 885                    // Run test(s) for a specific target within a file
 886                    TaskTemplate {
 887                        label: "unittest $ZED_CUSTOM_PYTHON_TEST_TARGET".to_owned(),
 888                        command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
 889                        args: vec![
 890                            "-m".to_owned(),
 891                            "unittest".to_owned(),
 892                            PYTHON_TEST_TARGET_TASK_VARIABLE.template_value_with_whitespace(),
 893                        ],
 894                        tags: vec![
 895                            "python-unittest-class".to_owned(),
 896                            "python-unittest-method".to_owned(),
 897                        ],
 898                        cwd: Some(VariableName::WorktreeRoot.template_value()),
 899                        ..TaskTemplate::default()
 900                    },
 901                ]
 902            }
 903            TestRunner::PYTEST => {
 904                [
 905                    // Run tests for an entire file
 906                    TaskTemplate {
 907                        label: format!("pytest '{}'", VariableName::File.template_value()),
 908                        command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
 909                        args: vec![
 910                            "-m".to_owned(),
 911                            "pytest".to_owned(),
 912                            VariableName::File.template_value_with_whitespace(),
 913                        ],
 914                        cwd: Some(VariableName::WorktreeRoot.template_value()),
 915                        ..TaskTemplate::default()
 916                    },
 917                    // Run test(s) for a specific target within a file
 918                    TaskTemplate {
 919                        label: "pytest $ZED_CUSTOM_PYTHON_TEST_TARGET".to_owned(),
 920                        command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
 921                        args: vec![
 922                            "-m".to_owned(),
 923                            "pytest".to_owned(),
 924                            PYTHON_TEST_TARGET_TASK_VARIABLE.template_value_with_whitespace(),
 925                        ],
 926                        cwd: Some(VariableName::WorktreeRoot.template_value()),
 927                        tags: vec![
 928                            "python-pytest-class".to_owned(),
 929                            "python-pytest-method".to_owned(),
 930                        ],
 931                        ..TaskTemplate::default()
 932                    },
 933                ]
 934            }
 935        });
 936
 937        Task::ready(Some(TaskTemplates(tasks)))
 938    }
 939}
 940
 941fn selected_test_runner(location: Option<&Arc<dyn language::File>>, cx: &App) -> TestRunner {
 942    const TEST_RUNNER_VARIABLE: &str = "TEST_RUNNER";
 943    language_settings(Some(LanguageName::new_static("Python")), location, cx)
 944        .tasks
 945        .variables
 946        .get(TEST_RUNNER_VARIABLE)
 947        .and_then(|val| TestRunner::from_str(val).ok())
 948        .unwrap_or(TestRunner::PYTEST)
 949}
 950
 951impl PythonContextProvider {
 952    fn build_unittest_target(
 953        &self,
 954        variables: &task::TaskVariables,
 955    ) -> Option<(VariableName, String)> {
 956        let python_module_name =
 957            python_module_name_from_relative_path(variables.get(&VariableName::RelativeFile)?)?;
 958
 959        let unittest_class_name =
 960            variables.get(&VariableName::Custom(Cow::Borrowed("_unittest_class_name")));
 961
 962        let unittest_method_name = variables.get(&VariableName::Custom(Cow::Borrowed(
 963            "_unittest_method_name",
 964        )));
 965
 966        let unittest_target_str = match (unittest_class_name, unittest_method_name) {
 967            (Some(class_name), Some(method_name)) => {
 968                format!("{python_module_name}.{class_name}.{method_name}")
 969            }
 970            (Some(class_name), None) => format!("{python_module_name}.{class_name}"),
 971            (None, None) => python_module_name,
 972            // should never happen, a TestCase class is the unit of testing
 973            (None, Some(_)) => return None,
 974        };
 975
 976        Some((
 977            PYTHON_TEST_TARGET_TASK_VARIABLE.clone(),
 978            unittest_target_str,
 979        ))
 980    }
 981
 982    fn build_pytest_target(
 983        &self,
 984        variables: &task::TaskVariables,
 985    ) -> Option<(VariableName, String)> {
 986        let file_path = variables.get(&VariableName::RelativeFile)?;
 987
 988        let pytest_class_name =
 989            variables.get(&VariableName::Custom(Cow::Borrowed("_pytest_class_name")));
 990
 991        let pytest_method_name =
 992            variables.get(&VariableName::Custom(Cow::Borrowed("_pytest_method_name")));
 993
 994        let pytest_target_str = match (pytest_class_name, pytest_method_name) {
 995            (Some(class_name), Some(method_name)) => {
 996                format!("{file_path}::{class_name}::{method_name}")
 997            }
 998            (Some(class_name), None) => {
 999                format!("{file_path}::{class_name}")
1000            }
1001            (None, Some(method_name)) => {
1002                format!("{file_path}::{method_name}")
1003            }
1004            (None, None) => file_path.to_string(),
1005        };
1006
1007        Some((PYTHON_TEST_TARGET_TASK_VARIABLE.clone(), pytest_target_str))
1008    }
1009
1010    fn build_module_target(
1011        &self,
1012        variables: &task::TaskVariables,
1013    ) -> Result<(VariableName, String)> {
1014        let python_module_name = variables
1015            .get(&VariableName::RelativeFile)
1016            .and_then(|module| python_module_name_from_relative_path(module))
1017            .unwrap_or_default();
1018
1019        let module_target = (PYTHON_MODULE_NAME_TASK_VARIABLE.clone(), python_module_name);
1020
1021        Ok(module_target)
1022    }
1023}
1024
1025fn python_module_name_from_relative_path(relative_path: &str) -> Option<String> {
1026    let rel_path = RelPath::new(relative_path.as_ref(), PathStyle::local()).ok()?;
1027    let path_with_dots = rel_path.display(PathStyle::Posix).replace('/', ".");
1028    Some(
1029        path_with_dots
1030            .strip_suffix(".py")
1031            .map(ToOwned::to_owned)
1032            .unwrap_or(path_with_dots),
1033    )
1034}
1035
1036fn is_python_env_global(k: &PythonEnvironmentKind) -> bool {
1037    matches!(
1038        k,
1039        PythonEnvironmentKind::Homebrew
1040            | PythonEnvironmentKind::Pyenv
1041            | PythonEnvironmentKind::GlobalPaths
1042            | PythonEnvironmentKind::MacPythonOrg
1043            | PythonEnvironmentKind::MacCommandLineTools
1044            | PythonEnvironmentKind::LinuxGlobal
1045            | PythonEnvironmentKind::MacXCode
1046            | PythonEnvironmentKind::WindowsStore
1047            | PythonEnvironmentKind::WindowsRegistry
1048    )
1049}
1050
1051fn python_env_kind_display(k: &PythonEnvironmentKind) -> &'static str {
1052    match k {
1053        PythonEnvironmentKind::Conda => "Conda",
1054        PythonEnvironmentKind::Pixi => "pixi",
1055        PythonEnvironmentKind::Homebrew => "Homebrew",
1056        PythonEnvironmentKind::Pyenv => "global (Pyenv)",
1057        PythonEnvironmentKind::GlobalPaths => "global",
1058        PythonEnvironmentKind::PyenvVirtualEnv => "Pyenv",
1059        PythonEnvironmentKind::Pipenv => "Pipenv",
1060        PythonEnvironmentKind::Poetry => "Poetry",
1061        PythonEnvironmentKind::MacPythonOrg => "global (Python.org)",
1062        PythonEnvironmentKind::MacCommandLineTools => "global (Command Line Tools for Xcode)",
1063        PythonEnvironmentKind::LinuxGlobal => "global",
1064        PythonEnvironmentKind::MacXCode => "global (Xcode)",
1065        PythonEnvironmentKind::Venv => "venv",
1066        PythonEnvironmentKind::VirtualEnv => "virtualenv",
1067        PythonEnvironmentKind::VirtualEnvWrapper => "virtualenvwrapper",
1068        PythonEnvironmentKind::WindowsStore => "global (Windows Store)",
1069        PythonEnvironmentKind::WindowsRegistry => "global (Windows Registry)",
1070        PythonEnvironmentKind::Uv => "uv",
1071        PythonEnvironmentKind::UvWorkspace => "uv (Workspace)",
1072    }
1073}
1074
1075pub(crate) struct PythonToolchainProvider;
1076
1077static ENV_PRIORITY_LIST: &[PythonEnvironmentKind] = &[
1078    // Prioritize non-Conda environments.
1079    PythonEnvironmentKind::UvWorkspace,
1080    PythonEnvironmentKind::Uv,
1081    PythonEnvironmentKind::Poetry,
1082    PythonEnvironmentKind::Pipenv,
1083    PythonEnvironmentKind::VirtualEnvWrapper,
1084    PythonEnvironmentKind::Venv,
1085    PythonEnvironmentKind::VirtualEnv,
1086    PythonEnvironmentKind::PyenvVirtualEnv,
1087    PythonEnvironmentKind::Pixi,
1088    PythonEnvironmentKind::Conda,
1089    PythonEnvironmentKind::Pyenv,
1090    PythonEnvironmentKind::GlobalPaths,
1091    PythonEnvironmentKind::Homebrew,
1092];
1093
1094fn env_priority(kind: Option<PythonEnvironmentKind>) -> usize {
1095    if let Some(kind) = kind {
1096        ENV_PRIORITY_LIST
1097            .iter()
1098            .position(|blessed_env| blessed_env == &kind)
1099            .unwrap_or(ENV_PRIORITY_LIST.len())
1100    } else {
1101        // Unknown toolchains are less useful than non-blessed ones.
1102        ENV_PRIORITY_LIST.len() + 1
1103    }
1104}
1105
1106/// Return the name of environment declared in <worktree-root/.venv.
1107///
1108/// https://virtualfish.readthedocs.io/en/latest/plugins.html#auto-activation-auto-activation
1109async fn get_worktree_venv_declaration(worktree_root: &Path) -> Option<String> {
1110    let file = async_fs::File::open(worktree_root.join(".venv"))
1111        .await
1112        .ok()?;
1113    let mut venv_name = String::new();
1114    smol::io::BufReader::new(file)
1115        .read_line(&mut venv_name)
1116        .await
1117        .ok()?;
1118    Some(venv_name.trim().to_string())
1119}
1120
1121fn get_venv_parent_dir(env: &PythonEnvironment) -> Option<PathBuf> {
1122    // If global, we aren't a virtual environment
1123    if let Some(kind) = env.kind
1124        && is_python_env_global(&kind)
1125    {
1126        return None;
1127    }
1128
1129    // Check to be sure we are a virtual environment using pet's most generic
1130    // virtual environment type, VirtualEnv
1131    let venv = env
1132        .executable
1133        .as_ref()
1134        .and_then(|p| p.parent())
1135        .and_then(|p| p.parent())
1136        .filter(|p| is_virtualenv_dir(p))?;
1137
1138    venv.parent().map(|parent| parent.to_path_buf())
1139}
1140
1141// How far is this venv from the root of our current project?
1142#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
1143enum SubprojectDistance {
1144    WithinSubproject(Reverse<usize>),
1145    WithinWorktree(Reverse<usize>),
1146    NotInWorktree,
1147}
1148
1149fn wr_distance(
1150    wr: &PathBuf,
1151    subroot_relative_path: &RelPath,
1152    venv: Option<&PathBuf>,
1153) -> SubprojectDistance {
1154    if let Some(venv) = venv
1155        && let Ok(p) = venv.strip_prefix(wr)
1156    {
1157        if subroot_relative_path.components().next().is_some()
1158            && let Ok(distance) = p
1159                .strip_prefix(subroot_relative_path.as_std_path())
1160                .map(|p| p.components().count())
1161        {
1162            SubprojectDistance::WithinSubproject(Reverse(distance))
1163        } else {
1164            SubprojectDistance::WithinWorktree(Reverse(p.components().count()))
1165        }
1166    } else {
1167        SubprojectDistance::NotInWorktree
1168    }
1169}
1170
1171fn micromamba_shell_name(kind: ShellKind) -> &'static str {
1172    match kind {
1173        ShellKind::Csh => "csh",
1174        ShellKind::Fish => "fish",
1175        ShellKind::Nushell => "nu",
1176        ShellKind::PowerShell => "powershell",
1177        ShellKind::Cmd => "cmd.exe",
1178        // default / catch-all:
1179        _ => "posix",
1180    }
1181}
1182
1183#[async_trait]
1184impl ToolchainLister for PythonToolchainProvider {
1185    async fn list(
1186        &self,
1187        worktree_root: PathBuf,
1188        subroot_relative_path: Arc<RelPath>,
1189        project_env: Option<HashMap<String, String>>,
1190        fs: &dyn Fs,
1191    ) -> ToolchainList {
1192        let env = project_env.unwrap_or_default();
1193        let environment = EnvironmentApi::from_env(&env);
1194        let locators = pet::locators::create_locators(
1195            Arc::new(pet_conda::Conda::from(&environment)),
1196            Arc::new(pet_poetry::Poetry::from(&environment)),
1197            &environment,
1198        );
1199        let mut config = Configuration::default();
1200
1201        // `.ancestors()` will yield at least one path, so in case of empty `subroot_relative_path`, we'll just use
1202        // worktree root as the workspace directory.
1203        config.workspace_directories = Some(
1204            subroot_relative_path
1205                .ancestors()
1206                .map(|ancestor| {
1207                    // remove trailing separator as it alters the environment name hash used by Poetry.
1208                    let path = worktree_root.join(ancestor.as_std_path());
1209                    let path_str = path.to_string_lossy();
1210                    if path_str.ends_with(std::path::MAIN_SEPARATOR) && path_str.len() > 1 {
1211                        PathBuf::from(path_str.trim_end_matches(std::path::MAIN_SEPARATOR))
1212                    } else {
1213                        path
1214                    }
1215                })
1216                .collect(),
1217        );
1218        for locator in locators.iter() {
1219            locator.configure(&config);
1220        }
1221
1222        let reporter = pet_reporter::collect::create_reporter();
1223        pet::find::find_and_report_envs(&reporter, config, &locators, &environment, None);
1224
1225        let mut toolchains = reporter
1226            .environments
1227            .lock()
1228            .map_or(Vec::new(), |mut guard| std::mem::take(&mut guard));
1229
1230        let wr = worktree_root;
1231        let wr_venv = get_worktree_venv_declaration(&wr).await;
1232        // Sort detected environments by:
1233        //     environment name matching activation file (<workdir>/.venv)
1234        //     environment project dir matching worktree_root
1235        //     general env priority
1236        //     environment path matching the CONDA_PREFIX env var
1237        //     executable path
1238        toolchains.sort_by(|lhs, rhs| {
1239            // Compare venv names against worktree .venv file
1240            let venv_ordering =
1241                wr_venv
1242                    .as_ref()
1243                    .map_or(Ordering::Equal, |venv| match (&lhs.name, &rhs.name) {
1244                        (Some(l), Some(r)) => (r == venv).cmp(&(l == venv)),
1245                        (Some(l), None) if l == venv => Ordering::Less,
1246                        (None, Some(r)) if r == venv => Ordering::Greater,
1247                        _ => Ordering::Equal,
1248                    });
1249
1250            // Compare project paths against worktree root
1251            let proj_ordering =
1252                || {
1253                    let lhs_project = lhs.project.clone().or_else(|| get_venv_parent_dir(lhs));
1254                    let rhs_project = rhs.project.clone().or_else(|| get_venv_parent_dir(rhs));
1255                    wr_distance(&wr, &subroot_relative_path, lhs_project.as_ref()).cmp(
1256                        &wr_distance(&wr, &subroot_relative_path, rhs_project.as_ref()),
1257                    )
1258                };
1259
1260            // Compare environment priorities
1261            let priority_ordering = || env_priority(lhs.kind).cmp(&env_priority(rhs.kind));
1262
1263            // Compare conda prefixes
1264            let conda_ordering = || {
1265                if lhs.kind == Some(PythonEnvironmentKind::Conda) {
1266                    environment
1267                        .get_env_var("CONDA_PREFIX".to_string())
1268                        .map(|conda_prefix| {
1269                            let is_match = |exe: &Option<PathBuf>| {
1270                                exe.as_ref().is_some_and(|e| e.starts_with(&conda_prefix))
1271                            };
1272                            match (is_match(&lhs.executable), is_match(&rhs.executable)) {
1273                                (true, false) => Ordering::Less,
1274                                (false, true) => Ordering::Greater,
1275                                _ => Ordering::Equal,
1276                            }
1277                        })
1278                        .unwrap_or(Ordering::Equal)
1279                } else {
1280                    Ordering::Equal
1281                }
1282            };
1283
1284            // Compare Python executables
1285            let exe_ordering = || lhs.executable.cmp(&rhs.executable);
1286
1287            venv_ordering
1288                .then_with(proj_ordering)
1289                .then_with(priority_ordering)
1290                .then_with(conda_ordering)
1291                .then_with(exe_ordering)
1292        });
1293
1294        let mut out_toolchains = Vec::new();
1295        for toolchain in toolchains {
1296            let Some(toolchain) = venv_to_toolchain(toolchain, fs).await else {
1297                continue;
1298            };
1299            out_toolchains.push(toolchain);
1300        }
1301        out_toolchains.dedup();
1302        ToolchainList {
1303            toolchains: out_toolchains,
1304            default: None,
1305            groups: Default::default(),
1306        }
1307    }
1308    fn meta(&self) -> ToolchainMetadata {
1309        ToolchainMetadata {
1310            term: SharedString::new_static("Virtual Environment"),
1311            new_toolchain_placeholder: SharedString::new_static(
1312                "A path to the python3 executable within a virtual environment, or path to virtual environment itself",
1313            ),
1314            manifest_name: ManifestName::from(SharedString::new_static("pyproject.toml")),
1315        }
1316    }
1317
1318    async fn resolve(
1319        &self,
1320        path: PathBuf,
1321        env: Option<HashMap<String, String>>,
1322        fs: &dyn Fs,
1323    ) -> anyhow::Result<Toolchain> {
1324        let env = env.unwrap_or_default();
1325        let environment = EnvironmentApi::from_env(&env);
1326        let locators = pet::locators::create_locators(
1327            Arc::new(pet_conda::Conda::from(&environment)),
1328            Arc::new(pet_poetry::Poetry::from(&environment)),
1329            &environment,
1330        );
1331        let toolchain = pet::resolve::resolve_environment(&path, &locators, &environment)
1332            .context("Could not find a virtual environment in provided path")?;
1333        let venv = toolchain.resolved.unwrap_or(toolchain.discovered);
1334        venv_to_toolchain(venv, fs)
1335            .await
1336            .context("Could not convert a venv into a toolchain")
1337    }
1338
1339    fn activation_script(
1340        &self,
1341        toolchain: &Toolchain,
1342        shell: ShellKind,
1343        cx: &App,
1344    ) -> BoxFuture<'static, Vec<String>> {
1345        let settings = TerminalSettings::get_global(cx);
1346        let conda_manager = settings
1347            .detect_venv
1348            .as_option()
1349            .map(|venv| venv.conda_manager)
1350            .unwrap_or(settings::CondaManager::Auto);
1351
1352        let toolchain_clone = toolchain.clone();
1353        Box::pin(async move {
1354            let Ok(toolchain) =
1355                serde_json::from_value::<PythonToolchainData>(toolchain_clone.as_json.clone())
1356            else {
1357                return vec![];
1358            };
1359
1360            log::debug!("(Python) Composing activation script for toolchain {toolchain:?}");
1361
1362            let mut activation_script = vec![];
1363
1364            match toolchain.environment.kind {
1365                Some(PythonEnvironmentKind::Conda) => {
1366                    let Some(manager_info) = &toolchain.environment.manager else {
1367                        return vec![];
1368                    };
1369                    if smol::fs::metadata(&manager_info.executable).await.is_err() {
1370                        return vec![];
1371                    }
1372
1373                    let manager = match conda_manager {
1374                        settings::CondaManager::Conda => "conda",
1375                        settings::CondaManager::Mamba => "mamba",
1376                        settings::CondaManager::Micromamba => "micromamba",
1377                        settings::CondaManager::Auto => toolchain
1378                            .environment
1379                            .manager
1380                            .as_ref()
1381                            .and_then(|m| m.executable.file_name())
1382                            .and_then(|name| name.to_str())
1383                            .filter(|name| matches!(*name, "conda" | "mamba" | "micromamba"))
1384                            .unwrap_or("conda"),
1385                    };
1386
1387                    // Activate micromamba shell in the child shell
1388                    // [required for micromamba]
1389                    if manager == "micromamba" {
1390                        let shell = micromamba_shell_name(shell);
1391                        activation_script
1392                            .push(format!(r#"eval "$({manager} shell hook --shell {shell})""#));
1393                    }
1394
1395                    if let Some(name) = &toolchain.environment.name {
1396                        activation_script.push(format!("{manager} activate {name}"));
1397                    } else {
1398                        activation_script.push(format!("{manager} activate base"));
1399                    }
1400                }
1401                Some(
1402                    PythonEnvironmentKind::Venv
1403                    | PythonEnvironmentKind::VirtualEnv
1404                    | PythonEnvironmentKind::Uv
1405                    | PythonEnvironmentKind::UvWorkspace
1406                    | PythonEnvironmentKind::Poetry,
1407                ) => {
1408                    if let Some(activation_scripts) = &toolchain.activation_scripts {
1409                        if let Some(activate_script_path) = activation_scripts.get(&shell) {
1410                            let activate_keyword = shell.activate_keyword();
1411                            if let Some(quoted) =
1412                                shell.try_quote(&activate_script_path.to_string_lossy())
1413                            {
1414                                activation_script.push(format!("{activate_keyword} {quoted}"));
1415                            }
1416                        }
1417                    }
1418                }
1419                Some(PythonEnvironmentKind::Pyenv) => {
1420                    let Some(manager) = &toolchain.environment.manager else {
1421                        return vec![];
1422                    };
1423                    let version = toolchain.environment.version.as_deref().unwrap_or("system");
1424                    let pyenv = &manager.executable;
1425                    let pyenv = pyenv.display();
1426                    activation_script.extend(match shell {
1427                        ShellKind::Fish => Some(format!("\"{pyenv}\" shell - fish {version}")),
1428                        ShellKind::Posix => Some(format!("\"{pyenv}\" shell - sh {version}")),
1429                        ShellKind::Nushell => Some(format!("^\"{pyenv}\" shell - nu {version}")),
1430                        ShellKind::PowerShell | ShellKind::Pwsh => None,
1431                        ShellKind::Csh => None,
1432                        ShellKind::Tcsh => None,
1433                        ShellKind::Cmd => None,
1434                        ShellKind::Rc => None,
1435                        ShellKind::Xonsh => None,
1436                        ShellKind::Elvish => None,
1437                    })
1438                }
1439                _ => {}
1440            }
1441            activation_script
1442        })
1443    }
1444}
1445
1446async fn venv_to_toolchain(venv: PythonEnvironment, fs: &dyn Fs) -> Option<Toolchain> {
1447    let mut name = String::from("Python");
1448    if let Some(ref version) = venv.version {
1449        _ = write!(name, " {version}");
1450    }
1451
1452    let name_and_kind = match (&venv.name, &venv.kind) {
1453        (Some(name), Some(kind)) => Some(format!("({name}; {})", python_env_kind_display(kind))),
1454        (Some(name), None) => Some(format!("({name})")),
1455        (None, Some(kind)) => Some(format!("({})", python_env_kind_display(kind))),
1456        (None, None) => None,
1457    };
1458
1459    if let Some(nk) = name_and_kind {
1460        _ = write!(name, " {nk}");
1461    }
1462
1463    let mut activation_scripts = HashMap::default();
1464    match venv.kind {
1465        Some(
1466            PythonEnvironmentKind::Venv
1467            | PythonEnvironmentKind::VirtualEnv
1468            | PythonEnvironmentKind::Uv
1469            | PythonEnvironmentKind::UvWorkspace
1470            | PythonEnvironmentKind::Poetry,
1471        ) => resolve_venv_activation_scripts(&venv, fs, &mut activation_scripts).await,
1472        _ => {}
1473    }
1474    let data = PythonToolchainData {
1475        environment: venv,
1476        activation_scripts: Some(activation_scripts),
1477    };
1478
1479    Some(Toolchain {
1480        name: name.into(),
1481        path: data
1482            .environment
1483            .executable
1484            .as_ref()?
1485            .to_str()?
1486            .to_owned()
1487            .into(),
1488        language_name: LanguageName::new_static("Python"),
1489        as_json: serde_json::to_value(data).ok()?,
1490    })
1491}
1492
1493async fn resolve_venv_activation_scripts(
1494    venv: &PythonEnvironment,
1495    fs: &dyn Fs,
1496    activation_scripts: &mut HashMap<ShellKind, PathBuf>,
1497) {
1498    log::debug!("(Python) Resolving activation scripts for venv toolchain {venv:?}");
1499    if let Some(prefix) = &venv.prefix {
1500        for (shell_kind, script_name) in &[
1501            (ShellKind::Posix, "activate"),
1502            (ShellKind::Rc, "activate"),
1503            (ShellKind::Csh, "activate.csh"),
1504            (ShellKind::Tcsh, "activate.csh"),
1505            (ShellKind::Fish, "activate.fish"),
1506            (ShellKind::Nushell, "activate.nu"),
1507            (ShellKind::PowerShell, "activate.ps1"),
1508            (ShellKind::Pwsh, "activate.ps1"),
1509            (ShellKind::Cmd, "activate.bat"),
1510            (ShellKind::Xonsh, "activate.xsh"),
1511        ] {
1512            let path = prefix.join(BINARY_DIR).join(script_name);
1513
1514            log::debug!("Trying path: {}", path.display());
1515
1516            if fs.is_file(&path).await {
1517                activation_scripts.insert(*shell_kind, path);
1518            }
1519        }
1520    }
1521}
1522
1523pub struct EnvironmentApi<'a> {
1524    global_search_locations: Arc<Mutex<Vec<PathBuf>>>,
1525    project_env: &'a HashMap<String, String>,
1526    pet_env: pet_core::os_environment::EnvironmentApi,
1527}
1528
1529impl<'a> EnvironmentApi<'a> {
1530    pub fn from_env(project_env: &'a HashMap<String, String>) -> Self {
1531        let paths = project_env
1532            .get("PATH")
1533            .map(|p| std::env::split_paths(p).collect())
1534            .unwrap_or_default();
1535
1536        EnvironmentApi {
1537            global_search_locations: Arc::new(Mutex::new(paths)),
1538            project_env,
1539            pet_env: pet_core::os_environment::EnvironmentApi::new(),
1540        }
1541    }
1542
1543    fn user_home(&self) -> Option<PathBuf> {
1544        self.project_env
1545            .get("HOME")
1546            .or_else(|| self.project_env.get("USERPROFILE"))
1547            .map(|home| pet_fs::path::norm_case(PathBuf::from(home)))
1548            .or_else(|| self.pet_env.get_user_home())
1549    }
1550}
1551
1552impl pet_core::os_environment::Environment for EnvironmentApi<'_> {
1553    fn get_user_home(&self) -> Option<PathBuf> {
1554        self.user_home()
1555    }
1556
1557    fn get_root(&self) -> Option<PathBuf> {
1558        None
1559    }
1560
1561    fn get_env_var(&self, key: String) -> Option<String> {
1562        self.project_env
1563            .get(&key)
1564            .cloned()
1565            .or_else(|| self.pet_env.get_env_var(key))
1566    }
1567
1568    fn get_know_global_search_locations(&self) -> Vec<PathBuf> {
1569        if self.global_search_locations.lock().is_empty() {
1570            let mut paths = std::env::split_paths(
1571                &self
1572                    .get_env_var("PATH".to_string())
1573                    .or_else(|| self.get_env_var("Path".to_string()))
1574                    .unwrap_or_default(),
1575            )
1576            .collect::<Vec<PathBuf>>();
1577
1578            log::trace!("Env PATH: {:?}", paths);
1579            for p in self.pet_env.get_know_global_search_locations() {
1580                if !paths.contains(&p) {
1581                    paths.push(p);
1582                }
1583            }
1584
1585            let mut paths = paths
1586                .into_iter()
1587                .filter(|p| p.exists())
1588                .collect::<Vec<PathBuf>>();
1589
1590            self.global_search_locations.lock().append(&mut paths);
1591        }
1592        self.global_search_locations.lock().clone()
1593    }
1594}
1595
1596pub(crate) struct PyLspAdapter {
1597    python_venv_base: OnceCell<Result<Arc<Path>, String>>,
1598}
1599impl PyLspAdapter {
1600    const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("pylsp");
1601    pub(crate) fn new() -> Self {
1602        Self {
1603            python_venv_base: OnceCell::new(),
1604        }
1605    }
1606    async fn ensure_venv(delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>> {
1607        let python_path = Self::find_base_python(delegate)
1608            .await
1609            .with_context(|| {
1610                let mut message = "Could not find Python installation for PyLSP".to_owned();
1611                if cfg!(windows){
1612                    message.push_str(". Install Python from the Microsoft Store, or manually from https://www.python.org/downloads/windows.")
1613                }
1614                message
1615            })?;
1616        let work_dir = delegate
1617            .language_server_download_dir(&Self::SERVER_NAME)
1618            .await
1619            .context("Could not get working directory for PyLSP")?;
1620        let mut path = PathBuf::from(work_dir.as_ref());
1621        path.push("pylsp-venv");
1622        if !path.exists() {
1623            util::command::new_smol_command(python_path)
1624                .arg("-m")
1625                .arg("venv")
1626                .arg("pylsp-venv")
1627                .current_dir(work_dir)
1628                .spawn()?
1629                .output()
1630                .await?;
1631        }
1632
1633        Ok(path.into())
1634    }
1635    // Find "baseline", user python version from which we'll create our own venv.
1636    async fn find_base_python(delegate: &dyn LspAdapterDelegate) -> Option<PathBuf> {
1637        for path in ["python3", "python"] {
1638            let Some(path) = delegate.which(path.as_ref()).await else {
1639                continue;
1640            };
1641            // Try to detect situations where `python3` exists but is not a real Python interpreter.
1642            // Notably, on fresh Windows installs, `python3` is a shim that opens the Microsoft Store app
1643            // when run with no arguments, and just fails otherwise.
1644            let Some(output) = new_smol_command(&path)
1645                .args(["-c", "print(1 + 2)"])
1646                .output()
1647                .await
1648                .ok()
1649            else {
1650                continue;
1651            };
1652            if output.stdout.trim_ascii() != b"3" {
1653                continue;
1654            }
1655            return Some(path);
1656        }
1657        None
1658    }
1659
1660    async fn base_venv(&self, delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>, String> {
1661        self.python_venv_base
1662            .get_or_init(move || async move {
1663                Self::ensure_venv(delegate)
1664                    .await
1665                    .map_err(|e| format!("{e}"))
1666            })
1667            .await
1668            .clone()
1669    }
1670}
1671
1672const BINARY_DIR: &str = if cfg!(target_os = "windows") {
1673    "Scripts"
1674} else {
1675    "bin"
1676};
1677
1678#[async_trait(?Send)]
1679impl LspAdapter for PyLspAdapter {
1680    fn name(&self) -> LanguageServerName {
1681        Self::SERVER_NAME
1682    }
1683
1684    async fn process_completions(&self, _items: &mut [lsp::CompletionItem]) {}
1685
1686    async fn label_for_completion(
1687        &self,
1688        item: &lsp::CompletionItem,
1689        language: &Arc<language::Language>,
1690    ) -> Option<language::CodeLabel> {
1691        let label = &item.label;
1692        let label_len = label.len();
1693        let grammar = language.grammar()?;
1694        let highlight_id = match item.kind? {
1695            lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method")?,
1696            lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function")?,
1697            lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type")?,
1698            lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant")?,
1699            _ => return None,
1700        };
1701        Some(language::CodeLabel::filtered(
1702            label.clone(),
1703            label_len,
1704            item.filter_text.as_deref(),
1705            vec![(0..label.len(), highlight_id)],
1706        ))
1707    }
1708
1709    async fn label_for_symbol(
1710        &self,
1711        name: &str,
1712        kind: lsp::SymbolKind,
1713        language: &Arc<language::Language>,
1714    ) -> Option<language::CodeLabel> {
1715        let (text, filter_range, display_range) = match kind {
1716            lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
1717                let text = format!("def {}():\n", name);
1718                let filter_range = 4..4 + name.len();
1719                let display_range = 0..filter_range.end;
1720                (text, filter_range, display_range)
1721            }
1722            lsp::SymbolKind::CLASS => {
1723                let text = format!("class {}:", name);
1724                let filter_range = 6..6 + name.len();
1725                let display_range = 0..filter_range.end;
1726                (text, filter_range, display_range)
1727            }
1728            lsp::SymbolKind::CONSTANT => {
1729                let text = format!("{} = 0", name);
1730                let filter_range = 0..name.len();
1731                let display_range = 0..filter_range.end;
1732                (text, filter_range, display_range)
1733            }
1734            _ => return None,
1735        };
1736        Some(language::CodeLabel::new(
1737            text[display_range.clone()].to_string(),
1738            filter_range,
1739            language.highlight_text(&text.as_str().into(), display_range),
1740        ))
1741    }
1742
1743    async fn workspace_configuration(
1744        self: Arc<Self>,
1745        adapter: &Arc<dyn LspAdapterDelegate>,
1746        toolchain: Option<Toolchain>,
1747        _: Option<Uri>,
1748        cx: &mut AsyncApp,
1749    ) -> Result<Value> {
1750        Ok(cx.update(move |cx| {
1751            let mut user_settings =
1752                language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
1753                    .and_then(|s| s.settings.clone())
1754                    .unwrap_or_else(|| {
1755                        json!({
1756                            "plugins": {
1757                                "pycodestyle": {"enabled": false},
1758                                "rope_autoimport": {"enabled": true, "memory": true},
1759                                "pylsp_mypy": {"enabled": false}
1760                            },
1761                            "rope": {
1762                                "ropeFolder": null
1763                            },
1764                        })
1765                    });
1766
1767            // If user did not explicitly modify their python venv, use one from picker.
1768            if let Some(toolchain) = toolchain {
1769                if !user_settings.is_object() {
1770                    user_settings = Value::Object(serde_json::Map::default());
1771                }
1772                let object = user_settings.as_object_mut().unwrap();
1773                if let Some(python) = object
1774                    .entry("plugins")
1775                    .or_insert(Value::Object(serde_json::Map::default()))
1776                    .as_object_mut()
1777                {
1778                    if let Some(jedi) = python
1779                        .entry("jedi")
1780                        .or_insert(Value::Object(serde_json::Map::default()))
1781                        .as_object_mut()
1782                    {
1783                        jedi.entry("environment".to_string())
1784                            .or_insert_with(|| Value::String(toolchain.path.clone().into()));
1785                    }
1786                    if let Some(pylint) = python
1787                        .entry("pylsp_mypy")
1788                        .or_insert(Value::Object(serde_json::Map::default()))
1789                        .as_object_mut()
1790                    {
1791                        pylint.entry("overrides".to_string()).or_insert_with(|| {
1792                            Value::Array(vec![
1793                                Value::String("--python-executable".into()),
1794                                Value::String(toolchain.path.into()),
1795                                Value::String("--cache-dir=/dev/null".into()),
1796                                Value::Bool(true),
1797                            ])
1798                        });
1799                    }
1800                }
1801            }
1802            user_settings = Value::Object(serde_json::Map::from_iter([(
1803                "pylsp".to_string(),
1804                user_settings,
1805            )]));
1806
1807            user_settings
1808        }))
1809    }
1810}
1811
1812impl LspInstaller for PyLspAdapter {
1813    type BinaryVersion = ();
1814    async fn check_if_user_installed(
1815        &self,
1816        delegate: &dyn LspAdapterDelegate,
1817        toolchain: Option<Toolchain>,
1818        _: &AsyncApp,
1819    ) -> Option<LanguageServerBinary> {
1820        if let Some(pylsp_bin) = delegate.which(Self::SERVER_NAME.as_ref()).await {
1821            let env = delegate.shell_env().await;
1822            Some(LanguageServerBinary {
1823                path: pylsp_bin,
1824                env: Some(env),
1825                arguments: vec![],
1826            })
1827        } else {
1828            let toolchain = toolchain?;
1829            let pylsp_path = Path::new(toolchain.path.as_ref()).parent()?.join("pylsp");
1830            pylsp_path.exists().then(|| LanguageServerBinary {
1831                path: toolchain.path.to_string().into(),
1832                arguments: vec![pylsp_path.into()],
1833                env: None,
1834            })
1835        }
1836    }
1837
1838    async fn fetch_latest_server_version(
1839        &self,
1840        _: &dyn LspAdapterDelegate,
1841        _: bool,
1842        _: &mut AsyncApp,
1843    ) -> Result<()> {
1844        Ok(())
1845    }
1846
1847    async fn fetch_server_binary(
1848        &self,
1849        _: (),
1850        _: PathBuf,
1851        delegate: &dyn LspAdapterDelegate,
1852    ) -> Result<LanguageServerBinary> {
1853        let venv = self.base_venv(delegate).await.map_err(|e| anyhow!(e))?;
1854        let pip_path = venv.join(BINARY_DIR).join("pip3");
1855        ensure!(
1856            util::command::new_smol_command(pip_path.as_path())
1857                .arg("install")
1858                .arg("python-lsp-server[all]")
1859                .arg("--upgrade")
1860                .output()
1861                .await?
1862                .status
1863                .success(),
1864            "python-lsp-server[all] installation failed"
1865        );
1866        ensure!(
1867            util::command::new_smol_command(pip_path)
1868                .arg("install")
1869                .arg("pylsp-mypy")
1870                .arg("--upgrade")
1871                .output()
1872                .await?
1873                .status
1874                .success(),
1875            "pylsp-mypy installation failed"
1876        );
1877        let pylsp = venv.join(BINARY_DIR).join("pylsp");
1878        ensure!(
1879            delegate.which(pylsp.as_os_str()).await.is_some(),
1880            "pylsp installation was incomplete"
1881        );
1882        Ok(LanguageServerBinary {
1883            path: pylsp,
1884            env: None,
1885            arguments: vec![],
1886        })
1887    }
1888
1889    async fn cached_server_binary(
1890        &self,
1891        _: PathBuf,
1892        delegate: &dyn LspAdapterDelegate,
1893    ) -> Option<LanguageServerBinary> {
1894        let venv = self.base_venv(delegate).await.ok()?;
1895        let pylsp = venv.join(BINARY_DIR).join("pylsp");
1896        delegate.which(pylsp.as_os_str()).await?;
1897        Some(LanguageServerBinary {
1898            path: pylsp,
1899            env: None,
1900            arguments: vec![],
1901        })
1902    }
1903}
1904
1905pub(crate) struct BasedPyrightLspAdapter {
1906    node: NodeRuntime,
1907}
1908
1909impl BasedPyrightLspAdapter {
1910    const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("basedpyright");
1911    const BINARY_NAME: &'static str = "basedpyright-langserver";
1912    const SERVER_PATH: &str = "node_modules/basedpyright/langserver.index.js";
1913    const NODE_MODULE_RELATIVE_SERVER_PATH: &str = "basedpyright/langserver.index.js";
1914
1915    pub(crate) fn new(node: NodeRuntime) -> Self {
1916        BasedPyrightLspAdapter { node }
1917    }
1918
1919    async fn get_cached_server_binary(
1920        container_dir: PathBuf,
1921        node: &NodeRuntime,
1922    ) -> Option<LanguageServerBinary> {
1923        let server_path = container_dir.join(Self::SERVER_PATH);
1924        if server_path.exists() {
1925            Some(LanguageServerBinary {
1926                path: node.binary_path().await.log_err()?,
1927                env: None,
1928                arguments: vec![server_path.into(), "--stdio".into()],
1929            })
1930        } else {
1931            log::error!("missing executable in directory {:?}", server_path);
1932            None
1933        }
1934    }
1935}
1936
1937#[async_trait(?Send)]
1938impl LspAdapter for BasedPyrightLspAdapter {
1939    fn name(&self) -> LanguageServerName {
1940        Self::SERVER_NAME
1941    }
1942
1943    async fn initialization_options(
1944        self: Arc<Self>,
1945        _: &Arc<dyn LspAdapterDelegate>,
1946    ) -> Result<Option<Value>> {
1947        // Provide minimal initialization options
1948        // Virtual environment configuration will be handled through workspace configuration
1949        Ok(Some(json!({
1950            "python": {
1951                "analysis": {
1952                    "autoSearchPaths": true,
1953                    "useLibraryCodeForTypes": true,
1954                    "autoImportCompletions": true
1955                }
1956            }
1957        })))
1958    }
1959
1960    async fn process_completions(&self, items: &mut [lsp::CompletionItem]) {
1961        process_pyright_completions(items);
1962    }
1963
1964    async fn label_for_completion(
1965        &self,
1966        item: &lsp::CompletionItem,
1967        language: &Arc<language::Language>,
1968    ) -> Option<language::CodeLabel> {
1969        let label = &item.label;
1970        let label_len = label.len();
1971        let grammar = language.grammar()?;
1972        let highlight_id = match item.kind? {
1973            lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method"),
1974            lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function"),
1975            lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type"),
1976            lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant"),
1977            lsp::CompletionItemKind::VARIABLE => grammar.highlight_id_for_name("variable"),
1978            _ => {
1979                return None;
1980            }
1981        };
1982        let mut text = label.clone();
1983        if let Some(completion_details) = item
1984            .label_details
1985            .as_ref()
1986            .and_then(|details| details.description.as_ref())
1987        {
1988            write!(&mut text, " {}", completion_details).ok();
1989        }
1990        Some(language::CodeLabel::filtered(
1991            text,
1992            label_len,
1993            item.filter_text.as_deref(),
1994            highlight_id
1995                .map(|id| (0..label.len(), id))
1996                .into_iter()
1997                .collect(),
1998        ))
1999    }
2000
2001    async fn label_for_symbol(
2002        &self,
2003        name: &str,
2004        kind: lsp::SymbolKind,
2005        language: &Arc<language::Language>,
2006    ) -> Option<language::CodeLabel> {
2007        let (text, filter_range, display_range) = match kind {
2008            lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
2009                let text = format!("def {}():\n", name);
2010                let filter_range = 4..4 + name.len();
2011                let display_range = 0..filter_range.end;
2012                (text, filter_range, display_range)
2013            }
2014            lsp::SymbolKind::CLASS => {
2015                let text = format!("class {}:", name);
2016                let filter_range = 6..6 + name.len();
2017                let display_range = 0..filter_range.end;
2018                (text, filter_range, display_range)
2019            }
2020            lsp::SymbolKind::CONSTANT => {
2021                let text = format!("{} = 0", name);
2022                let filter_range = 0..name.len();
2023                let display_range = 0..filter_range.end;
2024                (text, filter_range, display_range)
2025            }
2026            _ => return None,
2027        };
2028        Some(language::CodeLabel::new(
2029            text[display_range.clone()].to_string(),
2030            filter_range,
2031            language.highlight_text(&text.as_str().into(), display_range),
2032        ))
2033    }
2034
2035    async fn workspace_configuration(
2036        self: Arc<Self>,
2037        adapter: &Arc<dyn LspAdapterDelegate>,
2038        toolchain: Option<Toolchain>,
2039        _: Option<Uri>,
2040        cx: &mut AsyncApp,
2041    ) -> Result<Value> {
2042        Ok(cx.update(move |cx| {
2043            let mut user_settings =
2044                language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
2045                    .and_then(|s| s.settings.clone())
2046                    .unwrap_or_default();
2047
2048            // If we have a detected toolchain, configure Pyright to use it
2049            if let Some(toolchain) = toolchain
2050                && let Ok(env) = serde_json::from_value::<
2051                    pet_core::python_environment::PythonEnvironment,
2052                >(toolchain.as_json.clone())
2053            {
2054                if !user_settings.is_object() {
2055                    user_settings = Value::Object(serde_json::Map::default());
2056                }
2057                let object = user_settings.as_object_mut().unwrap();
2058
2059                let interpreter_path = toolchain.path.to_string();
2060                if let Some(venv_dir) = env.prefix {
2061                    // Set venvPath and venv at the root level
2062                    // This matches the format of a pyrightconfig.json file
2063                    if let Some(parent) = venv_dir.parent() {
2064                        // Use relative path if the venv is inside the workspace
2065                        let venv_path = if parent == adapter.worktree_root_path() {
2066                            ".".to_string()
2067                        } else {
2068                            parent.to_string_lossy().into_owned()
2069                        };
2070                        object.insert("venvPath".to_string(), Value::String(venv_path));
2071                    }
2072
2073                    if let Some(venv_name) = venv_dir.file_name() {
2074                        object.insert(
2075                            "venv".to_owned(),
2076                            Value::String(venv_name.to_string_lossy().into_owned()),
2077                        );
2078                    }
2079                }
2080
2081                // Set both pythonPath and defaultInterpreterPath for compatibility
2082                if let Some(python) = object
2083                    .entry("python")
2084                    .or_insert(Value::Object(serde_json::Map::default()))
2085                    .as_object_mut()
2086                {
2087                    python.insert(
2088                        "pythonPath".to_owned(),
2089                        Value::String(interpreter_path.clone()),
2090                    );
2091                    python.insert(
2092                        "defaultInterpreterPath".to_owned(),
2093                        Value::String(interpreter_path),
2094                    );
2095                }
2096                // Basedpyright by default uses `strict` type checking, we tone it down as to not surpris users
2097                maybe!({
2098                    let analysis = object
2099                        .entry("basedpyright.analysis")
2100                        .or_insert(Value::Object(serde_json::Map::default()));
2101                    if let serde_json::map::Entry::Vacant(v) =
2102                        analysis.as_object_mut()?.entry("typeCheckingMode")
2103                    {
2104                        v.insert(Value::String("standard".to_owned()));
2105                    }
2106                    Some(())
2107                });
2108                // Disable basedpyright's organizeImports so ruff handles it instead
2109                if let serde_json::map::Entry::Vacant(v) =
2110                    object.entry("basedpyright.disableOrganizeImports")
2111                {
2112                    v.insert(Value::Bool(true));
2113                }
2114            }
2115
2116            user_settings
2117        }))
2118    }
2119}
2120
2121impl LspInstaller for BasedPyrightLspAdapter {
2122    type BinaryVersion = Version;
2123
2124    async fn fetch_latest_server_version(
2125        &self,
2126        _: &dyn LspAdapterDelegate,
2127        _: bool,
2128        _: &mut AsyncApp,
2129    ) -> Result<Self::BinaryVersion> {
2130        self.node
2131            .npm_package_latest_version(Self::SERVER_NAME.as_ref())
2132            .await
2133    }
2134
2135    async fn check_if_user_installed(
2136        &self,
2137        delegate: &dyn LspAdapterDelegate,
2138        _: Option<Toolchain>,
2139        _: &AsyncApp,
2140    ) -> Option<LanguageServerBinary> {
2141        if let Some(path) = delegate.which(Self::BINARY_NAME.as_ref()).await {
2142            let env = delegate.shell_env().await;
2143            Some(LanguageServerBinary {
2144                path,
2145                env: Some(env),
2146                arguments: vec!["--stdio".into()],
2147            })
2148        } else {
2149            // TODO shouldn't this be self.node.binary_path()?
2150            let node = delegate.which("node".as_ref()).await?;
2151            let (node_modules_path, _) = delegate
2152                .npm_package_installed_version(Self::SERVER_NAME.as_ref())
2153                .await
2154                .log_err()??;
2155
2156            let path = node_modules_path.join(Self::NODE_MODULE_RELATIVE_SERVER_PATH);
2157
2158            let env = delegate.shell_env().await;
2159            Some(LanguageServerBinary {
2160                path: node,
2161                env: Some(env),
2162                arguments: vec![path.into(), "--stdio".into()],
2163            })
2164        }
2165    }
2166
2167    async fn fetch_server_binary(
2168        &self,
2169        latest_version: Self::BinaryVersion,
2170        container_dir: PathBuf,
2171        delegate: &dyn LspAdapterDelegate,
2172    ) -> Result<LanguageServerBinary> {
2173        let server_path = container_dir.join(Self::SERVER_PATH);
2174        let latest_version = latest_version.to_string();
2175
2176        self.node
2177            .npm_install_packages(
2178                &container_dir,
2179                &[(Self::SERVER_NAME.as_ref(), latest_version.as_str())],
2180            )
2181            .await?;
2182
2183        let env = delegate.shell_env().await;
2184        Ok(LanguageServerBinary {
2185            path: self.node.binary_path().await?,
2186            env: Some(env),
2187            arguments: vec![server_path.into(), "--stdio".into()],
2188        })
2189    }
2190
2191    async fn check_if_version_installed(
2192        &self,
2193        version: &Self::BinaryVersion,
2194        container_dir: &PathBuf,
2195        delegate: &dyn LspAdapterDelegate,
2196    ) -> Option<LanguageServerBinary> {
2197        let server_path = container_dir.join(Self::SERVER_PATH);
2198
2199        let should_install_language_server = self
2200            .node
2201            .should_install_npm_package(
2202                Self::SERVER_NAME.as_ref(),
2203                &server_path,
2204                container_dir,
2205                VersionStrategy::Latest(version),
2206            )
2207            .await;
2208
2209        if should_install_language_server {
2210            None
2211        } else {
2212            let env = delegate.shell_env().await;
2213            Some(LanguageServerBinary {
2214                path: self.node.binary_path().await.ok()?,
2215                env: Some(env),
2216                arguments: vec![server_path.into(), "--stdio".into()],
2217            })
2218        }
2219    }
2220
2221    async fn cached_server_binary(
2222        &self,
2223        container_dir: PathBuf,
2224        delegate: &dyn LspAdapterDelegate,
2225    ) -> Option<LanguageServerBinary> {
2226        let mut binary = Self::get_cached_server_binary(container_dir, &self.node).await?;
2227        binary.env = Some(delegate.shell_env().await);
2228        Some(binary)
2229    }
2230}
2231
2232pub(crate) struct RuffLspAdapter {
2233    fs: Arc<dyn Fs>,
2234}
2235
2236impl RuffLspAdapter {
2237    fn convert_ruff_schema(raw_schema: &serde_json::Value) -> serde_json::Value {
2238        let Some(schema_object) = raw_schema.as_object() else {
2239            return raw_schema.clone();
2240        };
2241
2242        let mut root_properties = serde_json::Map::new();
2243
2244        for (key, value) in schema_object {
2245            let parts: Vec<&str> = key.split('.').collect();
2246
2247            if parts.is_empty() {
2248                continue;
2249            }
2250
2251            let mut current = &mut root_properties;
2252
2253            for (i, part) in parts.iter().enumerate() {
2254                let is_last = i == parts.len() - 1;
2255
2256                if is_last {
2257                    let mut schema_entry = serde_json::Map::new();
2258
2259                    if let Some(doc) = value.get("doc").and_then(|d| d.as_str()) {
2260                        schema_entry.insert(
2261                            "markdownDescription".to_string(),
2262                            serde_json::Value::String(doc.to_string()),
2263                        );
2264                    }
2265
2266                    if let Some(default_val) = value.get("default") {
2267                        schema_entry.insert("default".to_string(), default_val.clone());
2268                    }
2269
2270                    if let Some(value_type) = value.get("value_type").and_then(|v| v.as_str()) {
2271                        if value_type.contains('|') {
2272                            let enum_values: Vec<serde_json::Value> = value_type
2273                                .split('|')
2274                                .map(|s| s.trim().trim_matches('"'))
2275                                .filter(|s| !s.is_empty())
2276                                .map(|s| serde_json::Value::String(s.to_string()))
2277                                .collect();
2278
2279                            if !enum_values.is_empty() {
2280                                schema_entry
2281                                    .insert("type".to_string(), serde_json::json!("string"));
2282                                schema_entry.insert(
2283                                    "enum".to_string(),
2284                                    serde_json::Value::Array(enum_values),
2285                                );
2286                            }
2287                        } else if value_type.starts_with("list[") {
2288                            schema_entry.insert("type".to_string(), serde_json::json!("array"));
2289                            if let Some(item_type) = value_type
2290                                .strip_prefix("list[")
2291                                .and_then(|s| s.strip_suffix(']'))
2292                            {
2293                                let json_type = match item_type {
2294                                    "str" => "string",
2295                                    "int" => "integer",
2296                                    "bool" => "boolean",
2297                                    _ => "string",
2298                                };
2299                                schema_entry.insert(
2300                                    "items".to_string(),
2301                                    serde_json::json!({"type": json_type}),
2302                                );
2303                            }
2304                        } else if value_type.starts_with("dict[") {
2305                            schema_entry.insert("type".to_string(), serde_json::json!("object"));
2306                        } else {
2307                            let json_type = match value_type {
2308                                "bool" => "boolean",
2309                                "int" | "usize" => "integer",
2310                                "str" => "string",
2311                                _ => "string",
2312                            };
2313                            schema_entry.insert(
2314                                "type".to_string(),
2315                                serde_json::Value::String(json_type.to_string()),
2316                            );
2317                        }
2318                    }
2319
2320                    current.insert(part.to_string(), serde_json::Value::Object(schema_entry));
2321                } else {
2322                    let next_current = current
2323                        .entry(part.to_string())
2324                        .or_insert_with(|| {
2325                            serde_json::json!({
2326                                "type": "object",
2327                                "properties": {}
2328                            })
2329                        })
2330                        .as_object_mut()
2331                        .expect("should be an object")
2332                        .entry("properties")
2333                        .or_insert_with(|| serde_json::json!({}))
2334                        .as_object_mut()
2335                        .expect("properties should be an object");
2336
2337                    current = next_current;
2338                }
2339            }
2340        }
2341
2342        serde_json::json!({
2343            "type": "object",
2344            "properties": root_properties
2345        })
2346    }
2347}
2348
2349#[cfg(target_os = "macos")]
2350impl RuffLspAdapter {
2351    const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
2352    const ARCH_SERVER_NAME: &str = "apple-darwin";
2353}
2354
2355#[cfg(target_os = "linux")]
2356impl RuffLspAdapter {
2357    const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
2358    const ARCH_SERVER_NAME: &str = "unknown-linux-gnu";
2359}
2360
2361#[cfg(target_os = "freebsd")]
2362impl RuffLspAdapter {
2363    const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
2364    const ARCH_SERVER_NAME: &str = "unknown-freebsd";
2365}
2366
2367#[cfg(target_os = "windows")]
2368impl RuffLspAdapter {
2369    const GITHUB_ASSET_KIND: AssetKind = AssetKind::Zip;
2370    const ARCH_SERVER_NAME: &str = "pc-windows-msvc";
2371}
2372
2373impl RuffLspAdapter {
2374    const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("ruff");
2375
2376    pub fn new(fs: Arc<dyn Fs>) -> RuffLspAdapter {
2377        RuffLspAdapter { fs }
2378    }
2379
2380    fn build_asset_name() -> Result<(String, String)> {
2381        let arch = match consts::ARCH {
2382            "x86" => "i686",
2383            _ => consts::ARCH,
2384        };
2385        let os = Self::ARCH_SERVER_NAME;
2386        let suffix = match consts::OS {
2387            "windows" => "zip",
2388            _ => "tar.gz",
2389        };
2390        let asset_name = format!("ruff-{arch}-{os}.{suffix}");
2391        let asset_stem = format!("ruff-{arch}-{os}");
2392        Ok((asset_stem, asset_name))
2393    }
2394}
2395
2396#[async_trait(?Send)]
2397impl LspAdapter for RuffLspAdapter {
2398    fn name(&self) -> LanguageServerName {
2399        Self::SERVER_NAME
2400    }
2401
2402    async fn initialization_options_schema(
2403        self: Arc<Self>,
2404        delegate: &Arc<dyn LspAdapterDelegate>,
2405        cached_binary: OwnedMutexGuard<Option<(bool, LanguageServerBinary)>>,
2406        cx: &mut AsyncApp,
2407    ) -> Option<serde_json::Value> {
2408        let binary = self
2409            .get_language_server_command(
2410                delegate.clone(),
2411                None,
2412                LanguageServerBinaryOptions {
2413                    allow_path_lookup: true,
2414                    allow_binary_download: false,
2415                    pre_release: false,
2416                },
2417                cached_binary,
2418                cx.clone(),
2419            )
2420            .await
2421            .0
2422            .ok()?;
2423
2424        let mut command = util::command::new_smol_command(&binary.path);
2425        command
2426            .args(&["config", "--output-format", "json"])
2427            .stdout(Stdio::piped())
2428            .stderr(Stdio::piped());
2429        let cmd = command
2430            .spawn()
2431            .map_err(|e| log::debug!("failed to spawn command {command:?}: {e}"))
2432            .ok()?;
2433        let output = cmd
2434            .output()
2435            .await
2436            .map_err(|e| log::debug!("failed to execute command {command:?}: {e}"))
2437            .ok()?;
2438        if !output.status.success() {
2439            return None;
2440        }
2441
2442        let raw_schema: serde_json::Value = serde_json::from_slice(output.stdout.as_slice())
2443            .map_err(|e| log::debug!("failed to parse ruff's JSON schema output: {e}"))
2444            .ok()?;
2445
2446        let converted_schema = Self::convert_ruff_schema(&raw_schema);
2447        Some(converted_schema)
2448    }
2449}
2450
2451impl LspInstaller for RuffLspAdapter {
2452    type BinaryVersion = GitHubLspBinaryVersion;
2453    async fn check_if_user_installed(
2454        &self,
2455        delegate: &dyn LspAdapterDelegate,
2456        toolchain: Option<Toolchain>,
2457        _: &AsyncApp,
2458    ) -> Option<LanguageServerBinary> {
2459        let ruff_in_venv = if let Some(toolchain) = toolchain
2460            && toolchain.language_name.as_ref() == "Python"
2461        {
2462            Path::new(toolchain.path.as_str())
2463                .parent()
2464                .map(|path| path.join("ruff"))
2465        } else {
2466            None
2467        };
2468
2469        for path in ruff_in_venv.into_iter().chain(["ruff".into()]) {
2470            if let Some(ruff_bin) = delegate.which(path.as_os_str()).await {
2471                let env = delegate.shell_env().await;
2472                return Some(LanguageServerBinary {
2473                    path: ruff_bin,
2474                    env: Some(env),
2475                    arguments: vec!["server".into()],
2476                });
2477            }
2478        }
2479
2480        None
2481    }
2482
2483    async fn fetch_latest_server_version(
2484        &self,
2485        delegate: &dyn LspAdapterDelegate,
2486        _: bool,
2487        _: &mut AsyncApp,
2488    ) -> Result<GitHubLspBinaryVersion> {
2489        let release =
2490            latest_github_release("astral-sh/ruff", true, false, delegate.http_client()).await?;
2491        let (_, asset_name) = Self::build_asset_name()?;
2492        let asset = release
2493            .assets
2494            .into_iter()
2495            .find(|asset| asset.name == asset_name)
2496            .with_context(|| format!("no asset found matching `{asset_name:?}`"))?;
2497        Ok(GitHubLspBinaryVersion {
2498            name: release.tag_name,
2499            url: asset.browser_download_url,
2500            digest: asset.digest,
2501        })
2502    }
2503
2504    async fn fetch_server_binary(
2505        &self,
2506        latest_version: GitHubLspBinaryVersion,
2507        container_dir: PathBuf,
2508        delegate: &dyn LspAdapterDelegate,
2509    ) -> Result<LanguageServerBinary> {
2510        let GitHubLspBinaryVersion {
2511            name,
2512            url,
2513            digest: expected_digest,
2514        } = latest_version;
2515        let destination_path = container_dir.join(format!("ruff-{name}"));
2516        let server_path = match Self::GITHUB_ASSET_KIND {
2517            AssetKind::TarGz | AssetKind::Gz => destination_path
2518                .join(Self::build_asset_name()?.0)
2519                .join("ruff"),
2520            AssetKind::Zip => destination_path.clone().join("ruff.exe"),
2521        };
2522
2523        let binary = LanguageServerBinary {
2524            path: server_path.clone(),
2525            env: None,
2526            arguments: vec!["server".into()],
2527        };
2528
2529        let metadata_path = destination_path.with_extension("metadata");
2530        let metadata = GithubBinaryMetadata::read_from_file(&metadata_path)
2531            .await
2532            .ok();
2533        if let Some(metadata) = metadata {
2534            let validity_check = async || {
2535                delegate
2536                    .try_exec(LanguageServerBinary {
2537                        path: server_path.clone(),
2538                        arguments: vec!["--version".into()],
2539                        env: None,
2540                    })
2541                    .await
2542                    .inspect_err(|err| {
2543                        log::warn!("Unable to run {server_path:?} asset, redownloading: {err:#}",)
2544                    })
2545            };
2546            if let (Some(actual_digest), Some(expected_digest)) =
2547                (&metadata.digest, &expected_digest)
2548            {
2549                if actual_digest == expected_digest {
2550                    if validity_check().await.is_ok() {
2551                        return Ok(binary);
2552                    }
2553                } else {
2554                    log::info!(
2555                        "SHA-256 mismatch for {destination_path:?} asset, downloading new asset. Expected: {expected_digest}, Got: {actual_digest}"
2556                    );
2557                }
2558            } else if validity_check().await.is_ok() {
2559                return Ok(binary);
2560            }
2561        }
2562
2563        download_server_binary(
2564            &*delegate.http_client(),
2565            &url,
2566            expected_digest.as_deref(),
2567            &destination_path,
2568            Self::GITHUB_ASSET_KIND,
2569        )
2570        .await?;
2571        make_file_executable(&server_path).await?;
2572        remove_matching(&container_dir, |path| path != destination_path).await;
2573        GithubBinaryMetadata::write_to_file(
2574            &GithubBinaryMetadata {
2575                metadata_version: 1,
2576                digest: expected_digest,
2577            },
2578            &metadata_path,
2579        )
2580        .await?;
2581
2582        Ok(LanguageServerBinary {
2583            path: server_path,
2584            env: None,
2585            arguments: vec!["server".into()],
2586        })
2587    }
2588
2589    async fn cached_server_binary(
2590        &self,
2591        container_dir: PathBuf,
2592        _: &dyn LspAdapterDelegate,
2593    ) -> Option<LanguageServerBinary> {
2594        maybe!(async {
2595            let mut last = None;
2596            let mut entries = self.fs.read_dir(&container_dir).await?;
2597            while let Some(entry) = entries.next().await {
2598                let path = entry?;
2599                if path.extension().is_some_and(|ext| ext == "metadata") {
2600                    continue;
2601                }
2602                last = Some(path);
2603            }
2604
2605            let path = last.context("no cached binary")?;
2606            let path = match Self::GITHUB_ASSET_KIND {
2607                AssetKind::TarGz | AssetKind::Gz => {
2608                    path.join(Self::build_asset_name()?.0).join("ruff")
2609                }
2610                AssetKind::Zip => path.join("ruff.exe"),
2611            };
2612
2613            anyhow::Ok(LanguageServerBinary {
2614                path,
2615                env: None,
2616                arguments: vec!["server".into()],
2617            })
2618        })
2619        .await
2620        .log_err()
2621    }
2622}
2623
2624#[cfg(test)]
2625mod tests {
2626    use gpui::{AppContext as _, BorrowAppContext, Context, TestAppContext};
2627    use language::{AutoindentMode, Buffer};
2628    use settings::SettingsStore;
2629    use std::num::NonZeroU32;
2630
2631    use crate::python::python_module_name_from_relative_path;
2632
2633    #[gpui::test]
2634    async fn test_python_autoindent(cx: &mut TestAppContext) {
2635        cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
2636        let language = crate::language("python", tree_sitter_python::LANGUAGE.into());
2637        cx.update(|cx| {
2638            let test_settings = SettingsStore::test(cx);
2639            cx.set_global(test_settings);
2640            cx.update_global::<SettingsStore, _>(|store, cx| {
2641                store.update_user_settings(cx, |s| {
2642                    s.project.all_languages.defaults.tab_size = NonZeroU32::new(2);
2643                });
2644            });
2645        });
2646
2647        cx.new(|cx| {
2648            let mut buffer = Buffer::local("", cx).with_language(language, cx);
2649            let append = |buffer: &mut Buffer, text: &str, cx: &mut Context<Buffer>| {
2650                let ix = buffer.len();
2651                buffer.edit([(ix..ix, text)], Some(AutoindentMode::EachLine), cx);
2652            };
2653
2654            // indent after "def():"
2655            append(&mut buffer, "def a():\n", cx);
2656            assert_eq!(buffer.text(), "def a():\n  ");
2657
2658            // preserve indent after blank line
2659            append(&mut buffer, "\n  ", cx);
2660            assert_eq!(buffer.text(), "def a():\n  \n  ");
2661
2662            // indent after "if"
2663            append(&mut buffer, "if a:\n  ", cx);
2664            assert_eq!(buffer.text(), "def a():\n  \n  if a:\n    ");
2665
2666            // preserve indent after statement
2667            append(&mut buffer, "b()\n", cx);
2668            assert_eq!(buffer.text(), "def a():\n  \n  if a:\n    b()\n    ");
2669
2670            // preserve indent after statement
2671            append(&mut buffer, "else", cx);
2672            assert_eq!(buffer.text(), "def a():\n  \n  if a:\n    b()\n    else");
2673
2674            // dedent "else""
2675            append(&mut buffer, ":", cx);
2676            assert_eq!(buffer.text(), "def a():\n  \n  if a:\n    b()\n  else:");
2677
2678            // indent lines after else
2679            append(&mut buffer, "\n", cx);
2680            assert_eq!(
2681                buffer.text(),
2682                "def a():\n  \n  if a:\n    b()\n  else:\n    "
2683            );
2684
2685            // indent after an open paren. the closing paren is not indented
2686            // because there is another token before it on the same line.
2687            append(&mut buffer, "foo(\n1)", cx);
2688            assert_eq!(
2689                buffer.text(),
2690                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n      1)"
2691            );
2692
2693            // dedent the closing paren if it is shifted to the beginning of the line
2694            let argument_ix = buffer.text().find('1').unwrap();
2695            buffer.edit(
2696                [(argument_ix..argument_ix + 1, "")],
2697                Some(AutoindentMode::EachLine),
2698                cx,
2699            );
2700            assert_eq!(
2701                buffer.text(),
2702                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n    )"
2703            );
2704
2705            // preserve indent after the close paren
2706            append(&mut buffer, "\n", cx);
2707            assert_eq!(
2708                buffer.text(),
2709                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n    )\n    "
2710            );
2711
2712            // manually outdent the last line
2713            let end_whitespace_ix = buffer.len() - 4;
2714            buffer.edit(
2715                [(end_whitespace_ix..buffer.len(), "")],
2716                Some(AutoindentMode::EachLine),
2717                cx,
2718            );
2719            assert_eq!(
2720                buffer.text(),
2721                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n    )\n"
2722            );
2723
2724            // preserve the newly reduced indentation on the next newline
2725            append(&mut buffer, "\n", cx);
2726            assert_eq!(
2727                buffer.text(),
2728                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n    )\n\n"
2729            );
2730
2731            // reset to a for loop statement
2732            let statement = "for i in range(10):\n  print(i)\n";
2733            buffer.edit([(0..buffer.len(), statement)], None, cx);
2734
2735            // insert single line comment after each line
2736            let eol_ixs = statement
2737                .char_indices()
2738                .filter_map(|(ix, c)| if c == '\n' { Some(ix) } else { None })
2739                .collect::<Vec<usize>>();
2740            let editions = eol_ixs
2741                .iter()
2742                .enumerate()
2743                .map(|(i, &eol_ix)| (eol_ix..eol_ix, format!(" # comment {}", i + 1)))
2744                .collect::<Vec<(std::ops::Range<usize>, String)>>();
2745            buffer.edit(editions, Some(AutoindentMode::EachLine), cx);
2746            assert_eq!(
2747                buffer.text(),
2748                "for i in range(10): # comment 1\n  print(i) # comment 2\n"
2749            );
2750
2751            // reset to a simple if statement
2752            buffer.edit([(0..buffer.len(), "if a:\n  b(\n  )")], None, cx);
2753
2754            // dedent "else" on the line after a closing paren
2755            append(&mut buffer, "\n  else:\n", cx);
2756            assert_eq!(buffer.text(), "if a:\n  b(\n  )\nelse:\n  ");
2757
2758            buffer
2759        });
2760    }
2761
2762    #[test]
2763    fn test_python_module_name_from_relative_path() {
2764        assert_eq!(
2765            python_module_name_from_relative_path("foo/bar.py"),
2766            Some("foo.bar".to_string())
2767        );
2768        assert_eq!(
2769            python_module_name_from_relative_path("foo/bar"),
2770            Some("foo.bar".to_string())
2771        );
2772        if cfg!(windows) {
2773            assert_eq!(
2774                python_module_name_from_relative_path("foo\\bar.py"),
2775                Some("foo.bar".to_string())
2776            );
2777            assert_eq!(
2778                python_module_name_from_relative_path("foo\\bar"),
2779                Some("foo.bar".to_string())
2780            );
2781        } else {
2782            assert_eq!(
2783                python_module_name_from_relative_path("foo\\bar.py"),
2784                Some("foo\\bar".to_string())
2785            );
2786            assert_eq!(
2787                python_module_name_from_relative_path("foo\\bar"),
2788                Some("foo\\bar".to_string())
2789            );
2790        }
2791    }
2792
2793    #[test]
2794    fn test_convert_ruff_schema() {
2795        use super::RuffLspAdapter;
2796
2797        let raw_schema = serde_json::json!({
2798            "line-length": {
2799                "doc": "The line length to use when enforcing long-lines violations",
2800                "default": "88",
2801                "value_type": "int",
2802                "scope": null,
2803                "example": "line-length = 120",
2804                "deprecated": null
2805            },
2806            "lint.select": {
2807                "doc": "A list of rule codes or prefixes to enable",
2808                "default": "[\"E4\", \"E7\", \"E9\", \"F\"]",
2809                "value_type": "list[RuleSelector]",
2810                "scope": null,
2811                "example": "select = [\"E4\", \"E7\", \"E9\", \"F\", \"B\", \"Q\"]",
2812                "deprecated": null
2813            },
2814            "lint.isort.case-sensitive": {
2815                "doc": "Sort imports taking into account case sensitivity.",
2816                "default": "false",
2817                "value_type": "bool",
2818                "scope": null,
2819                "example": "case-sensitive = true",
2820                "deprecated": null
2821            },
2822            "format.quote-style": {
2823                "doc": "Configures the preferred quote character for strings.",
2824                "default": "\"double\"",
2825                "value_type": "\"double\" | \"single\" | \"preserve\"",
2826                "scope": null,
2827                "example": "quote-style = \"single\"",
2828                "deprecated": null
2829            }
2830        });
2831
2832        let converted = RuffLspAdapter::convert_ruff_schema(&raw_schema);
2833
2834        assert!(converted.is_object());
2835        assert_eq!(
2836            converted.get("type").and_then(|v| v.as_str()),
2837            Some("object")
2838        );
2839
2840        let properties = converted
2841            .get("properties")
2842            .expect("should have properties")
2843            .as_object()
2844            .expect("properties should be an object");
2845
2846        assert!(properties.contains_key("line-length"));
2847        assert!(properties.contains_key("lint"));
2848        assert!(properties.contains_key("format"));
2849
2850        let line_length = properties
2851            .get("line-length")
2852            .expect("should have line-length")
2853            .as_object()
2854            .expect("line-length should be an object");
2855
2856        assert_eq!(
2857            line_length.get("type").and_then(|v| v.as_str()),
2858            Some("integer")
2859        );
2860        assert_eq!(
2861            line_length.get("default").and_then(|v| v.as_str()),
2862            Some("88")
2863        );
2864
2865        let lint = properties
2866            .get("lint")
2867            .expect("should have lint")
2868            .as_object()
2869            .expect("lint should be an object");
2870
2871        let lint_props = lint
2872            .get("properties")
2873            .expect("lint should have properties")
2874            .as_object()
2875            .expect("lint properties should be an object");
2876
2877        assert!(lint_props.contains_key("select"));
2878        assert!(lint_props.contains_key("isort"));
2879
2880        let select = lint_props.get("select").expect("should have select");
2881        assert_eq!(select.get("type").and_then(|v| v.as_str()), Some("array"));
2882
2883        let isort = lint_props
2884            .get("isort")
2885            .expect("should have isort")
2886            .as_object()
2887            .expect("isort should be an object");
2888
2889        let isort_props = isort
2890            .get("properties")
2891            .expect("isort should have properties")
2892            .as_object()
2893            .expect("isort properties should be an object");
2894
2895        let case_sensitive = isort_props
2896            .get("case-sensitive")
2897            .expect("should have case-sensitive");
2898
2899        assert_eq!(
2900            case_sensitive.get("type").and_then(|v| v.as_str()),
2901            Some("boolean")
2902        );
2903        assert!(case_sensitive.get("markdownDescription").is_some());
2904
2905        let format = properties
2906            .get("format")
2907            .expect("should have format")
2908            .as_object()
2909            .expect("format should be an object");
2910
2911        let format_props = format
2912            .get("properties")
2913            .expect("format should have properties")
2914            .as_object()
2915            .expect("format properties should be an object");
2916
2917        let quote_style = format_props
2918            .get("quote-style")
2919            .expect("should have quote-style");
2920
2921        assert_eq!(
2922            quote_style.get("type").and_then(|v| v.as_str()),
2923            Some("string")
2924        );
2925
2926        let enum_values = quote_style
2927            .get("enum")
2928            .expect("should have enum")
2929            .as_array()
2930            .expect("enum should be an array");
2931
2932        assert_eq!(enum_values.len(), 3);
2933        assert!(enum_values.contains(&serde_json::json!("double")));
2934        assert!(enum_values.contains(&serde_json::json!("single")));
2935        assert!(enum_values.contains(&serde_json::json!("preserve")));
2936    }
2937}