summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: d25fdaa4cc93786990f96c0da72b45b0b4be687c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
use directories_next::ProjectDirs;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use structopt::StructOpt;

const APP: &str = "clab";

fn main() -> anyhow::Result<()> {
    let mut opt = Opt::from_args();
    let book = if let Some(filename) = &opt.db {
        AddressBook::load(filename)?
    } else {
        let proj_dirs = ProjectDirs::from("", "", APP).expect("couldn't find home directory");
        let filename = proj_dirs.data_dir().join("address-book.yaml");
        opt.db = Some(filename.clone());
        if filename.exists() {
            AddressBook::load(&filename)?
        } else {
            AddressBook::default()
        }
    };
    match &opt.cmd {
        Cmd::Config(x) => x.run(&opt, &book),
        Cmd::Lint(x) => x.run(&opt, &book),
        Cmd::List(x) => x.run(&opt, &book)?,
        Cmd::Search(x) => x.run(&opt, &book)?,
        Cmd::MuttQuery(x) => x.run(&opt, &book),
    }
    Ok(())
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct Entry {
    name: String,
    org: Option<String>,
    url: Option<Vec<String>>,
    notes: Option<String>,
    aliases: Option<Vec<String>>,
    email: Option<HashMap<String, String>>,
    phone: Option<HashMap<String, String>>,
    irc: Option<HashMap<String, String>>,
    address: Option<HashMap<String, String>>,
    last_checked: String,
}

impl Entry {
    fn is_match(&self, needle: &str) -> bool {
        let text = serde_yaml::to_string(self).unwrap();
        contains(&text, needle)
    }

    fn emails(&self) -> Vec<String> {
        if let Some(map) = &self.email {
            map.values().map(|x| x.to_string()).collect()
        } else {
            vec![]
        }
    }
}

fn output_entries(entries: &[Entry]) -> anyhow::Result<()> {
    if !entries.is_empty() {
        serde_yaml::to_writer(std::io::stdout(), entries)?;
    }
    Ok(())
}

fn contains(haystack: &str, needle: &str) -> bool {
    let haystack = haystack.to_lowercase();
    let needle = needle.to_lowercase();
    haystack.contains(&needle)
}

#[derive(std::default::Default)]
struct AddressBook {
    entries: Vec<Entry>,
}

impl AddressBook {
    fn load(db: &Path) -> anyhow::Result<Self> {
        let mut book = Self::default();
        book.add_from(db)?;
        Ok(book)
    }

    fn add_from(&mut self, filename: &Path) -> anyhow::Result<()> {
        let text = std::fs::read(&filename)?;
        let mut entries: Vec<Entry> = serde_yaml::from_slice(&text)?;
        self.entries.append(&mut entries);
        Ok(())
    }

    fn entries(&self) -> &[Entry] {
        &self.entries
    }

    fn iter(&self) -> impl Iterator<Item = &Entry> {
        self.entries.iter()
    }
}

#[derive(Debug, StructOpt)]
struct Opt {
    #[structopt(long, parse(from_os_str))]
    db: Option<PathBuf>,

    #[structopt(subcommand)]
    cmd: Cmd,
}

#[derive(Debug, StructOpt)]
enum Cmd {
    Config(ConfigCommand),
    Lint(LintCommand),
    List(ListCommand),
    Search(SearchCommand),
    MuttQuery(MuttCommand),
}

#[derive(Debug, StructOpt)]
struct ConfigCommand {}

impl ConfigCommand {
    fn run(&self, opt: &Opt, _book: &AddressBook) {
        println!("{:#?}", opt);
    }
}

#[derive(Debug, StructOpt)]
struct LintCommand {
    #[structopt(parse(from_os_str))]
    filenames: Vec<PathBuf>,
}

impl LintCommand {
    fn run(&self, _opt: &Opt, _book: &AddressBook) {}
}

#[derive(Debug, StructOpt)]
struct ListCommand {}

impl ListCommand {
    fn run(&self, _opt: &Opt, book: &AddressBook) -> anyhow::Result<()> {
        output_entries(book.entries())
    }
}

#[derive(Debug, StructOpt)]
#[structopt(alias = "find")]
struct SearchCommand {
    #[structopt()]
    words: Vec<String>,
}

impl SearchCommand {
    fn run(&self, _opt: &Opt, book: &AddressBook) -> anyhow::Result<()> {
        let matches: Vec<Entry> = book.iter().filter(|e| self.is_match(e)).cloned().collect();
        output_entries(&matches)
    }

    fn is_match(&self, entry: &Entry) -> bool {
        for word in self.words.iter() {
            if !entry.is_match(word) {
                return false;
            }
        }
        true
    }
}

#[derive(Debug, StructOpt)]
struct MuttCommand {
    #[structopt()]
    word: String,
}

impl MuttCommand {
    fn run(&self, _opt: &Opt, book: &AddressBook) {
        let matches: Vec<Entry> = book.iter().filter(|e| self.is_match(e)).cloned().collect();
        if matches.is_empty() {
            println!("clab found no matches");
            std::process::exit(1);
        }

        println!("clab found matches:");
        for e in matches {
            for email in e.emails() {
                println!("{}\t{}", email, e.name);
            }
        }
    }

    fn is_match(&self, entry: &Entry) -> bool {
        entry.is_match(&self.word)
    }
}