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)?;
}
std::fs::write(path, serde_json::to_string_pretty(self)?).with_context(|| format!("cannot write {}", path.display()))?;
private(path);
Ok(())
}
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;
}