1use dap_types::StartDebuggingRequestArguments;
2use schemars::{gen::SchemaSettings, JsonSchema};
3use serde::{Deserialize, Serialize};
4use std::net::Ipv4Addr;
5use std::path::PathBuf;
6use util::ResultExt;
7
8use crate::{TaskTemplate, TaskTemplates, TaskType};
9
10impl Default for DebugConnectionType {
11 fn default() -> Self {
12 DebugConnectionType::TCP(TCPHost::default())
13 }
14}
15
16/// Represents the host information of the debug adapter
17#[derive(Default, Deserialize, Serialize, PartialEq, Eq, JsonSchema, Clone, Debug)]
18pub struct TCPHost {
19 /// The port that the debug adapter is listening on
20 ///
21 /// Default: We will try to find an open port
22 pub port: Option<u16>,
23 /// The host that the debug adapter is listening too
24 ///
25 /// Default: 127.0.0.1
26 pub host: Option<Ipv4Addr>,
27 /// The max amount of time in milliseconds to connect to a tcp DAP before returning an error
28 ///
29 /// Default: 2000ms
30 pub timeout: Option<u64>,
31}
32
33impl TCPHost {
34 /// Get the host or fallback to the default host
35 pub fn host(&self) -> Ipv4Addr {
36 self.host.unwrap_or_else(|| Ipv4Addr::new(127, 0, 0, 1))
37 }
38}
39
40/// Represents the attach request information of the debug adapter
41#[derive(Default, Deserialize, Serialize, PartialEq, Eq, JsonSchema, Clone, Debug)]
42pub struct AttachConfig {
43 /// The processId to attach to, if left empty we will show a process picker
44 #[serde(default)]
45 pub process_id: Option<u32>,
46}
47
48/// Represents the launch request information of the debug adapter
49#[derive(Deserialize, Serialize, Default, PartialEq, Eq, JsonSchema, Clone, Debug)]
50pub struct LaunchConfig {
51 /// The program that you trying to debug
52 pub program: String,
53 /// The current working directory of your project
54 pub cwd: Option<PathBuf>,
55}
56
57/// Represents the type that will determine which request to call on the debug adapter
58#[derive(Deserialize, Serialize, PartialEq, Eq, JsonSchema, Clone, Debug)]
59#[serde(rename_all = "lowercase", untagged)]
60pub enum DebugRequestType {
61 /// Call the `launch` request on the debug adapter
62 Launch(LaunchConfig),
63 /// Call the `attach` request on the debug adapter
64 Attach(AttachConfig),
65}
66
67/// Represents a request for starting the debugger.
68/// Contrary to `DebugRequestType`, `DebugRequestDisposition` is not Serializable.
69#[derive(PartialEq, Eq, Clone, Debug)]
70pub enum DebugRequestDisposition {
71 /// Debug session configured by the user.
72 UserConfigured(DebugRequestType),
73 /// Debug session configured by the debug adapter
74 ReverseRequest(StartDebuggingRequestArguments),
75}
76
77impl DebugRequestDisposition {
78 /// Get the current working directory from request if it's a launch request and exits
79 pub fn cwd(&self) -> Option<PathBuf> {
80 match self {
81 Self::UserConfigured(DebugRequestType::Launch(launch_config)) => {
82 launch_config.cwd.clone()
83 }
84 _ => None,
85 }
86 }
87}
88/// Represents the configuration for the debug adapter
89#[derive(PartialEq, Eq, Clone, Debug)]
90pub struct DebugAdapterConfig {
91 /// Name of the debug task
92 pub label: String,
93 /// The type of adapter you want to use
94 pub adapter: String,
95 /// The type of request that should be called on the debug adapter
96 pub request: DebugRequestDisposition,
97 /// Additional initialization arguments to be sent on DAP initialization
98 pub initialize_args: Option<serde_json::Value>,
99 /// Optional TCP connection information
100 ///
101 /// If provided, this will be used to connect to the debug adapter instead of
102 /// spawning a new process. This is useful for connecting to a debug adapter
103 /// that is already running or is started by another process.
104 pub tcp_connection: Option<TCPHost>,
105}
106
107impl From<DebugTaskDefinition> for DebugAdapterConfig {
108 fn from(def: DebugTaskDefinition) -> Self {
109 Self {
110 label: def.label,
111 adapter: def.adapter,
112 request: DebugRequestDisposition::UserConfigured(def.request),
113 initialize_args: def.initialize_args,
114 tcp_connection: def.tcp_connection,
115 }
116 }
117}
118
119impl TryFrom<DebugAdapterConfig> for DebugTaskDefinition {
120 type Error = ();
121 fn try_from(def: DebugAdapterConfig) -> Result<Self, Self::Error> {
122 let request = match def.request {
123 DebugRequestDisposition::UserConfigured(debug_request_type) => debug_request_type,
124 DebugRequestDisposition::ReverseRequest(_) => return Err(()),
125 };
126
127 Ok(Self {
128 label: def.label,
129 adapter: def.adapter,
130 request,
131 initialize_args: def.initialize_args,
132 tcp_connection: def.tcp_connection,
133 })
134 }
135}
136
137impl DebugTaskDefinition {
138 /// Translate from debug definition to a task template
139 pub fn to_zed_format(self) -> anyhow::Result<TaskTemplate> {
140 let command = "".to_string();
141
142 let cwd = if let DebugRequestType::Launch(ref launch) = self.request {
143 launch
144 .cwd
145 .as_ref()
146 .map(|path| path.to_string_lossy().into_owned())
147 } else {
148 None
149 };
150 let label = self.label.clone();
151 let task_type = TaskType::Debug(self);
152
153 Ok(TaskTemplate {
154 label,
155 command,
156 args: vec![],
157 task_type,
158 cwd,
159 ..Default::default()
160 })
161 }
162}
163/// Represents the type of the debugger adapter connection
164#[derive(Deserialize, Serialize, PartialEq, Eq, JsonSchema, Clone, Debug)]
165#[serde(rename_all = "lowercase", tag = "connection")]
166pub enum DebugConnectionType {
167 /// Connect to the debug adapter via TCP
168 TCP(TCPHost),
169 /// Connect to the debug adapter via STDIO
170 STDIO,
171}
172
173/// This struct represent a user created debug task
174#[derive(Deserialize, Serialize, PartialEq, Eq, JsonSchema, Clone, Debug)]
175#[serde(rename_all = "snake_case")]
176pub struct DebugTaskDefinition {
177 /// The adapter to run
178 pub adapter: String,
179 /// The type of request that should be called on the debug adapter
180 #[serde(flatten)]
181 pub request: DebugRequestType,
182 /// Name of the debug task
183 pub label: String,
184 /// Additional initialization arguments to be sent on DAP initialization
185 pub initialize_args: Option<serde_json::Value>,
186 /// Optional TCP connection information
187 ///
188 /// If provided, this will be used to connect to the debug adapter instead of
189 /// spawning a new process. This is useful for connecting to a debug adapter
190 /// that is already running or is started by another process.
191 pub tcp_connection: Option<TCPHost>,
192}
193
194/// A group of Debug Tasks defined in a JSON file.
195#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
196#[serde(transparent)]
197pub struct DebugTaskFile(pub Vec<DebugTaskDefinition>);
198
199impl DebugTaskFile {
200 /// Generates JSON schema of Tasks JSON template format.
201 pub fn generate_json_schema() -> serde_json_lenient::Value {
202 let schema = SchemaSettings::draft07()
203 .with(|settings| settings.option_add_null_type = false)
204 .into_generator()
205 .into_root_schema_for::<Self>();
206
207 serde_json_lenient::to_value(schema).unwrap()
208 }
209}
210
211impl TryFrom<DebugTaskFile> for TaskTemplates {
212 type Error = anyhow::Error;
213
214 fn try_from(value: DebugTaskFile) -> Result<Self, Self::Error> {
215 let templates = value
216 .0
217 .into_iter()
218 .filter_map(|debug_definition| debug_definition.to_zed_format().log_err())
219 .collect();
220
221 Ok(Self(templates))
222 }
223}