1 // Copyright (C) 2022 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 //! Converts a cargo project to Soong.
16 //!
17 //! Forked from development/scripts/cargo2android.py. Missing many of its features. Adds various
18 //! features to make it easier to work with projects containing many crates.
19 //!
20 //! At a high level, this is done by
21 //!
22 //!     1. Running `cargo build -v` and saving the output to a "cargo.out" file.
23 //!     2. Parsing the "cargo.out" file to find invocations of compilers, e.g. `rustc` and `cc`.
24 //!     3. For each compiler invocation, generating a equivalent Soong module, e.g. a "rust_library".
25 //!
26 //! The last step often involves messy, project specific business logic, so many options are
27 //! available to tweak it via a config file.
28 
29 mod bp;
30 mod cargo;
31 mod config;
32 
33 use crate::config::Config;
34 use crate::config::PackageConfig;
35 use crate::config::PackageVariantConfig;
36 use crate::config::VariantConfig;
37 use anyhow::anyhow;
38 use anyhow::bail;
39 use anyhow::Context;
40 use anyhow::Result;
41 use bp::*;
42 use cargo::{
43     cargo_out::parse_cargo_out, metadata::parse_cargo_metadata_str, Crate, CrateType, ExternType,
44 };
45 use clap::Parser;
46 use clap::Subcommand;
47 use log::debug;
48 use nix::fcntl::OFlag;
49 use nix::unistd::pipe2;
50 use once_cell::sync::Lazy;
51 use std::collections::BTreeMap;
52 use std::collections::VecDeque;
53 use std::env;
54 use std::fs::{read_to_string, write, File};
55 use std::io::{Read, Write};
56 use std::path::Path;
57 use std::path::PathBuf;
58 use std::process::{Command, Stdio};
59 use tempfile::tempdir;
60 
61 // Major TODOs
62 //  * handle errors, esp. in cargo.out parsing. they should fail the program with an error code
63 //  * handle warnings. put them in comments in the android.bp, some kind of report section
64 
65 /// Rust modules which shouldn't use the default generated names, to avoid conflicts or confusion.
66 pub static RENAME_MAP: Lazy<BTreeMap<&str, &str>> = Lazy::new(|| {
67     [
68         ("libash", "libash_rust"),
69         ("libatomic", "libatomic_rust"),
70         ("libbacktrace", "libbacktrace_rust"),
71         ("libbase", "libbase_rust"),
72         ("libbase64", "libbase64_rust"),
73         ("libfuse", "libfuse_rust"),
74         ("libgcc", "libgcc_rust"),
75         ("liblog", "liblog_rust"),
76         ("libminijail", "libminijail_rust"),
77         ("libsync", "libsync_rust"),
78         ("libx86_64", "libx86_64_rust"),
79         ("libxml", "libxml_rust"),
80         ("protoc_gen_rust", "protoc-gen-rust"),
81     ]
82     .into_iter()
83     .collect()
84 });
85 
86 /// This map tracks Rust crates that have special rules.mk modules that were not
87 /// generated automatically by this script. Examples include compiler builtins
88 /// and other foundational libraries. It also tracks the location of rules.mk
89 /// build files for crates that are not under external/rust/crates.
90 pub static RULESMK_RENAME_MAP: Lazy<BTreeMap<&str, &str>> = Lazy::new(|| {
91     [
92         ("liballoc", "trusty/user/base/lib/liballoc-rust"),
93         ("libcompiler_builtins", "trusty/user/base/lib/libcompiler_builtins-rust"),
94         ("libcore", "trusty/user/base/lib/libcore-rust"),
95         ("libhashbrown", "trusty/user/base/lib/libhashbrown-rust"),
96         ("libpanic_abort", "trusty/user/base/lib/libpanic_abort-rust"),
97         ("libstd", "trusty/user/base/lib/libstd-rust"),
98         ("libstd_detect", "trusty/user/base/lib/libstd_detect-rust"),
99         ("libunwind", "trusty/user/base/lib/libunwind-rust"),
100     ]
101     .into_iter()
102     .collect()
103 });
104 
105 /// Given a proposed module name, returns `None` if it is blocked by the given config, or
106 /// else apply any name overrides and returns the name to use.
override_module_name( module_name: &str, blocklist: &[String], module_name_overrides: &BTreeMap<String, String>, rename_map: &BTreeMap<&str, &str>, ) -> Option<String>107 fn override_module_name(
108     module_name: &str,
109     blocklist: &[String],
110     module_name_overrides: &BTreeMap<String, String>,
111     rename_map: &BTreeMap<&str, &str>,
112 ) -> Option<String> {
113     if blocklist.iter().any(|blocked_name| blocked_name == module_name) {
114         None
115     } else if let Some(overridden_name) = module_name_overrides.get(module_name) {
116         Some(overridden_name.to_string())
117     } else if let Some(renamed) = rename_map.get(module_name) {
118         Some(renamed.to_string())
119     } else {
120         Some(module_name.to_string())
121     }
122 }
123 
124 /// Command-line parameters for `cargo_embargo`.
125 #[derive(Parser, Debug)]
126 struct Args {
127     /// Use the cargo binary in the `cargo_bin` directory. Defaults to using the Android prebuilt.
128     #[clap(long)]
129     cargo_bin: Option<PathBuf>,
130     /// Store `cargo build` output in this directory. If not set, a temporary directory is created and used.
131     #[clap(long)]
132     cargo_out_dir: Option<PathBuf>,
133     /// Skip the `cargo build` commands and reuse the "cargo.out" file from a previous run if
134     /// available. Requires setting --cargo_out_dir.
135     #[clap(long)]
136     reuse_cargo_out: bool,
137     #[command(subcommand)]
138     mode: Mode,
139 }
140 
141 #[derive(Clone, Debug, Subcommand)]
142 enum Mode {
143     /// Generates `Android.bp` files for the crates under the current directory using the given
144     /// config file.
145     Generate {
146         /// `cargo_embargo.json` config file to use.
147         config: PathBuf,
148     },
149     /// Dumps information about the crates to the given JSON file.
150     DumpCrates {
151         /// `cargo_embargo.json` config file to use.
152         config: PathBuf,
153         /// Path to `crates.json` to output.
154         crates: PathBuf,
155     },
156     /// Tries to automatically generate a suitable `cargo_embargo.json` config file for the package
157     /// in the current directory.
158     Autoconfig {
159         /// `cargo_embargo.json` config file to create.
160         config: PathBuf,
161     },
162 }
163 
main() -> Result<()>164 fn main() -> Result<()> {
165     env_logger::init();
166     let args = Args::parse();
167 
168     if args.reuse_cargo_out && args.cargo_out_dir.is_none() {
169         return Err(anyhow!("Must specify --cargo_out_dir with --reuse_cargo_out"));
170     }
171     let tempdir = tempdir()?;
172     let intermediates_dir = args.cargo_out_dir.as_deref().unwrap_or(tempdir.path());
173 
174     match &args.mode {
175         Mode::DumpCrates { config, crates } => {
176             dump_crates(&args, config, crates, intermediates_dir)?;
177         }
178         Mode::Generate { config } => {
179             run_embargo(&args, config, intermediates_dir)?;
180         }
181         Mode::Autoconfig { config } => {
182             autoconfig(&args, config, intermediates_dir)?;
183         }
184     }
185 
186     Ok(())
187 }
188 
189 /// Runs cargo_embargo with the given JSON configuration string, but dumps the crate data to the
190 /// given `crates.json` file rather than generating an `Android.bp`.
dump_crates( args: &Args, config_filename: &Path, crates_filename: &Path, intermediates_dir: &Path, ) -> Result<()>191 fn dump_crates(
192     args: &Args,
193     config_filename: &Path,
194     crates_filename: &Path,
195     intermediates_dir: &Path,
196 ) -> Result<()> {
197     let cfg = Config::from_file(config_filename)?;
198     let crates = make_all_crates(args, &cfg, intermediates_dir)?;
199     serde_json::to_writer(
200         File::create(crates_filename)
201             .with_context(|| format!("Failed to create {:?}", crates_filename))?,
202         &crates,
203     )?;
204     Ok(())
205 }
206 
207 /// Tries to automatically generate a suitable `cargo_embargo.json` for the package in the current
208 /// directory.
autoconfig(args: &Args, config_filename: &Path, intermediates_dir: &Path) -> Result<()>209 fn autoconfig(args: &Args, config_filename: &Path, intermediates_dir: &Path) -> Result<()> {
210     println!("Trying default config with tests...");
211     let mut config_with_build = Config {
212         variants: vec![VariantConfig { tests: true, ..Default::default() }],
213         package: Default::default(),
214     };
215     let mut crates_with_build = make_all_crates(args, &config_with_build, intermediates_dir)?;
216 
217     let has_tests =
218         crates_with_build[0].iter().any(|c| c.types.contains(&CrateType::Test) && !c.empty_test);
219     if !has_tests {
220         println!("No tests, removing from config.");
221         config_with_build =
222             Config { variants: vec![Default::default()], package: Default::default() };
223         crates_with_build = make_all_crates(args, &config_with_build, intermediates_dir)?;
224     }
225 
226     println!("Trying without cargo build...");
227     let config_no_build = Config {
228         variants: vec![VariantConfig { run_cargo: false, tests: has_tests, ..Default::default() }],
229         package: Default::default(),
230     };
231     let crates_without_build = make_all_crates(args, &config_no_build, intermediates_dir)?;
232 
233     let config = if crates_with_build == crates_without_build {
234         println!("Output without build was the same, using that.");
235         config_no_build
236     } else {
237         println!("Output without build was different. Need to run cargo build.");
238         println!("With build: {}", serde_json::to_string_pretty(&crates_with_build)?);
239         println!("Without build: {}", serde_json::to_string_pretty(&crates_without_build)?);
240         config_with_build
241     };
242     write(config_filename, format!("{}\n", config.to_json_string()?))?;
243     println!(
244         "Wrote config to {0}. Run `cargo_embargo generate {0}` to use it.",
245         config_filename.to_string_lossy()
246     );
247 
248     Ok(())
249 }
250 
251 /// Finds the path to the directory containing the Android prebuilt Rust toolchain.
find_android_rust_toolchain() -> Result<PathBuf>252 fn find_android_rust_toolchain() -> Result<PathBuf> {
253     let platform_rustfmt = if cfg!(all(target_arch = "x86_64", target_os = "linux")) {
254         "linux-x86/stable/rustfmt"
255     } else if cfg!(all(target_arch = "x86_64", target_os = "macos")) {
256         "darwin-x86/stable/rustfmt"
257     } else if cfg!(all(target_arch = "x86_64", target_os = "windows")) {
258         "windows-x86/stable/rustfmt.exe"
259     } else {
260         bail!("No prebuilt Rust toolchain available for this platform.");
261     };
262 
263     let android_top = env::var("ANDROID_BUILD_TOP")
264         .context("ANDROID_BUILD_TOP was not set. Did you forget to run envsetup.sh?")?;
265     let stable_rustfmt = [android_top.as_str(), "prebuilts", "rust", platform_rustfmt]
266         .into_iter()
267         .collect::<PathBuf>();
268     let canonical_rustfmt = stable_rustfmt.canonicalize()?;
269     Ok(canonical_rustfmt.parent().unwrap().to_owned())
270 }
271 
272 /// Adds the given path to the start of the `PATH` environment variable.
add_to_path(extra_path: PathBuf) -> Result<()>273 fn add_to_path(extra_path: PathBuf) -> Result<()> {
274     let path = env::var_os("PATH").unwrap();
275     let mut paths = env::split_paths(&path).collect::<VecDeque<_>>();
276     paths.push_front(extra_path);
277     let new_path = env::join_paths(paths)?;
278     debug!("Set PATH to {:?}", new_path);
279     std::env::set_var("PATH", new_path);
280     Ok(())
281 }
282 
283 /// Calls make_crates for each variant in the given config.
make_all_crates(args: &Args, cfg: &Config, intermediates_dir: &Path) -> Result<Vec<Vec<Crate>>>284 fn make_all_crates(args: &Args, cfg: &Config, intermediates_dir: &Path) -> Result<Vec<Vec<Crate>>> {
285     cfg.variants.iter().map(|variant| make_crates(args, variant, intermediates_dir)).collect()
286 }
287 
make_crates(args: &Args, cfg: &VariantConfig, intermediates_dir: &Path) -> Result<Vec<Crate>>288 fn make_crates(args: &Args, cfg: &VariantConfig, intermediates_dir: &Path) -> Result<Vec<Crate>> {
289     if !Path::new("Cargo.toml").try_exists().context("when checking Cargo.toml")? {
290         bail!("Cargo.toml missing. Run in a directory with a Cargo.toml file.");
291     }
292 
293     // Add the custom cargo to PATH.
294     // NOTE: If the directory with cargo has more binaries, this could have some unpredictable side
295     // effects. That is partly intended though, because we want to use that cargo binary's
296     // associated rustc.
297     let cargo_bin = if let Some(cargo_bin) = &args.cargo_bin {
298         cargo_bin.to_owned()
299     } else {
300         // Find the Android prebuilt.
301         find_android_rust_toolchain()?
302     };
303     add_to_path(cargo_bin)?;
304 
305     let cargo_out_path = intermediates_dir.join("cargo.out");
306     let cargo_metadata_path = intermediates_dir.join("cargo.metadata");
307     let cargo_output = if args.reuse_cargo_out && cargo_out_path.exists() {
308         CargoOutput {
309             cargo_out: read_to_string(cargo_out_path)?,
310             cargo_metadata: read_to_string(cargo_metadata_path)?,
311         }
312     } else {
313         let cargo_output =
314             generate_cargo_out(cfg, intermediates_dir).context("generate_cargo_out failed")?;
315         if cfg.run_cargo {
316             write(cargo_out_path, &cargo_output.cargo_out)?;
317         }
318         write(cargo_metadata_path, &cargo_output.cargo_metadata)?;
319         cargo_output
320     };
321 
322     if cfg.run_cargo {
323         parse_cargo_out(&cargo_output).context("parse_cargo_out failed")
324     } else {
325         parse_cargo_metadata_str(&cargo_output.cargo_metadata, cfg)
326     }
327 }
328 
329 /// Runs cargo_embargo with the given JSON configuration file.
run_embargo(args: &Args, config_filename: &Path, intermediates_dir: &Path) -> Result<()>330 fn run_embargo(args: &Args, config_filename: &Path, intermediates_dir: &Path) -> Result<()> {
331     let intermediates_glob = intermediates_dir
332         .to_str()
333         .ok_or(anyhow!("Failed to convert intermediate dir path to string"))?
334         .to_string()
335         + "target.tmp/**/build/*/out/*";
336 
337     let cfg = Config::from_file(config_filename)?;
338     let crates = make_all_crates(args, &cfg, intermediates_dir)?;
339 
340     // TODO: Use different directories for different variants.
341     // Find out files.
342     // Example: target.tmp/x86_64-unknown-linux-gnu/debug/build/metrics-d2dd799cebf1888d/out/event_details.rs
343     let num_variants = cfg.variants.len();
344     let mut package_out_files: BTreeMap<String, Vec<Vec<PathBuf>>> = BTreeMap::new();
345     for (variant_index, variant_cfg) in cfg.variants.iter().enumerate() {
346         if variant_cfg.package.iter().any(|(_, v)| v.copy_out) {
347             for entry in glob::glob(&intermediates_glob)? {
348                 match entry {
349                     Ok(path) => {
350                         let package_name = || -> Option<_> {
351                             let dir_name = path.parent()?.parent()?.file_name()?.to_str()?;
352                             Some(dir_name.rsplit_once('-')?.0)
353                         }()
354                         .unwrap_or_else(|| panic!("failed to parse out file path: {:?}", path));
355                         package_out_files
356                             .entry(package_name.to_string())
357                             .or_insert_with(|| vec![vec![]; num_variants])[variant_index]
358                             .push(path.clone());
359                     }
360                     Err(e) => eprintln!("failed to check for out files: {}", e),
361                 }
362             }
363         }
364     }
365 
366     // If we were configured to run cargo, check whether we could have got away without it.
367     if cfg.variants.iter().any(|variant| variant.run_cargo) && package_out_files.is_empty() {
368         let mut cfg_no_cargo = cfg.clone();
369         for variant in &mut cfg_no_cargo.variants {
370             variant.run_cargo = false;
371         }
372         let crates_no_cargo = make_all_crates(args, &cfg_no_cargo, intermediates_dir)?;
373         if crates_no_cargo == crates {
374             eprintln!("Running cargo appears to be unnecessary for this crate, consider adding `\"run_cargo\": false` to your cargo_embargo.json.");
375         }
376     }
377 
378     write_all_build_files(&cfg, crates, &package_out_files)
379 }
380 
381 /// Input is indexed by variant, then all crates for that variant.
382 /// Output is a map from package directory to a list of variants, with all crates for that package
383 /// and variant.
group_by_package(crates: Vec<Vec<Crate>>) -> BTreeMap<PathBuf, Vec<Vec<Crate>>>384 fn group_by_package(crates: Vec<Vec<Crate>>) -> BTreeMap<PathBuf, Vec<Vec<Crate>>> {
385     let mut module_by_package: BTreeMap<PathBuf, Vec<Vec<Crate>>> = BTreeMap::new();
386 
387     let num_variants = crates.len();
388     for (i, variant_crates) in crates.into_iter().enumerate() {
389         for c in variant_crates {
390             let package_variants = module_by_package
391                 .entry(c.package_dir.clone())
392                 .or_insert_with(|| vec![vec![]; num_variants]);
393             package_variants[i].push(c);
394         }
395     }
396     module_by_package
397 }
398 
write_all_build_files( cfg: &Config, crates: Vec<Vec<Crate>>, package_out_files: &BTreeMap<String, Vec<Vec<PathBuf>>>, ) -> Result<()>399 fn write_all_build_files(
400     cfg: &Config,
401     crates: Vec<Vec<Crate>>,
402     package_out_files: &BTreeMap<String, Vec<Vec<PathBuf>>>,
403 ) -> Result<()> {
404     // Group by package.
405     let module_by_package = group_by_package(crates);
406 
407     let num_variants = cfg.variants.len();
408     let empty_package_out_files = vec![vec![]; num_variants];
409     let mut has_error = false;
410     // Write a build file per package.
411     for (package_dir, crates) in module_by_package {
412         let package_name = &crates.iter().flatten().next().unwrap().package_name;
413         if let Err(e) = write_build_files(
414             cfg,
415             package_name,
416             package_dir,
417             &crates,
418             package_out_files.get(package_name).unwrap_or(&empty_package_out_files),
419         ) {
420             // print the error, but continue to accumulate all of the errors
421             eprintln!("ERROR: {:#}", e);
422             has_error = true;
423         }
424     }
425     if has_error {
426         panic!("Encountered fatal errors that must be fixed.");
427     }
428 
429     Ok(())
430 }
431 
432 /// Runs the given command, and returns its standard output and standard error as a string.
run_cargo(cmd: &mut Command) -> Result<String>433 fn run_cargo(cmd: &mut Command) -> Result<String> {
434     let (pipe_read, pipe_write) = pipe2(OFlag::O_CLOEXEC)?;
435     cmd.stdout(pipe_write.try_clone()?).stderr(pipe_write).stdin(Stdio::null());
436     debug!("Running: {:?}\n", cmd);
437     let mut child = cmd.spawn()?;
438 
439     // Unset the stdout and stderr for the command so that they are dropped in this process.
440     // Otherwise the `read_to_string` below will block forever as there is still an open write file
441     // descriptor for the pipe even after the child finishes.
442     cmd.stderr(Stdio::null()).stdout(Stdio::null());
443 
444     let mut output = String::new();
445     File::from(pipe_read).read_to_string(&mut output)?;
446     let status = child.wait()?;
447     if !status.success() {
448         bail!(
449             "cargo command `{:?}` failed with exit status: {:?}.\nOutput: \n------\n{}\n------",
450             cmd,
451             status,
452             output
453         );
454     }
455 
456     Ok(output)
457 }
458 
459 /// The raw output from running `cargo metadata`, `cargo build` and other commands.
460 #[derive(Clone, Debug, Eq, PartialEq)]
461 pub struct CargoOutput {
462     cargo_metadata: String,
463     cargo_out: String,
464 }
465 
466 /// Run various cargo commands and returns the output.
generate_cargo_out(cfg: &VariantConfig, intermediates_dir: &Path) -> Result<CargoOutput>467 fn generate_cargo_out(cfg: &VariantConfig, intermediates_dir: &Path) -> Result<CargoOutput> {
468     let verbose_args = ["-v"];
469     let target_dir = intermediates_dir.join("target.tmp");
470 
471     // cargo clean
472     run_cargo(Command::new("cargo").arg("clean").arg("--target-dir").arg(&target_dir))
473         .context("Running cargo clean")?;
474 
475     let default_target = "x86_64-unknown-linux-gnu";
476     let feature_args = if let Some(features) = &cfg.features {
477         if features.is_empty() {
478             vec!["--no-default-features".to_string()]
479         } else {
480             vec!["--no-default-features".to_string(), "--features".to_string(), features.join(",")]
481         }
482     } else {
483         vec![]
484     };
485 
486     let workspace_args = if cfg.workspace {
487         let mut v = vec!["--workspace".to_string()];
488         if !cfg.workspace_excludes.is_empty() {
489             for x in cfg.workspace_excludes.iter() {
490                 v.push("--exclude".to_string());
491                 v.push(x.clone());
492             }
493         }
494         v
495     } else {
496         vec![]
497     };
498 
499     // cargo metadata
500     let cargo_metadata = run_cargo(
501         Command::new("cargo")
502             .arg("metadata")
503             .arg("-q") // don't output warnings to stderr
504             .arg("--format-version")
505             .arg("1")
506             .args(&feature_args),
507     )
508     .context("Running cargo metadata")?;
509 
510     let mut cargo_out = String::new();
511     if cfg.run_cargo {
512         let envs = if cfg.extra_cfg.is_empty() {
513             vec![]
514         } else {
515             vec![(
516                 "RUSTFLAGS",
517                 cfg.extra_cfg
518                     .iter()
519                     .map(|cfg_flag| format!("--cfg {}", cfg_flag))
520                     .collect::<Vec<_>>()
521                     .join(" "),
522             )]
523         };
524 
525         // cargo build
526         cargo_out += &run_cargo(
527             Command::new("cargo")
528                 .envs(envs.clone())
529                 .args(["build", "--target", default_target])
530                 .args(verbose_args)
531                 .arg("--target-dir")
532                 .arg(&target_dir)
533                 .args(&workspace_args)
534                 .args(&feature_args),
535         )?;
536 
537         if cfg.tests {
538             // cargo build --tests
539             cargo_out += &run_cargo(
540                 Command::new("cargo")
541                     .envs(envs.clone())
542                     .args(["build", "--target", default_target, "--tests"])
543                     .args(verbose_args)
544                     .arg("--target-dir")
545                     .arg(&target_dir)
546                     .args(&workspace_args)
547                     .args(&feature_args),
548             )?;
549             // cargo test -- --list
550             cargo_out += &run_cargo(
551                 Command::new("cargo")
552                     .envs(envs)
553                     .args(["test", "--target", default_target])
554                     .arg("--target-dir")
555                     .arg(&target_dir)
556                     .args(&workspace_args)
557                     .args(&feature_args)
558                     .args(["--", "--list"]),
559             )?;
560         }
561     }
562 
563     Ok(CargoOutput { cargo_metadata, cargo_out })
564 }
565 
566 /// Read and return license and other header lines from a build file.
567 ///
568 /// Skips initial comment lines, then returns all lines before the first line
569 /// starting with `rust_`, `genrule {`, or `LOCAL_DIR`.
570 ///
571 /// If `path` could not be read, return a placeholder license TODO line.
read_license_header(path: &Path) -> Result<String>572 fn read_license_header(path: &Path) -> Result<String> {
573     // Keep the old license header.
574     match std::fs::read_to_string(path) {
575         Ok(s) => Ok(s
576             .lines()
577             .skip_while(|l| l.starts_with("//") || l.starts_with('#'))
578             .take_while(|l| {
579                 !l.starts_with("rust_")
580                     && !l.starts_with("genrule {")
581                     && !l.starts_with("LOCAL_DIR")
582             })
583             .collect::<Vec<&str>>()
584             .join("\n")),
585         Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
586             Ok("// DO NOT SUBMIT: Add license before submitting.\n".to_string())
587         }
588         Err(e) => Err(anyhow!("error when reading {path:?}: {e}")),
589     }
590 }
591 
592 /// Create the build file for `package_dir`.
593 ///
594 /// `crates` and `out_files` are both indexed by variant.
write_build_files( cfg: &Config, package_name: &str, package_dir: PathBuf, crates: &[Vec<Crate>], out_files: &[Vec<PathBuf>], ) -> Result<()>595 fn write_build_files(
596     cfg: &Config,
597     package_name: &str,
598     package_dir: PathBuf,
599     crates: &[Vec<Crate>],
600     out_files: &[Vec<PathBuf>],
601 ) -> Result<()> {
602     assert_eq!(crates.len(), out_files.len());
603 
604     let mut bp_contents = String::new();
605     let mut mk_contents = String::new();
606     for (variant_index, variant_config) in cfg.variants.iter().enumerate() {
607         let variant_crates = &crates[variant_index];
608         let def = PackageVariantConfig::default();
609         let package_cfg = variant_config.package.get(package_name).unwrap_or(&def);
610 
611         // If `copy_out` is enabled and there are any generated out files for the package, copy them to
612         // the appropriate directory.
613         if package_cfg.copy_out && !out_files[variant_index].is_empty() {
614             let out_dir = package_dir.join("out");
615             if !out_dir.exists() {
616                 std::fs::create_dir(&out_dir).expect("failed to create out dir");
617             }
618 
619             for f in out_files[variant_index].iter() {
620                 let dest = out_dir.join(f.file_name().unwrap());
621                 std::fs::copy(f, dest).expect("failed to copy out file");
622             }
623         }
624 
625         if variant_config.generate_androidbp {
626             bp_contents += &generate_android_bp(
627                 variant_config,
628                 package_cfg,
629                 package_name,
630                 variant_crates,
631                 &out_files[variant_index],
632             )?;
633         }
634         if variant_config.generate_rulesmk {
635             mk_contents += &generate_rules_mk(
636                 variant_config,
637                 package_cfg,
638                 package_name,
639                 variant_crates,
640                 &out_files[variant_index],
641             )?;
642         }
643     }
644 
645     let def = PackageConfig::default();
646     let package_cfg = cfg.package.get(package_name).unwrap_or(&def);
647     if let Some(path) = &package_cfg.add_toplevel_block {
648         bp_contents +=
649             &std::fs::read_to_string(path).with_context(|| format!("failed to read {path:?}"))?;
650         bp_contents += "\n";
651     }
652     if !bp_contents.is_empty() {
653         let output_path = package_dir.join("Android.bp");
654         let bp_contents = "// This file is generated by cargo_embargo.\n".to_owned()
655             + "// Do not modify this file after the first \"rust_*\" or \"genrule\" module\n"
656             + "// because the changes will be overridden on upgrade.\n"
657             + "// Content before the first \"rust_*\" or \"genrule\" module is preserved.\n\n"
658             + read_license_header(&output_path)?.trim()
659             + "\n"
660             + &bp_contents;
661         write_format_android_bp(&output_path, &bp_contents, package_cfg.patch.as_deref())?;
662     }
663     if !mk_contents.is_empty() {
664         let output_path = package_dir.join("rules.mk");
665         let mk_contents = "# This file is generated by cargo_embargo.\n".to_owned()
666             + "# Do not modify this file after the LOCAL_DIR line\n"
667             + "# because the changes will be overridden on upgrade.\n"
668             + "# Content before the first line starting with LOCAL_DIR is preserved.\n"
669             + read_license_header(&output_path)?.trim()
670             + "\n"
671             + &mk_contents;
672         File::create(&output_path)?.write_all(mk_contents.as_bytes())?;
673         if let Some(patch) = package_cfg.rulesmk_patch.as_deref() {
674             apply_patch_file(&output_path, patch)?;
675         }
676     }
677 
678     Ok(())
679 }
680 
681 /// Generates and returns a Soong Blueprint for the given set of crates, for a single variant of a
682 /// package.
generate_android_bp( cfg: &VariantConfig, package_cfg: &PackageVariantConfig, package_name: &str, crates: &[Crate], out_files: &[PathBuf], ) -> Result<String>683 fn generate_android_bp(
684     cfg: &VariantConfig,
685     package_cfg: &PackageVariantConfig,
686     package_name: &str,
687     crates: &[Crate],
688     out_files: &[PathBuf],
689 ) -> Result<String> {
690     let mut bp_contents = String::new();
691 
692     let mut modules = Vec::new();
693 
694     let extra_srcs = if package_cfg.copy_out && !out_files.is_empty() {
695         let outs: Vec<String> = out_files
696             .iter()
697             .map(|f| f.file_name().unwrap().to_str().unwrap().to_string())
698             .collect();
699 
700         let mut m = BpModule::new("genrule".to_string());
701         if let Some(module_name) = override_module_name(
702             &format!("copy_{}_build_out", package_name),
703             &cfg.module_blocklist,
704             &cfg.module_name_overrides,
705             &RENAME_MAP,
706         ) {
707             m.props.set("name", module_name.clone());
708             m.props.set("srcs", vec!["out/*"]);
709             m.props.set("cmd", "cp $(in) $(genDir)");
710             m.props.set("out", outs);
711             modules.push(m);
712 
713             vec![":".to_string() + &module_name]
714         } else {
715             vec![]
716         }
717     } else {
718         vec![]
719     };
720 
721     for c in crates {
722         modules.extend(crate_to_bp_modules(c, cfg, package_cfg, &extra_srcs).with_context(
723             || {
724                 format!(
725                     "failed to generate bp module for crate \"{}\" with package name \"{}\"",
726                     c.name, c.package_name
727                 )
728             },
729         )?);
730     }
731 
732     // In some cases there are nearly identical rustc invocations that that get processed into
733     // identical BP modules. So far, dedup'ing them is a good enough fix. At some point we might
734     // need something more complex, maybe like cargo2android's logic for merging crates.
735     modules.sort();
736     modules.dedup();
737 
738     modules.sort_by_key(|m| m.props.get_string("name").to_string());
739     for m in modules {
740         m.write(&mut bp_contents)?;
741         bp_contents += "\n";
742     }
743     Ok(bp_contents)
744 }
745 
746 /// Generates and returns a Trusty rules.mk file for the given set of crates.
generate_rules_mk( cfg: &VariantConfig, package_cfg: &PackageVariantConfig, package_name: &str, crates: &[Crate], out_files: &[PathBuf], ) -> Result<String>747 fn generate_rules_mk(
748     cfg: &VariantConfig,
749     package_cfg: &PackageVariantConfig,
750     package_name: &str,
751     crates: &[Crate],
752     out_files: &[PathBuf],
753 ) -> Result<String> {
754     let out_files = if package_cfg.copy_out && !out_files.is_empty() {
755         out_files.iter().map(|f| f.file_name().unwrap().to_str().unwrap().to_string()).collect()
756     } else {
757         vec![]
758     };
759 
760     let crates: Vec<_> = crates
761         .iter()
762         .filter(|c| {
763             if c.types.contains(&CrateType::Bin) {
764                 eprintln!("WARNING: skipped generation of rules.mk for binary crate: {}", c.name);
765                 false
766             } else if c.types.iter().any(|t| t.is_test()) {
767                 // Test build file generation is not yet implemented
768                 eprintln!("WARNING: skipped generation of rules.mk for test crate: {}", c.name);
769                 false
770             } else {
771                 true
772             }
773         })
774         .collect();
775     let [crate_] = &crates[..] else {
776         bail!(
777             "Expected exactly one library crate for package {package_name} when generating \
778                rules.mk, found: {crates:?}"
779         );
780     };
781     crate_to_rulesmk(crate_, cfg, package_cfg, &out_files).with_context(|| {
782         format!(
783             "failed to generate rules.mk for crate \"{}\" with package name \"{}\"",
784             crate_.name, crate_.package_name
785         )
786     })
787 }
788 
789 /// Apply patch from `patch_path` to file `output_path`.
790 ///
791 /// Warns but still returns ok if the patch did not cleanly apply,
apply_patch_file(output_path: &Path, patch_path: &Path) -> Result<()>792 fn apply_patch_file(output_path: &Path, patch_path: &Path) -> Result<()> {
793     let patch_output = Command::new("patch")
794         .arg("-s")
795         .arg(output_path)
796         .arg(patch_path)
797         .output()
798         .context("Running patch")?;
799     if !patch_output.status.success() {
800         // These errors will cause the cargo_embargo command to fail, but not yet!
801         return Err(anyhow!("failed to apply patch {patch_path:?}"));
802     }
803     Ok(())
804 }
805 
806 /// Writes the given contents to the given `Android.bp` file, formats it with `bpfmt`, and applies
807 /// the patch if there is one.
write_format_android_bp( bp_path: &Path, bp_contents: &str, patch_path: Option<&Path>, ) -> Result<()>808 fn write_format_android_bp(
809     bp_path: &Path,
810     bp_contents: &str,
811     patch_path: Option<&Path>,
812 ) -> Result<()> {
813     File::create(bp_path)?.write_all(bp_contents.as_bytes())?;
814 
815     let bpfmt_output =
816         Command::new("bpfmt").arg("-w").arg(bp_path).output().context("Running bpfmt")?;
817     if !bpfmt_output.status.success() {
818         eprintln!(
819             "WARNING: bpfmt -w {:?} failed before patch: {}",
820             bp_path,
821             String::from_utf8_lossy(&bpfmt_output.stderr)
822         );
823     }
824 
825     if let Some(patch_path) = patch_path {
826         apply_patch_file(bp_path, patch_path)?;
827         // Re-run bpfmt after the patch so
828         let bpfmt_output = Command::new("bpfmt")
829             .arg("-w")
830             .arg(bp_path)
831             .output()
832             .context("Running bpfmt after patch")?;
833         if !bpfmt_output.status.success() {
834             eprintln!(
835                 "WARNING: bpfmt -w {:?} failed after patch: {}",
836                 bp_path,
837                 String::from_utf8_lossy(&bpfmt_output.stderr)
838             );
839         }
840     }
841 
842     Ok(())
843 }
844 
845 /// Convert a `Crate` into `BpModule`s.
846 ///
847 /// If messy business logic is necessary, prefer putting it here.
crate_to_bp_modules( crate_: &Crate, cfg: &VariantConfig, package_cfg: &PackageVariantConfig, extra_srcs: &[String], ) -> Result<Vec<BpModule>>848 fn crate_to_bp_modules(
849     crate_: &Crate,
850     cfg: &VariantConfig,
851     package_cfg: &PackageVariantConfig,
852     extra_srcs: &[String],
853 ) -> Result<Vec<BpModule>> {
854     let mut modules = Vec::new();
855     for crate_type in &crate_.types {
856         let host = if package_cfg.device_supported { "" } else { "_host" };
857         let rlib = if package_cfg.force_rlib { "_rlib" } else { "" };
858         let (module_type, module_name) = match crate_type {
859             CrateType::Bin => ("rust_binary".to_string() + host, crate_.name.clone()),
860             CrateType::Lib | CrateType::RLib => {
861                 let stem = "lib".to_string() + &crate_.name;
862                 ("rust_library".to_string() + host + rlib, stem)
863             }
864             CrateType::DyLib => {
865                 let stem = "lib".to_string() + &crate_.name;
866                 ("rust_library".to_string() + host + "_dylib", stem + "_dylib")
867             }
868             CrateType::CDyLib => {
869                 let stem = "lib".to_string() + &crate_.name;
870                 ("rust_ffi".to_string() + host + "_shared", stem + "_shared")
871             }
872             CrateType::StaticLib => {
873                 let stem = "lib".to_string() + &crate_.name;
874                 ("rust_ffi".to_string() + host + "_static", stem + "_static")
875             }
876             CrateType::ProcMacro => {
877                 let stem = "lib".to_string() + &crate_.name;
878                 ("rust_proc_macro".to_string(), stem)
879             }
880             CrateType::Test | CrateType::TestNoHarness => {
881                 let suffix = crate_.main_src.to_string_lossy().into_owned();
882                 let suffix = suffix.replace('/', "_").replace(".rs", "");
883                 let stem = crate_.package_name.clone() + "_test_" + &suffix;
884                 if crate_.empty_test {
885                     return Ok(Vec::new());
886                 }
887                 if crate_type == &CrateType::TestNoHarness {
888                     eprintln!(
889                         "WARNING: ignoring test \"{}\" with harness=false. not supported yet",
890                         stem
891                     );
892                     return Ok(Vec::new());
893                 }
894                 ("rust_test".to_string() + host, stem)
895             }
896         };
897 
898         let mut m = BpModule::new(module_type.clone());
899         let Some(module_name) = override_module_name(
900             &module_name,
901             &cfg.module_blocklist,
902             &cfg.module_name_overrides,
903             &RENAME_MAP,
904         ) else {
905             continue;
906         };
907         if matches!(
908             crate_type,
909             CrateType::Lib
910                 | CrateType::RLib
911                 | CrateType::DyLib
912                 | CrateType::CDyLib
913                 | CrateType::StaticLib
914         ) && !module_name.starts_with(&format!("lib{}", crate_.name))
915         {
916             bail!("Module name must start with lib{} but was {}", crate_.name, module_name);
917         }
918         m.props.set("name", module_name.clone());
919 
920         if let Some(defaults) = &cfg.global_defaults {
921             m.props.set("defaults", vec![defaults.clone()]);
922         }
923 
924         if package_cfg.host_supported
925             && package_cfg.device_supported
926             && module_type != "rust_proc_macro"
927         {
928             m.props.set("host_supported", true);
929         }
930 
931         if !crate_type.is_test() && package_cfg.host_supported && package_cfg.host_first_multilib {
932             m.props.set("compile_multilib", "first");
933         }
934         if crate_type.is_c_library() {
935             m.props.set_if_nonempty("include_dirs", package_cfg.exported_c_header_dir.clone());
936         }
937 
938         m.props.set("crate_name", crate_.name.clone());
939         m.props.set("cargo_env_compat", true);
940 
941         if let Some(version) = &crate_.version {
942             m.props.set("cargo_pkg_version", version.clone());
943         }
944 
945         if crate_.types.contains(&CrateType::Test) {
946             m.props.set("test_suites", vec!["general-tests"]);
947             m.props.set("auto_gen_config", true);
948             if package_cfg.host_supported {
949                 m.props.object("test_options").set("unit_test", !package_cfg.no_presubmit);
950             }
951         }
952 
953         m.props.set("crate_root", crate_.main_src.clone());
954         m.props.set_if_nonempty("srcs", extra_srcs.to_owned());
955 
956         m.props.set("edition", crate_.edition.clone());
957         m.props.set_if_nonempty("features", crate_.features.clone());
958         m.props.set_if_nonempty(
959             "cfgs",
960             crate_
961                 .cfgs
962                 .clone()
963                 .into_iter()
964                 .filter(|crate_cfg| !cfg.cfg_blocklist.contains(crate_cfg))
965                 .collect(),
966         );
967 
968         let mut flags = Vec::new();
969         if !crate_.cap_lints.is_empty() {
970             flags.push(crate_.cap_lints.clone());
971         }
972         flags.extend(crate_.codegens.iter().map(|codegen| format!("-C {}", codegen)));
973         m.props.set_if_nonempty("flags", flags);
974 
975         let mut rust_libs = Vec::new();
976         let mut proc_macro_libs = Vec::new();
977         let mut aliases = Vec::new();
978         for extern_dep in &crate_.externs {
979             match extern_dep.extern_type {
980                 ExternType::Rust => rust_libs.push(extern_dep.lib_name.clone()),
981                 ExternType::ProcMacro => proc_macro_libs.push(extern_dep.lib_name.clone()),
982             }
983             if extern_dep.name != extern_dep.lib_name {
984                 aliases.push(format!("{}:{}", extern_dep.lib_name, extern_dep.name));
985             }
986         }
987 
988         // Add "lib" prefix and apply name overrides.
989         let process_lib_deps = |libs: Vec<String>| -> Vec<String> {
990             let mut result = Vec::new();
991             for x in libs {
992                 let module_name = "lib".to_string() + x.as_str();
993                 if let Some(module_name) = override_module_name(
994                     &module_name,
995                     &package_cfg.dep_blocklist,
996                     &cfg.module_name_overrides,
997                     &RENAME_MAP,
998                 ) {
999                     result.push(module_name);
1000                 }
1001             }
1002             result.sort();
1003             result.dedup();
1004             result
1005         };
1006         m.props.set_if_nonempty("rustlibs", process_lib_deps(rust_libs));
1007         m.props.set_if_nonempty("proc_macros", process_lib_deps(proc_macro_libs));
1008         let (whole_static_libs, static_libs) = process_lib_deps(crate_.static_libs.clone())
1009             .into_iter()
1010             .partition(|static_lib| package_cfg.whole_static_libs.contains(static_lib));
1011         m.props.set_if_nonempty("static_libs", static_libs);
1012         m.props.set_if_nonempty("whole_static_libs", whole_static_libs);
1013         m.props.set_if_nonempty("shared_libs", process_lib_deps(crate_.shared_libs.clone()));
1014         m.props.set_if_nonempty("aliases", aliases);
1015 
1016         if package_cfg.device_supported {
1017             if !crate_type.is_test() {
1018                 if cfg.native_bridge_supported {
1019                     m.props.set("native_bridge_supported", true);
1020                 }
1021                 if cfg.product_available {
1022                     m.props.set("product_available", true);
1023                 }
1024                 if cfg.ramdisk_available {
1025                     m.props.set("ramdisk_available", true);
1026                 }
1027                 if cfg.recovery_available {
1028                     m.props.set("recovery_available", true);
1029                 }
1030                 if cfg.vendor_available {
1031                     m.props.set("vendor_available", true);
1032                 }
1033                 if cfg.vendor_ramdisk_available {
1034                     m.props.set("vendor_ramdisk_available", true);
1035                 }
1036             }
1037             if crate_type.is_library() {
1038                 m.props.set_if_nonempty("apex_available", cfg.apex_available.clone());
1039                 if let Some(min_sdk_version) = &cfg.min_sdk_version {
1040                     m.props.set("min_sdk_version", min_sdk_version.clone());
1041                 }
1042             }
1043         }
1044         if crate_type.is_test() {
1045             if let Some(data) =
1046                 package_cfg.test_data.get(crate_.main_src.to_string_lossy().as_ref())
1047             {
1048                 m.props.set("data", data.clone());
1049             }
1050         } else if package_cfg.no_std {
1051             m.props.set("prefer_rlib", true);
1052             m.props.set("no_stdlibs", true);
1053             let mut stdlibs = vec!["libcompiler_builtins.rust_sysroot", "libcore.rust_sysroot"];
1054             if package_cfg.alloc {
1055                 stdlibs.push("liballoc.rust_sysroot");
1056             }
1057             stdlibs.sort();
1058             m.props.set("stdlibs", stdlibs);
1059         }
1060 
1061         if let Some(visibility) = cfg.module_visibility.get(&module_name) {
1062             m.props.set("visibility", visibility.clone());
1063         }
1064 
1065         if let Some(path) = &package_cfg.add_module_block {
1066             let content = std::fs::read_to_string(path)
1067                 .with_context(|| format!("failed to read {path:?}"))?;
1068             m.props.raw_block = Some(content);
1069         }
1070 
1071         modules.push(m);
1072     }
1073     Ok(modules)
1074 }
1075 
1076 /// Convert a `Crate` into a rules.mk file.
1077 ///
1078 /// If messy business logic is necessary, prefer putting it here.
crate_to_rulesmk( crate_: &Crate, cfg: &VariantConfig, package_cfg: &PackageVariantConfig, out_files: &[String], ) -> Result<String>1079 fn crate_to_rulesmk(
1080     crate_: &Crate,
1081     cfg: &VariantConfig,
1082     package_cfg: &PackageVariantConfig,
1083     out_files: &[String],
1084 ) -> Result<String> {
1085     let mut contents = String::new();
1086 
1087     contents += "LOCAL_DIR := $(GET_LOCAL_DIR)\n";
1088     contents += "MODULE := $(LOCAL_DIR)\n";
1089     contents += &format!("MODULE_CRATE_NAME := {}\n", crate_.name);
1090 
1091     if !crate_.types.is_empty() {
1092         contents += "MODULE_RUST_CRATE_TYPES :=";
1093         for crate_type in &crate_.types {
1094             contents += match crate_type {
1095                 CrateType::Lib => " rlib",
1096                 CrateType::StaticLib => " staticlib",
1097                 CrateType::ProcMacro => " proc-macro",
1098                 _ => bail!("Cannot generate rules.mk for crate type {crate_type:?}"),
1099             };
1100         }
1101         contents += "\n";
1102     }
1103 
1104     contents += &format!("MODULE_SRCS := $(LOCAL_DIR)/{}\n", crate_.main_src.display());
1105 
1106     if !out_files.is_empty() {
1107         contents += &format!("OUT_FILES := {}\n", out_files.join(" "));
1108         contents += "BUILD_OUT_FILES := $(addprefix $(call TOBUILDDIR,$(MODULE))/,$(OUT_FILES))\n";
1109         contents += "$(BUILD_OUT_FILES): $(call TOBUILDDIR,$(MODULE))/% : $(MODULE)/out/%\n";
1110         contents += "\t@echo copying $^ to $@\n";
1111         contents += "\t@$(MKDIR)\n";
1112         contents += "\t@cp $^ $@\n\n";
1113         contents += "MODULE_RUST_ENV += OUT_DIR=$(call TOBUILDDIR,$(MODULE))\n\n";
1114         contents += "MODULE_SRCDEPS += $(BUILD_OUT_FILES)\n\n";
1115         contents += "OUT_FILES :=\n";
1116         contents += "BUILD_OUT_FILES :=\n";
1117         contents += "\n";
1118     }
1119 
1120     // crate dependencies without lib- prefix
1121     let mut library_deps: Vec<_> = crate_.externs.iter().map(|dep| dep.lib_name.clone()).collect();
1122     if package_cfg.no_std {
1123         contents += "MODULE_ADD_IMPLICIT_DEPS := false\n";
1124         library_deps.push("compiler_builtins".to_string());
1125         library_deps.push("core".to_string());
1126         if package_cfg.alloc {
1127             library_deps.push("alloc".to_string());
1128         }
1129     }
1130 
1131     contents += &format!("MODULE_RUST_EDITION := {}\n", crate_.edition);
1132 
1133     let mut flags = Vec::new();
1134     if !crate_.cap_lints.is_empty() {
1135         flags.push(crate_.cap_lints.clone());
1136     }
1137     flags.extend(crate_.codegens.iter().map(|codegen| format!("-C {}", codegen)));
1138     flags.extend(crate_.features.iter().map(|feat| format!("--cfg 'feature=\"{feat}\"'")));
1139     flags.extend(
1140         crate_
1141             .cfgs
1142             .iter()
1143             .filter(|crate_cfg| !cfg.cfg_blocklist.contains(crate_cfg))
1144             .map(|cfg| format!("--cfg '{cfg}'")),
1145     );
1146     if !flags.is_empty() {
1147         contents += "MODULE_RUSTFLAGS += \\\n\t";
1148         contents += &flags.join(" \\\n\t");
1149         contents += "\n\n";
1150     }
1151 
1152     let mut library_deps: Vec<String> = library_deps
1153         .into_iter()
1154         .flat_map(|dep| {
1155             override_module_name(
1156                 &format!("lib{dep}"),
1157                 &package_cfg.dep_blocklist,
1158                 &cfg.module_name_overrides,
1159                 &RULESMK_RENAME_MAP,
1160             )
1161         })
1162         .map(|dep| {
1163             // Rewrite dependency name to module path for Trusty build system
1164             if let Some(dep) = dep.strip_prefix("lib") {
1165                 format!("external/rust/crates/{dep}")
1166             } else {
1167                 dep
1168             }
1169         })
1170         .collect();
1171     library_deps.sort();
1172     library_deps.dedup();
1173     contents += "MODULE_LIBRARY_DEPS := \\\n\t";
1174     contents += &library_deps.join(" \\\n\t");
1175     contents += "\n\n";
1176 
1177     contents += "include make/library.mk\n";
1178     Ok(contents)
1179 }
1180 
1181 #[cfg(test)]
1182 mod tests {
1183     use super::*;
1184     use googletest::matchers::eq;
1185     use googletest::prelude::assert_that;
1186     use std::env::{current_dir, set_current_dir};
1187     use std::fs::{self, read_to_string};
1188     use std::path::PathBuf;
1189 
1190     const TESTDATA_PATH: &str = "testdata";
1191 
1192     #[test]
group_variants_by_package()1193     fn group_variants_by_package() {
1194         let main_v1 =
1195             Crate { name: "main_v1".to_string(), package_dir: "main".into(), ..Default::default() };
1196         let main_v1_tests = Crate {
1197             name: "main_v1_tests".to_string(),
1198             package_dir: "main".into(),
1199             ..Default::default()
1200         };
1201         let other_v1 = Crate {
1202             name: "other_v1".to_string(),
1203             package_dir: "other".into(),
1204             ..Default::default()
1205         };
1206         let main_v2 =
1207             Crate { name: "main_v2".to_string(), package_dir: "main".into(), ..Default::default() };
1208         let some_v2 =
1209             Crate { name: "some_v2".to_string(), package_dir: "some".into(), ..Default::default() };
1210         let crates = vec![
1211             vec![main_v1.clone(), main_v1_tests.clone(), other_v1.clone()],
1212             vec![main_v2.clone(), some_v2.clone()],
1213         ];
1214 
1215         let module_by_package = group_by_package(crates);
1216 
1217         let expected_by_package: BTreeMap<PathBuf, Vec<Vec<Crate>>> = [
1218             ("main".into(), vec![vec![main_v1, main_v1_tests], vec![main_v2]]),
1219             ("other".into(), vec![vec![other_v1], vec![]]),
1220             ("some".into(), vec![vec![], vec![some_v2]]),
1221         ]
1222         .into_iter()
1223         .collect();
1224         assert_eq!(module_by_package, expected_by_package);
1225     }
1226 
1227     #[test]
generate_bp()1228     fn generate_bp() {
1229         for testdata_directory_path in testdata_directories() {
1230             let cfg = Config::from_json_str(
1231                 &read_to_string(testdata_directory_path.join("cargo_embargo.json"))
1232                     .expect("Failed to open cargo_embargo.json"),
1233             )
1234             .unwrap();
1235             let crates: Vec<Vec<Crate>> = serde_json::from_reader(
1236                 File::open(testdata_directory_path.join("crates.json"))
1237                     .expect("Failed to open crates.json"),
1238             )
1239             .unwrap();
1240             let expected_output =
1241                 read_to_string(testdata_directory_path.join("expected_Android.bp")).unwrap();
1242 
1243             let old_current_dir = current_dir().unwrap();
1244             set_current_dir(&testdata_directory_path).unwrap();
1245 
1246             let module_by_package = group_by_package(crates);
1247             assert_eq!(module_by_package.len(), 1);
1248             let crates = module_by_package.into_values().next().unwrap();
1249 
1250             let mut output = String::new();
1251             for (variant_index, variant_cfg) in cfg.variants.iter().enumerate() {
1252                 let variant_crates = &crates[variant_index];
1253                 let package_name = &variant_crates[0].package_name;
1254                 let def = PackageVariantConfig::default();
1255                 let package_variant_cfg = variant_cfg.package.get(package_name).unwrap_or(&def);
1256 
1257                 output += &generate_android_bp(
1258                     variant_cfg,
1259                     package_variant_cfg,
1260                     package_name,
1261                     variant_crates,
1262                     &Vec::new(),
1263                 )
1264                 .unwrap();
1265             }
1266 
1267             assert_that!(output, eq(expected_output));
1268 
1269             set_current_dir(old_current_dir).unwrap();
1270         }
1271     }
1272 
1273     #[test]
crate_to_bp_empty()1274     fn crate_to_bp_empty() {
1275         let c = Crate {
1276             name: "name".to_string(),
1277             package_name: "package_name".to_string(),
1278             edition: "2021".to_string(),
1279             types: vec![],
1280             ..Default::default()
1281         };
1282         let cfg = VariantConfig { ..Default::default() };
1283         let package_cfg = PackageVariantConfig { ..Default::default() };
1284         let modules = crate_to_bp_modules(&c, &cfg, &package_cfg, &[]).unwrap();
1285 
1286         assert_eq!(modules, vec![]);
1287     }
1288 
1289     #[test]
crate_to_bp_minimal()1290     fn crate_to_bp_minimal() {
1291         let c = Crate {
1292             name: "name".to_string(),
1293             package_name: "package_name".to_string(),
1294             edition: "2021".to_string(),
1295             types: vec![CrateType::Lib],
1296             ..Default::default()
1297         };
1298         let cfg = VariantConfig { ..Default::default() };
1299         let package_cfg = PackageVariantConfig { ..Default::default() };
1300         let modules = crate_to_bp_modules(&c, &cfg, &package_cfg, &[]).unwrap();
1301 
1302         assert_eq!(
1303             modules,
1304             vec![BpModule {
1305                 module_type: "rust_library".to_string(),
1306                 props: BpProperties {
1307                     map: [
1308                         (
1309                             "apex_available".to_string(),
1310                             BpValue::List(vec![
1311                                 BpValue::String("//apex_available:platform".to_string()),
1312                                 BpValue::String("//apex_available:anyapex".to_string()),
1313                             ])
1314                         ),
1315                         ("cargo_env_compat".to_string(), BpValue::Bool(true)),
1316                         ("crate_name".to_string(), BpValue::String("name".to_string())),
1317                         ("edition".to_string(), BpValue::String("2021".to_string())),
1318                         ("host_supported".to_string(), BpValue::Bool(true)),
1319                         ("name".to_string(), BpValue::String("libname".to_string())),
1320                         ("product_available".to_string(), BpValue::Bool(true)),
1321                         ("crate_root".to_string(), BpValue::String("".to_string())),
1322                         ("vendor_available".to_string(), BpValue::Bool(true)),
1323                     ]
1324                     .into_iter()
1325                     .collect(),
1326                     raw_block: None
1327                 }
1328             }]
1329         );
1330     }
1331 
1332     #[test]
crate_to_bp_rename()1333     fn crate_to_bp_rename() {
1334         let c = Crate {
1335             name: "ash".to_string(),
1336             package_name: "package_name".to_string(),
1337             edition: "2021".to_string(),
1338             types: vec![CrateType::Lib],
1339             ..Default::default()
1340         };
1341         let cfg = VariantConfig { ..Default::default() };
1342         let package_cfg = PackageVariantConfig { ..Default::default() };
1343         let modules = crate_to_bp_modules(&c, &cfg, &package_cfg, &[]).unwrap();
1344 
1345         assert_eq!(
1346             modules,
1347             vec![BpModule {
1348                 module_type: "rust_library".to_string(),
1349                 props: BpProperties {
1350                     map: [
1351                         (
1352                             "apex_available".to_string(),
1353                             BpValue::List(vec![
1354                                 BpValue::String("//apex_available:platform".to_string()),
1355                                 BpValue::String("//apex_available:anyapex".to_string()),
1356                             ])
1357                         ),
1358                         ("cargo_env_compat".to_string(), BpValue::Bool(true)),
1359                         ("crate_name".to_string(), BpValue::String("ash".to_string())),
1360                         ("edition".to_string(), BpValue::String("2021".to_string())),
1361                         ("host_supported".to_string(), BpValue::Bool(true)),
1362                         ("name".to_string(), BpValue::String("libash_rust".to_string())),
1363                         ("product_available".to_string(), BpValue::Bool(true)),
1364                         ("crate_root".to_string(), BpValue::String("".to_string())),
1365                         ("vendor_available".to_string(), BpValue::Bool(true)),
1366                     ]
1367                     .into_iter()
1368                     .collect(),
1369                     raw_block: None
1370                 }
1371             }]
1372         );
1373     }
1374 
1375     /// Returns a list of directories containing test data.
1376     ///
1377     /// Each directory under `testdata/` contains a single test case.
testdata_directories() -> Vec<PathBuf>1378     pub fn testdata_directories() -> Vec<PathBuf> {
1379         fs::read_dir(TESTDATA_PATH)
1380             .expect("Failed to read testdata directory")
1381             .filter_map(|entry| {
1382                 let entry = entry.expect("Error reading testdata directory entry");
1383                 if entry
1384                     .file_type()
1385                     .expect("Error getting metadata for testdata subdirectory")
1386                     .is_dir()
1387                 {
1388                     Some(entry.path())
1389                 } else {
1390                     None
1391                 }
1392             })
1393             .collect()
1394     }
1395 }
1396