104 lines
2.8 KiB
Rust
104 lines
2.8 KiB
Rust
extern crate log;
|
||
use log::{info, warn};
|
||
|
||
use std::fs::File;
|
||
use std::io::{Read, Result};
|
||
use std::path::Path;
|
||
|
||
/// Type of supported settings format: yaml or json
|
||
pub enum SettingsType {
|
||
/// Files ending with the `yml` or `yaml` extension
|
||
Yaml,
|
||
|
||
/// Files ending with the `json` extension
|
||
Json,
|
||
}
|
||
|
||
/// Read a file’s content into a `String`
|
||
///
|
||
/// # Example
|
||
///
|
||
/// ```no_run
|
||
/// let path = std::path::Path::new("./some/path/to/my/file.json");
|
||
/// let content = lang_evolve_core::settings::utils::read_file(&path).unwrap();
|
||
/// ```
|
||
pub fn read_file(path: &Path) -> Result<String> {
|
||
let display = path.display();
|
||
let mut file = match File::open(&path) {
|
||
Err(why) => {
|
||
warn!("Could not read {}: {}", display, why.to_string());
|
||
return Err(why);
|
||
}
|
||
Ok(file) => file,
|
||
};
|
||
let mut content = String::new();
|
||
match file.read_to_string(&mut content) {
|
||
Err(why) => {
|
||
warn!("Could not read {}: {}", display, why.to_string());
|
||
return Err(why);
|
||
}
|
||
Ok(_) => {
|
||
info!("Content of {} read", display);
|
||
Ok(content)
|
||
}
|
||
}
|
||
}
|
||
|
||
pub fn write_file(path: &Path, content: String) -> Result<()> {
|
||
/// Write a `String` into a file
|
||
///
|
||
/// # Example
|
||
///
|
||
/// ```no_run
|
||
/// let content = String::from("This is my content");
|
||
/// let path = std::path::Path::new("./path/to/my/file.txt");
|
||
/// lang_evolve_core::settings::utils::write_file(&path, &content).unwrap();
|
||
/// ```
|
||
use std::io::prelude::*;
|
||
let mut file = match File::create(&path) {
|
||
Err(e) => {
|
||
warn!("Could not open file {}: {}", path.display(), e.to_string());
|
||
return Err(e);
|
||
}
|
||
Ok(file) => file,
|
||
};
|
||
match file.write_all(content.as_bytes()) {
|
||
Err(e) => {
|
||
warn!(
|
||
"Could not write settings to file {}: {}",
|
||
path.display(),
|
||
e.to_string()
|
||
);
|
||
return Err(e);
|
||
}
|
||
Ok(_) => {
|
||
info!("Wrote settings to file {}", path.display());
|
||
}
|
||
};
|
||
Ok(())
|
||
}
|
||
|
||
pub fn get_file_type(path: &Path) -> Result<SettingsType> {
|
||
let extension = match path.extension() {
|
||
None => {
|
||
return Err(std::io::Error::new(
|
||
std::io::ErrorKind::InvalidInput,
|
||
"File has no extension",
|
||
));
|
||
}
|
||
Some(val) => val,
|
||
};
|
||
let extension = extension
|
||
.to_str()
|
||
.expect("Could not get String out of extension")
|
||
.to_lowercase();
|
||
match extension.as_str() {
|
||
"yml" | "yaml" => Ok(SettingsType::Yaml),
|
||
"json" => Ok(SettingsType::Json),
|
||
_ => Err(std::io::Error::new(
|
||
std::io::ErrorKind::InvalidInput,
|
||
"Invalid extension",
|
||
)),
|
||
}
|
||
}
|