Skip to main content

actrpc_interceptor/interceptors/policy/config/
loader.rs

1use crate::interceptors::policy::{config::PolicyConfig, error::PolicyError};
2use std::{
3    ffi::OsStr,
4    path::{Path, PathBuf},
5};
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum PolicyConfigFormat {
9    Toml,
10    Yaml,
11}
12
13impl PolicyConfig {
14    pub fn from_path(path: impl AsRef<Path>) -> Result<Self, PolicyError> {
15        let path = path.as_ref();
16
17        let format = PolicyConfigFormat::from_path(path)?;
18
19        let text = std::fs::read_to_string(path).map_err(|source| PolicyError::ConfigRead {
20            path: path.to_path_buf(),
21            source,
22        })?;
23
24        Self::from_str_with_format(&text, format, path)
25    }
26
27    pub fn from_str_with_format(
28        text: &str,
29        format: PolicyConfigFormat,
30        path_for_errors: impl AsRef<Path>,
31    ) -> Result<Self, PolicyError> {
32        let path = path_for_errors.as_ref().to_path_buf();
33
34        match format {
35            PolicyConfigFormat::Toml => toml::from_str(text)
36                .map_err(|source| PolicyError::ConfigDeserializeToml { path, source }),
37            PolicyConfigFormat::Yaml => serde_yaml::from_str(text)
38                .map_err(|source| PolicyError::ConfigDeserializeYaml { path, source }),
39        }
40    }
41}
42
43impl PolicyConfigFormat {
44    pub fn from_path(path: &Path) -> Result<Self, PolicyError> {
45        match path.extension().and_then(OsStr::to_str) {
46            Some("toml") => Ok(Self::Toml),
47            Some("yaml") | Some("yml") => Ok(Self::Yaml),
48            _ => Err(PolicyError::UnsupportedConfigFormat {
49                path: PathBuf::from(path),
50            }),
51        }
52    }
53}