saving and loading library implemented

This commit is contained in:
2026-08-19 08:50:28 +01:00
parent 3e5079fd07
commit 412b77851b
3 changed files with 122 additions and 49 deletions

60
src/utils.rs Normal file
View File

@@ -0,0 +1,60 @@
use crate::structs::{Library, Shelf};
use std::{env, fs, io, io::Read};
use xdg::BaseDirectories;
pub fn get_shelf_index(shelves: &Vec<Shelf>, id: &u8) -> Option<usize> {
shelves.iter().position(|shelf| shelf.id == *id)
}
pub fn deserialize_state_file() -> io::Result<Library> {
let xdg_dirs = get_xdg();
let state_file_path = xdg_dirs.place_state_file("shelf-state.json")?;
let state_file_content = match fs::read_to_string(state_file_path) {
Ok(content) => content,
Err(e) => {
eprintln!("Could not read state file: {}", e);
return Ok(initialize_library());
}
};
let state_file_decoded: Library = serde_json::from_str(&state_file_content)?;
Ok(state_file_decoded)
}
pub fn get_xdg() -> BaseDirectories {
let xdg_dirs = xdg::BaseDirectories::with_prefix("shelf");
return xdg_dirs;
}
pub fn get_state_file() -> io::Result<std::path::PathBuf> {
let xdg_dirs = get_xdg();
let state_file_path = xdg_dirs.place_state_file("shelf-state.json")?;
Ok(state_file_path)
}
pub fn save_library(library: Library) -> io::Result<()> {
let seralized_library = serde_json::to_string(&library).unwrap_or_default();
let state_file = get_state_file()?;
fs::write(state_file, seralized_library)?;
Ok(())
}
pub fn initialize_library() -> Library {
let default_shelf: Shelf = Shelf {
id: 0,
name: "default".to_string(),
content: Vec::new(),
};
let mut shelf_vec: Vec<Shelf> = Vec::new();
shelf_vec.push(default_shelf);
let default_library: Library = Library {
current_shelf: 0,
shelves: shelf_vec,
};
return default_library;
}