Skip to content

Commit

Permalink
Merge pull request #324 from Maximkaaa/try_parse
Browse files Browse the repository at this point in the history
Add `Builder::try_parse()` method
  • Loading branch information
epage authored Jul 23, 2024
2 parents 0e25d9e + 05aacb9 commit 4dd976b
Show file tree
Hide file tree
Showing 6 changed files with 395 additions and 47 deletions.
35 changes: 35 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions crates/env_filter/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
<!-- next-header -->
## [Unreleased] - ReleaseDate

### Features

- Added `env_filter::Builder::try_parse(&self, &str)` method (failable version of `env_filter::Builder::parse()`)

## [0.1.0] - 2024-01-19

<!-- next-url -->
Expand Down
3 changes: 3 additions & 0 deletions crates/env_filter/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,8 @@ regex = ["dep:regex"]
log = { version = "0.4.8", features = ["std"] }
regex = { version = "1.0.3", optional = true, default-features=false, features=["std", "perf"] }

[dev-dependencies]
snapbox = "0.6"

[lints]
workspace = true
50 changes: 49 additions & 1 deletion crates/env_filter/src/filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ use log::{LevelFilter, Metadata, Record};

use crate::enabled;
use crate::parse_spec;
use crate::parser::ParseResult;
use crate::Directive;
use crate::FilterOp;
use crate::ParseError;

/// A builder for a log filter.
///
Expand Down Expand Up @@ -97,7 +99,17 @@ impl Builder {
///
/// [Enabling Logging]: ../index.html#enabling-logging
pub fn parse(&mut self, filters: &str) -> &mut Self {
let (directives, filter) = parse_spec(filters);
#![allow(clippy::print_stderr)] // compatibility

let ParseResult {
directives,
filter,
errors,
} = parse_spec(filters);

for error in errors {
eprintln!("warning: {error}, ignoring it");
}

self.filter = filter;

Expand All @@ -107,6 +119,22 @@ impl Builder {
self
}

/// Parses the directive string, returning an error if the given directive string is invalid.
///
/// See the [Enabling Logging] section for more details.
///
/// [Enabling Logging]: ../index.html#enabling-logging
pub fn try_parse(&mut self, filters: &str) -> Result<&mut Self, ParseError> {
let (directives, filter) = parse_spec(filters).ok()?;

self.filter = filter;

for directive in directives {
self.insert_directive(directive);
}
Ok(self)
}

/// Build a log filter.
pub fn build(&mut self) -> Filter {
assert!(!self.built, "attempt to re-use consumed builder");
Expand Down Expand Up @@ -230,6 +258,7 @@ impl fmt::Debug for Filter {
#[cfg(test)]
mod tests {
use log::{Level, LevelFilter};
use snapbox::{assert_data_eq, str};

use super::{enabled, Builder, Directive, Filter};

Expand Down Expand Up @@ -444,6 +473,25 @@ mod tests {
}
}

#[test]
fn try_parse_valid_filter() {
let logger = Builder::new()
.try_parse("info,crate1::mod1=warn")
.expect("valid filter returned error")
.build();
assert!(enabled(&logger.directives, Level::Warn, "crate1::mod1"));
assert!(enabled(&logger.directives, Level::Info, "crate2::mod2"));
}

#[test]
fn try_parse_invalid_filter() {
let error = Builder::new().try_parse("info,crate1=invalid").unwrap_err();
assert_data_eq!(
error,
str!["error parsing logger filter: invalid logging spec 'invalid'"]
);
}

#[test]
fn match_full_path() {
let logger = make_logger_filter(vec![
Expand Down
1 change: 1 addition & 0 deletions crates/env_filter/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,4 @@ use parser::parse_spec;
pub use filter::Builder;
pub use filter::Filter;
pub use filtered_log::FilteredLog;
pub use parser::ParseError;
Loading

0 comments on commit 4dd976b

Please sign in to comment.