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