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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
use std::path::PathBuf;

use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};

use crate::constants;
use crate::error::BridgerError;

/// The config names
#[derive(Clone, Debug)]
pub enum Names {
    /// Bridger
    Bridger,
    /// Bridge tempalte
    BridgeTemplate,
    /// Bridge pangolin-ropsten
    BridgePangolinRopsten,
    /// Bridge darwinia-ethereum
    BridgeDarwiniaEthereum,
    /// Bridge pangolin-pangoro
    BridgePangolinPangoro,
    /// bridge darwinia-crab
    BridgeDarwiniaCrab,
    /// bridge pangoro-chapel
    BridgePangoroChapel,
    /// bridge pangolin-pangolinparachain
    BridgePangolinPangolinParachain,
    /// bridge pangolin-pangolinparachain
    BridgeCrabCrabParachain,
    /// bridge pangoro-goerli
    BridgePangoroGoerli,
}

impl Names {
    pub fn name(&self) -> &'static str {
        match self {
            Self::Bridger => "bridger",
            Self::BridgeTemplate => "bridge-template",
            Self::BridgePangolinRopsten => "bridge-pangolin-ropsten",
            Self::BridgeDarwiniaEthereum => "bridge-darwinia-ethereum",
            Self::BridgePangolinPangoro => "bridge-pangolin-pangoro",
            Self::BridgeDarwiniaCrab => "bridge-darwinia-crab",
            Self::BridgePangoroChapel => "bridge-pangoro-chapel",
            Self::BridgePangolinPangolinParachain => "bridge-pangolin-pangolinparachain",
            Self::BridgeCrabCrabParachain => "bridge-crab-crabparachain",
            Self::BridgePangoroGoerli => "bridge-pangoro-goerli",
        }
    }
}

/// Config helpers. store config to file or restore from file
#[derive(Debug)]
pub struct Config {
    base_path: PathBuf,
}

/// Config format
#[derive(Clone, Debug, Deserialize, Serialize, strum::EnumString, strum::EnumVariantNames)]
#[strum(serialize_all = "kebab_case")]
pub enum ConfigFormat {
    /// yml
    #[serde(rename = "yml")]
    Yml,
    /// json
    #[serde(rename = "json")]
    Json,
    /// toml
    #[serde(rename = "toml")]
    Toml,
}

impl ConfigFormat {
    pub fn extension(&self) -> &'static str {
        match self {
            ConfigFormat::Yml => "yml",
            ConfigFormat::Json => "json",
            ConfigFormat::Toml => "toml",
        }
    }
}

impl Config {
    fn new() -> Self {
        let base_path = constants::bridger_home();
        Self { base_path }
    }
}

impl Config {
    /// Store without file format, if the config is exists will be replace it.
    /// If not choose toml default.
    pub fn store(name: Names, config: impl Serialize) -> color_eyre::Result<()> {
        Self::new().persist(name.name(), config, None)
    }

    /// Store config to file, the name argument is file name
    pub fn store_with_format(
        name: Names,
        config: impl Serialize,
        format: ConfigFormat,
    ) -> color_eyre::Result<()> {
        Self::new().persist(name.name(), config, Some(format))
    }

    /// Restore config from file by name
    pub fn restore<T: DeserializeOwned>(name: Names) -> color_eyre::Result<T> {
        Self::new().load(name.name())
    }

    /// The config file is exists
    pub fn exists(name: Names) -> bool {
        Self::new()
            .find_config_file(name.name())
            .unwrap_or_default()
            .is_some()
    }
}

impl Config {
    fn raw_config(
        &self,
        config: impl Serialize,
        format: &ConfigFormat,
    ) -> color_eyre::Result<String> {
        let content = match format {
            ConfigFormat::Yml => serde_yaml::to_string(&config)?,
            ConfigFormat::Json => serde_json::to_string_pretty(&config)?,
            ConfigFormat::Toml => {
                let value = serde_json::to_value(&config)?;
                let value: toml::Value = serde_json::from_value(value)?;
                toml::to_string(&value)?
            }
        };
        // This is danger log output
        // tracing::trace!(target: "config", "raw config: \n{}", content);
        Ok(content)
    }

    fn find_config_file(
        &self,
        name: impl AsRef<str>,
    ) -> color_eyre::Result<Option<(PathBuf, ConfigFormat)>> {
        let mut config_file = None;
        if !self.base_path.exists() {
            tracing::warn!(target: "bridger", "The base_path ({}) is not found.", self.base_path.display());
            return Ok(None);
        }
        let read_dir = std::fs::read_dir(&self.base_path)?;
        for path in read_dir {
            let file = path?.path();
            if !file.is_file() {
                continue;
            }
            let file_name = match file.file_name() {
                Some(v) => match v.to_str() {
                    Some(z) => z.to_string(),
                    None => continue,
                },
                None => continue,
            };
            if file_name.starts_with(name.as_ref()) {
                config_file = Some(file);
                break;
            }
        }
        match config_file {
            Some(v) => {
                let extension = v.extension().and_then(|v| v.to_str()).and_then(|s| {
                    match &s.to_lowercase()[..] {
                        "toml" => Some(ConfigFormat::Toml),
                        "json" => Some(ConfigFormat::Json),
                        "yml" => Some(ConfigFormat::Yml),
                        _ => None,
                    }
                });
                match extension {
                    Some(e) => Ok(Some((v, e))),
                    None => Ok(None),
                }
            }
            None => Ok(None),
        }
    }

    fn persist(
        &self,
        name: impl AsRef<str>,
        config: impl Serialize,
        format: Option<ConfigFormat>,
    ) -> color_eyre::Result<()> {
        if !self.base_path.exists() {
            std::fs::create_dir_all(&self.base_path)?;
        }
        let format = format.unwrap_or(
            self.find_config_file(name.as_ref())?
                .map(|(_, format)| format)
                .unwrap_or(ConfigFormat::Toml),
        );

        let config = self.raw_config(config, &format)?;
        let path = self
            .base_path
            .join(format!("{}.{}", name.as_ref(), format.extension()));
        std::fs::write(path, config)?;
        Ok(())
    }

    fn load<T: DeserializeOwned>(&self, name: impl AsRef<str>) -> color_eyre::Result<T> {
        if !self.base_path.exists() {
            return Err(std::io::Error::new(
                std::io::ErrorKind::NotFound,
                format!("The config path {:?} not found", &self.base_path),
            )
            .into());
        }

        let (path, _) = self.find_config_file(name.as_ref())?.ok_or_else(|| {
            BridgerError::Config(format!(
                "Not found config file for name: {} in path: {}",
                name.as_ref(),
                self.base_path.display()
            ))
        })?;
        let mut c = config::Config::default();
        c.merge(config::File::from(path.clone()))?;
        let tc = c.try_into::<T>().map_err(|e| {
            BridgerError::Config(format!(
                "Failed to load config: {:?} in path: {:?} for name {}",
                e,
                path,
                name.as_ref()
            ))
        })?;
        Ok(tc)
    }
}