From 69175a9eec0597e064a1c51415c1e47b026b6ebb Mon Sep 17 00:00:00 2001 From: Lars Wirzenius Date: Sat, 23 Mar 2013 14:01:57 +0000 Subject: mutt-query works --- clab | 53 +++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 37 insertions(+), 16 deletions(-) diff --git a/clab b/clab index 26f9c77..8d37977 100755 --- a/clab +++ b/clab @@ -23,6 +23,31 @@ import sys import yaml +class Entry(object): + + def __init__(self, parsed_yaml): + assert type(parsed_yaml) is dict + self._dict = parsed_yaml + + def as_yaml(self): + return yaml.safe_dump(self._dict) + + def get_single(self, key, default): + names = self.get_subdict(key) + if not names: + return default + keys = sorted(names.keys()) + return names[keys[0]] + + def get_subdict(self, key): + if key in self._dict: + v = self._dict[key] + if type(v) is dict: + return v + return { '': v } + return {} + + class AddressBook(object): def __init__(self): @@ -42,17 +67,15 @@ class AddressBook(object): def add_from_file(self, filename): logging.info('Adding from file %s' % filename) with open(filename) as f: - record = yaml.safe_load(f) - self.entries.append(record) + parsed_yaml = yaml.safe_load(f) + entry = Entry(parsed_yaml) + self.entries.append(entry) def find(self, pattern): - return [] - - def get_single(self, key, default): - return default - - def get_list(self, key): - return [] + return [e for e in self.entries if self.matches(e, pattern)] + + def matches(self, entry, pattern): + return pattern.lower() in entry.as_yaml().lower() class CommandLineAddressBook(cliapp.Application): @@ -69,13 +92,10 @@ class CommandLineAddressBook(cliapp.Application): book.add_from_database(database) return book - def format_entry(self, entry): - return yaml.safe_dump(entry) - def cmd_list(self, args): book = self.load_address_book() for entry in book.entries: - self.output.write(self.format_entry(entry) + '\n') + self.output.write(entry.as_yaml() + '\n') def cmd_mutt_query(self, args): if len(args) != 1: @@ -87,11 +107,12 @@ class CommandLineAddressBook(cliapp.Application): if not entries: self.output.write('No matches\n') sys.exit(1) - self.output.write('%d matching:\n' % len(entries)) + self.output.write('clab found matches:\n') for entry in entries: name = entry.get_single('name', '') - for email in entry.get_list('email'): - self.output.write('%s\t%s\n' % (email, name)) + emails = entry.get_subdict('email') + for email in emails: + self.output.write('%s\t%s\n' % (emails[email], name)) CommandLineAddressBook().run() -- cgit v1.2.1