Compare commits

..

3 Commits

Author SHA1 Message Date
8642067eb3 Updated settings::utils::write_file’s signature for more flexibility
`write_file` now accepts as its second argument any type that
implements the `ToString` trait so that not only Strings will be
accepted but any type that can be turned into one.
2020-03-27 19:09:34 +01:00
488ceba1bb Added some doc and tests 2020-03-27 19:08:47 +01:00
2e0c16e97c Added functions to import and export settings and refactoring 2020-03-27 18:25:20 +01:00
5 changed files with 256 additions and 41 deletions

4
.gitignore vendored
View File

@@ -1,2 +1,6 @@
/target /target
Cargo.lock Cargo.lock
*.log
*.yaml
*.yml
*.json

View File

@@ -1,3 +1,17 @@
#![crate_name = "lang_evolve_core"]
//! # LangEvolveCore
//!
//! `lang_evolve_core` is the core crate used by two other crates:
//! `lang_evolve_cli` and `lang_evolve_gui`.
//!
//! # What it does
//!
//! LangEvolveCore is the crate that hosts all the core logic behind LangEvolve,
//! a conlanging software developped after the
//! [original software](https://github.com/ceronyon/LangEvolve) which applies
//! user-defined sound changes to words and texts based on regex expressions.
use std::fs::File; use std::fs::File;
use std::io::Result; use std::io::Result;
use std::path::PathBuf; use std::path::PathBuf;
@@ -7,13 +21,28 @@ extern crate simplelog;
use log::{info, warn}; use log::{info, warn};
use simplelog::*; use simplelog::*;
#[cfg(test)] pub mod settings;
mod tests;
mod settings;
use settings::utils; use settings::utils;
#[allow(dead_code)] /// Initializes the crate
///
/// # What it does
///
/// Initializing the crate allows to initialize its logging system. All its logs
/// will be written to the file `core.log` while the errors will also be shown
/// in the terminal.
///
/// # Return type
///
/// This function returns a null object if it succeeds. However, if it does not,
/// it will send a `log::SetLoggerError` back.
///
/// # Example usage
///
/// Its usage is extremely simple, just call it before you do anything with it:
/// ```
/// lang_evolve_core::init();
/// ```
pub fn init() -> std::result::Result<(), log::SetLoggerError> { pub fn init() -> std::result::Result<(), log::SetLoggerError> {
match CombinedLogger::init(vec![ match CombinedLogger::init(vec![
TermLogger::new( TermLogger::new(
@@ -39,7 +68,7 @@ pub fn init() -> std::result::Result<(), log::SetLoggerError> {
} }
} }
#[allow(dead_code)] /// Import user input from a text file and return them as a String
fn import_words(path: PathBuf) -> Result<String> { pub fn import_input(path: PathBuf) -> Result<String> {
utils::read_file(&path) utils::read_file(&path)
} }

View File

@@ -1,23 +1,19 @@
extern crate serde; extern crate serde;
extern crate serde_json; extern crate serde_json;
extern crate serde_yaml; extern crate serde_yaml;
use serde::Deserialize; use serde::{Deserialize, Serialize};
extern crate log; extern crate log;
use log::warn; use log::warn;
// mod utils; // mod utils;
pub mod utils; pub mod utils;
use utils::SettingsType;
#[allow(dead_code)] #[allow(dead_code)]
const RULESET_CURRENT_VERSION: &'static str = "1"; const RULESET_CURRENT_VERSION: &'static str = "1";
pub enum SettingsType { #[derive(Debug, Deserialize, Serialize)]
Yaml,
Json,
}
#[derive(Debug, Deserialize)]
pub struct Settings { pub struct Settings {
#[serde(default = "Settings::get_ruleset_version")] #[serde(default = "Settings::get_ruleset_version")]
version: String, version: String,
@@ -27,8 +23,22 @@ pub struct Settings {
rules: Vec<(String, String)>, rules: Vec<(String, String)>,
} }
/// Representation inside the crate of LangEvolves settings.
impl Settings { impl Settings {
#[allow(dead_code)] /// Creates a new empty instance of `Settings`
///
/// # Example
///
/// ```
/// let s = lang_evolve_core::settings::Settings::new();
/// let content_yaml = r#"---
/// version: "1"
/// categories: []
/// rules: []"#;
/// let content_json = r#"{"version":"1","categories":[],"rules":[]}"#;
/// assert_eq!(content_yaml, serde_yaml::to_string(&s).unwrap());
/// assert_eq!(content_json, serde_json::to_string(&s).unwrap());
/// ```
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
version: Self::get_ruleset_version(), version: Self::get_ruleset_version(),
@@ -37,27 +47,35 @@ impl Settings {
} }
} }
fn get_ruleset_version() -> String { /// Import settings from an imput file. The currently allowed file formats
String::from(RULESET_CURRENT_VERSION) /// are:
} /// - JSON - with the `.json` extension
/// - Yaml - with the `.yaml` or `.yml` extension
#[allow(dead_code)] /// The format will be automatically detected based on the filename
pub fn import(path: &std::path::PathBuf) -> std::io::Result<Self> { /// extension.
///
/// # Arguments
///
/// * `path` - File to open and load settings from
///
/// # Example
///
/// ```no_run
/// use std::path::Path;
/// use lang_evolve_core::settings::Settings;
/// let path_json = Path::new("settings.json");
/// let _s_json = Settings::import(&path_json).unwrap();
///
/// let path_yaml = Path::new("settings.yaml");
/// let _s_yaml = Settings::import(&path_yaml).unwrap();
///
/// let path_yml = Path::new("settings.yml");
/// let _s_yml = Settings::import(&path_yml).unwrap();
/// ```
pub fn import(path: &std::path::Path) -> std::io::Result<Self> {
use SettingsType::*; use SettingsType::*;
let display = path.display(); let display = path.display();
let extension = path.extension().unwrap(); let file_type = utils::get_file_type(&path).unwrap();
let extension = extension.to_str().unwrap();
let method = match extension {
"yaml" => Yaml,
"json" => Json,
_ => {
use std::io::{Error, ErrorKind};
return Err(Error::new(
ErrorKind::InvalidInput,
"File must have \"yaml\" or \"json\" extension",
));
}
};
let content = match utils::read_file(&path) { let content = match utils::read_file(&path) {
Err(e) => { Err(e) => {
warn!("Could not read file {}: {}", display, e.to_string()); warn!("Could not read file {}: {}", display, e.to_string());
@@ -66,7 +84,7 @@ impl Settings {
Ok(content) => content, Ok(content) => content,
}; };
let settings: Settings = match method { let settings: Settings = match file_type {
Yaml => match serde_yaml::from_str(&content) { Yaml => match serde_yaml::from_str(&content) {
Err(e) => { Err(e) => {
warn!("Could not import settings: {}", e.to_string()); warn!("Could not import settings: {}", e.to_string());
@@ -91,4 +109,94 @@ impl Settings {
Ok(settings) Ok(settings)
} }
/// Export the current rules to a file. The allowed file formats are either
/// a YAML file or a Json file, hence the allowed filename extension are:
/// * "yml" or "yaml" for Yaml files
/// * "json" for Json files
/// The format is detected automatically depending on the extension of the
/// filename.
///
/// # Arguments
///
/// * `path` - Path to write and export settings to
///
/// # Example
///
/// ```
/// use std::path::Path;
/// let s = lang_evolve_core::settings::Settings::new();
///
/// // Export to JSON
/// let path_json = Path::new("./output.json");
/// s.export(&path_json).unwrap();
///
/// // Export to Yaml, both ".yml" and ".yaml" work
/// let path_yaml = Path::new("./output.yaml");
/// s.export(&path_yaml).unwrap();
/// let path_yml = Path::new("./output.yml");
/// s.export(&path_yml).unwrap();
/// ```
pub fn export(&self, path: &std::path::Path) -> std::io::Result<()> {
let filetype = utils::get_file_type(&path).unwrap();
let content = match filetype {
SettingsType::Yaml => match serde_yaml::to_string(&self) {
Err(e) => {
warn!("Could not serialize settings: {}", e.to_string());
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
e,
));
}
Ok(val) => val,
},
SettingsType::Json => match serde_json::to_string(&self) {
Err(e) => {
warn!("Could not serialize settings: {}", e.to_string());
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
e,
));
}
Ok(val) => val,
},
};
utils::write_file(&path, &content)
}
/// Get the current ruleset version of LangEvolve.
fn get_ruleset_version() -> String {
String::from(RULESET_CURRENT_VERSION)
}
}
impl PartialEq for Settings {
fn eq(&self, other: &Self) -> bool {
self.version == other.version
&& self.categories == other.categories
&& self.rules == other.rules
}
}
impl Eq for Settings {}
#[test]
fn write_settings() {
let s = Settings::new();
let path = std::path::Path::new("test.yaml");
let settings = r#"---
version: "1"
categories: []
rules: []"#;
utils::write_file(&path, &serde_yaml::to_string(&s).unwrap()).unwrap();
assert_eq!(settings, utils::read_file(&path).unwrap());
}
#[test]
fn read_settings() {
let s1 = Settings::new();
let path = std::path::Path::new("test.yml");
s1.export(&path).unwrap();
let s2 = Settings::import(&path).unwrap();
assert_eq!(s1, s2);
} }

View File

@@ -3,9 +3,26 @@ use log::{info, warn};
use std::fs::File; use std::fs::File;
use std::io::{Read, Result}; use std::io::{Read, Result};
use std::path::PathBuf; use std::path::Path;
pub fn read_file(path: &PathBuf) -> Result<String> { /// 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 files 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 display = path.display();
let mut file = match File::open(&path) { let mut file = match File::open(&path) {
Err(why) => { Err(why) => {
@@ -26,3 +43,64 @@ pub fn read_file(path: &PathBuf) -> Result<String> {
} }
} }
} }
/// 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();
/// ```
pub fn write_file<S>(path: &Path, content: &S) -> Result<()>
where
S: std::string::ToString,
{
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.to_string().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",
)),
}
}

View File

@@ -1,4 +0,0 @@
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}