python.rs

   1use anyhow::{Context as _, ensure};
   2use anyhow::{Result, anyhow};
   3use async_trait::async_trait;
   4use collections::HashMap;
   5use gpui::{App, Task};
   6use gpui::{AsyncApp, SharedString};
   7use language::Toolchain;
   8use language::ToolchainList;
   9use language::ToolchainLister;
  10use language::language_settings::language_settings;
  11use language::{ContextLocation, LanguageToolchainStore};
  12use language::{ContextProvider, LspAdapter, LspAdapterDelegate};
  13use language::{LanguageName, ManifestName, ManifestProvider, ManifestQuery};
  14use lsp::LanguageServerBinary;
  15use lsp::LanguageServerName;
  16use node_runtime::{NodeRuntime, VersionStrategy};
  17use pet_core::Configuration;
  18use pet_core::os_environment::Environment;
  19use pet_core::python_environment::PythonEnvironmentKind;
  20use project::Fs;
  21use project::lsp_store::language_server_settings;
  22use serde_json::{Value, json};
  23use smol::lock::OnceCell;
  24use std::cmp::Ordering;
  25
  26use parking_lot::Mutex;
  27use std::str::FromStr;
  28use std::{
  29    any::Any,
  30    borrow::Cow,
  31    ffi::OsString,
  32    fmt::Write,
  33    fs,
  34    io::{self, BufRead},
  35    path::{Path, PathBuf},
  36    sync::Arc,
  37};
  38use task::{TaskTemplate, TaskTemplates, VariableName};
  39use util::ResultExt;
  40
  41pub(crate) struct PyprojectTomlManifestProvider;
  42
  43impl ManifestProvider for PyprojectTomlManifestProvider {
  44    fn name(&self) -> ManifestName {
  45        SharedString::new_static("pyproject.toml").into()
  46    }
  47
  48    fn search(
  49        &self,
  50        ManifestQuery {
  51            path,
  52            depth,
  53            delegate,
  54        }: ManifestQuery,
  55    ) -> Option<Arc<Path>> {
  56        for path in path.ancestors().take(depth) {
  57            let p = path.join("pyproject.toml");
  58            if delegate.exists(&p, Some(false)) {
  59                return Some(path.into());
  60            }
  61        }
  62
  63        None
  64    }
  65}
  66
  67const SERVER_PATH: &str = "node_modules/pyright/langserver.index.js";
  68const NODE_MODULE_RELATIVE_SERVER_PATH: &str = "pyright/langserver.index.js";
  69
  70enum TestRunner {
  71    UNITTEST,
  72    PYTEST,
  73}
  74
  75impl FromStr for TestRunner {
  76    type Err = ();
  77
  78    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
  79        match s {
  80            "unittest" => Ok(Self::UNITTEST),
  81            "pytest" => Ok(Self::PYTEST),
  82            _ => Err(()),
  83        }
  84    }
  85}
  86
  87fn server_binary_arguments(server_path: &Path) -> Vec<OsString> {
  88    vec![server_path.into(), "--stdio".into()]
  89}
  90
  91pub struct PythonLspAdapter {
  92    node: NodeRuntime,
  93}
  94
  95impl PythonLspAdapter {
  96    const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("pyright");
  97
  98    pub fn new(node: NodeRuntime) -> Self {
  99        PythonLspAdapter { node }
 100    }
 101}
 102
 103#[async_trait(?Send)]
 104impl LspAdapter for PythonLspAdapter {
 105    fn name(&self) -> LanguageServerName {
 106        Self::SERVER_NAME.clone()
 107    }
 108
 109    async fn initialization_options(
 110        self: Arc<Self>,
 111        _: &dyn Fs,
 112        _: &Arc<dyn LspAdapterDelegate>,
 113    ) -> Result<Option<Value>> {
 114        // Provide minimal initialization options
 115        // Virtual environment configuration will be handled through workspace configuration
 116        Ok(Some(json!({
 117            "python": {
 118                "analysis": {
 119                    "autoSearchPaths": true,
 120                    "useLibraryCodeForTypes": true,
 121                    "autoImportCompletions": true
 122                }
 123            }
 124        })))
 125    }
 126
 127    async fn check_if_user_installed(
 128        &self,
 129        delegate: &dyn LspAdapterDelegate,
 130        _: Option<Toolchain>,
 131        _: &AsyncApp,
 132    ) -> Option<LanguageServerBinary> {
 133        if let Some(pyright_bin) = delegate.which("pyright-langserver".as_ref()).await {
 134            let env = delegate.shell_env().await;
 135            Some(LanguageServerBinary {
 136                path: pyright_bin,
 137                env: Some(env),
 138                arguments: vec!["--stdio".into()],
 139            })
 140        } else {
 141            let node = delegate.which("node".as_ref()).await?;
 142            let (node_modules_path, _) = delegate
 143                .npm_package_installed_version(Self::SERVER_NAME.as_ref())
 144                .await
 145                .log_err()??;
 146
 147            let path = node_modules_path.join(NODE_MODULE_RELATIVE_SERVER_PATH);
 148
 149            let env = delegate.shell_env().await;
 150            Some(LanguageServerBinary {
 151                path: node,
 152                env: Some(env),
 153                arguments: server_binary_arguments(&path),
 154            })
 155        }
 156    }
 157
 158    async fn fetch_latest_server_version(
 159        &self,
 160        _: &dyn LspAdapterDelegate,
 161    ) -> Result<Box<dyn 'static + Any + Send>> {
 162        Ok(Box::new(
 163            self.node
 164                .npm_package_latest_version(Self::SERVER_NAME.as_ref())
 165                .await?,
 166        ) as Box<_>)
 167    }
 168
 169    async fn fetch_server_binary(
 170        &self,
 171        latest_version: Box<dyn 'static + Send + Any>,
 172        container_dir: PathBuf,
 173        delegate: &dyn LspAdapterDelegate,
 174    ) -> Result<LanguageServerBinary> {
 175        let latest_version = latest_version.downcast::<String>().unwrap();
 176        let server_path = container_dir.join(SERVER_PATH);
 177
 178        self.node
 179            .npm_install_packages(
 180                &container_dir,
 181                &[(Self::SERVER_NAME.as_ref(), latest_version.as_str())],
 182            )
 183            .await?;
 184
 185        let env = delegate.shell_env().await;
 186        Ok(LanguageServerBinary {
 187            path: self.node.binary_path().await?,
 188            env: Some(env),
 189            arguments: server_binary_arguments(&server_path),
 190        })
 191    }
 192
 193    async fn check_if_version_installed(
 194        &self,
 195        version: &(dyn 'static + Send + Any),
 196        container_dir: &PathBuf,
 197        delegate: &dyn LspAdapterDelegate,
 198    ) -> Option<LanguageServerBinary> {
 199        let version = version.downcast_ref::<String>().unwrap();
 200        let server_path = container_dir.join(SERVER_PATH);
 201
 202        let should_install_language_server = self
 203            .node
 204            .should_install_npm_package(
 205                Self::SERVER_NAME.as_ref(),
 206                &server_path,
 207                container_dir,
 208                VersionStrategy::Latest(version),
 209            )
 210            .await;
 211
 212        if should_install_language_server {
 213            None
 214        } else {
 215            let env = delegate.shell_env().await;
 216            Some(LanguageServerBinary {
 217                path: self.node.binary_path().await.ok()?,
 218                env: Some(env),
 219                arguments: server_binary_arguments(&server_path),
 220            })
 221        }
 222    }
 223
 224    async fn cached_server_binary(
 225        &self,
 226        container_dir: PathBuf,
 227        delegate: &dyn LspAdapterDelegate,
 228    ) -> Option<LanguageServerBinary> {
 229        let mut binary = get_cached_server_binary(container_dir, &self.node).await?;
 230        binary.env = Some(delegate.shell_env().await);
 231        Some(binary)
 232    }
 233
 234    async fn process_completions(&self, items: &mut [lsp::CompletionItem]) {
 235        // Pyright assigns each completion item a `sortText` of the form `XX.YYYY.name`.
 236        // Where `XX` is the sorting category, `YYYY` is based on most recent usage,
 237        // and `name` is the symbol name itself.
 238        //
 239        // Because the symbol name is included, there generally are not ties when
 240        // sorting by the `sortText`, so the symbol's fuzzy match score is not taken
 241        // into account. Here, we remove the symbol name from the sortText in order
 242        // to allow our own fuzzy score to be used to break ties.
 243        //
 244        // see https://github.com/microsoft/pyright/blob/95ef4e103b9b2f129c9320427e51b73ea7cf78bd/packages/pyright-internal/src/languageService/completionProvider.ts#LL2873
 245        for item in items {
 246            let Some(sort_text) = &mut item.sort_text else {
 247                continue;
 248            };
 249            let mut parts = sort_text.split('.');
 250            let Some(first) = parts.next() else { continue };
 251            let Some(second) = parts.next() else { continue };
 252            let Some(_) = parts.next() else { continue };
 253            sort_text.replace_range(first.len() + second.len() + 1.., "");
 254        }
 255    }
 256
 257    async fn label_for_completion(
 258        &self,
 259        item: &lsp::CompletionItem,
 260        language: &Arc<language::Language>,
 261    ) -> Option<language::CodeLabel> {
 262        let label = &item.label;
 263        let grammar = language.grammar()?;
 264        let highlight_id = match item.kind? {
 265            lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method")?,
 266            lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function")?,
 267            lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type")?,
 268            lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant")?,
 269            _ => return None,
 270        };
 271        let filter_range = item
 272            .filter_text
 273            .as_deref()
 274            .and_then(|filter| label.find(filter).map(|ix| ix..ix + filter.len()))
 275            .unwrap_or(0..label.len());
 276        Some(language::CodeLabel {
 277            text: label.clone(),
 278            runs: vec![(0..label.len(), highlight_id)],
 279            filter_range,
 280        })
 281    }
 282
 283    async fn label_for_symbol(
 284        &self,
 285        name: &str,
 286        kind: lsp::SymbolKind,
 287        language: &Arc<language::Language>,
 288    ) -> Option<language::CodeLabel> {
 289        let (text, filter_range, display_range) = match kind {
 290            lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
 291                let text = format!("def {}():\n", name);
 292                let filter_range = 4..4 + name.len();
 293                let display_range = 0..filter_range.end;
 294                (text, filter_range, display_range)
 295            }
 296            lsp::SymbolKind::CLASS => {
 297                let text = format!("class {}:", name);
 298                let filter_range = 6..6 + name.len();
 299                let display_range = 0..filter_range.end;
 300                (text, filter_range, display_range)
 301            }
 302            lsp::SymbolKind::CONSTANT => {
 303                let text = format!("{} = 0", name);
 304                let filter_range = 0..name.len();
 305                let display_range = 0..filter_range.end;
 306                (text, filter_range, display_range)
 307            }
 308            _ => return None,
 309        };
 310
 311        Some(language::CodeLabel {
 312            runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
 313            text: text[display_range].to_string(),
 314            filter_range,
 315        })
 316    }
 317
 318    async fn workspace_configuration(
 319        self: Arc<Self>,
 320        _: &dyn Fs,
 321        adapter: &Arc<dyn LspAdapterDelegate>,
 322        toolchain: Option<Toolchain>,
 323        cx: &mut AsyncApp,
 324    ) -> Result<Value> {
 325        cx.update(move |cx| {
 326            let mut user_settings =
 327                language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
 328                    .and_then(|s| s.settings.clone())
 329                    .unwrap_or_default();
 330
 331            // If we have a detected toolchain, configure Pyright to use it
 332            if let Some(toolchain) = toolchain {
 333                if user_settings.is_null() {
 334                    user_settings = Value::Object(serde_json::Map::default());
 335                }
 336                let object = user_settings.as_object_mut().unwrap();
 337
 338                let interpreter_path = toolchain.path.to_string();
 339
 340                // Detect if this is a virtual environment
 341                if let Some(interpreter_dir) = Path::new(&interpreter_path).parent()
 342                    && let Some(venv_dir) = interpreter_dir.parent() {
 343                        // Check if this looks like a virtual environment
 344                        if venv_dir.join("pyvenv.cfg").exists()
 345                            || venv_dir.join("bin/activate").exists()
 346                            || venv_dir.join("Scripts/activate.bat").exists()
 347                        {
 348                            // Set venvPath and venv at the root level
 349                            // This matches the format of a pyrightconfig.json file
 350                            if let Some(parent) = venv_dir.parent() {
 351                                // Use relative path if the venv is inside the workspace
 352                                let venv_path = if parent == adapter.worktree_root_path() {
 353                                    ".".to_string()
 354                                } else {
 355                                    parent.to_string_lossy().into_owned()
 356                                };
 357                                object.insert("venvPath".to_string(), Value::String(venv_path));
 358                            }
 359
 360                            if let Some(venv_name) = venv_dir.file_name() {
 361                                object.insert(
 362                                    "venv".to_owned(),
 363                                    Value::String(venv_name.to_string_lossy().into_owned()),
 364                                );
 365                            }
 366                        }
 367                    }
 368
 369                // Always set the python interpreter path
 370                // Get or create the python section
 371                let python = object
 372                    .entry("python")
 373                    .or_insert(Value::Object(serde_json::Map::default()))
 374                    .as_object_mut()
 375                    .unwrap();
 376
 377                // Set both pythonPath and defaultInterpreterPath for compatibility
 378                python.insert(
 379                    "pythonPath".to_owned(),
 380                    Value::String(interpreter_path.clone()),
 381                );
 382                python.insert(
 383                    "defaultInterpreterPath".to_owned(),
 384                    Value::String(interpreter_path),
 385                );
 386            }
 387
 388            user_settings
 389        })
 390    }
 391}
 392
 393async fn get_cached_server_binary(
 394    container_dir: PathBuf,
 395    node: &NodeRuntime,
 396) -> Option<LanguageServerBinary> {
 397    let server_path = container_dir.join(SERVER_PATH);
 398    if server_path.exists() {
 399        Some(LanguageServerBinary {
 400            path: node.binary_path().await.log_err()?,
 401            env: None,
 402            arguments: server_binary_arguments(&server_path),
 403        })
 404    } else {
 405        log::error!("missing executable in directory {:?}", server_path);
 406        None
 407    }
 408}
 409
 410pub(crate) struct PythonContextProvider;
 411
 412const PYTHON_TEST_TARGET_TASK_VARIABLE: VariableName =
 413    VariableName::Custom(Cow::Borrowed("PYTHON_TEST_TARGET"));
 414
 415const PYTHON_ACTIVE_TOOLCHAIN_PATH: VariableName =
 416    VariableName::Custom(Cow::Borrowed("PYTHON_ACTIVE_ZED_TOOLCHAIN"));
 417
 418const PYTHON_ACTIVE_TOOLCHAIN_PATH_RAW: VariableName =
 419    VariableName::Custom(Cow::Borrowed("PYTHON_ACTIVE_ZED_TOOLCHAIN_RAW"));
 420
 421const PYTHON_MODULE_NAME_TASK_VARIABLE: VariableName =
 422    VariableName::Custom(Cow::Borrowed("PYTHON_MODULE_NAME"));
 423
 424impl ContextProvider for PythonContextProvider {
 425    fn build_context(
 426        &self,
 427        variables: &task::TaskVariables,
 428        location: ContextLocation<'_>,
 429        _: Option<HashMap<String, String>>,
 430        toolchains: Arc<dyn LanguageToolchainStore>,
 431        cx: &mut gpui::App,
 432    ) -> Task<Result<task::TaskVariables>> {
 433        let test_target =
 434            match selected_test_runner(location.file_location.buffer.read(cx).file(), cx) {
 435                TestRunner::UNITTEST => self.build_unittest_target(variables),
 436                TestRunner::PYTEST => self.build_pytest_target(variables),
 437            };
 438
 439        let module_target = self.build_module_target(variables);
 440        let location_file = location.file_location.buffer.read(cx).file().cloned();
 441        let worktree_id = location_file.as_ref().map(|f| f.worktree_id(cx));
 442
 443        cx.spawn(async move |cx| {
 444            let raw_toolchain = if let Some(worktree_id) = worktree_id {
 445                let file_path = location_file
 446                    .as_ref()
 447                    .and_then(|f| f.path().parent())
 448                    .map(Arc::from)
 449                    .unwrap_or_else(|| Arc::from("".as_ref()));
 450
 451                toolchains
 452                    .active_toolchain(worktree_id, file_path, "Python".into(), cx)
 453                    .await
 454                    .map_or_else(
 455                        || String::from("python3"),
 456                        |toolchain| toolchain.path.to_string(),
 457                    )
 458            } else {
 459                String::from("python3")
 460            };
 461
 462            let active_toolchain = format!("\"{raw_toolchain}\"");
 463            let toolchain = (PYTHON_ACTIVE_TOOLCHAIN_PATH, active_toolchain);
 464            let raw_toolchain_var = (PYTHON_ACTIVE_TOOLCHAIN_PATH_RAW, raw_toolchain);
 465
 466            Ok(task::TaskVariables::from_iter(
 467                test_target
 468                    .into_iter()
 469                    .chain(module_target.into_iter())
 470                    .chain([toolchain, raw_toolchain_var]),
 471            ))
 472        })
 473    }
 474
 475    fn associated_tasks(
 476        &self,
 477        _: Arc<dyn Fs>,
 478        file: Option<Arc<dyn language::File>>,
 479        cx: &App,
 480    ) -> Task<Option<TaskTemplates>> {
 481        let test_runner = selected_test_runner(file.as_ref(), cx);
 482
 483        let mut tasks = vec![
 484            // Execute a selection
 485            TaskTemplate {
 486                label: "execute selection".to_owned(),
 487                command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
 488                args: vec![
 489                    "-c".to_owned(),
 490                    VariableName::SelectedText.template_value_with_whitespace(),
 491                ],
 492                cwd: Some("$ZED_WORKTREE_ROOT".into()),
 493                ..TaskTemplate::default()
 494            },
 495            // Execute an entire file
 496            TaskTemplate {
 497                label: format!("run '{}'", VariableName::File.template_value()),
 498                command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
 499                args: vec![VariableName::File.template_value_with_whitespace()],
 500                cwd: Some("$ZED_WORKTREE_ROOT".into()),
 501                ..TaskTemplate::default()
 502            },
 503            // Execute a file as module
 504            TaskTemplate {
 505                label: format!("run module '{}'", VariableName::File.template_value()),
 506                command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
 507                args: vec![
 508                    "-m".to_owned(),
 509                    PYTHON_MODULE_NAME_TASK_VARIABLE.template_value(),
 510                ],
 511                cwd: Some("$ZED_WORKTREE_ROOT".into()),
 512                tags: vec!["python-module-main-method".to_owned()],
 513                ..TaskTemplate::default()
 514            },
 515        ];
 516
 517        tasks.extend(match test_runner {
 518            TestRunner::UNITTEST => {
 519                [
 520                    // Run tests for an entire file
 521                    TaskTemplate {
 522                        label: format!("unittest '{}'", VariableName::File.template_value()),
 523                        command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
 524                        args: vec![
 525                            "-m".to_owned(),
 526                            "unittest".to_owned(),
 527                            VariableName::File.template_value_with_whitespace(),
 528                        ],
 529                        cwd: Some("$ZED_WORKTREE_ROOT".into()),
 530                        ..TaskTemplate::default()
 531                    },
 532                    // Run test(s) for a specific target within a file
 533                    TaskTemplate {
 534                        label: "unittest $ZED_CUSTOM_PYTHON_TEST_TARGET".to_owned(),
 535                        command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
 536                        args: vec![
 537                            "-m".to_owned(),
 538                            "unittest".to_owned(),
 539                            PYTHON_TEST_TARGET_TASK_VARIABLE.template_value_with_whitespace(),
 540                        ],
 541                        tags: vec![
 542                            "python-unittest-class".to_owned(),
 543                            "python-unittest-method".to_owned(),
 544                        ],
 545                        cwd: Some("$ZED_WORKTREE_ROOT".into()),
 546                        ..TaskTemplate::default()
 547                    },
 548                ]
 549            }
 550            TestRunner::PYTEST => {
 551                [
 552                    // Run tests for an entire file
 553                    TaskTemplate {
 554                        label: format!("pytest '{}'", VariableName::File.template_value()),
 555                        command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
 556                        args: vec![
 557                            "-m".to_owned(),
 558                            "pytest".to_owned(),
 559                            VariableName::File.template_value_with_whitespace(),
 560                        ],
 561                        cwd: Some("$ZED_WORKTREE_ROOT".into()),
 562                        ..TaskTemplate::default()
 563                    },
 564                    // Run test(s) for a specific target within a file
 565                    TaskTemplate {
 566                        label: "pytest $ZED_CUSTOM_PYTHON_TEST_TARGET".to_owned(),
 567                        command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
 568                        args: vec![
 569                            "-m".to_owned(),
 570                            "pytest".to_owned(),
 571                            PYTHON_TEST_TARGET_TASK_VARIABLE.template_value_with_whitespace(),
 572                        ],
 573                        cwd: Some("$ZED_WORKTREE_ROOT".into()),
 574                        tags: vec![
 575                            "python-pytest-class".to_owned(),
 576                            "python-pytest-method".to_owned(),
 577                        ],
 578                        ..TaskTemplate::default()
 579                    },
 580                ]
 581            }
 582        });
 583
 584        Task::ready(Some(TaskTemplates(tasks)))
 585    }
 586}
 587
 588fn selected_test_runner(location: Option<&Arc<dyn language::File>>, cx: &App) -> TestRunner {
 589    const TEST_RUNNER_VARIABLE: &str = "TEST_RUNNER";
 590    language_settings(Some(LanguageName::new("Python")), location, cx)
 591        .tasks
 592        .variables
 593        .get(TEST_RUNNER_VARIABLE)
 594        .and_then(|val| TestRunner::from_str(val).ok())
 595        .unwrap_or(TestRunner::PYTEST)
 596}
 597
 598impl PythonContextProvider {
 599    fn build_unittest_target(
 600        &self,
 601        variables: &task::TaskVariables,
 602    ) -> Option<(VariableName, String)> {
 603        let python_module_name =
 604            python_module_name_from_relative_path(variables.get(&VariableName::RelativeFile)?);
 605
 606        let unittest_class_name =
 607            variables.get(&VariableName::Custom(Cow::Borrowed("_unittest_class_name")));
 608
 609        let unittest_method_name = variables.get(&VariableName::Custom(Cow::Borrowed(
 610            "_unittest_method_name",
 611        )));
 612
 613        let unittest_target_str = match (unittest_class_name, unittest_method_name) {
 614            (Some(class_name), Some(method_name)) => {
 615                format!("{python_module_name}.{class_name}.{method_name}")
 616            }
 617            (Some(class_name), None) => format!("{python_module_name}.{class_name}"),
 618            (None, None) => python_module_name,
 619            // should never happen, a TestCase class is the unit of testing
 620            (None, Some(_)) => return None,
 621        };
 622
 623        Some((
 624            PYTHON_TEST_TARGET_TASK_VARIABLE.clone(),
 625            unittest_target_str,
 626        ))
 627    }
 628
 629    fn build_pytest_target(
 630        &self,
 631        variables: &task::TaskVariables,
 632    ) -> Option<(VariableName, String)> {
 633        let file_path = variables.get(&VariableName::RelativeFile)?;
 634
 635        let pytest_class_name =
 636            variables.get(&VariableName::Custom(Cow::Borrowed("_pytest_class_name")));
 637
 638        let pytest_method_name =
 639            variables.get(&VariableName::Custom(Cow::Borrowed("_pytest_method_name")));
 640
 641        let pytest_target_str = match (pytest_class_name, pytest_method_name) {
 642            (Some(class_name), Some(method_name)) => {
 643                format!("{file_path}::{class_name}::{method_name}")
 644            }
 645            (Some(class_name), None) => {
 646                format!("{file_path}::{class_name}")
 647            }
 648            (None, Some(method_name)) => {
 649                format!("{file_path}::{method_name}")
 650            }
 651            (None, None) => file_path.to_string(),
 652        };
 653
 654        Some((PYTHON_TEST_TARGET_TASK_VARIABLE.clone(), pytest_target_str))
 655    }
 656
 657    fn build_module_target(
 658        &self,
 659        variables: &task::TaskVariables,
 660    ) -> Result<(VariableName, String)> {
 661        let python_module_name = python_module_name_from_relative_path(
 662            variables.get(&VariableName::RelativeFile).unwrap_or(""),
 663        );
 664
 665        let module_target = (PYTHON_MODULE_NAME_TASK_VARIABLE.clone(), python_module_name);
 666
 667        Ok(module_target)
 668    }
 669}
 670
 671fn python_module_name_from_relative_path(relative_path: &str) -> String {
 672    let path_with_dots = relative_path.replace('/', ".");
 673    path_with_dots
 674        .strip_suffix(".py")
 675        .unwrap_or(&path_with_dots)
 676        .to_string()
 677}
 678
 679fn python_env_kind_display(k: &PythonEnvironmentKind) -> &'static str {
 680    match k {
 681        PythonEnvironmentKind::Conda => "Conda",
 682        PythonEnvironmentKind::Pixi => "pixi",
 683        PythonEnvironmentKind::Homebrew => "Homebrew",
 684        PythonEnvironmentKind::Pyenv => "global (Pyenv)",
 685        PythonEnvironmentKind::GlobalPaths => "global",
 686        PythonEnvironmentKind::PyenvVirtualEnv => "Pyenv",
 687        PythonEnvironmentKind::Pipenv => "Pipenv",
 688        PythonEnvironmentKind::Poetry => "Poetry",
 689        PythonEnvironmentKind::MacPythonOrg => "global (Python.org)",
 690        PythonEnvironmentKind::MacCommandLineTools => "global (Command Line Tools for Xcode)",
 691        PythonEnvironmentKind::LinuxGlobal => "global",
 692        PythonEnvironmentKind::MacXCode => "global (Xcode)",
 693        PythonEnvironmentKind::Venv => "venv",
 694        PythonEnvironmentKind::VirtualEnv => "virtualenv",
 695        PythonEnvironmentKind::VirtualEnvWrapper => "virtualenvwrapper",
 696        PythonEnvironmentKind::WindowsStore => "global (Windows Store)",
 697        PythonEnvironmentKind::WindowsRegistry => "global (Windows Registry)",
 698    }
 699}
 700
 701pub(crate) struct PythonToolchainProvider {
 702    term: SharedString,
 703}
 704
 705impl Default for PythonToolchainProvider {
 706    fn default() -> Self {
 707        Self {
 708            term: SharedString::new_static("Virtual Environment"),
 709        }
 710    }
 711}
 712
 713static ENV_PRIORITY_LIST: &'static [PythonEnvironmentKind] = &[
 714    // Prioritize non-Conda environments.
 715    PythonEnvironmentKind::Poetry,
 716    PythonEnvironmentKind::Pipenv,
 717    PythonEnvironmentKind::VirtualEnvWrapper,
 718    PythonEnvironmentKind::Venv,
 719    PythonEnvironmentKind::VirtualEnv,
 720    PythonEnvironmentKind::PyenvVirtualEnv,
 721    PythonEnvironmentKind::Pixi,
 722    PythonEnvironmentKind::Conda,
 723    PythonEnvironmentKind::Pyenv,
 724    PythonEnvironmentKind::GlobalPaths,
 725    PythonEnvironmentKind::Homebrew,
 726];
 727
 728fn env_priority(kind: Option<PythonEnvironmentKind>) -> usize {
 729    if let Some(kind) = kind {
 730        ENV_PRIORITY_LIST
 731            .iter()
 732            .position(|blessed_env| blessed_env == &kind)
 733            .unwrap_or(ENV_PRIORITY_LIST.len())
 734    } else {
 735        // Unknown toolchains are less useful than non-blessed ones.
 736        ENV_PRIORITY_LIST.len() + 1
 737    }
 738}
 739
 740/// Return the name of environment declared in <worktree-root/.venv.
 741///
 742/// https://virtualfish.readthedocs.io/en/latest/plugins.html#auto-activation-auto-activation
 743fn get_worktree_venv_declaration(worktree_root: &Path) -> Option<String> {
 744    fs::File::open(worktree_root.join(".venv"))
 745        .and_then(|file| {
 746            let mut venv_name = String::new();
 747            io::BufReader::new(file).read_line(&mut venv_name)?;
 748            Ok(venv_name.trim().to_string())
 749        })
 750        .ok()
 751}
 752
 753#[async_trait]
 754impl ToolchainLister for PythonToolchainProvider {
 755    fn manifest_name(&self) -> language::ManifestName {
 756        ManifestName::from(SharedString::new_static("pyproject.toml"))
 757    }
 758    async fn list(
 759        &self,
 760        worktree_root: PathBuf,
 761        subroot_relative_path: Option<Arc<Path>>,
 762        project_env: Option<HashMap<String, String>>,
 763    ) -> ToolchainList {
 764        let env = project_env.unwrap_or_default();
 765        let environment = EnvironmentApi::from_env(&env);
 766        let locators = pet::locators::create_locators(
 767            Arc::new(pet_conda::Conda::from(&environment)),
 768            Arc::new(pet_poetry::Poetry::from(&environment)),
 769            &environment,
 770        );
 771        let mut config = Configuration::default();
 772
 773        let mut directories = vec![worktree_root.clone()];
 774        if let Some(subroot_relative_path) = subroot_relative_path {
 775            debug_assert!(subroot_relative_path.is_relative());
 776            directories.push(worktree_root.join(subroot_relative_path));
 777        }
 778
 779        config.workspace_directories = Some(directories);
 780        for locator in locators.iter() {
 781            locator.configure(&config);
 782        }
 783
 784        let reporter = pet_reporter::collect::create_reporter();
 785        pet::find::find_and_report_envs(&reporter, config, &locators, &environment, None);
 786
 787        let mut toolchains = reporter
 788            .environments
 789            .lock()
 790            .map_or(Vec::new(), |mut guard| std::mem::take(&mut guard));
 791
 792        let wr = worktree_root;
 793        let wr_venv = get_worktree_venv_declaration(&wr);
 794        // Sort detected environments by:
 795        //     environment name matching activation file (<workdir>/.venv)
 796        //     environment project dir matching worktree_root
 797        //     general env priority
 798        //     environment path matching the CONDA_PREFIX env var
 799        //     executable path
 800        toolchains.sort_by(|lhs, rhs| {
 801            // Compare venv names against worktree .venv file
 802            let venv_ordering =
 803                wr_venv
 804                    .as_ref()
 805                    .map_or(Ordering::Equal, |venv| match (&lhs.name, &rhs.name) {
 806                        (Some(l), Some(r)) => (r == venv).cmp(&(l == venv)),
 807                        (Some(l), None) if l == venv => Ordering::Less,
 808                        (None, Some(r)) if r == venv => Ordering::Greater,
 809                        _ => Ordering::Equal,
 810                    });
 811
 812            // Compare project paths against worktree root
 813            let proj_ordering = || match (&lhs.project, &rhs.project) {
 814                (Some(l), Some(r)) => (r == &wr).cmp(&(l == &wr)),
 815                (Some(l), None) if l == &wr => Ordering::Less,
 816                (None, Some(r)) if r == &wr => Ordering::Greater,
 817                _ => Ordering::Equal,
 818            };
 819
 820            // Compare environment priorities
 821            let priority_ordering = || env_priority(lhs.kind).cmp(&env_priority(rhs.kind));
 822
 823            // Compare conda prefixes
 824            let conda_ordering = || {
 825                if lhs.kind == Some(PythonEnvironmentKind::Conda) {
 826                    environment
 827                        .get_env_var("CONDA_PREFIX".to_string())
 828                        .map(|conda_prefix| {
 829                            let is_match = |exe: &Option<PathBuf>| {
 830                                exe.as_ref().map_or(false, |e| e.starts_with(&conda_prefix))
 831                            };
 832                            match (is_match(&lhs.executable), is_match(&rhs.executable)) {
 833                                (true, false) => Ordering::Less,
 834                                (false, true) => Ordering::Greater,
 835                                _ => Ordering::Equal,
 836                            }
 837                        })
 838                        .unwrap_or(Ordering::Equal)
 839                } else {
 840                    Ordering::Equal
 841                }
 842            };
 843
 844            // Compare Python executables
 845            let exe_ordering = || lhs.executable.cmp(&rhs.executable);
 846
 847            venv_ordering
 848                .then_with(proj_ordering)
 849                .then_with(priority_ordering)
 850                .then_with(conda_ordering)
 851                .then_with(exe_ordering)
 852        });
 853
 854        let mut toolchains: Vec<_> = toolchains
 855            .into_iter()
 856            .filter_map(|toolchain| {
 857                let mut name = String::from("Python");
 858                if let Some(ref version) = toolchain.version {
 859                    _ = write!(name, " {version}");
 860                }
 861
 862                let name_and_kind = match (&toolchain.name, &toolchain.kind) {
 863                    (Some(name), Some(kind)) => {
 864                        Some(format!("({name}; {})", python_env_kind_display(kind)))
 865                    }
 866                    (Some(name), None) => Some(format!("({name})")),
 867                    (None, Some(kind)) => Some(format!("({})", python_env_kind_display(kind))),
 868                    (None, None) => None,
 869                };
 870
 871                if let Some(nk) = name_and_kind {
 872                    _ = write!(name, " {nk}");
 873                }
 874
 875                Some(Toolchain {
 876                    name: name.into(),
 877                    path: toolchain.executable.as_ref()?.to_str()?.to_owned().into(),
 878                    language_name: LanguageName::new("Python"),
 879                    as_json: serde_json::to_value(toolchain).ok()?,
 880                })
 881            })
 882            .collect();
 883        toolchains.dedup();
 884        ToolchainList {
 885            toolchains,
 886            default: None,
 887            groups: Default::default(),
 888        }
 889    }
 890    fn term(&self) -> SharedString {
 891        self.term.clone()
 892    }
 893}
 894
 895pub struct EnvironmentApi<'a> {
 896    global_search_locations: Arc<Mutex<Vec<PathBuf>>>,
 897    project_env: &'a HashMap<String, String>,
 898    pet_env: pet_core::os_environment::EnvironmentApi,
 899}
 900
 901impl<'a> EnvironmentApi<'a> {
 902    pub fn from_env(project_env: &'a HashMap<String, String>) -> Self {
 903        let paths = project_env
 904            .get("PATH")
 905            .map(|p| std::env::split_paths(p).collect())
 906            .unwrap_or_default();
 907
 908        EnvironmentApi {
 909            global_search_locations: Arc::new(Mutex::new(paths)),
 910            project_env,
 911            pet_env: pet_core::os_environment::EnvironmentApi::new(),
 912        }
 913    }
 914
 915    fn user_home(&self) -> Option<PathBuf> {
 916        self.project_env
 917            .get("HOME")
 918            .or_else(|| self.project_env.get("USERPROFILE"))
 919            .map(|home| pet_fs::path::norm_case(PathBuf::from(home)))
 920            .or_else(|| self.pet_env.get_user_home())
 921    }
 922}
 923
 924impl pet_core::os_environment::Environment for EnvironmentApi<'_> {
 925    fn get_user_home(&self) -> Option<PathBuf> {
 926        self.user_home()
 927    }
 928
 929    fn get_root(&self) -> Option<PathBuf> {
 930        None
 931    }
 932
 933    fn get_env_var(&self, key: String) -> Option<String> {
 934        self.project_env
 935            .get(&key)
 936            .cloned()
 937            .or_else(|| self.pet_env.get_env_var(key))
 938    }
 939
 940    fn get_know_global_search_locations(&self) -> Vec<PathBuf> {
 941        if self.global_search_locations.lock().is_empty() {
 942            let mut paths =
 943                std::env::split_paths(&self.get_env_var("PATH".to_string()).unwrap_or_default())
 944                    .collect::<Vec<PathBuf>>();
 945
 946            log::trace!("Env PATH: {:?}", paths);
 947            for p in self.pet_env.get_know_global_search_locations() {
 948                if !paths.contains(&p) {
 949                    paths.push(p);
 950                }
 951            }
 952
 953            let mut paths = paths
 954                .into_iter()
 955                .filter(|p| p.exists())
 956                .collect::<Vec<PathBuf>>();
 957
 958            self.global_search_locations.lock().append(&mut paths);
 959        }
 960        self.global_search_locations.lock().clone()
 961    }
 962}
 963
 964pub(crate) struct PyLspAdapter {
 965    python_venv_base: OnceCell<Result<Arc<Path>, String>>,
 966}
 967impl PyLspAdapter {
 968    const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("pylsp");
 969    pub(crate) fn new() -> Self {
 970        Self {
 971            python_venv_base: OnceCell::new(),
 972        }
 973    }
 974    async fn ensure_venv(delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>> {
 975        let python_path = Self::find_base_python(delegate)
 976            .await
 977            .context("Could not find Python installation for PyLSP")?;
 978        let work_dir = delegate
 979            .language_server_download_dir(&Self::SERVER_NAME)
 980            .await
 981            .context("Could not get working directory for PyLSP")?;
 982        let mut path = PathBuf::from(work_dir.as_ref());
 983        path.push("pylsp-venv");
 984        if !path.exists() {
 985            util::command::new_smol_command(python_path)
 986                .arg("-m")
 987                .arg("venv")
 988                .arg("pylsp-venv")
 989                .current_dir(work_dir)
 990                .spawn()?
 991                .output()
 992                .await?;
 993        }
 994
 995        Ok(path.into())
 996    }
 997    // Find "baseline", user python version from which we'll create our own venv.
 998    async fn find_base_python(delegate: &dyn LspAdapterDelegate) -> Option<PathBuf> {
 999        for path in ["python3", "python"] {
1000            if let Some(path) = delegate.which(path.as_ref()).await {
1001                return Some(path);
1002            }
1003        }
1004        None
1005    }
1006
1007    async fn base_venv(&self, delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>, String> {
1008        self.python_venv_base
1009            .get_or_init(move || async move {
1010                Self::ensure_venv(delegate)
1011                    .await
1012                    .map_err(|e| format!("{e}"))
1013            })
1014            .await
1015            .clone()
1016    }
1017}
1018
1019const BINARY_DIR: &str = if cfg!(target_os = "windows") {
1020    "Scripts"
1021} else {
1022    "bin"
1023};
1024
1025#[async_trait(?Send)]
1026impl LspAdapter for PyLspAdapter {
1027    fn name(&self) -> LanguageServerName {
1028        Self::SERVER_NAME.clone()
1029    }
1030
1031    async fn check_if_user_installed(
1032        &self,
1033        delegate: &dyn LspAdapterDelegate,
1034        toolchain: Option<Toolchain>,
1035        _: &AsyncApp,
1036    ) -> Option<LanguageServerBinary> {
1037        if let Some(pylsp_bin) = delegate.which(Self::SERVER_NAME.as_ref()).await {
1038            let env = delegate.shell_env().await;
1039            Some(LanguageServerBinary {
1040                path: pylsp_bin,
1041                env: Some(env),
1042                arguments: vec![],
1043            })
1044        } else {
1045            let venv = toolchain?;
1046            let pylsp_path = Path::new(venv.path.as_ref()).parent()?.join("pylsp");
1047            pylsp_path.exists().then(|| LanguageServerBinary {
1048                path: venv.path.to_string().into(),
1049                arguments: vec![pylsp_path.into()],
1050                env: None,
1051            })
1052        }
1053    }
1054
1055    async fn fetch_latest_server_version(
1056        &self,
1057        _: &dyn LspAdapterDelegate,
1058    ) -> Result<Box<dyn 'static + Any + Send>> {
1059        Ok(Box::new(()) as Box<_>)
1060    }
1061
1062    async fn fetch_server_binary(
1063        &self,
1064        _: Box<dyn 'static + Send + Any>,
1065        _: PathBuf,
1066        delegate: &dyn LspAdapterDelegate,
1067    ) -> Result<LanguageServerBinary> {
1068        let venv = self.base_venv(delegate).await.map_err(|e| anyhow!(e))?;
1069        let pip_path = venv.join(BINARY_DIR).join("pip3");
1070        ensure!(
1071            util::command::new_smol_command(pip_path.as_path())
1072                .arg("install")
1073                .arg("python-lsp-server")
1074                .arg("-U")
1075                .output()
1076                .await?
1077                .status
1078                .success(),
1079            "python-lsp-server installation failed"
1080        );
1081        ensure!(
1082            util::command::new_smol_command(pip_path.as_path())
1083                .arg("install")
1084                .arg("python-lsp-server[all]")
1085                .arg("-U")
1086                .output()
1087                .await?
1088                .status
1089                .success(),
1090            "python-lsp-server[all] installation failed"
1091        );
1092        ensure!(
1093            util::command::new_smol_command(pip_path)
1094                .arg("install")
1095                .arg("pylsp-mypy")
1096                .arg("-U")
1097                .output()
1098                .await?
1099                .status
1100                .success(),
1101            "pylsp-mypy installation failed"
1102        );
1103        let pylsp = venv.join(BINARY_DIR).join("pylsp");
1104        Ok(LanguageServerBinary {
1105            path: pylsp,
1106            env: None,
1107            arguments: vec![],
1108        })
1109    }
1110
1111    async fn cached_server_binary(
1112        &self,
1113        _: PathBuf,
1114        delegate: &dyn LspAdapterDelegate,
1115    ) -> Option<LanguageServerBinary> {
1116        let venv = self.base_venv(delegate).await.ok()?;
1117        let pylsp = venv.join(BINARY_DIR).join("pylsp");
1118        Some(LanguageServerBinary {
1119            path: pylsp,
1120            env: None,
1121            arguments: vec![],
1122        })
1123    }
1124
1125    async fn process_completions(&self, _items: &mut [lsp::CompletionItem]) {}
1126
1127    async fn label_for_completion(
1128        &self,
1129        item: &lsp::CompletionItem,
1130        language: &Arc<language::Language>,
1131    ) -> Option<language::CodeLabel> {
1132        let label = &item.label;
1133        let grammar = language.grammar()?;
1134        let highlight_id = match item.kind? {
1135            lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method")?,
1136            lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function")?,
1137            lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type")?,
1138            lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant")?,
1139            _ => return None,
1140        };
1141        let filter_range = item
1142            .filter_text
1143            .as_deref()
1144            .and_then(|filter| label.find(filter).map(|ix| ix..ix + filter.len()))
1145            .unwrap_or(0..label.len());
1146        Some(language::CodeLabel {
1147            text: label.clone(),
1148            runs: vec![(0..label.len(), highlight_id)],
1149            filter_range,
1150        })
1151    }
1152
1153    async fn label_for_symbol(
1154        &self,
1155        name: &str,
1156        kind: lsp::SymbolKind,
1157        language: &Arc<language::Language>,
1158    ) -> Option<language::CodeLabel> {
1159        let (text, filter_range, display_range) = match kind {
1160            lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
1161                let text = format!("def {}():\n", name);
1162                let filter_range = 4..4 + name.len();
1163                let display_range = 0..filter_range.end;
1164                (text, filter_range, display_range)
1165            }
1166            lsp::SymbolKind::CLASS => {
1167                let text = format!("class {}:", name);
1168                let filter_range = 6..6 + name.len();
1169                let display_range = 0..filter_range.end;
1170                (text, filter_range, display_range)
1171            }
1172            lsp::SymbolKind::CONSTANT => {
1173                let text = format!("{} = 0", name);
1174                let filter_range = 0..name.len();
1175                let display_range = 0..filter_range.end;
1176                (text, filter_range, display_range)
1177            }
1178            _ => return None,
1179        };
1180
1181        Some(language::CodeLabel {
1182            runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
1183            text: text[display_range].to_string(),
1184            filter_range,
1185        })
1186    }
1187
1188    async fn workspace_configuration(
1189        self: Arc<Self>,
1190        _: &dyn Fs,
1191        adapter: &Arc<dyn LspAdapterDelegate>,
1192        toolchain: Option<Toolchain>,
1193        cx: &mut AsyncApp,
1194    ) -> Result<Value> {
1195        cx.update(move |cx| {
1196            let mut user_settings =
1197                language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
1198                    .and_then(|s| s.settings.clone())
1199                    .unwrap_or_else(|| {
1200                        json!({
1201                            "plugins": {
1202                                "pycodestyle": {"enabled": false},
1203                                "rope_autoimport": {"enabled": true, "memory": true},
1204                                "pylsp_mypy": {"enabled": false}
1205                            },
1206                            "rope": {
1207                                "ropeFolder": null
1208                            },
1209                        })
1210                    });
1211
1212            // If user did not explicitly modify their python venv, use one from picker.
1213            if let Some(toolchain) = toolchain {
1214                if user_settings.is_null() {
1215                    user_settings = Value::Object(serde_json::Map::default());
1216                }
1217                let object = user_settings.as_object_mut().unwrap();
1218                if let Some(python) = object
1219                    .entry("plugins")
1220                    .or_insert(Value::Object(serde_json::Map::default()))
1221                    .as_object_mut()
1222                {
1223                    if let Some(jedi) = python
1224                        .entry("jedi")
1225                        .or_insert(Value::Object(serde_json::Map::default()))
1226                        .as_object_mut()
1227                    {
1228                        jedi.entry("environment".to_string())
1229                            .or_insert_with(|| Value::String(toolchain.path.clone().into()));
1230                    }
1231                    if let Some(pylint) = python
1232                        .entry("pylsp_mypy")
1233                        .or_insert(Value::Object(serde_json::Map::default()))
1234                        .as_object_mut()
1235                    {
1236                        pylint.entry("overrides".to_string()).or_insert_with(|| {
1237                            Value::Array(vec![
1238                                Value::String("--python-executable".into()),
1239                                Value::String(toolchain.path.into()),
1240                                Value::String("--cache-dir=/dev/null".into()),
1241                                Value::Bool(true),
1242                            ])
1243                        });
1244                    }
1245                }
1246            }
1247            user_settings = Value::Object(serde_json::Map::from_iter([(
1248                "pylsp".to_string(),
1249                user_settings,
1250            )]));
1251
1252            user_settings
1253        })
1254    }
1255}
1256
1257pub(crate) struct BasedPyrightLspAdapter {
1258    python_venv_base: OnceCell<Result<Arc<Path>, String>>,
1259}
1260
1261impl BasedPyrightLspAdapter {
1262    const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("basedpyright");
1263    const BINARY_NAME: &'static str = "basedpyright-langserver";
1264
1265    pub(crate) fn new() -> Self {
1266        Self {
1267            python_venv_base: OnceCell::new(),
1268        }
1269    }
1270
1271    async fn ensure_venv(delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>> {
1272        let python_path = Self::find_base_python(delegate)
1273            .await
1274            .context("Could not find Python installation for basedpyright")?;
1275        let work_dir = delegate
1276            .language_server_download_dir(&Self::SERVER_NAME)
1277            .await
1278            .context("Could not get working directory for basedpyright")?;
1279        let mut path = PathBuf::from(work_dir.as_ref());
1280        path.push("basedpyright-venv");
1281        if !path.exists() {
1282            util::command::new_smol_command(python_path)
1283                .arg("-m")
1284                .arg("venv")
1285                .arg("basedpyright-venv")
1286                .current_dir(work_dir)
1287                .spawn()?
1288                .output()
1289                .await?;
1290        }
1291
1292        Ok(path.into())
1293    }
1294
1295    // Find "baseline", user python version from which we'll create our own venv.
1296    async fn find_base_python(delegate: &dyn LspAdapterDelegate) -> Option<PathBuf> {
1297        for path in ["python3", "python"] {
1298            if let Some(path) = delegate.which(path.as_ref()).await {
1299                return Some(path);
1300            }
1301        }
1302        None
1303    }
1304
1305    async fn base_venv(&self, delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>, String> {
1306        self.python_venv_base
1307            .get_or_init(move || async move {
1308                Self::ensure_venv(delegate)
1309                    .await
1310                    .map_err(|e| format!("{e}"))
1311            })
1312            .await
1313            .clone()
1314    }
1315}
1316
1317#[async_trait(?Send)]
1318impl LspAdapter for BasedPyrightLspAdapter {
1319    fn name(&self) -> LanguageServerName {
1320        Self::SERVER_NAME.clone()
1321    }
1322
1323    async fn initialization_options(
1324        self: Arc<Self>,
1325        _: &dyn Fs,
1326        _: &Arc<dyn LspAdapterDelegate>,
1327    ) -> Result<Option<Value>> {
1328        // Provide minimal initialization options
1329        // Virtual environment configuration will be handled through workspace configuration
1330        Ok(Some(json!({
1331            "python": {
1332                "analysis": {
1333                    "autoSearchPaths": true,
1334                    "useLibraryCodeForTypes": true,
1335                    "autoImportCompletions": true
1336                }
1337            }
1338        })))
1339    }
1340
1341    async fn check_if_user_installed(
1342        &self,
1343        delegate: &dyn LspAdapterDelegate,
1344        toolchain: Option<Toolchain>,
1345        _: &AsyncApp,
1346    ) -> Option<LanguageServerBinary> {
1347        if let Some(bin) = delegate.which(Self::BINARY_NAME.as_ref()).await {
1348            let env = delegate.shell_env().await;
1349            Some(LanguageServerBinary {
1350                path: bin,
1351                env: Some(env),
1352                arguments: vec!["--stdio".into()],
1353            })
1354        } else {
1355            let path = Path::new(toolchain?.path.as_ref())
1356                .parent()?
1357                .join(Self::BINARY_NAME);
1358            path.exists().then(|| LanguageServerBinary {
1359                path,
1360                arguments: vec!["--stdio".into()],
1361                env: None,
1362            })
1363        }
1364    }
1365
1366    async fn fetch_latest_server_version(
1367        &self,
1368        _: &dyn LspAdapterDelegate,
1369    ) -> Result<Box<dyn 'static + Any + Send>> {
1370        Ok(Box::new(()) as Box<_>)
1371    }
1372
1373    async fn fetch_server_binary(
1374        &self,
1375        _latest_version: Box<dyn 'static + Send + Any>,
1376        _container_dir: PathBuf,
1377        delegate: &dyn LspAdapterDelegate,
1378    ) -> Result<LanguageServerBinary> {
1379        let venv = self.base_venv(delegate).await.map_err(|e| anyhow!(e))?;
1380        let pip_path = venv.join(BINARY_DIR).join("pip3");
1381        ensure!(
1382            util::command::new_smol_command(pip_path.as_path())
1383                .arg("install")
1384                .arg("basedpyright")
1385                .arg("-U")
1386                .output()
1387                .await?
1388                .status
1389                .success(),
1390            "basedpyright installation failed"
1391        );
1392        let pylsp = venv.join(BINARY_DIR).join(Self::BINARY_NAME);
1393        Ok(LanguageServerBinary {
1394            path: pylsp,
1395            env: None,
1396            arguments: vec!["--stdio".into()],
1397        })
1398    }
1399
1400    async fn cached_server_binary(
1401        &self,
1402        _container_dir: PathBuf,
1403        delegate: &dyn LspAdapterDelegate,
1404    ) -> Option<LanguageServerBinary> {
1405        let venv = self.base_venv(delegate).await.ok()?;
1406        let pylsp = venv.join(BINARY_DIR).join(Self::BINARY_NAME);
1407        Some(LanguageServerBinary {
1408            path: pylsp,
1409            env: None,
1410            arguments: vec!["--stdio".into()],
1411        })
1412    }
1413
1414    async fn process_completions(&self, items: &mut [lsp::CompletionItem]) {
1415        // Pyright assigns each completion item a `sortText` of the form `XX.YYYY.name`.
1416        // Where `XX` is the sorting category, `YYYY` is based on most recent usage,
1417        // and `name` is the symbol name itself.
1418        //
1419        // Because the symbol name is included, there generally are not ties when
1420        // sorting by the `sortText`, so the symbol's fuzzy match score is not taken
1421        // into account. Here, we remove the symbol name from the sortText in order
1422        // to allow our own fuzzy score to be used to break ties.
1423        //
1424        // see https://github.com/microsoft/pyright/blob/95ef4e103b9b2f129c9320427e51b73ea7cf78bd/packages/pyright-internal/src/languageService/completionProvider.ts#LL2873
1425        for item in items {
1426            let Some(sort_text) = &mut item.sort_text else {
1427                continue;
1428            };
1429            let mut parts = sort_text.split('.');
1430            let Some(first) = parts.next() else { continue };
1431            let Some(second) = parts.next() else { continue };
1432            let Some(_) = parts.next() else { continue };
1433            sort_text.replace_range(first.len() + second.len() + 1.., "");
1434        }
1435    }
1436
1437    async fn label_for_completion(
1438        &self,
1439        item: &lsp::CompletionItem,
1440        language: &Arc<language::Language>,
1441    ) -> Option<language::CodeLabel> {
1442        let label = &item.label;
1443        let grammar = language.grammar()?;
1444        let highlight_id = match item.kind? {
1445            lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method")?,
1446            lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function")?,
1447            lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type")?,
1448            lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant")?,
1449            _ => return None,
1450        };
1451        let filter_range = item
1452            .filter_text
1453            .as_deref()
1454            .and_then(|filter| label.find(filter).map(|ix| ix..ix + filter.len()))
1455            .unwrap_or(0..label.len());
1456        Some(language::CodeLabel {
1457            text: label.clone(),
1458            runs: vec![(0..label.len(), highlight_id)],
1459            filter_range,
1460        })
1461    }
1462
1463    async fn label_for_symbol(
1464        &self,
1465        name: &str,
1466        kind: lsp::SymbolKind,
1467        language: &Arc<language::Language>,
1468    ) -> Option<language::CodeLabel> {
1469        let (text, filter_range, display_range) = match kind {
1470            lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
1471                let text = format!("def {}():\n", name);
1472                let filter_range = 4..4 + name.len();
1473                let display_range = 0..filter_range.end;
1474                (text, filter_range, display_range)
1475            }
1476            lsp::SymbolKind::CLASS => {
1477                let text = format!("class {}:", name);
1478                let filter_range = 6..6 + name.len();
1479                let display_range = 0..filter_range.end;
1480                (text, filter_range, display_range)
1481            }
1482            lsp::SymbolKind::CONSTANT => {
1483                let text = format!("{} = 0", name);
1484                let filter_range = 0..name.len();
1485                let display_range = 0..filter_range.end;
1486                (text, filter_range, display_range)
1487            }
1488            _ => return None,
1489        };
1490
1491        Some(language::CodeLabel {
1492            runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
1493            text: text[display_range].to_string(),
1494            filter_range,
1495        })
1496    }
1497
1498    async fn workspace_configuration(
1499        self: Arc<Self>,
1500        _: &dyn Fs,
1501        adapter: &Arc<dyn LspAdapterDelegate>,
1502        toolchain: Option<Toolchain>,
1503        cx: &mut AsyncApp,
1504    ) -> Result<Value> {
1505        cx.update(move |cx| {
1506            let mut user_settings =
1507                language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
1508                    .and_then(|s| s.settings.clone())
1509                    .unwrap_or_default();
1510
1511            // If we have a detected toolchain, configure Pyright to use it
1512            if let Some(toolchain) = toolchain {
1513                if user_settings.is_null() {
1514                    user_settings = Value::Object(serde_json::Map::default());
1515                }
1516                let object = user_settings.as_object_mut().unwrap();
1517
1518                let interpreter_path = toolchain.path.to_string();
1519
1520                // Detect if this is a virtual environment
1521                if let Some(interpreter_dir) = Path::new(&interpreter_path).parent()
1522                    && let Some(venv_dir) = interpreter_dir.parent() {
1523                        // Check if this looks like a virtual environment
1524                        if venv_dir.join("pyvenv.cfg").exists()
1525                            || venv_dir.join("bin/activate").exists()
1526                            || venv_dir.join("Scripts/activate.bat").exists()
1527                        {
1528                            // Set venvPath and venv at the root level
1529                            // This matches the format of a pyrightconfig.json file
1530                            if let Some(parent) = venv_dir.parent() {
1531                                // Use relative path if the venv is inside the workspace
1532                                let venv_path = if parent == adapter.worktree_root_path() {
1533                                    ".".to_string()
1534                                } else {
1535                                    parent.to_string_lossy().into_owned()
1536                                };
1537                                object.insert("venvPath".to_string(), Value::String(venv_path));
1538                            }
1539
1540                            if let Some(venv_name) = venv_dir.file_name() {
1541                                object.insert(
1542                                    "venv".to_owned(),
1543                                    Value::String(venv_name.to_string_lossy().into_owned()),
1544                                );
1545                            }
1546                        }
1547                    }
1548
1549                // Always set the python interpreter path
1550                // Get or create the python section
1551                let python = object
1552                    .entry("python")
1553                    .or_insert(Value::Object(serde_json::Map::default()))
1554                    .as_object_mut()
1555                    .unwrap();
1556
1557                // Set both pythonPath and defaultInterpreterPath for compatibility
1558                python.insert(
1559                    "pythonPath".to_owned(),
1560                    Value::String(interpreter_path.clone()),
1561                );
1562                python.insert(
1563                    "defaultInterpreterPath".to_owned(),
1564                    Value::String(interpreter_path),
1565                );
1566            }
1567
1568            user_settings
1569        })
1570    }
1571}
1572
1573#[cfg(test)]
1574mod tests {
1575    use gpui::{AppContext as _, BorrowAppContext, Context, TestAppContext};
1576    use language::{AutoindentMode, Buffer, language_settings::AllLanguageSettings};
1577    use settings::SettingsStore;
1578    use std::num::NonZeroU32;
1579
1580    #[gpui::test]
1581    async fn test_python_autoindent(cx: &mut TestAppContext) {
1582        cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
1583        let language = crate::language("python", tree_sitter_python::LANGUAGE.into());
1584        cx.update(|cx| {
1585            let test_settings = SettingsStore::test(cx);
1586            cx.set_global(test_settings);
1587            language::init(cx);
1588            cx.update_global::<SettingsStore, _>(|store, cx| {
1589                store.update_user_settings::<AllLanguageSettings>(cx, |s| {
1590                    s.defaults.tab_size = NonZeroU32::new(2);
1591                });
1592            });
1593        });
1594
1595        cx.new(|cx| {
1596            let mut buffer = Buffer::local("", cx).with_language(language, cx);
1597            let append = |buffer: &mut Buffer, text: &str, cx: &mut Context<Buffer>| {
1598                let ix = buffer.len();
1599                buffer.edit([(ix..ix, text)], Some(AutoindentMode::EachLine), cx);
1600            };
1601
1602            // indent after "def():"
1603            append(&mut buffer, "def a():\n", cx);
1604            assert_eq!(buffer.text(), "def a():\n  ");
1605
1606            // preserve indent after blank line
1607            append(&mut buffer, "\n  ", cx);
1608            assert_eq!(buffer.text(), "def a():\n  \n  ");
1609
1610            // indent after "if"
1611            append(&mut buffer, "if a:\n  ", cx);
1612            assert_eq!(buffer.text(), "def a():\n  \n  if a:\n    ");
1613
1614            // preserve indent after statement
1615            append(&mut buffer, "b()\n", cx);
1616            assert_eq!(buffer.text(), "def a():\n  \n  if a:\n    b()\n    ");
1617
1618            // preserve indent after statement
1619            append(&mut buffer, "else", cx);
1620            assert_eq!(buffer.text(), "def a():\n  \n  if a:\n    b()\n    else");
1621
1622            // dedent "else""
1623            append(&mut buffer, ":", cx);
1624            assert_eq!(buffer.text(), "def a():\n  \n  if a:\n    b()\n  else:");
1625
1626            // indent lines after else
1627            append(&mut buffer, "\n", cx);
1628            assert_eq!(
1629                buffer.text(),
1630                "def a():\n  \n  if a:\n    b()\n  else:\n    "
1631            );
1632
1633            // indent after an open paren. the closing paren is not indented
1634            // because there is another token before it on the same line.
1635            append(&mut buffer, "foo(\n1)", cx);
1636            assert_eq!(
1637                buffer.text(),
1638                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n      1)"
1639            );
1640
1641            // dedent the closing paren if it is shifted to the beginning of the line
1642            let argument_ix = buffer.text().find('1').unwrap();
1643            buffer.edit(
1644                [(argument_ix..argument_ix + 1, "")],
1645                Some(AutoindentMode::EachLine),
1646                cx,
1647            );
1648            assert_eq!(
1649                buffer.text(),
1650                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n    )"
1651            );
1652
1653            // preserve indent after the close paren
1654            append(&mut buffer, "\n", cx);
1655            assert_eq!(
1656                buffer.text(),
1657                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n    )\n    "
1658            );
1659
1660            // manually outdent the last line
1661            let end_whitespace_ix = buffer.len() - 4;
1662            buffer.edit(
1663                [(end_whitespace_ix..buffer.len(), "")],
1664                Some(AutoindentMode::EachLine),
1665                cx,
1666            );
1667            assert_eq!(
1668                buffer.text(),
1669                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n    )\n"
1670            );
1671
1672            // preserve the newly reduced indentation on the next newline
1673            append(&mut buffer, "\n", cx);
1674            assert_eq!(
1675                buffer.text(),
1676                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n    )\n\n"
1677            );
1678
1679            // reset to a simple if statement
1680            buffer.edit([(0..buffer.len(), "if a:\n  b(\n  )")], None, cx);
1681
1682            // dedent "else" on the line after a closing paren
1683            append(&mut buffer, "\n  else:\n", cx);
1684            assert_eq!(buffer.text(), "if a:\n  b(\n  )\nelse:\n  ");
1685
1686            buffer
1687        });
1688    }
1689}