Toml読み込み機能実装

This commit is contained in:
akiranishikawa
2020-10-10 09:59:08 +09:00
parent 22edee0332
commit f2f3a7e99a
8 changed files with 110 additions and 1 deletions

View File

@@ -1,2 +1,3 @@
pub mod detections;
pub mod models;
pub mod toml;

View File

@@ -6,6 +6,7 @@ use evtx::EvtxParser;
use quick_xml::de::DeError;
use std::{path::PathBuf, process};
use yamato_event_analyzer::detections::detection;
use yamato_event_analyzer::toml;
fn build_app() -> clap::App<'static, 'static> {
let program = std::env::args()
@@ -58,3 +59,4 @@ fn parse_file(filepath: &str) {
let mut detection = detection::Detection::new();
&detection.start(parser);
}

View File

@@ -1 +1,2 @@
pub mod event;
pub mod rule;

14
src/models/rule.rs Normal file
View File

@@ -0,0 +1,14 @@
extern crate serde;
use serde::Deserialize;
#[derive(Debug, Deserialize)]
pub struct Rule {
pub severity: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct Toml {
pub rule: Rule,
}

76
src/toml.rs Normal file
View File

@@ -0,0 +1,76 @@
extern crate serde_derive;
extern crate toml;
use std::fs;
use std::io;
use std::io::{BufReader, Read};
use std::path::{Path, PathBuf};
use crate::models::rule;
pub struct ParseToml {
pub rules: Vec<Result<rule::Toml, toml::de::Error>>,
}
impl ParseToml {
pub fn new() -> ParseToml {
ParseToml {
rules: Vec::new(),
}
}
fn read_file(&self, path: PathBuf) -> Result<String, String> {
let mut file_content = String::new();
let mut fr = fs::File::open(path)
.map(|f| BufReader::new(f))
.map_err(|e| e.to_string())?;
fr.read_to_string(&mut file_content)
.map_err(|e| e.to_string())?;
Ok(file_content)
}
fn read_dir<P: AsRef<Path>>(&mut self, path: P) -> io::Result<String> {
Ok(fs::read_dir(path)?
.filter_map(|entry| {
let entry = entry.ok()?;
if entry.file_type().ok()?.is_file() {
match self.read_file(entry.path()) {
Ok(s) => &self.rules.push(toml::from_str(&s)),
Err(e) => panic!("fail to read file: {}", e),
};
}
Some("")
})
.collect())
}
}
#[cfg(test)]
mod tests {
use crate::toml;
#[test]
fn test_read_toml() {
let mut toml = toml::ParseToml::new();
&toml.read_dir("rules".to_string());
for rule in toml.rules {
match rule {
Ok(_rule) => {
if let Some(severity) = _rule.rule.severity {
assert_eq!("high", severity);
}
},
Err(_) => (),
}
}
}
}