1use std::fs;
2use zed_extension_api::{self as zed, LanguageServerId, Result};
3
4struct ClojureExtension {
5 cached_binary_path: Option<String>,
6}
7
8impl ClojureExtension {
9 fn language_server_binary_path(
10 &mut self,
11 language_server_id: &LanguageServerId,
12 worktree: &zed::Worktree,
13 ) -> Result<String> {
14 if let Some(path) = worktree.which("clojure-lsp") {
15 return Ok(path);
16 }
17
18 if let Some(path) = &self.cached_binary_path {
19 if fs::metadata(path).map_or(false, |stat| stat.is_file()) {
20 return Ok(path.clone());
21 }
22 }
23
24 zed::set_language_server_installation_status(
25 language_server_id,
26 &zed::LanguageServerInstallationStatus::CheckingForUpdate,
27 );
28 let release = zed::latest_github_release(
29 "clojure-lsp/clojure-lsp",
30 zed::GithubReleaseOptions {
31 require_assets: true,
32 pre_release: false,
33 },
34 )?;
35
36 let (platform, arch) = zed::current_platform();
37 let asset_name = format!(
38 "clojure-lsp-native-{os}-{arch}.zip",
39 os = match platform {
40 zed::Os::Mac => "macos",
41 zed::Os::Linux => "linux",
42 zed::Os::Windows => "windows",
43 },
44 arch = match arch {
45 zed::Architecture::Aarch64 => "aarch64",
46 zed::Architecture::X8664 => "amd64",
47 zed::Architecture::X86 =>
48 return Err(format!("unsupported architecture: {arch:?}")),
49 },
50 );
51
52 let asset = release
53 .assets
54 .iter()
55 .find(|asset| asset.name == asset_name)
56 .ok_or_else(|| format!("no asset found matching {:?}", asset_name))?;
57
58 let version_dir = format!("clojure-lsp-{}", release.version);
59 let binary_path = format!("{version_dir}/clojure-lsp");
60
61 if !fs::metadata(&binary_path).map_or(false, |stat| stat.is_file()) {
62 zed::set_language_server_installation_status(
63 language_server_id,
64 &zed::LanguageServerInstallationStatus::Downloading,
65 );
66
67 zed::download_file(
68 &asset.download_url,
69 &version_dir,
70 zed::DownloadedFileType::Zip,
71 )
72 .map_err(|e| format!("failed to download file: {e}"))?;
73
74 let entries =
75 fs::read_dir(".").map_err(|e| format!("failed to list working directory {e}"))?;
76 for entry in entries {
77 let entry = entry.map_err(|e| format!("failed to load directory entry {e}"))?;
78 if entry.file_name().to_str() != Some(&version_dir) {
79 fs::remove_dir_all(entry.path()).ok();
80 }
81 }
82 }
83
84 self.cached_binary_path = Some(binary_path.clone());
85 Ok(binary_path)
86 }
87}
88
89impl zed::Extension for ClojureExtension {
90 fn new() -> Self {
91 Self {
92 cached_binary_path: None,
93 }
94 }
95
96 fn language_server_command(
97 &mut self,
98 language_server_id: &LanguageServerId,
99 worktree: &zed::Worktree,
100 ) -> Result<zed::Command> {
101 Ok(zed::Command {
102 command: self.language_server_binary_path(language_server_id, worktree)?,
103 args: Vec::new(),
104 env: Default::default(),
105 })
106 }
107}
108
109zed::register_extension!(ClojureExtension);