-
Notifications
You must be signed in to change notification settings - Fork 562
Expand file tree
/
Copy pathlib.rs
More file actions
529 lines (455 loc) · 18.3 KB
/
lib.rs
File metadata and controls
529 lines (455 loc) · 18.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
use std::collections::BTreeMap;
use std::fs;
use std::process::Command;
use anyhow::{bail, Context, Result};
use camino::{Utf8Path, Utf8PathBuf};
use log::debug;
use serde::Serialize;
use serde_json::Value;
pub struct BazelInfo {
pub output_base: String,
pub workspace: String,
}
fn bazel_command(bazel: &Utf8Path, workspace_root: &Utf8Path) -> Command {
let mut cmd = Command::new(bazel);
cmd.current_dir(workspace_root);
cmd
}
impl BazelInfo {
pub fn new(output_base: String, workspace: String) -> Self {
Self {
output_base,
workspace,
}
}
pub fn try_new(bazel: &Utf8Path, workspace_root: &Utf8Path) -> anyhow::Result<Self> {
let output = bazel_command(bazel, workspace_root)
.arg("info")
.output()
.context("Failed to execute 'bazel info'")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
bail!("bazel info failed: {}", stderr);
}
let info_map: BTreeMap<String, String> = String::from_utf8(output.stdout)?
.trim()
.lines()
.filter_map(|line| line.split_once(':'))
.map(|(k, v)| (k.to_owned(), v.trim().to_owned()))
.collect();
Ok(Self {
output_base: info_map
.get("output_base")
.context("Failed to query `bazel info output_base`")?
.clone(),
workspace: info_map
.get("workspace")
.context("Failed to query `bazel info workspace`")?
.clone(),
})
}
}
/// Information about a Bazel target for debugging.
#[derive(Debug, Clone)]
pub struct TargetInfo {
pub label: String,
pub binary_path: Utf8PathBuf,
pub is_test: bool,
pub target_kind: String,
}
/// VSCode launch configuration for debugging.
#[derive(Debug, Serialize)]
pub struct LaunchConfig {
pub name: String,
pub r#type: String,
pub request: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub program: Option<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub args: Vec<String>,
pub cwd: String,
#[serde(rename = "sourceLanguages")]
pub source_languages: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub env: Option<BTreeMap<String, String>>,
#[serde(
rename = "targetCreateCommands",
skip_serializing_if = "Option::is_none"
)]
pub target_create_commands: Option<Vec<String>>,
}
/// VSCode task configuration for building.
#[derive(Debug, Serialize)]
pub struct TaskConfig {
pub label: String,
pub r#type: String,
pub command: String,
pub args: Vec<String>,
pub group: String,
pub presentation: TaskPresentation,
#[serde(rename = "problemMatcher")]
pub problem_matcher: Vec<String>,
}
#[derive(Debug, Serialize)]
pub struct TaskPresentation {
pub reveal: String,
pub panel: String,
#[serde(rename = "showReuseMessage")]
pub show_reuse_message: bool,
pub clear: bool,
}
/// Generator for VSCode launch configurations.
pub struct LaunchConfigGenerator {
workspace_root: Utf8PathBuf,
bazel_binary: Utf8PathBuf,
bazel_info: BazelInfo,
}
impl LaunchConfigGenerator {
pub fn new(workspace_root: Utf8PathBuf, bazel_info: BazelInfo) -> Self {
Self {
workspace_root,
bazel_binary: "bazel".into(),
bazel_info,
}
}
pub fn with_bazel_binary(mut self, bazel: Utf8PathBuf) -> Self {
self.bazel_binary = bazel;
self
}
/// Query information about multiple targets at once.
pub fn query_targets_batch(&mut self, targets: &[String]) -> Result<Vec<TargetInfo>> {
if targets.is_empty() {
return Ok(vec![]);
}
// Get all target kinds in one query
let target_kinds = self.batch_query_target_kinds(targets)?;
let mut results = Vec::new();
for target in targets {
if let Some(target_kind) = target_kinds.get(target) {
let is_test = target_kind.contains("rust_test");
// We don't need to resolve binary paths now - that will happen at debug time
// Just create a placeholder path that will be resolved by the pre-launch task
results.push(TargetInfo {
label: target.to_string(),
binary_path: Utf8PathBuf::from(""), // Placeholder - resolved at debug time
is_test,
target_kind: target_kind.clone(),
});
}
}
Ok(results)
}
/// Batch query target kinds for multiple targets at once.
fn batch_query_target_kinds(&self, targets: &[String]) -> Result<BTreeMap<String, String>> {
let target_pattern = targets.join(" + ");
let output = bazel_command(&self.bazel_binary, &self.workspace_root)
.arg("query")
.arg("--output=label_kind")
.arg(&target_pattern)
.output()
.context("Failed to execute 'bazel query'")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
bail!("bazel query failed for targets: {}", stderr);
}
let stdout = String::from_utf8(output.stdout)?;
let mut result = BTreeMap::new();
for line in stdout.trim().lines() {
// Format: "rust_test rule //path/to:target"
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() >= 3 {
let kind = parts[0];
let label = parts[2];
if !kind.starts_with("rust_") {
// Skip non-Rust targets
continue;
}
result.insert(label.to_string(), kind.to_string());
}
}
Ok(result)
}
/// Execute a Bazel query and return the results.
fn execute_query(&self, query_expr: &str) -> Result<Vec<String>> {
debug!("Executing Bazel query: {}", query_expr);
let output = bazel_command(&self.bazel_binary, &self.workspace_root)
.arg("query")
.arg(query_expr)
.output()
.context("Failed to execute 'bazel query'")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
bail!("bazel query failed for '{}': {}", query_expr, stderr);
}
let targets = String::from_utf8(output.stdout)?
.lines()
.map(|line| line.trim().to_string())
.filter(|line| !line.is_empty())
.collect::<Vec<_>>();
debug!("Query returned {} targets", targets.len());
Ok(targets)
}
/// Find Rust targets using query patterns (similar to gen_rust_project approach).
/// Returns TargetInfo for all rust_binary and rust_test targets found.
pub fn find_rust_targets(&self, patterns: &[String]) -> Result<Vec<TargetInfo>> {
if patterns.is_empty() {
return Ok(vec![]);
}
let target_pattern = patterns.join(" + ");
let mut results = Vec::new();
// Query rust_binary targets
let binary_query = format!("kind('rust_binary', {})", target_pattern);
let binary_targets = self.execute_query(&binary_query)?;
for label in binary_targets {
results.push(TargetInfo {
label,
binary_path: Utf8PathBuf::from(""), // Placeholder - resolved at debug time
is_test: false,
target_kind: "rust_binary".to_string(),
});
}
// Query rust_test targets
let test_query = format!("kind('rust_test', {})", target_pattern);
let test_targets = self.execute_query(&test_query)?;
for label in test_targets {
results.push(TargetInfo {
label,
binary_path: Utf8PathBuf::from(""), // Placeholder - resolved at debug time
is_test: true,
target_kind: "rust_test".to_string(),
});
}
Ok(results)
}
/// Generate a launch configuration for a target.
pub fn generate_launch_config(&self, target_info: &TargetInfo) -> Result<LaunchConfig> {
let name = format!("Debug {}", target_info.label);
// Use CodeLLDB's "custom" request with Python scripting to build and get the binary path
// This consolidates everything into targetCreateCommands, no separate task needed
let target_create_commands = vec![
// Multi-line Python script that:
// 1. Runs bazel with --run_under to get the binary path
// 2. Parses stderr for the bazel-out path
// 3. Creates the debug target
"script ".to_owned() + &[
"import subprocess, os, sys".to_owned(),
format!("result = subprocess.run(['bazel', 'run', '--compilation_mode=dbg', '--strip=never', '--run_under=@rules_rust//tools/vscode:get_binary_path', '{}'], stderr=subprocess.PIPE, text=True, cwd='${{workspaceFolder}}')", target_info.label),
"binary_path = result.stderr.strip().splitlines()[-1]".to_owned(),
format!("assert binary_path, 'No binary path output for {}'", target_info.label),
"abs_path = os.path.join('${workspaceFolder}', binary_path)".to_owned(),
"lldb.debugger.CreateTarget(abs_path)".to_owned(),
].join("; ")
];
let mut config = LaunchConfig {
name,
r#type: "lldb".to_string(),
request: "custom".to_string(),
program: None,
args: vec![],
cwd: self.workspace_root.to_string(),
source_languages: vec!["rust".to_string()],
env: None,
target_create_commands: Some(target_create_commands),
};
// Add test environment if this is a test target
if target_info.is_test {
let test_env = self.generate_test_environment(&target_info.label);
config.env = Some(test_env);
}
Ok(config)
}
/// Sanitize target name for use in filenames.
fn sanitize_target_name(&self, target: &str) -> String {
target.replace("//", "").replace([':', '/'], "_")
}
/// Generate test environment variables based on Bazel test encyclopedia.
fn generate_test_environment(&self, target: &str) -> BTreeMap<String, String> {
let workspace_name = &self.bazel_info.workspace;
let mut env = BTreeMap::new();
let sanitized_name = self.sanitize_target_name(target);
let vscode_dir = self.workspace_root.join(".vscode");
// Core test environment variables from Bazel test encyclopedia
// https://bazel.build/reference/test-encyclopedia
env.insert("BAZEL_TEST".to_string(), "1".to_string());
env.insert("TEST_TARGET".to_string(), target.to_string());
env.insert("TEST_WORKSPACE".to_string(), workspace_name.clone());
// Test output directories (use .vscode subdirectories)
env.insert(
"TEST_TMPDIR".to_string(),
vscode_dir
.join(format!("bazel-test-tmp-{}", sanitized_name))
.to_string(),
);
env.insert(
"TEST_UNDECLARED_OUTPUTS_DIR".to_string(),
vscode_dir
.join(format!("bazel-test-outputs-{}", sanitized_name))
.to_string(),
);
env.insert(
"TEST_UNDECLARED_OUTPUTS_ANNOTATIONS_DIR".to_string(),
vscode_dir
.join(format!("bazel-test-annotations-{}", sanitized_name))
.to_string(),
);
// Rust-specific
env.insert("RUST_BACKTRACE".to_string(), "all".to_string());
env
}
/// Read existing launch.json file if it exists.
pub fn read_existing_launch_config(&self, path: &Utf8Path) -> Result<Option<Value>> {
if !path.exists() {
return Ok(None);
}
let content = fs::read_to_string(path)
.with_context(|| format!("Failed to read existing launch config from {}", path))?;
let config: Value = serde_json::from_str(&content)
.with_context(|| format!("Failed to parse existing launch config from {}", path))?;
Ok(Some(config))
}
/// Read existing tasks.json file if it exists.
pub fn read_existing_tasks_config(&self, path: &Utf8Path) -> Result<Option<Value>> {
if !path.exists() {
return Ok(None);
}
let content = fs::read_to_string(path)
.with_context(|| format!("Failed to read existing tasks config from {}", path))?;
let config: Value = serde_json::from_str(&content)
.with_context(|| format!("Failed to parse existing tasks config from {}", path))?;
Ok(Some(config))
}
/// Check if a configuration name matches our "Debug {label}" pattern and extract the label.
fn extract_debug_label(name: &str) -> Option<&str> {
name.strip_prefix("Debug ")
}
/// Check if a task name matches our "bazel-debug: build {label}" pattern and extract the label.
fn extract_build_task_label(name: &str) -> Option<&str> {
name.strip_prefix("bazel-debug: build ")
}
/// Filter out existing configurations that match our generated patterns.
fn filter_existing_configurations(
existing: &mut Value,
generated_targets: &[String],
) -> Result<()> {
if let Some(configurations) = existing.get_mut("configurations") {
if let Some(configs_array) = configurations.as_array_mut() {
configs_array.retain(|config| {
if let Some(name) = config.get("name").and_then(|v| v.as_str()) {
if let Some(label) = Self::extract_debug_label(name) {
// Check if this is a valid Bazel label that we're generating
if label::analyze(label).is_ok() {
// If it's in our list of targets to generate, remove it
return !generated_targets.contains(&label.to_string());
}
}
}
// Keep configurations that don't match our pattern
true
});
}
}
Ok(())
}
/// Filter out existing tasks that match our generated patterns.
fn filter_existing_tasks(existing: &mut Value, generated_targets: &[String]) -> Result<()> {
if let Some(tasks) = existing.get_mut("tasks") {
if let Some(tasks_array) = tasks.as_array_mut() {
tasks_array.retain(|task| {
if let Some(label) = task.get("label").and_then(|v| v.as_str()) {
if let Some(target_label) = Self::extract_build_task_label(label) {
// Check if this is a valid Bazel label that we're generating
if label::analyze(target_label).is_ok() {
// If it's in our list of targets to generate, remove it
return !generated_targets.contains(&target_label.to_string());
}
}
}
// Keep tasks that don't match our pattern
true
});
}
}
Ok(())
}
/// Merge new configurations with existing launch.json.
pub fn merge_launch_configs(
&self,
new_configs: &[LaunchConfig],
existing_path: &Utf8Path,
) -> Result<Value> {
let generated_targets: Vec<String> = new_configs
.iter()
.filter_map(|config| Self::extract_debug_label(&config.name))
.map(|s| s.to_string())
.collect();
let mut result =
if let Some(mut existing) = self.read_existing_launch_config(existing_path)? {
// Remove existing configurations for targets we're regenerating
Self::filter_existing_configurations(&mut existing, &generated_targets)?;
existing
} else {
// Create new launch.json structure
serde_json::json!({
"version": "0.2.0",
"configurations": []
})
};
// Add new configurations
if let Some(configurations) = result.get_mut("configurations") {
if let Some(configs_array) = configurations.as_array_mut() {
for config in new_configs {
configs_array.push(serde_json::to_value(config)?);
}
}
}
Ok(result)
}
/// Merge new tasks with existing tasks.json.
pub fn merge_tasks_configs(
&self,
new_tasks: &[TaskConfig],
existing_path: &Utf8Path,
) -> Result<Value> {
let generated_targets: Vec<String> = new_tasks
.iter()
.filter_map(|task| Self::extract_build_task_label(&task.label))
.map(|s| s.to_string())
.collect();
let mut result =
if let Some(mut existing) = self.read_existing_tasks_config(existing_path)? {
// Remove existing tasks for targets we're regenerating
Self::filter_existing_tasks(&mut existing, &generated_targets)?;
existing
} else {
// Create new tasks.json structure
serde_json::json!({
"version": "2.0.0",
"tasks": []
})
};
// Add new tasks
if let Some(tasks) = result.get_mut("tasks") {
if let Some(tasks_array) = tasks.as_array_mut() {
for task in new_tasks {
tasks_array.push(serde_json::to_value(task)?);
}
}
}
Ok(result)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_target_info_creation() {
let target_info = TargetInfo {
label: "//test:my_test".to_string(),
binary_path: "/path/to/binary".into(),
is_test: true,
target_kind: "rust_test rule".to_string(),
};
assert_eq!(target_info.label, "//test:my_test");
assert!(target_info.is_test);
}
}