lexa_fs/
load.rs

1// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
2// ┃ Copyright: (c) 2023, Mike 'PhiSyX' S. (https://github.com/PhiSyX)         ┃
3// ┃ SPDX-License-Identifier: MPL-2.0                                          ┃
4// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
5// ┃                                                                           ┃
6// ┃  This Source Code Form is subject to the terms of the Mozilla Public      ┃
7// ┃  License, v. 2.0. If a copy of the MPL was not distributed with this      ┃
8// ┃  file, You can obtain one at https://mozilla.org/MPL/2.0/.                ┃
9// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
10
11use std::{fmt, fs, io, path};
12
13use crate::error::mapped_to_io_invalid_data_err;
14use crate::Extension;
15
16// -------- //
17// Fonction //
18// -------- //
19
20/// Charge un fichier à partir d'un dossier, et le dé-sérialise en un type donné
21/// par générique.
22pub fn load<T>(
23	directory: impl AsRef<path::Path>,
24	filename: impl fmt::Display,
25	extension: impl Into<Extension> + fmt::Display,
26) -> io::Result<T>
27where
28	T: serde::de::DeserializeOwned,
29{
30	let fullpath = path::Path::new(directory.as_ref()).join(format!("{filename}.{extension}"));
31
32	match extension.into() {
33		| Extension::ENV => {
34			let content = fs::read_to_string(fullpath)?;
35			lexa_env::from_str(&content).map_err(mapped_to_io_invalid_data_err)
36		}
37
38		| Extension::JSON => {
39			let fd = fs::File::open(fullpath)?;
40			serde_json::from_reader(fd).map_err(mapped_to_io_invalid_data_err)
41		}
42
43		| Extension::TOML => {
44			let content = fs::read_to_string(fullpath)?;
45			serde_toml::from_str(&content).map_err(mapped_to_io_invalid_data_err)
46		}
47
48		| Extension::YAML => {
49			let fd = fs::File::open(fullpath)?;
50			serde_yaml::from_reader(fd).map_err(mapped_to_io_invalid_data_err)
51		}
52	}
53}