Simplified exporting logic

This commit is contained in:
Manuel Ebert 2013-07-17 18:19:14 +02:00
parent 4d681ca095
commit b0c79d4b3b
2 changed files with 47 additions and 88 deletions

View file

@ -32,24 +32,16 @@ def to_tag_list(journal):
result += "\n".join(u"{0:20} : {1}".format(tag, n) for n, tag in sorted(tag_counts, reverse=False)) result += "\n".join(u"{0:20} : {1}".format(tag, n) for n, tag in sorted(tag_counts, reverse=False))
return result return result
def to_json(journal, output): def to_json(journal):
"""Returns a JSON representation of the Journal.""" """Returns a JSON representation of the Journal."""
tags = get_tags_count(journal) tags = get_tags_count(journal)
result = { result = {
"tags": dict((tag, count) for count, tag in tags), "tags": dict((tag, count) for count, tag in tags),
"entries": [e.to_dict() for e in journal.entries] "entries": [e.to_dict() for e in journal.entries]
} }
if output is not False:
path = output_path('json', output)
if not is_globable(path):
message = write_file(json.dumps(result, indent=2), path)
else:
message = to_files(journal, path)
return message
else:
return json.dumps(result, indent=2) return json.dumps(result, indent=2)
def to_md(journal, output): def to_md(journal):
"""Returns a markdown representation of the Journal""" """Returns a markdown representation of the Journal"""
out = [] out = []
year, month = -1, -1 year, month = -1, -1
@ -64,79 +56,52 @@ def to_md(journal, output):
out.append('-' * len(e.date.strftime("%B")) + "\n") out.append('-' * len(e.date.strftime("%B")) + "\n")
out.append(e.to_md()) out.append(e.to_md())
result = "\n".join(out) result = "\n".join(out)
if output is not False:
path = output_path('md', output)
if not is_globable(path):
message = write_file(result, path)
else:
message = to_files(journal, path)
return message
else:
return result return result
def to_txt(journal, output): def to_txt(journal):
"""Returns the complete text of the Journal.""" """Returns the complete text of the Journal."""
if output is not False:
path = output_path('txt', output)
if not is_globable(path):
message = write_file(unicode(journal), path)
else:
message = to_files(journal, path)
return message
else:
return unicode(journal) return unicode(journal)
def to_files(journal, output): def export(journal, format, output=None):
"""Turns your journal into separate files for each entry.""" """Exports the journal to various formats.
path, extension = os.path.splitext(os.path.expanduser(output)) format should be one of json, txt, text, md, markdown.
If output is None, returns a unicode representation of the output.
for e in journal.entries: If output is a directory, exports entries into individual files.
content = "" Otherwise, exports to the given output file.
date = e.date.strftime('%C-%m-%d') """
title = slugify(unicode(e.title)) maps = {
"json": to_json,
filename = string.replace(path, "%C-%m-%d", date) "txt": to_txt,
filename = string.replace(filename, "slug", title) "text": to_txt,
"md": to_md,
fullpath = filename + extension "markdown": to_md
}
if extension == '.json': if output and os.path.isdir(output): # multiple files
content = json.dumps(e.to_dict(), indent=2) return write_files(journal, output, format)
elif extension == '.md':
content = e.to_md()
elif extension == '.txt':
content = unicode(e)
write_file(content, fullpath)
return ("Journal exported.")
def is_globable(output):
path, extension = os.path.splitext(os.path.expanduser(output))
head, tail = os.path.split(path)
if tail == "%C-%m-%d_slug":
return True
else: else:
return False content = maps[format](journal)
if output:
def output_path(file_ext, output): try:
path, extension = os.path.splitext(os.path.expanduser(output)) with open(output, 'w') as f:
head, tail = os.path.split(path)
if head != '':
if not os.path.exists(head): # if the folder doesn't exist, create it
os.makedirs(head)
fullpath = head + '/' + tail + '.' + file_ext
else:
fullpath = tail + '.' + file_ext
return fullpath
def write_file(content, path):
"""Writes content to the file provided"""
f = open(path, 'w+')
f.write(content) f.write(content)
f.close() return "[Journal exported to {}]".format(output)
except IOError as e:
return "[ERROR: {} {}]".format(e.filename, e.strerror)
else:
return content
return ("File exported to " + path) def write_files(journal, path, format):
"""Turns your journal into separate files for each entry.
Format should be either json, md or txt."""
make_filename = lambda entry: e.date.strftime("%C-%m-%d_{}.{}".format(slugify(unicode(e.title)), format))
for e in journal.entries:
full_path = os.path.join(path, make_filename(e))
if format == 'json':
content = json.dumps(e.to_dict(), indent=2) + "\n"
elif format == 'md':
content = e.to_md()
elif format == 'txt':
content = unicode(e)
with open(full_path, 'w') as f:
f.write(content)
return "[Journal exported individual files in {}]".format(path)

View file

@ -190,14 +190,8 @@ def cli():
elif args.tags: elif args.tags:
print(exporters.to_tag_list(journal)) print(exporters.to_tag_list(journal))
elif args.export == 'json': # export to json elif args.export is not False:
print(exporters.to_json(journal, args.output)) print(exporters.export(journal, args.export, args.output))
elif args.export == 'markdown' or args.export == 'md': # export to markdown
print(exporters.to_md(journal, args.output))
elif args.export == 'text' or args.export == 'txt': # export to text
print(exporters.to_txt(journal, args.output))
elif (args.encrypt is not False or args.decrypt is not False) and not PYCRYPTO: elif (args.encrypt is not False or args.decrypt is not False) and not PYCRYPTO:
print("PyCrypto not found. To encrypt or decrypt your journal, install the PyCrypto package from http://www.pycrypto.org.") print("PyCrypto not found. To encrypt or decrypt your journal, install the PyCrypto package from http://www.pycrypto.org.")