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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
#[macro_use]
extern crate lazy_static;
extern crate regex;

use regex::Regex;
use std::fmt;
use std::str::FromStr;
use std::vec::Vec;

#[derive(Debug, Eq, PartialEq)]
pub struct HostsFile {
    pub lines: Vec<HostsFileLine>,
}

#[derive(Debug, Eq, PartialEq)]
pub struct HostsFileLine {
    is_empty: bool,
    comment: Option<String>,
    ip: Option<String>,
    hosts: Option<Vec<String>>,
}

impl fmt::Display for HostsFileLine {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // let out = match self {
        //     HostsFileLine::Empty => "".to_string(),
        //     HostsFileLine::Comment(s) => format!("#{}", s),
        //     HostsFileLine::Host(h) => format!("{} {}", h.ip, h.hosts.join(" ")),
        //     // write!(f, "Error parsing hosts file")
        // };
        let mut parts: Vec<Option<String>> = vec![self.ip.clone()];
        if let Some(hosts) = self.hosts.clone() {
            let mut clone: Vec<Option<String>> =
                hosts.clone().iter_mut().map(|h| Some(h.clone())).collect();
            parts.append(&mut clone);
        }
        parts.push(self.comment.clone());
        let parts: Vec<String> = parts
            .iter()
            .filter(|s| s.is_some())
            .map(|s| s.clone().unwrap())
            .collect();
        write!(f, "{}", parts.join(" "))
    }
}

impl FromStr for HostsFileLine {
    type Err = ParseError;
    fn from_str(s: &str) -> Result<HostsFileLine, Self::Err> {
        HostsFileLine::from_string(s)
    }
}

impl HostsFileLine {
    pub fn from_empty() -> HostsFileLine {
        HostsFileLine {
            is_empty: true,
            comment: None,
            ip: None,
            hosts: None,
        }
    }
    pub fn from_comment(c: &str) -> HostsFileLine {
        HostsFileLine {
            is_empty: false,
            comment: Some(c.to_string()),
            ip: None,
            hosts: None,
        }
    }
    pub fn from_string(line: &str) -> Result<HostsFileLine, ParseError> {
        let line = line.trim();
        if line == "" {
            return Ok(HostsFileLine::from_empty());
        }
        lazy_static! {
            static ref COMMENT_RE: Regex = Regex::new(r"^#.*").unwrap();
        }
        if COMMENT_RE.is_match(line) {
            return Ok(HostsFileLine::from_comment(line));
        }
        let slices: Vec<String> = line.split_whitespace().map(|s| s.to_string()).collect();
        let ip: String = slices.first().ok_or(ParseError)?.clone();
        let hosts: Vec<String> = (&slices[1..])
            .iter()
            .take_while(|s| !COMMENT_RE.is_match(s))
            .map(|h| h.to_string())
            .collect();
        if hosts.is_empty() {
            return Err(ParseError);
        }
        let comment: String = (&slices[1..])
            .iter()
            .skip_while(|s| !COMMENT_RE.is_match(s))
            .map(|h| h.to_string())
            .collect::<Vec<String>>()
            .join(" ");
        let comment = match comment.as_str() {
            "" => None,
            _ => Some(comment.to_string()),
        };
        Ok(HostsFileLine {
            is_empty: false,
            ip: Some(ip),
            hosts: Some(hosts),
            comment,
        })
    }
    pub fn ip(&self) -> Option<String> {
        self.ip.clone()
    }
    pub fn hosts(&self) -> Vec<String> {
        self.hosts.clone().unwrap_or_else(|| vec![])
    }
    pub fn comment(&self) -> Option<String> {
        self.comment.clone()
    }
    pub fn has_host(&self) -> bool {
        self.ip.is_some()
    }
    pub fn has_comment(&self) -> bool {
        self.comment.is_some()
    }
}

#[derive(Debug, Eq, PartialEq)]
pub struct HostsFileHost {
    pub ip: String,
    pub hosts: Vec<String>,
    pub comment: Option<String>,
}

pub struct ParseError;

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Error parsing hosts file")
    }
}

impl fmt::Debug for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{{ file: {}, line: {} }}", file!(), line!())
    }
}

impl FromStr for HostsFile {
    type Err = ParseError;
    fn from_str(s: &str) -> Result<HostsFile, Self::Err> {
        HostsFile::from_string(s)
    }
}
impl HostsFile {
    fn from_string(s: &str) -> Result<HostsFile, ParseError> {
        let lines: Vec<HostsFileLine> = s
            .lines()
            .map(|l| l.parse::<HostsFileLine>())
            .collect::<Result<Vec<HostsFileLine>, ParseError>>()?;
        Ok(HostsFile { lines })
    }
    pub fn serialize(&self) -> String {
        format!(
            "{}\n",
            self.lines
                .iter()
                .map(|l| format!("{}", l))
                .collect::<Vec<String>>()
                .join("\n")
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // Parse tests
    #[test]
    fn from_empty() {
        let parsed = HostsFileLine::from_empty();
        let expected = HostsFileLine {
            is_empty: true,
            ip: None,
            comment: None,
            hosts: None,
        };
        assert_eq!(parsed, expected);
    }
    #[test]
    fn from_comment() {
        let parsed = HostsFileLine::from_comment("#test");
        let expected = HostsFileLine {
            is_empty: false,
            ip: None,
            comment: Some("#test".to_string()),
            hosts: None,
        };
        assert_eq!(parsed, expected);
    }

    #[test]
    fn empty_line_from_string() {
        let parsed = HostsFileLine::from_string("").unwrap();
        let expected = HostsFileLine::from_empty();
        assert_eq!(parsed, expected);
    }
    #[test]
    fn comment_from_string() {
        let parsed = HostsFileLine::from_string("# comment").unwrap();
        let expected = HostsFileLine::from_comment("# comment");
        assert_eq!(parsed, expected);
    }

    #[test]
    fn broken_from_string() {
        HostsFileLine::from_string("127.0.0.1").expect_err("should fail");
    }
    #[test]
    fn host_from_string() {
        let parsed = HostsFileLine::from_string("127.0.0.1 localhost").unwrap();
        let expected = HostsFileLine {
            is_empty: false,
            ip: Some("127.0.0.1".to_string()),
            hosts: Some(vec!["localhost".to_string()]),
            comment: None,
        };
        assert_eq!(parsed, expected);
    }
    #[test]
    fn full_from_string() {
        let parsed = HostsFileLine::from_string("127.0.0.1 localhost  # a comment").unwrap();
        let expected = HostsFileLine {
            is_empty: false,
            ip: Some("127.0.0.1".to_string()),
            hosts: Some(vec!["localhost".to_string()]),
            comment: Some("# a comment".to_string()),
        };
        assert_eq!(parsed, expected);
    }
    #[test]
    fn empty_input() {
        let parsed = HostsFile::from_str("").unwrap();
        let expected = HostsFile { lines: vec![] };
        assert_eq!(parsed, expected);
    }
    #[test]
    fn a_comment() {
        let parsed = HostsFile::from_str("# comment").unwrap();
        let expected = HostsFile {
            lines: vec![HostsFileLine::from_comment("# comment")],
        };
        assert_eq!(parsed, expected);
    }
    #[test]
    fn two_comments() {
        let parsed = HostsFile::from_str("# comment1\n## comment2\n").unwrap();
        let expected = HostsFile {
            lines: vec![
                HostsFileLine::from_comment("# comment1"),
                HostsFileLine::from_comment("## comment2"),
            ],
        };
        assert_eq!(parsed, expected);
    }
    #[test]
    fn host_with_comments() {
        let parsed = HostsFile::from_str("127.0.0.1 localhost # comment\n").unwrap();
        let expected = HostsFile {
            lines: vec![HostsFileLine {
                is_empty: false,
                ip: Some("127.0.0.1".to_string()),
                hosts: Some(vec!["localhost".to_string()]),
                comment: Some("# comment".to_string()),
            }],
        };
        assert_eq!(parsed, expected);
    }
    #[test]
    fn whitespace() {
        let parsed = HostsFile::from_str(" # comment1\n \n    127.0.0.1    localhost\n").unwrap();
        let expected = HostsFile {
            lines: vec![
                HostsFileLine::from_comment("# comment1"),
                HostsFileLine::from_empty(),
                HostsFileLine::from_string("127.0.0.1 localhost").unwrap(),
            ],
        };
        assert_eq!(parsed, expected);
    }
    #[test]
    fn a_ipv6_host() {
        let parsed = HostsFile::from_str("fe80::1%lo0 localhost\n").unwrap();
        let expected = HostsFile {
            lines: vec![HostsFileLine {
                is_empty: false,
                ip: Some("fe80::1%lo0".to_string()),
                hosts: Some(vec!["localhost".to_string()]),
                comment: None,
            }],
        };
        assert_eq!(parsed, expected);
    }

    #[test]
    fn a_ipv4_host() {
        let parsed = HostsFile::from_str("127.0.0.1 localhost").unwrap();
        let expected = HostsFile {
            lines: vec![HostsFileLine {
                is_empty: false,
                ip: Some("127.0.0.1".to_string()),
                hosts: Some(vec!["localhost".to_string()]),
                comment: None,
            }],
        };
        assert_eq!(parsed, expected);
    }

    #[test]
    fn complex_1() {
        let parsed = HostsFile::from_str("# A sample host file\n# empty line\n\n127.0.0.1 localhost\n# multiple hosts\n127.0.0.2 host1 host2\n").unwrap();
        let expected = HostsFile {
            lines: vec![
                HostsFileLine::from_comment("# A sample host file"),
                HostsFileLine::from_comment("# empty line"),
                HostsFileLine::from_empty(),
                HostsFileLine {
                    is_empty: false,
                    ip: Some("127.0.0.1".to_string()),
                    hosts: Some(vec!["localhost".to_string()]),
                    comment: None,
                },
                HostsFileLine::from_comment("# multiple hosts"),
                HostsFileLine {
                    is_empty: false,
                    ip: Some("127.0.0.2".to_string()),
                    hosts: Some(
                        vec!["host1", "host2"]
                            .iter()
                            .map(|s| s.to_string())
                            .collect(),
                    ),
                    comment: None,
                },
            ],
        };
        assert_eq!(parsed, expected);
    }

    // Serialize

    #[test]
    fn serialize_empty() {
        let input = "\n";
        let serialized = HostsFile::from_str(input).unwrap().serialize();
        assert_eq!(serialized, input);
    }
    #[test]
    fn serialize_a_comment() {
        let input = "# a comment\n";
        let serialized = HostsFile::from_str(input).unwrap().serialize();
        assert_eq!(serialized, input);
    }

    #[test]
    fn serialize_complex_1() {
        let input = "# A sample host file\n# empty line\n\n127.0.0.1 localhost\n# multiple hosts\n127.0.0.2 host1 host2\n";
        let serialized = HostsFile::from_str(input).unwrap().serialize();
        assert_eq!(serialized, input);
    }
}