agentmux_srv_core/backend/wconfig/
unrecognized.rs1use std::collections::HashMap;
12
13use serde::{Deserialize, Serialize};
14
15#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
17pub struct UnrecognizedSetting {
18 pub key: String,
19 #[serde(default, skip_serializing_if = "Option::is_none")]
21 pub suggestion: Option<String>,
22 #[serde(default, skip_serializing_if = "Option::is_none")]
24 pub line: Option<u32>,
25}
26
27const NOT_SETTINGS: [&str; 2] = ["connections", "$schema"];
30
31fn allowed_distance(len: usize) -> usize {
34 (len / 8).clamp(1, 3)
35}
36
37fn distance(a: &[char], b: &[char], max: usize) -> Option<usize> {
40 if a.len().abs_diff(b.len()) > max {
41 return None;
42 }
43 let mut previous: Vec<usize> = (0..=b.len()).collect();
44 for (i, ca) in a.iter().enumerate() {
45 let mut row = vec![i + 1];
46 for (j, cb) in b.iter().enumerate() {
47 let replace = previous[j] + usize::from(ca != cb);
48 row.push(replace.min(previous[j + 1] + 1).min(row[j] + 1));
49 }
50 previous = row;
51 }
52 let d = previous[b.len()];
53 (d <= max).then_some(d)
54}
55
56fn closest<'a>(key: &str, known: &[&'a str]) -> Option<&'a str> {
59 let lower: Vec<char> = key.to_lowercase().chars().collect();
60 let max = allowed_distance(lower.len());
61 known
62 .iter()
63 .filter(|k| !k.ends_with('*'))
64 .filter_map(|k| {
65 let other: Vec<char> = k.to_lowercase().chars().collect();
66 distance(&lower, &other, max).map(|d| (d, *k))
67 })
68 .min()
69 .map(|(_, k)| k)
70}
71
72pub fn find<'a>(keys: impl IntoIterator<Item = &'a String>, known: &[&str], lines: &HashMap<String, u32>) -> Vec<UnrecognizedSetting> {
75 let mut found: Vec<UnrecognizedSetting> = keys
76 .into_iter()
77 .filter(|key| !known.contains(&key.as_str()) && !NOT_SETTINGS.contains(&key.as_str()))
78 .map(|key| UnrecognizedSetting { key: key.clone(), suggestion: closest(key, known).map(str::to_string), line: lines.get(key).copied() })
79 .collect();
80 found.sort_by(|a, b| (a.line.unwrap_or(u32::MAX), &a.key).cmp(&(b.line.unwrap_or(u32::MAX), &b.key)));
81 found
82}
83
84#[cfg(test)]
85mod tests {
86 use super::*;
87
88 const KNOWN: [&str; 6] = ["term:fontsize", "term:theme", "term:scrollback", "app:*", "window:zoom", "agent:livefeedturns"];
89
90 fn keys(list: &[&str]) -> Vec<String> {
91 list.iter().map(|s| s.to_string()).collect()
92 }
93
94 fn found(list: &[&str]) -> Vec<UnrecognizedSetting> {
95 find(&keys(list), &KNOWN, &HashMap::new())
96 }
97
98 #[test]
99 fn a_recognised_key_is_not_listed_and_a_family_key_is_recognised_as_written() {
100 assert!(found(&["term:fontsize", "app:*", "window:zoom"]).is_empty());
101 }
102
103 #[test]
104 fn what_agentmux_writes_into_the_file_beside_the_settings_is_not_listed() {
105 assert!(found(&["connections", "$schema"]).is_empty());
106 }
107
108 #[test]
109 fn a_typo_is_listed_with_the_key_it_was_probably_meant_to_be() {
110 let list = found(&["term:fontsise"]);
111 assert_eq!(list, vec![UnrecognizedSetting { key: "term:fontsise".into(), suggestion: Some("term:fontsize".into()), line: None }]);
112 }
113
114 #[test]
115 fn a_key_that_differs_only_in_case_is_offered_as_the_right_one() {
116 assert_eq!(found(&["Term:FontSize"])[0].suggestion.as_deref(), Some("term:fontsize"));
117 }
118
119 #[test]
120 fn a_key_far_from_everything_is_listed_with_no_suggestion() {
121 assert_eq!(found(&["my:own:note"])[0].suggestion, None);
122 assert_eq!(found(&["zzzzzz"])[0].suggestion, None);
123 }
124
125 #[test]
126 fn a_short_key_is_offered_only_one_edit_away_and_a_long_one_up_to_three() {
127 assert_eq!(found(&["term:thme"])[0].suggestion.as_deref(), Some("term:theme"));
129 assert_eq!(found(&["term:tm"])[0].suggestion, None);
130 assert_eq!(found(&["agent:livefeedturnz"])[0].suggestion.as_deref(), Some("agent:livefeedturns"));
131 assert_eq!(found(&["agent:livefedtrns"])[0].suggestion.as_deref(), Some("agent:livefeedturns"));
132 }
133
134 #[test]
135 fn a_family_key_is_never_the_suggestion() {
136 assert_eq!(found(&["app:x"])[0].suggestion, None);
137 }
138
139 #[test]
140 fn the_answer_follows_the_file_order_then_the_name_and_does_not_depend_on_map_order() {
141 let lines: HashMap<String, u32> = [("b:key".to_string(), 3), ("a:key".to_string(), 9)].into_iter().collect();
142 let list = find(&keys(&["a:key", "b:key", "c:key"]), &KNOWN, &lines);
143 assert_eq!(list.iter().map(|u| u.key.as_str()).collect::<Vec<_>>(), ["b:key", "a:key", "c:key"]);
144 assert_eq!(list[0].line, Some(3));
145 assert_eq!(list[2].line, None);
146 }
147
148 #[test]
149 fn a_non_ascii_key_is_compared_by_characters() {
150 let list = found(&["term:théme"]);
151 assert_eq!(list[0].suggestion.as_deref(), Some("term:theme"));
152 }
153
154 #[test]
155 fn distance_stops_early_when_the_lengths_alone_are_too_far_apart() {
156 let a: Vec<char> = "abc".chars().collect();
157 let b: Vec<char> = "abcdefgh".chars().collect();
158 assert_eq!(distance(&a, &b, 3), None);
159 assert_eq!(distance(&a, &a, 3), Some(0));
160 }
161}