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
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
use crate::anulap::{Anulap, Initialize};

#[cfg(any(feature = "with-source-clap", feature = "with-source-on"))]
use crate::anulap::Source;

#[cfg(feature = "with-source-clap")]
#[derive(Debug)]
pub struct ClapSource<'a> {
    matches: clap::ArgMatches<'a>,
}

#[cfg(feature = "with-source-clap")]
impl<'a> ClapSource<'a> {
    pub fn new(matches: clap::ArgMatches<'a>) -> Self {
        Self { matches }
    }
}

#[cfg(feature = "with-source-clap")]
impl<'a> Source for ClapSource<'a> {
    fn get(&self, key: &str) -> Option<String> {
        self.matches.value_of(key).map(String::from)
    }
}

#[cfg(feature = "with-source-ron")]
#[derive(Debug)]
pub struct RonSource {
    value: ron::Value,
}

#[cfg(feature = "with-source-ron")]
impl RonSource {
    pub fn from_file<P>(path: P) -> Result<Self, RonSourceError>
    where
        P: AsRef<std::path::Path>,
    {
        let file = std::fs::OpenOptions::new().read(true).open(path)?;
        let mut reader = std::io::BufReader::new(file);

        let value = ron::de::from_reader(&mut reader)?;

        Ok(Self { value })
    }
}

#[cfg(feature = "with-source-ron")]
impl Source for RonSource {
    fn get(&self, key: &str) -> Option<String> {
        match &self.value {
            ron::Value::Map(map) => map
                .iter()
                .find(|(k, _)| match k {
                    ron::Value::String(k) => k == key,
                    _ => false,
                })
                .and_then(|(_, value)| -> Option<String> {
                    match value {
                        ron::Value::Bool(boolean) => Some(boolean.to_string()),
                        ron::Value::Number(number) => match number {
                            ron::Number::Integer(integer) => Some(integer.to_string()),
                            ron::Number::Float(float) => Some(float.get().to_string()),
                        },
                        ron::Value::String(string) => Some(string.clone()),
                        _ => None,
                    }
                }),
            _ => None,
        }
    }
}

#[cfg(feature = "with-source-ron")]
#[derive(Debug)]
pub enum RonSourceError {
    IO { source: std::io::Error },
    Ron { source: ron::Error },
}

#[cfg(feature = "with-source-ron")]
impl std::fmt::Display for RonSourceError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            RonSourceError::IO { source } => write!(f, "ron source, io error: {}", source),
            RonSourceError::Ron { source } => {
                write!(f, "ron source, ron deserialize error: {}", source)
            }
        }
    }
}

#[cfg(feature = "with-source-ron")]
impl std::error::Error for RonSourceError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            RonSourceError::IO { source } => Some(source),
            RonSourceError::Ron { source } => Some(source),
        }
    }
}

#[cfg(feature = "with-source-ron")]
impl From<std::io::Error> for RonSourceError {
    fn from(source: std::io::Error) -> Self {
        Self::IO { source }
    }
}

#[cfg(feature = "with-source-ron")]
impl From<ron::Error> for RonSourceError {
    fn from(source: ron::Error) -> Self {
        Self::Ron { source }
    }
}

#[derive(Clone, Debug, serde::Deserialize)]
#[serde(default)]
pub struct Config {
    pub ip: [u8; 4],
    pub port: u16,
    pub database: String,
}

impl Initialize for Config {
    fn init(config: &Anulap<'_>) -> Option<Self> {
        Some(Self {
            ip: config
                .get_string("ip")
                .and_then(|value| {
                    let mut parts = value
                        .split('.')
                        .map(str::parse)
                        .collect::<Vec<Result<u8, _>>>();

                    let four = parts.pop()?.ok()?;
                    let three = parts.pop()?.ok()?;
                    let two = parts.pop()?.ok()?;
                    let one = parts.pop()?.ok()?;

                    Some([one, two, three, four])
                })
                .unwrap_or_else(|| [0, 0, 0, 0]),
            port: config
                .get_string("port")
                .and_then(|value| value.parse().ok())
                .unwrap_or(8901),
            database: config
                .get_string("database")
                .unwrap_or_else(|| String::from("postgres://stry:stry@localhost:5432/stry")),
        })
    }
}

impl Default for Config {
    fn default() -> Self {
        Self {
            ip: [0, 0, 0, 0],
            port: 8901,
            database: String::from("postgres://stry:stry@localhost:5432/stry"),
        }
    }
}