debug_format.rs

  1use anyhow::{Context as _, 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.request.context("Missing debug request")?;
151        match request {
152            proto::debug_request::Request::DebugLaunchRequest(proto::DebugLaunchRequest {
153                program,
154                cwd,
155                args,
156                env,
157            }) => Ok(DebugRequest::Launch(LaunchRequest {
158                program,
159                cwd: cwd.map(From::from),
160                args,
161                env: env.into_iter().collect(),
162            })),
163
164            proto::debug_request::Request::DebugAttachRequest(proto::DebugAttachRequest {
165                process_id,
166            }) => Ok(DebugRequest::Attach(AttachRequest {
167                process_id: Some(process_id),
168            })),
169        }
170    }
171}
172
173impl From<LaunchRequest> for DebugRequest {
174    fn from(launch_config: LaunchRequest) -> Self {
175        DebugRequest::Launch(launch_config)
176    }
177}
178
179impl From<AttachRequest> for DebugRequest {
180    fn from(attach_config: AttachRequest) -> Self {
181        DebugRequest::Attach(attach_config)
182    }
183}
184
185#[derive(Deserialize, Serialize, PartialEq, Eq, JsonSchema, Clone, Debug)]
186#[serde(untagged)]
187pub enum BuildTaskDefinition {
188    ByName(SharedString),
189    Template {
190        #[serde(flatten)]
191        task_template: TaskTemplate,
192        #[serde(skip)]
193        locator_name: Option<SharedString>,
194    },
195}
196/// This struct represent a user created debug task
197#[derive(Deserialize, Serialize, PartialEq, Eq, JsonSchema, Clone, Debug)]
198#[serde(rename_all = "snake_case")]
199pub struct DebugScenario {
200    pub adapter: SharedString,
201    /// Name of the debug task
202    pub label: SharedString,
203    /// A task to run prior to spawning the debuggee.
204    #[serde(default, skip_serializing_if = "Option::is_none")]
205    pub build: Option<BuildTaskDefinition>,
206    #[serde(flatten)]
207    pub request: Option<DebugRequest>,
208    /// Additional initialization arguments to be sent on DAP initialization
209    #[serde(default, skip_serializing_if = "Option::is_none")]
210    pub initialize_args: Option<serde_json::Value>,
211    /// Optional TCP connection information
212    ///
213    /// If provided, this will be used to connect to the debug adapter instead of
214    /// spawning a new process. This is useful for connecting to a debug adapter
215    /// that is already running or is started by another process.
216    #[serde(default, skip_serializing_if = "Option::is_none")]
217    pub tcp_connection: Option<TcpArgumentsTemplate>,
218    /// Whether to tell the debug adapter to stop on entry
219    #[serde(default, skip_serializing_if = "Option::is_none")]
220    pub stop_on_entry: Option<bool>,
221}
222
223impl DebugScenario {
224    pub fn cwd(&self) -> Option<&Path> {
225        if let Some(DebugRequest::Launch(config)) = &self.request {
226            config.cwd.as_ref().map(Path::new)
227        } else {
228            None
229        }
230    }
231}
232
233/// A group of Debug Tasks defined in a JSON file.
234#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
235#[serde(transparent)]
236pub struct DebugTaskFile(pub Vec<DebugScenario>);
237
238impl DebugTaskFile {
239    /// Generates JSON schema of Tasks JSON template format.
240    pub fn generate_json_schema() -> serde_json_lenient::Value {
241        let schema = SchemaSettings::draft07()
242            .with(|settings| settings.option_add_null_type = false)
243            .into_generator()
244            .into_root_schema_for::<Self>();
245
246        serde_json_lenient::to_value(schema).unwrap()
247    }
248}
249
250#[cfg(test)]
251mod tests {
252    use crate::{DebugRequest, DebugScenario, LaunchRequest};
253
254    #[test]
255    fn test_can_deserialize_non_attach_task() {
256        let deserialized: DebugRequest =
257            serde_json::from_str(r#"{"program": "cafebabe"}"#).unwrap();
258        assert_eq!(
259            deserialized,
260            DebugRequest::Launch(LaunchRequest {
261                program: "cafebabe".to_owned(),
262                ..Default::default()
263            })
264        );
265    }
266
267    #[test]
268    fn test_empty_scenario_has_none_request() {
269        let json = r#"{
270            "label": "Build & debug rust",
271            "build": "rust",
272            "adapter": "CodeLLDB"
273        }"#;
274
275        let deserialized: DebugScenario = serde_json::from_str(json).unwrap();
276        assert_eq!(deserialized.request, None);
277    }
278
279    #[test]
280    fn test_launch_scenario_deserialization() {
281        let json = r#"{
282            "label": "Launch program",
283            "adapter": "CodeLLDB",
284            "program": "target/debug/myapp",
285            "args": ["--test"]
286        }"#;
287
288        let deserialized: DebugScenario = serde_json::from_str(json).unwrap();
289        match deserialized.request {
290            Some(DebugRequest::Launch(launch)) => {
291                assert_eq!(launch.program, "target/debug/myapp");
292                assert_eq!(launch.args, vec!["--test"]);
293            }
294            _ => panic!("Expected Launch request"),
295        }
296    }
297
298    #[test]
299    fn test_attach_scenario_deserialization() {
300        let json = r#"{
301            "label": "Attach to process",
302            "adapter": "CodeLLDB",
303            "process_id": 1234
304        }"#;
305
306        let deserialized: DebugScenario = serde_json::from_str(json).unwrap();
307        match deserialized.request {
308            Some(DebugRequest::Attach(attach)) => {
309                assert_eq!(attach.process_id, Some(1234));
310            }
311            _ => panic!("Expected Attach request"),
312        }
313    }
314}