tf_bindgen/
config.rs

1use anyhow::{Context, Result};
2use semver::VersionReq;
3use serde::{Deserialize, Serialize};
4use std::path::Path;
5use toml::{map::Map, Value};
6
7#[derive(Deserialize, Serialize)]
8pub struct Config {
9    pub provider: Map<String, Value>,
10}
11
12impl Config {
13    /// Load configuration file from file system.
14    pub fn from_file(path: impl AsRef<Path>) -> anyhow::Result<Self> {
15        let config = std::fs::read_to_string(path).context("failed to read config file")?;
16        toml::from_str(&config).context("failed to parse config file")
17    }
18
19    /// Generates a list of `(<provider name>, <version constraint>)` pairs from specified providers.
20    ///
21    /// # Errors
22    ///
23    /// Will return `Err` if a provider constraint cannot been parsed.
24    pub fn providers(&self) -> Result<Vec<(String, VersionReq)>> {
25        self.provider
26            .iter()
27            .map(|(name, provider)| match provider {
28                Value::String(constraint) => {
29                    let version = VersionReq::parse(constraint)
30                        .context("failed to parse version constraint")?;
31                    Ok((name.clone(), version))
32                }
33                _ => Err(anyhow::anyhow!(
34                    "unexpected type of constraint `{name}` (expected: string)"
35                )),
36            })
37            .collect()
38    }
39}