1use anyhow::Result;
2use async_trait::async_trait;
3use collections::HashMap;
4use dap::{DapLocator, DebugRequest, adapters::DebugAdapterName};
5use gpui::SharedString;
6use serde::{Deserialize, Serialize};
7use task::{DebugScenario, SpawnInTerminal, TaskTemplate};
8
9pub(crate) struct GoLocator;
10
11#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
12#[serde(rename_all = "camelCase")]
13struct DelveLaunchRequest {
14 request: String,
15 mode: String,
16 program: String,
17 #[serde(skip_serializing_if = "Option::is_none")]
18 cwd: Option<String>,
19 args: Vec<String>,
20 build_flags: Vec<String>,
21 env: HashMap<String, String>,
22}
23
24fn is_debug_flag(arg: &str) -> Option<bool> {
25 let mut part = if let Some(suffix) = arg.strip_prefix("test.") {
26 suffix
27 } else {
28 arg
29 };
30 let mut might_have_arg = true;
31 if let Some(idx) = part.find('=') {
32 might_have_arg = false;
33 part = &part[..idx];
34 }
35 match part {
36 "benchmem" | "failfast" | "fullpath" | "fuzzworker" | "json" | "short" | "v"
37 | "paniconexit0" => Some(false),
38 "bench"
39 | "benchtime"
40 | "blockprofile"
41 | "blockprofilerate"
42 | "count"
43 | "coverprofile"
44 | "cpu"
45 | "cpuprofile"
46 | "fuzz"
47 | "fuzzcachedir"
48 | "fuzzminimizetime"
49 | "fuzztime"
50 | "gocoverdir"
51 | "list"
52 | "memprofile"
53 | "memprofilerate"
54 | "mutexprofile"
55 | "mutexprofilefraction"
56 | "outputdir"
57 | "parallel"
58 | "run"
59 | "shuffle"
60 | "skip"
61 | "testlogfile"
62 | "timeout"
63 | "trace" => Some(might_have_arg),
64 _ if arg.starts_with("test.") => Some(false),
65 _ => None,
66 }
67}
68
69fn is_build_flag(mut arg: &str) -> Option<bool> {
70 let mut might_have_arg = true;
71 if let Some(idx) = arg.find('=') {
72 might_have_arg = false;
73 arg = &arg[..idx];
74 }
75 match arg {
76 "a" | "n" | "race" | "msan" | "asan" | "cover" | "work" | "x" | "v" | "buildvcs"
77 | "json" | "linkshared" | "modcacherw" | "trimpath" => Some(false),
78
79 "p" | "covermode" | "coverpkg" | "asmflags" | "buildmode" | "compiler" | "gccgoflags"
80 | "gcflags" | "installsuffix" | "ldflags" | "mod" | "modfile" | "overlay" | "pgo"
81 | "pkgdir" | "tags" | "toolexec" => Some(might_have_arg),
82 _ => None,
83 }
84}
85
86#[async_trait]
87impl DapLocator for GoLocator {
88 fn name(&self) -> SharedString {
89 SharedString::new_static("go-debug-locator")
90 }
91
92 fn create_scenario(
93 &self,
94 build_config: &TaskTemplate,
95 resolved_label: &str,
96 adapter: DebugAdapterName,
97 ) -> Option<DebugScenario> {
98 if build_config.command != "go" {
99 return None;
100 }
101 let go_action = build_config.args.first()?;
102
103 match go_action.as_str() {
104 "test" => {
105 let mut program = ".".to_string();
106 let mut args = Vec::default();
107 let mut build_flags = Vec::default();
108
109 let mut all_args_are_test = false;
110 let mut next_arg_is_test = false;
111 let mut next_arg_is_build = false;
112 let mut seen_pkg = false;
113 let mut seen_v = false;
114
115 for arg in build_config.args.iter().skip(1) {
116 if all_args_are_test || next_arg_is_test {
117 // HACK: tasks assume that they are run in a shell context,
118 // so the -run regex has escaped specials. Delve correctly
119 // handles escaping, so we undo that here.
120 if arg.starts_with("\\^") && arg.ends_with("\\$") {
121 let mut arg = arg[1..arg.len() - 2].to_string();
122 arg.push('$');
123 args.push(arg);
124 } else {
125 args.push(arg.clone());
126 }
127 next_arg_is_test = false;
128 } else if next_arg_is_build {
129 build_flags.push(arg.clone());
130 next_arg_is_build = false;
131 } else if arg.starts_with('-') {
132 let flag = arg.trim_start_matches('-');
133 if flag == "args" {
134 all_args_are_test = true;
135 } else if let Some(has_arg) = is_debug_flag(flag) {
136 if flag == "v" || flag == "test.v" {
137 seen_v = true;
138 }
139 if flag.starts_with("test.") {
140 args.push(arg.clone());
141 } else {
142 args.push(format!("-test.{flag}"))
143 }
144 next_arg_is_test = has_arg;
145 } else if let Some(has_arg) = is_build_flag(flag) {
146 build_flags.push(arg.clone());
147 next_arg_is_build = has_arg;
148 }
149 } else if !seen_pkg {
150 program = arg.clone();
151 seen_pkg = true;
152 } else {
153 args.push(arg.clone());
154 }
155 }
156 if !seen_v {
157 args.push("-test.v".to_string());
158 }
159
160 let config: serde_json::Value = serde_json::to_value(DelveLaunchRequest {
161 request: "launch".to_string(),
162 mode: "test".to_string(),
163 program,
164 args: args,
165 build_flags,
166 cwd: build_config.cwd.clone(),
167 env: build_config.env.clone(),
168 })
169 .unwrap();
170
171 Some(DebugScenario {
172 label: resolved_label.to_string().into(),
173 adapter: adapter.0,
174 build: None,
175 config: config,
176 tcp_connection: None,
177 })
178 }
179 "run" => {
180 let mut next_arg_is_build = false;
181 let mut seen_pkg = false;
182
183 let mut program = ".".to_string();
184 let mut args = Vec::default();
185 let mut build_flags = Vec::default();
186
187 for arg in build_config.args.iter().skip(1) {
188 if seen_pkg {
189 args.push(arg.clone())
190 } else if next_arg_is_build {
191 build_flags.push(arg.clone());
192 next_arg_is_build = false;
193 } else if arg.starts_with("-") {
194 if let Some(has_arg) = is_build_flag(arg.trim_start_matches("-")) {
195 next_arg_is_build = has_arg;
196 }
197 build_flags.push(arg.clone())
198 } else {
199 program = arg.to_string();
200 seen_pkg = true;
201 }
202 }
203
204 let config: serde_json::Value = serde_json::to_value(DelveLaunchRequest {
205 cwd: build_config.cwd.clone(),
206 env: build_config.env.clone(),
207 request: "launch".to_string(),
208 mode: "debug".to_string(),
209 program,
210 args: args,
211 build_flags,
212 })
213 .unwrap();
214
215 Some(DebugScenario {
216 label: resolved_label.to_string().into(),
217 adapter: adapter.0,
218 build: None,
219 config,
220 tcp_connection: None,
221 })
222 }
223 _ => None,
224 }
225 }
226
227 async fn run(&self, _build_config: SpawnInTerminal) -> Result<DebugRequest> {
228 unreachable!()
229 }
230}
231
232#[cfg(test)]
233mod tests {
234 use super::*;
235 use task::{HideStrategy, RevealStrategy, RevealTarget, Shell, TaskTemplate};
236
237 #[test]
238 fn test_create_scenario_for_go_build() {
239 let locator = GoLocator;
240 let task = TaskTemplate {
241 label: "go build".into(),
242 command: "go".into(),
243 args: vec!["build".into(), ".".into()],
244 env: Default::default(),
245 cwd: Some("${ZED_WORKTREE_ROOT}".into()),
246 use_new_terminal: false,
247 allow_concurrent_runs: false,
248 reveal: RevealStrategy::Always,
249 reveal_target: RevealTarget::Dock,
250 hide: HideStrategy::Never,
251 shell: Shell::System,
252 tags: vec![],
253 show_summary: true,
254 show_command: true,
255 };
256
257 let scenario =
258 locator.create_scenario(&task, "test label", DebugAdapterName("Delve".into()));
259
260 assert!(scenario.is_none());
261 }
262
263 #[test]
264 fn test_skip_non_go_commands_with_non_delve_adapter() {
265 let locator = GoLocator;
266 let task = TaskTemplate {
267 label: "cargo build".into(),
268 command: "cargo".into(),
269 args: vec!["build".into()],
270 env: Default::default(),
271 cwd: Some("${ZED_WORKTREE_ROOT}".into()),
272 use_new_terminal: false,
273 allow_concurrent_runs: false,
274 reveal: RevealStrategy::Always,
275 reveal_target: RevealTarget::Dock,
276 hide: HideStrategy::Never,
277 shell: Shell::System,
278 tags: vec![],
279 show_summary: true,
280 show_command: true,
281 };
282
283 let scenario = locator.create_scenario(
284 &task,
285 "test label",
286 DebugAdapterName("SomeOtherAdapter".into()),
287 );
288 assert!(scenario.is_none());
289
290 let scenario =
291 locator.create_scenario(&task, "test label", DebugAdapterName("Delve".into()));
292 assert!(scenario.is_none());
293 }
294 #[test]
295 fn test_go_locator_run() {
296 let locator = GoLocator;
297 let delve = DebugAdapterName("Delve".into());
298
299 let task = TaskTemplate {
300 label: "go run with flags".into(),
301 command: "go".into(),
302 args: vec![
303 "run".to_string(),
304 "-race".to_string(),
305 "-ldflags".to_string(),
306 "-X main.version=1.0".to_string(),
307 "./cmd/myapp".to_string(),
308 "--config".to_string(),
309 "production.yaml".to_string(),
310 "--verbose".to_string(),
311 ],
312 env: {
313 let mut env = HashMap::default();
314 env.insert("GO_ENV".to_string(), "production".to_string());
315 env
316 },
317 cwd: Some("/project/root".into()),
318 ..Default::default()
319 };
320
321 let scenario = locator
322 .create_scenario(&task, "test run label", delve)
323 .unwrap();
324
325 let config: DelveLaunchRequest = serde_json::from_value(scenario.config).unwrap();
326
327 assert_eq!(
328 config,
329 DelveLaunchRequest {
330 request: "launch".to_string(),
331 mode: "debug".to_string(),
332 program: "./cmd/myapp".to_string(),
333 build_flags: vec![
334 "-race".to_string(),
335 "-ldflags".to_string(),
336 "-X main.version=1.0".to_string()
337 ],
338 args: vec![
339 "--config".to_string(),
340 "production.yaml".to_string(),
341 "--verbose".to_string(),
342 ],
343 env: {
344 let mut env = HashMap::default();
345 env.insert("GO_ENV".to_string(), "production".to_string());
346 env
347 },
348 cwd: Some("/project/root".to_string()),
349 }
350 );
351 }
352
353 #[test]
354 fn test_go_locator_test() {
355 let locator = GoLocator;
356 let delve = DebugAdapterName("Delve".into());
357
358 // Test with tags and run flag
359 let task_with_tags = TaskTemplate {
360 label: "test".into(),
361 command: "go".into(),
362 args: vec![
363 "test".to_string(),
364 "-tags".to_string(),
365 "integration,unit".to_string(),
366 "-run".to_string(),
367 "Foo".to_string(),
368 ".".to_string(),
369 ],
370 ..Default::default()
371 };
372 let result = locator
373 .create_scenario(&task_with_tags, "", delve.clone())
374 .unwrap();
375
376 let config: DelveLaunchRequest = serde_json::from_value(result.config).unwrap();
377
378 assert_eq!(
379 config,
380 DelveLaunchRequest {
381 request: "launch".to_string(),
382 mode: "test".to_string(),
383 program: ".".to_string(),
384 build_flags: vec!["-tags".to_string(), "integration,unit".to_string(),],
385 args: vec![
386 "-test.run".to_string(),
387 "Foo".to_string(),
388 "-test.v".to_string()
389 ],
390 env: HashMap::default(),
391 cwd: None,
392 }
393 );
394 }
395
396 #[test]
397 fn test_skip_unsupported_go_commands() {
398 let locator = GoLocator;
399 let task = TaskTemplate {
400 label: "go clean".into(),
401 command: "go".into(),
402 args: vec!["clean".into()],
403 env: Default::default(),
404 cwd: Some("${ZED_WORKTREE_ROOT}".into()),
405 use_new_terminal: false,
406 allow_concurrent_runs: false,
407 reveal: RevealStrategy::Always,
408 reveal_target: RevealTarget::Dock,
409 hide: HideStrategy::Never,
410 shell: Shell::System,
411 tags: vec![],
412 show_summary: true,
413 show_command: true,
414 };
415
416 let scenario =
417 locator.create_scenario(&task, "test label", DebugAdapterName("Delve".into()));
418 assert!(scenario.is_none());
419 }
420}