python.rs

   1use anyhow::ensure;
   2use anyhow::{Result, anyhow};
   3use async_trait::async_trait;
   4use collections::HashMap;
   5use gpui::{App, Task};
   6use gpui::{AsyncApp, SharedString};
   7use language::LanguageToolchainStore;
   8use language::Toolchain;
   9use language::ToolchainList;
  10use language::ToolchainLister;
  11use language::language_settings::language_settings;
  12use language::{ContextProvider, LspAdapter, LspAdapterDelegate};
  13use language::{LanguageName, ManifestName, ManifestProvider, ManifestQuery};
  14use lsp::LanguageServerBinary;
  15use lsp::LanguageServerName;
  16use node_runtime::NodeRuntime;
  17use pet_core::Configuration;
  18use pet_core::os_environment::Environment;
  19use pet_core::python_environment::PythonEnvironmentKind;
  20use project::Fs;
  21use project::lsp_store::language_server_settings;
  22use serde_json::{Value, json};
  23use smol::lock::OnceCell;
  24use std::cmp::Ordering;
  25
  26use std::str::FromStr;
  27use std::sync::Mutex;
  28use std::{
  29    any::Any,
  30    borrow::Cow,
  31    ffi::OsString,
  32    fmt::Write,
  33    fs,
  34    io::{self, BufRead},
  35    path::{Path, PathBuf},
  36    sync::Arc,
  37};
  38use task::{TaskTemplate, TaskTemplates, VariableName};
  39use util::ResultExt;
  40
  41pub(crate) struct PyprojectTomlManifestProvider;
  42
  43impl ManifestProvider for PyprojectTomlManifestProvider {
  44    fn name(&self) -> ManifestName {
  45        SharedString::new_static("pyproject.toml").into()
  46    }
  47
  48    fn search(
  49        &self,
  50        ManifestQuery {
  51            path,
  52            depth,
  53            delegate,
  54        }: ManifestQuery,
  55    ) -> Option<Arc<Path>> {
  56        for path in path.ancestors().take(depth) {
  57            let p = path.join("pyproject.toml");
  58            if delegate.exists(&p, Some(false)) {
  59                return Some(path.into());
  60            }
  61        }
  62
  63        None
  64    }
  65}
  66
  67const SERVER_PATH: &str = "node_modules/pyright/langserver.index.js";
  68const NODE_MODULE_RELATIVE_SERVER_PATH: &str = "pyright/langserver.index.js";
  69
  70enum TestRunner {
  71    UNITTEST,
  72    PYTEST,
  73}
  74
  75impl FromStr for TestRunner {
  76    type Err = ();
  77
  78    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
  79        match s {
  80            "unittest" => Ok(Self::UNITTEST),
  81            "pytest" => Ok(Self::PYTEST),
  82            _ => Err(()),
  83        }
  84    }
  85}
  86
  87fn server_binary_arguments(server_path: &Path) -> Vec<OsString> {
  88    vec![server_path.into(), "--stdio".into()]
  89}
  90
  91pub struct PythonLspAdapter {
  92    node: NodeRuntime,
  93}
  94
  95impl PythonLspAdapter {
  96    const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("pyright");
  97
  98    pub fn new(node: NodeRuntime) -> Self {
  99        PythonLspAdapter { node }
 100    }
 101}
 102
 103#[async_trait(?Send)]
 104impl LspAdapter for PythonLspAdapter {
 105    fn name(&self) -> LanguageServerName {
 106        Self::SERVER_NAME.clone()
 107    }
 108
 109    async fn check_if_user_installed(
 110        &self,
 111        delegate: &dyn LspAdapterDelegate,
 112        _: Arc<dyn LanguageToolchainStore>,
 113        _: &AsyncApp,
 114    ) -> Option<LanguageServerBinary> {
 115        if let Some(pyright_bin) = delegate.which("pyright-langserver".as_ref()).await {
 116            let env = delegate.shell_env().await;
 117            Some(LanguageServerBinary {
 118                path: pyright_bin,
 119                env: Some(env),
 120                arguments: vec!["--stdio".into()],
 121            })
 122        } else {
 123            let node = delegate.which("node".as_ref()).await?;
 124            let (node_modules_path, _) = delegate
 125                .npm_package_installed_version(Self::SERVER_NAME.as_ref())
 126                .await
 127                .log_err()??;
 128
 129            let path = node_modules_path.join(NODE_MODULE_RELATIVE_SERVER_PATH);
 130
 131            Some(LanguageServerBinary {
 132                path: node,
 133                env: None,
 134                arguments: server_binary_arguments(&path),
 135            })
 136        }
 137    }
 138
 139    async fn fetch_latest_server_version(
 140        &self,
 141        _: &dyn LspAdapterDelegate,
 142    ) -> Result<Box<dyn 'static + Any + Send>> {
 143        Ok(Box::new(
 144            self.node
 145                .npm_package_latest_version(Self::SERVER_NAME.as_ref())
 146                .await?,
 147        ) as Box<_>)
 148    }
 149
 150    async fn fetch_server_binary(
 151        &self,
 152        latest_version: Box<dyn 'static + Send + Any>,
 153        container_dir: PathBuf,
 154        _: &dyn LspAdapterDelegate,
 155    ) -> Result<LanguageServerBinary> {
 156        let latest_version = latest_version.downcast::<String>().unwrap();
 157        let server_path = container_dir.join(SERVER_PATH);
 158
 159        self.node
 160            .npm_install_packages(
 161                &container_dir,
 162                &[(Self::SERVER_NAME.as_ref(), latest_version.as_str())],
 163            )
 164            .await?;
 165
 166        Ok(LanguageServerBinary {
 167            path: self.node.binary_path().await?,
 168            env: None,
 169            arguments: server_binary_arguments(&server_path),
 170        })
 171    }
 172
 173    async fn check_if_version_installed(
 174        &self,
 175        version: &(dyn 'static + Send + Any),
 176        container_dir: &PathBuf,
 177        _: &dyn LspAdapterDelegate,
 178    ) -> Option<LanguageServerBinary> {
 179        let version = version.downcast_ref::<String>().unwrap();
 180        let server_path = container_dir.join(SERVER_PATH);
 181
 182        let should_install_language_server = self
 183            .node
 184            .should_install_npm_package(
 185                Self::SERVER_NAME.as_ref(),
 186                &server_path,
 187                &container_dir,
 188                &version,
 189            )
 190            .await;
 191
 192        if should_install_language_server {
 193            None
 194        } else {
 195            Some(LanguageServerBinary {
 196                path: self.node.binary_path().await.ok()?,
 197                env: None,
 198                arguments: server_binary_arguments(&server_path),
 199            })
 200        }
 201    }
 202
 203    async fn cached_server_binary(
 204        &self,
 205        container_dir: PathBuf,
 206        _: &dyn LspAdapterDelegate,
 207    ) -> Option<LanguageServerBinary> {
 208        get_cached_server_binary(container_dir, &self.node).await
 209    }
 210
 211    async fn process_completions(&self, items: &mut [lsp::CompletionItem]) {
 212        // Pyright assigns each completion item a `sortText` of the form `XX.YYYY.name`.
 213        // Where `XX` is the sorting category, `YYYY` is based on most recent usage,
 214        // and `name` is the symbol name itself.
 215        //
 216        // Because the symbol name is included, there generally are not ties when
 217        // sorting by the `sortText`, so the symbol's fuzzy match score is not taken
 218        // into account. Here, we remove the symbol name from the sortText in order
 219        // to allow our own fuzzy score to be used to break ties.
 220        //
 221        // see https://github.com/microsoft/pyright/blob/95ef4e103b9b2f129c9320427e51b73ea7cf78bd/packages/pyright-internal/src/languageService/completionProvider.ts#LL2873
 222        for item in items {
 223            let Some(sort_text) = &mut item.sort_text else {
 224                continue;
 225            };
 226            let mut parts = sort_text.split('.');
 227            let Some(first) = parts.next() else { continue };
 228            let Some(second) = parts.next() else { continue };
 229            let Some(_) = parts.next() else { continue };
 230            sort_text.replace_range(first.len() + second.len() + 1.., "");
 231        }
 232    }
 233
 234    async fn label_for_completion(
 235        &self,
 236        item: &lsp::CompletionItem,
 237        language: &Arc<language::Language>,
 238    ) -> Option<language::CodeLabel> {
 239        let label = &item.label;
 240        let grammar = language.grammar()?;
 241        let highlight_id = match item.kind? {
 242            lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method")?,
 243            lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function")?,
 244            lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type")?,
 245            lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant")?,
 246            _ => return None,
 247        };
 248        Some(language::CodeLabel {
 249            text: label.clone(),
 250            runs: vec![(0..label.len(), highlight_id)],
 251            filter_range: 0..label.len(),
 252        })
 253    }
 254
 255    async fn label_for_symbol(
 256        &self,
 257        name: &str,
 258        kind: lsp::SymbolKind,
 259        language: &Arc<language::Language>,
 260    ) -> Option<language::CodeLabel> {
 261        let (text, filter_range, display_range) = match kind {
 262            lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
 263                let text = format!("def {}():\n", name);
 264                let filter_range = 4..4 + name.len();
 265                let display_range = 0..filter_range.end;
 266                (text, filter_range, display_range)
 267            }
 268            lsp::SymbolKind::CLASS => {
 269                let text = format!("class {}:", name);
 270                let filter_range = 6..6 + name.len();
 271                let display_range = 0..filter_range.end;
 272                (text, filter_range, display_range)
 273            }
 274            lsp::SymbolKind::CONSTANT => {
 275                let text = format!("{} = 0", name);
 276                let filter_range = 0..name.len();
 277                let display_range = 0..filter_range.end;
 278                (text, filter_range, display_range)
 279            }
 280            _ => return None,
 281        };
 282
 283        Some(language::CodeLabel {
 284            runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
 285            text: text[display_range].to_string(),
 286            filter_range,
 287        })
 288    }
 289
 290    async fn workspace_configuration(
 291        self: Arc<Self>,
 292        _: &dyn Fs,
 293        adapter: &Arc<dyn LspAdapterDelegate>,
 294        toolchains: Arc<dyn LanguageToolchainStore>,
 295        cx: &mut AsyncApp,
 296    ) -> Result<Value> {
 297        let toolchain = toolchains
 298            .active_toolchain(
 299                adapter.worktree_id(),
 300                Arc::from("".as_ref()),
 301                LanguageName::new("Python"),
 302                cx,
 303            )
 304            .await;
 305        cx.update(move |cx| {
 306            let mut user_settings =
 307                language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
 308                    .and_then(|s| s.settings.clone())
 309                    .unwrap_or_default();
 310
 311            // If python.pythonPath is not set in user config, do so using our toolchain picker.
 312            if let Some(toolchain) = toolchain {
 313                if user_settings.is_null() {
 314                    user_settings = Value::Object(serde_json::Map::default());
 315                }
 316                let object = user_settings.as_object_mut().unwrap();
 317                if let Some(python) = object
 318                    .entry("python")
 319                    .or_insert(Value::Object(serde_json::Map::default()))
 320                    .as_object_mut()
 321                {
 322                    python
 323                        .entry("pythonPath")
 324                        .or_insert(Value::String(toolchain.path.into()));
 325                }
 326            }
 327            user_settings
 328        })
 329    }
 330    fn manifest_name(&self) -> Option<ManifestName> {
 331        Some(SharedString::new_static("pyproject.toml").into())
 332    }
 333}
 334
 335async fn get_cached_server_binary(
 336    container_dir: PathBuf,
 337    node: &NodeRuntime,
 338) -> Option<LanguageServerBinary> {
 339    let server_path = container_dir.join(SERVER_PATH);
 340    if server_path.exists() {
 341        Some(LanguageServerBinary {
 342            path: node.binary_path().await.log_err()?,
 343            env: None,
 344            arguments: server_binary_arguments(&server_path),
 345        })
 346    } else {
 347        log::error!("missing executable in directory {:?}", server_path);
 348        None
 349    }
 350}
 351
 352pub(crate) struct PythonContextProvider;
 353
 354const PYTHON_TEST_TARGET_TASK_VARIABLE: VariableName =
 355    VariableName::Custom(Cow::Borrowed("PYTHON_TEST_TARGET"));
 356
 357const PYTHON_ACTIVE_TOOLCHAIN_PATH: VariableName =
 358    VariableName::Custom(Cow::Borrowed("PYTHON_ACTIVE_ZED_TOOLCHAIN"));
 359
 360const PYTHON_MODULE_NAME_TASK_VARIABLE: VariableName =
 361    VariableName::Custom(Cow::Borrowed("PYTHON_MODULE_NAME"));
 362
 363impl ContextProvider for PythonContextProvider {
 364    fn build_context(
 365        &self,
 366        variables: &task::TaskVariables,
 367        location: &project::Location,
 368        _: Option<HashMap<String, String>>,
 369        toolchains: Arc<dyn LanguageToolchainStore>,
 370        cx: &mut gpui::App,
 371    ) -> Task<Result<task::TaskVariables>> {
 372        let test_target = match selected_test_runner(location.buffer.read(cx).file(), cx) {
 373            TestRunner::UNITTEST => self.build_unittest_target(variables),
 374            TestRunner::PYTEST => self.build_pytest_target(variables),
 375        };
 376
 377        let module_target = self.build_module_target(variables);
 378        let worktree_id = location.buffer.read(cx).file().map(|f| f.worktree_id(cx));
 379
 380        cx.spawn(async move |cx| {
 381            let active_toolchain = if let Some(worktree_id) = worktree_id {
 382                toolchains
 383                    .active_toolchain(worktree_id, Arc::from("".as_ref()), "Python".into(), cx)
 384                    .await
 385                    .map_or_else(
 386                        || "python3".to_owned(),
 387                        |toolchain| format!("\"{}\"", toolchain.path),
 388                    )
 389            } else {
 390                String::from("python3")
 391            };
 392            let toolchain = (PYTHON_ACTIVE_TOOLCHAIN_PATH, active_toolchain);
 393
 394            Ok(task::TaskVariables::from_iter(
 395                test_target
 396                    .into_iter()
 397                    .chain(module_target.into_iter())
 398                    .chain([toolchain]),
 399            ))
 400        })
 401    }
 402
 403    fn associated_tasks(
 404        &self,
 405        file: Option<Arc<dyn language::File>>,
 406        cx: &App,
 407    ) -> Option<TaskTemplates> {
 408        let test_runner = selected_test_runner(file.as_ref(), cx);
 409
 410        let mut tasks = vec![
 411            // Execute a selection
 412            TaskTemplate {
 413                label: "execute selection".to_owned(),
 414                command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
 415                args: vec![
 416                    "-c".to_owned(),
 417                    VariableName::SelectedText.template_value_with_whitespace(),
 418                ],
 419                ..TaskTemplate::default()
 420            },
 421            // Execute an entire file
 422            TaskTemplate {
 423                label: format!("run '{}'", VariableName::File.template_value()),
 424                command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
 425                args: vec![VariableName::File.template_value_with_whitespace()],
 426                ..TaskTemplate::default()
 427            },
 428            // Execute a file as module
 429            TaskTemplate {
 430                label: format!("run module '{}'", VariableName::File.template_value()),
 431                command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
 432                args: vec![
 433                    "-m".to_owned(),
 434                    PYTHON_MODULE_NAME_TASK_VARIABLE.template_value(),
 435                ],
 436                tags: vec!["python-module-main-method".to_owned()],
 437                ..TaskTemplate::default()
 438            },
 439        ];
 440
 441        tasks.extend(match test_runner {
 442            TestRunner::UNITTEST => {
 443                [
 444                    // Run tests for an entire file
 445                    TaskTemplate {
 446                        label: format!("unittest '{}'", VariableName::File.template_value()),
 447                        command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
 448                        args: vec![
 449                            "-m".to_owned(),
 450                            "unittest".to_owned(),
 451                            VariableName::File.template_value_with_whitespace(),
 452                        ],
 453                        ..TaskTemplate::default()
 454                    },
 455                    // Run test(s) for a specific target within a file
 456                    TaskTemplate {
 457                        label: "unittest $ZED_CUSTOM_PYTHON_TEST_TARGET".to_owned(),
 458                        command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
 459                        args: vec![
 460                            "-m".to_owned(),
 461                            "unittest".to_owned(),
 462                            PYTHON_TEST_TARGET_TASK_VARIABLE.template_value_with_whitespace(),
 463                        ],
 464                        tags: vec![
 465                            "python-unittest-class".to_owned(),
 466                            "python-unittest-method".to_owned(),
 467                        ],
 468                        ..TaskTemplate::default()
 469                    },
 470                ]
 471            }
 472            TestRunner::PYTEST => {
 473                [
 474                    // Run tests for an entire file
 475                    TaskTemplate {
 476                        label: format!("pytest '{}'", VariableName::File.template_value()),
 477                        command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
 478                        args: vec![
 479                            "-m".to_owned(),
 480                            "pytest".to_owned(),
 481                            VariableName::File.template_value_with_whitespace(),
 482                        ],
 483                        ..TaskTemplate::default()
 484                    },
 485                    // Run test(s) for a specific target within a file
 486                    TaskTemplate {
 487                        label: "pytest $ZED_CUSTOM_PYTHON_TEST_TARGET".to_owned(),
 488                        command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
 489                        args: vec![
 490                            "-m".to_owned(),
 491                            "pytest".to_owned(),
 492                            PYTHON_TEST_TARGET_TASK_VARIABLE.template_value_with_whitespace(),
 493                        ],
 494                        tags: vec![
 495                            "python-pytest-class".to_owned(),
 496                            "python-pytest-method".to_owned(),
 497                        ],
 498                        ..TaskTemplate::default()
 499                    },
 500                ]
 501            }
 502        });
 503
 504        Some(TaskTemplates(tasks))
 505    }
 506
 507    fn debug_adapter(&self) -> Option<String> {
 508        Some("Debugpy".into())
 509    }
 510}
 511
 512fn selected_test_runner(location: Option<&Arc<dyn language::File>>, cx: &App) -> TestRunner {
 513    const TEST_RUNNER_VARIABLE: &str = "TEST_RUNNER";
 514    language_settings(Some(LanguageName::new("Python")), location, cx)
 515        .tasks
 516        .variables
 517        .get(TEST_RUNNER_VARIABLE)
 518        .and_then(|val| TestRunner::from_str(val).ok())
 519        .unwrap_or(TestRunner::PYTEST)
 520}
 521
 522impl PythonContextProvider {
 523    fn build_unittest_target(
 524        &self,
 525        variables: &task::TaskVariables,
 526    ) -> Option<(VariableName, String)> {
 527        let python_module_name =
 528            python_module_name_from_relative_path(variables.get(&VariableName::RelativeFile)?);
 529
 530        let unittest_class_name =
 531            variables.get(&VariableName::Custom(Cow::Borrowed("_unittest_class_name")));
 532
 533        let unittest_method_name = variables.get(&VariableName::Custom(Cow::Borrowed(
 534            "_unittest_method_name",
 535        )));
 536
 537        let unittest_target_str = match (unittest_class_name, unittest_method_name) {
 538            (Some(class_name), Some(method_name)) => {
 539                format!("{python_module_name}.{class_name}.{method_name}")
 540            }
 541            (Some(class_name), None) => format!("{python_module_name}.{class_name}"),
 542            (None, None) => python_module_name,
 543            // should never happen, a TestCase class is the unit of testing
 544            (None, Some(_)) => return None,
 545        };
 546
 547        Some((
 548            PYTHON_TEST_TARGET_TASK_VARIABLE.clone(),
 549            unittest_target_str,
 550        ))
 551    }
 552
 553    fn build_pytest_target(
 554        &self,
 555        variables: &task::TaskVariables,
 556    ) -> Option<(VariableName, String)> {
 557        let file_path = variables.get(&VariableName::RelativeFile)?;
 558
 559        let pytest_class_name =
 560            variables.get(&VariableName::Custom(Cow::Borrowed("_pytest_class_name")));
 561
 562        let pytest_method_name =
 563            variables.get(&VariableName::Custom(Cow::Borrowed("_pytest_method_name")));
 564
 565        let pytest_target_str = match (pytest_class_name, pytest_method_name) {
 566            (Some(class_name), Some(method_name)) => {
 567                format!("{file_path}::{class_name}::{method_name}")
 568            }
 569            (Some(class_name), None) => {
 570                format!("{file_path}::{class_name}")
 571            }
 572            (None, Some(method_name)) => {
 573                format!("{file_path}::{method_name}")
 574            }
 575            (None, None) => file_path.to_string(),
 576        };
 577
 578        Some((PYTHON_TEST_TARGET_TASK_VARIABLE.clone(), pytest_target_str))
 579    }
 580
 581    fn build_module_target(
 582        &self,
 583        variables: &task::TaskVariables,
 584    ) -> Result<(VariableName, String)> {
 585        let python_module_name = python_module_name_from_relative_path(
 586            variables.get(&VariableName::RelativeFile).unwrap_or(""),
 587        );
 588
 589        let module_target = (PYTHON_MODULE_NAME_TASK_VARIABLE.clone(), python_module_name);
 590
 591        Ok(module_target)
 592    }
 593}
 594
 595fn python_module_name_from_relative_path(relative_path: &str) -> String {
 596    let path_with_dots = relative_path.replace('/', ".");
 597    path_with_dots
 598        .strip_suffix(".py")
 599        .unwrap_or(&path_with_dots)
 600        .to_string()
 601}
 602
 603fn python_env_kind_display(k: &PythonEnvironmentKind) -> &'static str {
 604    match k {
 605        PythonEnvironmentKind::Conda => "Conda",
 606        PythonEnvironmentKind::Pixi => "pixi",
 607        PythonEnvironmentKind::Homebrew => "Homebrew",
 608        PythonEnvironmentKind::Pyenv => "global (Pyenv)",
 609        PythonEnvironmentKind::GlobalPaths => "global",
 610        PythonEnvironmentKind::PyenvVirtualEnv => "Pyenv",
 611        PythonEnvironmentKind::Pipenv => "Pipenv",
 612        PythonEnvironmentKind::Poetry => "Poetry",
 613        PythonEnvironmentKind::MacPythonOrg => "global (Python.org)",
 614        PythonEnvironmentKind::MacCommandLineTools => "global (Command Line Tools for Xcode)",
 615        PythonEnvironmentKind::LinuxGlobal => "global",
 616        PythonEnvironmentKind::MacXCode => "global (Xcode)",
 617        PythonEnvironmentKind::Venv => "venv",
 618        PythonEnvironmentKind::VirtualEnv => "virtualenv",
 619        PythonEnvironmentKind::VirtualEnvWrapper => "virtualenvwrapper",
 620        PythonEnvironmentKind::WindowsStore => "global (Windows Store)",
 621        PythonEnvironmentKind::WindowsRegistry => "global (Windows Registry)",
 622    }
 623}
 624
 625pub(crate) struct PythonToolchainProvider {
 626    term: SharedString,
 627}
 628
 629impl Default for PythonToolchainProvider {
 630    fn default() -> Self {
 631        Self {
 632            term: SharedString::new_static("Virtual Environment"),
 633        }
 634    }
 635}
 636
 637static ENV_PRIORITY_LIST: &'static [PythonEnvironmentKind] = &[
 638    // Prioritize non-Conda environments.
 639    PythonEnvironmentKind::Poetry,
 640    PythonEnvironmentKind::Pipenv,
 641    PythonEnvironmentKind::VirtualEnvWrapper,
 642    PythonEnvironmentKind::Venv,
 643    PythonEnvironmentKind::VirtualEnv,
 644    PythonEnvironmentKind::PyenvVirtualEnv,
 645    PythonEnvironmentKind::Pixi,
 646    PythonEnvironmentKind::Conda,
 647    PythonEnvironmentKind::Pyenv,
 648    PythonEnvironmentKind::GlobalPaths,
 649    PythonEnvironmentKind::Homebrew,
 650];
 651
 652fn env_priority(kind: Option<PythonEnvironmentKind>) -> usize {
 653    if let Some(kind) = kind {
 654        ENV_PRIORITY_LIST
 655            .iter()
 656            .position(|blessed_env| blessed_env == &kind)
 657            .unwrap_or(ENV_PRIORITY_LIST.len())
 658    } else {
 659        // Unknown toolchains are less useful than non-blessed ones.
 660        ENV_PRIORITY_LIST.len() + 1
 661    }
 662}
 663
 664/// Return the name of environment declared in <worktree-root/.venv.
 665///
 666/// https://virtualfish.readthedocs.io/en/latest/plugins.html#auto-activation-auto-activation
 667fn get_worktree_venv_declaration(worktree_root: &Path) -> Option<String> {
 668    fs::File::open(worktree_root.join(".venv"))
 669        .and_then(|file| {
 670            let mut venv_name = String::new();
 671            io::BufReader::new(file).read_line(&mut venv_name)?;
 672            Ok(venv_name.trim().to_string())
 673        })
 674        .ok()
 675}
 676
 677#[async_trait]
 678impl ToolchainLister for PythonToolchainProvider {
 679    async fn list(
 680        &self,
 681        worktree_root: PathBuf,
 682        project_env: Option<HashMap<String, String>>,
 683    ) -> ToolchainList {
 684        let env = project_env.unwrap_or_default();
 685        let environment = EnvironmentApi::from_env(&env);
 686        let locators = pet::locators::create_locators(
 687            Arc::new(pet_conda::Conda::from(&environment)),
 688            Arc::new(pet_poetry::Poetry::from(&environment)),
 689            &environment,
 690        );
 691        let mut config = Configuration::default();
 692        config.workspace_directories = Some(vec![worktree_root.clone()]);
 693        for locator in locators.iter() {
 694            locator.configure(&config);
 695        }
 696
 697        let reporter = pet_reporter::collect::create_reporter();
 698        pet::find::find_and_report_envs(&reporter, config, &locators, &environment, None);
 699
 700        let mut toolchains = reporter
 701            .environments
 702            .lock()
 703            .ok()
 704            .map_or(Vec::new(), |mut guard| std::mem::take(&mut guard));
 705
 706        let wr = worktree_root;
 707        let wr_venv = get_worktree_venv_declaration(&wr);
 708        // Sort detected environments by:
 709        //     environment name matching activation file (<workdir>/.venv)
 710        //     environment project dir matching worktree_root
 711        //     general env priority
 712        //     environment path matching the CONDA_PREFIX env var
 713        //     executable path
 714        toolchains.sort_by(|lhs, rhs| {
 715            // Compare venv names against worktree .venv file
 716            let venv_ordering =
 717                wr_venv
 718                    .as_ref()
 719                    .map_or(Ordering::Equal, |venv| match (&lhs.name, &rhs.name) {
 720                        (Some(l), Some(r)) => (r == venv).cmp(&(l == venv)),
 721                        (Some(l), None) if l == venv => Ordering::Less,
 722                        (None, Some(r)) if r == venv => Ordering::Greater,
 723                        _ => Ordering::Equal,
 724                    });
 725
 726            // Compare project paths against worktree root
 727            let proj_ordering = || match (&lhs.project, &rhs.project) {
 728                (Some(l), Some(r)) => (r == &wr).cmp(&(l == &wr)),
 729                (Some(l), None) if l == &wr => Ordering::Less,
 730                (None, Some(r)) if r == &wr => Ordering::Greater,
 731                _ => Ordering::Equal,
 732            };
 733
 734            // Compare environment priorities
 735            let priority_ordering = || env_priority(lhs.kind).cmp(&env_priority(rhs.kind));
 736
 737            // Compare conda prefixes
 738            let conda_ordering = || {
 739                if lhs.kind == Some(PythonEnvironmentKind::Conda) {
 740                    environment
 741                        .get_env_var("CONDA_PREFIX".to_string())
 742                        .map(|conda_prefix| {
 743                            let is_match = |exe: &Option<PathBuf>| {
 744                                exe.as_ref().map_or(false, |e| e.starts_with(&conda_prefix))
 745                            };
 746                            match (is_match(&lhs.executable), is_match(&rhs.executable)) {
 747                                (true, false) => Ordering::Less,
 748                                (false, true) => Ordering::Greater,
 749                                _ => Ordering::Equal,
 750                            }
 751                        })
 752                        .unwrap_or(Ordering::Equal)
 753                } else {
 754                    Ordering::Equal
 755                }
 756            };
 757
 758            // Compare Python executables
 759            let exe_ordering = || lhs.executable.cmp(&rhs.executable);
 760
 761            venv_ordering
 762                .then_with(proj_ordering)
 763                .then_with(priority_ordering)
 764                .then_with(conda_ordering)
 765                .then_with(exe_ordering)
 766        });
 767
 768        let mut toolchains: Vec<_> = toolchains
 769            .into_iter()
 770            .filter_map(|toolchain| {
 771                let mut name = String::from("Python");
 772                if let Some(ref version) = toolchain.version {
 773                    _ = write!(name, " {version}");
 774                }
 775
 776                let name_and_kind = match (&toolchain.name, &toolchain.kind) {
 777                    (Some(name), Some(kind)) => {
 778                        Some(format!("({name}; {})", python_env_kind_display(kind)))
 779                    }
 780                    (Some(name), None) => Some(format!("({name})")),
 781                    (None, Some(kind)) => Some(format!("({})", python_env_kind_display(kind))),
 782                    (None, None) => None,
 783                };
 784
 785                if let Some(nk) = name_and_kind {
 786                    _ = write!(name, " {nk}");
 787                }
 788
 789                Some(Toolchain {
 790                    name: name.into(),
 791                    path: toolchain.executable.as_ref()?.to_str()?.to_owned().into(),
 792                    language_name: LanguageName::new("Python"),
 793                    as_json: serde_json::to_value(toolchain).ok()?,
 794                })
 795            })
 796            .collect();
 797        toolchains.dedup();
 798        ToolchainList {
 799            toolchains,
 800            default: None,
 801            groups: Default::default(),
 802        }
 803    }
 804    fn term(&self) -> SharedString {
 805        self.term.clone()
 806    }
 807}
 808
 809pub struct EnvironmentApi<'a> {
 810    global_search_locations: Arc<Mutex<Vec<PathBuf>>>,
 811    project_env: &'a HashMap<String, String>,
 812    pet_env: pet_core::os_environment::EnvironmentApi,
 813}
 814
 815impl<'a> EnvironmentApi<'a> {
 816    pub fn from_env(project_env: &'a HashMap<String, String>) -> Self {
 817        let paths = project_env
 818            .get("PATH")
 819            .map(|p| std::env::split_paths(p).collect())
 820            .unwrap_or_default();
 821
 822        EnvironmentApi {
 823            global_search_locations: Arc::new(Mutex::new(paths)),
 824            project_env,
 825            pet_env: pet_core::os_environment::EnvironmentApi::new(),
 826        }
 827    }
 828
 829    fn user_home(&self) -> Option<PathBuf> {
 830        self.project_env
 831            .get("HOME")
 832            .or_else(|| self.project_env.get("USERPROFILE"))
 833            .map(|home| pet_fs::path::norm_case(PathBuf::from(home)))
 834            .or_else(|| self.pet_env.get_user_home())
 835    }
 836}
 837
 838impl pet_core::os_environment::Environment for EnvironmentApi<'_> {
 839    fn get_user_home(&self) -> Option<PathBuf> {
 840        self.user_home()
 841    }
 842
 843    fn get_root(&self) -> Option<PathBuf> {
 844        None
 845    }
 846
 847    fn get_env_var(&self, key: String) -> Option<String> {
 848        self.project_env
 849            .get(&key)
 850            .cloned()
 851            .or_else(|| self.pet_env.get_env_var(key))
 852    }
 853
 854    fn get_know_global_search_locations(&self) -> Vec<PathBuf> {
 855        if self.global_search_locations.lock().unwrap().is_empty() {
 856            let mut paths =
 857                std::env::split_paths(&self.get_env_var("PATH".to_string()).unwrap_or_default())
 858                    .collect::<Vec<PathBuf>>();
 859
 860            log::trace!("Env PATH: {:?}", paths);
 861            for p in self.pet_env.get_know_global_search_locations() {
 862                if !paths.contains(&p) {
 863                    paths.push(p);
 864                }
 865            }
 866
 867            let mut paths = paths
 868                .into_iter()
 869                .filter(|p| p.exists())
 870                .collect::<Vec<PathBuf>>();
 871
 872            self.global_search_locations
 873                .lock()
 874                .unwrap()
 875                .append(&mut paths);
 876        }
 877        self.global_search_locations.lock().unwrap().clone()
 878    }
 879}
 880
 881pub(crate) struct PyLspAdapter {
 882    python_venv_base: OnceCell<Result<Arc<Path>, String>>,
 883}
 884impl PyLspAdapter {
 885    const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("pylsp");
 886    pub(crate) fn new() -> Self {
 887        Self {
 888            python_venv_base: OnceCell::new(),
 889        }
 890    }
 891    async fn ensure_venv(delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>> {
 892        let python_path = Self::find_base_python(delegate)
 893            .await
 894            .ok_or_else(|| anyhow!("Could not find Python installation for PyLSP"))?;
 895        let work_dir = delegate
 896            .language_server_download_dir(&Self::SERVER_NAME)
 897            .await
 898            .ok_or_else(|| anyhow!("Could not get working directory for PyLSP"))?;
 899        let mut path = PathBuf::from(work_dir.as_ref());
 900        path.push("pylsp-venv");
 901        if !path.exists() {
 902            util::command::new_smol_command(python_path)
 903                .arg("-m")
 904                .arg("venv")
 905                .arg("pylsp-venv")
 906                .current_dir(work_dir)
 907                .spawn()?
 908                .output()
 909                .await?;
 910        }
 911
 912        Ok(path.into())
 913    }
 914    // Find "baseline", user python version from which we'll create our own venv.
 915    async fn find_base_python(delegate: &dyn LspAdapterDelegate) -> Option<PathBuf> {
 916        for path in ["python3", "python"] {
 917            if let Some(path) = delegate.which(path.as_ref()).await {
 918                return Some(path);
 919            }
 920        }
 921        None
 922    }
 923
 924    async fn base_venv(&self, delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>, String> {
 925        self.python_venv_base
 926            .get_or_init(move || async move {
 927                Self::ensure_venv(delegate)
 928                    .await
 929                    .map_err(|e| format!("{e}"))
 930            })
 931            .await
 932            .clone()
 933    }
 934}
 935
 936const BINARY_DIR: &str = if cfg!(target_os = "windows") {
 937    "Scripts"
 938} else {
 939    "bin"
 940};
 941
 942#[async_trait(?Send)]
 943impl LspAdapter for PyLspAdapter {
 944    fn name(&self) -> LanguageServerName {
 945        Self::SERVER_NAME.clone()
 946    }
 947
 948    async fn check_if_user_installed(
 949        &self,
 950        delegate: &dyn LspAdapterDelegate,
 951        toolchains: Arc<dyn LanguageToolchainStore>,
 952        cx: &AsyncApp,
 953    ) -> Option<LanguageServerBinary> {
 954        if let Some(pylsp_bin) = delegate.which(Self::SERVER_NAME.as_ref()).await {
 955            let env = delegate.shell_env().await;
 956            Some(LanguageServerBinary {
 957                path: pylsp_bin,
 958                env: Some(env),
 959                arguments: vec![],
 960            })
 961        } else {
 962            let venv = toolchains
 963                .active_toolchain(
 964                    delegate.worktree_id(),
 965                    Arc::from("".as_ref()),
 966                    LanguageName::new("Python"),
 967                    &mut cx.clone(),
 968                )
 969                .await?;
 970            let pylsp_path = Path::new(venv.path.as_ref()).parent()?.join("pylsp");
 971            pylsp_path.exists().then(|| LanguageServerBinary {
 972                path: venv.path.to_string().into(),
 973                arguments: vec![pylsp_path.into()],
 974                env: None,
 975            })
 976        }
 977    }
 978
 979    async fn fetch_latest_server_version(
 980        &self,
 981        _: &dyn LspAdapterDelegate,
 982    ) -> Result<Box<dyn 'static + Any + Send>> {
 983        Ok(Box::new(()) as Box<_>)
 984    }
 985
 986    async fn fetch_server_binary(
 987        &self,
 988        _: Box<dyn 'static + Send + Any>,
 989        _: PathBuf,
 990        delegate: &dyn LspAdapterDelegate,
 991    ) -> Result<LanguageServerBinary> {
 992        let venv = self.base_venv(delegate).await.map_err(|e| anyhow!(e))?;
 993        let pip_path = venv.join(BINARY_DIR).join("pip3");
 994        ensure!(
 995            util::command::new_smol_command(pip_path.as_path())
 996                .arg("install")
 997                .arg("python-lsp-server")
 998                .arg("-U")
 999                .output()
1000                .await?
1001                .status
1002                .success(),
1003            "python-lsp-server installation failed"
1004        );
1005        ensure!(
1006            util::command::new_smol_command(pip_path.as_path())
1007                .arg("install")
1008                .arg("python-lsp-server[all]")
1009                .arg("-U")
1010                .output()
1011                .await?
1012                .status
1013                .success(),
1014            "python-lsp-server[all] installation failed"
1015        );
1016        ensure!(
1017            util::command::new_smol_command(pip_path)
1018                .arg("install")
1019                .arg("pylsp-mypy")
1020                .arg("-U")
1021                .output()
1022                .await?
1023                .status
1024                .success(),
1025            "pylsp-mypy installation failed"
1026        );
1027        let pylsp = venv.join(BINARY_DIR).join("pylsp");
1028        Ok(LanguageServerBinary {
1029            path: pylsp,
1030            env: None,
1031            arguments: vec![],
1032        })
1033    }
1034
1035    async fn cached_server_binary(
1036        &self,
1037        _: PathBuf,
1038        delegate: &dyn LspAdapterDelegate,
1039    ) -> Option<LanguageServerBinary> {
1040        let venv = self.base_venv(delegate).await.ok()?;
1041        let pylsp = venv.join(BINARY_DIR).join("pylsp");
1042        Some(LanguageServerBinary {
1043            path: pylsp,
1044            env: None,
1045            arguments: vec![],
1046        })
1047    }
1048
1049    async fn process_completions(&self, _items: &mut [lsp::CompletionItem]) {}
1050
1051    async fn label_for_completion(
1052        &self,
1053        item: &lsp::CompletionItem,
1054        language: &Arc<language::Language>,
1055    ) -> Option<language::CodeLabel> {
1056        let label = &item.label;
1057        let grammar = language.grammar()?;
1058        let highlight_id = match item.kind? {
1059            lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method")?,
1060            lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function")?,
1061            lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type")?,
1062            lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant")?,
1063            _ => return None,
1064        };
1065        Some(language::CodeLabel {
1066            text: label.clone(),
1067            runs: vec![(0..label.len(), highlight_id)],
1068            filter_range: 0..label.len(),
1069        })
1070    }
1071
1072    async fn label_for_symbol(
1073        &self,
1074        name: &str,
1075        kind: lsp::SymbolKind,
1076        language: &Arc<language::Language>,
1077    ) -> Option<language::CodeLabel> {
1078        let (text, filter_range, display_range) = match kind {
1079            lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
1080                let text = format!("def {}():\n", name);
1081                let filter_range = 4..4 + name.len();
1082                let display_range = 0..filter_range.end;
1083                (text, filter_range, display_range)
1084            }
1085            lsp::SymbolKind::CLASS => {
1086                let text = format!("class {}:", name);
1087                let filter_range = 6..6 + name.len();
1088                let display_range = 0..filter_range.end;
1089                (text, filter_range, display_range)
1090            }
1091            lsp::SymbolKind::CONSTANT => {
1092                let text = format!("{} = 0", name);
1093                let filter_range = 0..name.len();
1094                let display_range = 0..filter_range.end;
1095                (text, filter_range, display_range)
1096            }
1097            _ => return None,
1098        };
1099
1100        Some(language::CodeLabel {
1101            runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
1102            text: text[display_range].to_string(),
1103            filter_range,
1104        })
1105    }
1106
1107    async fn workspace_configuration(
1108        self: Arc<Self>,
1109        _: &dyn Fs,
1110        adapter: &Arc<dyn LspAdapterDelegate>,
1111        toolchains: Arc<dyn LanguageToolchainStore>,
1112        cx: &mut AsyncApp,
1113    ) -> Result<Value> {
1114        let toolchain = toolchains
1115            .active_toolchain(
1116                adapter.worktree_id(),
1117                Arc::from("".as_ref()),
1118                LanguageName::new("Python"),
1119                cx,
1120            )
1121            .await;
1122        cx.update(move |cx| {
1123            let mut user_settings =
1124                language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
1125                    .and_then(|s| s.settings.clone())
1126                    .unwrap_or_else(|| {
1127                        json!({
1128                            "plugins": {
1129                                "pycodestyle": {"enabled": false},
1130                                "rope_autoimport": {"enabled": true, "memory": true},
1131                                "pylsp_mypy": {"enabled": false}
1132                            },
1133                            "rope": {
1134                                "ropeFolder": null
1135                            },
1136                        })
1137                    });
1138
1139            // If user did not explicitly modify their python venv, use one from picker.
1140            if let Some(toolchain) = toolchain {
1141                if user_settings.is_null() {
1142                    user_settings = Value::Object(serde_json::Map::default());
1143                }
1144                let object = user_settings.as_object_mut().unwrap();
1145                if let Some(python) = object
1146                    .entry("plugins")
1147                    .or_insert(Value::Object(serde_json::Map::default()))
1148                    .as_object_mut()
1149                {
1150                    if let Some(jedi) = python
1151                        .entry("jedi")
1152                        .or_insert(Value::Object(serde_json::Map::default()))
1153                        .as_object_mut()
1154                    {
1155                        jedi.entry("environment".to_string())
1156                            .or_insert_with(|| Value::String(toolchain.path.clone().into()));
1157                    }
1158                    if let Some(pylint) = python
1159                        .entry("pylsp_mypy")
1160                        .or_insert(Value::Object(serde_json::Map::default()))
1161                        .as_object_mut()
1162                    {
1163                        pylint.entry("overrides".to_string()).or_insert_with(|| {
1164                            Value::Array(vec![
1165                                Value::String("--python-executable".into()),
1166                                Value::String(toolchain.path.into()),
1167                                Value::String("--cache-dir=/dev/null".into()),
1168                                Value::Bool(true),
1169                            ])
1170                        });
1171                    }
1172                }
1173            }
1174            user_settings = Value::Object(serde_json::Map::from_iter([(
1175                "pylsp".to_string(),
1176                user_settings,
1177            )]));
1178
1179            user_settings
1180        })
1181    }
1182    fn manifest_name(&self) -> Option<ManifestName> {
1183        Some(SharedString::new_static("pyproject.toml").into())
1184    }
1185}
1186
1187#[cfg(test)]
1188mod tests {
1189    use gpui::{AppContext as _, BorrowAppContext, Context, TestAppContext};
1190    use language::{AutoindentMode, Buffer, language_settings::AllLanguageSettings};
1191    use settings::SettingsStore;
1192    use std::num::NonZeroU32;
1193
1194    #[gpui::test]
1195    async fn test_python_autoindent(cx: &mut TestAppContext) {
1196        cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
1197        let language = crate::language("python", tree_sitter_python::LANGUAGE.into());
1198        cx.update(|cx| {
1199            let test_settings = SettingsStore::test(cx);
1200            cx.set_global(test_settings);
1201            language::init(cx);
1202            cx.update_global::<SettingsStore, _>(|store, cx| {
1203                store.update_user_settings::<AllLanguageSettings>(cx, |s| {
1204                    s.defaults.tab_size = NonZeroU32::new(2);
1205                });
1206            });
1207        });
1208
1209        cx.new(|cx| {
1210            let mut buffer = Buffer::local("", cx).with_language(language, cx);
1211            let append = |buffer: &mut Buffer, text: &str, cx: &mut Context<Buffer>| {
1212                let ix = buffer.len();
1213                buffer.edit([(ix..ix, text)], Some(AutoindentMode::EachLine), cx);
1214            };
1215
1216            // indent after "def():"
1217            append(&mut buffer, "def a():\n", cx);
1218            assert_eq!(buffer.text(), "def a():\n  ");
1219
1220            // preserve indent after blank line
1221            append(&mut buffer, "\n  ", cx);
1222            assert_eq!(buffer.text(), "def a():\n  \n  ");
1223
1224            // indent after "if"
1225            append(&mut buffer, "if a:\n  ", cx);
1226            assert_eq!(buffer.text(), "def a():\n  \n  if a:\n    ");
1227
1228            // preserve indent after statement
1229            append(&mut buffer, "b()\n", cx);
1230            assert_eq!(buffer.text(), "def a():\n  \n  if a:\n    b()\n    ");
1231
1232            // preserve indent after statement
1233            append(&mut buffer, "else", cx);
1234            assert_eq!(buffer.text(), "def a():\n  \n  if a:\n    b()\n    else");
1235
1236            // dedent "else""
1237            append(&mut buffer, ":", cx);
1238            assert_eq!(buffer.text(), "def a():\n  \n  if a:\n    b()\n  else:");
1239
1240            // indent lines after else
1241            append(&mut buffer, "\n", cx);
1242            assert_eq!(
1243                buffer.text(),
1244                "def a():\n  \n  if a:\n    b()\n  else:\n    "
1245            );
1246
1247            // indent after an open paren. the closing  paren is not indented
1248            // because there is another token before it on the same line.
1249            append(&mut buffer, "foo(\n1)", cx);
1250            assert_eq!(
1251                buffer.text(),
1252                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n      1)"
1253            );
1254
1255            // dedent the closing paren if it is shifted to the beginning of the line
1256            let argument_ix = buffer.text().find('1').unwrap();
1257            buffer.edit(
1258                [(argument_ix..argument_ix + 1, "")],
1259                Some(AutoindentMode::EachLine),
1260                cx,
1261            );
1262            assert_eq!(
1263                buffer.text(),
1264                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n    )"
1265            );
1266
1267            // preserve indent after the close paren
1268            append(&mut buffer, "\n", cx);
1269            assert_eq!(
1270                buffer.text(),
1271                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n    )\n    "
1272            );
1273
1274            // manually outdent the last line
1275            let end_whitespace_ix = buffer.len() - 4;
1276            buffer.edit(
1277                [(end_whitespace_ix..buffer.len(), "")],
1278                Some(AutoindentMode::EachLine),
1279                cx,
1280            );
1281            assert_eq!(
1282                buffer.text(),
1283                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n    )\n"
1284            );
1285
1286            // preserve the newly reduced indentation on the next newline
1287            append(&mut buffer, "\n", cx);
1288            assert_eq!(
1289                buffer.text(),
1290                "def a():\n  \n  if a:\n    b()\n  else:\n    foo(\n    )\n\n"
1291            );
1292
1293            // reset to a simple if statement
1294            buffer.edit([(0..buffer.len(), "if a:\n  b(\n  )")], None, cx);
1295
1296            // dedent "else" on the line after a closing paren
1297            append(&mut buffer, "\n  else:\n", cx);
1298            assert_eq!(buffer.text(), "if a:\n  b(\n  )\nelse:\n  ");
1299
1300            buffer
1301        });
1302    }
1303}