Решение на упр.06 задача 1 от Милен Хаджиев
Резултати
- 4 точки от тестове
- 0 бонус точки
- 4 точки общо
- 4 успешни тест(а)
- 0 неуспешни тест(а)
Код
use std::{
collections::HashMap,
env,
fmt,
fs::{self, File},
io::{self, BufReader, Read},
path::Path,
process,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LogLevel {
Error,
Warn,
Info,
Debug,
}
#[derive(Debug)]
pub enum ParseLogError {
Read(io::Error),
ParseLine,
}
impl fmt::Display for ParseLogError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ParseLogError::Read(e) => write!(f, "I/O error while reading log file: {e}"),
ParseLogError::ParseLine => write!(f, "Invalid log line (unknown level)"),
}
}
}
impl std::error::Error for ParseLogError {}
pub struct AggregateInfo {
pub log_counts: HashMap<LogLevel, usize>,
pub skipped_files: Vec<String>,
}
pub fn parse_log_file<R>(mut reader: R, map: &mut HashMap<LogLevel, usize>) -> Result<(), ParseLogError>
where
R: Read,
{
let mut content = String::new();
reader.read_to_string(&mut content).map_err(ParseLogError::Read)?;
for line in content.lines() {
if line.trim().is_empty() {
continue;
}
let level_word = line.split_whitespace().next().ok_or(ParseLogError::ParseLine)?;
let level = match level_word {
"ERROR" => LogLevel::Error,
"WARN" => LogLevel::Warn,
"INFO" => LogLevel::Info,
"DEBUG" => LogLevel::Debug,
_ => return Err(ParseLogError::ParseLine),
};
*map.entry(level).or_insert(0) += 1;
}
Ok(())
}
pub fn aggregate_logs(dir: &Path) -> Result<AggregateInfo, io::Error> {
let mut log_counts: HashMap<LogLevel, usize> = HashMap::new();
let mut skipped_files: Vec<String> = Vec::new();
for entry in fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
if path.extension().and_then(|s| s.to_str()) != Some("log") {
skipped_files.push(path.to_string_lossy().into_owned());
continue;
}
let file = match File::open(&path) {
Ok(f) => f,
Err(e) => {
eprintln!("⚠️ Cannot open `{}`: {e}", path.display());
skipped_files.push(path.to_string_lossy().into_owned());
continue;
}
};
let meta = fs::metadata(&path)?;
let parse_res = if meta.len() > 10 * 1024 {
let buf = BufReader::new(file);
parse_log_file(buf, &mut log_counts)
} else {
parse_log_file(file, &mut log_counts)
};
if let Err(e) = parse_res {
eprintln!(
"⚠️ Skipping `{}` because of parsing error: {e}",
path.display()
);
skipped_files.push(path.to_string_lossy().into_owned());
}
}
Ok(AggregateInfo {
log_counts,
skipped_files,
})
}
fn main() {
let args: Vec<_> = env::args_os().collect();
if args.len() != 2 {
eprintln!("Usage: {} <logs-directory>", args[0].to_string_lossy());
process::exit(1);
}
let dir = Path::new(&args[1]);
let info = match aggregate_logs(dir) {
Ok(i) => i,
Err(e) => {
eprintln!("Error: {e}");
process::exit(1);
}
};
let order = [
(LogLevel::Debug, "Debug"),
(LogLevel::Info, "Info"),
(LogLevel::Warn, "Warn"),
(LogLevel::Error, "Error"),
];
for (lvl, name) in &order {
let cnt = info.log_counts.get(lvl).copied().unwrap_or(0);
println!("{name}: {cnt}");
}
if !info.skipped_files.is_empty() {
println!("Skipped files:");
for f in info.skipped_files {
println!(" - {f}");
}
}
}
Лог от изпълнението
Updating crates.io index
Locking 17 packages to latest compatible versions
Compiling proc-macro2 v1.0.103
Compiling unicode-ident v1.0.22
Compiling quote v1.0.42
Compiling futures-core v0.3.31
Compiling futures-sink v0.3.31
Compiling futures-channel v0.3.31
Compiling memchr v2.7.6
Compiling syn v2.0.110
Compiling futures-io v0.3.31
Compiling pin-utils v0.1.0
Compiling pin-project-lite v0.2.16
Compiling futures-task v0.3.31
Compiling slab v0.4.11
Compiling solution v0.1.0 (/tmp/d20251120-1757769-qenmil/solution)
warning: function `main` is never used
--> src/lib.rs:107:4
|
107 | fn main() {
| ^^^^
|
= note: `#[warn(dead_code)]` on by default
warning: `solution` (lib) generated 1 warning
Compiling futures-macro v0.3.31
Compiling futures-util v0.3.31
Compiling futures-executor v0.3.31
Compiling futures v0.3.31
warning: function `main` is never used
--> tests/../src/lib.rs:107:4
|
107 | fn main() {
| ^^^^
|
= note: `#[warn(dead_code)]` on by default
warning: `solution` (test "solution_test") generated 1 warning
Finished `test` profile [unoptimized + debuginfo] target(s) in 9.17s
Running tests/solution_test.rs (target/debug/deps/solution_test-f75e629a1d90e17c)
running 4 tests
test solution_test::test_parse_log_basic ... ok
test solution_test::test_aggregate ... ok
test solution_test::test_parse_log_big_data ... ok
test solution_test::test_parse_log_invalid ... ok
test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
