1use anyhow::anyhow;
2use std::path::Path;
3#[cfg(any(feature = "json", feature = "yaml"))]
4use std::{fs::File, io::Read, str::FromStr};
5
6pub mod common;
7pub mod convert;
8pub mod html;
9pub mod info;
10pub mod interrupts;
11pub mod makedeps;
12pub mod mmap;
13pub mod patch;
14
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16#[non_exhaustive]
17pub enum ConfigFormat {
18 #[cfg(feature = "yaml")]
19 Yaml,
20 #[cfg(feature = "json")]
21 Json,
22}
23
24#[cfg(any(feature = "json", feature = "yaml"))]
25impl FromStr for ConfigFormat {
26 type Err = anyhow::Error;
27 fn from_str(s: &str) -> Result<Self, Self::Err> {
28 match s {
29 #[cfg(feature = "yaml")]
30 "yml" | "yaml" | "YAML" => Ok(Self::Yaml),
31 #[cfg(feature = "json")]
32 "json" | "JSON" => Ok(Self::Json),
33 _ => Err(anyhow!("Unknown config file format")),
34 }
35 }
36}
37
38#[cfg(any(feature = "json", feature = "yaml"))]
39pub(crate) fn get_encoder_config(
40 format_config: Option<&Path>,
41) -> anyhow::Result<svd_encoder::Config> {
42 Ok(if let Some(format_config) = format_config {
43 let config_format = match format_config.extension().and_then(|e| e.to_str()) {
44 Some(s) => ConfigFormat::from_str(s)?,
45 _ => return Err(anyhow!("Unknown output file format")),
46 };
47 let mut config = String::new();
48 File::open(format_config)?.read_to_string(&mut config)?;
49
50 let config_map: std::collections::HashMap<String, String> = match config_format {
51 #[cfg(feature = "yaml")]
52 ConfigFormat::Yaml => serde_yaml::from_str(&config)?,
53 #[cfg(feature = "json")]
54 ConfigFormat::Json => serde_json::from_str(&config)?,
55 };
56
57 let mut config = svd_encoder::Config::default();
58 config_map
59 .iter()
60 .for_each(|(name, value)| config.update(name, value));
61
62 config
63 } else {
64 svd_encoder::Config::default()
65 })
66}
67
68#[cfg(not(any(feature = "json", feature = "yaml")))]
69
70pub(crate) fn get_encoder_config(
71 format_config: Option<&Path>,
72) -> anyhow::Result<svd_encoder::Config> {
73 if let Some(format_config) = format_config {
74 Err(anyhow!("In path: {}", format_config.display())
75 .context("Config file passed to a build of svdtools that does not support it"))
76 } else {
77 Ok(svd_encoder::Config::default())
78 }
79}
80
81#[cfg(test)]
82mod test_utils;