#!/usr/bin/env python """Notes format parser.""" import sets class Note(list): """A class for holding a note.""" Date, Meta, Data = 0, 1, 2 def __init__(cls, date, meta, data): assert isinstance(meta, sets.Set) list.__init__(cls, (date, meta, data)) def __iadd__(self, items): self[Note.Meta] |= sets.Set(items) return self def __isub__(self, items): self[Note.Meta] -= sets.Set(items) return self class Notes(dict): """A class for holding parsed notes.""" def __init__(self, s=None): if s: self.feed(s) def __str__(self): return self.serialize() def feed(self, s): s = s.replace('\r\n', '\n') s = s.replace('\r', '\n') lines = s.splitlines() for (i, line) in enumerate(lines): line = line.lstrip() if line and not line.startswith('#'): date, meta, data = tuple(line.split('\t')) meta = [n for n in meta.split(' ') if n] self[i] = Note(date, sets.Set(meta), data) return True def serialize(self, format=None): if format is None: format = '%(date)s\t%(meta)s\t%(data)s\n' keys = self.keys() keys.sort() result = '' for key in keys: date, meta, data = tuple(self[key]) meta = ' '.join(meta) result += format % vars() return result def queryKeywords(self, *args): keywords = sets.Set(args) return [note for note in self.values() if keywords <= note[Note.Meta]] def tail(self, n=None): if n is None: n = 10 assert n > 0 keys = self.keys() keys.sort() keys = keys[-n:] result = Notes() for key in keys: result[key] = self[key] return result def dialogue(self): while 1: try: command = raw_input('>>> ') except (KeyboardInterrupt, EOFError): break if command == 'quit': break elif command in ('print', 'show', 'display', 'view', 'serialize'): print self elif command.startswith('tail'): command, n = command.split(' ') n = int(n) schema = '%(meta)s: %(data)s (%(date)s)\n' print self.tail(n).serialize(schema) else: print "Unknown command: %s" % command def test(): s = """ 2003-11-05T09:15:00+0000 scribbledygook 2003-11-08T13:19:17+0000 @@ update FOAF file with maker information 2003-11-10T04:50:34+0000 mount -t vfat -o [...] """ import time t = time.clock() n = Notes(s) # * 10000) print time.clock() - t print n print n.queryKeywords('@@') print n.queryKeywords('@@', 'project') note = n.queryKeywords('project')[0] note -= ['@@'] note += ['hmm'] print note print n.serialize() def mainTest(): s = """ 2003-11-05T09:15:00+0000 scribbledygook 2003-11-08T13:19:17+0000 @@ update FOAF file with maker information 2003-11-10T04:50:34+0000 mount -t vfat -o [...] """ notes = Notes(s) notes.dialogue() def main(): print __doc__ mainTest() # notes[i][Meta] |= sets.Set(['blargh']) # notes[i] -= ['todo'] # notes[i] += ['done', '2003-05-15'] if __name__=="__main__": main()