Add: id, level validation

This commit is contained in:
itiB
2022-04-05 01:52:44 +09:00
parent 026d18a605
commit 373dd0f8c7
3 changed files with 22 additions and 14 deletions

View File

@@ -10,7 +10,7 @@ use std::io::BufWriter;
use std::io::{BufRead, BufReader};
lazy_static! {
static ref IDS_REGEX: Regex =
pub static ref IDS_REGEX: Regex =
Regex::new(r"^[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}$").unwrap();
}

View File

@@ -120,10 +120,8 @@ impl App {
{
if Path::new(level_tuning_config_path).exists() {
if let Err(err) = LevelTuning::run(level_tuning_config_path) {
AlertMessage::alert(
&mut BufWriter::new(std::io::stderr().lock()),
&err,
).ok();
AlertMessage::alert(&mut BufWriter::new(std::io::stderr().lock()), &err)
.ok();
}
} else {
AlertMessage::alert(

View File

@@ -4,7 +4,6 @@ use crate::yaml::ParseYaml;
use std::collections::HashMap;
use std::fs::{self, File};
use std::io::Write;
pub struct LevelTuning {}
impl LevelTuning {
@@ -18,11 +17,26 @@ impl LevelTuning {
let mut tuning_map: HashMap<String, String> = HashMap::new();
read_result.unwrap().into_iter().try_for_each(|line| -> Result<(), String> {
let id = match line.get(0) {
Some(_id) => _id, // TODO: Validate id
Some(_id) => {
if !filter::IDS_REGEX.is_match(_id) {
return Result::Err(format!("Failed to read level tuning file. {} is not correct id format, fix it.", _id));
}
_id
}
_ => return Result::Err("Failed to read id...".to_string())
};
let level = match line.get(1) {
Some(_level) => _level, // TODO: Validate level
Some(_level) => {
if _level.starts_with("informational")
|| _level.starts_with("low")
|| _level.starts_with("medium")
|| _level.starts_with("high")
|| _level.starts_with("critical") {
_level
} else {
return Result::Err("level tuning file's level must in informational, low, medium, high, critical".to_string())
}
}
_ => return Result::Err("Failed to read level...".to_string())
};
tuning_map.insert(id.to_string(), level.to_string());
@@ -71,16 +85,12 @@ impl LevelTuning {
content = content.replace(&past_level, "level: critical");
}
let mut file = match File::options()
.write(true)
.truncate(true)
.open(&path)
{
let mut file = match File::options().write(true).truncate(true).open(&path) {
Ok(file) => file,
Err(e) => return Result::Err(e.to_string()),
};
file.write_all(content.as_bytes()).unwrap(); // TODO: use result
file.write_all(content.as_bytes()).unwrap();
println!(
"level: {} -> {}",
rule["level"].as_str().unwrap(),