shrupl/src/appstate.rs

50 lines
1.2 KiB
Rust
Raw Normal View History

2025-06-02 23:57:17 +00:00
use std::{
fs,
io::{self, Write},
path::Path,
};
use log::{debug, trace};
use serde::{Deserialize, Serialize};
use super::{
cli::Cli,
sharry::{Alias, File, Share},
};
#[derive(Serialize, Deserialize, Debug)]
pub struct AppState {
alias: Alias,
share: Share,
files: Vec<File>,
}
impl AppState {
fn load(file_name: impl AsRef<Path>) -> io::Result<Self> {
let content = fs::read_to_string(file_name)?;
let state = serde_json::from_str(&content).map_err(io::Error::other)?;
Ok(state)
}
fn save(&self, file_name: impl AsRef<Path>) -> io::Result<()> {
let json = serde_json::to_string_pretty(self).map_err(io::Error::other)?;
let mut file = fs::File::create(file_name)?;
file.write_all(json.as_bytes())?;
Ok(())
}
pub fn try_resume(args: &Cli) -> Option<Self> {
let file_name = dirs_next::cache_dir()?
.join("shrupl")
.join(format!("{}.json", args.get_hash()));
trace!("loading from {}", file_name.display());
Self::load(&file_name)
.inspect_err(|e| debug!("could not resume from {}: {e}", file_name.display()))
.ok()
}
}