hledger_parser/directive/
tag.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
use chumsky::prelude::*;

use crate::component::whitespace::whitespace;
use crate::state::State;
use crate::utils::end_of_line;

#[derive(Clone, Debug, PartialEq)]
pub struct Tag {
    pub name: String,
}

pub fn tag<'a>() -> impl Parser<'a, &'a str, Tag, extra::Full<Rich<'a, char>, State, ()>> {
    just("tag")
        .ignore_then(whitespace().repeated().at_least(1))
        .ignore_then(
            any()
                .and_is(text::newline().not())
                .and_is(just(";").not())
                .and_is(whitespace().not())
                .repeated()
                .at_least(1)
                .collect::<String>(),
        )
        .then_ignore(end_of_line())
        .map(|tag| Tag {
            name: tag.trim_end().to_string(),
        })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn ok_simple() {
        let result = tag().then_ignore(end()).parse("tag test-tag").into_result();
        assert_eq!(
            result,
            Ok(Tag {
                name: String::from("test-tag")
            })
        );
    }

    #[test]
    fn ok_with_comment() {
        let result = tag()
            .then_ignore(end())
            .parse("tag Test ; comment")
            .into_result();
        assert_eq!(
            result,
            Ok(Tag {
                name: String::from("Test")
            })
        );
    }

    #[test]
    fn err_with_space() {
        let result = tag()
            .then_ignore(end())
            .parse("tag Testing things")
            .into_result();
        assert!(result.is_err());
    }

    #[test]
    fn ok_with_trailing() {
        let result = tag().then_ignore(end()).parse("tag 123  ").into_result();
        assert_eq!(
            result,
            Ok(Tag {
                name: String::from("123")
            })
        );
    }

    #[test]
    fn err() {
        let result = tag().then_ignore(end()).parse("t Test").into_result();
        assert!(result.is_err());
    }
}