Решение на упр.06 задача 1 от Нели Илиева
Резултати
- 2 точки от тестове
- 1 бонус точка
- 3 точки общо
- 2 успешни тест(а)
- 2 неуспешни тест(а)
Код
use std::collections::HashMap;
use std::convert::TryFrom;
use std::env;
use std::error::Error;
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)]
enum LogLevel {
Error,
Warn,
Info,
Debug,
}
struct AggregateInfo {
log_counts: HashMap<LogLevel, usize>,
skipped_files: Vec<String>,
}
#[derive(Debug)]
enum ParseLogError {
Read(io::Error),
ParseLine,
UnknownLevel(String),
}
impl From<io::Error> for ParseLogError {
fn from(err: io::Error) -> Self {
ParseLogError::Read(err)
}
}
impl Error for ParseLogError {}
impl std::fmt::Display for ParseLogError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
ParseLogError::Read(e) => write!(f, "I/O error: {}", e),
ParseLogError::ParseLine => write!(f, "Invalid log format"),
ParseLogError::UnknownLevel(level) => write!(f, "Unknown log level: {}", level),
}
}
}
impl TryFrom<&str> for LogLevel {
type Error = String;
fn try_from(value: &str) -> Result<Self, String> {
match value {
"ERROR" => Ok(LogLevel::Error),
"WARN" => Ok(LogLevel::Warn),
"INFO" => Ok(LogLevel::Info),
"DEBUG" => Ok(LogLevel::Debug),
_ => Err(value.to_string()),
}
}
}
impl LogLevel {
fn as_str(&self) -> &'static str {
match self {
LogLevel::Error => "Error",
LogLevel::Warn => "Warn",
LogLevel::Info => "Info",
LogLevel::Debug => "Debug",
}
}
}
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.trim();
if trimmed.is_empty() {
continue;
}
if let Some(space_pos) = trimmed.find(' ') {
let level_str = &trimmed[..space_pos];
let level = LogLevel::try_from(level_str).map_err(|err| ParseLogError::UnknownLevel(err))?;
*map.entry(level).or_insert(0) += 1;
}
else {
return Err(ParseLogError::ParseLine);
}
}
Ok(())
}
fn aggregate_logs(dir: &Path) -> Result<AggregateInfo, Box<dyn Error>> {
let mut log_counts = HashMap::new();
let mut skipped_files = Vec::new();
if !dir.exists() {
return Err(format!("Directory does not exist: {}", dir.display()).into());
}
if !dir.is_dir() {
return Err(format!("Path is not a directory: {}", dir.display()).into());
}
for entry in fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
if path.extension().map_or(false, |ext| ext == "log") {
let filename = path
.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_string();
let metadata = fs::metadata(&path)?;
let file_size = metadata.len();
let result: Result<(), ParseLogError> = if file_size > 10 * 1024 {
let file = File::open(&path)?;
parse_log_file(file, &mut log_counts)
}
else {
let content = fs::read_to_string(&path)?;
let cursor = io::Cursor::new(content);
parse_log_file(cursor, &mut log_counts)
};
if let Err(e) = result {
skipped_files.push(format!("{}: {}", filename, e));
}
}
}
Ok(AggregateInfo {
log_counts,
skipped_files,
})
}
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() != 2 {
eprintln!("Usage: {} <path_to_log_directory>", args[0]);
eprintln!("Example: {} ./logs", args[0]);
process::exit(1);
}
let dir_path = Path::new(&args[1]);
match aggregate_logs(dir_path) {
Ok(info) => {
println!("Statistics:");
let levels = [
LogLevel::Debug,
LogLevel::Info,
LogLevel::Warn,
LogLevel::Error,
];
for level in levels.iter() {
let count = info.log_counts.get(level).unwrap_or(&0);
println!(" {}: {}", level.as_str(), count);
}
if !info.skipped_files.is_empty() {
println!("\nSkipped files:");
for file in info.skipped_files {
println!(" {}", 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-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-task v0.3.31
Compiling pin-utils v0.1.0
Compiling futures-io v0.3.31
Compiling slab v0.4.11
Compiling pin-project-lite v0.2.16
Compiling solution v0.1.0 (/tmp/d20251120-1757769-1qj7pk3/solution)
warning: struct `AggregateInfo` is never constructed
--> src/lib.rs:18:8
|
18 | struct AggregateInfo {
| ^^^^^^^^^^^^^
|
= note: `#[warn(dead_code)]` on by default
warning: variants `ParseLine` and `UnknownLevel` are never constructed
--> src/lib.rs:26:5
|
24 | enum ParseLogError {
| ------------- variants in this enum
25 | Read(io::Error),
26 | ParseLine,
| ^^^^^^^^^
27 | UnknownLevel(String),
| ^^^^^^^^^^^^
|
= note: `ParseLogError` has a derived impl for the trait `Debug`, but this is intentionally ignored during dead code analysis
warning: method `as_str` is never used
--> src/lib.rs:63:8
|
62 | impl LogLevel {
| ------------- method in this implementation
63 | fn as_str(&self) -> &'static str {
| ^^^^^^
warning: function `parse_log_file` is never used
--> src/lib.rs:73:4
|
73 | fn parse_log_file<R>(file: R, map: &mut HashMap<LogLevel, usize>) -> Result<(), ParseLogError>
| ^^^^^^^^^^^^^^
warning: function `aggregate_logs` is never used
--> src/lib.rs:101:4
|
101 | fn aggregate_logs(dir: &Path) -> Result<AggregateInfo, Box<dyn Error>> {
| ^^^^^^^^^^^^^^
warning: function `main` is never used
--> src/lib.rs:149:4
|
149 | fn main() {
| ^^^^
warning: `solution` (lib) generated 6 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: method `as_str` is never used
--> tests/../src/lib.rs:63:8
|
62 | impl LogLevel {
| ------------- method in this implementation
63 | fn as_str(&self) -> &'static str {
| ^^^^^^
|
= note: `#[warn(dead_code)]` on by default
warning: function `main` is never used
--> tests/../src/lib.rs:149:4
|
149 | fn main() {
| ^^^^
warning: `solution` (test "solution_test") generated 2 warnings
Finished `test` profile [unoptimized + debuginfo] target(s) in 8.87s
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 ... FAILED
test solution_test::test_parse_log_big_data ... ok
test solution_test::test_parse_log_invalid ... FAILED
failures:
---- solution_test::test_aggregate stdout ----
thread 'solution_test::test_aggregate' panicked at tests/solution_test.rs:139:13:
assertion `left == right` failed
left: 0
right: 1
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
---- solution_test::test_parse_log_invalid stdout ----
thread 'solution_test::test_parse_log_invalid' panicked at tests/solution_test.rs:62:9:
assertion failed: matches!(parse_log_file(data, &mut map), Err(ParseLogError::ParseLine))
failures:
solution_test::test_aggregate
solution_test::test_parse_log_invalid
test result: FAILED. 2 passed; 2 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
error: test failed, to rerun pass `--test solution_test`
