Properly initialise journal files after creating them

This commit is contained in:
Manuel Ebert 2015-04-04 18:58:33 +11:00
parent cc85d905ca
commit df82ad1f4d
4 changed files with 36 additions and 16 deletions

View file

@ -50,3 +50,10 @@ class EncryptedJournal(Journal.Journal):
journal = Fernet(key).encrypt(text.encode('utf-8')) journal = Fernet(key).encrypt(text.encode('utf-8'))
with open(filename, 'w') as f: with open(filename, 'w') as f:
f.write(journal) 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)

View file

@ -58,6 +58,10 @@ class Journal(object):
def _store(self, filename, text): def _store(self, filename, text):
raise NotImplementedError raise NotImplementedError
@classmethod
def _create(cls, filename):
raise NotImplementedError
def _parse(self, journal_txt): def _parse(self, journal_txt):
"""Parses a journal that's stored in a string and returns a list of entries""" """Parses a journal that's stored in a string and returns a list of entries"""
@ -85,7 +89,7 @@ class Journal(object):
else: else:
starred = False 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: except ValueError:
# Happens when we can't parse the start of the line as an date. # Happens when we can't parse the start of the line as an date.
# In this case, just append line to our body. # In this case, just append line to our body.
@ -114,9 +118,11 @@ class Journal(object):
lambda match: util.colorize(match.group(0)), lambda match: util.colorize(match.group(0)),
pp, re.UNICODE) pp, re.UNICODE)
else: else:
pp = re.sub( Entry.Entry.tag_regex(self.config['tagsymbols']), pp = re.sub(
lambda match: util.colorize(match.group(0)), Entry.Entry.tag_regex(self.config['tagsymbols']),
pp) lambda match: util.colorize(match.group(0)),
pp
)
return pp return pp
def __repr__(self): def __repr__(self):
@ -164,7 +170,7 @@ class Journal(object):
matches = [m for m in re.finditer(tag, e.body)] matches = [m for m in re.finditer(tag, e.body)]
for m in matches: for m in matches:
date = e.date.strftime(self.config['timeformat']) 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)) res.append('{0} {1} ..'.format(date, excerpt))
e.body = "\n".join(res) e.body = "\n".join(res)
else: else:
@ -187,7 +193,7 @@ class Journal(object):
starred = "*" in title[:title.find(": ")] starred = "*" in title[:title.find(": ")]
date = time.parse(title[:title.find(": ")], default_hour=self.config['default_hour'], default_minute=self.config['default_minute']) 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 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("*"): elif title.strip().startswith("*"):
starred = True starred = True
title = title[1:].strip() title = title[1:].strip()
@ -223,6 +229,11 @@ class PlainJournal(Journal):
def __init__(self, name='default', **kwargs): def __init__(self, name='default', **kwargs):
super(PlainJournal, self).__init__(name, **kwargs) super(PlainJournal, self).__init__(name, **kwargs)
@classmethod
def _create(cls, filename):
with codecs.open(filename, "a", "utf-8"):
pass
def _load(self, filename): def _load(self, filename):
with codecs.open(filename, "r", "utf-8") as f: with codecs.open(filename, "r", "utf-8") as f:
return f.read() return f.read()

View file

@ -105,9 +105,8 @@ def decrypt(journal, filename=None):
def touch_journal(filename): def touch_journal(filename):
"""If filename does not exist, touch the file""" """If filename does not exist, touch the file"""
if not os.path.exists(filename): if not os.path.exists(filename):
log.debug('Creating journal file %s', filename)
util.prompt("[Journal created at {0}]".format(filename)) util.prompt("[Journal created at {0}]".format(filename))
open(filename, 'a').close() Journal.PlainJournal._create(filename)
def list_journals(config): def list_journals(config):

View file

@ -10,6 +10,8 @@ import xdg.BaseDirectory
from . import util from . import util
from . import upgrade from . import upgrade
from . import __version__ from . import __version__
from .Journal import PlainJournal
from .EncryptedJournal import EncryptedJournal
import yaml import yaml
import logging import logging
@ -104,6 +106,12 @@ def install():
journal_path = util.py23_input(path_query).strip() or JOURNAL_FILE_PATH journal_path = util.py23_input(path_query).strip() or JOURNAL_FILE_PATH
default_config['journals']['default'] = os.path.expanduser(os.path.expandvars(journal_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? # Encrypt it?
password = getpass.getpass("Enter password for journal (leave blank for no encryption): ") password = getpass.getpass("Enter password for journal (leave blank for no encryption): ")
if password: if password:
@ -112,15 +120,10 @@ def install():
util.set_keychain("default", password) util.set_keychain("default", password)
else: else:
util.set_keychain("default", None) util.set_keychain("default", None)
EncryptedJournal._create(default_config['journals']['default'], password)
print("Journal will be encrypted.") print("Journal will be encrypted.")
else:
path = os.path.split(default_config['journals']['default'])[0] # If the folder doesn't exist, create it PlainJournal._create(default_config['journals']['default'])
try:
os.makedirs(path)
except OSError:
pass
open(default_config['journals']['default'], 'a').close() # Touch to make sure it's there
config = default_config config = default_config
save_config(config) save_config(config)