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

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

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

Резултати

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

Код

use std::collections::HashMap;
use std::env;
use std::error::Error;
use std::fmt;
use std::fs::{self, File};
use std::io::{self, BufRead, BufReader, Read};
use std::path::Path;
use std::process;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LogLevel {
Error,
Warn,
Info,
Debug,
}
pub struct AggregateInfo {
pub(crate) log_counts: HashMap<LogLevel, usize>,
pub(crate) skipped_files: Vec<String>,
}
#[derive(Debug)]
pub enum AggregateError {
InvalidDirectory,
Io(io::Error),
}
impl fmt::Display for AggregateError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AggregateError::InvalidDirectory =>
write!(f, "Provided path is not a directory"),
AggregateError::Io(e) =>
write!(f, "IO error: {}", e),
}
}
}
impl Error for AggregateError {}
impl From<io::Error> for AggregateError {
fn from(err: io::Error) -> Self {
AggregateError::Io(err)
}
}
#[derive(Debug)]
pub enum ParseLogError {
Read(io::Error),
ParseLine,
}
impl From<io::Error> for ParseLogError {
fn from(e: io::Error) -> Self {
ParseLogError::Read(e)
}
}
pub fn parse_log_file<R>(reader: R, map: &mut HashMap<LogLevel, usize>) -> Result<(), ParseLogError>
where
R: Read,
{
let buf_reader = BufReader::new(reader);
for line_res in buf_reader.lines() {
let line = line_res.map_err(ParseLogError::Read)?;
let level = if line.starts_with("ERROR") {
LogLevel::Error
} else if line.starts_with("WARN") {
LogLevel::Warn
} else if line.starts_with("INFO") {
LogLevel::Info
} else if line.starts_with("DEBUG") {
LogLevel::Debug
} else {
return Err(ParseLogError::ParseLine);
};
let counter = map.entry(level).or_insert(0);
*counter += 1;
}
Ok(())
}
pub fn aggregate_logs(dir: &Path) -> Result<AggregateInfo, Box<dyn Error>> {
if !dir.is_dir() {
return Err(Box::new(AggregateError::InvalidDirectory));
}
let mut counts: HashMap<LogLevel, usize> = HashMap::new();
let mut skipped: Vec<String> = Vec::new();
for entry_res in fs::read_dir(dir)? {
let entry = entry_res?;
let path = entry.path();
if path.extension().and_then(|s| s.to_str()) != Some("log") {
let file_name = path.to_string_lossy().to_string();
skipped.push(file_name);
continue;
}
let metadata = fs::metadata(&path)?;
let file_name = path.to_string_lossy().to_string();
let result = if metadata.len() > 10 * 1024 {
match File::open(&path) {
Ok(file) => parse_log_file(file, &mut counts),
Err(e) => Err(ParseLogError::Read(e)),
}
} else {
let mut content = Vec::new();
match File::open(&path) {
Ok(mut file) => {
if let Err(e) = file.read_to_end(&mut content) {
Err(ParseLogError::Read(e))
} else {
parse_log_file(&content[..], &mut counts)
}
}
Err(e) => Err(ParseLogError::Read(e)),
}
};
if let Err(e) = result {
eprintln!("Skipped {} due to error: {:?}", file_name, e);
skipped.push(file_name);
}
}
Ok(AggregateInfo {
log_counts: counts,
skipped_files: skipped,
})
}
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() != 2 {
eprintln!("Usage: logcli <log_directory>");
process::exit(1);
}
let dir_path = Path::new(&args[1]);
let result = aggregate_logs(dir_path);
let info = match result {
Ok(ok) => ok,
Err(e) => {
eprintln!("Error: {}", e);
process::exit(1);
}
};
let counts = info.log_counts;
println!("Debug: {}", counts.get(&LogLevel::Debug).copied().unwrap_or(0));
println!("Info: {}", counts.get(&LogLevel::Info).copied().unwrap_or(0));
println!("Warn: {}", counts.get(&LogLevel::Warn).copied().unwrap_or(0));
println!("Error: {}", counts.get(&LogLevel::Error).copied().unwrap_or(0));
if !info.skipped_files.is_empty() {
println!("\nSkipped files:");
for file in info.skipped_files {
println!(" {}", file);
}
}
}

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

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 memchr v2.7.6
   Compiling syn v2.0.110
   Compiling pin-utils v0.1.0
   Compiling pin-project-lite v0.2.16
   Compiling slab v0.4.11
   Compiling futures-task v0.3.31
   Compiling futures-io v0.3.31
   Compiling solution v0.1.0 (/tmp/d20251120-1757769-1b15n7v/solution)
warning: fields `log_counts` and `skipped_files` are never read
  --> src/lib.rs:19:16
   |
18 | pub struct AggregateInfo {
   |            ------------- fields in this struct
19 |     pub(crate) log_counts: HashMap<LogLevel, usize>,
   |                ^^^^^^^^^^
20 |     pub(crate) skipped_files: Vec<String>,
   |                ^^^^^^^^^^^^^
   |
   = note: `#[warn(dead_code)]` on by default

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

warning: `solution` (lib) generated 2 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: field `0` is never read
  --> tests/../src/lib.rs:50:10
   |
50 |     Read(io::Error),
   |     ---- ^^^^^^^^^
   |     |
   |     field in this variant
   |
   = note: `ParseLogError` has a derived impl for the trait `Debug`, but this is intentionally ignored during dead code analysis
   = note: `#[warn(dead_code)]` on by default
help: consider changing the field to be of unit type to suppress this warning while preserving the field numbering, or remove the field
   |
50 |     Read(()),
   |          ~~

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

warning: `solution` (test "solution_test") generated 2 warnings
    Finished `test` profile [unoptimized + debuginfo] target(s) in 9.12s
     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

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

Илиян качи първо решение на 19.11.2025 22:41 (преди 16 дена)