Решение на упр.06 задача 1 от Илиян Гаврилов
Резултати
- 4 точки от тестове
- 1 бонус точка
- 5 точки общо
- 4 успешни тест(а)
- 0 неуспешни тест(а)
Код
use std::collections::HashMap;
use std::error::Error;
use std::fmt;
use std::io::{self, BufRead, BufReader, Read};
use std::path::Path;
use std::fs;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum LogLevel {
Error,
Warn,
Info,
Debug,
}
impl LogLevel {
fn from_str(s: &str) -> Option<Self> {
match s {
"ERROR" => Some(LogLevel::Error),
"WARN" => Some(LogLevel::Warn),
"INFO" => Some(LogLevel::Info),
"DEBUG" => Some(LogLevel::Debug),
_ => None,
}
}
}
struct AggregateInfo {
log_counts: HashMap<LogLevel, usize>,
skipped_files: Vec<String>,
}
#[derive(Debug)]
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: {}", e),
ParseLogError::ParseLine => write!(f, "Failed to parse log line"),
}
}
}
impl Error for ParseLogError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
ParseLogError::Read(e) => Some(e),
ParseLogError::ParseLine => None,
}
}
}
impl From<io::Error> for ParseLogError {
fn from(err: io::Error) -> Self {
ParseLogError::Read(err)
}
}
fn parse_log_file<R>(file: R, map: &mut HashMap<LogLevel, usize>) -> Result<(), ParseLogError>
where
R: Read,
{
let reader = BufReader::new(file);
for line_result in reader.lines() {
let line = line_result?;
if line.trim().is_empty() {
continue;
}
let level_str = line.split_whitespace().next()
.ok_or(ParseLogError::ParseLine)?;
let level = LogLevel::from_str(level_str)
.ok_or(ParseLogError::ParseLine)?;
*map.entry(level).or_insert(0) += 1;
}
Ok(())
}
fn aggregate_logs(dir: &Path) -> Result<AggregateInfo, Box<dyn Error>> {
let mut log_counts = HashMap::new();
let mut skipped_files = Vec::new();
let entries = fs::read_dir(dir)?;
for entry_result in entries {
let entry = entry_result?;
let path = entry.path();
if path.extension().and_then(|s| s.to_str()) != Some("log") {
if let Some(filename) = path.file_name() {
skipped_files.push(filename.to_string_lossy().into_owned());
}
continue;
}
let file = match fs::File::open(&path) {
Ok(f) => f,
Err(e) => {
eprintln!("Warning: Could not open file {:?}: {}", path, e);
if let Some(filename) = path.file_name() {
skipped_files.push(filename.to_string_lossy().into_owned());
}
continue;
}
};
let parse_result = parse_log_file(file, &mut log_counts);
// Ако има грешка при парсване, пропускаме файла
if let Err(e) = parse_result {
eprintln!("Warning: Error parsing file {:?}: {}", path, e);
if let Some(filename) = path.file_name() {
skipped_files.push(filename.to_string_lossy().into_owned());
}
}
}
Ok(AggregateInfo {
log_counts,
skipped_files,
})
}
// Bonus - CLI
fn main() {
let args: Vec<String> = std::env::args().collect();
if args.len() < 2 {
eprintln!("Usage: {} <log_directory>", args[0]);
std::process::exit(1);
}
let dir_path = Path::new(&args[1]);
match aggregate_logs(dir_path) {
Ok(info) => {
if let Some(&count) = info.log_counts.get(&LogLevel::Debug) {
println!("Debug: {}", count);
}
if let Some(&count) = info.log_counts.get(&LogLevel::Info) {
println!("Info: {}", count);
}
if let Some(&count) = info.log_counts.get(&LogLevel::Warn) {
println!("Warn: {}", count);
}
if let Some(&count) = info.log_counts.get(&LogLevel::Error) {
println!("Error: {}", count);
}
if !info.skipped_files.is_empty() {
println!("\nSkipped files:");
for file in &info.skipped_files {
println!(" - {}", file);
}
}
}
Err(e) => {
eprintln!("Error: {}", e);
std::process::exit(1);
}
}
}
Лог от изпълнението
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 pin-utils v0.1.0
Compiling slab v0.4.11
Compiling syn v2.0.110
Compiling futures-task v0.3.31
Compiling futures-io v0.3.31
Compiling memchr v2.7.6
Compiling pin-project-lite v0.2.16
Compiling solution v0.1.0 (/tmp/d20251120-1757769-1n015g7/solution)
warning: enum `LogLevel` is never used
--> src/lib.rs:9:6
|
9 | enum LogLevel {
| ^^^^^^^^
|
= note: `#[warn(dead_code)]` on by default
warning: associated function `from_str` is never used
--> src/lib.rs:17:6
|
16 | impl LogLevel {
| ------------- associated function in this implementation
17 | fn from_str(s: &str) -> Option<Self> {
| ^^^^^^^^
warning: struct `AggregateInfo` is never constructed
--> src/lib.rs:28:8
|
28 | struct AggregateInfo {
| ^^^^^^^^^^^^^
warning: variant `ParseLine` is never constructed
--> src/lib.rs:36:3
|
34 | enum ParseLogError {
| ------------- variant in this enum
35 | Read(io::Error),
36 | ParseLine,
| ^^^^^^^^^
|
= note: `ParseLogError` has a derived impl for the trait `Debug`, but this is intentionally ignored during dead code analysis
warning: function `parse_log_file` is never used
--> src/lib.rs:63:4
|
63 | fn parse_log_file<R>(file: R, map: &mut HashMap<LogLevel, usize>) -> Result<(), ParseLogError>
| ^^^^^^^^^^^^^^
warning: function `aggregate_logs` is never used
--> src/lib.rs:88:4
|
88 | fn aggregate_logs(dir: &Path) -> Result<AggregateInfo, Box<dyn Error>> {
| ^^^^^^^^^^^^^^
warning: function `main` is never used
--> src/lib.rs:134:4
|
134 | fn main() {
| ^^^^
warning: `solution` (lib) generated 7 warnings
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:134:4
|
134 | 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 8.76s
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_invalid ... ok
test solution_test::test_parse_log_big_data ... ok
test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
