oma_mirror/
parser.rs

1use std::{
2    fs, io,
3    path::{Path, PathBuf},
4};
5
6use ahash::HashMap;
7use serde::Deserialize;
8use snafu::{ResultExt, Snafu};
9
10#[derive(Debug, Deserialize)]
11pub struct MirrorsConfigTemplate {
12    pub config: Vec<MirrorConfigTemplate>,
13}
14
15#[derive(Debug, Deserialize)]
16pub struct MirrorConfigTemplate {
17    pub components: Vec<String>,
18    #[serde(default, rename = "signed-by")]
19    pub signed_by: Vec<String>,
20    #[serde(default)]
21    pub architectures: Vec<String>,
22    #[serde(rename = "always-trusted", default)]
23    pub always_trusted: bool,
24    #[serde(default = "MirrorsConfigTemplate::default_enabled")]
25    pub enabled: bool,
26}
27
28#[derive(Debug, Snafu)]
29pub enum TemplateParseError {
30    #[snafu(display("Failed to read file: {}", path.display()))]
31    ReadFile { source: io::Error, path: PathBuf },
32    #[snafu(transparent)]
33    Parse { source: toml::de::Error },
34    #[snafu(display("The ID of your custom mirror `{name}' conflicts with an existing mirror"))]
35    ConflictName { name: Box<str> },
36}
37
38impl MirrorsConfigTemplate {
39    const fn default_enabled() -> bool {
40        true
41    }
42
43    pub fn parse_from_file(path: impl AsRef<Path>) -> Result<Self, TemplateParseError> {
44        let s = fs::read(path.as_ref()).context(ReadFileSnafu {
45            path: path.as_ref().to_path_buf(),
46        })?;
47
48        Self::parse_from_slice(&s)
49    }
50
51    pub fn parse_from_slice(slice: &[u8]) -> Result<Self, TemplateParseError> {
52        Ok(toml::from_slice(slice)?)
53    }
54}
55
56#[derive(Debug, Deserialize, Clone)]
57pub struct MirrorsConfig(pub HashMap<Box<str>, MirrorConfig>);
58
59#[derive(Debug, Deserialize, Clone)]
60pub struct MirrorConfig {
61    pub description: HashMap<String, String>,
62    pub url: Box<str>,
63}
64
65impl MirrorsConfig {
66    pub fn parse_from_file(path: impl AsRef<Path>) -> Result<Self, TemplateParseError> {
67        let s = fs::read(path.as_ref()).context(ReadFileSnafu {
68            path: path.as_ref().to_path_buf(),
69        })?;
70
71        Self::parse_from_slice(&s)
72    }
73
74    pub fn parse_from_slice(slice: &[u8]) -> Result<Self, TemplateParseError> {
75        Ok(toml::from_slice(slice)?)
76    }
77}