1use anyhow::{Context as _, Result};
2use async_trait::async_trait;
3use dap::{DapLocator, DebugRequest, adapters::DebugAdapterName};
4use gpui::SharedString;
5use serde_json::{Value, json};
6use smol::{Timer, io::AsyncReadExt, process::Stdio};
7use std::time::Duration;
8use task::{BuildTaskDefinition, DebugScenario, ShellBuilder, SpawnInTerminal, TaskTemplate};
9use util::command::new_smol_command;
10
11pub(crate) struct CargoLocator;
12
13async fn find_best_executable(executables: &[String], test_name: &str) -> Option<String> {
14 if executables.len() == 1 {
15 return executables.first().cloned();
16 }
17 for executable in executables {
18 let Some(mut child) = new_smol_command(&executable)
19 .arg("--list")
20 .stdout(Stdio::piped())
21 .spawn()
22 .ok()
23 else {
24 continue;
25 };
26 let mut test_lines = String::default();
27 let exec_result = smol::future::race(
28 async {
29 if let Some(mut stdout) = child.stdout.take() {
30 stdout.read_to_string(&mut test_lines).await?;
31 }
32 Ok(())
33 },
34 async {
35 Timer::after(Duration::from_secs(3)).await;
36 anyhow::bail!("Timed out waiting for executable stdout")
37 },
38 );
39
40 if let Err(err) = exec_result.await {
41 log::warn!("Failed to list tests for {executable}: {err}");
42 } else {
43 for line in test_lines.lines() {
44 if line.contains(&test_name) {
45 return Some(executable.clone());
46 }
47 }
48 }
49 let _ = child.kill();
50 }
51 None
52}
53#[async_trait]
54impl DapLocator for CargoLocator {
55 fn name(&self) -> SharedString {
56 SharedString::new_static("rust-cargo-locator")
57 }
58 async fn create_scenario(
59 &self,
60 build_config: &TaskTemplate,
61 resolved_label: &str,
62 adapter: &DebugAdapterName,
63 ) -> Option<DebugScenario> {
64 if build_config.command != "cargo" {
65 return None;
66 }
67 let mut task_template = build_config.clone();
68 let cargo_action = task_template.args.first_mut()?;
69 if cargo_action == "check" || cargo_action == "clean" {
70 return None;
71 }
72
73 match cargo_action.as_ref() {
74 "run" | "r" => {
75 *cargo_action = "build".to_owned();
76 }
77 "test" | "t" | "bench" => {
78 let delimiter = task_template
79 .args
80 .iter()
81 .position(|arg| arg == "--")
82 .unwrap_or(task_template.args.len());
83 if !task_template.args[..delimiter]
84 .iter()
85 .any(|arg| arg == "--no-run")
86 {
87 task_template.args.insert(delimiter, "--no-run".to_owned());
88 }
89 }
90 _ => {}
91 }
92
93 let config = if adapter.as_ref() == "CodeLLDB" {
94 json!({
95 "sourceLanguages": ["rust"]
96 })
97 } else {
98 Value::Null
99 };
100 Some(DebugScenario {
101 adapter: adapter.0.clone(),
102 label: resolved_label.to_string().into(),
103 build: Some(BuildTaskDefinition::Template {
104 task_template,
105 locator_name: Some(self.name()),
106 }),
107 config,
108 tcp_connection: None,
109 })
110 }
111
112 async fn run(&self, build_config: SpawnInTerminal) -> Result<DebugRequest> {
113 let cwd = build_config
114 .cwd
115 .clone()
116 .context("Couldn't get cwd from debug config which is needed for locators")?;
117 let builder = ShellBuilder::new(&build_config.shell, cfg!(windows)).non_interactive();
118 let mut child = builder
119 .build_command(
120 Some("cargo".into()),
121 &build_config
122 .args
123 .iter()
124 .cloned()
125 .take_while(|arg| arg != "--")
126 .chain(Some("--message-format=json".to_owned()))
127 .collect::<Vec<_>>(),
128 )
129 .envs(build_config.env.iter().map(|(k, v)| (k.clone(), v.clone())))
130 .current_dir(cwd)
131 .stdout(Stdio::piped())
132 .spawn()?;
133
134 let mut output = String::new();
135 if let Some(mut stdout) = child.stdout.take() {
136 stdout.read_to_string(&mut output).await?;
137 }
138
139 let status = child.status().await?;
140 anyhow::ensure!(status.success(), "Cargo command failed");
141
142 let is_test = build_config
143 .args
144 .first()
145 .is_some_and(|arg| arg == "test" || arg == "t");
146
147 let is_ignored = build_config.args.contains(&"--include-ignored".to_owned());
148
149 let executables = output
150 .lines()
151 .filter(|line| !line.trim().is_empty())
152 .filter_map(|line| serde_json::from_str(line).ok())
153 .filter(|json: &Value| {
154 let is_test_binary = json
155 .get("profile")
156 .and_then(|profile| profile.get("test"))
157 .and_then(Value::as_bool)
158 .unwrap_or(false);
159
160 if is_test {
161 is_test_binary
162 } else {
163 !is_test_binary
164 }
165 })
166 .filter_map(|json: Value| {
167 json.get("executable")
168 .and_then(Value::as_str)
169 .map(String::from)
170 })
171 .collect::<Vec<_>>();
172 anyhow::ensure!(
173 !executables.is_empty(),
174 "Couldn't get executable in cargo locator"
175 );
176
177 let mut test_name = None;
178 if is_test {
179 test_name = build_config
180 .args
181 .iter()
182 .rev()
183 .take_while(|name| "--" != name.as_str())
184 .find(|name| !name.starts_with("-"))
185 .cloned();
186 }
187 let executable = {
188 if let Some(name) = test_name.as_ref().and_then(|name| {
189 name.strip_prefix('$')
190 .map(|name| build_config.env.get(name))
191 .unwrap_or(Some(name))
192 }) {
193 find_best_executable(&executables, name).await
194 } else {
195 None
196 }
197 };
198
199 let Some(executable) = executable.or_else(|| executables.first().cloned()) else {
200 anyhow::bail!("Couldn't get executable in cargo locator");
201 };
202
203 let mut args: Vec<_> = test_name.into_iter().collect();
204 if is_test {
205 args.push("--nocapture".to_owned());
206 if is_ignored {
207 args.push("--include-ignored".to_owned());
208 args.push("--exact".to_owned());
209 }
210 }
211
212 Ok(DebugRequest::Launch(task::LaunchRequest {
213 program: executable,
214 cwd: build_config.cwd,
215 args,
216 env: build_config.env.into_iter().collect(),
217 }))
218 }
219}