Debian Codegraph @

src/config/ident.rs

raw
1 use std::fmt;
2
3 use log::error;
4 use regex::Regex;
5 use toml::Value;
6
7 use super::error::TomlHelper;
8
9 #[derive(Clone, Debug)]
10 pub enum Ident {
11 Name(String),
12 Pattern(Box<Regex>),
13 }
14
15 impl fmt::Display for Ident {
16 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
17 match self {
18 Self::Name(name) => f.write_str(name),
19 Self::Pattern(regex) => write!(f, "Regex {regex}"),
20 }
21 }
22 }
23
24 impl PartialEq for Ident {
25 fn eq(&self, other: &Ident) -> bool {
26 match (self, other) {
27 (Self::Name(s1), Self::Name(s2)) => s1 == s2,
28 (Self::Pattern(r1), Self::Pattern(r2)) => r1.as_str() == r2.as_str(),
29 _ => false,
30 }
31 }
32 }
33
34 impl Eq for Ident {}
35
36 impl Ident {
37 pub fn parse(toml: &Value, object_name: &str, what: &str) -> Option<Self> {
38 match toml.lookup("pattern").and_then(Value::as_str) {
39 Some(s) => Regex::new(&format!("^{s}$"))
40 .map(Box::new)
41 .map(Self::Pattern)
42 .map_err(|e| {
43 error!("Bad pattern `{s}` in {what} for `{object_name}`: {e}");
44 e
45 })
46 .ok(),
47 None => match toml.lookup("name").and_then(Value::as_str) {
48 Some(name) => {
49 if name.contains(['.', '+', '*'].as_ref()) {
50 error!(
51 "Should be `pattern` instead of `name` in {what} for `{object_name}`"
52 );
53 None
54 } else {
55 Some(Self::Name(name.into()))
56 }
57 }
58 None => None,
59 },
60 }
61 }
62
63 pub fn is_match(&self, name: &str) -> bool {
64 use self::Ident::*;
65 match self {
66 Name(n) => name == n,
67 Pattern(regex) => regex.is_match(name),
68 }
69 }
70 }