2023-07-21 16:11:10 -04:00
|
|
|
use crate::lox_context;
|
|
|
|
use chrono::prelude::*;
|
|
|
|
use std::{
|
|
|
|
env,
|
|
|
|
error::Error,
|
|
|
|
fs::{DirEntry, File},
|
|
|
|
io::BufReader,
|
|
|
|
path::Path,
|
|
|
|
};
|
|
|
|
|
|
|
|
pub fn read_context_from_file<P: AsRef<Path>>(
|
|
|
|
path: P,
|
|
|
|
) -> Result<lox_context::LoxServerContext, Box<dyn Error>> {
|
|
|
|
let file = File::open(path)?;
|
|
|
|
let reader = BufReader::new(file);
|
|
|
|
let context = serde_json::from_reader(reader)?;
|
|
|
|
Ok(context)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn write_context_to_file(context: lox_context::LoxServerContext) {
|
|
|
|
let mut date = Local::now().format("%Y-%m-%d_%H:%M:%S").to_string();
|
|
|
|
let path = "_lox.json";
|
|
|
|
date.push_str(path);
|
2023-07-28 14:04:23 -04:00
|
|
|
let file = File::create(&date)
|
|
|
|
.expect(format!("Unable to write to db file: {:?} !", stringify!($date)).as_str());
|
2023-07-21 16:11:10 -04:00
|
|
|
let _ = serde_json::to_writer(file, &context);
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn check_db_exists() -> Option<DirEntry> {
|
|
|
|
let current_path = env::current_dir().expect("Unable to access current dir");
|
|
|
|
std::fs::read_dir(current_path)
|
|
|
|
.expect("Couldn't read local directory")
|
|
|
|
.flatten() // Remove failed
|
|
|
|
.filter(|f| {
|
|
|
|
f.metadata().unwrap().is_file()
|
|
|
|
&& (f.file_name().into_string().unwrap().contains("_lox.json"))
|
|
|
|
}) // Filter out directories (only consider files)
|
|
|
|
.max_by_key(|x| x.metadata().unwrap().modified().unwrap())
|
|
|
|
}
|