]> git.r.bdr.sh - rbdr/blog/blame - src/remote/mod.rs
Add mac
[rbdr/blog] / src / remote / mod.rs
CommitLineData
172f4c88
RBR
1mod git;
2
3use std::fs::{create_dir_all, remove_file, write, File};
4use std::io::{Error, ErrorKind::Other, Read, Result};
5use std::path::PathBuf;
6
7use git::Git;
8
9pub trait Remote {
10 fn can_handle(&self, remote: &str) -> bool;
11 fn sync_up(&self, remote: &str, directory: &PathBuf) -> Result<()>;
12 fn sync_down(&self, remote: &str, directory: &PathBuf) -> Result<()>;
13}
14
15pub fn add(config_directory: &PathBuf, remote_config: &PathBuf, remote: &String) -> Result<()> {
16 create_dir_all(config_directory)?;
17 write(remote_config, remote)?;
18 Ok(())
19}
20
21pub fn remove(remote_config: &PathBuf) -> Result<()> {
22 if remote_config.exists() {
23 remove_file(remote_config)?
24 }
25 Ok(())
26}
27
28pub fn sync_up(data_directory: &PathBuf, remote_config: &PathBuf) -> Result<()> {
29 let remote_address = read_remote(remote_config)
50f53dc4 30 .ok_or_else(|| Error::new(Other, "No remote is configured"))?;
172f4c88
RBR
31 create_dir_all(data_directory)?;
32 let remotes = available_remotes();
33 for remote in remotes {
34 if remote.can_handle(&remote_address) {
35 return remote.sync_up(&remote_address, data_directory);
36 }
37 }
38 Err(Error::new(Other, "No valid strategies found for your configured remote."))
39}
40
41pub fn sync_down(data_directory: &PathBuf, remote_config: &PathBuf) -> Result<()> {
42 let remote_address = read_remote(remote_config)
50f53dc4 43 .ok_or_else(|| Error::new(Other, "No remote is configured"))?;
172f4c88
RBR
44 create_dir_all(data_directory)?;
45 let remotes = available_remotes();
46 for remote in remotes {
47 if remote.can_handle(&remote_address) {
48 return remote.sync_down(&remote_address, data_directory);
49 }
50 }
51 Err(Error::new(Other, "No valid strategies found for your configured remote."))
52}
53
54fn available_remotes() -> Vec<Box<dyn Remote>> {
55 vec![
56 Box::new(Git::new())
57 ]
58}
59
60fn read_remote(file_path: &PathBuf) -> Option<String> {
61 let mut file = File::open(file_path).ok()?;
62 let mut contents = String::new();
63 file.read_to_string(&mut contents).ok()?;
64 Some(contents)
65}