Решение на упр.06 задача 1 от Стилиян Иванов

Обратно към всички решения

Към профила на Стилиян Иванов

Резултати

  • 4 точки от тестове
  • 1 бонус точка
  • 5 точки общо
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)

Код

use std::collections::HashMap;
use std::error::Error;
use std::io::{self, BufRead, BufReader, Read};
use std::path::Path;
use std::str::FromStr;
use std::fs::{self, File};
use std::fmt;
use std::env;
use std::process;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum LogLevel {
Error,
Warn,
Info,
Debug,
}
#[derive(Debug)]
struct AggregateInfo {
log_counts: HashMap<LogLevel, usize>,
skipped_files: Vec<String>,
}
#[derive(Debug)]
enum ParseLogError {
Read(io::Error),
ParseLine,
UnknownLevel(String),
}
impl fmt::Display for ParseLogError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ParseLogError::Read(e) => write!(f, "Failed to read line: {}", e),
ParseLogError::ParseLine => write!(f, "Failed to parse log line format (expected 'LEVEL ...')"),
ParseLogError::UnknownLevel(level) => write!(f, "Unknown log level: {}", level),
}
}
}
impl Error for ParseLogError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
ParseLogError::Read(e) => Some(e),
_ => None,
}
}
}
impl From<io::Error> for ParseLogError {
fn from(err: io::Error) -> Self {
ParseLogError::Read(err)
}
}
impl FromStr for LogLevel {
type Err = ParseLogError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"ERROR" => Ok(LogLevel::Error),
"WARN" => Ok(LogLevel::Warn),
"INFO" => Ok(LogLevel::Info),
"DEBUG" => Ok(LogLevel::Debug),
_ => Err(ParseLogError::UnknownLevel(s.to_string())),
}
}
}
fn aggregate_logs(dir: &Path) -> Result<AggregateInfo, Box<dyn Error>> {
let mut total_log_counts = HashMap::new();
let mut skipped_files = Vec::new();
let entries = match fs::read_dir(dir) {
Ok(entries) => entries,
Err(e) => {
return Err(format!("Failed to read directory {}: {}", dir.display(), e).into());
}
};
for entry_result in entries {
let entry = match entry_result {
Ok(entry) => entry,
Err(e) => {
eprintln!("Warning: Failed to read directory entry: {}", e);
continue;
}
};
let path = entry.path();
if path.is_file() {
let file_name = path.file_name()
.map_or_else(
|| path.to_string_lossy().to_string(),
|s| s.to_string_lossy().to_string()
);
if path.extension().map_or(false, |s| s == "log") {
let file = match File::open(&path) {
Ok(file) => file,
Err(e) => {
eprintln!("Warning: Failed to open file {}: {}", file_name, e);
skipped_files.push(file_name);
continue;
}
};
let mut file_map = HashMap::new();
match parse_log_file(file, &mut file_map) {
Ok(_) => {
for (level, count) in file_map {
*total_log_counts.entry(level).or_insert(0) += count;
}
}
Err(e) => {
eprintln!("Warning: Failed to parse file {}: {}", file_name, e);
skipped_files.push(file_name);
}
}
} else {
skipped_files.push(file_name);
}
}
}
Ok(AggregateInfo {
log_counts: total_log_counts,
skipped_files,
})
}
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?;
let trimmed_line = line.trim();
if trimmed_line.is_empty() {
continue;
}
let parts: Vec<&str> = trimmed_line.splitn(2, ' ').collect();
let level_str = parts.get(0).ok_or(ParseLogError::ParseLine)?;
let level = match LogLevel::from_str(level_str) {
Ok(l) => l,
Err(_) => return Err(ParseLogError::ParseLine),
};
*map.entry(level).or_insert(0) += 1;
}
Ok(())
}
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() != 2 {
eprintln!("Usage: {} <log_directory>", args[0]);
process::exit(1);
}
let dir_path = Path::new(&args[1]);
match aggregate_logs(dir_path) {
Ok(info) => {
println!("Debug: {}", info.log_counts.get(&LogLevel::Debug).unwrap_or(&0));
println!("Info: {}", info.log_counts.get(&LogLevel::Info).unwrap_or(&0));
println!("Warn: {}", info.log_counts.get(&LogLevel::Warn).unwrap_or(&0));
println!("Error: {}", info.log_counts.get(&LogLevel::Error).unwrap_or(&0));
if !info.skipped_files.is_empty() {
eprintln!("\nSkipped files:");
for file in info.skipped_files {
eprintln!("- {}", file);
}
}
}
Err(e) => {
eprintln!("Error: {}", e);
process::exit(1);
}
}
}

Лог от изпълнението

Updating crates.io index
     Locking 17 packages to latest compatible versions
   Compiling proc-macro2 v1.0.103
   Compiling quote v1.0.42
   Compiling unicode-ident v1.0.22
   Compiling futures-sink v0.3.31
   Compiling futures-core v0.3.31
   Compiling futures-channel v0.3.31
   Compiling pin-project-lite v0.2.16
   Compiling futures-task v0.3.31
   Compiling syn v2.0.110
   Compiling futures-io v0.3.31
   Compiling pin-utils v0.1.0
   Compiling memchr v2.7.6
   Compiling slab v0.4.11
   Compiling solution v0.1.0 (/tmp/d20251120-1757769-s1q9xf/solution)
warning: struct `AggregateInfo` is never constructed
  --> src/lib.rs:20:8
   |
20 | struct AggregateInfo {
   |        ^^^^^^^^^^^^^
   |
   = note: `#[warn(dead_code)]` on by default

warning: variant `ParseLine` is never constructed
  --> src/lib.rs:28:5
   |
26 | enum ParseLogError {
   |      ------------- variant in this enum
27 |     Read(io::Error),
28 |     ParseLine,
   |     ^^^^^^^^^
   |
   = note: `ParseLogError` has a derived impl for the trait `Debug`, but this is intentionally ignored during dead code analysis

warning: function `aggregate_logs` is never used
  --> src/lib.rs:71:4
   |
71 | fn aggregate_logs(dir: &Path) -> Result<AggregateInfo, Box<dyn Error>> {
   |    ^^^^^^^^^^^^^^

warning: function `parse_log_file` is never used
   --> src/lib.rs:135:4
    |
135 | fn parse_log_file<R>(file: R, map: &mut HashMap<LogLevel, usize>) -> Result<(), ParseLogError>
    |    ^^^^^^^^^^^^^^

warning: function `main` is never used
   --> src/lib.rs:163:4
    |
163 | fn main() {
    |    ^^^^

warning: `solution` (lib) generated 5 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:163:4
    |
163 | 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.81s
     Running tests/solution_test.rs (target/debug/deps/solution_test-f75e629a1d90e17c)

running 4 tests
test solution_test::test_aggregate ... ok
test solution_test::test_parse_log_basic ... 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

История (1 версия и 0 коментара)

Стилиян качи първо решение на 19.11.2025 01:28 (преди 17 дена)