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