borg-hive 0.0.2

Automated backups using Borg Backup
// borg-hive - Zero-configuration wrapper for borg
// Copyright (C) 2017  Lorenzo Villani
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

use std::collections;
use std::fs;

use chrono;
use serde_json;

use config;
use paths;

use errors::*;

#[derive(PartialEq, Serialize, Deserialize, Debug)]
pub struct State {
    pub success: collections::HashMap<String, chrono::DateTime<chrono::Utc>>,
}

impl State {
    pub fn new() -> State {
        State { success: collections::HashMap::new() }
    }

    pub fn load() -> Result<Self> {
        let path = paths::state_file()?;

        if !path.is_file() {
            return Ok(Self::new());
        }

        Ok(serde_json::from_reader(fs::File::open(&path)?).chain_err(
            || "cannot load the state file",
        )?)
    }

    pub fn mark_success(&mut self, destination: &config::Destination) -> Result<()> {
        self.success.insert(
            destination.repo.clone(),
            chrono::Utc::now(),
        );

        self.save()
    }

    pub fn save(&self) -> Result<()> {
        let mut file = fs::File::create(paths::state_file()?)?;

        Ok(serde_json::to_writer_pretty(&mut file, &self).chain_err(
            || "cannot save the state file",
        )?)
    }
}