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