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]
60impl LspAdapter for DenoLspAdapter {
61 fn name(&self) -> LanguageServerName {
62 LanguageServerName("deno-language-server".into())
63 }
64
65 fn short_name(&self) -> &'static str {
66 "deno-ts"
67 }
68
69 async fn fetch_latest_server_version(
70 &self,
71 delegate: &dyn LspAdapterDelegate,
72 ) -> Result<Box<dyn 'static + Send + Any>> {
73 let release =
74 latest_github_release("denoland/deno", true, false, delegate.http_client()).await?;
75 let os = match consts::OS {
76 "macos" => "apple-darwin",
77 "linux" => "unknown-linux-gnu",
78 "windows" => "pc-windows-msvc",
79 other => bail!("Running on unsupported os: {other}"),
80 };
81 let asset_name = format!("deno-{}-{os}.zip", consts::ARCH);
82 let asset = release
83 .assets
84 .iter()
85 .find(|asset| asset.name == asset_name)
86 .ok_or_else(|| anyhow!("no asset found matching {:?}", asset_name))?;
87 let version = GitHubLspBinaryVersion {
88 name: release.tag_name,
89 url: asset.browser_download_url.clone(),
90 };
91 Ok(Box::new(version) as Box<_>)
92 }
93
94 async fn fetch_server_binary(
95 &self,
96 version: Box<dyn 'static + Send + Any>,
97 container_dir: PathBuf,
98 delegate: &dyn LspAdapterDelegate,
99 ) -> Result<LanguageServerBinary> {
100 let version = version.downcast::<GitHubLspBinaryVersion>().unwrap();
101 let zip_path = container_dir.join(format!("deno_{}.zip", version.name));
102 let version_dir = container_dir.join(format!("deno_{}", version.name));
103 let binary_path = version_dir.join("deno");
104
105 if fs::metadata(&binary_path).await.is_err() {
106 let mut response = delegate
107 .http_client()
108 .get(&version.url, Default::default(), true)
109 .await
110 .context("error downloading release")?;
111 let mut file = File::create(&zip_path).await?;
112 if !response.status().is_success() {
113 Err(anyhow!(
114 "download failed with status {}",
115 response.status().to_string()
116 ))?;
117 }
118 futures::io::copy(response.body_mut(), &mut file).await?;
119
120 let unzip_status = smol::process::Command::new("unzip")
121 .current_dir(&container_dir)
122 .arg(&zip_path)
123 .arg("-d")
124 .arg(&version_dir)
125 .output()
126 .await?
127 .status;
128 if !unzip_status.success() {
129 Err(anyhow!("failed to unzip deno archive"))?;
130 }
131
132 remove_matching(&container_dir, |entry| entry != version_dir).await;
133 }
134
135 Ok(LanguageServerBinary {
136 path: binary_path,
137 env: None,
138 arguments: deno_server_binary_arguments(),
139 })
140 }
141
142 async fn cached_server_binary(
143 &self,
144 container_dir: PathBuf,
145 _: &dyn LspAdapterDelegate,
146 ) -> Option<LanguageServerBinary> {
147 get_cached_server_binary(container_dir).await
148 }
149
150 async fn installation_test_binary(
151 &self,
152 container_dir: PathBuf,
153 ) -> Option<LanguageServerBinary> {
154 get_cached_server_binary(container_dir).await
155 }
156
157 fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
158 Some(vec![
159 CodeActionKind::QUICKFIX,
160 CodeActionKind::REFACTOR,
161 CodeActionKind::REFACTOR_EXTRACT,
162 CodeActionKind::SOURCE,
163 ])
164 }
165
166 async fn label_for_completion(
167 &self,
168 item: &lsp::CompletionItem,
169 language: &Arc<language::Language>,
170 ) -> Option<language::CodeLabel> {
171 use lsp::CompletionItemKind as Kind;
172 let len = item.label.len();
173 let grammar = language.grammar()?;
174 let highlight_id = match item.kind? {
175 Kind::CLASS | Kind::INTERFACE => grammar.highlight_id_for_name("type"),
176 Kind::CONSTRUCTOR => grammar.highlight_id_for_name("type"),
177 Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
178 Kind::FUNCTION | Kind::METHOD => grammar.highlight_id_for_name("function"),
179 Kind::PROPERTY | Kind::FIELD => grammar.highlight_id_for_name("property"),
180 _ => None,
181 }?;
182
183 let text = match &item.detail {
184 Some(detail) => format!("{} {}", item.label, detail),
185 None => item.label.clone(),
186 };
187
188 Some(language::CodeLabel {
189 text,
190 runs: vec![(0..len, highlight_id)],
191 filter_range: 0..len,
192 })
193 }
194
195 fn initialization_options(&self) -> Option<serde_json::Value> {
196 Some(json!({
197 "provideFormatter": true,
198 }))
199 }
200
201 fn language_ids(&self) -> HashMap<String, String> {
202 HashMap::from_iter([
203 ("TypeScript".into(), "typescript".into()),
204 ("JavaScript".into(), "javascript".into()),
205 ("TSX".into(), "typescriptreact".into()),
206 ])
207 }
208}
209
210async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServerBinary> {
211 async_maybe!({
212 let mut last = None;
213 let mut entries = fs::read_dir(&container_dir).await?;
214 while let Some(entry) = entries.next().await {
215 last = Some(entry?.path());
216 }
217
218 match last {
219 Some(path) if path.is_dir() => {
220 let binary = path.join("deno");
221 if fs::metadata(&binary).await.is_ok() {
222 return Ok(LanguageServerBinary {
223 path: binary,
224 env: None,
225 arguments: deno_server_binary_arguments(),
226 });
227 }
228 }
229 _ => {}
230 }
231
232 Err(anyhow!("no cached binary"))
233 })
234 .await
235 .log_err()
236}