cargo_mobile2/config/
metadata.rs

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
use crate::util::cli::{Report, Reportable};
use serde::Deserialize;
use std::{
    fs, io,
    path::{Path, PathBuf},
};
use thiserror::Error;

#[derive(Debug, Error)]
pub enum Error {
    #[error("Failed to read {path}: {cause}")]
    ReadFailed { path: PathBuf, cause: io::Error },
    #[error("Failed to parse {path}: {cause}")]
    ParseFailed {
        path: PathBuf,
        cause: toml::de::Error,
    },
}

impl Reportable for Error {
    fn report(&self) -> Report {
        Report::error("Failed to read metadata from Cargo.toml", self)
    }
}

#[derive(Debug, Default, Deserialize)]
pub struct Metadata {
    #[cfg(target_os = "macos")]
    #[serde(default, rename = "cargo-apple")]
    pub apple: crate::apple::config::Metadata,
    #[serde(default, rename = "cargo-android")]
    pub android: crate::android::config::Metadata,
}

impl Metadata {
    pub fn load(project_root: &Path) -> Result<Self, Error> {
        #[derive(Debug, Deserialize)]
        struct Package {
            #[serde(default)]
            metadata: Option<Metadata>,
        }

        #[derive(Debug, Deserialize)]
        struct CargoToml {
            package: Package,
        }

        let path = project_root.join("Cargo.toml");
        let toml_str = fs::read_to_string(&path).map_err(|cause| Error::ReadFailed {
            path: path.clone(),
            cause,
        })?;
        let cargo_toml = toml::from_str::<CargoToml>(&toml_str)
            .map_err(|cause| Error::ParseFailed { path, cause })?;
        Ok(cargo_toml.package.metadata.unwrap_or_default())
    }

    #[cfg(target_os = "macos")]
    pub fn apple(&self) -> &crate::apple::config::Metadata {
        &self.apple
    }

    pub fn android(&self) -> &crate::android::config::Metadata {
        &self.android
    }
}