Skip to main content

quick_links_rofi/
input.rs

1use std::collections::HashMap;
2
3use anyhow::anyhow;
4
5#[derive(Debug)]
6pub struct Item {
7    pub key: String,
8    pub link: String,
9}
10
11impl TryFrom<&str> for Item {
12    type Error = anyhow::Error;
13    fn try_from(s: &str) -> Result<Self, Self::Error> {
14        let split: Vec<&str> = s.split(',').collect();
15        if split.len() != 2 {
16            return Err(anyhow!("There should be 2 elements per line"));
17        }
18        let key = String::from(split[0]);
19        let link = String::from(split[1]);
20        Ok(Item { key, link })
21    }
22}
23
24#[derive(Debug)]
25pub struct Items {
26    values: HashMap<String, String>,
27}
28
29impl TryFrom<&str> for Items {
30    type Error = anyhow::Error;
31    fn try_from(path: &str) -> Result<Self, Self::Error> {
32        let mut values = HashMap::new();
33        for line in std::fs::read_to_string(path)?.lines() {
34            if line.is_empty() {
35                continue;
36            }
37            let item = Item::try_from(line)?;
38            values.insert(item.key, item.link);
39        }
40        Ok(Items { values })
41    }
42}
43
44impl Items {
45    pub fn get_link(&self, s: &str) -> Option<String> {
46        self.values.get(s).cloned()
47    }
48
49    pub fn get_names(&self) -> String {
50        self.values.keys().fold(String::new(), |acc, x| {
51            if !acc.is_empty() {
52                format!("{acc}\n{}", x)
53            } else {
54                String::from(x)
55            }
56        })
57    }
58}