cargo_backup/remote/
mod.rs

1use crate::Package;
2use serde::{de, ser};
3use std::{
4    error::Error,
5    fs::{create_dir, read_to_string, write},
6};
7
8pub mod github;
9
10pub trait RemoteProvider {
11    /// Get the keyring for the provider.
12    fn get_keyring() -> keyring::Entry;
13    /// Initializes a new `RemoteProvider`
14    fn new() -> Self;
15    /// Pulls a backup from a remote server.
16    fn pull(&self) -> Result<Vec<Package>, Box<dyn Error>>;
17    /// Pushes a backup to a remote server.
18    fn push(&self, backup: &[Package]) -> Result<(), Box<dyn Error>>;
19    /// Obtain a access token for the remote server.
20    fn login(&self, relogin: bool) -> Result<(), Box<dyn Error>>;
21    /// Set the id for the backup.
22    fn set_id(&self, id: String) -> Result<(), Box<dyn Error>>;
23}
24
25/// # Example
26/// ```
27/// struct SomeProvider;
28///
29/// impl ProviderConfig for SomeProvider {
30///     fn get_name() -> String {
31///         String::from("provider")
32///     }
33/// }
34/// ```
35pub(crate) trait ProviderConfig {
36    /// Gets the name of the Provider.
37    /// Used for the config file name.
38    fn get_name() -> String;
39}
40
41pub(crate) fn get_config<T>() -> T
42where
43    T: de::DeserializeOwned,
44    T: ser::Serialize,
45    T: Default,
46    T: ProviderConfig,
47{
48    let path = dirs::config_dir().unwrap().join("cargo-backup");
49
50    if !path.exists() {
51        create_dir(&path).unwrap();
52    }
53
54    let path = path.join(format!("{}.toml", T::get_name()));
55
56    if path.exists() {
57        let content = read_to_string(&path).unwrap();
58        let config: T = toml::from_str(&content).unwrap();
59        config
60    } else {
61        let config = T::default();
62        let content = toml::to_string(&config).unwrap();
63        write(&path, content).unwrap();
64        config
65    }
66}
67
68pub(crate) fn save_config<T>(config: T)
69where
70    T: ser::Serialize,
71    T: ProviderConfig,
72{
73    let path = dirs::config_dir().unwrap().join("cargo-backup");
74
75    if !path.exists() {
76        create_dir(&path).unwrap();
77    }
78
79    let path = path.join(format!("{}.toml", T::get_name()));
80
81    write(path, toml::to_string(&config).unwrap()).unwrap();
82}