aboutsummaryrefslogtreecommitdiff
path: root/src/remote/git.rs
blob: 66c5a89b115756bb06438a3f381c40080217e56e (plain)
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
use std::io::{Error, ErrorKind::Other, Result};
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::time::{SystemTime, UNIX_EPOCH};

pub struct Git;

impl Git {
    pub fn new() -> Self {
        Git
    }
}

impl super::Remote for Git {
    fn can_handle(&self, _: &str) -> bool {
        // If we ever implement another remote we will want a check strategy
        true
    }

    fn sync_up(&self, remote: &str, directory: &PathBuf) -> Result<()> {
        let timestamp = SystemTime::now().duration_since(UNIX_EPOCH)
            .map_err(|_| Error::new(Other, "Invalid time"))?
            .as_millis();

        let commands = vec![
            format!("cd {} && git init -b main", directory.display()),
            format!("cd {} && git add .", directory.display()),
            format!("cd {} && git commit --allow-empty -m blog-sync-up-{}", directory.display(), timestamp),
            format!("cd {} && git push {} main --force", directory.display(), remote),
        ];

        for command in commands {
            Command::new("sh")
                .arg("-c")
                .arg(&command)
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .status()
                .map_err(|_| Error::new(Other, "Failed while performing sync up with git"))?;
        }

        Ok(())
    }

    fn sync_down(&self, remote: &str, directory: &PathBuf) -> Result<()> {
        let commands = vec![
            format!("cd {} && git init -b main", directory.display()),
            format!("cd {} && git checkout .", directory.display()),
            format!("cd {} && git clean . -f", directory.display()),
            format!("cd {} && git pull {} main", directory.display(), remote),
        ];

        for command in commands {
            Command::new("sh")
                .arg("-c")
                .arg(&command)
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .status()
                .map_err(|_| Error::new(Other, "Failed while performing sync down with git"))?;
        }
        Ok(())
    }
}