remove py2 remnants and use mocks in tests

fstring wip
Run pyupgrade
fix broken pyupgrade fstring
run pyupgrade on plugin dir
fixup! remove py2 remnants and use mocks in tests
small print bugfix
The file=sys.stderr was part of the format(), so an error got printed to
stdout
Drop use of codecs package
Use builtins.open() instead
fixup! remove py2 remnants and use mocks in tests
This commit is contained in:
Peter Schmidbauer 2019-10-31 21:12:55 +01:00
parent b7e2e91af3
commit 9d8d6a83ae
28 changed files with 211 additions and 321 deletions

View file

@ -1,13 +1,10 @@
#!/usr/bin/env python
# encoding: utf-8
from __future__ import absolute_import, unicode_literals
from . import Entry
from . import util
from . import time
import os
import sys
import codecs
import re
from datetime import datetime
import logging
@ -15,7 +12,7 @@ import logging
log = logging.getLogger(__name__)
class Tag(object):
class Tag:
def __init__(self, name, count=0):
self.name = name
self.count = count
@ -24,10 +21,10 @@ class Tag(object):
return self.name
def __repr__(self):
return "<Tag '{}'>".format(self.name)
return f"<Tag '{self.name}'>"
class Journal(object):
class Journal:
def __init__(self, name='default', **kwargs):
self.config = {
'journal': "journal.txt",
@ -72,7 +69,7 @@ class Journal(object):
filename = filename or self.config['journal']
if not os.path.exists(filename):
util.prompt("[Journal '{0}' created at {1}]".format(self.name, filename))
print(f"[Journal '{self.name}' created at {filename}]", file=sys.stderr)
self._create(filename)
text = self._load(filename)
@ -96,7 +93,7 @@ class Journal(object):
return True
def _to_text(self):
return "\n".join([e.__unicode__() for e in self.entries])
return "\n".join([str(e) for e in self.entries])
def _load(self, filename):
raise NotImplementedError
@ -118,7 +115,7 @@ class Journal(object):
# Initialise our current entry
entries = []
date_blob_re = re.compile("(?:^|\n)\[([^\\]]+)\] ")
date_blob_re = re.compile("(?:^|\n)\\[([^\\]]+)\\] ")
last_entry_pos = 0
for match in date_blob_re.finditer(journal_txt):
date_blob = match.groups()[0]
@ -140,9 +137,6 @@ class Journal(object):
entry._parse_text()
return entries
def __unicode__(self):
return self.pprint()
def pprint(self, short=False):
"""Prettyprints the journal's entries"""
sep = "\n"
@ -153,7 +147,7 @@ class Journal(object):
tagre = re.compile(re.escape(tag), re.IGNORECASE)
pp = re.sub(tagre,
lambda match: util.colorize(match.group(0)),
pp, re.UNICODE)
pp)
else:
pp = re.sub(
Entry.Entry.tag_regex(self.config['tagsymbols']),
@ -162,8 +156,11 @@ class Journal(object):
)
return pp
def __str__(self):
return self.pprint()
def __repr__(self):
return "<Journal with {0} entries>".format(len(self.entries))
return f"<Journal with {len(self.entries)} entries>"
def sort(self):
"""Sorts the Journal's entries by date"""
@ -183,7 +180,7 @@ class Journal(object):
for entry in self.entries
for tag in set(entry.tags)]
# To be read: [for entry in journal.entries: for tag in set(entry.tags): tag]
tag_counts = set([(tags.count(tag), tag) for tag in tags])
tag_counts = {(tags.count(tag), tag) for tag in tags}
return [Tag(tag, count=count) for count, tag in sorted(tag_counts)]
def filter(self, tags=[], start_date=None, end_date=None, starred=False, strict=False, short=False, exclude=[]):
@ -200,8 +197,8 @@ class Journal(object):
exclude is a list of the tags which should not appear in the results.
entry is kept if any tag is present, unless they appear in exclude."""
self.search_tags = set([tag.lower() for tag in tags])
excluded_tags = set([tag.lower() for tag in exclude])
self.search_tags = {tag.lower() for tag in tags}
excluded_tags = {tag.lower() for tag in exclude}
end_date = time.parse(end_date, inclusive=True)
start_date = time.parse(start_date)
@ -226,7 +223,7 @@ class Journal(object):
raw = raw.replace('\\n ', '\n').replace('\\n', '\n')
starred = False
# Split raw text into title and body
sep = re.search("\n|[\?!.]+ +\n?", raw)
sep = re.search(r"\n|[?!.]+ +\n?", raw)
first_line = raw[:sep.end()].strip() if sep else raw
starred = False
@ -254,7 +251,7 @@ class Journal(object):
def editable_str(self):
"""Turns the journal into a string of entries that can be edited
manually and later be parsed with eslf.parse_editable_str."""
return "\n".join([e.__unicode__() for e in self.entries])
return "\n".join([str(e) for e in self.entries])
def parse_editable_str(self, edited):
"""Parses the output of self.editable_str and updates it's entries."""
@ -270,15 +267,15 @@ class Journal(object):
class PlainJournal(Journal):
@classmethod
def _create(cls, filename):
with codecs.open(filename, "a", "utf-8"):
with open(filename, "a", encoding="utf-8"):
pass
def _load(self, filename):
with codecs.open(filename, "r", "utf-8") as f:
with open(filename, "r", encoding="utf-8") as f:
return f.read()
def _store(self, filename, text):
with codecs.open(filename, 'w', "utf-8") as f:
with open(filename, 'w', encoding="utf-8") as f:
f.write(text)
@ -287,7 +284,7 @@ class LegacyJournal(Journal):
standard. Main difference here is that in 1.x, timestamps were not cuddled
by square brackets. You'll not be able to save these journals anymore."""
def _load(self, filename):
with codecs.open(filename, "r", "utf-8") as f:
with open(filename, "r", encoding="utf-8") as f:
return f.read()
def _parse(self, journal_txt):
@ -323,7 +320,7 @@ class LegacyJournal(Journal):
# escaping for the new format).
line = new_date_format_regex.sub(r' \1', line)
if current_entry:
current_entry.text += line + u"\n"
current_entry.text += line + "\n"
# Append last entry
if current_entry:
@ -347,8 +344,9 @@ def open_journal(name, config, legacy=False):
from . import DayOneJournal
return DayOneJournal.DayOne(**config).open()
else:
util.prompt(
u"[Error: {0} is a directory, but doesn't seem to be a DayOne journal either.".format(config['journal'])
print(
f"[Error: {config['journal']} is a directory, but doesn't seem to be a DayOne journal either.",
file=sys.stderr
)
sys.exit(1)