39 lines
1.2 KiB
Rust
39 lines
1.2 KiB
Rust
![]() |
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);
|
||
|
let file = File::create(&date).expect("Unable to write to file!");
|
||
|
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())
|
||
|
}
|