1use anyhow::{Context as _, ensure};
2use anyhow::{Result, anyhow};
3use async_trait::async_trait;
4use collections::HashMap;
5use futures::{AsyncBufReadExt, StreamExt as _};
6use gpui::{App, AsyncApp, SharedString, Task};
7use http_client::github::{AssetKind, GitHubLspBinaryVersion, latest_github_release};
8use language::language_settings::language_settings;
9use language::{ContextLocation, LanguageToolchainStore, LspInstaller};
10use language::{ContextProvider, LspAdapter, LspAdapterDelegate};
11use language::{LanguageName, ManifestName, ManifestProvider, ManifestQuery};
12use language::{Toolchain, ToolchainList, ToolchainLister, ToolchainMetadata};
13use lsp::LanguageServerBinary;
14use lsp::LanguageServerName;
15use node_runtime::{NodeRuntime, VersionStrategy};
16use pet_core::Configuration;
17use pet_core::os_environment::Environment;
18use pet_core::python_environment::{PythonEnvironment, PythonEnvironmentKind};
19use pet_virtualenv::is_virtualenv_dir;
20use project::Fs;
21use project::lsp_store::language_server_settings;
22use serde_json::{Value, json};
23use smol::lock::OnceCell;
24use std::cmp::Ordering;
25use std::env::consts;
26use util::fs::{make_file_executable, remove_matching};
27
28use parking_lot::Mutex;
29use std::str::FromStr;
30use std::{
31 borrow::Cow,
32 fmt::Write,
33 path::{Path, PathBuf},
34 sync::Arc,
35};
36use task::{ShellKind, TaskTemplate, TaskTemplates, VariableName};
37use util::{ResultExt, maybe};
38
39use crate::github_download::{GithubBinaryMetadata, download_server_binary};
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
67enum TestRunner {
68 UNITTEST,
69 PYTEST,
70}
71
72impl FromStr for TestRunner {
73 type Err = ();
74
75 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
76 match s {
77 "unittest" => Ok(Self::UNITTEST),
78 "pytest" => Ok(Self::PYTEST),
79 _ => Err(()),
80 }
81 }
82}
83
84/// Pyright assigns each completion item a `sortText` of the form `XX.YYYY.name`.
85/// Where `XX` is the sorting category, `YYYY` is based on most recent usage,
86/// and `name` is the symbol name itself.
87///
88/// The problem with it is that Pyright adjusts the sort text based on previous resolutions (items for which we've issued `completion/resolve` call have their sortText adjusted),
89/// which - long story short - makes completion items list non-stable. Pyright probably relies on VSCode's implementation detail.
90/// see https://github.com/microsoft/pyright/blob/95ef4e103b9b2f129c9320427e51b73ea7cf78bd/packages/pyright-internal/src/languageService/completionProvider.ts#LL2873
91fn process_pyright_completions(items: &mut [lsp::CompletionItem]) {
92 for item in items {
93 item.sort_text.take();
94 }
95}
96
97pub struct TyLspAdapter {
98 fs: Arc<dyn Fs>,
99}
100
101#[cfg(target_os = "macos")]
102impl TyLspAdapter {
103 const GITHUB_ASSET_KIND: AssetKind = AssetKind::Gz;
104 const ARCH_SERVER_NAME: &str = "apple-darwin";
105}
106
107#[cfg(target_os = "linux")]
108impl TyLspAdapter {
109 const GITHUB_ASSET_KIND: AssetKind = AssetKind::Gz;
110 const ARCH_SERVER_NAME: &str = "unknown-linux-gnu";
111}
112
113#[cfg(target_os = "freebsd")]
114impl TyLspAdapter {
115 const GITHUB_ASSET_KIND: AssetKind = AssetKind::Gz;
116 const ARCH_SERVER_NAME: &str = "unknown-freebsd";
117}
118
119#[cfg(target_os = "windows")]
120impl TyLspAdapter {
121 const GITHUB_ASSET_KIND: AssetKind = AssetKind::Zip;
122 const ARCH_SERVER_NAME: &str = "pc-windows-msvc";
123}
124
125impl TyLspAdapter {
126 const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("ty");
127
128 pub fn new(fs: Arc<dyn Fs>) -> TyLspAdapter {
129 TyLspAdapter { fs }
130 }
131
132 fn build_asset_name() -> Result<(String, String)> {
133 let arch = match consts::ARCH {
134 "x86" => "i686",
135 _ => consts::ARCH,
136 };
137 let os = Self::ARCH_SERVER_NAME;
138 let suffix = match consts::OS {
139 "windows" => "zip",
140 _ => "tar.gz",
141 };
142 let asset_name = format!("ty-{arch}-{os}.{suffix}");
143 let asset_stem = format!("ty-{arch}-{os}");
144 Ok((asset_stem, asset_name))
145 }
146}
147
148#[async_trait(?Send)]
149impl LspAdapter for TyLspAdapter {
150 fn name(&self) -> LanguageServerName {
151 Self::SERVER_NAME
152 }
153
154 async fn workspace_configuration(
155 self: Arc<Self>,
156 _: &Arc<dyn LspAdapterDelegate>,
157 toolchain: Option<Toolchain>,
158 _cx: &mut AsyncApp,
159 ) -> Result<Value> {
160 let mut ret = json!({});
161 if let Some(toolchain) = toolchain.and_then(|toolchain| {
162 serde_json::from_value::<PythonEnvironment>(toolchain.as_json).ok()
163 }) {
164 _ = maybe!({
165 let uri = url::Url::from_file_path(toolchain.executable?).ok()?;
166 let sys_prefix = toolchain.prefix.clone()?;
167 let environment = json!({
168 "executable": {
169 "uri": uri,
170 "sysPrefix": sys_prefix
171 }
172 });
173 ret.as_object_mut()?.insert(
174 "pythonExtension".into(),
175 json!({ "activeEnvironment": environment }),
176 );
177 Some(())
178 });
179 }
180 Ok(json!({"ty": ret}))
181 }
182}
183
184impl LspInstaller for TyLspAdapter {
185 type BinaryVersion = GitHubLspBinaryVersion;
186 async fn fetch_latest_server_version(
187 &self,
188 delegate: &dyn LspAdapterDelegate,
189 _: bool,
190 _: &mut AsyncApp,
191 ) -> Result<Self::BinaryVersion> {
192 let release =
193 latest_github_release("astral-sh/ty", true, true, delegate.http_client()).await?;
194 let (_, asset_name) = Self::build_asset_name()?;
195 let asset = release
196 .assets
197 .into_iter()
198 .find(|asset| asset.name == asset_name)
199 .with_context(|| format!("no asset found matching `{asset_name:?}`"))?;
200 Ok(GitHubLspBinaryVersion {
201 name: release.tag_name,
202 url: asset.browser_download_url,
203 digest: asset.digest,
204 })
205 }
206
207 async fn fetch_server_binary(
208 &self,
209 latest_version: Self::BinaryVersion,
210 container_dir: PathBuf,
211 delegate: &dyn LspAdapterDelegate,
212 ) -> Result<LanguageServerBinary> {
213 let GitHubLspBinaryVersion {
214 name,
215 url,
216 digest: expected_digest,
217 } = latest_version;
218 let destination_path = container_dir.join(format!("ty-{name}"));
219 let server_path = match Self::GITHUB_ASSET_KIND {
220 AssetKind::TarGz | AssetKind::Gz => destination_path.clone(), // Tar and gzip extract in place.
221 AssetKind::Zip => destination_path.clone().join("ty.exe"), // zip contains a .exe
222 };
223
224 let binary = LanguageServerBinary {
225 path: server_path.clone(),
226 env: None,
227 arguments: Default::default(),
228 };
229
230 let metadata_path = destination_path.with_extension("metadata");
231 let metadata = GithubBinaryMetadata::read_from_file(&metadata_path)
232 .await
233 .ok();
234 if let Some(metadata) = metadata {
235 let validity_check = async || {
236 delegate
237 .try_exec(LanguageServerBinary {
238 path: server_path.clone(),
239 arguments: vec!["--version".into()],
240 env: None,
241 })
242 .await
243 .inspect_err(|err| {
244 log::warn!("Unable to run {server_path:?} asset, redownloading: {err}",)
245 })
246 };
247 if let (Some(actual_digest), Some(expected_digest)) =
248 (&metadata.digest, &expected_digest)
249 {
250 if actual_digest == expected_digest {
251 if validity_check().await.is_ok() {
252 return Ok(binary);
253 }
254 } else {
255 log::info!(
256 "SHA-256 mismatch for {destination_path:?} asset, downloading new asset. Expected: {expected_digest}, Got: {actual_digest}"
257 );
258 }
259 } else if validity_check().await.is_ok() {
260 return Ok(binary);
261 }
262 }
263
264 download_server_binary(
265 delegate,
266 &url,
267 expected_digest.as_deref(),
268 &destination_path,
269 Self::GITHUB_ASSET_KIND,
270 )
271 .await?;
272 make_file_executable(&server_path).await?;
273 remove_matching(&container_dir, |path| path != destination_path).await;
274 GithubBinaryMetadata::write_to_file(
275 &GithubBinaryMetadata {
276 metadata_version: 1,
277 digest: expected_digest,
278 },
279 &metadata_path,
280 )
281 .await?;
282
283 Ok(LanguageServerBinary {
284 path: server_path,
285 env: None,
286 arguments: Default::default(),
287 })
288 }
289
290 async fn cached_server_binary(
291 &self,
292 container_dir: PathBuf,
293 _: &dyn LspAdapterDelegate,
294 ) -> Option<LanguageServerBinary> {
295 maybe!(async {
296 let mut last = None;
297 let mut entries = self.fs.read_dir(&container_dir).await?;
298 while let Some(entry) = entries.next().await {
299 let path = entry?;
300 if path.extension().is_some_and(|ext| ext == "metadata") {
301 continue;
302 }
303 last = Some(path);
304 }
305
306 let path = last.context("no cached binary")?;
307 let path = match TyLspAdapter::GITHUB_ASSET_KIND {
308 AssetKind::TarGz | AssetKind::Gz => path, // Tar and gzip extract in place.
309 AssetKind::Zip => path.join("ty.exe"), // zip contains a .exe
310 };
311
312 anyhow::Ok(LanguageServerBinary {
313 path,
314 env: None,
315 arguments: Default::default(),
316 })
317 })
318 .await
319 .log_err()
320 }
321}
322
323pub struct PyrightLspAdapter {
324 node: NodeRuntime,
325}
326
327impl PyrightLspAdapter {
328 const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("pyright");
329 const SERVER_PATH: &str = "node_modules/pyright/langserver.index.js";
330 const NODE_MODULE_RELATIVE_SERVER_PATH: &str = "pyright/langserver.index.js";
331
332 pub fn new(node: NodeRuntime) -> Self {
333 PyrightLspAdapter { node }
334 }
335
336 async fn get_cached_server_binary(
337 container_dir: PathBuf,
338 node: &NodeRuntime,
339 ) -> Option<LanguageServerBinary> {
340 let server_path = container_dir.join(Self::SERVER_PATH);
341 if server_path.exists() {
342 Some(LanguageServerBinary {
343 path: node.binary_path().await.log_err()?,
344 env: None,
345 arguments: vec![server_path.into(), "--stdio".into()],
346 })
347 } else {
348 log::error!("missing executable in directory {:?}", server_path);
349 None
350 }
351 }
352}
353
354#[async_trait(?Send)]
355impl LspAdapter for PyrightLspAdapter {
356 fn name(&self) -> LanguageServerName {
357 Self::SERVER_NAME
358 }
359
360 async fn initialization_options(
361 self: Arc<Self>,
362 _: &Arc<dyn LspAdapterDelegate>,
363 ) -> Result<Option<Value>> {
364 // Provide minimal initialization options
365 // Virtual environment configuration will be handled through workspace configuration
366 Ok(Some(json!({
367 "python": {
368 "analysis": {
369 "autoSearchPaths": true,
370 "useLibraryCodeForTypes": true,
371 "autoImportCompletions": true
372 }
373 }
374 })))
375 }
376
377 async fn process_completions(&self, items: &mut [lsp::CompletionItem]) {
378 process_pyright_completions(items);
379 }
380
381 async fn label_for_completion(
382 &self,
383 item: &lsp::CompletionItem,
384 language: &Arc<language::Language>,
385 ) -> Option<language::CodeLabel> {
386 let label = &item.label;
387 let grammar = language.grammar()?;
388 let highlight_id = match item.kind? {
389 lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method"),
390 lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function"),
391 lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type"),
392 lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant"),
393 lsp::CompletionItemKind::VARIABLE => grammar.highlight_id_for_name("variable"),
394 _ => {
395 return None;
396 }
397 };
398 let filter_range = item
399 .filter_text
400 .as_deref()
401 .and_then(|filter| label.find(filter).map(|ix| ix..ix + filter.len()))
402 .unwrap_or(0..label.len());
403 let mut text = label.clone();
404 if let Some(completion_details) = item
405 .label_details
406 .as_ref()
407 .and_then(|details| details.description.as_ref())
408 {
409 write!(&mut text, " {}", completion_details).ok();
410 }
411 Some(language::CodeLabel {
412 runs: highlight_id
413 .map(|id| (0..label.len(), id))
414 .into_iter()
415 .collect(),
416 text,
417 filter_range,
418 })
419 }
420
421 async fn label_for_symbol(
422 &self,
423 name: &str,
424 kind: lsp::SymbolKind,
425 language: &Arc<language::Language>,
426 ) -> Option<language::CodeLabel> {
427 let (text, filter_range, display_range) = match kind {
428 lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
429 let text = format!("def {}():\n", name);
430 let filter_range = 4..4 + name.len();
431 let display_range = 0..filter_range.end;
432 (text, filter_range, display_range)
433 }
434 lsp::SymbolKind::CLASS => {
435 let text = format!("class {}:", name);
436 let filter_range = 6..6 + name.len();
437 let display_range = 0..filter_range.end;
438 (text, filter_range, display_range)
439 }
440 lsp::SymbolKind::CONSTANT => {
441 let text = format!("{} = 0", name);
442 let filter_range = 0..name.len();
443 let display_range = 0..filter_range.end;
444 (text, filter_range, display_range)
445 }
446 _ => return None,
447 };
448
449 Some(language::CodeLabel {
450 runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
451 text: text[display_range].to_string(),
452 filter_range,
453 })
454 }
455
456 async fn workspace_configuration(
457 self: Arc<Self>,
458
459 adapter: &Arc<dyn LspAdapterDelegate>,
460 toolchain: Option<Toolchain>,
461 cx: &mut AsyncApp,
462 ) -> Result<Value> {
463 cx.update(move |cx| {
464 let mut user_settings =
465 language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
466 .and_then(|s| s.settings.clone())
467 .unwrap_or_default();
468
469 // If we have a detected toolchain, configure Pyright to use it
470 if let Some(toolchain) = toolchain
471 && let Ok(env) = serde_json::from_value::<
472 pet_core::python_environment::PythonEnvironment,
473 >(toolchain.as_json.clone())
474 {
475 if !user_settings.is_object() {
476 user_settings = Value::Object(serde_json::Map::default());
477 }
478 let object = user_settings.as_object_mut().unwrap();
479
480 let interpreter_path = toolchain.path.to_string();
481 if let Some(venv_dir) = env.prefix {
482 // Set venvPath and venv at the root level
483 // This matches the format of a pyrightconfig.json file
484 if let Some(parent) = venv_dir.parent() {
485 // Use relative path if the venv is inside the workspace
486 let venv_path = if parent == adapter.worktree_root_path() {
487 ".".to_string()
488 } else {
489 parent.to_string_lossy().into_owned()
490 };
491 object.insert("venvPath".to_string(), Value::String(venv_path));
492 }
493
494 if let Some(venv_name) = venv_dir.file_name() {
495 object.insert(
496 "venv".to_owned(),
497 Value::String(venv_name.to_string_lossy().into_owned()),
498 );
499 }
500 }
501
502 // Always set the python interpreter path
503 // Get or create the python section
504 let python = object
505 .entry("python")
506 .and_modify(|v| {
507 if !v.is_object() {
508 *v = Value::Object(serde_json::Map::default());
509 }
510 })
511 .or_insert(Value::Object(serde_json::Map::default()));
512 let python = python.as_object_mut().unwrap();
513
514 // Set both pythonPath and defaultInterpreterPath for compatibility
515 python.insert(
516 "pythonPath".to_owned(),
517 Value::String(interpreter_path.clone()),
518 );
519 python.insert(
520 "defaultInterpreterPath".to_owned(),
521 Value::String(interpreter_path),
522 );
523 }
524
525 user_settings
526 })
527 }
528}
529
530impl LspInstaller for PyrightLspAdapter {
531 type BinaryVersion = String;
532
533 async fn fetch_latest_server_version(
534 &self,
535 _: &dyn LspAdapterDelegate,
536 _: bool,
537 _: &mut AsyncApp,
538 ) -> Result<String> {
539 self.node
540 .npm_package_latest_version(Self::SERVER_NAME.as_ref())
541 .await
542 }
543
544 async fn check_if_user_installed(
545 &self,
546 delegate: &dyn LspAdapterDelegate,
547 _: Option<Toolchain>,
548 _: &AsyncApp,
549 ) -> Option<LanguageServerBinary> {
550 if let Some(pyright_bin) = delegate.which("pyright-langserver".as_ref()).await {
551 let env = delegate.shell_env().await;
552 Some(LanguageServerBinary {
553 path: pyright_bin,
554 env: Some(env),
555 arguments: vec!["--stdio".into()],
556 })
557 } else {
558 let node = delegate.which("node".as_ref()).await?;
559 let (node_modules_path, _) = delegate
560 .npm_package_installed_version(Self::SERVER_NAME.as_ref())
561 .await
562 .log_err()??;
563
564 let path = node_modules_path.join(Self::NODE_MODULE_RELATIVE_SERVER_PATH);
565
566 let env = delegate.shell_env().await;
567 Some(LanguageServerBinary {
568 path: node,
569 env: Some(env),
570 arguments: vec![path.into(), "--stdio".into()],
571 })
572 }
573 }
574
575 async fn fetch_server_binary(
576 &self,
577 latest_version: Self::BinaryVersion,
578 container_dir: PathBuf,
579 delegate: &dyn LspAdapterDelegate,
580 ) -> Result<LanguageServerBinary> {
581 let server_path = container_dir.join(Self::SERVER_PATH);
582
583 self.node
584 .npm_install_packages(
585 &container_dir,
586 &[(Self::SERVER_NAME.as_ref(), latest_version.as_str())],
587 )
588 .await?;
589
590 let env = delegate.shell_env().await;
591 Ok(LanguageServerBinary {
592 path: self.node.binary_path().await?,
593 env: Some(env),
594 arguments: vec![server_path.into(), "--stdio".into()],
595 })
596 }
597
598 async fn check_if_version_installed(
599 &self,
600 version: &Self::BinaryVersion,
601 container_dir: &PathBuf,
602 delegate: &dyn LspAdapterDelegate,
603 ) -> Option<LanguageServerBinary> {
604 let server_path = container_dir.join(Self::SERVER_PATH);
605
606 let should_install_language_server = self
607 .node
608 .should_install_npm_package(
609 Self::SERVER_NAME.as_ref(),
610 &server_path,
611 container_dir,
612 VersionStrategy::Latest(version),
613 )
614 .await;
615
616 if should_install_language_server {
617 None
618 } else {
619 let env = delegate.shell_env().await;
620 Some(LanguageServerBinary {
621 path: self.node.binary_path().await.ok()?,
622 env: Some(env),
623 arguments: vec![server_path.into(), "--stdio".into()],
624 })
625 }
626 }
627
628 async fn cached_server_binary(
629 &self,
630 container_dir: PathBuf,
631 delegate: &dyn LspAdapterDelegate,
632 ) -> Option<LanguageServerBinary> {
633 let mut binary = Self::get_cached_server_binary(container_dir, &self.node).await?;
634 binary.env = Some(delegate.shell_env().await);
635 Some(binary)
636 }
637}
638
639pub(crate) struct PythonContextProvider;
640
641const PYTHON_TEST_TARGET_TASK_VARIABLE: VariableName =
642 VariableName::Custom(Cow::Borrowed("PYTHON_TEST_TARGET"));
643
644const PYTHON_ACTIVE_TOOLCHAIN_PATH: VariableName =
645 VariableName::Custom(Cow::Borrowed("PYTHON_ACTIVE_ZED_TOOLCHAIN"));
646
647const PYTHON_MODULE_NAME_TASK_VARIABLE: VariableName =
648 VariableName::Custom(Cow::Borrowed("PYTHON_MODULE_NAME"));
649
650impl ContextProvider for PythonContextProvider {
651 fn build_context(
652 &self,
653 variables: &task::TaskVariables,
654 location: ContextLocation<'_>,
655 _: Option<HashMap<String, String>>,
656 toolchains: Arc<dyn LanguageToolchainStore>,
657 cx: &mut gpui::App,
658 ) -> Task<Result<task::TaskVariables>> {
659 let test_target =
660 match selected_test_runner(location.file_location.buffer.read(cx).file(), cx) {
661 TestRunner::UNITTEST => self.build_unittest_target(variables),
662 TestRunner::PYTEST => self.build_pytest_target(variables),
663 };
664
665 let module_target = self.build_module_target(variables);
666 let location_file = location.file_location.buffer.read(cx).file().cloned();
667 let worktree_id = location_file.as_ref().map(|f| f.worktree_id(cx));
668
669 cx.spawn(async move |cx| {
670 let active_toolchain = if let Some(worktree_id) = worktree_id {
671 let file_path = location_file
672 .as_ref()
673 .and_then(|f| f.path().parent())
674 .map(Arc::from)
675 .unwrap_or_else(|| Arc::from("".as_ref()));
676
677 toolchains
678 .active_toolchain(worktree_id, file_path, "Python".into(), cx)
679 .await
680 .map_or_else(
681 || String::from("python3"),
682 |toolchain| toolchain.path.to_string(),
683 )
684 } else {
685 String::from("python3")
686 };
687
688 let toolchain = (PYTHON_ACTIVE_TOOLCHAIN_PATH, active_toolchain);
689
690 Ok(task::TaskVariables::from_iter(
691 test_target
692 .into_iter()
693 .chain(module_target.into_iter())
694 .chain([toolchain]),
695 ))
696 })
697 }
698
699 fn associated_tasks(
700 &self,
701 file: Option<Arc<dyn language::File>>,
702 cx: &App,
703 ) -> Task<Option<TaskTemplates>> {
704 let test_runner = selected_test_runner(file.as_ref(), cx);
705
706 let mut tasks = vec![
707 // Execute a selection
708 TaskTemplate {
709 label: "execute selection".to_owned(),
710 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
711 args: vec![
712 "-c".to_owned(),
713 VariableName::SelectedText.template_value_with_whitespace(),
714 ],
715 cwd: Some(VariableName::WorktreeRoot.template_value()),
716 ..TaskTemplate::default()
717 },
718 // Execute an entire file
719 TaskTemplate {
720 label: format!("run '{}'", VariableName::File.template_value()),
721 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
722 args: vec![VariableName::File.template_value_with_whitespace()],
723 cwd: Some(VariableName::WorktreeRoot.template_value()),
724 ..TaskTemplate::default()
725 },
726 // Execute a file as module
727 TaskTemplate {
728 label: format!("run module '{}'", VariableName::File.template_value()),
729 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
730 args: vec![
731 "-m".to_owned(),
732 PYTHON_MODULE_NAME_TASK_VARIABLE.template_value(),
733 ],
734 cwd: Some(VariableName::WorktreeRoot.template_value()),
735 tags: vec!["python-module-main-method".to_owned()],
736 ..TaskTemplate::default()
737 },
738 ];
739
740 tasks.extend(match test_runner {
741 TestRunner::UNITTEST => {
742 [
743 // Run tests for an entire file
744 TaskTemplate {
745 label: format!("unittest '{}'", VariableName::File.template_value()),
746 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
747 args: vec![
748 "-m".to_owned(),
749 "unittest".to_owned(),
750 VariableName::File.template_value_with_whitespace(),
751 ],
752 cwd: Some(VariableName::WorktreeRoot.template_value()),
753 ..TaskTemplate::default()
754 },
755 // Run test(s) for a specific target within a file
756 TaskTemplate {
757 label: "unittest $ZED_CUSTOM_PYTHON_TEST_TARGET".to_owned(),
758 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
759 args: vec![
760 "-m".to_owned(),
761 "unittest".to_owned(),
762 PYTHON_TEST_TARGET_TASK_VARIABLE.template_value_with_whitespace(),
763 ],
764 tags: vec![
765 "python-unittest-class".to_owned(),
766 "python-unittest-method".to_owned(),
767 ],
768 cwd: Some(VariableName::WorktreeRoot.template_value()),
769 ..TaskTemplate::default()
770 },
771 ]
772 }
773 TestRunner::PYTEST => {
774 [
775 // Run tests for an entire file
776 TaskTemplate {
777 label: format!("pytest '{}'", VariableName::File.template_value()),
778 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
779 args: vec![
780 "-m".to_owned(),
781 "pytest".to_owned(),
782 VariableName::File.template_value_with_whitespace(),
783 ],
784 cwd: Some(VariableName::WorktreeRoot.template_value()),
785 ..TaskTemplate::default()
786 },
787 // Run test(s) for a specific target within a file
788 TaskTemplate {
789 label: "pytest $ZED_CUSTOM_PYTHON_TEST_TARGET".to_owned(),
790 command: PYTHON_ACTIVE_TOOLCHAIN_PATH.template_value(),
791 args: vec![
792 "-m".to_owned(),
793 "pytest".to_owned(),
794 PYTHON_TEST_TARGET_TASK_VARIABLE.template_value_with_whitespace(),
795 ],
796 cwd: Some(VariableName::WorktreeRoot.template_value()),
797 tags: vec![
798 "python-pytest-class".to_owned(),
799 "python-pytest-method".to_owned(),
800 ],
801 ..TaskTemplate::default()
802 },
803 ]
804 }
805 });
806
807 Task::ready(Some(TaskTemplates(tasks)))
808 }
809}
810
811fn selected_test_runner(location: Option<&Arc<dyn language::File>>, cx: &App) -> TestRunner {
812 const TEST_RUNNER_VARIABLE: &str = "TEST_RUNNER";
813 language_settings(Some(LanguageName::new("Python")), location, cx)
814 .tasks
815 .variables
816 .get(TEST_RUNNER_VARIABLE)
817 .and_then(|val| TestRunner::from_str(val).ok())
818 .unwrap_or(TestRunner::PYTEST)
819}
820
821impl PythonContextProvider {
822 fn build_unittest_target(
823 &self,
824 variables: &task::TaskVariables,
825 ) -> Option<(VariableName, String)> {
826 let python_module_name =
827 python_module_name_from_relative_path(variables.get(&VariableName::RelativeFile)?);
828
829 let unittest_class_name =
830 variables.get(&VariableName::Custom(Cow::Borrowed("_unittest_class_name")));
831
832 let unittest_method_name = variables.get(&VariableName::Custom(Cow::Borrowed(
833 "_unittest_method_name",
834 )));
835
836 let unittest_target_str = match (unittest_class_name, unittest_method_name) {
837 (Some(class_name), Some(method_name)) => {
838 format!("{python_module_name}.{class_name}.{method_name}")
839 }
840 (Some(class_name), None) => format!("{python_module_name}.{class_name}"),
841 (None, None) => python_module_name,
842 // should never happen, a TestCase class is the unit of testing
843 (None, Some(_)) => return None,
844 };
845
846 Some((
847 PYTHON_TEST_TARGET_TASK_VARIABLE.clone(),
848 unittest_target_str,
849 ))
850 }
851
852 fn build_pytest_target(
853 &self,
854 variables: &task::TaskVariables,
855 ) -> Option<(VariableName, String)> {
856 let file_path = variables.get(&VariableName::RelativeFile)?;
857
858 let pytest_class_name =
859 variables.get(&VariableName::Custom(Cow::Borrowed("_pytest_class_name")));
860
861 let pytest_method_name =
862 variables.get(&VariableName::Custom(Cow::Borrowed("_pytest_method_name")));
863
864 let pytest_target_str = match (pytest_class_name, pytest_method_name) {
865 (Some(class_name), Some(method_name)) => {
866 format!("{file_path}::{class_name}::{method_name}")
867 }
868 (Some(class_name), None) => {
869 format!("{file_path}::{class_name}")
870 }
871 (None, Some(method_name)) => {
872 format!("{file_path}::{method_name}")
873 }
874 (None, None) => file_path.to_string(),
875 };
876
877 Some((PYTHON_TEST_TARGET_TASK_VARIABLE.clone(), pytest_target_str))
878 }
879
880 fn build_module_target(
881 &self,
882 variables: &task::TaskVariables,
883 ) -> Result<(VariableName, String)> {
884 let python_module_name = python_module_name_from_relative_path(
885 variables.get(&VariableName::RelativeFile).unwrap_or(""),
886 );
887
888 let module_target = (PYTHON_MODULE_NAME_TASK_VARIABLE.clone(), python_module_name);
889
890 Ok(module_target)
891 }
892}
893
894fn python_module_name_from_relative_path(relative_path: &str) -> String {
895 let path_with_dots = relative_path.replace('/', ".");
896 path_with_dots
897 .strip_suffix(".py")
898 .unwrap_or(&path_with_dots)
899 .to_string()
900}
901
902fn is_python_env_global(k: &PythonEnvironmentKind) -> bool {
903 matches!(
904 k,
905 PythonEnvironmentKind::Homebrew
906 | PythonEnvironmentKind::Pyenv
907 | PythonEnvironmentKind::GlobalPaths
908 | PythonEnvironmentKind::MacPythonOrg
909 | PythonEnvironmentKind::MacCommandLineTools
910 | PythonEnvironmentKind::LinuxGlobal
911 | PythonEnvironmentKind::MacXCode
912 | PythonEnvironmentKind::WindowsStore
913 | PythonEnvironmentKind::WindowsRegistry
914 )
915}
916
917fn python_env_kind_display(k: &PythonEnvironmentKind) -> &'static str {
918 match k {
919 PythonEnvironmentKind::Conda => "Conda",
920 PythonEnvironmentKind::Pixi => "pixi",
921 PythonEnvironmentKind::Homebrew => "Homebrew",
922 PythonEnvironmentKind::Pyenv => "global (Pyenv)",
923 PythonEnvironmentKind::GlobalPaths => "global",
924 PythonEnvironmentKind::PyenvVirtualEnv => "Pyenv",
925 PythonEnvironmentKind::Pipenv => "Pipenv",
926 PythonEnvironmentKind::Poetry => "Poetry",
927 PythonEnvironmentKind::MacPythonOrg => "global (Python.org)",
928 PythonEnvironmentKind::MacCommandLineTools => "global (Command Line Tools for Xcode)",
929 PythonEnvironmentKind::LinuxGlobal => "global",
930 PythonEnvironmentKind::MacXCode => "global (Xcode)",
931 PythonEnvironmentKind::Venv => "venv",
932 PythonEnvironmentKind::VirtualEnv => "virtualenv",
933 PythonEnvironmentKind::VirtualEnvWrapper => "virtualenvwrapper",
934 PythonEnvironmentKind::WindowsStore => "global (Windows Store)",
935 PythonEnvironmentKind::WindowsRegistry => "global (Windows Registry)",
936 }
937}
938
939pub(crate) struct PythonToolchainProvider;
940
941static ENV_PRIORITY_LIST: &[PythonEnvironmentKind] = &[
942 // Prioritize non-Conda environments.
943 PythonEnvironmentKind::Poetry,
944 PythonEnvironmentKind::Pipenv,
945 PythonEnvironmentKind::VirtualEnvWrapper,
946 PythonEnvironmentKind::Venv,
947 PythonEnvironmentKind::VirtualEnv,
948 PythonEnvironmentKind::PyenvVirtualEnv,
949 PythonEnvironmentKind::Pixi,
950 PythonEnvironmentKind::Conda,
951 PythonEnvironmentKind::Pyenv,
952 PythonEnvironmentKind::GlobalPaths,
953 PythonEnvironmentKind::Homebrew,
954];
955
956fn env_priority(kind: Option<PythonEnvironmentKind>) -> usize {
957 if let Some(kind) = kind {
958 ENV_PRIORITY_LIST
959 .iter()
960 .position(|blessed_env| blessed_env == &kind)
961 .unwrap_or(ENV_PRIORITY_LIST.len())
962 } else {
963 // Unknown toolchains are less useful than non-blessed ones.
964 ENV_PRIORITY_LIST.len() + 1
965 }
966}
967
968/// Return the name of environment declared in <worktree-root/.venv.
969///
970/// https://virtualfish.readthedocs.io/en/latest/plugins.html#auto-activation-auto-activation
971async fn get_worktree_venv_declaration(worktree_root: &Path) -> Option<String> {
972 let file = async_fs::File::open(worktree_root.join(".venv"))
973 .await
974 .ok()?;
975 let mut venv_name = String::new();
976 smol::io::BufReader::new(file)
977 .read_line(&mut venv_name)
978 .await
979 .ok()?;
980 Some(venv_name.trim().to_string())
981}
982
983fn get_venv_parent_dir(env: &PythonEnvironment) -> Option<PathBuf> {
984 // If global, we aren't a virtual environment
985 if let Some(kind) = env.kind
986 && is_python_env_global(&kind)
987 {
988 return None;
989 }
990
991 // Check to be sure we are a virtual environment using pet's most generic
992 // virtual environment type, VirtualEnv
993 let venv = env
994 .executable
995 .as_ref()
996 .and_then(|p| p.parent())
997 .and_then(|p| p.parent())
998 .filter(|p| is_virtualenv_dir(p))?;
999
1000 venv.parent().map(|parent| parent.to_path_buf())
1001}
1002
1003#[async_trait]
1004impl ToolchainLister for PythonToolchainProvider {
1005 async fn list(
1006 &self,
1007 worktree_root: PathBuf,
1008 subroot_relative_path: Arc<Path>,
1009 project_env: Option<HashMap<String, String>>,
1010 ) -> ToolchainList {
1011 let env = project_env.unwrap_or_default();
1012 let environment = EnvironmentApi::from_env(&env);
1013 let locators = pet::locators::create_locators(
1014 Arc::new(pet_conda::Conda::from(&environment)),
1015 Arc::new(pet_poetry::Poetry::from(&environment)),
1016 &environment,
1017 );
1018 let mut config = Configuration::default();
1019
1020 debug_assert!(subroot_relative_path.is_relative());
1021 // `.ancestors()` will yield at least one path, so in case of empty `subroot_relative_path`, we'll just use
1022 // worktree root as the workspace directory.
1023 config.workspace_directories = Some(
1024 subroot_relative_path
1025 .ancestors()
1026 .map(|ancestor| worktree_root.join(ancestor))
1027 .collect(),
1028 );
1029 for locator in locators.iter() {
1030 locator.configure(&config);
1031 }
1032
1033 let reporter = pet_reporter::collect::create_reporter();
1034 pet::find::find_and_report_envs(&reporter, config, &locators, &environment, None);
1035
1036 let mut toolchains = reporter
1037 .environments
1038 .lock()
1039 .map_or(Vec::new(), |mut guard| std::mem::take(&mut guard));
1040
1041 let wr = worktree_root;
1042 let wr_venv = get_worktree_venv_declaration(&wr).await;
1043 // Sort detected environments by:
1044 // environment name matching activation file (<workdir>/.venv)
1045 // environment project dir matching worktree_root
1046 // general env priority
1047 // environment path matching the CONDA_PREFIX env var
1048 // executable path
1049 toolchains.sort_by(|lhs, rhs| {
1050 // Compare venv names against worktree .venv file
1051 let venv_ordering =
1052 wr_venv
1053 .as_ref()
1054 .map_or(Ordering::Equal, |venv| match (&lhs.name, &rhs.name) {
1055 (Some(l), Some(r)) => (r == venv).cmp(&(l == venv)),
1056 (Some(l), None) if l == venv => Ordering::Less,
1057 (None, Some(r)) if r == venv => Ordering::Greater,
1058 _ => Ordering::Equal,
1059 });
1060
1061 // Compare project paths against worktree root
1062 let proj_ordering = || {
1063 let lhs_project = lhs.project.clone().or_else(|| get_venv_parent_dir(lhs));
1064 let rhs_project = rhs.project.clone().or_else(|| get_venv_parent_dir(rhs));
1065 match (&lhs_project, &rhs_project) {
1066 (Some(l), Some(r)) => (r == &wr).cmp(&(l == &wr)),
1067 (Some(l), None) if l == &wr => Ordering::Less,
1068 (None, Some(r)) if r == &wr => Ordering::Greater,
1069 _ => Ordering::Equal,
1070 }
1071 };
1072
1073 // Compare environment priorities
1074 let priority_ordering = || env_priority(lhs.kind).cmp(&env_priority(rhs.kind));
1075
1076 // Compare conda prefixes
1077 let conda_ordering = || {
1078 if lhs.kind == Some(PythonEnvironmentKind::Conda) {
1079 environment
1080 .get_env_var("CONDA_PREFIX".to_string())
1081 .map(|conda_prefix| {
1082 let is_match = |exe: &Option<PathBuf>| {
1083 exe.as_ref().is_some_and(|e| e.starts_with(&conda_prefix))
1084 };
1085 match (is_match(&lhs.executable), is_match(&rhs.executable)) {
1086 (true, false) => Ordering::Less,
1087 (false, true) => Ordering::Greater,
1088 _ => Ordering::Equal,
1089 }
1090 })
1091 .unwrap_or(Ordering::Equal)
1092 } else {
1093 Ordering::Equal
1094 }
1095 };
1096
1097 // Compare Python executables
1098 let exe_ordering = || lhs.executable.cmp(&rhs.executable);
1099
1100 venv_ordering
1101 .then_with(proj_ordering)
1102 .then_with(priority_ordering)
1103 .then_with(conda_ordering)
1104 .then_with(exe_ordering)
1105 });
1106
1107 let mut toolchains: Vec<_> = toolchains
1108 .into_iter()
1109 .filter_map(venv_to_toolchain)
1110 .collect();
1111 toolchains.dedup();
1112 ToolchainList {
1113 toolchains,
1114 default: None,
1115 groups: Default::default(),
1116 }
1117 }
1118 fn meta(&self) -> ToolchainMetadata {
1119 ToolchainMetadata {
1120 term: SharedString::new_static("Virtual Environment"),
1121 new_toolchain_placeholder: SharedString::new_static(
1122 "A path to the python3 executable within a virtual environment, or path to virtual environment itself",
1123 ),
1124 manifest_name: ManifestName::from(SharedString::new_static("pyproject.toml")),
1125 }
1126 }
1127
1128 async fn resolve(
1129 &self,
1130 path: PathBuf,
1131 env: Option<HashMap<String, String>>,
1132 ) -> anyhow::Result<Toolchain> {
1133 let env = env.unwrap_or_default();
1134 let environment = EnvironmentApi::from_env(&env);
1135 let locators = pet::locators::create_locators(
1136 Arc::new(pet_conda::Conda::from(&environment)),
1137 Arc::new(pet_poetry::Poetry::from(&environment)),
1138 &environment,
1139 );
1140 let toolchain = pet::resolve::resolve_environment(&path, &locators, &environment)
1141 .context("Could not find a virtual environment in provided path")?;
1142 let venv = toolchain.resolved.unwrap_or(toolchain.discovered);
1143 venv_to_toolchain(venv).context("Could not convert a venv into a toolchain")
1144 }
1145
1146 async fn activation_script(
1147 &self,
1148 toolchain: &Toolchain,
1149 shell: ShellKind,
1150 fs: &dyn Fs,
1151 ) -> Vec<String> {
1152 let Ok(toolchain) = serde_json::from_value::<pet_core::python_environment::PythonEnvironment>(
1153 toolchain.as_json.clone(),
1154 ) else {
1155 return vec![];
1156 };
1157 let mut activation_script = vec![];
1158
1159 match toolchain.kind {
1160 Some(PythonEnvironmentKind::Conda) => {
1161 if let Some(name) = &toolchain.name {
1162 activation_script.push(format!("conda activate {name}"));
1163 } else {
1164 activation_script.push("conda activate".to_string());
1165 }
1166 }
1167 Some(PythonEnvironmentKind::Venv | PythonEnvironmentKind::VirtualEnv) => {
1168 if let Some(prefix) = &toolchain.prefix {
1169 let activate_keyword = match shell {
1170 ShellKind::Cmd => ".",
1171 ShellKind::Nushell => "overlay use",
1172 ShellKind::PowerShell => ".",
1173 ShellKind::Fish => "source",
1174 ShellKind::Csh => "source",
1175 ShellKind::Posix => "source",
1176 };
1177 let activate_script_name = match shell {
1178 ShellKind::Posix => "activate",
1179 ShellKind::Csh => "activate.csh",
1180 ShellKind::Fish => "activate.fish",
1181 ShellKind::Nushell => "activate.nu",
1182 ShellKind::PowerShell => "activate.ps1",
1183 ShellKind::Cmd => "activate.bat",
1184 };
1185 let path = prefix.join(BINARY_DIR).join(activate_script_name);
1186
1187 if let Ok(quoted) =
1188 shlex::try_quote(&path.to_string_lossy()).map(Cow::into_owned)
1189 && fs.is_file(&path).await
1190 {
1191 activation_script.push(format!("{activate_keyword} {quoted}"));
1192 }
1193 }
1194 }
1195 Some(PythonEnvironmentKind::Pyenv) => {
1196 let Some(manager) = toolchain.manager else {
1197 return vec![];
1198 };
1199 let version = toolchain.version.as_deref().unwrap_or("system");
1200 let pyenv = manager.executable;
1201 let pyenv = pyenv.display();
1202 activation_script.extend(match shell {
1203 ShellKind::Fish => Some(format!("\"{pyenv}\" shell - fish {version}")),
1204 ShellKind::Posix => Some(format!("\"{pyenv}\" shell - sh {version}")),
1205 ShellKind::Nushell => Some(format!("\"{pyenv}\" shell - nu {version}")),
1206 ShellKind::PowerShell => None,
1207 ShellKind::Csh => None,
1208 ShellKind::Cmd => None,
1209 })
1210 }
1211 _ => {}
1212 }
1213 activation_script
1214 }
1215}
1216
1217fn venv_to_toolchain(venv: PythonEnvironment) -> Option<Toolchain> {
1218 let mut name = String::from("Python");
1219 if let Some(ref version) = venv.version {
1220 _ = write!(name, " {version}");
1221 }
1222
1223 let name_and_kind = match (&venv.name, &venv.kind) {
1224 (Some(name), Some(kind)) => Some(format!("({name}; {})", python_env_kind_display(kind))),
1225 (Some(name), None) => Some(format!("({name})")),
1226 (None, Some(kind)) => Some(format!("({})", python_env_kind_display(kind))),
1227 (None, None) => None,
1228 };
1229
1230 if let Some(nk) = name_and_kind {
1231 _ = write!(name, " {nk}");
1232 }
1233
1234 Some(Toolchain {
1235 name: name.into(),
1236 path: venv.executable.as_ref()?.to_str()?.to_owned().into(),
1237 language_name: LanguageName::new("Python"),
1238 as_json: serde_json::to_value(venv).ok()?,
1239 })
1240}
1241
1242pub struct EnvironmentApi<'a> {
1243 global_search_locations: Arc<Mutex<Vec<PathBuf>>>,
1244 project_env: &'a HashMap<String, String>,
1245 pet_env: pet_core::os_environment::EnvironmentApi,
1246}
1247
1248impl<'a> EnvironmentApi<'a> {
1249 pub fn from_env(project_env: &'a HashMap<String, String>) -> Self {
1250 let paths = project_env
1251 .get("PATH")
1252 .map(|p| std::env::split_paths(p).collect())
1253 .unwrap_or_default();
1254
1255 EnvironmentApi {
1256 global_search_locations: Arc::new(Mutex::new(paths)),
1257 project_env,
1258 pet_env: pet_core::os_environment::EnvironmentApi::new(),
1259 }
1260 }
1261
1262 fn user_home(&self) -> Option<PathBuf> {
1263 self.project_env
1264 .get("HOME")
1265 .or_else(|| self.project_env.get("USERPROFILE"))
1266 .map(|home| pet_fs::path::norm_case(PathBuf::from(home)))
1267 .or_else(|| self.pet_env.get_user_home())
1268 }
1269}
1270
1271impl pet_core::os_environment::Environment for EnvironmentApi<'_> {
1272 fn get_user_home(&self) -> Option<PathBuf> {
1273 self.user_home()
1274 }
1275
1276 fn get_root(&self) -> Option<PathBuf> {
1277 None
1278 }
1279
1280 fn get_env_var(&self, key: String) -> Option<String> {
1281 self.project_env
1282 .get(&key)
1283 .cloned()
1284 .or_else(|| self.pet_env.get_env_var(key))
1285 }
1286
1287 fn get_know_global_search_locations(&self) -> Vec<PathBuf> {
1288 if self.global_search_locations.lock().is_empty() {
1289 let mut paths =
1290 std::env::split_paths(&self.get_env_var("PATH".to_string()).unwrap_or_default())
1291 .collect::<Vec<PathBuf>>();
1292
1293 log::trace!("Env PATH: {:?}", paths);
1294 for p in self.pet_env.get_know_global_search_locations() {
1295 if !paths.contains(&p) {
1296 paths.push(p);
1297 }
1298 }
1299
1300 let mut paths = paths
1301 .into_iter()
1302 .filter(|p| p.exists())
1303 .collect::<Vec<PathBuf>>();
1304
1305 self.global_search_locations.lock().append(&mut paths);
1306 }
1307 self.global_search_locations.lock().clone()
1308 }
1309}
1310
1311pub(crate) struct PyLspAdapter {
1312 python_venv_base: OnceCell<Result<Arc<Path>, String>>,
1313}
1314impl PyLspAdapter {
1315 const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("pylsp");
1316 pub(crate) fn new() -> Self {
1317 Self {
1318 python_venv_base: OnceCell::new(),
1319 }
1320 }
1321 async fn ensure_venv(delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>> {
1322 let python_path = Self::find_base_python(delegate)
1323 .await
1324 .context("Could not find Python installation for PyLSP")?;
1325 let work_dir = delegate
1326 .language_server_download_dir(&Self::SERVER_NAME)
1327 .await
1328 .context("Could not get working directory for PyLSP")?;
1329 let mut path = PathBuf::from(work_dir.as_ref());
1330 path.push("pylsp-venv");
1331 if !path.exists() {
1332 util::command::new_smol_command(python_path)
1333 .arg("-m")
1334 .arg("venv")
1335 .arg("pylsp-venv")
1336 .current_dir(work_dir)
1337 .spawn()?
1338 .output()
1339 .await?;
1340 }
1341
1342 Ok(path.into())
1343 }
1344 // Find "baseline", user python version from which we'll create our own venv.
1345 async fn find_base_python(delegate: &dyn LspAdapterDelegate) -> Option<PathBuf> {
1346 for path in ["python3", "python"] {
1347 if let Some(path) = delegate.which(path.as_ref()).await {
1348 return Some(path);
1349 }
1350 }
1351 None
1352 }
1353
1354 async fn base_venv(&self, delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>, String> {
1355 self.python_venv_base
1356 .get_or_init(move || async move {
1357 Self::ensure_venv(delegate)
1358 .await
1359 .map_err(|e| format!("{e}"))
1360 })
1361 .await
1362 .clone()
1363 }
1364}
1365
1366const BINARY_DIR: &str = if cfg!(target_os = "windows") {
1367 "Scripts"
1368} else {
1369 "bin"
1370};
1371
1372#[async_trait(?Send)]
1373impl LspAdapter for PyLspAdapter {
1374 fn name(&self) -> LanguageServerName {
1375 Self::SERVER_NAME
1376 }
1377
1378 async fn process_completions(&self, _items: &mut [lsp::CompletionItem]) {}
1379
1380 async fn label_for_completion(
1381 &self,
1382 item: &lsp::CompletionItem,
1383 language: &Arc<language::Language>,
1384 ) -> Option<language::CodeLabel> {
1385 let label = &item.label;
1386 let grammar = language.grammar()?;
1387 let highlight_id = match item.kind? {
1388 lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method")?,
1389 lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function")?,
1390 lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type")?,
1391 lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant")?,
1392 _ => return None,
1393 };
1394 let filter_range = item
1395 .filter_text
1396 .as_deref()
1397 .and_then(|filter| label.find(filter).map(|ix| ix..ix + filter.len()))
1398 .unwrap_or(0..label.len());
1399 Some(language::CodeLabel {
1400 text: label.clone(),
1401 runs: vec![(0..label.len(), highlight_id)],
1402 filter_range,
1403 })
1404 }
1405
1406 async fn label_for_symbol(
1407 &self,
1408 name: &str,
1409 kind: lsp::SymbolKind,
1410 language: &Arc<language::Language>,
1411 ) -> Option<language::CodeLabel> {
1412 let (text, filter_range, display_range) = match kind {
1413 lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
1414 let text = format!("def {}():\n", name);
1415 let filter_range = 4..4 + name.len();
1416 let display_range = 0..filter_range.end;
1417 (text, filter_range, display_range)
1418 }
1419 lsp::SymbolKind::CLASS => {
1420 let text = format!("class {}:", name);
1421 let filter_range = 6..6 + name.len();
1422 let display_range = 0..filter_range.end;
1423 (text, filter_range, display_range)
1424 }
1425 lsp::SymbolKind::CONSTANT => {
1426 let text = format!("{} = 0", name);
1427 let filter_range = 0..name.len();
1428 let display_range = 0..filter_range.end;
1429 (text, filter_range, display_range)
1430 }
1431 _ => return None,
1432 };
1433
1434 Some(language::CodeLabel {
1435 runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
1436 text: text[display_range].to_string(),
1437 filter_range,
1438 })
1439 }
1440
1441 async fn workspace_configuration(
1442 self: Arc<Self>,
1443 adapter: &Arc<dyn LspAdapterDelegate>,
1444 toolchain: Option<Toolchain>,
1445 cx: &mut AsyncApp,
1446 ) -> Result<Value> {
1447 cx.update(move |cx| {
1448 let mut user_settings =
1449 language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
1450 .and_then(|s| s.settings.clone())
1451 .unwrap_or_else(|| {
1452 json!({
1453 "plugins": {
1454 "pycodestyle": {"enabled": false},
1455 "rope_autoimport": {"enabled": true, "memory": true},
1456 "pylsp_mypy": {"enabled": false}
1457 },
1458 "rope": {
1459 "ropeFolder": null
1460 },
1461 })
1462 });
1463
1464 // If user did not explicitly modify their python venv, use one from picker.
1465 if let Some(toolchain) = toolchain {
1466 if !user_settings.is_object() {
1467 user_settings = Value::Object(serde_json::Map::default());
1468 }
1469 let object = user_settings.as_object_mut().unwrap();
1470 if let Some(python) = object
1471 .entry("plugins")
1472 .or_insert(Value::Object(serde_json::Map::default()))
1473 .as_object_mut()
1474 {
1475 if let Some(jedi) = python
1476 .entry("jedi")
1477 .or_insert(Value::Object(serde_json::Map::default()))
1478 .as_object_mut()
1479 {
1480 jedi.entry("environment".to_string())
1481 .or_insert_with(|| Value::String(toolchain.path.clone().into()));
1482 }
1483 if let Some(pylint) = python
1484 .entry("pylsp_mypy")
1485 .or_insert(Value::Object(serde_json::Map::default()))
1486 .as_object_mut()
1487 {
1488 pylint.entry("overrides".to_string()).or_insert_with(|| {
1489 Value::Array(vec![
1490 Value::String("--python-executable".into()),
1491 Value::String(toolchain.path.into()),
1492 Value::String("--cache-dir=/dev/null".into()),
1493 Value::Bool(true),
1494 ])
1495 });
1496 }
1497 }
1498 }
1499 user_settings = Value::Object(serde_json::Map::from_iter([(
1500 "pylsp".to_string(),
1501 user_settings,
1502 )]));
1503
1504 user_settings
1505 })
1506 }
1507}
1508
1509impl LspInstaller for PyLspAdapter {
1510 type BinaryVersion = ();
1511 async fn check_if_user_installed(
1512 &self,
1513 delegate: &dyn LspAdapterDelegate,
1514 toolchain: Option<Toolchain>,
1515 _: &AsyncApp,
1516 ) -> Option<LanguageServerBinary> {
1517 if let Some(pylsp_bin) = delegate.which(Self::SERVER_NAME.as_ref()).await {
1518 let env = delegate.shell_env().await;
1519 Some(LanguageServerBinary {
1520 path: pylsp_bin,
1521 env: Some(env),
1522 arguments: vec![],
1523 })
1524 } else {
1525 let toolchain = toolchain?;
1526 let pylsp_path = Path::new(toolchain.path.as_ref()).parent()?.join("pylsp");
1527 pylsp_path.exists().then(|| LanguageServerBinary {
1528 path: toolchain.path.to_string().into(),
1529 arguments: vec![pylsp_path.into()],
1530 env: None,
1531 })
1532 }
1533 }
1534
1535 async fn fetch_latest_server_version(
1536 &self,
1537 _: &dyn LspAdapterDelegate,
1538 _: bool,
1539 _: &mut AsyncApp,
1540 ) -> Result<()> {
1541 Ok(())
1542 }
1543
1544 async fn fetch_server_binary(
1545 &self,
1546 _: (),
1547 _: PathBuf,
1548 delegate: &dyn LspAdapterDelegate,
1549 ) -> Result<LanguageServerBinary> {
1550 let venv = self.base_venv(delegate).await.map_err(|e| anyhow!(e))?;
1551 let pip_path = venv.join(BINARY_DIR).join("pip3");
1552 ensure!(
1553 util::command::new_smol_command(pip_path.as_path())
1554 .arg("install")
1555 .arg("python-lsp-server[all]")
1556 .arg("--upgrade")
1557 .output()
1558 .await?
1559 .status
1560 .success(),
1561 "python-lsp-server[all] installation failed"
1562 );
1563 ensure!(
1564 util::command::new_smol_command(pip_path)
1565 .arg("install")
1566 .arg("pylsp-mypy")
1567 .arg("--upgrade")
1568 .output()
1569 .await?
1570 .status
1571 .success(),
1572 "pylsp-mypy installation failed"
1573 );
1574 let pylsp = venv.join(BINARY_DIR).join("pylsp");
1575 ensure!(
1576 delegate.which(pylsp.as_os_str()).await.is_some(),
1577 "pylsp installation was incomplete"
1578 );
1579 Ok(LanguageServerBinary {
1580 path: pylsp,
1581 env: None,
1582 arguments: vec![],
1583 })
1584 }
1585
1586 async fn cached_server_binary(
1587 &self,
1588 _: PathBuf,
1589 delegate: &dyn LspAdapterDelegate,
1590 ) -> Option<LanguageServerBinary> {
1591 let venv = self.base_venv(delegate).await.ok()?;
1592 let pylsp = venv.join(BINARY_DIR).join("pylsp");
1593 delegate.which(pylsp.as_os_str()).await?;
1594 Some(LanguageServerBinary {
1595 path: pylsp,
1596 env: None,
1597 arguments: vec![],
1598 })
1599 }
1600}
1601
1602pub(crate) struct BasedPyrightLspAdapter {
1603 node: NodeRuntime,
1604}
1605
1606impl BasedPyrightLspAdapter {
1607 const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("basedpyright");
1608 const BINARY_NAME: &'static str = "basedpyright-langserver";
1609 const SERVER_PATH: &str = "node_modules/basedpyright/langserver.index.js";
1610 const NODE_MODULE_RELATIVE_SERVER_PATH: &str = "basedpyright/langserver.index.js";
1611
1612 pub(crate) fn new(node: NodeRuntime) -> Self {
1613 BasedPyrightLspAdapter { node }
1614 }
1615
1616 async fn get_cached_server_binary(
1617 container_dir: PathBuf,
1618 node: &NodeRuntime,
1619 ) -> Option<LanguageServerBinary> {
1620 let server_path = container_dir.join(Self::SERVER_PATH);
1621 if server_path.exists() {
1622 Some(LanguageServerBinary {
1623 path: node.binary_path().await.log_err()?,
1624 env: None,
1625 arguments: vec![server_path.into(), "--stdio".into()],
1626 })
1627 } else {
1628 log::error!("missing executable in directory {:?}", server_path);
1629 None
1630 }
1631 }
1632}
1633
1634#[async_trait(?Send)]
1635impl LspAdapter for BasedPyrightLspAdapter {
1636 fn name(&self) -> LanguageServerName {
1637 Self::SERVER_NAME
1638 }
1639
1640 async fn initialization_options(
1641 self: Arc<Self>,
1642 _: &Arc<dyn LspAdapterDelegate>,
1643 ) -> Result<Option<Value>> {
1644 // Provide minimal initialization options
1645 // Virtual environment configuration will be handled through workspace configuration
1646 Ok(Some(json!({
1647 "python": {
1648 "analysis": {
1649 "autoSearchPaths": true,
1650 "useLibraryCodeForTypes": true,
1651 "autoImportCompletions": true
1652 }
1653 }
1654 })))
1655 }
1656
1657 async fn process_completions(&self, items: &mut [lsp::CompletionItem]) {
1658 process_pyright_completions(items);
1659 }
1660
1661 async fn label_for_completion(
1662 &self,
1663 item: &lsp::CompletionItem,
1664 language: &Arc<language::Language>,
1665 ) -> Option<language::CodeLabel> {
1666 let label = &item.label;
1667 let grammar = language.grammar()?;
1668 let highlight_id = match item.kind? {
1669 lsp::CompletionItemKind::METHOD => grammar.highlight_id_for_name("function.method"),
1670 lsp::CompletionItemKind::FUNCTION => grammar.highlight_id_for_name("function"),
1671 lsp::CompletionItemKind::CLASS => grammar.highlight_id_for_name("type"),
1672 lsp::CompletionItemKind::CONSTANT => grammar.highlight_id_for_name("constant"),
1673 lsp::CompletionItemKind::VARIABLE => grammar.highlight_id_for_name("variable"),
1674 _ => {
1675 return None;
1676 }
1677 };
1678 let filter_range = item
1679 .filter_text
1680 .as_deref()
1681 .and_then(|filter| label.find(filter).map(|ix| ix..ix + filter.len()))
1682 .unwrap_or(0..label.len());
1683 let mut text = label.clone();
1684 if let Some(completion_details) = item
1685 .label_details
1686 .as_ref()
1687 .and_then(|details| details.description.as_ref())
1688 {
1689 write!(&mut text, " {}", completion_details).ok();
1690 }
1691 Some(language::CodeLabel {
1692 runs: highlight_id
1693 .map(|id| (0..label.len(), id))
1694 .into_iter()
1695 .collect(),
1696 text,
1697 filter_range,
1698 })
1699 }
1700
1701 async fn label_for_symbol(
1702 &self,
1703 name: &str,
1704 kind: lsp::SymbolKind,
1705 language: &Arc<language::Language>,
1706 ) -> Option<language::CodeLabel> {
1707 let (text, filter_range, display_range) = match kind {
1708 lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
1709 let text = format!("def {}():\n", name);
1710 let filter_range = 4..4 + name.len();
1711 let display_range = 0..filter_range.end;
1712 (text, filter_range, display_range)
1713 }
1714 lsp::SymbolKind::CLASS => {
1715 let text = format!("class {}:", name);
1716 let filter_range = 6..6 + name.len();
1717 let display_range = 0..filter_range.end;
1718 (text, filter_range, display_range)
1719 }
1720 lsp::SymbolKind::CONSTANT => {
1721 let text = format!("{} = 0", name);
1722 let filter_range = 0..name.len();
1723 let display_range = 0..filter_range.end;
1724 (text, filter_range, display_range)
1725 }
1726 _ => return None,
1727 };
1728
1729 Some(language::CodeLabel {
1730 runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
1731 text: text[display_range].to_string(),
1732 filter_range,
1733 })
1734 }
1735
1736 async fn workspace_configuration(
1737 self: Arc<Self>,
1738 adapter: &Arc<dyn LspAdapterDelegate>,
1739 toolchain: Option<Toolchain>,
1740 cx: &mut AsyncApp,
1741 ) -> Result<Value> {
1742 cx.update(move |cx| {
1743 let mut user_settings =
1744 language_server_settings(adapter.as_ref(), &Self::SERVER_NAME, cx)
1745 .and_then(|s| s.settings.clone())
1746 .unwrap_or_default();
1747
1748 // If we have a detected toolchain, configure Pyright to use it
1749 if let Some(toolchain) = toolchain
1750 && let Ok(env) = serde_json::from_value::<
1751 pet_core::python_environment::PythonEnvironment,
1752 >(toolchain.as_json.clone())
1753 {
1754 if !user_settings.is_object() {
1755 user_settings = Value::Object(serde_json::Map::default());
1756 }
1757 let object = user_settings.as_object_mut().unwrap();
1758
1759 let interpreter_path = toolchain.path.to_string();
1760 if let Some(venv_dir) = env.prefix {
1761 // Set venvPath and venv at the root level
1762 // This matches the format of a pyrightconfig.json file
1763 if let Some(parent) = venv_dir.parent() {
1764 // Use relative path if the venv is inside the workspace
1765 let venv_path = if parent == adapter.worktree_root_path() {
1766 ".".to_string()
1767 } else {
1768 parent.to_string_lossy().into_owned()
1769 };
1770 object.insert("venvPath".to_string(), Value::String(venv_path));
1771 }
1772
1773 if let Some(venv_name) = venv_dir.file_name() {
1774 object.insert(
1775 "venv".to_owned(),
1776 Value::String(venv_name.to_string_lossy().into_owned()),
1777 );
1778 }
1779 }
1780
1781 // Set both pythonPath and defaultInterpreterPath for compatibility
1782 if let Some(python) = object
1783 .entry("python")
1784 .or_insert(Value::Object(serde_json::Map::default()))
1785 .as_object_mut()
1786 {
1787 python.insert(
1788 "pythonPath".to_owned(),
1789 Value::String(interpreter_path.clone()),
1790 );
1791 python.insert(
1792 "defaultInterpreterPath".to_owned(),
1793 Value::String(interpreter_path),
1794 );
1795 }
1796 // Basedpyright by default uses `strict` type checking, we tone it down as to not surpris users
1797 maybe!({
1798 let basedpyright = object
1799 .entry("basedpyright")
1800 .or_insert(Value::Object(serde_json::Map::default()));
1801 let analysis = basedpyright
1802 .as_object_mut()?
1803 .entry("analysis")
1804 .or_insert(Value::Object(serde_json::Map::default()));
1805 if let serde_json::map::Entry::Vacant(v) =
1806 analysis.as_object_mut()?.entry("typeCheckingMode")
1807 {
1808 v.insert(Value::String("standard".to_owned()));
1809 }
1810 Some(())
1811 });
1812 }
1813
1814 user_settings
1815 })
1816 }
1817}
1818
1819impl LspInstaller for BasedPyrightLspAdapter {
1820 type BinaryVersion = String;
1821
1822 async fn fetch_latest_server_version(
1823 &self,
1824 _: &dyn LspAdapterDelegate,
1825 _: bool,
1826 _: &mut AsyncApp,
1827 ) -> Result<String> {
1828 self.node
1829 .npm_package_latest_version(Self::SERVER_NAME.as_ref())
1830 .await
1831 }
1832
1833 async fn check_if_user_installed(
1834 &self,
1835 delegate: &dyn LspAdapterDelegate,
1836 _: Option<Toolchain>,
1837 _: &AsyncApp,
1838 ) -> Option<LanguageServerBinary> {
1839 if let Some(path) = delegate.which(Self::BINARY_NAME.as_ref()).await {
1840 let env = delegate.shell_env().await;
1841 Some(LanguageServerBinary {
1842 path,
1843 env: Some(env),
1844 arguments: vec!["--stdio".into()],
1845 })
1846 } else {
1847 // TODO shouldn't this be self.node.binary_path()?
1848 let node = delegate.which("node".as_ref()).await?;
1849 let (node_modules_path, _) = delegate
1850 .npm_package_installed_version(Self::SERVER_NAME.as_ref())
1851 .await
1852 .log_err()??;
1853
1854 let path = node_modules_path.join(Self::NODE_MODULE_RELATIVE_SERVER_PATH);
1855
1856 let env = delegate.shell_env().await;
1857 Some(LanguageServerBinary {
1858 path: node,
1859 env: Some(env),
1860 arguments: vec![path.into(), "--stdio".into()],
1861 })
1862 }
1863 }
1864
1865 async fn fetch_server_binary(
1866 &self,
1867 latest_version: Self::BinaryVersion,
1868 container_dir: PathBuf,
1869 delegate: &dyn LspAdapterDelegate,
1870 ) -> Result<LanguageServerBinary> {
1871 let server_path = container_dir.join(Self::SERVER_PATH);
1872
1873 self.node
1874 .npm_install_packages(
1875 &container_dir,
1876 &[(Self::SERVER_NAME.as_ref(), latest_version.as_str())],
1877 )
1878 .await?;
1879
1880 let env = delegate.shell_env().await;
1881 Ok(LanguageServerBinary {
1882 path: self.node.binary_path().await?,
1883 env: Some(env),
1884 arguments: vec![server_path.into(), "--stdio".into()],
1885 })
1886 }
1887
1888 async fn check_if_version_installed(
1889 &self,
1890 version: &Self::BinaryVersion,
1891 container_dir: &PathBuf,
1892 delegate: &dyn LspAdapterDelegate,
1893 ) -> Option<LanguageServerBinary> {
1894 let server_path = container_dir.join(Self::SERVER_PATH);
1895
1896 let should_install_language_server = self
1897 .node
1898 .should_install_npm_package(
1899 Self::SERVER_NAME.as_ref(),
1900 &server_path,
1901 container_dir,
1902 VersionStrategy::Latest(version),
1903 )
1904 .await;
1905
1906 if should_install_language_server {
1907 None
1908 } else {
1909 let env = delegate.shell_env().await;
1910 Some(LanguageServerBinary {
1911 path: self.node.binary_path().await.ok()?,
1912 env: Some(env),
1913 arguments: vec![server_path.into(), "--stdio".into()],
1914 })
1915 }
1916 }
1917
1918 async fn cached_server_binary(
1919 &self,
1920 container_dir: PathBuf,
1921 delegate: &dyn LspAdapterDelegate,
1922 ) -> Option<LanguageServerBinary> {
1923 let mut binary = Self::get_cached_server_binary(container_dir, &self.node).await?;
1924 binary.env = Some(delegate.shell_env().await);
1925 Some(binary)
1926 }
1927}
1928
1929pub(crate) struct RuffLspAdapter {
1930 fs: Arc<dyn Fs>,
1931}
1932
1933#[cfg(target_os = "macos")]
1934impl RuffLspAdapter {
1935 const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
1936 const ARCH_SERVER_NAME: &str = "apple-darwin";
1937}
1938
1939#[cfg(target_os = "linux")]
1940impl RuffLspAdapter {
1941 const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
1942 const ARCH_SERVER_NAME: &str = "unknown-linux-gnu";
1943}
1944
1945#[cfg(target_os = "freebsd")]
1946impl RuffLspAdapter {
1947 const GITHUB_ASSET_KIND: AssetKind = AssetKind::TarGz;
1948 const ARCH_SERVER_NAME: &str = "unknown-freebsd";
1949}
1950
1951#[cfg(target_os = "windows")]
1952impl RuffLspAdapter {
1953 const GITHUB_ASSET_KIND: AssetKind = AssetKind::Zip;
1954 const ARCH_SERVER_NAME: &str = "pc-windows-msvc";
1955}
1956
1957impl RuffLspAdapter {
1958 const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("ruff");
1959
1960 pub fn new(fs: Arc<dyn Fs>) -> RuffLspAdapter {
1961 RuffLspAdapter { fs }
1962 }
1963
1964 fn build_asset_name() -> Result<(String, String)> {
1965 let arch = match consts::ARCH {
1966 "x86" => "i686",
1967 _ => consts::ARCH,
1968 };
1969 let os = Self::ARCH_SERVER_NAME;
1970 let suffix = match consts::OS {
1971 "windows" => "zip",
1972 _ => "tar.gz",
1973 };
1974 let asset_name = format!("ruff-{arch}-{os}.{suffix}");
1975 let asset_stem = format!("ruff-{arch}-{os}");
1976 Ok((asset_stem, asset_name))
1977 }
1978}
1979
1980#[async_trait(?Send)]
1981impl LspAdapter for RuffLspAdapter {
1982 fn name(&self) -> LanguageServerName {
1983 Self::SERVER_NAME
1984 }
1985}
1986
1987impl LspInstaller for RuffLspAdapter {
1988 type BinaryVersion = GitHubLspBinaryVersion;
1989 async fn check_if_user_installed(
1990 &self,
1991 delegate: &dyn LspAdapterDelegate,
1992 toolchain: Option<Toolchain>,
1993 _: &AsyncApp,
1994 ) -> Option<LanguageServerBinary> {
1995 let ruff_in_venv = if let Some(toolchain) = toolchain
1996 && toolchain.language_name.as_ref() == "Python"
1997 {
1998 Path::new(toolchain.path.as_str())
1999 .parent()
2000 .map(|path| path.join("ruff"))
2001 } else {
2002 None
2003 };
2004
2005 for path in ruff_in_venv.into_iter().chain(["ruff".into()]) {
2006 if let Some(ruff_bin) = delegate.which(path.as_os_str()).await {
2007 let env = delegate.shell_env().await;
2008 return Some(LanguageServerBinary {
2009 path: ruff_bin,
2010 env: Some(env),
2011 arguments: vec!["server".into()],
2012 });
2013 }
2014 }
2015
2016 None
2017 }
2018
2019 async fn fetch_latest_server_version(
2020 &self,
2021 delegate: &dyn LspAdapterDelegate,
2022 _: bool,
2023 _: &mut AsyncApp,
2024 ) -> Result<GitHubLspBinaryVersion> {
2025 let release =
2026 latest_github_release("astral-sh/ruff", true, false, delegate.http_client()).await?;
2027 let (_, asset_name) = Self::build_asset_name()?;
2028 let asset = release
2029 .assets
2030 .into_iter()
2031 .find(|asset| asset.name == asset_name)
2032 .with_context(|| format!("no asset found matching `{asset_name:?}`"))?;
2033 Ok(GitHubLspBinaryVersion {
2034 name: release.tag_name,
2035 url: asset.browser_download_url,
2036 digest: asset.digest,
2037 })
2038 }
2039
2040 async fn fetch_server_binary(
2041 &self,
2042 latest_version: GitHubLspBinaryVersion,
2043 container_dir: PathBuf,
2044 delegate: &dyn LspAdapterDelegate,
2045 ) -> Result<LanguageServerBinary> {
2046 let GitHubLspBinaryVersion {
2047 name,
2048 url,
2049 digest: expected_digest,
2050 } = latest_version;
2051 let destination_path = container_dir.join(format!("ruff-{name}"));
2052 let server_path = match Self::GITHUB_ASSET_KIND {
2053 AssetKind::TarGz | AssetKind::Gz => destination_path
2054 .join(Self::build_asset_name()?.0)
2055 .join("ruff"),
2056 AssetKind::Zip => destination_path.clone().join("ruff.exe"),
2057 };
2058
2059 let binary = LanguageServerBinary {
2060 path: server_path.clone(),
2061 env: None,
2062 arguments: vec!["server".into()],
2063 };
2064
2065 let metadata_path = destination_path.with_extension("metadata");
2066 let metadata = GithubBinaryMetadata::read_from_file(&metadata_path)
2067 .await
2068 .ok();
2069 if let Some(metadata) = metadata {
2070 let validity_check = async || {
2071 delegate
2072 .try_exec(LanguageServerBinary {
2073 path: server_path.clone(),
2074 arguments: vec!["--version".into()],
2075 env: None,
2076 })
2077 .await
2078 .inspect_err(|err| {
2079 log::warn!("Unable to run {server_path:?} asset, redownloading: {err}",)
2080 })
2081 };
2082 if let (Some(actual_digest), Some(expected_digest)) =
2083 (&metadata.digest, &expected_digest)
2084 {
2085 if actual_digest == expected_digest {
2086 if validity_check().await.is_ok() {
2087 return Ok(binary);
2088 }
2089 } else {
2090 log::info!(
2091 "SHA-256 mismatch for {destination_path:?} asset, downloading new asset. Expected: {expected_digest}, Got: {actual_digest}"
2092 );
2093 }
2094 } else if validity_check().await.is_ok() {
2095 return Ok(binary);
2096 }
2097 }
2098
2099 download_server_binary(
2100 delegate,
2101 &url,
2102 expected_digest.as_deref(),
2103 &destination_path,
2104 Self::GITHUB_ASSET_KIND,
2105 )
2106 .await?;
2107 make_file_executable(&server_path).await?;
2108 remove_matching(&container_dir, |path| path != destination_path).await;
2109 GithubBinaryMetadata::write_to_file(
2110 &GithubBinaryMetadata {
2111 metadata_version: 1,
2112 digest: expected_digest,
2113 },
2114 &metadata_path,
2115 )
2116 .await?;
2117
2118 Ok(LanguageServerBinary {
2119 path: server_path,
2120 env: None,
2121 arguments: vec!["server".into()],
2122 })
2123 }
2124
2125 async fn cached_server_binary(
2126 &self,
2127 container_dir: PathBuf,
2128 _: &dyn LspAdapterDelegate,
2129 ) -> Option<LanguageServerBinary> {
2130 maybe!(async {
2131 let mut last = None;
2132 let mut entries = self.fs.read_dir(&container_dir).await?;
2133 while let Some(entry) = entries.next().await {
2134 let path = entry?;
2135 if path.extension().is_some_and(|ext| ext == "metadata") {
2136 continue;
2137 }
2138 last = Some(path);
2139 }
2140
2141 let path = last.context("no cached binary")?;
2142 let path = match Self::GITHUB_ASSET_KIND {
2143 AssetKind::TarGz | AssetKind::Gz => {
2144 path.join(Self::build_asset_name()?.0).join("ruff")
2145 }
2146 AssetKind::Zip => path.join("ruff.exe"),
2147 };
2148
2149 anyhow::Ok(LanguageServerBinary {
2150 path,
2151 env: None,
2152 arguments: vec!["server".into()],
2153 })
2154 })
2155 .await
2156 .log_err()
2157 }
2158}
2159
2160#[cfg(test)]
2161mod tests {
2162 use gpui::{AppContext as _, BorrowAppContext, Context, TestAppContext};
2163 use language::{AutoindentMode, Buffer};
2164 use settings::SettingsStore;
2165 use std::num::NonZeroU32;
2166
2167 #[gpui::test]
2168 async fn test_python_autoindent(cx: &mut TestAppContext) {
2169 cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
2170 let language = crate::language("python", tree_sitter_python::LANGUAGE.into());
2171 cx.update(|cx| {
2172 let test_settings = SettingsStore::test(cx);
2173 cx.set_global(test_settings);
2174 language::init(cx);
2175 cx.update_global::<SettingsStore, _>(|store, cx| {
2176 store.update_user_settings(cx, |s| {
2177 s.project.all_languages.defaults.tab_size = NonZeroU32::new(2);
2178 });
2179 });
2180 });
2181
2182 cx.new(|cx| {
2183 let mut buffer = Buffer::local("", cx).with_language(language, cx);
2184 let append = |buffer: &mut Buffer, text: &str, cx: &mut Context<Buffer>| {
2185 let ix = buffer.len();
2186 buffer.edit([(ix..ix, text)], Some(AutoindentMode::EachLine), cx);
2187 };
2188
2189 // indent after "def():"
2190 append(&mut buffer, "def a():\n", cx);
2191 assert_eq!(buffer.text(), "def a():\n ");
2192
2193 // preserve indent after blank line
2194 append(&mut buffer, "\n ", cx);
2195 assert_eq!(buffer.text(), "def a():\n \n ");
2196
2197 // indent after "if"
2198 append(&mut buffer, "if a:\n ", cx);
2199 assert_eq!(buffer.text(), "def a():\n \n if a:\n ");
2200
2201 // preserve indent after statement
2202 append(&mut buffer, "b()\n", cx);
2203 assert_eq!(buffer.text(), "def a():\n \n if a:\n b()\n ");
2204
2205 // preserve indent after statement
2206 append(&mut buffer, "else", cx);
2207 assert_eq!(buffer.text(), "def a():\n \n if a:\n b()\n else");
2208
2209 // dedent "else""
2210 append(&mut buffer, ":", cx);
2211 assert_eq!(buffer.text(), "def a():\n \n if a:\n b()\n else:");
2212
2213 // indent lines after else
2214 append(&mut buffer, "\n", cx);
2215 assert_eq!(
2216 buffer.text(),
2217 "def a():\n \n if a:\n b()\n else:\n "
2218 );
2219
2220 // indent after an open paren. the closing paren is not indented
2221 // because there is another token before it on the same line.
2222 append(&mut buffer, "foo(\n1)", cx);
2223 assert_eq!(
2224 buffer.text(),
2225 "def a():\n \n if a:\n b()\n else:\n foo(\n 1)"
2226 );
2227
2228 // dedent the closing paren if it is shifted to the beginning of the line
2229 let argument_ix = buffer.text().find('1').unwrap();
2230 buffer.edit(
2231 [(argument_ix..argument_ix + 1, "")],
2232 Some(AutoindentMode::EachLine),
2233 cx,
2234 );
2235 assert_eq!(
2236 buffer.text(),
2237 "def a():\n \n if a:\n b()\n else:\n foo(\n )"
2238 );
2239
2240 // preserve indent after the close paren
2241 append(&mut buffer, "\n", cx);
2242 assert_eq!(
2243 buffer.text(),
2244 "def a():\n \n if a:\n b()\n else:\n foo(\n )\n "
2245 );
2246
2247 // manually outdent the last line
2248 let end_whitespace_ix = buffer.len() - 4;
2249 buffer.edit(
2250 [(end_whitespace_ix..buffer.len(), "")],
2251 Some(AutoindentMode::EachLine),
2252 cx,
2253 );
2254 assert_eq!(
2255 buffer.text(),
2256 "def a():\n \n if a:\n b()\n else:\n foo(\n )\n"
2257 );
2258
2259 // preserve the newly reduced indentation on the next newline
2260 append(&mut buffer, "\n", cx);
2261 assert_eq!(
2262 buffer.text(),
2263 "def a():\n \n if a:\n b()\n else:\n foo(\n )\n\n"
2264 );
2265
2266 // reset to a for loop statement
2267 let statement = "for i in range(10):\n print(i)\n";
2268 buffer.edit([(0..buffer.len(), statement)], None, cx);
2269
2270 // insert single line comment after each line
2271 let eol_ixs = statement
2272 .char_indices()
2273 .filter_map(|(ix, c)| if c == '\n' { Some(ix) } else { None })
2274 .collect::<Vec<usize>>();
2275 let editions = eol_ixs
2276 .iter()
2277 .enumerate()
2278 .map(|(i, &eol_ix)| (eol_ix..eol_ix, format!(" # comment {}", i + 1)))
2279 .collect::<Vec<(std::ops::Range<usize>, String)>>();
2280 buffer.edit(editions, Some(AutoindentMode::EachLine), cx);
2281 assert_eq!(
2282 buffer.text(),
2283 "for i in range(10): # comment 1\n print(i) # comment 2\n"
2284 );
2285
2286 // reset to a simple if statement
2287 buffer.edit([(0..buffer.len(), "if a:\n b(\n )")], None, cx);
2288
2289 // dedent "else" on the line after a closing paren
2290 append(&mut buffer, "\n else:\n", cx);
2291 assert_eq!(buffer.text(), "if a:\n b(\n )\nelse:\n ");
2292
2293 buffer
2294 });
2295 }
2296}