summaryrefslogtreecommitdiffstats
path: root/src/ssh.rs
blob: 606509ad16e9039bbb0e75672911e2e0ed064b45 (plain)
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
use std::{
    fs::File,
    io::{BufRead, BufReader, Error, ErrorKind},
};

use directories::UserDirs;

use crate::Session;

pub struct KnownHosts(Vec<Session>);

impl KnownHosts {
    pub fn open() -> Result<Self, Error> {
        let path = UserDirs::new()
            .ok_or(ErrorKind::NotFound)?
            .home_dir()
            .join(".ssh/known_hosts");

        let file = File::open(path)?;

        let inner = BufReader::new(file)
            .lines()
            .flatten()
            .take_while(|s| !s.starts_with('#'))
            .filter_map(|l| l.split_whitespace().next().map(str::to_owned))
            .map(Session::discover)
            .collect();

        Ok(Self(inner))
    }
}

impl IntoIterator for KnownHosts {
    type Item = Session;

    type IntoIter = std::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}