1use anyhow::{anyhow, bail, Context, Result};
2use async_trait::async_trait;
3use collections::HashMap;
4use futures::StreamExt;
5use language::{LanguageServerName, LspAdapter, LspAdapterDelegate};
6use lsp::{CodeActionKind, LanguageServerBinary};
7use schemars::JsonSchema;
8use serde_derive::{Deserialize, Serialize};
9use serde_json::json;
10use settings::Settings;
11use smol::{fs, fs::File};
12use std::{any::Any, env::consts, ffi::OsString, path::PathBuf, sync::Arc};
13use util::{
14 async_maybe,
15 fs::remove_matching,
16 github::{latest_github_release, GitHubLspBinaryVersion},
17 ResultExt,
18};
19
20#[derive(Clone, Serialize, Deserialize, JsonSchema)]
21pub struct DenoSettings {
22 pub enable: bool,
23}
24
25#[derive(Clone, Serialize, Default, Deserialize, JsonSchema)]
26pub struct DenoSettingsContent {
27 enable: Option<bool>,
28}
29
30impl Settings for DenoSettings {
31 const KEY: Option<&'static str> = Some("deno");
32
33 type FileContent = DenoSettingsContent;
34
35 fn load(
36 default_value: &Self::FileContent,
37 user_values: &[&Self::FileContent],
38 _: &mut gpui::AppContext,
39 ) -> Result<Self>
40 where
41 Self: Sized,
42 {
43 Self::load_via_json_merge(default_value, user_values)
44 }
45}
46
47fn deno_server_binary_arguments() -> Vec<OsString> {
48 vec!["lsp".into()]
49}
50
51pub struct DenoLspAdapter {}
52
53impl DenoLspAdapter {
54 pub fn new() -> Self {
55 DenoLspAdapter {}
56 }
57}
58
59#[async_trait(?Send)]
60impl LspAdapter for DenoLspAdapter {
61 fn name(&self) -> LanguageServerName {
62 LanguageServerName("deno-language-server".into())
63 }
64
65 async fn fetch_latest_server_version(
66 &self,
67 delegate: &dyn LspAdapterDelegate,
68 ) -> Result<Box<dyn 'static + Send + Any>> {
69 let release =
70 latest_github_release("denoland/deno", true, false, delegate.http_client()).await?;
71 let os = match consts::OS {
72 "macos" => "apple-darwin",
73 "linux" => "unknown-linux-gnu",
74 "windows" => "pc-windows-msvc",
75 other => bail!("Running on unsupported os: {other}"),
76 };
77 let asset_name = format!("deno-{}-{os}.zip", consts::ARCH);
78 let asset = release
79 .assets
80 .iter()
81 .find(|asset| asset.name == asset_name)
82 .ok_or_else(|| anyhow!("no asset found matching {:?}", asset_name))?;
83 let version = GitHubLspBinaryVersion {
84 name: release.tag_name,
85 url: asset.browser_download_url.clone(),
86 };
87 Ok(Box::new(version) as Box<_>)
88 }
89
90 async fn fetch_server_binary(
91 &self,
92 version: Box<dyn 'static + Send + Any>,
93 container_dir: PathBuf,
94 delegate: &dyn LspAdapterDelegate,
95 ) -> Result<LanguageServerBinary> {
96 let version = version.downcast::<GitHubLspBinaryVersion>().unwrap();
97 let zip_path = container_dir.join(format!("deno_{}.zip", version.name));
98 let version_dir = container_dir.join(format!("deno_{}", version.name));
99 let binary_path = version_dir.join("deno");
100
101 if fs::metadata(&binary_path).await.is_err() {
102 let mut response = delegate
103 .http_client()
104 .get(&version.url, Default::default(), true)
105 .await
106 .context("error downloading release")?;
107 let mut file = File::create(&zip_path).await?;
108 if !response.status().is_success() {
109 Err(anyhow!(
110 "download failed with status {}",
111 response.status().to_string()
112 ))?;
113 }
114 futures::io::copy(response.body_mut(), &mut file).await?;
115
116 let unzip_status = smol::process::Command::new("unzip")
117 .current_dir(&container_dir)
118 .arg(&zip_path)
119 .arg("-d")
120 .arg(&version_dir)
121 .output()
122 .await?
123 .status;
124 if !unzip_status.success() {
125 Err(anyhow!("failed to unzip deno archive"))?;
126 }
127
128 remove_matching(&container_dir, |entry| entry != version_dir).await;
129 }
130
131 Ok(LanguageServerBinary {
132 path: binary_path,
133 env: None,
134 arguments: deno_server_binary_arguments(),
135 })
136 }
137
138 async fn cached_server_binary(
139 &self,
140 container_dir: PathBuf,
141 _: &dyn LspAdapterDelegate,
142 ) -> Option<LanguageServerBinary> {
143 get_cached_server_binary(container_dir).await
144 }
145
146 async fn installation_test_binary(
147 &self,
148 container_dir: PathBuf,
149 ) -> Option<LanguageServerBinary> {
150 get_cached_server_binary(container_dir).await
151 }
152
153 fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
154 Some(vec![
155 CodeActionKind::QUICKFIX,
156 CodeActionKind::REFACTOR,
157 CodeActionKind::REFACTOR_EXTRACT,
158 CodeActionKind::SOURCE,
159 ])
160 }
161
162 async fn label_for_completion(
163 &self,
164 item: &lsp::CompletionItem,
165 language: &Arc<language::Language>,
166 ) -> Option<language::CodeLabel> {
167 use lsp::CompletionItemKind as Kind;
168 let len = item.label.len();
169 let grammar = language.grammar()?;
170 let highlight_id = match item.kind? {
171 Kind::CLASS | Kind::INTERFACE => grammar.highlight_id_for_name("type"),
172 Kind::CONSTRUCTOR => grammar.highlight_id_for_name("type"),
173 Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
174 Kind::FUNCTION | Kind::METHOD => grammar.highlight_id_for_name("function"),
175 Kind::PROPERTY | Kind::FIELD => grammar.highlight_id_for_name("property"),
176 _ => None,
177 }?;
178
179 let text = match &item.detail {
180 Some(detail) => format!("{} {}", item.label, detail),
181 None => item.label.clone(),
182 };
183
184 Some(language::CodeLabel {
185 text,
186 runs: vec![(0..len, highlight_id)],
187 filter_range: 0..len,
188 })
189 }
190
191 fn initialization_options(&self) -> Option<serde_json::Value> {
192 Some(json!({
193 "provideFormatter": true,
194 }))
195 }
196
197 fn language_ids(&self) -> HashMap<String, String> {
198 HashMap::from_iter([
199 ("TypeScript".into(), "typescript".into()),
200 ("JavaScript".into(), "javascript".into()),
201 ("TSX".into(), "typescriptreact".into()),
202 ])
203 }
204}
205
206async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServerBinary> {
207 async_maybe!({
208 let mut last = None;
209 let mut entries = fs::read_dir(&container_dir).await?;
210 while let Some(entry) = entries.next().await {
211 last = Some(entry?.path());
212 }
213
214 match last {
215 Some(path) if path.is_dir() => {
216 let binary = path.join("deno");
217 if fs::metadata(&binary).await.is_ok() {
218 return Ok(LanguageServerBinary {
219 path: binary,
220 env: None,
221 arguments: deno_server_binary_arguments(),
222 });
223 }
224 }
225 _ => {}
226 }
227
228 Err(anyhow!("no cached binary"))
229 })
230 .await
231 .log_err()
232}