1use ::fs::Fs;
2use anyhow::{Context as _, Result};
3use async_compression::futures::bufread::GzipDecoder;
4use async_tar::Archive;
5use async_trait::async_trait;
6use collections::HashMap;
7pub use dap_types::{StartDebuggingRequestArguments, StartDebuggingRequestArgumentsRequest};
8use futures::io::BufReader;
9use gpui::{AsyncApp, SharedString};
10pub use http_client::{HttpClient, github::latest_github_release};
11use language::{LanguageName, LanguageToolchainStore};
12use node_runtime::NodeRuntime;
13use serde::{Deserialize, Serialize};
14use settings::WorktreeId;
15use smol::{self, fs::File};
16use std::{
17 borrow::Borrow,
18 ffi::OsStr,
19 fmt::Debug,
20 net::Ipv4Addr,
21 ops::Deref,
22 path::{Path, PathBuf},
23 sync::Arc,
24};
25use task::{AttachRequest, DebugRequest, DebugScenario, LaunchRequest, TcpArgumentsTemplate};
26
27#[derive(Clone, Debug, PartialEq, Eq)]
28pub enum DapStatus {
29 None,
30 CheckingForUpdate,
31 Downloading,
32 Failed { error: String },
33}
34
35#[async_trait]
36pub trait DapDelegate: Send + Sync + 'static {
37 fn worktree_id(&self) -> WorktreeId;
38 fn worktree_root_path(&self) -> &Path;
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 output_to_console(&self, msg: String);
44 async fn which(&self, command: &OsStr) -> Option<PathBuf>;
45 async fn read_text_file(&self, path: PathBuf) -> Result<String>;
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}
83impl From<SharedString> for DebugAdapterName {
84 fn from(name: SharedString) -> Self {
85 DebugAdapterName(name)
86 }
87}
88
89impl<'a> From<&'a str> for DebugAdapterName {
90 fn from(str: &'a str) -> DebugAdapterName {
91 DebugAdapterName(str.to_string().into())
92 }
93}
94
95#[derive(Debug, Clone, PartialEq)]
96pub struct TcpArguments {
97 pub host: Ipv4Addr,
98 pub port: u16,
99 pub timeout: Option<u64>,
100}
101
102impl TcpArguments {
103 pub fn from_proto(proto: proto::TcpHost) -> anyhow::Result<Self> {
104 let host = TcpArgumentsTemplate::from_proto(proto)?;
105 Ok(TcpArguments {
106 host: host.host.context("missing host")?,
107 port: host.port.context("missing port")?,
108 timeout: host.timeout,
109 })
110 }
111
112 pub fn to_proto(&self) -> proto::TcpHost {
113 TcpArgumentsTemplate {
114 host: Some(self.host),
115 port: Some(self.port),
116 timeout: self.timeout,
117 }
118 .to_proto()
119 }
120}
121
122/// Represents a debuggable binary/process (what process is going to be debugged and with what arguments).
123///
124/// We start off with a [DebugScenario], a user-facing type that additionally defines how a debug target is built; once
125/// an optional build step is completed, we turn it's result into a DebugTaskDefinition by running a locator (or using a user-provided task) and resolving task variables.
126/// Finally, a [DebugTaskDefinition] has to be turned into a concrete debugger invocation ([DebugAdapterBinary]).
127#[derive(Clone, Debug, PartialEq)]
128#[cfg_attr(
129 any(feature = "test-support", test),
130 derive(serde::Deserialize, serde::Serialize)
131)]
132pub struct DebugTaskDefinition {
133 pub label: SharedString,
134 pub adapter: DebugAdapterName,
135 pub request: DebugRequest,
136 /// Additional initialization arguments to be sent on DAP initialization
137 pub initialize_args: Option<serde_json::Value>,
138 /// Whether to tell the debug adapter to stop on entry
139 pub stop_on_entry: Option<bool>,
140 /// Optional TCP connection information
141 ///
142 /// If provided, this will be used to connect to the debug adapter instead of
143 /// spawning a new debug adapter process. This is useful for connecting to a debug adapter
144 /// that is already running or is started by another process.
145 pub tcp_connection: Option<TcpArgumentsTemplate>,
146}
147
148impl DebugTaskDefinition {
149 pub fn cwd(&self) -> Option<&Path> {
150 if let DebugRequest::Launch(config) = &self.request {
151 config.cwd.as_ref().map(Path::new)
152 } else {
153 None
154 }
155 }
156
157 pub fn to_scenario(&self) -> DebugScenario {
158 DebugScenario {
159 label: self.label.clone(),
160 adapter: self.adapter.clone().into(),
161 build: None,
162 request: Some(self.request.clone()),
163 stop_on_entry: self.stop_on_entry,
164 tcp_connection: self.tcp_connection.clone(),
165 initialize_args: self.initialize_args.clone(),
166 }
167 }
168
169 pub fn to_proto(&self) -> proto::DebugTaskDefinition {
170 proto::DebugTaskDefinition {
171 adapter: self.adapter.to_string(),
172 request: Some(match &self.request {
173 DebugRequest::Launch(config) => {
174 proto::debug_task_definition::Request::DebugLaunchRequest(
175 proto::DebugLaunchRequest {
176 program: config.program.clone(),
177 cwd: config.cwd.as_ref().map(|c| c.to_string_lossy().to_string()),
178 args: config.args.clone(),
179 env: config
180 .env
181 .iter()
182 .map(|(k, v)| (k.clone(), v.clone()))
183 .collect(),
184 },
185 )
186 }
187 DebugRequest::Attach(attach_request) => {
188 proto::debug_task_definition::Request::DebugAttachRequest(
189 proto::DebugAttachRequest {
190 process_id: attach_request.process_id.unwrap_or_default(),
191 },
192 )
193 }
194 }),
195 label: self.label.to_string(),
196 initialize_args: self.initialize_args.as_ref().map(|v| v.to_string()),
197 tcp_connection: self.tcp_connection.as_ref().map(|t| t.to_proto()),
198 stop_on_entry: self.stop_on_entry,
199 }
200 }
201
202 pub fn from_proto(proto: proto::DebugTaskDefinition) -> Result<Self> {
203 let request = proto.request.context("request is required")?;
204 Ok(Self {
205 label: proto.label.into(),
206 initialize_args: proto.initialize_args.map(|v| v.into()),
207 tcp_connection: proto
208 .tcp_connection
209 .map(TcpArgumentsTemplate::from_proto)
210 .transpose()?,
211 stop_on_entry: proto.stop_on_entry,
212 adapter: DebugAdapterName(proto.adapter.into()),
213 request: match request {
214 proto::debug_task_definition::Request::DebugAttachRequest(config) => {
215 DebugRequest::Attach(AttachRequest {
216 process_id: Some(config.process_id),
217 })
218 }
219
220 proto::debug_task_definition::Request::DebugLaunchRequest(config) => {
221 DebugRequest::Launch(LaunchRequest {
222 program: config.program,
223 cwd: config.cwd.map(|cwd| cwd.into()),
224 args: config.args,
225 env: Default::default(),
226 })
227 }
228 },
229 })
230 }
231}
232
233/// Created from a [DebugTaskDefinition], this struct describes how to spawn the debugger to create a previously-configured debug session.
234#[derive(Debug, Clone, PartialEq)]
235pub struct DebugAdapterBinary {
236 pub command: String,
237 pub arguments: Vec<String>,
238 pub envs: HashMap<String, String>,
239 pub cwd: Option<PathBuf>,
240 pub connection: Option<TcpArguments>,
241 pub request_args: StartDebuggingRequestArguments,
242}
243
244impl DebugAdapterBinary {
245 pub fn from_proto(binary: proto::DebugAdapterBinary) -> anyhow::Result<Self> {
246 let request = match binary.launch_type() {
247 proto::debug_adapter_binary::LaunchType::Launch => {
248 StartDebuggingRequestArgumentsRequest::Launch
249 }
250 proto::debug_adapter_binary::LaunchType::Attach => {
251 StartDebuggingRequestArgumentsRequest::Attach
252 }
253 };
254
255 Ok(DebugAdapterBinary {
256 command: binary.command,
257 arguments: binary.arguments,
258 envs: binary.envs.into_iter().collect(),
259 connection: binary
260 .connection
261 .map(TcpArguments::from_proto)
262 .transpose()?,
263 request_args: StartDebuggingRequestArguments {
264 configuration: serde_json::from_str(&binary.configuration)?,
265 request,
266 },
267 cwd: binary.cwd.map(|cwd| cwd.into()),
268 })
269 }
270
271 pub fn to_proto(&self) -> proto::DebugAdapterBinary {
272 proto::DebugAdapterBinary {
273 command: self.command.clone(),
274 arguments: self.arguments.clone(),
275 envs: self
276 .envs
277 .iter()
278 .map(|(k, v)| (k.clone(), v.clone()))
279 .collect(),
280 cwd: self
281 .cwd
282 .as_ref()
283 .map(|cwd| cwd.to_string_lossy().to_string()),
284 connection: self.connection.as_ref().map(|c| c.to_proto()),
285 launch_type: match self.request_args.request {
286 StartDebuggingRequestArgumentsRequest::Launch => {
287 proto::debug_adapter_binary::LaunchType::Launch.into()
288 }
289 StartDebuggingRequestArgumentsRequest::Attach => {
290 proto::debug_adapter_binary::LaunchType::Attach.into()
291 }
292 },
293 configuration: self.request_args.configuration.to_string(),
294 }
295 }
296}
297
298#[derive(Debug, Clone)]
299pub struct AdapterVersion {
300 pub tag_name: String,
301 pub url: String,
302}
303
304pub enum DownloadedFileType {
305 Vsix,
306 GzipTar,
307 Zip,
308}
309
310pub struct GithubRepo {
311 pub repo_name: String,
312 pub repo_owner: String,
313}
314
315pub async fn download_adapter_from_github(
316 adapter_name: DebugAdapterName,
317 github_version: AdapterVersion,
318 file_type: DownloadedFileType,
319 delegate: &dyn DapDelegate,
320) -> Result<PathBuf> {
321 let adapter_path = paths::debug_adapters_dir().join(&adapter_name.as_ref());
322 let version_path = adapter_path.join(format!("{}_{}", adapter_name, github_version.tag_name));
323 let fs = delegate.fs();
324
325 if version_path.exists() {
326 return Ok(version_path);
327 }
328
329 if !adapter_path.exists() {
330 fs.create_dir(&adapter_path.as_path())
331 .await
332 .context("Failed creating adapter path")?;
333 }
334
335 log::debug!(
336 "Downloading adapter {} from {}",
337 adapter_name,
338 &github_version.url,
339 );
340 delegate.output_to_console(format!("Downloading from {}...", github_version.url));
341
342 let mut response = delegate
343 .http_client()
344 .get(&github_version.url, Default::default(), true)
345 .await
346 .context("Error downloading release")?;
347 anyhow::ensure!(
348 response.status().is_success(),
349 "download failed with status {}",
350 response.status().to_string()
351 );
352
353 match file_type {
354 DownloadedFileType::GzipTar => {
355 let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
356 let archive = Archive::new(decompressed_bytes);
357 archive.unpack(&version_path).await?;
358 }
359 DownloadedFileType::Zip | DownloadedFileType::Vsix => {
360 let zip_path = version_path.with_extension("zip");
361
362 let mut file = File::create(&zip_path).await?;
363 futures::io::copy(response.body_mut(), &mut file).await?;
364
365 // we cannot check the status as some adapter include files with names that trigger `Illegal byte sequence`
366 util::command::new_smol_command("unzip")
367 .arg(&zip_path)
368 .arg("-d")
369 .arg(&version_path)
370 .output()
371 .await?;
372
373 util::fs::remove_matching(&adapter_path, |entry| {
374 entry
375 .file_name()
376 .is_some_and(|file| file.to_string_lossy().ends_with(".zip"))
377 })
378 .await;
379 }
380 }
381
382 // remove older versions
383 util::fs::remove_matching(&adapter_path, |entry| {
384 entry.to_string_lossy() != version_path.to_string_lossy()
385 })
386 .await;
387
388 Ok(version_path)
389}
390
391pub async fn fetch_latest_adapter_version_from_github(
392 github_repo: GithubRepo,
393 delegate: &dyn DapDelegate,
394) -> Result<AdapterVersion> {
395 let release = latest_github_release(
396 &format!("{}/{}", github_repo.repo_owner, github_repo.repo_name),
397 false,
398 false,
399 delegate.http_client(),
400 )
401 .await?;
402
403 Ok(AdapterVersion {
404 tag_name: release.tag_name,
405 url: release.zipball_url,
406 })
407}
408
409#[async_trait(?Send)]
410pub trait DebugAdapter: 'static + Send + Sync {
411 fn name(&self) -> DebugAdapterName;
412
413 async fn get_binary(
414 &self,
415 delegate: &Arc<dyn DapDelegate>,
416 config: &DebugTaskDefinition,
417 user_installed_path: Option<PathBuf>,
418 cx: &mut AsyncApp,
419 ) -> Result<DebugAdapterBinary>;
420
421 /// Returns the language name of an adapter if it only supports one language
422 fn adapter_language_name(&self) -> Option<LanguageName> {
423 None
424 }
425}
426
427#[cfg(any(test, feature = "test-support"))]
428pub struct FakeAdapter {}
429
430#[cfg(any(test, feature = "test-support"))]
431impl FakeAdapter {
432 pub const ADAPTER_NAME: &'static str = "fake-adapter";
433
434 pub fn new() -> Self {
435 Self {}
436 }
437
438 fn request_args(&self, config: &DebugTaskDefinition) -> StartDebuggingRequestArguments {
439 use serde_json::json;
440 use task::DebugRequest;
441
442 let value = json!({
443 "request": match config.request {
444 DebugRequest::Launch(_) => "launch",
445 DebugRequest::Attach(_) => "attach",
446 },
447 "process_id": if let DebugRequest::Attach(attach_config) = &config.request {
448 attach_config.process_id
449 } else {
450 None
451 },
452 "raw_request": serde_json::to_value(config).unwrap()
453 });
454 let request = match config.request {
455 DebugRequest::Launch(_) => dap_types::StartDebuggingRequestArgumentsRequest::Launch,
456 DebugRequest::Attach(_) => dap_types::StartDebuggingRequestArgumentsRequest::Attach,
457 };
458 StartDebuggingRequestArguments {
459 configuration: value,
460 request,
461 }
462 }
463}
464
465#[cfg(any(test, feature = "test-support"))]
466#[async_trait(?Send)]
467impl DebugAdapter for FakeAdapter {
468 fn name(&self) -> DebugAdapterName {
469 DebugAdapterName(Self::ADAPTER_NAME.into())
470 }
471
472 async fn get_binary(
473 &self,
474 _: &Arc<dyn DapDelegate>,
475 config: &DebugTaskDefinition,
476 _: Option<PathBuf>,
477 _: &mut AsyncApp,
478 ) -> Result<DebugAdapterBinary> {
479 Ok(DebugAdapterBinary {
480 command: "command".into(),
481 arguments: vec![],
482 connection: None,
483 envs: HashMap::default(),
484 cwd: None,
485 request_args: self.request_args(config),
486 })
487 }
488}