From df82ad1f4d6125e00fbcc51d7fbb2ea3b3504368 Mon Sep 17 00:00:00 2001 From: Manuel Ebert Date: Sat, 4 Apr 2015 18:58:33 +1100 Subject: [PATCH] Properly initialise journal files after creating them --- jrnl/EncryptedJournal.py | 7 +++++++ jrnl/Journal.py | 23 +++++++++++++++++------ jrnl/cli.py | 3 +-- jrnl/install.py | 19 +++++++++++-------- 4 files changed, 36 insertions(+), 16 deletions(-) diff --git a/jrnl/EncryptedJournal.py b/jrnl/EncryptedJournal.py index 7f27e297..16821191 100644 --- a/jrnl/EncryptedJournal.py +++ b/jrnl/EncryptedJournal.py @@ -50,3 +50,10 @@ class EncryptedJournal(Journal.Journal): journal = Fernet(key).encrypt(text.encode('utf-8')) with open(filename, 'w') as f: f.write(journal) + + @classmethod + def _create(cls, filename, password): + key = make_key(password) + dummy = Fernet(key).encrypt("") + with open(filename, 'w') as f: + f.write(dummy) diff --git a/jrnl/Journal.py b/jrnl/Journal.py index a7b6521b..7371703c 100644 --- a/jrnl/Journal.py +++ b/jrnl/Journal.py @@ -58,6 +58,10 @@ class Journal(object): def _store(self, filename, text): raise NotImplementedError + @classmethod + def _create(cls, filename): + raise NotImplementedError + def _parse(self, journal_txt): """Parses a journal that's stored in a string and returns a list of entries""" @@ -85,7 +89,7 @@ class Journal(object): else: starred = False - current_entry = Entry.Entry(self, date=new_date, title=line[date_length+1:], starred=starred) + current_entry = Entry.Entry(self, date=new_date, title=line[date_length + 1:], starred=starred) except ValueError: # Happens when we can't parse the start of the line as an date. # In this case, just append line to our body. @@ -114,9 +118,11 @@ class Journal(object): lambda match: util.colorize(match.group(0)), pp, re.UNICODE) else: - pp = re.sub( Entry.Entry.tag_regex(self.config['tagsymbols']), - lambda match: util.colorize(match.group(0)), - pp) + pp = re.sub( + Entry.Entry.tag_regex(self.config['tagsymbols']), + lambda match: util.colorize(match.group(0)), + pp + ) return pp def __repr__(self): @@ -164,7 +170,7 @@ class Journal(object): matches = [m for m in re.finditer(tag, e.body)] for m in matches: date = e.date.strftime(self.config['timeformat']) - excerpt = e.body[m.start():min(len(e.body), m.end()+60)] + excerpt = e.body[m.start():min(len(e.body), m.end() + 60)] res.append('{0} {1} ..'.format(date, excerpt)) e.body = "\n".join(res) else: @@ -187,7 +193,7 @@ class Journal(object): starred = "*" in title[:title.find(": ")] date = time.parse(title[:title.find(": ")], default_hour=self.config['default_hour'], default_minute=self.config['default_minute']) if date or starred: # Parsed successfully, strip that from the raw text - title = title[title.find(": ")+1:].strip() + title = title[title.find(": ") + 1:].strip() elif title.strip().startswith("*"): starred = True title = title[1:].strip() @@ -223,6 +229,11 @@ class PlainJournal(Journal): def __init__(self, name='default', **kwargs): super(PlainJournal, self).__init__(name, **kwargs) + @classmethod + def _create(cls, filename): + with codecs.open(filename, "a", "utf-8"): + pass + def _load(self, filename): with codecs.open(filename, "r", "utf-8") as f: return f.read() diff --git a/jrnl/cli.py b/jrnl/cli.py index 7407f836..fbbdefec 100644 --- a/jrnl/cli.py +++ b/jrnl/cli.py @@ -105,9 +105,8 @@ def decrypt(journal, filename=None): def touch_journal(filename): """If filename does not exist, touch the file""" if not os.path.exists(filename): - log.debug('Creating journal file %s', filename) util.prompt("[Journal created at {0}]".format(filename)) - open(filename, 'a').close() + Journal.PlainJournal._create(filename) def list_journals(config): diff --git a/jrnl/install.py b/jrnl/install.py index 1ce0f211..550d9935 100644 --- a/jrnl/install.py +++ b/jrnl/install.py @@ -10,6 +10,8 @@ import xdg.BaseDirectory from . import util from . import upgrade from . import __version__ +from .Journal import PlainJournal +from .EncryptedJournal import EncryptedJournal import yaml import logging @@ -104,6 +106,12 @@ def install(): journal_path = util.py23_input(path_query).strip() or JOURNAL_FILE_PATH default_config['journals']['default'] = os.path.expanduser(os.path.expandvars(journal_path)) + path = os.path.split(default_config['journals']['default'])[0] # If the folder doesn't exist, create it + try: + os.makedirs(path) + except OSError: + pass + # Encrypt it? password = getpass.getpass("Enter password for journal (leave blank for no encryption): ") if password: @@ -112,15 +120,10 @@ def install(): util.set_keychain("default", password) else: util.set_keychain("default", None) + EncryptedJournal._create(default_config['journals']['default'], password) print("Journal will be encrypted.") - - path = os.path.split(default_config['journals']['default'])[0] # If the folder doesn't exist, create it - try: - os.makedirs(path) - except OSError: - pass - - open(default_config['journals']['default'], 'a').close() # Touch to make sure it's there + else: + PlainJournal._create(default_config['journals']['default']) config = default_config save_config(config)