saving and loading library implemented
This commit is contained in:
60
src/utils.rs
Normal file
60
src/utils.rs
Normal 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;
|
||||
}
|
||||
Reference in New Issue
Block a user