ssh_vault/
tools.rs

1use anyhow::{Result, anyhow};
2use std::path::PathBuf;
3
4/// Return the user's home directory.
5///
6/// # Errors
7///
8/// Returns an error if the home directory cannot be determined.
9pub fn get_home() -> Result<PathBuf> {
10    home::home_dir().map_or_else(|| Err(anyhow!("Could not find home directory")), Ok)
11}
12
13/// Filter fetched text to only include supported SSH public keys.
14///
15/// # Errors
16///
17/// Returns an error if no supported keys are found.
18pub fn filter_fetched_keys(response: &str) -> Result<String> {
19    let mut filtered_keys = String::new();
20
21    for line in response.lines() {
22        if line.starts_with("ssh-rsa") || line.starts_with("ssh-ed25519") {
23            filtered_keys.push_str(line);
24            filtered_keys.push('\n'); // Add a newline to separate the lines
25        }
26    }
27
28    if filtered_keys.is_empty() {
29        Err(anyhow!("No SSH keys (ssh-rsa or ssh-ed25519) found"))
30    } else {
31        Ok(filtered_keys)
32    }
33}
34
35#[cfg(test)]
36#[allow(clippy::unwrap_used)]
37mod tests {
38    use super::*;
39
40    #[test]
41    fn test_get_home() -> Result<(), Box<dyn std::error::Error>> {
42        let home = get_home()?;
43        assert!(home.is_dir());
44        Ok(())
45    }
46}