Skip to content

Commit

Permalink
feat: Directive::as_transaction
Browse files Browse the repository at this point in the history
  • Loading branch information
jcornaz committed Sep 14, 2022
1 parent b5df709 commit 8a497d2
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 9 deletions.
18 changes: 15 additions & 3 deletions src/directive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,15 @@ pub enum Directive<'a> {
Transaction(Transaction<'a>),
}

impl<'a> Directive<'a> {
#[must_use]
pub fn as_transaction(&self) -> Option<&Transaction<'a>> {
match self {
Directive::Transaction(trx) => Some(trx),
}
}
}

pub(crate) fn directive(input: &str) -> IResult<&str, (Date, Option<Directive<'_>>)> {
separated_pair(
date,
Expand All @@ -39,9 +48,12 @@ mod tests {
let input = r#"2022-09-10 txn "My transaction""#;
let (_, (date, directive)) = directive(input).expect("should successfully parse directive");
assert_eq!(date, Date::new(2022, 9, 10));
match directive.expect("should recognize the directive") {
Directive::Transaction(trx) => assert_eq!(trx.narration(), Some("My transaction")),
}
let transaction = directive
.as_ref()
.expect("should recognize the directive")
.as_transaction()
.expect("the directive should be a transaction");
assert_eq!(transaction.narration(), Some("My transaction"));
}

#[rstest]
Expand Down
11 changes: 5 additions & 6 deletions tests/spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,11 @@ fn examples_have_expected_number_of_transaction(
#[case(COMMENTS, 0)]
fn examples_have_expected_number_of_postings(#[case] input: &str, #[case] expected_count: usize) {
let actual_count: usize = Parser::new(input)
.map(|d| {
if let Ok((_, Directive::Transaction(t))) = d {
t.postings().len()
} else {
0
}
.filter_map(|d| {
d.ok()
.as_ref()
.and_then(|(_, d)| d.as_transaction())
.map(|t| t.postings().len())
})
.sum();
assert_eq!(actual_count, expected_count);
Expand Down

0 comments on commit 8a497d2

Please sign in to comment.