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
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
//! Recap deserializes structures from regex [named capture groups](https://www.regular-expressions.info/named.html)
//! extracted from strings.
//!
//! You may find this crate useful for cases where input is provided as a raw string in a loosely structured format.
//! A common use case for this is when you're dealing with log file data that was not stored in a particular structed format
//! like JSON but rather in a format that can be represented with a pattern.
//!
//! Recap is provides what [envy](https://crates.io/crates/envy) provides environment variables for named regex capture groups
//!
//!
//! # Examples
//!
//! Below is an example that derives a `FromStr` for your type that will
//! parse into the struct using named capture groups
//!
//! ```rust
//! use recap::Recap;
//! use serde::Deserialize;
//! use std::error::Error;
//!
//! #[derive(Debug, Deserialize, PartialEq, Recap)]
//! #[recap(regex=r#"(?P<foo>\S+)\s(?P<bar>\S+)"#)]
//! struct Example {
//!   foo: String,
//!   bar: String,
//! }
//!
//! fn main() -> Result<(), Box<dyn Error>> {
//!
//!   assert_eq!(
//!      "hello there".parse::<Example>()?,
//!      Example {
//!        foo: "hello".into(),
//!        bar: "there".into()
//!      }
//!   );
//!
//!   Ok(())
//! }
//! ```
//!
//! You can also use recap by using the generic function `from_captures` in which
//! case you'll be reponsible for bringing your only Regex reference.
//!
//! 💡 For convenience the [regex](https://crates.io/crates/regex) crate's [`Regex`](https://docs.rs/regex/latest/regex/struct.Regex.html)
//! type is re-exported
//!
//! ```rust
//! use recap::{Regex, from_captures};
//! use serde::Deserialize;
//! use std::error::Error;
//!
//! #[derive(Debug, Deserialize, PartialEq)]
//! struct Example {
//!   foo: String,
//!   bar: String,
//! }
//!
//! fn main() -> Result<(), Box<dyn Error>> {
//!   let pattern = Regex::new(
//!     r#"(?P<foo>\S+)\s(?P<bar>\S+)"#
//!   )?;
//!
//!   let example: Example = from_captures(
//!     &pattern, "hello there"
//!   )?;
//!
//!   assert_eq!(
//!      example,
//!      Example {
//!        foo: "hello".into(),
//!        bar: "there".into()
//!      }
//!   );
//!
//!   Ok(())
//! }
//! ```
pub use regex::Regex;
use serde::de::DeserializeOwned;
use std::convert::identity;

// used in derive crate output
// to derive a static for compiled
// regex
#[cfg(feature = "derive")]
#[doc(hidden)]
pub use lazy_static::lazy_static;

// Re-export for #[derive(Recap)]
#[cfg(feature = "derive")]
#[allow(unused_imports)]
#[macro_use]
extern crate recap_derive;
#[cfg(feature = "derive")]
#[doc(hidden)]
pub use recap_derive::*;

/// A type which encapsulates recap errors
pub type Error = envy::Error;

/// Deserialize a type from named regex capture groups
///
/// See module level documentation for examples
pub fn from_captures<D>(
    re: &Regex,
    input: &str,
) -> Result<D, Error>
where
    D: DeserializeOwned,
{
    let caps = re.captures(input).ok_or_else(|| {
        envy::Error::Custom(format!("No captures resolved in string '{}'", input))
    })?;
    envy::from_iter(
        re.capture_names()
            .map(|maybe_name| {
                maybe_name.and_then(|name| {
                    caps.name(name)
                        .map(|val| (name.to_string(), val.as_str().to_string()))
                })
            })
            .filter_map(identity),
    )
}

#[cfg(test)]
mod tests {
    use super::{from_captures, Regex};
    use serde::Deserialize;
    use std::error::Error;

    #[derive(Debug, PartialEq, Deserialize)]
    struct LogEntry {
        foo: String,
        bar: String,
        baz: String,
    }

    #[derive(Debug, PartialEq, Deserialize)]
    struct LogEntryOptional {
        foo: String,
        bar: String,
        baz: Option<String>,
    }

    #[test]
    fn deserializes_matching_captures_optional() -> Result<(), Box<dyn Error>> {
        assert_eq!(
            from_captures::<LogEntryOptional>(
                &Regex::new(
                    r#"(?x)
                    (?P<foo>\S+)
                    \s+
                    (?P<bar>\S+)
                    \s+
                    (?P<baz>\S+)?
                "#
                )?,
                "one two "
            )?,
            LogEntryOptional {
                foo: "one".into(),
                bar: "two".into(),
                baz: None
            }
        );

        Ok(())
    }

    #[test]
    fn deserializes_matching_captures() -> Result<(), Box<dyn Error>> {
        assert_eq!(
            from_captures::<LogEntry>(
                &Regex::new(
                    r#"(?x)
                    (?P<foo>\S+)
                    \s+
                    (?P<bar>\S+)
                    \s+
                    (?P<baz>\S+)
                "#
                )?,
                "one two three"
            )?,
            LogEntry {
                foo: "one".into(),
                bar: "two".into(),
                baz: "three".into()
            }
        );

        Ok(())
    }

    #[test]
    fn fails_without_captures() -> Result<(), Box<dyn Error>> {
        let result = from_captures::<LogEntry>(&Regex::new("test")?, "one two three");
        match result {
            Ok(_) => panic!("should have failed"),
            // enum variants on type aliases are experimental
            Err(err) => assert_eq!(
                err.to_string(),
                "No captures resolved in string \'one two three\'"
            ),
        }

        Ok(())
    }

    #[test]
    fn fails_with_unmatched_captures() -> Result<(), Box<dyn Error>> {
        let result = from_captures::<LogEntry>(&Regex::new(".+")?, "one two three");
        match result {
            Ok(_) => panic!("should have failed"),
            // enum variants on type aliases are experimental
            Err(err) => assert_eq!(err.to_string(), "missing value for field foo"),
        }

        Ok(())
    }
}