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
224
225
226
227
228
229
230
231
232
extern crate serde;
extern crate serde_json;

#[macro_use]
extern crate serde_derive;

extern crate base64;

// use std::ops::Range;

// TODO Use `&str` where possible

/// A parser for the output of [grep_printer::JSON](https://docs.rs/grep-printer/0.1.1/grep_printer/struct.JSON.html).
/// Created to deserialize `ripgrep` `--json` output for [rg_replace](https://github.com/Avi-D-coder/rg_replace).
#[derive(Deserialize, Serialize, Debug, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
#[serde(tag = "type", content = "data")]
pub enum Type {
    /// As specified in: [message-begin](https://docs.rs/grep-printer/0.1.1/grep_printer/struct.JSON.html#message-begin).
    Begin { path: ArbitraryData },
    /// As specified in: [message-end](https://docs.rs/grep-printer/0.1.1/grep_printer/struct.JSON.html#message-end).
    End {
        path: ArbitraryData,
        binary_offset: Option<isize>, // FIXME I am not sure it's a isize
        stats: Stats,
    },
    /// As specified in: [message-match](https://docs.rs/grep-printer/0.1.1/grep_printer/struct.JSON.html#message-match).
    Match {
        path: ArbitraryData,
        lines: ArbitraryData,
        line_number: Option<usize>,
        absolute_offset: isize,
        submatches: Vec<SubMatch>, //TODO Optimize
    },
    /// As specified in: [message-context](https://docs.rs/grep-printer/0.1.1/grep_printer/struct.JSON.html#message-context).
    Context {
        path: ArbitraryData,
        lines: ArbitraryData,
        line_number: Option<usize>,
        absolute_offset: isize,
        submatches: Vec<SubMatch>,
    },
    Summary {
        elapsed_total: Duration,
        stats: Stats,
    },
}

/// As specified in: [object-arbitrary-data](https://docs.rs/grep-printer/0.1.1/grep_printer/struct.JSON.html#object-arbitrary-data).
#[derive(Deserialize, Serialize, Debug, PartialEq, Eq)]
#[serde(untagged)]
pub enum ArbitraryData {
    Text { text: String },
    Base64 { bytes: String },
}

impl ArbitraryData {
    pub fn lossy_utf8(&self) -> String {
        match self {
            ArbitraryData::Text { text } => text.to_owned(),
            ArbitraryData::Base64 { bytes } => {
                String::from_utf8_lossy(base64::decode(bytes).unwrap().as_slice()).to_string()
            }
        }
    }
}

/// As specified in: [object-stats](https://docs.rs/grep-printer/0.1.1/grep_printer/struct.JSON.html#object-stats).
#[derive(Deserialize, Serialize, Debug, PartialEq, Eq)]
pub struct Stats {
    pub elapsed: Duration,
    pub searches: isize,
    pub searches_with_match: usize,
    pub bytes_searched: usize,
    pub bytes_printed: usize,
    pub matched_lines: usize,
    pub matches: usize,
}

/// As specified in: [object-duration](https://docs.rs/grep-printer/0.1.1/grep_printer/struct.JSON.html#object-duration).
#[derive(Deserialize, Serialize, Debug, PartialEq, Eq)]
pub struct Duration {
    pub secs: usize,
    pub nanos: usize,
    pub human: String,
}

/// Almost as specified in: [object-submatch](https://docs.rs/grep-printer/0.1.1/grep_printer/struct.JSON.html#object-submatch).
/// `match` is deserialized to `matched` because a rust reserves match as a keyword.
// TODO `start` and `end` are also deserialized to `range`.
#[derive(Deserialize, Serialize, Debug, PartialEq, Eq)]
#[serde(rename = "submatch")]
pub struct SubMatch {
    #[serde(rename = "match")]
    pub matched: ArbitraryData,
    pub start: usize,
    pub end: usize,
    // pub range: Range<usize>, TODO
}

#[cfg(test)]
mod tests {
    // tests based on [`grep_printer` example output](https://docs.rs/grep-printer/0.1.1/grep_printer/struct.JSON.html#example)

    use crate::{ArbitraryData::*, Type::*, *};

    #[test]
    fn arbitrarydata() {
        let json = r#"{"text":"/home/andrew/sherlock"}"#;
        assert_eq!(
            Text {
                text: "/home/andrew/sherlock".to_owned()
            },
            serde_json::from_str(json).unwrap()
        )
    }

    #[test]
    fn begin_deserialize() {
        let json = r#"{"type":"begin","data":{"path":{"text":"/home/andrew/sherlock"}}}"#;
        assert_eq!(
            Begin {
                path: Text {
                    text: "/home/andrew/sherlock".to_owned()
                }
            },
            serde_json::from_str(json).unwrap()
        );
    }

    #[test]
    fn end_deserialize() {
        let json=r#"{"type":"end","data":{"path":{"text":"/home/andrew/sherlock"},"binary_offset":null,"stats":{"elapsed":{"secs":0,"nanos":36296,"human":"0.0000s"},"searches":1,"searches_with_match":1,"bytes_searched":367,"bytes_printed":1151,"matched_lines":2,"matches":2}}}"#;
        assert_eq!(
            End {
                path: Text {
                    text: "/home/andrew/sherlock".to_owned()
                },
                binary_offset: None,
                stats: Stats {
                    elapsed: Duration {
                        secs: 0,
                        nanos: 36296,
                        human: "0.0000s".to_owned()
                    },
                    searches: 1,
                    searches_with_match: 1,
                    bytes_searched: 367,
                    bytes_printed: 1151,
                    matched_lines: 2,
                    matches: 2
                }
            },
            serde_json::from_str(json).unwrap()
        );
    }

    #[test]
    fn match_deserialize() {
        let json=r#"{"type":"match","data":{"path":{"text":"/home/andrew/sherlock"},"lines":{"text":"but Doctor Watson has to have it taken out for him and dusted,\n"},"line_number":5,"absolute_offset":258,"submatches":[{"match":{"text":"Watson"},"start":11,"end":17}]}}"#;
        assert_eq!(
            Match {
                path: Text {
                    text: "/home/andrew/sherlock".to_owned()
                },
                lines: Text {
                    text: "but Doctor Watson has to have it taken out for him and dusted,\n"
                        .to_owned()
                },
                line_number: Some(5),
                absolute_offset: 258,
                submatches: vec![SubMatch {
                    matched: Text {
                        text: "Watson".to_owned()
                    },
                    start: 11,
                    end: 17
                }],
            },
            serde_json::from_str(json).unwrap()
        )
    }

    #[test]
    fn content_deserialize() {
        let json = r#"{"type":"context","data":{"path":{"text":"/home/andrew/sherlock"},"lines":{"text":"can extract a clew from a wisp of straw or a flake of cigar ash;\n"},"line_number":4,"absolute_offset":193,"submatches":[]}}"#;
        assert_eq!(
            Context {
                path: Text {
                    text: "/home/andrew/sherlock".to_owned()
                },
                lines: Text {
                    text: "can extract a clew from a wisp of straw or a flake of cigar ash;\n"
                        .to_owned()
                },
                line_number: Some(4),
                absolute_offset: 193,
                submatches: vec![],
            },
            serde_json::from_str(json).unwrap()
        )
    }

    #[test]
    fn summary_deserialize() {
        let json = r#"{"data":{"elapsed_total":{"human":"0.099726s","nanos":99726344,"secs":0},"stats":{"bytes_printed":4106,"bytes_searched":5860,"elapsed":{"human":"0.000047s","nanos":46800,"secs":0},"matched_lines":3,"matches":3,"searches":1,"searches_with_match":1}},"type":"summary"}"#;
        assert_eq!(
            Summary {
                elapsed_total: Duration {
                    human: "0.099726s".to_string(),
                    nanos: 99726344,
                    secs: 0
                },
                stats: Stats {
                    bytes_printed: 4106,
                    bytes_searched: 5860,
                    elapsed: Duration {
                        human: "0.000047s".to_owned(),
                        nanos: 46800,
                        secs: 0,
                    },
                    matched_lines: 3,
                    matches: 3,
                    searches: 1,
                    searches_with_match: 1
                }
            },
            serde_json::from_str(json).unwrap()
        )
    }

}