cargo_mobile2/config/
metadata.rs

1use crate::util::cli::{Report, Reportable};
2use serde::Deserialize;
3use std::{
4    fs, io,
5    path::{Path, PathBuf},
6};
7use thiserror::Error;
8
9#[derive(Debug, Error)]
10pub enum Error {
11    #[error("Failed to read {path}: {cause}")]
12    ReadFailed { path: PathBuf, cause: io::Error },
13    #[error("Failed to parse {path}: {cause}")]
14    ParseFailed {
15        path: PathBuf,
16        cause: toml::de::Error,
17    },
18}
19
20impl Reportable for Error {
21    fn report(&self) -> Report {
22        Report::error("Failed to read metadata from Cargo.toml", self)
23    }
24}
25
26#[derive(Debug, Default, Deserialize)]
27pub struct Metadata {
28    #[cfg(target_os = "macos")]
29    #[serde(default, rename = "cargo-apple")]
30    pub apple: crate::apple::config::Metadata,
31    #[serde(default, rename = "cargo-android")]
32    pub android: crate::android::config::Metadata,
33}
34
35impl Metadata {
36    pub fn load(project_root: &Path) -> Result<Self, Error> {
37        #[derive(Debug, Deserialize)]
38        struct Package {
39            #[serde(default)]
40            metadata: Option<Metadata>,
41        }
42
43        #[derive(Debug, Deserialize)]
44        struct CargoToml {
45            package: Package,
46        }
47
48        let path = project_root.join("Cargo.toml");
49        let toml_str = fs::read_to_string(&path).map_err(|cause| Error::ReadFailed {
50            path: path.clone(),
51            cause,
52        })?;
53        let cargo_toml = toml::from_str::<CargoToml>(&toml_str)
54            .map_err(|cause| Error::ParseFailed { path, cause })?;
55        Ok(cargo_toml.package.metadata.unwrap_or_default())
56    }
57
58    #[cfg(target_os = "macos")]
59    pub fn apple(&self) -> &crate::apple::config::Metadata {
60        &self.apple
61    }
62
63    pub fn android(&self) -> &crate::android::config::Metadata {
64        &self.android
65    }
66}