1#[derive(Clone, Debug, Eq, PartialEq)]
2pub struct Host {
3 pub name: String,
4 pub group: String,
5 pub color: Option<String>,
6}
7
8pub fn parse_ssh_config(text: &str) -> Vec<Host> {
9 let mut group = "other".to_owned();
10 let mut color = None;
11 let mut hosts = Vec::new();
12
13 for line in text.lines() {
14 let trimmed = line.trim();
15 if let Some(rest) = trimmed.strip_prefix('#') {
16 let mut fields = rest.split_whitespace();
17 if fields.next() == Some("@group")
18 && let Some(name) = fields.next()
19 {
20 group = name.to_owned();
21 color = fields
22 .next()
23 .filter(|value| valid_color(value))
24 .map(str::to_owned);
25 }
26 continue;
27 }
28 let mut fields = trimmed.split_whitespace();
29 if fields
30 .next()
31 .is_some_and(|word| word.eq_ignore_ascii_case("host"))
32 {
33 for name in fields.filter(|name| !name.chars().any(|c| "*?!".contains(c))) {
34 hosts.push(Host {
35 name: name.to_owned(),
36 group: group.clone(),
37 color: color.clone(),
38 });
39 }
40 }
41 }
42 hosts
43}
44
45fn valid_color(value: &str) -> bool {
46 value.len() == 7 && value.starts_with('#') && value[1..].chars().all(|c| c.is_ascii_hexdigit())
47}
48
49#[cfg(test)]
50mod tests {
51 use super::*;
52
53 #[test]
54 fn parses_groups_colors_and_skips_wildcards() {
55 let hosts = parse_ssh_config(
56 "# @group pve #E57000\nHost one two\nHost *.internal\n# @group lucid\nHost three\n",
57 );
58 assert_eq!(
59 hosts,
60 vec![
61 Host {
62 name: "one".into(),
63 group: "pve".into(),
64 color: Some("#E57000".into())
65 },
66 Host {
67 name: "two".into(),
68 group: "pve".into(),
69 color: Some("#E57000".into())
70 },
71 Host {
72 name: "three".into(),
73 group: "lucid".into(),
74 color: None
75 },
76 ]
77 );
78 }
79}