1use anyhow::Result;
2use collections::FxHashMap;
3use gpui::SharedString;
4use schemars::{JsonSchema, r#gen::SchemaSettings};
5use serde::{Deserialize, Serialize};
6use std::path::PathBuf;
7use std::{net::Ipv4Addr, path::Path};
8
9/// Represents the host information of the debug adapter
10#[derive(Default, Deserialize, Serialize, PartialEq, Eq, JsonSchema, Clone, Debug)]
11pub struct TcpArgumentsTemplate {
12 /// The port that the debug adapter is listening on
13 ///
14 /// Default: We will try to find an open port
15 pub port: Option<u16>,
16 /// The host that the debug adapter is listening too
17 ///
18 /// Default: 127.0.0.1
19 pub host: Option<Ipv4Addr>,
20 /// The max amount of time in milliseconds to connect to a tcp DAP before returning an error
21 ///
22 /// Default: 2000ms
23 pub timeout: Option<u64>,
24}
25
26impl TcpArgumentsTemplate {
27 /// Get the host or fallback to the default host
28 pub fn host(&self) -> Ipv4Addr {
29 self.host.unwrap_or_else(|| Ipv4Addr::new(127, 0, 0, 1))
30 }
31
32 pub fn from_proto(proto: proto::TcpHost) -> Result<Self> {
33 Ok(Self {
34 port: proto.port.map(|p| p.try_into()).transpose()?,
35 host: proto.host.map(|h| h.parse()).transpose()?,
36 timeout: proto.timeout,
37 })
38 }
39
40 pub fn to_proto(&self) -> proto::TcpHost {
41 proto::TcpHost {
42 port: self.port.map(|p| p.into()),
43 host: self.host.map(|h| h.to_string()),
44 timeout: self.timeout,
45 }
46 }
47}
48
49/// Represents the attach request information of the debug adapter
50#[derive(Default, Deserialize, Serialize, PartialEq, Eq, JsonSchema, Clone, Debug)]
51pub struct AttachRequest {
52 /// The processId to attach to, if left empty we will show a process picker
53 pub process_id: Option<u32>,
54}
55
56/// Represents the launch request information of the debug adapter
57#[derive(Deserialize, Serialize, Default, PartialEq, Eq, JsonSchema, Clone, Debug)]
58pub struct LaunchRequest {
59 /// The program that you trying to debug
60 pub program: String,
61 /// The current working directory of your project
62 pub cwd: Option<PathBuf>,
63 /// Arguments to pass to a debuggee
64 #[serde(default)]
65 pub args: Vec<String>,
66 #[serde(default)]
67 pub env: FxHashMap<String, String>,
68}
69
70/// Represents the type that will determine which request to call on the debug adapter
71#[derive(Deserialize, Serialize, PartialEq, Eq, JsonSchema, Clone, Debug)]
72#[serde(rename_all = "lowercase", untagged)]
73pub enum DebugRequest {
74 /// Call the `launch` request on the debug adapter
75 Launch(LaunchRequest),
76 /// Call the `attach` request on the debug adapter
77 Attach(AttachRequest),
78}
79
80impl DebugRequest {
81 pub fn to_proto(&self) -> proto::DebugRequest {
82 match self {
83 DebugRequest::Launch(launch_request) => proto::DebugRequest {
84 request: Some(proto::debug_request::Request::DebugLaunchRequest(
85 proto::DebugLaunchRequest {
86 program: launch_request.program.clone(),
87 cwd: launch_request
88 .cwd
89 .as_ref()
90 .map(|cwd| cwd.to_string_lossy().into_owned()),
91 args: launch_request.args.clone(),
92 env: launch_request
93 .env
94 .iter()
95 .map(|(k, v)| (k.clone(), v.clone()))
96 .collect(),
97 },
98 )),
99 },
100 DebugRequest::Attach(attach_request) => proto::DebugRequest {
101 request: Some(proto::debug_request::Request::DebugAttachRequest(
102 proto::DebugAttachRequest {
103 process_id: attach_request
104 .process_id
105 .expect("The process ID to be already filled out."),
106 },
107 )),
108 },
109 }
110 }
111
112 pub fn from_proto(val: proto::DebugRequest) -> Result<DebugRequest> {
113 let request = val
114 .request
115 .ok_or_else(|| anyhow::anyhow!("Missing debug request"))?;
116 match request {
117 proto::debug_request::Request::DebugLaunchRequest(proto::DebugLaunchRequest {
118 program,
119 cwd,
120 args,
121 env,
122 }) => Ok(DebugRequest::Launch(LaunchRequest {
123 program,
124 cwd: cwd.map(From::from),
125 args,
126 env: env.into_iter().collect(),
127 })),
128
129 proto::debug_request::Request::DebugAttachRequest(proto::DebugAttachRequest {
130 process_id,
131 }) => Ok(DebugRequest::Attach(AttachRequest {
132 process_id: Some(process_id),
133 })),
134 }
135 }
136}
137
138impl From<LaunchRequest> for DebugRequest {
139 fn from(launch_config: LaunchRequest) -> Self {
140 DebugRequest::Launch(launch_config)
141 }
142}
143
144impl From<AttachRequest> for DebugRequest {
145 fn from(attach_config: AttachRequest) -> Self {
146 DebugRequest::Attach(attach_config)
147 }
148}
149
150/// This struct represent a user created debug task
151#[derive(Deserialize, Serialize, PartialEq, Eq, JsonSchema, Clone, Debug)]
152#[serde(rename_all = "snake_case")]
153pub struct DebugScenario {
154 pub adapter: SharedString,
155 /// Name of the debug task
156 pub label: SharedString,
157 /// A task to run prior to spawning the debuggee.
158 pub build: Option<SharedString>,
159 #[serde(flatten)]
160 pub request: Option<DebugRequest>,
161 /// Additional initialization arguments to be sent on DAP initialization
162 #[serde(default)]
163 pub initialize_args: Option<serde_json::Value>,
164 /// Optional TCP connection information
165 ///
166 /// If provided, this will be used to connect to the debug adapter instead of
167 /// spawning a new process. This is useful for connecting to a debug adapter
168 /// that is already running or is started by another process.
169 #[serde(default)]
170 pub tcp_connection: Option<TcpArgumentsTemplate>,
171 /// Whether to tell the debug adapter to stop on entry
172 #[serde(default)]
173 pub stop_on_entry: Option<bool>,
174}
175
176impl DebugScenario {
177 pub fn cwd(&self) -> Option<&Path> {
178 if let Some(DebugRequest::Launch(config)) = &self.request {
179 config.cwd.as_ref().map(Path::new)
180 } else {
181 None
182 }
183 }
184}
185
186/// A group of Debug Tasks defined in a JSON file.
187#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
188#[serde(transparent)]
189pub struct DebugTaskFile(pub Vec<DebugScenario>);
190
191impl DebugTaskFile {
192 /// Generates JSON schema of Tasks JSON template format.
193 pub fn generate_json_schema() -> serde_json_lenient::Value {
194 let schema = SchemaSettings::draft07()
195 .with(|settings| settings.option_add_null_type = false)
196 .into_generator()
197 .into_root_schema_for::<Self>();
198
199 serde_json_lenient::to_value(schema).unwrap()
200 }
201}
202
203#[cfg(test)]
204mod tests {
205 use crate::{DebugRequest, LaunchRequest};
206
207 #[test]
208 fn test_can_deserialize_non_attach_task() {
209 let deserialized: DebugRequest =
210 serde_json::from_str(r#"{"program": "cafebabe"}"#).unwrap();
211 assert_eq!(
212 deserialized,
213 DebugRequest::Launch(LaunchRequest {
214 program: "cafebabe".to_owned(),
215 ..Default::default()
216 })
217 );
218 }
219}