Deleting the last entry

This commit is contained in:
Manuel Ebert 2013-11-30 14:55:37 -08:00
parent 490ba01a2e
commit abe586d84e
3 changed files with 57 additions and 24 deletions

View file

@ -54,6 +54,10 @@ class Journal(object):
self.entries = self.parse(journal_txt) self.entries = self.parse(journal_txt)
self.sort() self.sort()
def __len__(self):
"""Returns the number of entries"""
return len(self.entries)
def _colorize(self, string): def _colorize(self, string):
if colorama: if colorama:
return colorama.Fore.CYAN + string + colorama.Fore.RESET return colorama.Fore.CYAN + string + colorama.Fore.RESET
@ -184,7 +188,7 @@ class Journal(object):
def write(self, filename=None): def write(self, filename=None):
"""Dumps the journal into the config file, overwriting it""" """Dumps the journal into the config file, overwriting it"""
filename = filename or self.config['journal'] filename = filename or self.config['journal']
journal = "\n".join([e.__unicode__() for e in self.entries]) journal = u"\n".join([e.__unicode__() for e in self.entries])
if self.config['encrypt']: if self.config['encrypt']:
journal = self._encrypt(journal) journal = self._encrypt(journal)
with open(filename, 'wb') as journal_file: with open(filename, 'wb') as journal_file:

View file

@ -20,8 +20,6 @@ except (SystemError, ValueError):
import install import install
import jrnl import jrnl
import os import os
import tempfile
import subprocess
import argparse import argparse
import sys import sys
@ -51,7 +49,8 @@ def parse_args(args=None):
exporting.add_argument('-o', metavar='OUTPUT', dest='output', help='The output of the file can be provided when using with --export', default=False, const=None) exporting.add_argument('-o', metavar='OUTPUT', dest='output', help='The output of the file can be provided when using with --export', default=False, const=None)
exporting.add_argument('--encrypt', metavar='FILENAME', dest='encrypt', help='Encrypts your existing journal with a new password', nargs='?', default=False, const=None) exporting.add_argument('--encrypt', metavar='FILENAME', dest='encrypt', help='Encrypts your existing journal with a new password', nargs='?', default=False, const=None)
exporting.add_argument('--decrypt', metavar='FILENAME', dest='decrypt', help='Decrypts your journal and stores it in plain text', nargs='?', default=False, const=None) exporting.add_argument('--decrypt', metavar='FILENAME', dest='decrypt', help='Decrypts your journal and stores it in plain text', nargs='?', default=False, const=None)
exporting.add_argument('--delete-last', dest='delete_last', help='Deletes the last entry from your journal file.', action="store_true") exporting.add_argument('--delete', dest='delete', help='Deletes the selected entries your journal file.', action="store_true")
exporting.add_argument('--edit', dest='edit', help='Opens your editor to edit the selected entries.', action="store_true")
return parser.parse_args(args) return parser.parse_args(args)
@ -59,7 +58,7 @@ def guess_mode(args, config):
"""Guesses the mode (compose, read or export) from the given arguments""" """Guesses the mode (compose, read or export) from the given arguments"""
compose = True compose = True
export = False export = False
if args.decrypt is not False or args.encrypt is not False or args.export is not False or any((args.short, args.tags, args.delete_last)): if args.decrypt is not False or args.encrypt is not False or args.export is not False or any((args.short, args.tags, args.delete, args.edit)):
compose = False compose = False
export = True export = True
elif any((args.start_date, args.end_date, args.limit, args.strict, args.starred)): elif any((args.start_date, args.end_date, args.limit, args.strict, args.starred)):
@ -71,20 +70,6 @@ def guess_mode(args, config):
return compose, export return compose, export
def get_text_from_editor(config):
tmpfile = os.path.join(tempfile.gettempdir(), "jrnl")
subprocess.call(config['editor'].split() + [tmpfile])
if os.path.exists(tmpfile):
with open(tmpfile) as f:
raw = f.read()
os.remove(tmpfile)
else:
util.prompt('[Nothing saved to file]')
raw = ''
return raw
def encrypt(journal, filename=None): def encrypt(journal, filename=None):
""" Encrypt into new file. If filename is not set, we encrypt the journal file itself. """ """ Encrypt into new file. If filename is not set, we encrypt the journal file itself. """
password = util.getpass("Enter new password: ") password = util.getpass("Enter new password: ")
@ -176,7 +161,7 @@ def run(manual_args=None):
# Piping data into jrnl # Piping data into jrnl
raw = util.py23_read() raw = util.py23_read()
elif config['editor']: elif config['editor']:
raw = get_text_from_editor(config) raw = util.get_text_from_editor(config)
else: else:
raw = util.py23_read("[Compose Entry; " + _exit_multiline_code + " to finish writing]\n") raw = util.py23_read("[Compose Entry; " + _exit_multiline_code + " to finish writing]\n")
if raw: if raw:
@ -193,6 +178,7 @@ def run(manual_args=None):
util.prompt("[Entry added to {0} journal]".format(journal_name)) util.prompt("[Entry added to {0} journal]".format(journal_name))
journal.write() journal.write()
else: else:
old_entries = journal.entries
journal.filter(tags=args.text, journal.filter(tags=args.text,
start_date=args.start_date, end_date=args.end_date, start_date=args.start_date, end_date=args.end_date,
strict=args.strict, strict=args.strict,
@ -231,10 +217,34 @@ def run(manual_args=None):
update_config(original_config, {"encrypt": False}, journal_name, force_local=True) update_config(original_config, {"encrypt": False}, journal_name, force_local=True)
install.save_config(original_config, config_path=CONFIG_PATH) install.save_config(original_config, config_path=CONFIG_PATH)
elif args.delete_last: elif args.delete:
last_entry = journal.entries.pop() other_entries = [e for e in old_entries if e not in journal.entries]
util.prompt("[Deleted Entry:]") util.prompt("Following entries will be deleted:")
print(last_entry.pprint()) for e in journal.entries[:10]:
util.prompt(" "+e.pprint(short=True))
if len(journal) > 10:
q = "...and {0} more. Do you really want to delete these entries?".format(len(journal) - 10)
else:
q = "Do you really want to delete these entries?"
ok = util.yesno(q, default=False)
if ok:
util.prompt("[Deleted {0} entries]".format(len(journal)))
journal.entries = other_entries
journal.write()
elif args.edit:
other_entries = [e for e in old_entries if e not in journal.entries]
# Edit
old_num_entries = len(journal)
template = u"\n".join([e.__unicode__() for e in journal.entries])
edited = util.get_text_from_editor(config, template)
journal.entries = journal.parse(edited)
num_deleted = old_num_entries - len(journal)
if num_deleted:
util.prompt("[Deleted {0} entries]".format(num_deleted))
else:
util.prompt("[Edited {0} entries]".format(len(journal)))
journal.entries += other_entries
journal.write() journal.write()
if __name__ == "__main__": if __name__ == "__main__":

View file

@ -9,6 +9,9 @@ import pytz
try: import simplejson as json try: import simplejson as json
except ImportError: import json except ImportError: import json
import re import re
import tempfile
import subprocess
import codecs
PY3 = sys.version_info[0] == 3 PY3 = sys.version_info[0] == 3
PY2 = sys.version_info[0] == 2 PY2 = sys.version_info[0] == 2
@ -121,3 +124,19 @@ def load_and_fix_json(json_path):
prompt("[Entry was NOT added to your journal]") prompt("[Entry was NOT added to your journal]")
sys.exit(1) sys.exit(1)
def get_text_from_editor(config, template=""):
tmpfile = os.path.join(tempfile.gettempdir(), "jrnl")
if template:
with codecs.open(tmpfile, 'w', "utf-8") as f:
f.write(template)
subprocess.call(config['editor'].split() + [tmpfile])
if os.path.exists(tmpfile):
with codecs.open(tmpfile, "r", "utf-8") as f:
raw = f.read()
os.remove(tmpfile)
else:
prompt('[Nothing saved to file]')
raw = ''
return raw