1use ::fs::Fs;
2use anyhow::{Context as _, Ok, Result, anyhow};
3use async_compression::futures::bufread::GzipDecoder;
4use async_tar::Archive;
5use async_trait::async_trait;
6use futures::io::BufReader;
7use gpui::{AsyncApp, SharedString};
8pub use http_client::{HttpClient, github::latest_github_release};
9use language::LanguageToolchainStore;
10use node_runtime::NodeRuntime;
11use serde::{Deserialize, Serialize};
12use serde_json::Value;
13use settings::WorktreeId;
14use smol::{self, fs::File, lock::Mutex};
15use std::{
16 borrow::Borrow,
17 collections::{HashMap, HashSet},
18 ffi::{OsStr, OsString},
19 fmt::Debug,
20 net::Ipv4Addr,
21 ops::Deref,
22 path::PathBuf,
23 sync::Arc,
24};
25use task::{DebugAdapterConfig, DebugTaskDefinition};
26use util::ResultExt;
27
28#[derive(Clone, Debug, PartialEq, Eq)]
29pub enum DapStatus {
30 None,
31 CheckingForUpdate,
32 Downloading,
33 Failed { error: String },
34}
35
36#[async_trait(?Send)]
37pub trait DapDelegate {
38 fn worktree_id(&self) -> WorktreeId;
39 fn http_client(&self) -> Arc<dyn HttpClient>;
40 fn node_runtime(&self) -> NodeRuntime;
41 fn toolchain_store(&self) -> Arc<dyn LanguageToolchainStore>;
42 fn fs(&self) -> Arc<dyn Fs>;
43 fn updated_adapters(&self) -> Arc<Mutex<HashSet<DebugAdapterName>>>;
44 fn update_status(&self, dap_name: DebugAdapterName, status: DapStatus);
45 fn which(&self, command: &OsStr) -> Option<PathBuf>;
46 async fn shell_env(&self) -> collections::HashMap<String, String>;
47}
48
49#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
50pub struct DebugAdapterName(pub SharedString);
51
52impl Deref for DebugAdapterName {
53 type Target = str;
54
55 fn deref(&self) -> &Self::Target {
56 &self.0
57 }
58}
59
60impl AsRef<str> for DebugAdapterName {
61 fn as_ref(&self) -> &str {
62 &self.0
63 }
64}
65
66impl Borrow<str> for DebugAdapterName {
67 fn borrow(&self) -> &str {
68 &self.0
69 }
70}
71
72impl std::fmt::Display for DebugAdapterName {
73 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74 std::fmt::Display::fmt(&self.0, f)
75 }
76}
77
78impl From<DebugAdapterName> for SharedString {
79 fn from(name: DebugAdapterName) -> Self {
80 name.0
81 }
82}
83
84impl<'a> From<&'a str> for DebugAdapterName {
85 fn from(str: &'a str) -> DebugAdapterName {
86 DebugAdapterName(str.to_string().into())
87 }
88}
89
90#[derive(Debug, Clone)]
91pub struct TcpArguments {
92 pub host: Ipv4Addr,
93 pub port: u16,
94 pub timeout: Option<u64>,
95}
96#[derive(Default, Debug, Clone)]
97pub struct DebugAdapterBinary {
98 pub command: String,
99 pub arguments: Option<Vec<OsString>>,
100 pub envs: Option<HashMap<String, String>>,
101 pub cwd: Option<PathBuf>,
102 pub connection: Option<TcpArguments>,
103}
104
105#[derive(Debug)]
106pub struct AdapterVersion {
107 pub tag_name: String,
108 pub url: String,
109}
110
111pub enum DownloadedFileType {
112 Vsix,
113 GzipTar,
114 Zip,
115}
116
117pub struct GithubRepo {
118 pub repo_name: String,
119 pub repo_owner: String,
120}
121
122pub async fn download_adapter_from_github(
123 adapter_name: DebugAdapterName,
124 github_version: AdapterVersion,
125 file_type: DownloadedFileType,
126 delegate: &dyn DapDelegate,
127) -> Result<PathBuf> {
128 let adapter_path = paths::debug_adapters_dir().join(&adapter_name.as_ref());
129 let version_path = adapter_path.join(format!("{}_{}", adapter_name, github_version.tag_name));
130 let fs = delegate.fs();
131
132 if version_path.exists() {
133 return Ok(version_path);
134 }
135
136 if !adapter_path.exists() {
137 fs.create_dir(&adapter_path.as_path())
138 .await
139 .context("Failed creating adapter path")?;
140 }
141
142 log::debug!(
143 "Downloading adapter {} from {}",
144 adapter_name,
145 &github_version.url,
146 );
147
148 let mut response = delegate
149 .http_client()
150 .get(&github_version.url, Default::default(), true)
151 .await
152 .context("Error downloading release")?;
153 if !response.status().is_success() {
154 Err(anyhow!(
155 "download failed with status {}",
156 response.status().to_string()
157 ))?;
158 }
159
160 match file_type {
161 DownloadedFileType::GzipTar => {
162 let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
163 let archive = Archive::new(decompressed_bytes);
164 archive.unpack(&version_path).await?;
165 }
166 DownloadedFileType::Zip | DownloadedFileType::Vsix => {
167 let zip_path = version_path.with_extension("zip");
168
169 let mut file = File::create(&zip_path).await?;
170 futures::io::copy(response.body_mut(), &mut file).await?;
171
172 // we cannot check the status as some adapter include files with names that trigger `Illegal byte sequence`
173 util::command::new_smol_command("unzip")
174 .arg(&zip_path)
175 .arg("-d")
176 .arg(&version_path)
177 .output()
178 .await?;
179
180 util::fs::remove_matching(&adapter_path, |entry| {
181 entry
182 .file_name()
183 .is_some_and(|file| file.to_string_lossy().ends_with(".zip"))
184 })
185 .await;
186 }
187 }
188
189 // remove older versions
190 util::fs::remove_matching(&adapter_path, |entry| {
191 entry.to_string_lossy() != version_path.to_string_lossy()
192 })
193 .await;
194
195 Ok(version_path)
196}
197
198pub async fn fetch_latest_adapter_version_from_github(
199 github_repo: GithubRepo,
200 delegate: &dyn DapDelegate,
201) -> Result<AdapterVersion> {
202 let release = latest_github_release(
203 &format!("{}/{}", github_repo.repo_owner, github_repo.repo_name),
204 false,
205 false,
206 delegate.http_client(),
207 )
208 .await?;
209
210 Ok(AdapterVersion {
211 tag_name: release.tag_name,
212 url: release.zipball_url,
213 })
214}
215
216#[async_trait(?Send)]
217pub trait DebugAdapter: 'static + Send + Sync {
218 fn name(&self) -> DebugAdapterName;
219
220 async fn get_binary(
221 &self,
222 delegate: &dyn DapDelegate,
223 config: &DebugAdapterConfig,
224 user_installed_path: Option<PathBuf>,
225 cx: &mut AsyncApp,
226 ) -> Result<DebugAdapterBinary> {
227 if delegate
228 .updated_adapters()
229 .lock()
230 .await
231 .contains(&self.name())
232 {
233 log::info!("Using cached debug adapter binary {}", self.name());
234
235 if let Some(binary) = self
236 .get_installed_binary(delegate, &config, user_installed_path.clone(), cx)
237 .await
238 .log_err()
239 {
240 return Ok(binary);
241 }
242
243 log::info!(
244 "Cached binary {} is corrupt falling back to install",
245 self.name()
246 );
247 }
248
249 log::info!("Getting latest version of debug adapter {}", self.name());
250 delegate.update_status(self.name(), DapStatus::CheckingForUpdate);
251 if let Some(version) = self.fetch_latest_adapter_version(delegate).await.log_err() {
252 log::info!(
253 "Installiing latest version of debug adapter {}",
254 self.name()
255 );
256 delegate.update_status(self.name(), DapStatus::Downloading);
257 self.install_binary(version, delegate).await?;
258
259 delegate
260 .updated_adapters()
261 .lock_arc()
262 .await
263 .insert(self.name());
264 }
265
266 self.get_installed_binary(delegate, &config, user_installed_path, cx)
267 .await
268 }
269
270 async fn fetch_latest_adapter_version(
271 &self,
272 delegate: &dyn DapDelegate,
273 ) -> Result<AdapterVersion>;
274
275 /// Installs the binary for the debug adapter.
276 /// This method is called when the adapter binary is not found or needs to be updated.
277 /// It should download and install the necessary files for the debug adapter to function.
278 async fn install_binary(
279 &self,
280 version: AdapterVersion,
281 delegate: &dyn DapDelegate,
282 ) -> Result<()>;
283
284 async fn get_installed_binary(
285 &self,
286 delegate: &dyn DapDelegate,
287 config: &DebugAdapterConfig,
288 user_installed_path: Option<PathBuf>,
289 cx: &mut AsyncApp,
290 ) -> Result<DebugAdapterBinary>;
291
292 /// Should return base configuration to make the debug adapter work
293 fn request_args(&self, config: &DebugTaskDefinition) -> Value;
294}
295#[cfg(any(test, feature = "test-support"))]
296pub struct FakeAdapter {}
297
298#[cfg(any(test, feature = "test-support"))]
299impl FakeAdapter {
300 pub const ADAPTER_NAME: &'static str = "fake-adapter";
301
302 pub fn new() -> Self {
303 Self {}
304 }
305}
306
307#[cfg(any(test, feature = "test-support"))]
308#[async_trait(?Send)]
309impl DebugAdapter for FakeAdapter {
310 fn name(&self) -> DebugAdapterName {
311 DebugAdapterName(Self::ADAPTER_NAME.into())
312 }
313
314 async fn get_binary(
315 &self,
316 _: &dyn DapDelegate,
317 _: &DebugAdapterConfig,
318 _: Option<PathBuf>,
319 _: &mut AsyncApp,
320 ) -> Result<DebugAdapterBinary> {
321 Ok(DebugAdapterBinary {
322 command: "command".into(),
323 arguments: None,
324 connection: None,
325 envs: None,
326 cwd: None,
327 })
328 }
329
330 async fn fetch_latest_adapter_version(
331 &self,
332 _delegate: &dyn DapDelegate,
333 ) -> Result<AdapterVersion> {
334 unimplemented!("fetch latest adapter version");
335 }
336
337 async fn install_binary(
338 &self,
339 _version: AdapterVersion,
340 _delegate: &dyn DapDelegate,
341 ) -> Result<()> {
342 unimplemented!("install binary");
343 }
344
345 async fn get_installed_binary(
346 &self,
347 _: &dyn DapDelegate,
348 _: &DebugAdapterConfig,
349 _: Option<PathBuf>,
350 _: &mut AsyncApp,
351 ) -> Result<DebugAdapterBinary> {
352 unimplemented!("get installed binary");
353 }
354
355 fn request_args(&self, config: &DebugTaskDefinition) -> Value {
356 use serde_json::json;
357 use task::DebugRequestType;
358
359 json!({
360 "request": match config.request {
361 DebugRequestType::Launch(_) => "launch",
362 DebugRequestType::Attach(_) => "attach",
363 },
364 "process_id": if let DebugRequestType::Attach(attach_config) = &config.request {
365 attach_config.process_id
366 } else {
367 None
368 },
369 })
370 }
371}