1use anyhow::{Context as _, Result};
2use collections::FxHashMap;
3use gpui::SharedString;
4use log as _;
5use schemars::JsonSchema;
6use serde::{Deserialize, Serialize};
7use std::net::Ipv4Addr;
8use std::path::PathBuf;
9use util::debug_panic;
10
11use crate::{TaskTemplate, adapter_schema::AdapterSchemas};
12
13/// Represents the host information of the debug adapter
14#[derive(Default, Deserialize, Serialize, PartialEq, Eq, JsonSchema, Clone, Debug)]
15pub struct TcpArgumentsTemplate {
16 /// The port that the debug adapter is listening on
17 ///
18 /// Default: We will try to find an open port
19 pub port: Option<u16>,
20 /// The host that the debug adapter is listening too
21 ///
22 /// Default: 127.0.0.1
23 pub host: Option<Ipv4Addr>,
24 /// The max amount of time in milliseconds to connect to a tcp DAP before returning an error
25 ///
26 /// Default: 2000ms
27 pub timeout: Option<u64>,
28}
29
30impl TcpArgumentsTemplate {
31 /// Get the host or fallback to the default host
32 pub fn host(&self) -> Ipv4Addr {
33 self.host.unwrap_or_else(|| Ipv4Addr::new(127, 0, 0, 1))
34 }
35
36 pub fn from_proto(proto: proto::TcpHost) -> Result<Self> {
37 Ok(Self {
38 port: proto.port.map(|p| p.try_into()).transpose()?,
39 host: proto.host.map(|h| h.parse()).transpose()?,
40 timeout: proto.timeout,
41 })
42 }
43
44 pub fn to_proto(&self) -> proto::TcpHost {
45 proto::TcpHost {
46 port: self.port.map(|p| p.into()),
47 host: self.host.map(|h| h.to_string()),
48 timeout: self.timeout,
49 }
50 }
51}
52
53/// Represents the attach request information of the debug adapter
54#[derive(Default, Serialize, PartialEq, Eq, JsonSchema, Clone, Debug)]
55pub struct AttachRequest {
56 /// The processId to attach to, if left empty we will show a process picker
57 pub process_id: Option<u32>,
58}
59
60impl<'de> Deserialize<'de> for AttachRequest {
61 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
62 where
63 D: serde::Deserializer<'de>,
64 {
65 #[derive(Deserialize)]
66 struct Helper {
67 process_id: Option<u32>,
68 }
69
70 let helper = Helper::deserialize(deserializer)?;
71
72 // Skip creating an AttachRequest if process_id is None
73 if helper.process_id.is_none() {
74 return Err(serde::de::Error::custom("process_id is required"));
75 }
76
77 Ok(AttachRequest {
78 process_id: helper.process_id,
79 })
80 }
81}
82
83/// Represents the launch request information of the debug adapter
84#[derive(Deserialize, Serialize, Default, PartialEq, Eq, JsonSchema, Clone, Debug)]
85pub struct LaunchRequest {
86 /// The program that you trying to debug
87 pub program: String,
88 /// The current working directory of your project
89 #[serde(default)]
90 pub cwd: Option<PathBuf>,
91 /// Arguments to pass to a debuggee
92 #[serde(default)]
93 pub args: Vec<String>,
94 #[serde(default)]
95 pub env: FxHashMap<String, String>,
96}
97
98impl LaunchRequest {
99 pub fn env_json(&self) -> serde_json::Value {
100 serde_json::Value::Object(
101 self.env
102 .iter()
103 .map(|(k, v)| (k.clone(), v.to_owned().into()))
104 .collect::<serde_json::Map<String, serde_json::Value>>(),
105 )
106 }
107}
108
109/// Represents the type that will determine which request to call on the debug adapter
110#[derive(Deserialize, Serialize, PartialEq, Eq, JsonSchema, Clone, Debug)]
111#[serde(rename_all = "lowercase", tag = "request")]
112pub enum DebugRequest {
113 /// Call the `launch` request on the debug adapter
114 Launch(LaunchRequest),
115 /// Call the `attach` request on the debug adapter
116 Attach(AttachRequest),
117}
118
119impl DebugRequest {
120 pub fn to_proto(&self) -> proto::DebugRequest {
121 match self {
122 DebugRequest::Launch(launch_request) => proto::DebugRequest {
123 request: Some(proto::debug_request::Request::DebugLaunchRequest(
124 proto::DebugLaunchRequest {
125 program: launch_request.program.clone(),
126 cwd: launch_request
127 .cwd
128 .as_ref()
129 .map(|cwd| cwd.to_string_lossy().into_owned()),
130 args: launch_request.args.clone(),
131 env: launch_request
132 .env
133 .iter()
134 .map(|(k, v)| (k.clone(), v.clone()))
135 .collect(),
136 },
137 )),
138 },
139 DebugRequest::Attach(attach_request) => proto::DebugRequest {
140 request: Some(proto::debug_request::Request::DebugAttachRequest(
141 proto::DebugAttachRequest {
142 process_id: attach_request
143 .process_id
144 .expect("The process ID to be already filled out."),
145 },
146 )),
147 },
148 }
149 }
150
151 pub fn from_proto(val: proto::DebugRequest) -> Result<DebugRequest> {
152 let request = val.request.context("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(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
199impl<'de> Deserialize<'de> for BuildTaskDefinition {
200 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
201 where
202 D: serde::Deserializer<'de>,
203 {
204 #[derive(Deserialize)]
205 struct TemplateHelper {
206 #[serde(default)]
207 label: Option<String>,
208 #[serde(flatten)]
209 rest: serde_json::Value,
210 }
211
212 let value = serde_json::Value::deserialize(deserializer)?;
213
214 if let Ok(name) = serde_json::from_value::<SharedString>(value.clone()) {
215 return Ok(BuildTaskDefinition::ByName(name));
216 }
217
218 let helper: TemplateHelper =
219 serde_json::from_value(value).map_err(serde::de::Error::custom)?;
220
221 let mut template_value = helper.rest;
222 if let serde_json::Value::Object(ref mut map) = template_value {
223 map.insert(
224 "label".to_string(),
225 serde_json::to_value(helper.label.unwrap_or_else(|| "debug-build".to_owned()))
226 .map_err(serde::de::Error::custom)?,
227 );
228 }
229
230 let task_template: TaskTemplate =
231 serde_json::from_value(template_value).map_err(serde::de::Error::custom)?;
232
233 Ok(BuildTaskDefinition::Template {
234 task_template,
235 locator_name: None,
236 })
237 }
238}
239
240#[derive(Deserialize, Serialize, PartialEq, Eq, Clone, Debug, JsonSchema)]
241pub enum Request {
242 Launch,
243 Attach,
244}
245
246/// This struct represent a user created debug task from the new session modal
247#[derive(Deserialize, Serialize, PartialEq, Eq, Clone, Debug, JsonSchema)]
248#[serde(rename_all = "snake_case")]
249pub struct ZedDebugConfig {
250 /// Name of the debug task
251 pub label: SharedString,
252 /// The debug adapter to use
253 pub adapter: SharedString,
254 #[serde(flatten)]
255 pub request: DebugRequest,
256 /// Whether to tell the debug adapter to stop on entry
257 #[serde(default, skip_serializing_if = "Option::is_none")]
258 pub stop_on_entry: Option<bool>,
259}
260
261/// This struct represent a user created debug task
262#[derive(Deserialize, Serialize, PartialEq, Eq, Clone, Debug, JsonSchema)]
263#[serde(rename_all = "snake_case")]
264pub struct DebugScenario {
265 pub adapter: SharedString,
266 /// Name of the debug task
267 pub label: SharedString,
268 /// A task to run prior to spawning the debuggee.
269 #[serde(default, skip_serializing_if = "Option::is_none")]
270 pub build: Option<BuildTaskDefinition>,
271 /// The main arguments to be sent to the debug adapter
272 #[serde(default, flatten)]
273 pub config: serde_json::Value,
274 /// Optional TCP connection information
275 ///
276 /// If provided, this will be used to connect to the debug adapter instead of
277 /// spawning a new process. This is useful for connecting to a debug adapter
278 /// that is already running or is started by another process.
279 #[serde(default, skip_serializing_if = "Option::is_none")]
280 pub tcp_connection: Option<TcpArgumentsTemplate>,
281}
282
283/// A group of Debug Tasks defined in a JSON file.
284#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
285#[serde(transparent)]
286pub struct DebugTaskFile(pub Vec<DebugScenario>);
287
288impl DebugTaskFile {
289 pub fn generate_json_schema(schemas: &AdapterSchemas) -> serde_json_lenient::Value {
290 let build_task_schema = schemars::schema_for!(BuildTaskDefinition);
291 let mut build_task_value =
292 serde_json_lenient::to_value(&build_task_schema).unwrap_or_default();
293
294 if let Some(template_object) = build_task_value
295 .get_mut("anyOf")
296 .and_then(|array| array.as_array_mut())
297 .and_then(|array| array.get_mut(1))
298 {
299 if let Some(properties) = template_object
300 .get_mut("properties")
301 .and_then(|value| value.as_object_mut())
302 {
303 properties.remove("label");
304 }
305
306 if let Some(arr) = template_object
307 .get_mut("required")
308 .and_then(|array| array.as_array_mut())
309 {
310 arr.retain(|v| v.as_str() != Some("label"));
311 }
312 } else {
313 debug_panic!("Task Template schema in debug scenario's needs to be updated");
314 }
315
316 let task_definitions = build_task_value
317 .get("definitions")
318 .cloned()
319 .unwrap_or_default();
320
321 let adapter_conditions = schemas
322 .0
323 .iter()
324 .map(|adapter_schema| {
325 let adapter_name = adapter_schema.adapter.to_string();
326 serde_json::json!({
327 "if": {
328 "properties": {
329 "adapter": { "const": adapter_name }
330 }
331 },
332 "then": adapter_schema.schema
333 })
334 })
335 .collect::<Vec<_>>();
336
337 serde_json_lenient::json!({
338 "$schema": "http://json-schema.org/draft-07/schema#",
339 "title": "Debug Configurations",
340 "description": "Configuration for debug scenarios",
341 "type": "array",
342 "items": {
343 "type": "object",
344 "required": ["adapter", "label"],
345 "properties": {
346 "adapter": {
347 "type": "string",
348 "description": "The name of the debug adapter"
349 },
350 "label": {
351 "type": "string",
352 "description": "The name of the debug configuration"
353 },
354 "build": build_task_value,
355 "tcp_connection": {
356 "type": "object",
357 "description": "Optional TCP connection information for connecting to an already running debug adapter",
358 "properties": {
359 "port": {
360 "type": "integer",
361 "description": "The port that the debug adapter is listening on (default: auto-find open port)"
362 },
363 "host": {
364 "type": "string",
365 "pattern": "^((25[0-5]|(2[0-4]|1\\d|[1-9]|)\\d)\\.?\\b){4}$",
366 "description": "The host that the debug adapter is listening to (default: 127.0.0.1)"
367 },
368 "timeout": {
369 "type": "integer",
370 "description": "The max amount of time in milliseconds to connect to a tcp DAP before returning an error (default: 2000ms)"
371 }
372 }
373 }
374 },
375 "allOf": adapter_conditions
376 },
377 "definitions": task_definitions
378 })
379 }
380}
381
382#[cfg(test)]
383mod tests {
384 use crate::DebugScenario;
385 use serde_json::json;
386
387 #[test]
388 fn test_just_build_args() {
389 let json = r#"{
390 "label": "Build & debug rust",
391 "adapter": "CodeLLDB",
392 "build": {
393 "command": "rust",
394 "args": ["build"]
395 }
396 }"#;
397
398 let deserialized: DebugScenario = serde_json::from_str(json).unwrap();
399 assert!(deserialized.build.is_some());
400 match deserialized.build.as_ref().unwrap() {
401 crate::BuildTaskDefinition::Template { task_template, .. } => {
402 assert_eq!("debug-build", task_template.label);
403 assert_eq!("rust", task_template.command);
404 assert_eq!(vec!["build"], task_template.args);
405 }
406 _ => panic!("Expected Template variant"),
407 }
408 assert_eq!(json!({}), deserialized.config);
409 assert_eq!("CodeLLDB", deserialized.adapter.as_ref());
410 assert_eq!("Build & debug rust", deserialized.label.as_ref());
411 }
412
413 #[test]
414 fn test_empty_scenario_has_none_request() {
415 let json = r#"{
416 "label": "Build & debug rust",
417 "build": "rust",
418 "adapter": "CodeLLDB"
419 }"#;
420
421 let deserialized: DebugScenario = serde_json::from_str(json).unwrap();
422
423 assert_eq!(json!({}), deserialized.config);
424 assert_eq!("CodeLLDB", deserialized.adapter.as_ref());
425 assert_eq!("Build & debug rust", deserialized.label.as_ref());
426 }
427
428 #[test]
429 fn test_launch_scenario_deserialization() {
430 let json = r#"{
431 "label": "Launch program",
432 "adapter": "CodeLLDB",
433 "request": "launch",
434 "program": "target/debug/myapp",
435 "args": ["--test"]
436 }"#;
437
438 let deserialized: DebugScenario = serde_json::from_str(json).unwrap();
439
440 assert_eq!(
441 json!({ "request": "launch", "program": "target/debug/myapp", "args": ["--test"] }),
442 deserialized.config
443 );
444 assert_eq!("CodeLLDB", deserialized.adapter.as_ref());
445 assert_eq!("Launch program", deserialized.label.as_ref());
446 }
447
448 #[test]
449 fn test_attach_scenario_deserialization() {
450 let json = r#"{
451 "label": "Attach to process",
452 "adapter": "CodeLLDB",
453 "process_id": 1234,
454 "request": "attach"
455 }"#;
456
457 let deserialized: DebugScenario = serde_json::from_str(json).unwrap();
458
459 assert_eq!(
460 json!({ "request": "attach", "process_id": 1234 }),
461 deserialized.config
462 );
463 assert_eq!("CodeLLDB", deserialized.adapter.as_ref());
464 assert_eq!("Attach to process", deserialized.label.as_ref());
465 }
466
467 #[test]
468 fn test_build_task_definition_without_label() {
469 use crate::BuildTaskDefinition;
470
471 let json = r#""my_build_task""#;
472 let deserialized: BuildTaskDefinition = serde_json::from_str(json).unwrap();
473 match deserialized {
474 BuildTaskDefinition::ByName(name) => assert_eq!("my_build_task", name.as_ref()),
475 _ => panic!("Expected ByName variant"),
476 }
477
478 let json = r#"{
479 "command": "cargo",
480 "args": ["build", "--release"]
481 }"#;
482 let deserialized: BuildTaskDefinition = serde_json::from_str(json).unwrap();
483 match deserialized {
484 BuildTaskDefinition::Template { task_template, .. } => {
485 assert_eq!("debug-build", task_template.label);
486 assert_eq!("cargo", task_template.command);
487 assert_eq!(vec!["build", "--release"], task_template.args);
488 }
489 _ => panic!("Expected Template variant"),
490 }
491
492 let json = r#"{
493 "label": "Build Release",
494 "command": "cargo",
495 "args": ["build", "--release"]
496 }"#;
497 let deserialized: BuildTaskDefinition = serde_json::from_str(json).unwrap();
498 match deserialized {
499 BuildTaskDefinition::Template { task_template, .. } => {
500 assert_eq!("Build Release", task_template.label);
501 assert_eq!("cargo", task_template.command);
502 assert_eq!(vec!["build", "--release"], task_template.args);
503 }
504 _ => panic!("Expected Template variant"),
505 }
506 }
507}