Debian Codegraph @

third_party/rust/uniffi_bindgen/src/cargo_metadata.rs

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 //! Helpers for data returned by cargo_metadata. Note that this doesn't
6 //! execute cargo_metadata, just parses its output.
7
8 use anyhow::{bail, Context};
9 use camino::Utf8PathBuf;
10 use cargo_metadata::Metadata;
11 use std::{collections::HashMap, fs};
12
13 use crate::BindgenCrateConfigSupplier;
14
15 #[derive(Debug, Clone, Default)]
16 pub struct CrateConfigSupplier {
17 paths: HashMap<String, Utf8PathBuf>,
18 }
19
20 impl BindgenCrateConfigSupplier for CrateConfigSupplier {
21 fn get_toml(&self, crate_name: &str) -> anyhow::Result<Option<toml::value::Table>> {
22 crate::load_toml_file(self.get_toml_path(crate_name).as_deref())
23 }
24
25 fn get_toml_path(&self, crate_name: &str) -> Option<Utf8PathBuf> {
26 self.paths.get(crate_name).map(|p| p.join("uniffi.toml"))
27 }
28
29 fn get_udl(&self, crate_name: &str, udl_name: &str) -> anyhow::Result<String> {
30 let path = self
31 .paths
32 .get(crate_name)
33 .context(format!("No path known to UDL files for '{crate_name}'"))?
34 .join("src")
35 .join(format!("{udl_name}.udl"));
36 if path.exists() {
37 Ok(fs::read_to_string(path)?)
38 } else {
39 bail!(format!("No UDL file found at '{path}'"));
40 }
41 }
42 }
43
44 impl From<Metadata> for CrateConfigSupplier {
45 fn from(metadata: Metadata) -> Self {
46 let paths: HashMap<String, Utf8PathBuf> = metadata
47 .packages
48 .iter()
49 .flat_map(|p| {
50 p.targets
51 .iter()
52 .filter(|t| {
53 !t.is_bin()
54 && !t.is_example()
55 && !t.is_test()
56 && !t.is_bench()
57 && !t.is_custom_build()
58 })
59 .filter_map(|t| {
60 p.manifest_path
61 .parent()
62 .map(|p| (t.name.replace('-', "_"), p.to_owned()))
63 })
64 })
65 .collect();
66 Self { paths }
67 }
68 }