Merge pull request #77 from jpralves/master

Add support for markdown file import/export
This commit is contained in:
Arun Prakash Jana 2016-10-22 10:49:57 +05:30 committed by GitHub
commit 5d68c2cac9
5 changed files with 70 additions and 38 deletions

View File

@ -184,6 +184,7 @@ Shell completion scripts for Bash, Fish and Zsh can be found in respective subdi
-r, --replace oldtag [newtag ...]
replace oldtag with newtag everywhere
delete oldtag, if no newtag
--markdown import/exports files from/to markdown format
-j, --json Json formatted output for -p, -s, -S, --st
--noprompt do not show the prompt, run and exit
-o, --open [N] open bookmark at DB index N in web browser
@ -396,6 +397,11 @@ The same number of iterations must be specified for one lock & unlock instance.
$ buku
$ man buku
27. Export bookmarks into markdown format tagged `tag 1` or `tag 2`:
$ buku --markdown -e bookmarks.md tag 1, tag 2
## Contributions
Pull requests are welcome. Please visit [#39](https://github.com/jarun/Buku/issues/39) for a list of TODOs.

View File

@ -12,7 +12,7 @@ _buku () {
local -a opts opts_with_args
opts=(-a --add -c --comment --deep -d --delete -e --export -h --help -i --import
-k --unlock -l --lock -m --merge --noprompt -o --open -p --print -r --replace
-s --sany -S --sall --st --stag --tag -t --title -u --update --url)
-s --sany -S --sall --st --stag --tag -t --title -u --update --url --markdown)
opts_with_arg=(-a --add -e --export -i --import -m --merge
-o --open -r --replace -s --sany -S --sall --url)

View File

@ -11,6 +11,7 @@ complete -c buku -s d -l delete --description 'delete bookmark'
complete -c buku -s e -l export -r --description 'export bookmarks'
complete -c buku -s h -l help --description 'show help'
complete -c buku -s i -l import -r --description 'import bookmarks'
complete -c buku -l markdown --description 'markdown mode'
complete -c buku -s k -l unlock --description 'decrypt database'
complete -c buku -s l -l lock --description 'encrypt database'
complete -c buku -s m -l merge -r --description 'merge another buku database'

View File

@ -20,6 +20,7 @@ args=(
'(-l --lock)'{-l,--lock}'[encrypt database]'
'(--merge)--merge[merge another buku database]:buku db file'
'(--noprompt)--noprompt[noninteractive mode]'
'(--markdown)--markdown[markdown mode]'
'(-o --open)'{-o,--open}'[open bookmark in browser]:bookmark index'
'(-p --print)'{-p,--print}'[show bookmark details]'
'(-r --replace)'{-r,--replace}'[replace a tag]:tag to replace'

98
buku
View File

@ -45,6 +45,7 @@ description = None # Description of the bookmark
tagsearch = False # Search bookmarks by tag
titleData = None # Title fetched from a webpage
interrupted = False # Received SIGINT
markdownFormat = False # Support import/export to markdown format
DELIMITER = ',' # Delimiter used to store tags in DB
_VERSION_ = '2.5' # Program version
@ -1034,7 +1035,8 @@ class BukuDb:
logger.error(e)
return
f.write('''<!DOCTYPE NETSCAPE-Bookmark-file-1>
if not markdownFormat:
f.write('''<!DOCTYPE NETSCAPE-Bookmark-file-1>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
<TITLE>Bookmarks</TITLE>
@ -1045,19 +1047,25 @@ class BukuDb:
<DL><p>
''' % (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 TAGS="%s"' % (out, row[3][1:-1])
out = '%s>%s</A>\n' % (out, row[2])
if row[4] != '':
out = '%s <DD>%s\n' % (out, row[4])
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 TAGS="%s"' % (out, row[3][1:-1])
out = '%s>%s</A>\n' % (out, row[2])
if row[4] != '':
out = '%s <DD>%s\n' % (out, row[4])
f.write(out)
count += 1
f.write(out)
count += 1
f.write(' </DL><p>\n</DL><p>')
f.write(' </DL><p>\n</DL><p>')
else:
f.write("List of buku bookmarks:\n\n")
for row in resultset:
out = '- [%s](%s)\n' % (row[2], row[1])
f.write(out)
count += 1
f.close()
print('%s bookmarks exported' % count)
@ -1068,32 +1076,43 @@ class BukuDb:
Params: Path to file to import
'''
try:
import bs4
if not markdownFormat:
try:
import bs4
with open(fp, mode='r', encoding='utf-8') as f:
soup = bs4.BeautifulSoup(f, 'html.parser')
except ImportError:
logger.error('Beautiful Soup not found')
return
except Exception as e:
logger.error(e)
return
html_tags = soup.findAll('a')
for tag in html_tags:
# Extract comment from <dd> tag
desc = None
comment_tag = tag.findNextSibling('dd')
if comment_tag:
desc = comment_tag.text[0:comment_tag.text.find('\n')]
self.add_bookmark(tag['href'], tag.string,
('%s%s%s' % (DELIMITER, tag['tags'], DELIMITER))
if tag.has_attr('tags') else None, desc, True)
self.conn.commit()
f.close()
else:
with open(fp, mode='r', encoding='utf-8') as f:
soup = bs4.BeautifulSoup(f, 'html.parser')
except ImportError:
logger.error('Beautiful Soup not found')
return
except Exception as e:
logger.error(e)
return
html_tags = soup.findAll('a')
for tag in html_tags:
# Extract comment from <dd> tag
desc = None
comment_tag = tag.findNextSibling('dd')
if comment_tag:
desc = comment_tag.text[0:comment_tag.text.find('\n')]
self.add_bookmark(tag['href'], tag.string,
('%s%s%s' % (DELIMITER, tag['tags'], DELIMITER))
if tag.has_attr('tags') else None, desc, True)
self.conn.commit()
f.close()
reg = re.compile("\[([^\]]+)\]\(([^\)]+)\)")
for line in f:
m = reg.search(line)
if m:
desc = m.group(1)
self.add_bookmark(m.group(2), None, None, desc, True)
self.conn.commit()
f.close()
def mergedb(self, fp):
'''Merge bookmarks from another Buku database file
@ -1771,6 +1790,7 @@ if __name__ == '__main__':
-r, --replace oldtag [newtag ...]
replace oldtag with newtag everywhere
delete oldtag, if no newtag
--markdown import/exports files from/to markdown format
-j, --json Json formatted output for -p, -s, -S, --st
--noprompt do not show the prompt, run and exit
-o, --open [N] open bookmark at DB index N in web browser
@ -1789,6 +1809,8 @@ if __name__ == '__main__':
choices=[1, 2, 3], metavar='N', help=argparse.SUPPRESS)
addarg('-r', '--replace', nargs='+', dest='replace',
metavar=('oldtag', 'newtag'), help=argparse.SUPPRESS)
addarg('--markdown', dest='markdown', action='store_true',
help=argparse.SUPPRESS)
addarg('-j', '--json', dest='jsonOutput', action='store_true',
help=argparse.SUPPRESS)
addarg('--noprompt', dest='noninteractive', action='store_true',
@ -1820,6 +1842,8 @@ if __name__ == '__main__':
description = ' '.join(args.desc)
if args.jsonOutput:
import json
if args.markdown:
markdownFormat = True
if args.debug:
logger.setLevel(logging.DEBUG)
logger.debug('Version %s', _VERSION_)