From 30caf9cae2d2dfeee21c088705897b138ed8390e Mon Sep 17 00:00:00 2001 From: Peter Schmidbauer Date: Fri, 1 Nov 2019 11:16:12 +0100 Subject: [PATCH] Run pyupgrade --- jrnl/DayOneJournal.py | 5 ++--- jrnl/EncryptedJournal.py | 6 +++--- jrnl/Entry.py | 7 +++---- jrnl/Journal.py | 19 +++++++++---------- jrnl/__init__.py | 1 - jrnl/__main__.py | 1 - jrnl/cli.py | 25 ++++++++++++------------- jrnl/export.py | 15 +++++++-------- jrnl/install.py | 6 ++---- jrnl/time.py | 2 +- jrnl/upgrade.py | 12 ++++++------ jrnl/util.py | 1 - 12 files changed, 45 insertions(+), 55 deletions(-) diff --git a/jrnl/DayOneJournal.py b/jrnl/DayOneJournal.py index 30846f71..59314c4b 100644 --- a/jrnl/DayOneJournal.py +++ b/jrnl/DayOneJournal.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -# encoding: utf-8 from . import Entry from . import Journal @@ -25,7 +24,7 @@ class DayOne(Journal.Journal): def __init__(self, **kwargs): self.entries = [] self._deleted_entries = [] - super(DayOne, self).__init__(**kwargs) + super().__init__(**kwargs) def open(self): 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.uuid = m.group(1).lower() else: - date_blob_re = re.compile("^\[[^\\]]+\] ") + date_blob_re = re.compile("^\\[[^\\]]+\\] ") date_blob = date_blob_re.findall(line) if date_blob: date_blob = date_blob[0] diff --git a/jrnl/EncryptedJournal.py b/jrnl/EncryptedJournal.py index 67345f45..1cce66b8 100644 --- a/jrnl/EncryptedJournal.py +++ b/jrnl/EncryptedJournal.py @@ -29,7 +29,7 @@ def make_key(password): class EncryptedJournal(Journal.Journal): def __init__(self, name='default', **kwargs): - super(EncryptedJournal, self).__init__(name, **kwargs) + super().__init__(name, **kwargs) self.config['encrypt'] = True def open(self, filename=None): @@ -47,7 +47,7 @@ class EncryptedJournal(Journal.Journal): self.config['password'] = password 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: print("No password supplied for encrypted journal", file=sys.stderr) sys.exit(1) @@ -97,7 +97,7 @@ class LegacyEncryptedJournal(Journal.LegacyJournal): """Legacy class to support opening journals encrypted with the jrnl 1.x standard. You'll not be able to save these journals anymore.""" def __init__(self, name='default', **kwargs): - super(LegacyEncryptedJournal, self).__init__(name, **kwargs) + super().__init__(name, **kwargs) self.config['encrypt'] = True def _load(self, filename, password=None): diff --git a/jrnl/Entry.py b/jrnl/Entry.py index cf012e80..ca80b231 100755 --- a/jrnl/Entry.py +++ b/jrnl/Entry.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -# encoding: utf-8 import re import textwrap @@ -50,12 +49,12 @@ class Entry: @staticmethod def tag_regex(tagsymbols): - pattern = r'(?u)(?:^|\s)([{tags}][-+*#/\w]+)'.format(tags=tagsymbols) + pattern = fr'(?u)(?:^|\s)([{tagsymbols}][-+*#/\w]+)' return re.compile(pattern) def _parse_tags(self): 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): """Returns a string representation of the entry to be written into a journal file.""" @@ -105,7 +104,7 @@ class Entry: ) def __repr__(self): - return "".format(self.title.strip(), self.date.strftime("%Y-%m-%d %H:%M")) + return "".format(self.title.strip(), self.date.strftime("%Y-%m-%d %H:%M")) def __hash__(self): return hash(self.__repr__()) diff --git a/jrnl/Journal.py b/jrnl/Journal.py index aeab7385..e5f87e03 100644 --- a/jrnl/Journal.py +++ b/jrnl/Journal.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -# encoding: utf-8 from . import Entry from . import util @@ -71,7 +70,7 @@ class Journal: filename = filename or self.config['journal'] 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) text = self._load(filename) @@ -117,7 +116,7 @@ class Journal: # 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] @@ -162,7 +161,7 @@ class Journal: return self.pprint() def __repr__(self): - return "".format(len(self.entries)) + return f"" def sort(self): """Sorts the Journal's entries by date""" @@ -182,7 +181,7 @@ class Journal: 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=[]): @@ -199,8 +198,8 @@ class Journal: 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) @@ -225,7 +224,7 @@ class Journal: 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("\n|[\\?!.]+ +\n?", raw) first_line = raw[:sep.end()].strip() if sep else raw starred = False @@ -322,7 +321,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,7 +346,7 @@ def open_journal(name, config, legacy=False): return DayOneJournal.DayOne(**config).open() else: 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 ) diff --git a/jrnl/__init__.py b/jrnl/__init__.py index 57664dbb..1905b195 100644 --- a/jrnl/__init__.py +++ b/jrnl/__init__.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -# encoding: utf-8 import pkg_resources diff --git a/jrnl/__main__.py b/jrnl/__main__.py index b01d9ff4..3ce86730 100644 --- a/jrnl/__main__.py +++ b/jrnl/__main__.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -# encoding: utf-8 from . import cli diff --git a/jrnl/cli.py b/jrnl/cli.py index 464c8c39..3cf67030 100644 --- a/jrnl/cli.py +++ b/jrnl/cli.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -# encoding: utf-8 """ 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): 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): @@ -100,12 +99,12 @@ def decrypt(journal, filename=None): new_journal = Journal.PlainJournal(filename, **journal.config) new_journal.entries = journal.entries 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): """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) for journal, cfg in config['journals'].items(): 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) configure_logger(args.debug) if args.version: - version_str = "{0} version {1}".format(jrnl.__title__, jrnl.__version__) + version_str = f"{jrnl.__title__} version {jrnl.__version__}" print(version_str) sys.exit(0) @@ -158,7 +157,7 @@ def run(manual_args=None): # use this! 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:] elif "default" not in config['journals']: print("No default journal configured.", file=sys.stderr) @@ -193,8 +192,8 @@ def run(manual_args=None): if config['template']: try: template = open(config['template']).read() - except IOError: - print("[Could not read template at '']".format(config['template']), file=sys.stderr) + except OSError: + print(f"[Could not read template at '{config['template']}']", file=sys.stderr) sys.exit(1) raw = util.get_text_from_editor(config, template) else: @@ -213,7 +212,7 @@ def run(manual_args=None): try: journal = Journal.open_journal(journal_name, config) 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) # Import mode @@ -225,7 +224,7 @@ def run(manual_args=None): raw = " ".join(args.text).strip() log.debug('Appending raw line "%s" to journal "%s"', raw, journal_name) 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() 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]) prompts = [] 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: - 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: - print("[{0}]".format(", ".join(prompts).capitalize()), file=sys.stderr) + print("[{}]".format(", ".join(prompts).capitalize()), file=sys.stderr) journal.entries += other_entries journal.sort() journal.write() diff --git a/jrnl/export.py b/jrnl/export.py index a69ee00e..399f2db0 100644 --- a/jrnl/export.py +++ b/jrnl/export.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -# encoding: utf-8 from .util import ERROR_COLOR, RESET_COLOR from .util import slugify @@ -35,12 +34,12 @@ class Exporter: try: with codecs.open(path, "w", "utf-8") as f: f.write(self.export_journal(journal)) - return "[Journal exported to {0}]".format(path) - except IOError as e: - return "[{2}ERROR{3}: {0} {1}]".format(e.filename, e.strerror, ERROR_COLOR, RESET_COLOR) + return f"[Journal exported to {path}]" + except OSError as e: + return f"[{ERROR_COLOR}ERROR{RESET_COLOR}: {e.filename} {e.strerror}]" 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): """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)) with codecs.open(full_path, "w", "utf-8") as f: f.write(self.export_entry(entry)) - except IOError as e: - return "[{2}ERROR{3}: {0} {1}]".format(e.filename, e.strerror, ERROR_COLOR, RESET_COLOR) - return "[Journal exported to {0}]".format(path) + except OSError as e: + return f"[{ERROR_COLOR}ERROR{RESET_COLOR}: {e.filename} {e.strerror}]" + return f"[Journal exported to {path}]" def export(self, journal, format="text", output=None): """Exports to individual files if output is an existing path, or into diff --git a/jrnl/install.py b/jrnl/install.py index 08bb44dd..c104b46b 100644 --- a/jrnl/install.py +++ b/jrnl/install.py @@ -1,7 +1,5 @@ #!/usr/bin/env python -# encoding: utf-8 -from __future__ import absolute_import import readline import glob import getpass @@ -69,7 +67,7 @@ def upgrade_config(config): for key in missing_keys: config[key] = default_config[key] 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): @@ -120,7 +118,7 @@ def install(): readline.set_completer(autocomplete) # 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 default_config['journals']['default'] = os.path.expanduser(os.path.expandvars(journal_path)) diff --git a/jrnl/time.py b/jrnl/time.py index 9ff125aa..eee3fc20 100644 --- a/jrnl/time.py +++ b/jrnl/time.py @@ -51,7 +51,7 @@ def parse(date_str, inclusive=False, default_hour=None, default_minute=None): except TypeError: 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) else: date = datetime(*date[:6]) diff --git a/jrnl/upgrade.py b/jrnl/upgrade.py index 2a5c1192..d1b83809 100644 --- a/jrnl/upgrade.py +++ b/jrnl/upgrade.py @@ -10,7 +10,7 @@ import codecs 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)) with open(filename, 'rb' if binary else 'r') as original: contents = original.read() @@ -63,12 +63,12 @@ older versions of jrnl anymore. longest_journal_name = max([len(journal) for journal in config['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(): print(" {:{pad}} -> {}".format(journal, path, pad=longest_journal_name), file=sys.stderr) 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(): 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.") 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) old_journal = Journal.open_journal(journal_name, util.scope_config(config, journal_name), legacy=True) all_journals.append(EncryptedJournal.from_journal(old_journal)) 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) old_journal = Journal.open_journal(journal_name, util.scope_config(config, journal_name), legacy=True) all_journals.append(Journal.PlainJournal.from_journal(old_journal)) @@ -114,7 +114,7 @@ older versions of jrnl anymore. print("\nUpgrading config...", file=sys.stderr) 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): diff --git a/jrnl/util.py b/jrnl/util.py index 52f7e4c4..d2bdf9c4 100644 --- a/jrnl/util.py +++ b/jrnl/util.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -# encoding: utf-8 import sys import os