blob: 68db7e088d9345e52ca5f7e4112dc21d17b7d81a [file] [log] [blame]
Brian Silvermancc09f182022-03-09 15:40:20 -08001use std::path::Path;
2use std::process::Command;
3
4use anyhow::anyhow;
5use runfiles::Runfiles;
6
7mod aquery;
8mod rust_project;
9
10const SYSROOT_SRC_FILE_RUNFILES_PREFIX: &str = "rules_rust";
11
12pub fn generate_crate_info(
13 bazel: impl AsRef<Path>,
14 workspace: impl AsRef<Path>,
15 rules_rust: impl AsRef<str>,
16 targets: &[String],
17) -> anyhow::Result<()> {
18 log::debug!("Building rust_analyzer_crate_spec files for {:?}", targets);
19
20 let output = Command::new(bazel.as_ref())
21 .current_dir(workspace.as_ref())
22 .arg("build")
23 .arg(format!(
24 "--aspects={}//rust:defs.bzl%rust_analyzer_aspect",
25 rules_rust.as_ref()
26 ))
27 .arg("--output_groups=rust_analyzer_crate_spec")
28 .args(targets)
29 .output()?;
30
31 if !output.status.success() {
32 return Err(anyhow!(
33 "bazel build failed:({})\n{}",
34 output.status,
35 String::from_utf8_lossy(&output.stderr)
36 ));
37 }
38
39 Ok(())
40}
41
42pub fn write_rust_project(
43 bazel: impl AsRef<Path>,
44 workspace: impl AsRef<Path>,
45 rules_rust_name: &impl AsRef<str>,
46 targets: &[String],
47 execution_root: impl AsRef<Path>,
48 rust_project_path: impl AsRef<Path>,
49) -> anyhow::Result<()> {
50 let crate_specs = aquery::get_crate_specs(
51 bazel.as_ref(),
52 workspace.as_ref(),
53 execution_root.as_ref(),
54 targets,
55 rules_rust_name.as_ref(),
56 )?;
57
58 let workspace_name = match rules_rust_name.as_ref().trim_start_matches('@') {
59 "" => SYSROOT_SRC_FILE_RUNFILES_PREFIX,
60 s => s,
61 };
62 let sysroot_path = format!(
63 "{}/rust/private/rust_analyzer_detect_sysroot.rust_analyzer_sysroot_src",
64 workspace_name
65 );
66 let r = Runfiles::create()?;
67 let path = r.rlocation(sysroot_path);
68 let sysroot_src = std::fs::read_to_string(&path)?;
69
70 let rust_project = rust_project::generate_rust_project(&sysroot_src, &crate_specs)?;
71
72 rust_project::write_rust_project(
73 rust_project_path.as_ref(),
74 execution_root.as_ref(),
75 &rust_project,
76 )?;
77
78 Ok(())
79}