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