Source code for dispass.labelfile
# Copyright (c) 2011-2012 Benjamin Althues <benjamin@babab.nl>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
import datetime
from os.path import expanduser
from dispass import versionStr
[docs]class FileHandler:
'''Parsing of labelfiles and writing to labelfiles'''
default_length = 30
'''Default passphrase length'''
default_hashname = 'dispass1'
'''Name of hash to use by default'''
filehandle = None
'''File object, set on init if labelfile is found'''
file_found = None
'''Boolean value set on init'''
file_location = None
'''String of labelfile location, set on init'''
file_stripped = []
'''Labelfile contents with comments and blank lines removed'''
labels = None
'''Dict of `{label: length}`'''
def __init__(self, write=False, file_location='~/.dispass'):
'''Open file; if file is found: strip comments and parse()'''
self.file_location = file_location
try:
if write:
self.filehandle = open(expanduser(file_location), 'r+')
else:
self.filehandle = open(expanduser(file_location), 'r')
self.file_found = True
except IOError:
self.file_found = False
return
# Strip comments and blank lines
for i in self.filehandle:
if i[0] != '\n' and i[0] != '#':
self.file_stripped.append(i)
if self.file_found:
if not write:
self.close()
self.parse()
[docs] def parse(self):
'''Create dictionary of ``labels = {label: length, ...}``'''
labels = []
labels_dispass1 = []
for i in self.file_stripped:
wordlist = []
line = i.rsplit(' ')
for word in line:
if word != '':
wordlist.append(word.strip('\n'))
labels.append(wordlist)
for line in labels:
labelname = line.pop(0)
length = self.default_length
hashname = self.default_hashname
for arg in line:
if 'length=' in arg:
try:
length = int(arg.strip('length='))
except ValueError:
print "Warning: Invalid length in: '%s'" % line
elif 'hash=' in arg:
hashname = arg.strip('hash=')
if hashname == 'dispass1':
labels_dispass1.append((labelname, length))
self.labels = dict(labels_dispass1)
return self
def write(self, labels=None):
if isinstance(labels, dict):
self.labels = labels
if self.labels:
label_list = []
for label, length in self.labels.iteritems():
label_list.append(label)
divlen = len(max(label_list, key=len)) + 2
config = '# Generated by %s on %s\n\n' % \
(versionStr, datetime.datetime.now())
for label, length in self.labels.iteritems():
config += '{:{fill}} length={}\n'.format(label, length,
fill=divlen)
self.filehandle.write(config)
self.filehandle.close()
return True
else:
return False
def close(self):
if self.filehandle:
self.filehandle.close()
if __name__ == '__main__':
fh = FileHandler(write=True)
if fh.file_found:
if fh.write():
print 'Saved to %s' % fh.file_location
else:
print 'No labels found'
else:
print 'Labelfile not found'