python.rs

   1use anyhow::{Context as _, ensure};
   2use anyhow::{Result, anyhow};
   3use async_trait::async_trait;
   4use collections::HashMap;
   5use futures::AsyncBufReadExt;
   6use gpui::{App, Task};
   7use gpui::{AsyncApp, SharedString};
   8use language::Toolchain;
   9use language::ToolchainList;
  10use language::ToolchainLister;
  11use language::language_settings::language_settings;
  12use language::{ContextLocation, LanguageToolchainStore};
  13use language::{ContextProvider, LspAdapter, LspAdapterDelegate};
  14use language::{LanguageName, ManifestName, ManifestProvider, ManifestQuery};
  15use lsp::LanguageServerBinary;
  16use lsp::LanguageServerName;
  17use node_runtime::{NodeRuntime, VersionStrategy};
  18use pet_core::Configuration;
  19use pet_core::os_environment::Environment;
  20use pet_core::python_environment::PythonEnvironmentKind;
  21use project::Fs;
  22use project::lsp_store::language_server_settings;
  23use serde_json::{Value, json};
  24use smol::lock::OnceCell;
  25use std::cmp::Ordering;
  26
  27use parking_lot::Mutex;
  28use std::str::FromStr;
  29use std::{
  30    any::Any,
  31    borrow::Cow,
  32    ffi::OsString,
  33    fmt::Write,
  34    path::{Path, PathBuf},
  35    sync::Arc,
  36};
  37use task::{ShellKind, TaskTemplate, TaskTemplates, VariableName};
  38use util::ResultExt;
  39
  40pub(crate) struct PyprojectTomlManifestProvider;
  41
  42impl ManifestProvider for PyprojectTomlManifestProvider {
  43    fn name(&self) -> ManifestName {
  44        SharedString::new_static("pyproject.toml").into()
  45    }
  46
  47    fn search(
  48        &self,
  49        ManifestQuery {
  50            path,
  51            depth,
  52            delegate,
  53        }: ManifestQuery,
  54    ) -> Option<Arc<Path>> {
  55        for path in path.ancestors().take(depth) {
  56            let p = path.join("pyproject.toml");
  57            if delegate.exists(&p, Some(false)) {
  58                return Some(path.into());
  59            }
  60        }
  61
  62        None
  63    }
  64}
  65
  66const SERVER_PATH: &str = "node_modules/pyright/langserver.index.js";
  67const NODE_MODULE_RELATIVE_SERVER_PATH: &str = "pyright/langserver.index.js";
  68
  69enum TestRunner {
  70    UNITTEST,
  71    PYTEST,
  72}
  73
  74impl FromStr for TestRunner {
  75    type Err = ();
  76
  77    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
  78        match s {
  79            "unittest" => Ok(Self::UNITTEST),
  80            "pytest" => Ok(Self::PYTEST),
  81            _ => Err(()),
  82        }
  83    }
  84}
  85
  86fn server_binary_arguments(server_path: &Path) -> Vec<OsString> {
  87    vec![server_path.into(), "--stdio".into()]
  88}
  89
  90pub struct PythonLspAdapter {
  91    node: NodeRuntime,
  92}
  93
  94impl PythonLspAdapter {
  95    const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("pyright");
  96
  97    pub fn new(node: NodeRuntime) -> Self {
  98        PythonLspAdapter { node }
  99    }
 100}
 101
 102#[async_trait(?Send)]
 103impl LspAdapter for PythonLspAdapter {
 104    fn name(&self) -> LanguageServerName {
 105        Self::SERVER_NAME
 106    }
 107
 108    async fn initialization_options(
 109        self: Arc<Self>,
 110        _: &dyn Fs,
 111        _: &Arc<dyn LspAdapterDelegate>,
 112    ) -> Result<Option<Value>> {
 113        // Provide minimal initialization options
 114        // Virtual environment configuration will be handled through workspace configuration
 115        Ok(Some(json!({
 116            "python": {
 117                "analysis": {
 118                    "autoSearchPaths": true,
 119                    "useLibraryCodeForTypes": true,
 120                    "autoImportCompletions": true
 121                }
 122            }
 123        })))
 124    }
 125
 126    async fn check_if_user_installed(
 127        &self,
 128        delegate: &dyn LspAdapterDelegate,
 129        _: Option<Toolchain>,
 130        _: &AsyncApp,
 131    ) -> Option<LanguageServerBinary> {
 132        if let Some(pyright_bin) = delegate.which("pyright-langserver".as_ref()).await {
 133            let env = delegate.shell_env().await;
 134            Some(LanguageServerBinary {
 135                path: pyright_bin,
 136                env: Some(env),
 137                arguments: vec!["--stdio".into()],
 138            })
 139        } else {
 140            let node = delegate.which("node".as_ref()).await?;
 141            let (node_modules_path, _) = delegate
 142                .npm_package_installed_version(Self::SERVER_NAME.as_ref())
 143                .await
 144                .log_err()??;
 145
 146            let path = node_modules_path.join(NODE_MODULE_RELATIVE_SERVER_PATH);
 147
 148            let env = delegate.shell_env().await;
 149            Some(LanguageServerBinary {
 150                path: node,
 151                env: Some(env),
 152                arguments: server_binary_arguments(&path),
 153            })
 154        }
 155    }
 156
 157    async fn fetch_latest_server_version(
 158        &self,
 159        _: &dyn LspAdapterDelegate,
 160    ) -> Result<Box<dyn 'static + Any + Send>> {
 161        Ok(Box::new(
 162            self.node
 163                .npm_package_latest_version(Self::SERVER_NAME.as_ref())
 164                .await?,
 165        ) as Box<_>)
 166    }
 167
 168    async fn fetch_server_binary(
 169        &self,
 170        latest_version: Box<dyn 'static + Send + Any>,
 171        container_dir: PathBuf,
 172        delegate: &dyn LspAdapterDelegate,
 173    ) -> Result<LanguageServerBinary> {
 174        let latest_version = latest_version.downcast::<String>().unwrap();
 175        let server_path = container_dir.join(SERVER_PATH);
 176
 177        self.node
 178            .npm_install_packages(
 179                &container_dir,
 180                &[(Self::SERVER_NAME.as_ref(), latest_version.as_str())],
 181            )
 182            .await?;
 183
 184        let env = delegate.shell_env().await;
 185        Ok(LanguageServerBinary {
 186            path: self.node.binary_path().await?,
 187            env: Some(env),
 188            arguments: server_binary_arguments(&server_path),
 189        })
 190    }
 191
 192    async fn check_if_version_installed(
 193        &self,
 194        version: &(dyn 'static + Send + Any),
 195        container_dir: &PathBuf,
 196        delegate: &dyn LspAdapterDelegate,
 197    ) -> Option<LanguageServerBinary> {
 198        let version = version.downcast_ref::<String>().unwrap();
 199        let server_path = container_dir.join(SERVER_PATH);
 200
 201        let should_install_language_server = self
 202            .node
 203            .should_install_npm_package(
 204                Self::SERVER_NAME.as_ref(),
 205                &server_path,
 206                container_dir,
 207                VersionStrategy::Latest(version),
 208            )
 209            .await;
 210
 211        if should_install_language_server {
 212            None
 213        } else {
 214            let env = delegate.shell_env().await;
 215            Some(LanguageServerBinary {
 216                path: self.node.binary_path().await.ok()?,
 217                env: Some(env),
 218                arguments: server_binary_arguments(&server_path),
 219            })
 220        }
 221    }
 222
 223    async fn cached_server_binary(
 224        &self,
 225        container_dir: PathBuf,
 226        delegate: &dyn LspAdapterDelegate,
 227    ) -> Option<LanguageServerBinary> {
 228        let mut binary = get_cached_server_binary(container_dir, &self.node).await?;
 229        binary.env = Some(delegate.shell_env().await);
 230        Some(binary)
 231    }
 232
 233    async fn process_completions(&self, items: &mut [lsp::CompletionItem]) {
 234        // Pyright assigns each completion item a `sortText` of the form `XX.YYYY.name`.
 235        // Where `XX` is the sorting category, `YYYY` is based on most recent usage,
 236        // and `name` is the symbol name itself.
 237        //
 238        // Because the symbol name is included, there generally are not ties when
 239        // sorting by the `sortText`, so the symbol's fuzzy match score is not taken
 240        // into account. Here, we remove the symbol name from the sortText in order
 241        // to allow our own fuzzy score to be used to break ties.
 242        //
 243        // see https://github.com/microsoft/pyright/blob/95ef4e103b9b2f129c9320427e51b73ea7cf78bd/packages/pyright-internal/src/languageService/completionProvider.ts#LL2873
 244        for item in items {
 245            let Some(sort_text) = &mut item.sort_text else {
 246                continue;
 247            };
 248            let mut parts = sort_text.split('.');
 249            let Some(first) = parts.next() else { continue };
 250            let Some(second) = parts.next() else { continue };
 251            let Some(_) = parts.next() else { continue };
 252            sort_text.replace_range(first.len() + second.len() + 1.., "");
 253        }
 254    }
 255
 256    async fn label_for_completion(
 257        &self,
 258        item: &lsp::CompletionItem,
 259        language: &Arc<language::Language>,
 260    ) -> Option<language::CodeLabel> {
 261        let label = &item.label;
 262        let grammar = language.grammar()?;
 263        let highlight_id = match item.kind? {
 264            lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method")?,
 265            lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function")?,
 266            lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type")?,
 267            lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant")?,
 268            _ => return None,
 269        };
 270        let filter_range = item
 271            .filter_text
 272            .as_deref()
 273            .and_then(|filter| label.find(filter).map(|ix| ix..ix + filter.len()))
 274            .unwrap_or(0..label.len());
 275        Some(language::CodeLabel {
 276            text: label.clone(),
 277            runs: vec![(0..label.len(), highlight_id)],
 278            filter_range,
 279        })
 280    }
 281
 282    async fn label_for_symbol(
 283        &self,
 284        name: &str,
 285        kind: lsp::SymbolKind,
 286        language: &Arc<language::Language>,
 287    ) -> Option<language::CodeLabel> {
 288        let (text, filter_range, display_range) = match kind {
 289            lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
 290                let text = format!("def {}():\n", name);
 291                let filter_range = 4..4 + name.len();
 292                let display_range = 0..filter_range.end;
 293                (text, filter_range, display_range)
 294            }
 295            lsp::SymbolKind::CLASS => {
 296                let text = format!("class {}:", name);
 297                let filter_range = 6..6 + name.len();
 298                let display_range = 0..filter_range.end;
 299                (text, filter_range, display_range)
 300            }
 301            lsp::SymbolKind::CONSTANT => {
 302                let text = format!("{} = 0", name);
 303                let filter_range = 0..name.len();
 304                let display_range = 0..filter_range.end;
 305                (text, filter_range, display_range)
 306            }
 307            _ => return None,
 308        };
 309
 310        Some(language::CodeLabel {
 311            runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
 312            text: text[display_range].to_string(),
 313            filter_range,
 314        })
 315    }
 316
 317    async fn workspace_configuration(
 318        self: Arc<Self>,
 319        _: &dyn Fs,
 320        adapter: &Arc<dyn LspAdapterDelegate>,
 321        toolchain: Option<Toolchain>,
 322        cx: &mut AsyncApp,
 323    ) -> Result<Value> {
 324        cx.update(move |cx| {
 325            let mut user_settings =
 326                language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
 327                    .and_then(|s| s.settings.clone())
 328                    .unwrap_or_default();
 329
 330            // If we have a detected toolchain, configure Pyright to use it
 331            if let Some(toolchain) = toolchain {
 332                if user_settings.is_null() {
 333                    user_settings = Value::Object(serde_json::Map::default());
 334                }
 335                let object = user_settings.as_object_mut().unwrap();
 336
 337                let interpreter_path = toolchain.path.to_string();
 338
 339                // Detect if this is a virtual environment
 340                if let Some(interpreter_dir) = Path::new(&interpreter_path).parent()
 341                    && let Some(venv_dir) = interpreter_dir.parent()
 342                {
 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: &[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
 743async fn get_worktree_venv_declaration(worktree_root: &Path) -> Option<String> {
 744    let file = async_fs::File::open(worktree_root.join(".venv"))
 745        .await
 746        .ok()?;
 747    let mut venv_name = String::new();
 748    smol::io::BufReader::new(file)
 749        .read_line(&mut venv_name)
 750        .await
 751        .ok()?;
 752    Some(venv_name.trim().to_string())
 753}
 754
 755#[async_trait]
 756impl ToolchainLister for PythonToolchainProvider {
 757    fn manifest_name(&self) -> language::ManifestName {
 758        ManifestName::from(SharedString::new_static("pyproject.toml"))
 759    }
 760    async fn list(
 761        &self,
 762        worktree_root: PathBuf,
 763        subroot_relative_path: Option<Arc<Path>>,
 764        project_env: Option<HashMap<String, String>>,
 765    ) -> ToolchainList {
 766        let env = project_env.unwrap_or_default();
 767        let environment = EnvironmentApi::from_env(&env);
 768        let locators = pet::locators::create_locators(
 769            Arc::new(pet_conda::Conda::from(&environment)),
 770            Arc::new(pet_poetry::Poetry::from(&environment)),
 771            &environment,
 772        );
 773        let mut config = Configuration::default();
 774
 775        let mut directories = vec![worktree_root.clone()];
 776        if let Some(subroot_relative_path) = subroot_relative_path {
 777            debug_assert!(subroot_relative_path.is_relative());
 778            directories.push(worktree_root.join(subroot_relative_path));
 779        }
 780
 781        config.workspace_directories = Some(directories);
 782        for locator in locators.iter() {
 783            locator.configure(&config);
 784        }
 785
 786        let reporter = pet_reporter::collect::create_reporter();
 787        pet::find::find_and_report_envs(&reporter, config, &locators, &environment, None);
 788
 789        let mut toolchains = reporter
 790            .environments
 791            .lock()
 792            .map_or(Vec::new(), |mut guard| std::mem::take(&mut guard));
 793
 794        let wr = worktree_root;
 795        let wr_venv = get_worktree_venv_declaration(&wr).await;
 796        // Sort detected environments by:
 797        //     environment name matching activation file (<workdir>/.venv)
 798        //     environment project dir matching worktree_root
 799        //     general env priority
 800        //     environment path matching the CONDA_PREFIX env var
 801        //     executable path
 802        toolchains.sort_by(|lhs, rhs| {
 803            // Compare venv names against worktree .venv file
 804            let venv_ordering =
 805                wr_venv
 806                    .as_ref()
 807                    .map_or(Ordering::Equal, |venv| match (&lhs.name, &rhs.name) {
 808                        (Some(l), Some(r)) => (r == venv).cmp(&(l == venv)),
 809                        (Some(l), None) if l == venv => Ordering::Less,
 810                        (None, Some(r)) if r == venv => Ordering::Greater,
 811                        _ => Ordering::Equal,
 812                    });
 813
 814            // Compare project paths against worktree root
 815            let proj_ordering = || match (&lhs.project, &rhs.project) {
 816                (Some(l), Some(r)) => (r == &wr).cmp(&(l == &wr)),
 817                (Some(l), None) if l == &wr => Ordering::Less,
 818                (None, Some(r)) if r == &wr => Ordering::Greater,
 819                _ => Ordering::Equal,
 820            };
 821
 822            // Compare environment priorities
 823            let priority_ordering = || env_priority(lhs.kind).cmp(&env_priority(rhs.kind));
 824
 825            // Compare conda prefixes
 826            let conda_ordering = || {
 827                if lhs.kind == Some(PythonEnvironmentKind::Conda) {
 828                    environment
 829                        .get_env_var("CONDA_PREFIX".to_string())
 830                        .map(|conda_prefix| {
 831                            let is_match = |exe: &Option<PathBuf>| {
 832                                exe.as_ref().is_some_and(|e| e.starts_with(&conda_prefix))
 833                            };
 834                            match (is_match(&lhs.executable), is_match(&rhs.executable)) {
 835                                (true, false) => Ordering::Less,
 836                                (false, true) => Ordering::Greater,
 837                                _ => Ordering::Equal,
 838                            }
 839                        })
 840                        .unwrap_or(Ordering::Equal)
 841                } else {
 842                    Ordering::Equal
 843                }
 844            };
 845
 846            // Compare Python executables
 847            let exe_ordering = || lhs.executable.cmp(&rhs.executable);
 848
 849            venv_ordering
 850                .then_with(proj_ordering)
 851                .then_with(priority_ordering)
 852                .then_with(conda_ordering)
 853                .then_with(exe_ordering)
 854        });
 855
 856        let mut toolchains: Vec<_> = toolchains
 857            .into_iter()
 858            .filter_map(|toolchain| {
 859                let mut name = String::from("Python");
 860                if let Some(version) = &toolchain.version {
 861                    _ = write!(name, " {version}");
 862                }
 863
 864                let name_and_kind = match (&toolchain.name, &toolchain.kind) {
 865                    (Some(name), Some(kind)) => {
 866                        Some(format!("({name}; {})", python_env_kind_display(kind)))
 867                    }
 868                    (Some(name), None) => Some(format!("({name})")),
 869                    (None, Some(kind)) => Some(format!("({})", python_env_kind_display(kind))),
 870                    (None, None) => None,
 871                };
 872
 873                if let Some(nk) = name_and_kind {
 874                    _ = write!(name, " {nk}");
 875                }
 876
 877                Some(Toolchain {
 878                    name: name.into(),
 879                    path: toolchain.executable.as_ref()?.to_str()?.to_owned().into(),
 880                    language_name: LanguageName::new("Python"),
 881                    as_json: serde_json::to_value(toolchain.clone()).ok()?,
 882                })
 883            })
 884            .collect();
 885        toolchains.dedup();
 886        ToolchainList {
 887            toolchains,
 888            default: None,
 889            groups: Default::default(),
 890        }
 891    }
 892    fn term(&self) -> SharedString {
 893        self.term.clone()
 894    }
 895    async fn activation_script(
 896        &self,
 897        toolchain: &Toolchain,
 898        shell: ShellKind,
 899        fs: &dyn Fs,
 900    ) -> Vec<String> {
 901        let Ok(toolchain) = serde_json::from_value::<pet_core::python_environment::PythonEnvironment>(
 902            toolchain.as_json.clone(),
 903        ) else {
 904            return vec![];
 905        };
 906        let mut activation_script = vec![];
 907
 908        match toolchain.kind {
 909            Some(PythonEnvironmentKind::Pixi) => {
 910                let env = toolchain.name.as_deref().unwrap_or("default");
 911                activation_script.push(format!("pixi shell -e {env}"))
 912            }
 913            Some(PythonEnvironmentKind::Venv | PythonEnvironmentKind::VirtualEnv) => {
 914                if let Some(prefix) = &toolchain.prefix {
 915                    let activate_keyword = match shell {
 916                        ShellKind::Cmd => ".",
 917                        ShellKind::Nushell => "overlay use",
 918                        ShellKind::Powershell => ".",
 919                        ShellKind::Fish => "source",
 920                        ShellKind::Csh => "source",
 921                        ShellKind::Posix => "source",
 922                    };
 923                    let activate_script_name = match shell {
 924                        ShellKind::Posix => "activate",
 925                        ShellKind::Csh => "activate.csh",
 926                        ShellKind::Fish => "activate.fish",
 927                        ShellKind::Nushell => "activate.nu",
 928                        ShellKind::Powershell => "activate.ps1",
 929                        ShellKind::Cmd => "activate.bat",
 930                    };
 931                    let path = prefix.join(BINARY_DIR).join(activate_script_name);
 932                    if fs.is_file(&path).await {
 933                        activation_script.push(format!("{activate_keyword} {}", path.display()));
 934                    }
 935                }
 936            }
 937            Some(PythonEnvironmentKind::Pyenv) => {
 938                let Some(manager) = toolchain.manager else {
 939                    return vec![];
 940                };
 941                let version = toolchain.version.as_deref().unwrap_or("system");
 942                let pyenv = manager.executable;
 943                let pyenv = pyenv.display();
 944                activation_script.extend(match shell {
 945                    ShellKind::Fish => Some(format!("{pyenv} shell - fish {version}")),
 946                    ShellKind::Posix => Some(format!("{pyenv} shell - sh {version}")),
 947                    ShellKind::Nushell => Some(format!("{pyenv} shell - nu {version}")),
 948                    ShellKind::Powershell => None,
 949                    ShellKind::Csh => None,
 950                    ShellKind::Cmd => None,
 951                })
 952            }
 953            _ => {}
 954        }
 955        activation_script
 956    }
 957}
 958
 959pub struct EnvironmentApi<'a> {
 960    global_search_locations: Arc<Mutex<Vec<PathBuf>>>,
 961    project_env: &'a HashMap<String, String>,
 962    pet_env: pet_core::os_environment::EnvironmentApi,
 963}
 964
 965impl<'a> EnvironmentApi<'a> {
 966    pub fn from_env(project_env: &'a HashMap<String, String>) -> Self {
 967        let paths = project_env
 968            .get("PATH")
 969            .map(|p| std::env::split_paths(p).collect())
 970            .unwrap_or_default();
 971
 972        EnvironmentApi {
 973            global_search_locations: Arc::new(Mutex::new(paths)),
 974            project_env,
 975            pet_env: pet_core::os_environment::EnvironmentApi::new(),
 976        }
 977    }
 978
 979    fn user_home(&self) -> Option<PathBuf> {
 980        self.project_env
 981            .get("HOME")
 982            .or_else(|| self.project_env.get("USERPROFILE"))
 983            .map(|home| pet_fs::path::norm_case(PathBuf::from(home)))
 984            .or_else(|| self.pet_env.get_user_home())
 985    }
 986}
 987
 988impl pet_core::os_environment::Environment for EnvironmentApi<'_> {
 989    fn get_user_home(&self) -> Option<PathBuf> {
 990        self.user_home()
 991    }
 992
 993    fn get_root(&self) -> Option<PathBuf> {
 994        None
 995    }
 996
 997    fn get_env_var(&self, key: String) -> Option<String> {
 998        self.project_env
 999            .get(&key)
1000            .cloned()
1001            .or_else(|| self.pet_env.get_env_var(key))
1002    }
1003
1004    fn get_know_global_search_locations(&self) -> Vec<PathBuf> {
1005        if self.global_search_locations.lock().is_empty() {
1006            let mut paths =
1007                std::env::split_paths(&self.get_env_var("PATH".to_string()).unwrap_or_default())
1008                    .collect::<Vec<PathBuf>>();
1009
1010            log::trace!("Env PATH: {:?}", paths);
1011            for p in self.pet_env.get_know_global_search_locations() {
1012                if !paths.contains(&p) {
1013                    paths.push(p);
1014                }
1015            }
1016
1017            let mut paths = paths
1018                .into_iter()
1019                .filter(|p| p.exists())
1020                .collect::<Vec<PathBuf>>();
1021
1022            self.global_search_locations.lock().append(&mut paths);
1023        }
1024        self.global_search_locations.lock().clone()
1025    }
1026}
1027
1028pub(crate) struct PyLspAdapter {
1029    python_venv_base: OnceCell<Result<Arc<Path>, String>>,
1030}
1031impl PyLspAdapter {
1032    const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("pylsp");
1033    pub(crate) fn new() -> Self {
1034        Self {
1035            python_venv_base: OnceCell::new(),
1036        }
1037    }
1038    async fn ensure_venv(delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>> {
1039        let python_path = Self::find_base_python(delegate)
1040            .await
1041            .context("Could not find Python installation for PyLSP")?;
1042        let work_dir = delegate
1043            .language_server_download_dir(&Self::SERVER_NAME)
1044            .await
1045            .context("Could not get working directory for PyLSP")?;
1046        let mut path = PathBuf::from(work_dir.as_ref());
1047        path.push("pylsp-venv");
1048        if !path.exists() {
1049            util::command::new_smol_command(python_path)
1050                .arg("-m")
1051                .arg("venv")
1052                .arg("pylsp-venv")
1053                .current_dir(work_dir)
1054                .spawn()?
1055                .output()
1056                .await?;
1057        }
1058
1059        Ok(path.into())
1060    }
1061    // Find "baseline", user python version from which we'll create our own venv.
1062    async fn find_base_python(delegate: &dyn LspAdapterDelegate) -> Option<PathBuf> {
1063        for path in ["python3", "python"] {
1064            if let Some(path) = delegate.which(path.as_ref()).await {
1065                return Some(path);
1066            }
1067        }
1068        None
1069    }
1070
1071    async fn base_venv(&self, delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>, String> {
1072        self.python_venv_base
1073            .get_or_init(move || async move {
1074                Self::ensure_venv(delegate)
1075                    .await
1076                    .map_err(|e| format!("{e}"))
1077            })
1078            .await
1079            .clone()
1080    }
1081}
1082
1083const BINARY_DIR: &str = if cfg!(target_os = "windows") {
1084    "Scripts"
1085} else {
1086    "bin"
1087};
1088
1089#[async_trait(?Send)]
1090impl LspAdapter for PyLspAdapter {
1091    fn name(&self) -> LanguageServerName {
1092        Self::SERVER_NAME
1093    }
1094
1095    async fn check_if_user_installed(
1096        &self,
1097        delegate: &dyn LspAdapterDelegate,
1098        toolchain: Option<Toolchain>,
1099        _: &AsyncApp,
1100    ) -> Option<LanguageServerBinary> {
1101        if let Some(pylsp_bin) = delegate.which(Self::SERVER_NAME.as_ref()).await {
1102            let env = delegate.shell_env().await;
1103            Some(LanguageServerBinary {
1104                path: pylsp_bin,
1105                env: Some(env),
1106                arguments: vec![],
1107            })
1108        } else {
1109            let venv = toolchain?;
1110            let pylsp_path = Path::new(venv.path.as_ref()).parent()?.join("pylsp");
1111            pylsp_path.exists().then(|| LanguageServerBinary {
1112                path: venv.path.to_string().into(),
1113                arguments: vec![pylsp_path.into()],
1114                env: None,
1115            })
1116        }
1117    }
1118
1119    async fn fetch_latest_server_version(
1120        &self,
1121        _: &dyn LspAdapterDelegate,
1122    ) -> Result<Box<dyn 'static + Any + Send>> {
1123        Ok(Box::new(()) as Box<_>)
1124    }
1125
1126    async fn fetch_server_binary(
1127        &self,
1128        _: Box<dyn 'static + Send + Any>,
1129        _: PathBuf,
1130        delegate: &dyn LspAdapterDelegate,
1131    ) -> Result<LanguageServerBinary> {
1132        let venv = self.base_venv(delegate).await.map_err(|e| anyhow!(e))?;
1133        let pip_path = venv.join(BINARY_DIR).join("pip3");
1134        ensure!(
1135            util::command::new_smol_command(pip_path.as_path())
1136                .arg("install")
1137                .arg("python-lsp-server")
1138                .arg("-U")
1139                .output()
1140                .await?
1141                .status
1142                .success(),
1143            "python-lsp-server installation failed"
1144        );
1145        ensure!(
1146            util::command::new_smol_command(pip_path.as_path())
1147                .arg("install")
1148                .arg("python-lsp-server[all]")
1149                .arg("-U")
1150                .output()
1151                .await?
1152                .status
1153                .success(),
1154            "python-lsp-server[all] installation failed"
1155        );
1156        ensure!(
1157            util::command::new_smol_command(pip_path)
1158                .arg("install")
1159                .arg("pylsp-mypy")
1160                .arg("-U")
1161                .output()
1162                .await?
1163                .status
1164                .success(),
1165            "pylsp-mypy installation failed"
1166        );
1167        let pylsp = venv.join(BINARY_DIR).join("pylsp");
1168        Ok(LanguageServerBinary {
1169            path: pylsp,
1170            env: None,
1171            arguments: vec![],
1172        })
1173    }
1174
1175    async fn cached_server_binary(
1176        &self,
1177        _: PathBuf,
1178        delegate: &dyn LspAdapterDelegate,
1179    ) -> Option<LanguageServerBinary> {
1180        let venv = self.base_venv(delegate).await.ok()?;
1181        let pylsp = venv.join(BINARY_DIR).join("pylsp");
1182        Some(LanguageServerBinary {
1183            path: pylsp,
1184            env: None,
1185            arguments: vec![],
1186        })
1187    }
1188
1189    async fn process_completions(&self, _items: &mut [lsp::CompletionItem]) {}
1190
1191    async fn label_for_completion(
1192        &self,
1193        item: &lsp::CompletionItem,
1194        language: &Arc<language::Language>,
1195    ) -> Option<language::CodeLabel> {
1196        let label = &item.label;
1197        let grammar = language.grammar()?;
1198        let highlight_id = match item.kind? {
1199            lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method")?,
1200            lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function")?,
1201            lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type")?,
1202            lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant")?,
1203            _ => return None,
1204        };
1205        let filter_range = item
1206            .filter_text
1207            .as_deref()
1208            .and_then(|filter| label.find(filter).map(|ix| ix..ix + filter.len()))
1209            .unwrap_or(0..label.len());
1210        Some(language::CodeLabel {
1211            text: label.clone(),
1212            runs: vec![(0..label.len(), highlight_id)],
1213            filter_range,
1214        })
1215    }
1216
1217    async fn label_for_symbol(
1218        &self,
1219        name: &str,
1220        kind: lsp::SymbolKind,
1221        language: &Arc<language::Language>,
1222    ) -> Option<language::CodeLabel> {
1223        let (text, filter_range, display_range) = match kind {
1224            lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
1225                let text = format!("def {}():\n", name);
1226                let filter_range = 4..4 + name.len();
1227                let display_range = 0..filter_range.end;
1228                (text, filter_range, display_range)
1229            }
1230            lsp::SymbolKind::CLASS => {
1231                let text = format!("class {}:", name);
1232                let filter_range = 6..6 + name.len();
1233                let display_range = 0..filter_range.end;
1234                (text, filter_range, display_range)
1235            }
1236            lsp::SymbolKind::CONSTANT => {
1237                let text = format!("{} = 0", name);
1238                let filter_range = 0..name.len();
1239                let display_range = 0..filter_range.end;
1240                (text, filter_range, display_range)
1241            }
1242            _ => return None,
1243        };
1244
1245        Some(language::CodeLabel {
1246            runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
1247            text: text[display_range].to_string(),
1248            filter_range,
1249        })
1250    }
1251
1252    async fn workspace_configuration(
1253        self: Arc<Self>,
1254        _: &dyn Fs,
1255        adapter: &Arc<dyn LspAdapterDelegate>,
1256        toolchain: Option<Toolchain>,
1257        cx: &mut AsyncApp,
1258    ) -> Result<Value> {
1259        cx.update(move |cx| {
1260            let mut user_settings =
1261                language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
1262                    .and_then(|s| s.settings.clone())
1263                    .unwrap_or_else(|| {
1264                        json!({
1265                            "plugins": {
1266                                "pycodestyle": {"enabled": false},
1267                                "rope_autoimport": {"enabled": true, "memory": true},
1268                                "pylsp_mypy": {"enabled": false}
1269                            },
1270                            "rope": {
1271                                "ropeFolder": null
1272                            },
1273                        })
1274                    });
1275
1276            // If user did not explicitly modify their python venv, use one from picker.
1277            if let Some(toolchain) = toolchain {
1278                if user_settings.is_null() {
1279                    user_settings = Value::Object(serde_json::Map::default());
1280                }
1281                let object = user_settings.as_object_mut().unwrap();
1282                if let Some(python) = object
1283                    .entry("plugins")
1284                    .or_insert(Value::Object(serde_json::Map::default()))
1285                    .as_object_mut()
1286                {
1287                    if let Some(jedi) = python
1288                        .entry("jedi")
1289                        .or_insert(Value::Object(serde_json::Map::default()))
1290                        .as_object_mut()
1291                    {
1292                        jedi.entry("environment".to_string())
1293                            .or_insert_with(|| Value::String(toolchain.path.clone().into()));
1294                    }
1295                    if let Some(pylint) = python
1296                        .entry("pylsp_mypy")
1297                        .or_insert(Value::Object(serde_json::Map::default()))
1298                        .as_object_mut()
1299                    {
1300                        pylint.entry("overrides".to_string()).or_insert_with(|| {
1301                            Value::Array(vec![
1302                                Value::String("--python-executable".into()),
1303                                Value::String(toolchain.path.into()),
1304                                Value::String("--cache-dir=/dev/null".into()),
1305                                Value::Bool(true),
1306                            ])
1307                        });
1308                    }
1309                }
1310            }
1311            user_settings = Value::Object(serde_json::Map::from_iter([(
1312                "pylsp".to_string(),
1313                user_settings,
1314            )]));
1315
1316            user_settings
1317        })
1318    }
1319}
1320
1321pub(crate) struct BasedPyrightLspAdapter {
1322    python_venv_base: OnceCell<Result<Arc<Path>, String>>,
1323}
1324
1325impl BasedPyrightLspAdapter {
1326    const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("basedpyright");
1327    const BINARY_NAME: &'static str = "basedpyright-langserver";
1328
1329    pub(crate) fn new() -> Self {
1330        Self {
1331            python_venv_base: OnceCell::new(),
1332        }
1333    }
1334
1335    async fn ensure_venv(delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>> {
1336        let python_path = Self::find_base_python(delegate)
1337            .await
1338            .context("Could not find Python installation for basedpyright")?;
1339        let work_dir = delegate
1340            .language_server_download_dir(&Self::SERVER_NAME)
1341            .await
1342            .context("Could not get working directory for basedpyright")?;
1343        let mut path = PathBuf::from(work_dir.as_ref());
1344        path.push("basedpyright-venv");
1345        if !path.exists() {
1346            util::command::new_smol_command(python_path)
1347                .arg("-m")
1348                .arg("venv")
1349                .arg("basedpyright-venv")
1350                .current_dir(work_dir)
1351                .spawn()?
1352                .output()
1353                .await?;
1354        }
1355
1356        Ok(path.into())
1357    }
1358
1359    // Find "baseline", user python version from which we'll create our own venv.
1360    async fn find_base_python(delegate: &dyn LspAdapterDelegate) -> Option<PathBuf> {
1361        for path in ["python3", "python"] {
1362            if let Some(path) = delegate.which(path.as_ref()).await {
1363                return Some(path);
1364            }
1365        }
1366        None
1367    }
1368
1369    async fn base_venv(&self, delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>, String> {
1370        self.python_venv_base
1371            .get_or_init(move || async move {
1372                Self::ensure_venv(delegate)
1373                    .await
1374                    .map_err(|e| format!("{e}"))
1375            })
1376            .await
1377            .clone()
1378    }
1379}
1380
1381#[async_trait(?Send)]
1382impl LspAdapter for BasedPyrightLspAdapter {
1383    fn name(&self) -> LanguageServerName {
1384        Self::SERVER_NAME
1385    }
1386
1387    async fn initialization_options(
1388        self: Arc<Self>,
1389        _: &dyn Fs,
1390        _: &Arc<dyn LspAdapterDelegate>,
1391    ) -> Result<Option<Value>> {
1392        // Provide minimal initialization options
1393        // Virtual environment configuration will be handled through workspace configuration
1394        Ok(Some(json!({
1395            "python": {
1396                "analysis": {
1397                    "autoSearchPaths": true,
1398                    "useLibraryCodeForTypes": true,
1399                    "autoImportCompletions": true
1400                }
1401            }
1402        })))
1403    }
1404
1405    async fn check_if_user_installed(
1406        &self,
1407        delegate: &dyn LspAdapterDelegate,
1408        toolchain: Option<Toolchain>,
1409        _: &AsyncApp,
1410    ) -> Option<LanguageServerBinary> {
1411        if let Some(bin) = delegate.which(Self::BINARY_NAME.as_ref()).await {
1412            let env = delegate.shell_env().await;
1413            Some(LanguageServerBinary {
1414                path: bin,
1415                env: Some(env),
1416                arguments: vec!["--stdio".into()],
1417            })
1418        } else {
1419            let path = Path::new(toolchain?.path.as_ref())
1420                .parent()?
1421                .join(Self::BINARY_NAME);
1422            path.exists().then(|| LanguageServerBinary {
1423                path,
1424                arguments: vec!["--stdio".into()],
1425                env: None,
1426            })
1427        }
1428    }
1429
1430    async fn fetch_latest_server_version(
1431        &self,
1432        _: &dyn LspAdapterDelegate,
1433    ) -> Result<Box<dyn 'static + Any + Send>> {
1434        Ok(Box::new(()) as Box<_>)
1435    }
1436
1437    async fn fetch_server_binary(
1438        &self,
1439        _latest_version: Box<dyn 'static + Send + Any>,
1440        _container_dir: PathBuf,
1441        delegate: &dyn LspAdapterDelegate,
1442    ) -> Result<LanguageServerBinary> {
1443        let venv = self.base_venv(delegate).await.map_err(|e| anyhow!(e))?;
1444        let pip_path = venv.join(BINARY_DIR).join("pip3");
1445        ensure!(
1446            util::command::new_smol_command(pip_path.as_path())
1447                .arg("install")
1448                .arg("basedpyright")
1449                .arg("-U")
1450                .output()
1451                .await?
1452                .status
1453                .success(),
1454            "basedpyright installation failed"
1455        );
1456        let pylsp = venv.join(BINARY_DIR).join(Self::BINARY_NAME);
1457        Ok(LanguageServerBinary {
1458            path: pylsp,
1459            env: None,
1460            arguments: vec!["--stdio".into()],
1461        })
1462    }
1463
1464    async fn cached_server_binary(
1465        &self,
1466        _container_dir: PathBuf,
1467        delegate: &dyn LspAdapterDelegate,
1468    ) -> Option<LanguageServerBinary> {
1469        let venv = self.base_venv(delegate).await.ok()?;
1470        let pylsp = venv.join(BINARY_DIR).join(Self::BINARY_NAME);
1471        Some(LanguageServerBinary {
1472            path: pylsp,
1473            env: None,
1474            arguments: vec!["--stdio".into()],
1475        })
1476    }
1477
1478    async fn process_completions(&self, items: &mut [lsp::CompletionItem]) {
1479        // Pyright assigns each completion item a `sortText` of the form `XX.YYYY.name`.
1480        // Where `XX` is the sorting category, `YYYY` is based on most recent usage,
1481        // and `name` is the symbol name itself.
1482        //
1483        // Because the symbol name is included, there generally are not ties when
1484        // sorting by the `sortText`, so the symbol's fuzzy match score is not taken
1485        // into account. Here, we remove the symbol name from the sortText in order
1486        // to allow our own fuzzy score to be used to break ties.
1487        //
1488        // see https://github.com/microsoft/pyright/blob/95ef4e103b9b2f129c9320427e51b73ea7cf78bd/packages/pyright-internal/src/languageService/completionProvider.ts#LL2873
1489        for item in items {
1490            let Some(sort_text) = &mut item.sort_text else {
1491                continue;
1492            };
1493            let mut parts = sort_text.split('.');
1494            let Some(first) = parts.next() else { continue };
1495            let Some(second) = parts.next() else { continue };
1496            let Some(_) = parts.next() else { continue };
1497            sort_text.replace_range(first.len() + second.len() + 1.., "");
1498        }
1499    }
1500
1501    async fn label_for_completion(
1502        &self,
1503        item: &lsp::CompletionItem,
1504        language: &Arc<language::Language>,
1505    ) -> Option<language::CodeLabel> {
1506        let label = &item.label;
1507        let grammar = language.grammar()?;
1508        let highlight_id = match item.kind? {
1509            lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method")?,
1510            lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function")?,
1511            lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type")?,
1512            lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant")?,
1513            _ => return None,
1514        };
1515        let filter_range = item
1516            .filter_text
1517            .as_deref()
1518            .and_then(|filter| label.find(filter).map(|ix| ix..ix + filter.len()))
1519            .unwrap_or(0..label.len());
1520        Some(language::CodeLabel {
1521            text: label.clone(),
1522            runs: vec![(0..label.len(), highlight_id)],
1523            filter_range,
1524        })
1525    }
1526
1527    async fn label_for_symbol(
1528        &self,
1529        name: &str,
1530        kind: lsp::SymbolKind,
1531        language: &Arc<language::Language>,
1532    ) -> Option<language::CodeLabel> {
1533        let (text, filter_range, display_range) = match kind {
1534            lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
1535                let text = format!("def {}():\n", name);
1536                let filter_range = 4..4 + name.len();
1537                let display_range = 0..filter_range.end;
1538                (text, filter_range, display_range)
1539            }
1540            lsp::SymbolKind::CLASS => {
1541                let text = format!("class {}:", name);
1542                let filter_range = 6..6 + name.len();
1543                let display_range = 0..filter_range.end;
1544                (text, filter_range, display_range)
1545            }
1546            lsp::SymbolKind::CONSTANT => {
1547                let text = format!("{} = 0", name);
1548                let filter_range = 0..name.len();
1549                let display_range = 0..filter_range.end;
1550                (text, filter_range, display_range)
1551            }
1552            _ => return None,
1553        };
1554
1555        Some(language::CodeLabel {
1556            runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
1557            text: text[display_range].to_string(),
1558            filter_range,
1559        })
1560    }
1561
1562    async fn workspace_configuration(
1563        self: Arc<Self>,
1564        _: &dyn Fs,
1565        adapter: &Arc<dyn LspAdapterDelegate>,
1566        toolchain: Option<Toolchain>,
1567        cx: &mut AsyncApp,
1568    ) -> Result<Value> {
1569        cx.update(move |cx| {
1570            let mut user_settings =
1571                language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
1572                    .and_then(|s| s.settings.clone())
1573                    .unwrap_or_default();
1574
1575            // If we have a detected toolchain, configure Pyright to use it
1576            if let Some(toolchain) = toolchain {
1577                if user_settings.is_null() {
1578                    user_settings = Value::Object(serde_json::Map::default());
1579                }
1580                let object = user_settings.as_object_mut().unwrap();
1581
1582                let interpreter_path = toolchain.path.to_string();
1583
1584                // Detect if this is a virtual environment
1585                if let Some(interpreter_dir) = Path::new(&interpreter_path).parent()
1586                    && let Some(venv_dir) = interpreter_dir.parent()
1587                {
1588                    // Check if this looks like a virtual environment
1589                    if venv_dir.join("pyvenv.cfg").exists()
1590                        || venv_dir.join("bin/activate").exists()
1591                        || venv_dir.join("Scripts/activate.bat").exists()
1592                    {
1593                        // Set venvPath and venv at the root level
1594                        // This matches the format of a pyrightconfig.json file
1595                        if let Some(parent) = venv_dir.parent() {
1596                            // Use relative path if the venv is inside the workspace
1597                            let venv_path = if parent == adapter.worktree_root_path() {
1598                                ".".to_string()
1599                            } else {
1600                                parent.to_string_lossy().into_owned()
1601                            };
1602                            object.insert("venvPath".to_string(), Value::String(venv_path));
1603                        }
1604
1605                        if let Some(venv_name) = venv_dir.file_name() {
1606                            object.insert(
1607                                "venv".to_owned(),
1608                                Value::String(venv_name.to_string_lossy().into_owned()),
1609                            );
1610                        }
1611                    }
1612                }
1613
1614                // Always set the python interpreter path
1615                // Get or create the python section
1616                let python = object
1617                    .entry("python")
1618                    .or_insert(Value::Object(serde_json::Map::default()))
1619                    .as_object_mut()
1620                    .unwrap();
1621
1622                // Set both pythonPath and defaultInterpreterPath for compatibility
1623                python.insert(
1624                    "pythonPath".to_owned(),
1625                    Value::String(interpreter_path.clone()),
1626                );
1627                python.insert(
1628                    "defaultInterpreterPath".to_owned(),
1629                    Value::String(interpreter_path),
1630                );
1631            }
1632
1633            user_settings
1634        })
1635    }
1636}
1637
1638#[cfg(test)]
1639mod tests {
1640    use gpui::{AppContext as _, BorrowAppContext, Context, TestAppContext};
1641    use language::{AutoindentMode, Buffer, language_settings::AllLanguageSettings};
1642    use settings::SettingsStore;
1643    use std::num::NonZeroU32;
1644
1645    #[gpui::test]
1646    async fn test_python_autoindent(cx: &mut TestAppContext) {
1647        cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
1648        let language = crate::language("python", tree_sitter_python::LANGUAGE.into());
1649        cx.update(|cx| {
1650            let test_settings = SettingsStore::test(cx);
1651            cx.set_global(test_settings);
1652            language::init(cx);
1653            cx.update_global::<SettingsStore, _>(|store, cx| {
1654                store.update_user_settings::<AllLanguageSettings>(cx, |s| {
1655                    s.defaults.tab_size = NonZeroU32::new(2);
1656                });
1657            });
1658        });
1659
1660        cx.new(|cx| {
1661            let mut buffer = Buffer::local("", cx).with_language(language, cx);
1662            let append = |buffer: &mut Buffer, text: &str, cx: &mut Context<Buffer>| {
1663                let ix = buffer.len();
1664                buffer.edit([(ix..ix, text)], Some(AutoindentMode::EachLine), cx);
1665            };
1666
1667            // indent after "def():"
1668            append(&mut buffer, "def a():\n", cx);
1669            assert_eq!(buffer.text(), "def a():\n  ");
1670
1671            // preserve indent after blank line
1672            append(&mut buffer, "\n  ", cx);
1673            assert_eq!(buffer.text(), "def a():\n  \n  ");
1674
1675            // indent after "if"
1676            append(&mut buffer, "if a:\n  ", cx);
1677            assert_eq!(buffer.text(), "def a():\n  \n  if a:\n    ");
1678
1679            // preserve indent after statement
1680            append(&mut buffer, "b()\n", cx);
1681            assert_eq!(buffer.text(), "def a():\n  \n  if a:\n    b()\n    ");
1682
1683            // preserve indent after statement
1684            append(&mut buffer, "else", cx);
1685            assert_eq!(buffer.text(), "def a():\n  \n  if a:\n    b()\n    else");
1686
1687            // dedent "else""
1688            append(&mut buffer, ":", cx);
1689            assert_eq!(buffer.text(), "def a():\n  \n  if a:\n    b()\n  else:");
1690
1691            // indent lines after else
1692            append(&mut buffer, "\n", cx);
1693            assert_eq!(
1694                buffer.text(),
1695                "def a():\n  \n  if a:\n    b()\n  else:\n    "
1696            );
1697
1698            // indent after an open paren. the closing paren is not indented
1699            // because there is another token before it on the same line.
1700            append(&mut buffer, "foo(\n1)", cx);
1701            assert_eq!(
1702                buffer.text(),
1703                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n      1)"
1704            );
1705
1706            // dedent the closing paren if it is shifted to the beginning of the line
1707            let argument_ix = buffer.text().find('1').unwrap();
1708            buffer.edit(
1709                [(argument_ix..argument_ix + 1, "")],
1710                Some(AutoindentMode::EachLine),
1711                cx,
1712            );
1713            assert_eq!(
1714                buffer.text(),
1715                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n    )"
1716            );
1717
1718            // preserve indent after the close paren
1719            append(&mut buffer, "\n", cx);
1720            assert_eq!(
1721                buffer.text(),
1722                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n    )\n    "
1723            );
1724
1725            // manually outdent the last line
1726            let end_whitespace_ix = buffer.len() - 4;
1727            buffer.edit(
1728                [(end_whitespace_ix..buffer.len(), "")],
1729                Some(AutoindentMode::EachLine),
1730                cx,
1731            );
1732            assert_eq!(
1733                buffer.text(),
1734                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n    )\n"
1735            );
1736
1737            // preserve the newly reduced indentation on the next newline
1738            append(&mut buffer, "\n", cx);
1739            assert_eq!(
1740                buffer.text(),
1741                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n    )\n\n"
1742            );
1743
1744            // reset to a simple if statement
1745            buffer.edit([(0..buffer.len(), "if a:\n  b(\n  )")], None, cx);
1746
1747            // dedent "else" on the line after a closing paren
1748            append(&mut buffer, "\n  else:\n", cx);
1749            assert_eq!(buffer.text(), "if a:\n  b(\n  )\nelse:\n  ");
1750
1751            buffer
1752        });
1753    }
1754}