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