hyperlit_model/
directives.rs

1use hyperlit_base::result::HyperlitResult;
2use hyperlit_base::{bail, err};
3
4#[derive(Debug, PartialEq)]
5pub enum Directive {
6    IncludeByTag { tag: String },
7    IncludeRest,
8}
9
10pub fn parse_directive(directive_string: &str) -> HyperlitResult<Directive> {
11    let directive_string = directive_string
12        .trim()
13        .strip_prefix("§{")
14        .ok_or_else(|| {
15            err!(
16                "Directive must start with '§{{', but was '{}'",
17                directive_string
18            )
19        })?
20        .strip_suffix("}")
21        .ok_or_else(|| {
22            err!(
23                "Directive must end with '}}', but was '{}'",
24                directive_string
25            )
26        })?;
27    let directive_string = directive_string.trim();
28    Ok(
29        if let Some(tag) = directive_string.strip_prefix("@include_by_tag:") {
30            let tag = tag.trim();
31            let tag = tag.strip_prefix("#").unwrap_or(tag);
32            Directive::IncludeByTag {
33                tag: tag.to_string(),
34            }
35        } else if directive_string == "@include_rest" {
36            Directive::IncludeRest
37        } else {
38            bail!("Unknown directive: '{}'", directive_string);
39        },
40    )
41}
42
43#[cfg(test)]
44mod tests {
45    use super::*;
46
47    #[test]
48    fn test_parse_include_by_tag() {
49        assert_eq!(
50            parse_directive("§{@include_by_tag: #the_tag}").unwrap(),
51            Directive::IncludeByTag {
52                tag: "the_tag".to_string()
53            }
54        );
55    }
56
57    #[test]
58    fn test_parse_include() {
59        assert_eq!(
60            parse_directive("§{@include_rest}").unwrap(),
61            Directive::IncludeRest,
62        );
63    }
64
65    #[test]
66    fn test_parse_other() {
67        assert_eq!(
68            parse_directive("foobar").unwrap_err().to_string(),
69            "Directive must start with '§{', but was 'foobar'"
70        );
71    }
72}