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
//! Handler which puts output into a file

use super::Handler;
use crate::{error, path::Path};
use std::{fs, io::Write};

/// File handler responsible for storing data to a file.
pub struct File {
    /// Opened file structure for storing output
    file: fs::File,

    /// Indicator whether the path will be displayed
    /// e.g. `{"items"}: {"sub": 4}` vs `{"sub": 4}`
    use_path: bool,

    /// String which will be appended to the end of each record
    /// to separate it with the next record (default '#')
    separator: String,
}

impl File {
    /// Creates new File handler
    ///
    /// # Arguments
    /// * `fs_path` - path to a file in the file system (will be truncated)
    ///
    /// # Returns
    /// * `Ok(File)` - Handler was successfully created
    /// * `Err(_)` - Failed to create handler
    ///
    /// # Errors
    ///
    /// Error might occur when the file fails to open
    pub fn new(fs_path: &str) -> Result<Self, error::Handler> {
        let file = fs::File::create(fs_path).map_err(|err| error::Handler::new(err.to_string()))?;
        Ok(Self {
            file,
            use_path: false,
            separator: "\n".into(),
        })
    }

    /// Set whether to show path
    ///
    /// # Arguments
    /// * `use_path` - should path be shown in the output
    ///
    /// # Example
    /// ```
    /// use streamson_lib::handler;
    /// let file = handler::File::new("output.txt")
    ///     .unwrap()
    ///     .set_use_path(true);
    /// ```
    pub fn set_use_path(mut self, use_path: bool) -> Self {
        self.use_path = use_path;
        self
    }

    /// Set which separator will be used in the output
    ///
    /// Note that every separator will be extended to every found item.
    ///
    /// # Arguments
    /// * `separator` - how found record will be separated
    ///
    /// # Example
    /// ```
    /// use streamson_lib::handler;
    /// let file = handler::File::new("output.txt")
    ///     .unwrap()
    ///     .set_separator("######\n");
    /// ```
    pub fn set_separator<S>(mut self, separator: S) -> Self
    where
        S: ToString,
    {
        self.separator = separator.to_string();
        self
    }
}

impl Handler for File {
    fn use_path(&self) -> bool {
        self.use_path
    }

    fn separator(&self) -> &str {
        &self.separator
    }

    fn handle(
        &mut self,
        path: &Path,
        _matcher_idx: usize,
        data: Option<&[u8]>,
    ) -> Result<Option<Vec<u8>>, error::Handler> {
        if self.use_path {
            self.file
                .write(format!("{}: ", path).as_bytes())
                .map_err(|err| error::Handler::new(err.to_string()))?;
        }
        self.file
            .write(data.unwrap())
            .map_err(|err| error::Handler::new(err.to_string()))?;
        let separator = self.separator().to_string();
        self.file
            .write(separator.as_bytes())
            .map_err(|err| error::Handler::new(err.to_string()))?;
        Ok(None)
    }
}

#[cfg(test)]
mod tests {
    use crate::{handler, matcher, strategy};
    use std::{
        fs, str,
        sync::{Arc, Mutex},
    };
    use tempfile::NamedTempFile;

    fn make_output(
        path: &str,
        matcher: matcher::Simple,
        handler: handler::File,
        input: &[u8],
    ) -> String {
        let handler = Arc::new(Mutex::new(handler));
        let mut trigger = strategy::Trigger::new();
        trigger.add_matcher(Box::new(matcher), &[handler]);

        trigger.process(input).unwrap();
        fs::read_to_string(path).unwrap()
    }

    #[test]
    fn basic() {
        let tmp_path = NamedTempFile::new().unwrap().into_temp_path();
        let str_path = tmp_path.to_str().unwrap();

        let matcher = matcher::Simple::new(r#"{"aa"}[]"#).unwrap();
        let handler = handler::File::new(str_path).unwrap();

        let output = make_output(
            str_path,
            matcher,
            handler,
            br#"{"aa": [1, 2, "u"], "b": true}"#,
        );

        assert_eq!(
            output,
            str::from_utf8(
                br#"1
2
"u"
"#
            )
            .unwrap()
        );
    }

    #[test]
    fn separator() {
        let tmp_path = NamedTempFile::new().unwrap().into_temp_path();
        let str_path = tmp_path.to_str().unwrap();

        let matcher = matcher::Simple::new(r#"{"aa"}[]"#).unwrap();
        let handler = handler::File::new(str_path).unwrap().set_separator("XXX");

        let output = make_output(
            str_path,
            matcher,
            handler,
            br#"{"aa": [1, 2, "u"], "b": true}"#,
        );

        assert_eq!(output, str::from_utf8(br#"1XXX2XXX"u"XXX"#).unwrap());
    }

    #[test]
    fn use_path() {
        let tmp_path = NamedTempFile::new().unwrap().into_temp_path();
        let str_path = tmp_path.to_str().unwrap();

        let matcher = matcher::Simple::new(r#"{"aa"}[]"#).unwrap();
        let handler = handler::File::new(str_path).unwrap().set_use_path(true);

        let output = make_output(
            str_path,
            matcher,
            handler,
            br#"{"aa": [1, 2, "u"], "b": true}"#,
        );

        assert_eq!(
            output,
            str::from_utf8(
                br#"{"aa"}[0]: 1
{"aa"}[1]: 2
{"aa"}[2]: "u"
"#
            )
            .unwrap()
        );
    }
}