use crate::model::{Location, Severity};
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct State {
#[serde(default)]
pub known: BTreeSet<String>,
#[serde(default)]
pub rotated: BTreeSet<String>,
#[serde(default)]
pub ignored: BTreeSet<String>,
#[serde(default)]
pub masked: BTreeMap<String, Masked>,
#[serde(default)]
pub known_hosts: BTreeSet<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Masked {
pub rule: String,
pub severity: Severity,
pub preview: String,
pub location: Location,
pub edits: Vec<Edit>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Edit {
pub file: PathBuf,
pub backup: PathBuf,
}
impl State {
pub fn load(path: &Path) -> Result<Self> {
match std::fs::read_to_string(path) {
Ok(text) => serde_json::from_str(&text).with_context(|| format!("{} is not valid", path.display())),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
Err(e) => Err(e).with_context(|| format!("cannot read {}", path.display())),
}
}
pub fn save(&self, path: &Path) -> Result<()> {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
let mut tmp = path.to_path_buf();
tmp.set_extension("json.tmp");
std::fs::write(&tmp, serde_json::to_string_pretty(self)?).with_context(|| format!("cannot write {}", tmp.display()))?;
private(&tmp);
std::fs::rename(&tmp, path).with_context(|| format!("cannot replace {}", path.display()))?;
private(path);
Ok(())
}
#[cfg_attr(not(feature = "tui"), allow(dead_code))]
pub fn toggle(set: &mut BTreeSet<String>, id: &str) -> bool {
if set.remove(id) {
false
} else {
set.insert(id.to_string());
true
}
}
}
pub fn private(path: &Path) {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = if path.is_dir() { 0o700 } else { 0o600 };
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode));
}
#[cfg(not(unix))]
let _ = path;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn saves_through_a_temporary_file_and_round_trips() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("state.json");
let mut state = State::default();
state.known.insert("0123456789abcdef".into());
state.save(&path).unwrap();
assert!(State::load(&path).unwrap().known.contains("0123456789abcdef"));
assert!(!path.with_extension("json.tmp").exists(), "the temporary file is renamed away");
state.known.insert("fedcba9876543210".into());
state.save(&path).unwrap();
assert_eq!(State::load(&path).unwrap().known.len(), 2);
}
}