Coding style changes. API rename. Use 'macro' DELIM.

This commit is contained in:
Arun Prakash Jana 2016-10-29 16:06:29 +05:30
parent 2424836ea5
commit cb2db62496

127
buku
View File

@ -46,7 +46,7 @@ description = None # Description of the bookmark
tagsearch = False # Search bookmarks by tag
title_data = None # Title fetched from a webpage
interrupted = False # Received SIGINT
DELIMITER = ',' # Delimiter used to store tags in DB
DELIM = ',' # Delimiter used to store tags in DB
_VERSION_ = '2.5' # Program version
# Crypto globals
@ -199,8 +199,7 @@ class BukuCrypt:
elif len(chunk) % 16 != 0:
chunk = '%s%s' % (chunk, ' ' * (16 - len(chunk) % 16))
outfp.write(encryptor.update(chunk) +
encryptor.finalize())
outfp.write(encryptor.update(chunk) + encryptor.finalize())
os.remove(dbpath)
print('File encrypted')
@ -246,8 +245,7 @@ class BukuCrypt:
sys.exit(1)
with open(encpath, 'rb') as infp:
origsize = struct.unpack('<Q',
infp.read(struct.calcsize('Q')))[0]
origsize = struct.unpack('<Q', infp.read(struct.calcsize('Q')))[0]
# Read 256-bit salt and generate key
salt = infp.read(32)
@ -272,8 +270,7 @@ class BukuCrypt:
if len(chunk) == 0:
break
outfp.write(decryptor.update(chunk) +
decryptor.finalize())
outfp.write(decryptor.update(chunk) + decryptor.finalize())
outfp.truncate(origsize)
@ -467,12 +464,12 @@ class BukuDb:
# Process tags
if tags_in is None:
tags_in = DELIMITER
tags_in = DELIM
else:
if tags_in[0] != DELIMITER:
tags_in = '%s%s' % (DELIMITER, tags_in)
if tags_in[-1] != DELIMITER:
tags_in = '%s%s' % (tags_in, DELIMITER)
if tags_in[0] != DELIM:
tags_in = '%s%s' % (DELIM, tags_in)
if tags_in[-1] != DELIM:
tags_in = '%s%s' % (tags_in, DELIM)
# Process description
if desc is None:
@ -532,7 +529,7 @@ class BukuDb:
:return: True on success, False on failure
'''
tags_to_delete = tags_in.strip(DELIMITER).split(DELIMITER)
tags_to_delete = tags_in.strip(DELIM).split(DELIM)
if index == 0:
resp = input('Delete specified tags from ALL bookmarks? (y/n): ')
@ -543,15 +540,13 @@ class BukuDb:
LIKE '%' || ? || '%' ORDER BY id ASC"
query2 = 'UPDATE bookmarks SET tags = ? WHERE id = ?'
for tag in tags_to_delete:
self.cur.execute(query1, (DELIMITER + tag + DELIMITER,))
self.cur.execute(query1, (DELIM + tag + DELIM,))
resultset = self.cur.fetchall()
for row in resultset:
tags = row[1]
tags = tags.replace('%s%s%s'
% (DELIMITER, tag, DELIMITER,),
DELIMITER)
tags = tags.replace('%s%s%s' % (DELIM, tag, DELIM,), DELIM)
self.cur.execute(query2, (parse_tags([tags]), row[0],))
if verbose:
self.print_bookmark(row[0])
@ -568,17 +563,16 @@ class BukuDb:
tags = row[1]
for tag in tags_to_delete:
tags = tags.replace('%s%s%s' % (DELIMITER, tag,
DELIMITER,), DELIMITER)
tags = tags.replace('%s%s%s' % (DELIM, tag, DELIM,), DELIM)
self.cur.execute(query, (parse_tags([tags]), row[0],))
self.conn.commit()
return True
def update_bookmark(self, index, url='', title_in=None,
tags_in=None, desc=None, append_tag=False,
delete_tag=False, verbose=True):
def update_bookmark(self, index, url='', title_in=None, tags_in=None,
desc=None, append_tag=False, delete_tag=False,
verbose=True):
'''Update an existing record at index
Update all records if index is 0 and url is not specified.
URL is an exception because URLs are unique in DB.
@ -741,8 +735,8 @@ class BukuDb:
else:
query = '%s (tags LIKE (%s) OR URL LIKE (%s) OR metadata \
LIKE (%s) OR desc LIKE (%s)) AND' \
% (query, placeholder, placeholder,
placeholder, placeholder)
% (query, placeholder, placeholder, placeholder,
placeholder)
arguments += (token, token, token, token)
query = query[:-4]
@ -756,10 +750,11 @@ class BukuDb:
else:
query = '%s tags LIKE (%s) OR URL LIKE (%s) OR metadata \
LIKE (%s) OR desc LIKE (%s) OR' \
% (query, placeholder, placeholder,
placeholder, placeholder)
% (query, placeholder, placeholder, placeholder,
placeholder)
arguments += (token, token, token, token)
query = query[:-3]
query = '%s ORDER BY id ASC' % query
@ -936,7 +931,7 @@ class BukuDb:
resultset = self.cur.fetchall()
else:
qry = "SELECT * FROM bookmarks WHERE metadata = '' OR tags = ?"
self.cur.execute(qry, (DELIMITER,))
self.cur.execute(qry, (DELIM,))
resultset = self.cur.fetchall()
print('\x1b[1m%s records found\x1b[21m\n' % len(resultset))
@ -988,7 +983,7 @@ class BukuDb:
unique_tags = []
query = 'SELECT DISTINCT tags FROM bookmarks ORDER BY tags'
for row in self.cur.execute(query):
tagset = row[0].strip(DELIMITER).split(DELIMITER)
tagset = row[0].strip(DELIM).split(DELIM)
for tag in tagset:
if tag not in tags:
tags += (tag,)
@ -1012,14 +1007,14 @@ class BukuDb:
update = False
delete = False
newtags = DELIMITER
newtags = DELIM
orig = '%s%s%s' % (DELIMITER, orig, DELIMITER)
orig = '%s%s%s' % (DELIM, orig, DELIM)
if new is None:
delete = True
else:
newtags = parse_tags(new)
if newtags == DELIMITER:
if newtags == DELIM:
delete = True
if orig == newtags:
@ -1035,7 +1030,7 @@ class BukuDb:
if not delete:
# Check if tag newtags is already added
if row[1].find(newtags) >= 0:
newtags = DELIMITER
newtags = DELIM
tags = row[1].replace(orig, newtags)
tags = parse_tags([tags])
@ -1080,9 +1075,8 @@ class BukuDb:
return False
def export_bookmark(self, filepath, markdown=False, taglist=None):
'''Export bookmarks to a Firefox
bookmarks formatted html file.
def exportdb(self, filepath, markdown=False, taglist=None):
'''Export bookmarks to a Firefox bookmarks formatted html file.
:param filepath: path to file to export to
:param markdown: use markdown syntax
@ -1101,18 +1095,18 @@ class BukuDb:
if taglist is not None:
tagstr = parse_tags(taglist)
if len(tagstr) == 0 or tagstr == DELIMITER:
if len(tagstr) == 0 or tagstr == DELIM:
logger.error('Invalid tag')
return False
if len(tagstr) > 0:
tags = tagstr.split(DELIMITER)
tags = tagstr.split(DELIM)
query = '%s WHERE' % query
for tag in tags:
if tag != '':
is_tag_valid = True
query += " tags LIKE '%' || ? || '%' OR"
tag = '%s%s%s' % (DELIMITER, tag, DELIMITER)
tag = '%s%s%s' % (DELIM, tag, DELIM)
arguments += (tag,)
if is_tag_valid:
@ -1152,9 +1146,9 @@ class BukuDb:
''' % (timestamp, timestamp))
for row in resultset:
out = ' <DT><A HREF="%s" ADD_DATE="%s" LAST_MODIFIED="%s"' \
% (row[1], timestamp, timestamp)
if row[3] != DELIMITER:
out = '%s<DT><A HREF="%s" ADD_DATE="%s" LAST_MODIFIED="%s"' \
% (' ', row[1], timestamp, timestamp)
if row[3] != DELIM:
out = '%s TAGS="%s"' % (out, row[3][1:-1])
out = '%s>%s</A>\n' % (out, row[2])
if row[4] != '':
@ -1178,7 +1172,7 @@ class BukuDb:
print('%s exported' % count)
return True
def import_bookmark(self, filepath, markdown=False):
def importdb(self, filepath, markdown=False):
'''Import bookmarks from a html file.
Supports Firefox, Google Chrome and IE imports
@ -1208,7 +1202,7 @@ class BukuDb:
desc = comment_tag.text[0:comment_tag.text.find('\n')]
self.add_bookmark(tag['href'], tag.string, ('%s%s%s' %
(DELIMITER, tag['tags'], DELIMITER))
(DELIM, tag['tags'], DELIM))
if tag.has_attr('tags') else None,
desc, True)
@ -1239,10 +1233,10 @@ class BukuDb:
return True
def mergedb(self, filepath):
def mergedb(self, path):
'''Merge bookmarks from another Buku database file
:param filepath: path to file to merge
:param path: path to DB file to merge
:return: True on success, False on failure
'''
@ -1250,9 +1244,9 @@ class BukuDb:
# Connect to input DB
if sys.version_info >= (3, 4, 4):
# Python 3.4.4 and above
indb_conn = sqlite3.connect('file:%s?mode=ro' % filepath, uri=True)
indb_conn = sqlite3.connect('file:%s?mode=ro' % path, uri=True)
else:
indb_conn = sqlite3.connect(filepath)
indb_conn = sqlite3.connect(path)
indb_cur = indb_conn.cursor()
indb_cur.execute('SELECT * FROM bookmarks')
@ -1468,35 +1462,35 @@ def parse_tags(keywords=None):
if keywords is None:
return None
tags = DELIMITER
tags = DELIM
orig_tags = []
unique_tags = []
# Cleanse and get the tags
tagstr = ' '.join(keywords)
marker = tagstr.find(DELIMITER)
marker = tagstr.find(DELIM)
while marker >= 0:
token = tagstr[0:marker]
tagstr = tagstr[marker + 1:]
marker = tagstr.find(DELIMITER)
marker = tagstr.find(DELIM)
token = token.strip()
if token == '':
continue
tags = '%s%s%s' % (tags, token, DELIMITER)
tags = '%s%s%s' % (tags, token, DELIM)
tagstr = tagstr.strip()
if tagstr != '':
tags = '%s%s%s' % (tags, tagstr, DELIMITER)
tags = '%s%s%s' % (tags, tagstr, DELIM)
logger.debug('keywords: %s', keywords)
logger.debug('parsed tags: [%s]', tags)
if tags == DELIMITER:
if tags == DELIM:
return tags
orig_tags += tags.strip(DELIMITER).split(DELIMITER)
orig_tags += tags.strip(DELIM).split(DELIM)
for tag in orig_tags:
if tag not in unique_tags:
unique_tags += (tag, ) # Select unique tags
@ -1505,7 +1499,7 @@ def parse_tags(keywords=None):
sorted_tags = sorted(unique_tags, key=str.lower)
# Wrap with delimiter
return '%s%s%s' % (DELIMITER, DELIMITER.join(sorted_tags), DELIMITER)
return '%s%s%s' % (DELIM, DELIM.join(sorted_tags), DELIM)
def prompt(results, noninteractive=False):
@ -1595,8 +1589,8 @@ def print_record(row, idx=0):
if row[4] != '':
pr = '%s \x1B[91m+\x1B[0m %s\n' % (pr, row[4])
# Append tags IF not default (DELIMITER)
if row[3] != DELIMITER:
# Append tags IF not default (delimiter)
if row[3] != DELIM:
pr = '%s \x1B[91m#\x1B[0m %s\n' % (pr, row[3][1:-1])
print(pr)
@ -1746,7 +1740,7 @@ class CustomTagAction(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
global tags_in
tags_in = [DELIMITER, ]
tags_in = [DELIM, ]
setattr(args, self.dest, values)
@ -2021,7 +2015,7 @@ if __name__ == '__main__':
# Add a record
if args.addurl is not None:
# Parse tags into a comma-separated string
tags = DELIMITER
tags = DELIM
keywords = args.addurl
if tags_in is not None:
if tags_in[0] == '+' and len(tags_in) == 1:
@ -2029,10 +2023,10 @@ if __name__ == '__main__':
elif tags_in[0] == '+':
tags_in = tags_in[1:]
# In case of add, args.addurl may have URL followed by tags
# Add DELIMITER as url+tags may not end with comma
keywords = args.addurl + [DELIMITER] + tags_in
# Add delimiter as url+tags may not end with one
keywords = args.addurl + [DELIM] + tags_in
else:
keywords = args.addurl + [DELIMITER] + tags_in
keywords = args.addurl + [DELIM] + tags_in
if len(keywords) > 1:
tags = parse_tags(keywords[1:])
@ -2114,8 +2108,7 @@ if __name__ == '__main__':
elif tagsearch:
search_opted = True
if len(args.stag) > 0:
tag = '%s%s%s' % (DELIMITER, ' '.join(args.stag).strip(DELIMITER),
DELIMITER)
tag = '%s%s%s' % (DELIM, ' '.join(args.stag).strip(DELIM), DELIM)
search_results = bdb.search_by_tag(tag)
else:
bdb.list_tags()
@ -2198,15 +2191,15 @@ if __name__ == '__main__':
# Export bookmarks
if args.export is not None:
if args.tag is None:
bdb.export_bookmark(args.export[0], args.markdown)
bdb.exportdb(args.export[0], args.markdown)
elif len(args.tag) == 0:
logger.error('Missing tag')
else:
bdb.export_bookmark(args.export[0], args.markdown, args.tag)
bdb.exportdb(args.export[0], args.markdown, args.tag)
# Import bookmarks
if args.imports is not None:
bdb.import_bookmark(args.imports[0], args.markdown)
bdb.importdb(args.imports[0], args.markdown)
# Merge a database file and exit
if args.merge is not None: