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
9use crate::TaskTemplate;
10
11/// Represents the host information of the debug adapter
12#[derive(Default, Deserialize, Serialize, PartialEq, Eq, JsonSchema, Clone, Debug)]
13pub struct TcpArgumentsTemplate {
14 /// The port that the debug adapter is listening on
15 ///
16 /// Default: We will try to find an open port
17 pub port: Option<u16>,
18 /// The host that the debug adapter is listening too
19 ///
20 /// Default: 127.0.0.1
21 pub host: Option<Ipv4Addr>,
22 /// The max amount of time in milliseconds to connect to a tcp DAP before returning an error
23 ///
24 /// Default: 2000ms
25 pub timeout: Option<u64>,
26}
27
28impl TcpArgumentsTemplate {
29 /// Get the host or fallback to the default host
30 pub fn host(&self) -> Ipv4Addr {
31 self.host.unwrap_or_else(|| Ipv4Addr::new(127, 0, 0, 1))
32 }
33
34 pub fn from_proto(proto: proto::TcpHost) -> Result<Self> {
35 Ok(Self {
36 port: proto.port.map(|p| p.try_into()).transpose()?,
37 host: proto.host.map(|h| h.parse()).transpose()?,
38 timeout: proto.timeout,
39 })
40 }
41
42 pub fn to_proto(&self) -> proto::TcpHost {
43 proto::TcpHost {
44 port: self.port.map(|p| p.into()),
45 host: self.host.map(|h| h.to_string()),
46 timeout: self.timeout,
47 }
48 }
49}
50
51/// Represents the attach request information of the debug adapter
52#[derive(Default, Serialize, PartialEq, Eq, JsonSchema, Clone, Debug)]
53pub struct AttachRequest {
54 /// The processId to attach to, if left empty we will show a process picker
55 pub process_id: Option<u32>,
56}
57
58impl<'de> Deserialize<'de> for AttachRequest {
59 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
60 where
61 D: serde::Deserializer<'de>,
62 {
63 #[derive(Deserialize)]
64 struct Helper {
65 process_id: Option<u32>,
66 }
67
68 let helper = Helper::deserialize(deserializer)?;
69
70 // Skip creating an AttachRequest if process_id is None
71 if helper.process_id.is_none() {
72 return Err(serde::de::Error::custom("process_id is required"));
73 }
74
75 Ok(AttachRequest {
76 process_id: helper.process_id,
77 })
78 }
79}
80
81/// Represents the launch request information of the debug adapter
82#[derive(Deserialize, Serialize, Default, PartialEq, Eq, JsonSchema, Clone, Debug)]
83pub struct LaunchRequest {
84 /// The program that you trying to debug
85 pub program: String,
86 /// The current working directory of your project
87 #[serde(default)]
88 pub cwd: Option<PathBuf>,
89 /// Arguments to pass to a debuggee
90 #[serde(default)]
91 pub args: Vec<String>,
92 #[serde(default)]
93 pub env: FxHashMap<String, String>,
94}
95
96impl LaunchRequest {
97 pub fn env_json(&self) -> serde_json::Value {
98 serde_json::Value::Object(
99 self.env
100 .iter()
101 .map(|(k, v)| (k.clone(), v.to_owned().into()))
102 .collect::<serde_json::Map<String, serde_json::Value>>(),
103 )
104 }
105}
106
107/// Represents the type that will determine which request to call on the debug adapter
108#[derive(Deserialize, Serialize, PartialEq, Eq, JsonSchema, Clone, Debug)]
109#[serde(rename_all = "lowercase", untagged)]
110pub enum DebugRequest {
111 /// Call the `launch` request on the debug adapter
112 Launch(LaunchRequest),
113 /// Call the `attach` request on the debug adapter
114 Attach(AttachRequest),
115}
116
117impl DebugRequest {
118 pub fn to_proto(&self) -> proto::DebugRequest {
119 match self {
120 DebugRequest::Launch(launch_request) => proto::DebugRequest {
121 request: Some(proto::debug_request::Request::DebugLaunchRequest(
122 proto::DebugLaunchRequest {
123 program: launch_request.program.clone(),
124 cwd: launch_request
125 .cwd
126 .as_ref()
127 .map(|cwd| cwd.to_string_lossy().into_owned()),
128 args: launch_request.args.clone(),
129 env: launch_request
130 .env
131 .iter()
132 .map(|(k, v)| (k.clone(), v.clone()))
133 .collect(),
134 },
135 )),
136 },
137 DebugRequest::Attach(attach_request) => proto::DebugRequest {
138 request: Some(proto::debug_request::Request::DebugAttachRequest(
139 proto::DebugAttachRequest {
140 process_id: attach_request
141 .process_id
142 .expect("The process ID to be already filled out."),
143 },
144 )),
145 },
146 }
147 }
148
149 pub fn from_proto(val: proto::DebugRequest) -> Result<DebugRequest> {
150 let request = val
151 .request
152 .ok_or_else(|| anyhow::anyhow!("Missing debug request"))?;
153 match request {
154 proto::debug_request::Request::DebugLaunchRequest(proto::DebugLaunchRequest {
155 program,
156 cwd,
157 args,
158 env,
159 }) => Ok(DebugRequest::Launch(LaunchRequest {
160 program,
161 cwd: cwd.map(From::from),
162 args,
163 env: env.into_iter().collect(),
164 })),
165
166 proto::debug_request::Request::DebugAttachRequest(proto::DebugAttachRequest {
167 process_id,
168 }) => Ok(DebugRequest::Attach(AttachRequest {
169 process_id: Some(process_id),
170 })),
171 }
172 }
173}
174
175impl From<LaunchRequest> for DebugRequest {
176 fn from(launch_config: LaunchRequest) -> Self {
177 DebugRequest::Launch(launch_config)
178 }
179}
180
181impl From<AttachRequest> for DebugRequest {
182 fn from(attach_config: AttachRequest) -> Self {
183 DebugRequest::Attach(attach_config)
184 }
185}
186
187#[derive(Deserialize, Serialize, PartialEq, Eq, JsonSchema, Clone, Debug)]
188#[serde(untagged)]
189pub enum BuildTaskDefinition {
190 ByName(SharedString),
191 Template {
192 #[serde(flatten)]
193 task_template: TaskTemplate,
194 #[serde(skip)]
195 locator_name: Option<SharedString>,
196 },
197}
198/// This struct represent a user created debug task
199#[derive(Deserialize, Serialize, PartialEq, Eq, JsonSchema, Clone, Debug)]
200#[serde(rename_all = "snake_case")]
201pub struct DebugScenario {
202 pub adapter: SharedString,
203 /// Name of the debug task
204 pub label: SharedString,
205 /// A task to run prior to spawning the debuggee.
206 #[serde(default, skip_serializing_if = "Option::is_none")]
207 pub build: Option<BuildTaskDefinition>,
208 #[serde(flatten)]
209 pub request: Option<DebugRequest>,
210 /// Additional initialization arguments to be sent on DAP initialization
211 #[serde(default, skip_serializing_if = "Option::is_none")]
212 pub initialize_args: Option<serde_json::Value>,
213 /// Optional TCP connection information
214 ///
215 /// If provided, this will be used to connect to the debug adapter instead of
216 /// spawning a new process. This is useful for connecting to a debug adapter
217 /// that is already running or is started by another process.
218 #[serde(default, skip_serializing_if = "Option::is_none")]
219 pub tcp_connection: Option<TcpArgumentsTemplate>,
220 /// Whether to tell the debug adapter to stop on entry
221 #[serde(default, skip_serializing_if = "Option::is_none")]
222 pub stop_on_entry: Option<bool>,
223}
224
225impl DebugScenario {
226 pub fn cwd(&self) -> Option<&Path> {
227 if let Some(DebugRequest::Launch(config)) = &self.request {
228 config.cwd.as_ref().map(Path::new)
229 } else {
230 None
231 }
232 }
233}
234
235/// A group of Debug Tasks defined in a JSON file.
236#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
237#[serde(transparent)]
238pub struct DebugTaskFile(pub Vec<DebugScenario>);
239
240impl DebugTaskFile {
241 /// Generates JSON schema of Tasks JSON template format.
242 pub fn generate_json_schema() -> serde_json_lenient::Value {
243 let schema = SchemaSettings::draft07()
244 .with(|settings| settings.option_add_null_type = false)
245 .into_generator()
246 .into_root_schema_for::<Self>();
247
248 serde_json_lenient::to_value(schema).unwrap()
249 }
250}
251
252#[cfg(test)]
253mod tests {
254 use crate::{DebugRequest, DebugScenario, LaunchRequest};
255
256 #[test]
257 fn test_can_deserialize_non_attach_task() {
258 let deserialized: DebugRequest =
259 serde_json::from_str(r#"{"program": "cafebabe"}"#).unwrap();
260 assert_eq!(
261 deserialized,
262 DebugRequest::Launch(LaunchRequest {
263 program: "cafebabe".to_owned(),
264 ..Default::default()
265 })
266 );
267 }
268
269 #[test]
270 fn test_empty_scenario_has_none_request() {
271 let json = r#"{
272 "label": "Build & debug rust",
273 "build": "rust",
274 "adapter": "CodeLLDB"
275 }"#;
276
277 let deserialized: DebugScenario = serde_json::from_str(json).unwrap();
278 assert_eq!(deserialized.request, None);
279 }
280
281 #[test]
282 fn test_launch_scenario_deserialization() {
283 let json = r#"{
284 "label": "Launch program",
285 "adapter": "CodeLLDB",
286 "program": "target/debug/myapp",
287 "args": ["--test"]
288 }"#;
289
290 let deserialized: DebugScenario = serde_json::from_str(json).unwrap();
291 match deserialized.request {
292 Some(DebugRequest::Launch(launch)) => {
293 assert_eq!(launch.program, "target/debug/myapp");
294 assert_eq!(launch.args, vec!["--test"]);
295 }
296 _ => panic!("Expected Launch request"),
297 }
298 }
299
300 #[test]
301 fn test_attach_scenario_deserialization() {
302 let json = r#"{
303 "label": "Attach to process",
304 "adapter": "CodeLLDB",
305 "process_id": 1234
306 }"#;
307
308 let deserialized: DebugScenario = serde_json::from_str(json).unwrap();
309 match deserialized.request {
310 Some(DebugRequest::Attach(attach)) => {
311 assert_eq!(attach.process_id, Some(1234));
312 }
313 _ => panic!("Expected Attach request"),
314 }
315 }
316}