JHHM

lol-cal

terminal lolesports schedule viewer
git clone https://jhhm.no/repos/lol-cal.git

lol-cal/src/config/parser.rs

get raw file: parser.rs

1use std::char;
2use std::ops::{Deref, DerefMut};
3use std::{collections::HashMap, fs::read_to_string, path::Path};
4
5use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
6use ratatui::style::{Color, Modifier, Style};
7use ratatui::widgets::BorderType;
8use tracing::*;
9
10use super::error::Error;
11use crate::config::Config;
12use crate::event::AppEvent;
13
14use super::utils::{get_border_connections, get_config_dir, get_data_dir};
15
16const SEPERATOR: char = '=';
17
18#[derive(Debug)]
19struct RawConfig(pub HashMap<String, Vec<(String, String)>>);
20
21impl Deref for RawConfig {
22    type Target = HashMap<String, Vec<(String, String)>>;
23
24    fn deref(&self) -> &Self::Target {
25        &self.0
26    }
27}
28
29impl DerefMut for RawConfig {
30    fn deref_mut(&mut self) -> &mut Self::Target {
31        &mut self.0
32    }
33}
34
35impl Config {
36    pub fn new() -> Result<Self, Error> {
37        let config_path = get_config_dir().join("config");
38        if config_path.exists() {
39            Config::from_file(config_path)
40        } else {
41            info!("Found no config file, proceeding with default values");
42            Ok(Config::default())
43        }
44    }
45
46    fn from_file<P: AsRef<Path>>(path: P) -> Result<Config, Error> {
47        let config_file = path.as_ref();
48        if !config_file.exists() {
49            return Err(Error::NoConfigFile(
50                config_file.to_string_lossy().into_owned(),
51            ));
52        }
53        let mut config = Config::default();
54
55        config.config_dir = path.as_ref().to_path_buf();
56        config.data_dir = get_data_dir();
57
58        let raw_config = raw_from_file(config_file)?;
59
60        info!("{:?}", raw_config);
61
62        if let Some(style) = raw_config.get("settings") {
63            for (raw_key, raw_value) in style {
64                match raw_key.as_str() {
65                    "default_leagues" => {
66                        config.default_leagues =
67                            raw_value.split(',').map(|s| s.trim().to_string()).collect()
68                    }
69                    "spoil_results" => config.spoil_results = parse_bool(raw_value)?,
70                    "spoil_matches" => config.spoil_matches = parse_bool(raw_value)?,
71                    "automatic_reload" => config.automatic_reload = parse_bool(raw_value)?,
72                    _ => {
73                        return Err(Error::UnknownKey(
74                            raw_key.to_string(),
75                            "settings".to_string(),
76                        ));
77                    }
78                };
79            }
80        }
81
82        if let Some(binds) = raw_config.get("keybindings") {
83            for (raw_key, raw_command) in binds {
84                let key_event = parse_key_event(raw_key)?;
85                let command = parse_command(&raw_command)?;
86                config.keybindings.insert(key_event, command);
87            }
88        }
89
90        if let Some(style) = raw_config.get("style") {
91            for (raw_key, raw_style) in style {
92                match raw_key.as_str() {
93                    "default" => config.style.default = parse_style(raw_style)?,
94                    "highlight" => config.style.highlight = parse_style(raw_style)?,
95                    "selected" => config.style.selected = parse_style(raw_style)?,
96                    "winner" => config.style.winner = parse_optional_style(raw_style)?,
97                    "loser" => config.style.loser = parse_optional_style(raw_style)?,
98                    "border" => {
99                        config.style.border = parse_border_type(raw_style)?;
100                        config.style.border_set = get_border_connections(config.style.border);
101                    }
102                    _ => {
103                        return Err(Error::UnknownKey(raw_key.to_string(), "style".to_string()));
104                    }
105                };
106            }
107        }
108
109        Ok(config)
110    }
111}
112
113fn raw_from_file<P: AsRef<Path>>(path: P) -> Result<RawConfig, Error> {
114    let content = read_to_string(path)?;
115    let mut section = String::new();
116    let mut sections: RawConfig = RawConfig(HashMap::new());
117
118    for (i, line) in content.lines().enumerate() {
119        let line = line.trim();
120        // Skip comments and empty lines
121        if line.is_empty() || line.starts_with('#') || line.starts_with(';') {
122            continue;
123        }
124
125        if line.starts_with('[') && line.ends_with(']') {
126            section = line[1..line.len() - 1].trim().to_string();
127            if section.is_empty() {
128                return Err(Error::EmptyHeader(i));
129            }
130            sections.entry(section.clone()).or_default();
131            continue;
132        } else if line.starts_with('[') || line.ends_with(']') {
133            return Err(Error::IncompleteHeader(i));
134        }
135
136        if let Some((key, value)) = line.split_once(SEPERATOR) {
137            let key = key.trim().to_string();
138            if key.is_empty() {
139                return Err(Error::EmptyKey(i));
140            }
141            let value = value.trim().to_string();
142            if value.is_empty() {
143                return Err(Error::EmptyValue(i));
144            }
145            if let Some(s) = sections.get_mut(&section) {
146                s.push((key, value));
147            } else {
148                sections
149                    .entry("settings".to_string())
150                    .or_default()
151                    .push((key, value));
152            }
153        } else {
154            return Err(Error::MissingSeperator(i));
155        }
156    }
157    Ok(sections)
158}
159
160fn parse_key_event(raw: &str) -> Result<KeyEvent, Error> {
161    let raw_lower = raw.to_ascii_lowercase();
162    let (remaining, modifiers) = extract_modifiers(&raw_lower);
163    parse_key_code_with_modifiers(remaining, modifiers)
164}
165
166fn parse_command(raw: &str) -> Result<AppEvent, Error> {
167    use AppEvent::*;
168
169    Ok(match raw {
170        "Quit" => Quit,
171        "Up" => Up,
172        "Down" => Down,
173        "Left" => Left,
174        "Right" => Right,
175        "Select" => Select,
176        "GotoToday" => GotoToday,
177        "ToggleSpoilResults" => ToggleSpoilResults,
178        "ToggleSpoilMatches" => ToggleSpoilMatches,
179        "ReloadLeagues" => ReloadLeagues,
180        "ReloadSchedule" => ReloadSchedule,
181        _ => return Err(Error::InvalidCommand(raw.to_string())),
182    })
183}
184
185fn extract_modifiers(raw: &str) -> (&str, KeyModifiers) {
186    let mut modifiers = KeyModifiers::empty();
187    let mut current = raw;
188
189    loop {
190        match current {
191            rest if rest.starts_with("ctrl-") => {
192                modifiers.insert(KeyModifiers::CONTROL);
193                current = &rest[5..];
194            }
195            rest if rest.starts_with("alt-") => {
196                modifiers.insert(KeyModifiers::ALT);
197                current = &rest[4..];
198            }
199            rest if rest.starts_with("shift-") => {
200                modifiers.insert(KeyModifiers::SHIFT);
201                current = &rest[6..];
202            }
203            _ => break, // break out of the loop if no known prefix is detected
204        };
205    }
206
207    (current, modifiers)
208}
209
210fn parse_key_code_with_modifiers(
211    raw: &str,
212    mut modifiers: KeyModifiers,
213) -> Result<KeyEvent, Error> {
214    let c = match raw {
215        "esc" => KeyCode::Esc,
216        "enter" => KeyCode::Enter,
217        "left" => KeyCode::Left,
218        "right" => KeyCode::Right,
219        "up" => KeyCode::Up,
220        "down" => KeyCode::Down,
221        "home" => KeyCode::Home,
222        "end" => KeyCode::End,
223        "pageup" => KeyCode::PageUp,
224        "pagedown" => KeyCode::PageDown,
225        "backtab" => {
226            modifiers.insert(KeyModifiers::SHIFT);
227            KeyCode::BackTab
228        }
229        "backspace" => KeyCode::Backspace,
230        "delete" => KeyCode::Delete,
231        "insert" => KeyCode::Insert,
232        "f1" => KeyCode::F(1),
233        "f2" => KeyCode::F(2),
234        "f3" => KeyCode::F(3),
235        "f4" => KeyCode::F(4),
236        "f5" => KeyCode::F(5),
237        "f6" => KeyCode::F(6),
238        "f7" => KeyCode::F(7),
239        "f8" => KeyCode::F(8),
240        "f9" => KeyCode::F(9),
241        "f10" => KeyCode::F(10),
242        "f11" => KeyCode::F(11),
243        "f12" => KeyCode::F(12),
244        "space" => KeyCode::Char(' '),
245        "hyphen" => KeyCode::Char('-'),
246        "minus" => KeyCode::Char('-'),
247        "tab" => KeyCode::Tab,
248        c if c.len() == 1 => {
249            let mut c = c.chars().next().unwrap();
250            if modifiers.contains(KeyModifiers::SHIFT) {
251                c = c.to_ascii_uppercase();
252            }
253            KeyCode::Char(c)
254        }
255        _ => return Err(Error::InvalidKeybind(raw.to_string())),
256    };
257    Ok(KeyEvent::new(c, modifiers))
258}
259
260fn parse_style(line: &str) -> Result<Style, Error> {
261    let (foreground, background) =
262        line.split_at(line.to_lowercase().find("on ").unwrap_or(line.len()));
263    let foreground = process_color_string(foreground);
264    let background = process_color_string(&background.replace("on ", ""));
265
266    let mut style = Style::default();
267    if !foreground.0.is_empty() {
268        let fg = parse_color(&foreground.0)?;
269        style = style.fg(fg);
270    }
271    if !background.0.is_empty() {
272        let bg = parse_color(&background.0)?;
273        style = style.bg(bg);
274    }
275    style = style.add_modifier(foreground.1 | background.1);
276    Ok(style)
277}
278
279fn parse_optional_style(line: &str) -> Result<Option<Style>, Error> {
280    if line.to_lowercase() == "none" {
281        Ok(None)
282    } else {
283        Ok(Some(parse_style(line)?))
284    }
285}
286
287fn process_color_string(color_str: &str) -> (String, Modifier) {
288    let color = color_str
289        .replace("bold ", "")
290        // .replace("underline ", "")
291        .replace("inverse ", "")
292        .trim()
293        .to_string();
294
295    let mut modifiers = Modifier::empty();
296    /*
297        if color_str.contains("underline") {
298            modifiers |= Modifier::UNDERLINED;
299        }
300    */
301    if color_str.contains("bold") {
302        modifiers |= Modifier::BOLD;
303    }
304    if color_str.contains("inverse") {
305        modifiers |= Modifier::REVERSED;
306    }
307
308    (color, modifiers)
309}
310
311fn parse_color(s: &str) -> Result<Color, Error> {
312    if let Some(rgb) = parse_rgb(s) {
313        return Ok(Color::Rgb(rgb.0, rgb.1, rgb.2));
314    }
315    match s {
316        "black" => Ok(Color::Indexed(0)),
317        "red" => Ok(Color::Indexed(1)),
318        "green" => Ok(Color::Indexed(2)),
319        "yellow" => Ok(Color::Indexed(3)),
320        "blue" => Ok(Color::Indexed(4)),
321        "magenta" => Ok(Color::Indexed(5)),
322        "cyan" => Ok(Color::Indexed(6)),
323        "gray" => Ok(Color::Indexed(7)),
324        "bright black" => Ok(Color::Indexed(8)),
325        "bright red" => Ok(Color::Indexed(9)),
326        "bright green" => Ok(Color::Indexed(10)),
327        "bright yellow" => Ok(Color::Indexed(11)),
328        "bright blue" => Ok(Color::Indexed(12)),
329        "bright magenta" => Ok(Color::Indexed(13)),
330        "bright cyan" => Ok(Color::Indexed(14)),
331        "white" => Ok(Color::Indexed(15)),
332        _ => Err(Error::InvalidColor(s.to_string())),
333    }
334}
335
336fn parse_rgb(s: &str) -> Option<(u8, u8, u8)> {
337    if !s.starts_with('#') || s.len() != 7 {
338        return None;
339    }
340
341    let r = u8::from_str_radix(&s[1..3], 16).ok()?;
342    let g = u8::from_str_radix(&s[3..5], 16).ok()?;
343    let b = u8::from_str_radix(&s[5..7], 16).ok()?;
344
345    Some((r, g, b))
346}
347
348fn parse_border_type(line: &str) -> Result<Option<BorderType>, Error> {
349    match line.to_lowercase().as_str() {
350        "plain" => Ok(Some(BorderType::Plain)),
351        "rounded" => Ok(Some(BorderType::Rounded)),
352        "double" => Ok(Some(BorderType::Double)),
353        "thick" => Ok(Some(BorderType::Thick)),
354        "none" => Ok(None),
355        _ => Err(Error::InvalidBorder(line.to_string())),
356    }
357}
358
359fn parse_bool(line: &str) -> Result<bool, Error> {
360    match line.to_lowercase().as_str() {
361        "yes" | "true" => Ok(true),
362        "no" | "false" => Ok(false),
363        _ => return Err(Error::InvalidBool(line.to_string())),
364    }
365}