emerald_vault/migration/
types.rs

1use crate::error::VaultError;
2use std::path::Path;
3use uuid::Uuid;
4
5/// Migration Results
6#[derive(Clone, Debug, PartialEq, Eq)]
7#[derive(Default)]
8pub struct MigrationResult {
9    /// Ids of newly created wallets
10    pub wallets: Vec<Uuid>,
11    /// Log of the migration
12    pub logs: Vec<LogMessage>,
13}
14
15#[derive(Clone, Debug, PartialEq, Eq)]
16pub enum LogMessage {
17    Error(String),
18    Warning(String),
19    Info(String),
20}
21
22#[derive(Clone, Debug, PartialEq, Eq)]
23pub enum MigrationError {
24    VaultError(String),
25    OtherError(String),
26}
27
28pub trait Migrate {
29    fn migrate<P>(&mut self, target: P) -> Result<&MigrationResult, MigrationError>
30    where
31        P: AsRef<Path>;
32}
33
34impl From<VaultError> for MigrationError {
35    fn from(err: VaultError) -> Self {
36        MigrationError::VaultError(err.to_string())
37    }
38}
39
40impl From<String> for MigrationError {
41    fn from(err: String) -> Self {
42        MigrationError::OtherError(err)
43    }
44}
45
46
47impl LogMessage {
48    fn get_msg(&self) -> &String {
49        match self {
50            LogMessage::Error(msg) => msg,
51            LogMessage::Warning(msg) => msg,
52            LogMessage::Info(msg) => msg,
53        }
54    }
55}
56
57impl MigrationResult {
58    /// Add ERROR message into the log
59    pub fn error(&mut self, msg: String) {
60        self.logs.push(LogMessage::Error(msg))
61    }
62    /// Add WARN message into the log
63    pub fn warn(&mut self, msg: String) {
64        self.logs.push(LogMessage::Warning(msg))
65    }
66    /// Add INFO message into the log
67    pub fn info(&mut self, msg: String) {
68        self.logs.push(LogMessage::Info(msg))
69    }
70
71    /// _Replaces_ list of wallet ids with new list
72    pub fn set_wallets(&mut self, wallets: Vec<Uuid>) {
73        self.wallets = wallets
74    }
75
76    /// Convert logs into a multiline string, suitable to save into a file
77    pub fn logs_to_string(&self) -> String {
78        let mut buf = String::new();
79
80        self.logs.iter().for_each(|l| {
81            match l {
82                LogMessage::Error(_) => buf.push_str("ERROR  "),
83                LogMessage::Warning(_) => buf.push_str("WARN   "),
84                LogMessage::Info(_) => buf.push_str("INFO   "),
85            };
86            buf.push_str(l.get_msg());
87            buf.push('\n');
88        });
89
90        buf
91    }
92
93    pub fn has_log(&self) -> bool {
94        self.logs.iter().any(|l| match l {
95            LogMessage::Warning(_) | LogMessage::Error(_) => true,
96            LogMessage::Info(_) => false,
97        })
98    }
99}