Run pyupgrade

This commit is contained in:
Peter Schmidbauer 2019-11-01 11:16:12 +01:00
parent 1c403904e5
commit 30caf9cae2
12 changed files with 45 additions and 55 deletions

View file

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# encoding: utf-8
from . import Entry from . import Entry
from . import Journal from . import Journal
@ -25,7 +24,7 @@ class DayOne(Journal.Journal):
def __init__(self, **kwargs): def __init__(self, **kwargs):
self.entries = [] self.entries = []
self._deleted_entries = [] self._deleted_entries = []
super(DayOne, self).__init__(**kwargs) super().__init__(**kwargs)
def open(self): def open(self):
filenames = [os.path.join(self.config['journal'], "entries", f) for f in os.listdir(os.path.join(self.config['journal'], "entries"))] filenames = [os.path.join(self.config['journal'], "entries", f) for f in os.listdir(os.path.join(self.config['journal'], "entries"))]
@ -106,7 +105,7 @@ class DayOne(Journal.Journal):
current_entry.modified = False current_entry.modified = False
current_entry.uuid = m.group(1).lower() current_entry.uuid = m.group(1).lower()
else: else:
date_blob_re = re.compile("^\[[^\\]]+\] ") date_blob_re = re.compile("^\\[[^\\]]+\\] ")
date_blob = date_blob_re.findall(line) date_blob = date_blob_re.findall(line)
if date_blob: if date_blob:
date_blob = date_blob[0] date_blob = date_blob[0]

View file

@ -29,7 +29,7 @@ def make_key(password):
class EncryptedJournal(Journal.Journal): class EncryptedJournal(Journal.Journal):
def __init__(self, name='default', **kwargs): def __init__(self, name='default', **kwargs):
super(EncryptedJournal, self).__init__(name, **kwargs) super().__init__(name, **kwargs)
self.config['encrypt'] = True self.config['encrypt'] = True
def open(self, filename=None): def open(self, filename=None):
@ -47,7 +47,7 @@ class EncryptedJournal(Journal.Journal):
self.config['password'] = password self.config['password'] = password
text = "" text = ""
self._store(filename, text) self._store(filename, text)
print("[Journal '{0}' created at {1}]".format(self.name, filename), file=sys.stderr) print(f"[Journal '{self.name}' created at {filename}]", file=sys.stderr)
else: else:
print("No password supplied for encrypted journal", file=sys.stderr) print("No password supplied for encrypted journal", file=sys.stderr)
sys.exit(1) sys.exit(1)
@ -97,7 +97,7 @@ class LegacyEncryptedJournal(Journal.LegacyJournal):
"""Legacy class to support opening journals encrypted with the jrnl 1.x """Legacy class to support opening journals encrypted with the jrnl 1.x
standard. You'll not be able to save these journals anymore.""" standard. You'll not be able to save these journals anymore."""
def __init__(self, name='default', **kwargs): def __init__(self, name='default', **kwargs):
super(LegacyEncryptedJournal, self).__init__(name, **kwargs) super().__init__(name, **kwargs)
self.config['encrypt'] = True self.config['encrypt'] = True
def _load(self, filename, password=None): def _load(self, filename, password=None):

View file

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# encoding: utf-8
import re import re
import textwrap import textwrap
@ -50,12 +49,12 @@ class Entry:
@staticmethod @staticmethod
def tag_regex(tagsymbols): def tag_regex(tagsymbols):
pattern = r'(?u)(?:^|\s)([{tags}][-+*#/\w]+)'.format(tags=tagsymbols) pattern = fr'(?u)(?:^|\s)([{tagsymbols}][-+*#/\w]+)'
return re.compile(pattern) return re.compile(pattern)
def _parse_tags(self): def _parse_tags(self):
tagsymbols = self.journal.config['tagsymbols'] tagsymbols = self.journal.config['tagsymbols']
return set(tag.lower() for tag in re.findall(Entry.tag_regex(tagsymbols), self.text)) return {tag.lower() for tag in re.findall(Entry.tag_regex(tagsymbols), self.text)}
def __str__(self): def __str__(self):
"""Returns a string representation of the entry to be written into a journal file.""" """Returns a string representation of the entry to be written into a journal file."""
@ -105,7 +104,7 @@ class Entry:
) )
def __repr__(self): def __repr__(self):
return "<Entry '{0}' on {1}>".format(self.title.strip(), self.date.strftime("%Y-%m-%d %H:%M")) return "<Entry '{}' on {}>".format(self.title.strip(), self.date.strftime("%Y-%m-%d %H:%M"))
def __hash__(self): def __hash__(self):
return hash(self.__repr__()) return hash(self.__repr__())

View file

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# encoding: utf-8
from . import Entry from . import Entry
from . import util from . import util
@ -71,7 +70,7 @@ class Journal:
filename = filename or self.config['journal'] filename = filename or self.config['journal']
if not os.path.exists(filename): if not os.path.exists(filename):
print("[Journal '{0}' created at {1}]".format(self.name, filename), file=sys.stderr) print(f"[Journal '{self.name}' created at {filename}]", file=sys.stderr)
self._create(filename) self._create(filename)
text = self._load(filename) text = self._load(filename)
@ -117,7 +116,7 @@ class Journal:
# Initialise our current entry # Initialise our current entry
entries = [] entries = []
date_blob_re = re.compile("(?:^|\n)\[([^\\]]+)\] ") date_blob_re = re.compile("(?:^|\n)\\[([^\\]]+)\\] ")
last_entry_pos = 0 last_entry_pos = 0
for match in date_blob_re.finditer(journal_txt): for match in date_blob_re.finditer(journal_txt):
date_blob = match.groups()[0] date_blob = match.groups()[0]
@ -162,7 +161,7 @@ class Journal:
return self.pprint() return self.pprint()
def __repr__(self): def __repr__(self):
return "<Journal with {0} entries>".format(len(self.entries)) return f"<Journal with {len(self.entries)} entries>"
def sort(self): def sort(self):
"""Sorts the Journal's entries by date""" """Sorts the Journal's entries by date"""
@ -182,7 +181,7 @@ class Journal:
for entry in self.entries for entry in self.entries
for tag in set(entry.tags)] for tag in set(entry.tags)]
# To be read: [for entry in journal.entries: for tag in set(entry.tags): tag] # 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)] 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=[]): def filter(self, tags=[], start_date=None, end_date=None, starred=False, strict=False, short=False, exclude=[]):
@ -199,8 +198,8 @@ class Journal:
exclude is a list of the tags which should not appear in the results. 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.""" entry is kept if any tag is present, unless they appear in exclude."""
self.search_tags = set([tag.lower() for tag in tags]) self.search_tags = {tag.lower() for tag in tags}
excluded_tags = set([tag.lower() for tag in exclude]) excluded_tags = {tag.lower() for tag in exclude}
end_date = time.parse(end_date, inclusive=True) end_date = time.parse(end_date, inclusive=True)
start_date = time.parse(start_date) start_date = time.parse(start_date)
@ -225,7 +224,7 @@ class Journal:
raw = raw.replace('\\n ', '\n').replace('\\n', '\n') raw = raw.replace('\\n ', '\n').replace('\\n', '\n')
starred = False starred = False
# Split raw text into title and body # Split raw text into title and body
sep = re.search("\n|[\?!.]+ +\n?", raw) sep = re.search("\n|[\\?!.]+ +\n?", raw)
first_line = raw[:sep.end()].strip() if sep else raw first_line = raw[:sep.end()].strip() if sep else raw
starred = False starred = False
@ -322,7 +321,7 @@ class LegacyJournal(Journal):
# escaping for the new format). # escaping for the new format).
line = new_date_format_regex.sub(r' \1', line) line = new_date_format_regex.sub(r' \1', line)
if current_entry: if current_entry:
current_entry.text += line + u"\n" current_entry.text += line + "\n"
# Append last entry # Append last entry
if current_entry: if current_entry:
@ -347,7 +346,7 @@ def open_journal(name, config, legacy=False):
return DayOneJournal.DayOne(**config).open() return DayOneJournal.DayOne(**config).open()
else: else:
print( print(
u"[Error: {0} is a directory, but doesn't seem to be a DayOne journal either.".format(config['journal']), f"[Error: {config['journal']} is a directory, but doesn't seem to be a DayOne journal either.",
file=sys.stderr file=sys.stderr
) )

View file

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# encoding: utf-8
import pkg_resources import pkg_resources

View file

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# encoding: utf-8
from . import cli from . import cli

View file

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# encoding: utf-8
""" """
jrnl jrnl
@ -89,7 +88,7 @@ def encrypt(journal, filename=None):
if util.yesno("Do you want to store the password in your keychain?", default=True): if util.yesno("Do you want to store the password in your keychain?", default=True):
util.set_keychain(journal.name, journal.config['password']) util.set_keychain(journal.name, journal.config['password'])
print("Journal encrypted to {0}.".format(filename or new_journal.config['journal']), file=sys.stderr) print("Journal encrypted to {}.".format(filename or new_journal.config['journal']), file=sys.stderr)
def decrypt(journal, filename=None): def decrypt(journal, filename=None):
@ -100,12 +99,12 @@ def decrypt(journal, filename=None):
new_journal = Journal.PlainJournal(filename, **journal.config) new_journal = Journal.PlainJournal(filename, **journal.config)
new_journal.entries = journal.entries new_journal.entries = journal.entries
new_journal.write(filename) new_journal.write(filename)
print("Journal decrypted to {0}.".format(filename or new_journal.config['journal']), file=sys.stderr) print("Journal decrypted to {}.".format(filename or new_journal.config['journal']), file=sys.stderr)
def list_journals(config): def list_journals(config):
"""List the journals specified in the configuration file""" """List the journals specified in the configuration file"""
result = "Journals defined in {}\n".format(install.CONFIG_FILE_PATH) result = f"Journals defined in {install.CONFIG_FILE_PATH}\n"
ml = min(max(len(k) for k in config['journals']), 20) ml = min(max(len(k) for k in config['journals']), 20)
for journal, cfg in config['journals'].items(): for journal, cfg in config['journals'].items():
result += " * {:{}} -> {}\n".format(journal, ml, cfg['journal'] if isinstance(cfg, dict) else cfg) result += " * {:{}} -> {}\n".format(journal, ml, cfg['journal'] if isinstance(cfg, dict) else cfg)
@ -137,7 +136,7 @@ def run(manual_args=None):
args = parse_args(manual_args) args = parse_args(manual_args)
configure_logger(args.debug) configure_logger(args.debug)
if args.version: if args.version:
version_str = "{0} version {1}".format(jrnl.__title__, jrnl.__version__) version_str = f"{jrnl.__title__} version {jrnl.__version__}"
print(version_str) print(version_str)
sys.exit(0) sys.exit(0)
@ -158,7 +157,7 @@ def run(manual_args=None):
# use this! # use this!
journal_name = args.text[0] if (args.text and args.text[0] in config['journals']) else 'default' journal_name = args.text[0] if (args.text and args.text[0] in config['journals']) else 'default'
if journal_name is not 'default': if journal_name != 'default':
args.text = args.text[1:] args.text = args.text[1:]
elif "default" not in config['journals']: elif "default" not in config['journals']:
print("No default journal configured.", file=sys.stderr) print("No default journal configured.", file=sys.stderr)
@ -193,8 +192,8 @@ def run(manual_args=None):
if config['template']: if config['template']:
try: try:
template = open(config['template']).read() template = open(config['template']).read()
except IOError: except OSError:
print("[Could not read template at '']".format(config['template']), file=sys.stderr) print(f"[Could not read template at '{config['template']}']", file=sys.stderr)
sys.exit(1) sys.exit(1)
raw = util.get_text_from_editor(config, template) raw = util.get_text_from_editor(config, template)
else: else:
@ -213,7 +212,7 @@ def run(manual_args=None):
try: try:
journal = Journal.open_journal(journal_name, config) journal = Journal.open_journal(journal_name, config)
except KeyboardInterrupt: except KeyboardInterrupt:
print("[Interrupted while opening journal]".format(journal_name), file=sys.stderr) print(f"[Interrupted while opening journal]", file=sys.stderr)
sys.exit(1) sys.exit(1)
# Import mode # Import mode
@ -225,7 +224,7 @@ def run(manual_args=None):
raw = " ".join(args.text).strip() raw = " ".join(args.text).strip()
log.debug('Appending raw line "%s" to journal "%s"', raw, journal_name) log.debug('Appending raw line "%s" to journal "%s"', raw, journal_name)
journal.new_entry(raw) journal.new_entry(raw)
print("[Entry added to {0} journal]".format(journal_name), file=sys.stderr) print(f"[Entry added to {journal_name} journal]", file=sys.stderr)
journal.write() journal.write()
if not mode_compose: if not mode_compose:
@ -283,11 +282,11 @@ def run(manual_args=None):
num_edited = len([e for e in journal.entries if e.modified]) num_edited = len([e for e in journal.entries if e.modified])
prompts = [] prompts = []
if num_deleted: if num_deleted:
prompts.append("{0} {1} deleted".format(num_deleted, "entry" if num_deleted == 1 else "entries")) prompts.append("{} {} deleted".format(num_deleted, "entry" if num_deleted == 1 else "entries"))
if num_edited: if num_edited:
prompts.append("{0} {1} modified".format(num_edited, "entry" if num_deleted == 1 else "entries")) prompts.append("{} {} modified".format(num_edited, "entry" if num_deleted == 1 else "entries"))
if prompts: if prompts:
print("[{0}]".format(", ".join(prompts).capitalize()), file=sys.stderr) print("[{}]".format(", ".join(prompts).capitalize()), file=sys.stderr)
journal.entries += other_entries journal.entries += other_entries
journal.sort() journal.sort()
journal.write() journal.write()

View file

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# encoding: utf-8
from .util import ERROR_COLOR, RESET_COLOR from .util import ERROR_COLOR, RESET_COLOR
from .util import slugify from .util import slugify
@ -35,12 +34,12 @@ class Exporter:
try: try:
with codecs.open(path, "w", "utf-8") as f: with codecs.open(path, "w", "utf-8") as f:
f.write(self.export_journal(journal)) f.write(self.export_journal(journal))
return "[Journal exported to {0}]".format(path) return f"[Journal exported to {path}]"
except IOError as e: except OSError as e:
return "[{2}ERROR{3}: {0} {1}]".format(e.filename, e.strerror, ERROR_COLOR, RESET_COLOR) return f"[{ERROR_COLOR}ERROR{RESET_COLOR}: {e.filename} {e.strerror}]"
def make_filename(self, entry): def make_filename(self, entry):
return entry.date.strftime("%Y-%m-%d_{0}.{1}".format(slugify(entry.title), self.extension)) return entry.date.strftime("%Y-%m-%d_{}.{}".format(slugify(entry.title), self.extension))
def write_files(self, journal, path): def write_files(self, journal, path):
"""Exports a journal into individual files for each entry.""" """Exports a journal into individual files for each entry."""
@ -49,9 +48,9 @@ class Exporter:
full_path = os.path.join(path, self.make_filename(entry)) full_path = os.path.join(path, self.make_filename(entry))
with codecs.open(full_path, "w", "utf-8") as f: with codecs.open(full_path, "w", "utf-8") as f:
f.write(self.export_entry(entry)) f.write(self.export_entry(entry))
except IOError as e: except OSError as e:
return "[{2}ERROR{3}: {0} {1}]".format(e.filename, e.strerror, ERROR_COLOR, RESET_COLOR) return f"[{ERROR_COLOR}ERROR{RESET_COLOR}: {e.filename} {e.strerror}]"
return "[Journal exported to {0}]".format(path) return f"[Journal exported to {path}]"
def export(self, journal, format="text", output=None): def export(self, journal, format="text", output=None):
"""Exports to individual files if output is an existing path, or into """Exports to individual files if output is an existing path, or into

View file

@ -1,7 +1,5 @@
#!/usr/bin/env python #!/usr/bin/env python
# encoding: utf-8
from __future__ import absolute_import
import readline import readline
import glob import glob
import getpass import getpass
@ -69,7 +67,7 @@ def upgrade_config(config):
for key in missing_keys: for key in missing_keys:
config[key] = default_config[key] config[key] = default_config[key]
save_config(config) save_config(config)
print("[Configuration updated to newest version at {}]".format(CONFIG_FILE_PATH), file=sys.stderr) print(f"[Configuration updated to newest version at {CONFIG_FILE_PATH}]", file=sys.stderr)
def save_config(config): def save_config(config):
@ -120,7 +118,7 @@ def install():
readline.set_completer(autocomplete) readline.set_completer(autocomplete)
# Where to create the journal? # Where to create the journal?
path_query = 'Path to your journal file (leave blank for {}): '.format(JOURNAL_FILE_PATH) path_query = f'Path to your journal file (leave blank for {JOURNAL_FILE_PATH}): '
journal_path = input(path_query).strip() or JOURNAL_FILE_PATH journal_path = 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))

View file

@ -51,7 +51,7 @@ def parse(date_str, inclusive=False, default_hour=None, default_minute=None):
except TypeError: except TypeError:
return None return None
if flag is 1: # Date found, but no time. Use the default time. if flag == 1: # Date found, but no time. Use the default time.
date = datetime(*date[:3], hour=default_hour or 0, minute=default_minute or 0) date = datetime(*date[:3], hour=default_hour or 0, minute=default_minute or 0)
else: else:
date = datetime(*date[:6]) date = datetime(*date[:6])

View file

@ -10,7 +10,7 @@ import codecs
def backup(filename, binary=False): def backup(filename, binary=False):
print(" Created a backup at {}.backup".format(filename), file=sys.stderr) print(f" Created a backup at {filename}.backup", file=sys.stderr)
filename = os.path.expanduser(os.path.expandvars(filename)) filename = os.path.expanduser(os.path.expandvars(filename))
with open(filename, 'rb' if binary else 'r') as original: with open(filename, 'rb' if binary else 'r') as original:
contents = original.read() contents = original.read()
@ -63,12 +63,12 @@ older versions of jrnl anymore.
longest_journal_name = max([len(journal) for journal in config['journals']]) longest_journal_name = max([len(journal) for journal in config['journals']])
if encrypted_journals: if encrypted_journals:
print("\nFollowing encrypted journals will be upgraded to jrnl {}:".format(__version__), file=sys.stderr) print(f"\nFollowing encrypted journals will be upgraded to jrnl {__version__}:", file=sys.stderr)
for journal, path in encrypted_journals.items(): for journal, path in encrypted_journals.items():
print(" {:{pad}} -> {}".format(journal, path, pad=longest_journal_name), file=sys.stderr) print(" {:{pad}} -> {}".format(journal, path, pad=longest_journal_name), file=sys.stderr)
if plain_journals: if plain_journals:
print("\nFollowing plain text journals will upgraded to jrnl {}:".format(__version__), file=sys.stderr) print(f"\nFollowing plain text journals will upgraded to jrnl {__version__}:", file=sys.stderr)
for journal, path in plain_journals.items(): for journal, path in plain_journals.items():
print(" {:{pad}} -> {}".format(journal, path, pad=longest_journal_name), file=sys.stderr) print(" {:{pad}} -> {}".format(journal, path, pad=longest_journal_name), file=sys.stderr)
@ -85,13 +85,13 @@ older versions of jrnl anymore.
raise UserAbort("jrnl NOT upgraded, exiting.") raise UserAbort("jrnl NOT upgraded, exiting.")
for journal_name, path in encrypted_journals.items(): for journal_name, path in encrypted_journals.items():
print("\nUpgrading encrypted '{}' journal stored in {}...".format(journal_name, path), file=sys.stderr) print(f"\nUpgrading encrypted '{journal_name}' journal stored in {path}...", file=sys.stderr)
backup(path, binary=True) backup(path, binary=True)
old_journal = Journal.open_journal(journal_name, util.scope_config(config, journal_name), legacy=True) old_journal = Journal.open_journal(journal_name, util.scope_config(config, journal_name), legacy=True)
all_journals.append(EncryptedJournal.from_journal(old_journal)) all_journals.append(EncryptedJournal.from_journal(old_journal))
for journal_name, path in plain_journals.items(): for journal_name, path in plain_journals.items():
print("\nUpgrading plain text '{}' journal stored in {}...".format(journal_name, path), file=sys.stderr) print(f"\nUpgrading plain text '{journal_name}' journal stored in {path}...", file=sys.stderr)
backup(path) backup(path)
old_journal = Journal.open_journal(journal_name, util.scope_config(config, journal_name), legacy=True) old_journal = Journal.open_journal(journal_name, util.scope_config(config, journal_name), legacy=True)
all_journals.append(Journal.PlainJournal.from_journal(old_journal)) all_journals.append(Journal.PlainJournal.from_journal(old_journal))
@ -114,7 +114,7 @@ older versions of jrnl anymore.
print("\nUpgrading config...", file=sys.stderr) print("\nUpgrading config...", file=sys.stderr)
backup(config_path) backup(config_path)
print("\nWe're all done here and you can start enjoying jrnl 2.".format(config_path), file=sys.stderr) print("\nWe're all done here and you can start enjoying jrnl 2.", file=sys.stderr)
class UpgradeValidationException(Exception): class UpgradeValidationException(Exception):

View file

@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
# encoding: utf-8
import sys import sys
import os import os