From 3d6f5a264ff3aff3121ffa0dd2960066c43ab106 Mon Sep 17 00:00:00 2001 From: Jonni Liljamo Date: Thu, 22 Dec 2022 12:45:13 +0200 Subject: [PATCH] Generic functions for saving and loading --- sdbclient/src/util/mod.rs | 1 + sdbclient/src/util/sl.rs | 89 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+) create mode 100644 sdbclient/src/util/sl.rs diff --git a/sdbclient/src/util/mod.rs b/sdbclient/src/util/mod.rs index 9ba9383..3bcda96 100644 --- a/sdbclient/src/util/mod.rs +++ b/sdbclient/src/util/mod.rs @@ -7,3 +7,4 @@ */ pub mod eguipwd; +pub mod sl; diff --git a/sdbclient/src/util/sl.rs b/sdbclient/src/util/sl.rs new file mode 100644 index 0000000..dde58c6 --- /dev/null +++ b/sdbclient/src/util/sl.rs @@ -0,0 +1,89 @@ +/* + * This file is part of sdbclient + * Copyright (C) 2022 Jonni Liljamo + * + * Licensed under GPL-3.0-only. + * See LICENSE for licensing information. + */ + +use bevy::prelude::*; +use bevy_console::PrintConsoleLine; + +pub fn load serde::Deserialize<'a>>( + file_path: &str, + mut console: EventWriter, +) -> T { + match std::path::Path::new(file_path).exists() { + true => { + console.send(PrintConsoleLine::new(format!( + "sl::load found '{}'", + file_path + ))); + let yaml: Vec = std::fs::read(file_path.clone()).unwrap(); + serde_json::from_str(std::str::from_utf8(&yaml).unwrap()).expect(&format!( + "sl::load couldn't deserialize the config at '{}'", + file_path + )) + } + false => { + console.send(PrintConsoleLine::new(format!( + "sl::load couldn't find '{}', using defaults", + file_path + ))); + T::default() + } + } +} + +pub fn save( + target_dir: &str, + file_name: &str, + value: &T, + mut console: EventWriter, +) -> bool +where + T: ?Sized + serde::Serialize, +{ + let file_path: String = format!("{}/{}", target_dir, file_name); + let yaml: String = serde_json::to_string(&value).unwrap(); + + match std::path::Path::new(target_dir).exists() { + true => {} + false => { + console.send(PrintConsoleLine::new(format!( + "sl::save creating target dir '{}'", + target_dir + ))); + match std::fs::create_dir_all(target_dir) { + Ok(_) => {} + Err(_) => { + console.send(PrintConsoleLine::new(format!( + "sl::save couldn't create target dir '{}'", + target_dir + ))); + console.send(PrintConsoleLine::new(format!( + "sl::save nothing will be saved!" + ))); + return false; + } + } + } + } + + match std::fs::write(&file_path, yaml) { + Ok(_) => { + console.send(PrintConsoleLine::new(format!( + "sl::save wrote file '{}'", + file_path + ))); + true + } + Err(_) => { + console.send(PrintConsoleLine::new(format!( + "sl::save couldn't write file '{}'", + file_path + ))); + false + } + } +} -- 2.44.1