]> git.r.bdr.sh - rbdr/blog/blob - src/remote/mod.rs
de90ef57f4f2b6bb585ae38c996fe75cf849963f
[rbdr/blog] / src / remote / mod.rs
1 mod git;
2
3 use std::fs::{create_dir_all, remove_file, write, File};
4 use std::io::{Error, ErrorKind::Other, Read, Result};
5 use std::path::PathBuf;
6
7 use git::Git;
8
9 pub 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
15 pub 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
21 pub fn remove(remote_config: &PathBuf) -> Result<()> {
22 if remote_config.exists() {
23 remove_file(remote_config)?
24 }
25 Ok(())
26 }
27
28 pub fn sync_up(data_directory: &PathBuf, remote_config: &PathBuf) -> Result<()> {
29 let remote_address = read_remote(remote_config)
30 .expect("No remote is configured");
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
41 pub fn sync_down(data_directory: &PathBuf, remote_config: &PathBuf) -> Result<()> {
42 let remote_address = read_remote(remote_config)
43 .expect("No remote is configured");
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
54 fn available_remotes() -> Vec<Box<dyn Remote>> {
55 vec![
56 Box::new(Git::new())
57 ]
58 }
59
60 fn 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 }