From 9e8ec6d31e9f7456f3a98ca422445d0cfc3a4f73 Mon Sep 17 00:00:00 2001 From: outa Date: Tue, 11 Oct 2022 16:13:38 +0200 Subject: [PATCH 1/5] Add type hints --- jrnl/DayOneJournal.py | 14 +++++++------- jrnl/Entry.py | 15 ++++++++------- jrnl/FolderJournal.py | 15 ++++++++------- jrnl/args.py | 4 ++-- jrnl/cli.py | 4 ++-- jrnl/color.py | 11 +++++++---- jrnl/config.py | 21 +++++++++++---------- jrnl/editor.py | 4 ++-- jrnl/install.py | 14 +++++++------- jrnl/jrnl.py | 38 +++++++++++++++++++------------------- jrnl/os_compat.py | 6 +++--- jrnl/output.py | 18 +++++++++--------- jrnl/override.py | 4 ++-- jrnl/path.py | 6 +++--- jrnl/prompt.py | 2 +- jrnl/time.py | 6 +++--- jrnl/upgrade.py | 10 +++++----- 17 files changed, 99 insertions(+), 93 deletions(-) diff --git a/jrnl/DayOneJournal.py b/jrnl/DayOneJournal.py index d7f062496..4e827cedc 100644 --- a/jrnl/DayOneJournal.py +++ b/jrnl/DayOneJournal.py @@ -38,7 +38,7 @@ def __init__(self, **kwargs): self.can_be_encrypted = False super().__init__(**kwargs) - def open(self): + def open(self) -> "DayOne": filenames = [] for root, dirnames, f in os.walk(self.config["journal"]): for filename in fnmatch.filter(f, "*.doentry"): @@ -113,7 +113,7 @@ def open(self): self.sort() return self - def write(self): + def write(self) -> None: """Writes only the entries that have been modified into plist files.""" for entry in self.entries: if entry.modified: @@ -177,12 +177,12 @@ def write(self): ) os.remove(filename) - def editable_str(self): + def editable_str(self) -> str: """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([f"{str(e)}\n# {e.uuid}\n" for e in self.entries]) - def _update_old_entry(self, entry, new_entry): + def _update_old_entry(self, entry: Entry, new_entry: Entry) -> None: for attr in ("title", "body", "date"): old_attr = getattr(entry, attr) new_attr = getattr(new_entry, attr) @@ -190,7 +190,7 @@ def _update_old_entry(self, entry, new_entry): entry.modified = True setattr(entry, attr, new_attr) - def _get_and_remove_uuid_from_entry(self, entry): + def _get_and_remove_uuid_from_entry(self, entry: Entry) -> Entry: uuid_regex = "^ *?# ([a-zA-Z0-9]+) *?$" m = re.search(uuid_regex, entry.body, re.MULTILINE) entry.uuid = m.group(1) if m else None @@ -201,7 +201,7 @@ def _get_and_remove_uuid_from_entry(self, entry): return entry - def parse_editable_str(self, edited): + def parse_editable_str(self, edited: str) -> None: """Parses the output of self.editable_str and updates its entries.""" # Method: create a new list of entries from the edited text, then match # UUIDs of the new entries against self.entries, updating the entries @@ -210,7 +210,7 @@ def parse_editable_str(self, edited): entries_from_editor = self._parse(edited) for entry in entries_from_editor: - entry = self._get_and_remove_uuid_from_entry(entry) + self._get_and_remove_uuid_from_entry(entry) # Remove deleted entries edited_uuids = [e.uuid for e in entries_from_editor] diff --git a/jrnl/Entry.py b/jrnl/Entry.py index b8c3b640d..0d17ad47b 100644 --- a/jrnl/Entry.py +++ b/jrnl/Entry.py @@ -8,12 +8,13 @@ import ansiwrap +from .Journal import Journal from .color import colorize from .color import highlight_tags_with_background_color class Entry: - def __init__(self, journal, date=None, text="", starred=False): + def __init__(self, journal: Journal, date: datetime.datetime | None = None, text: str = "", starred: bool = False): self.journal = journal # Reference to journal mainly to access its config self.date = date or datetime.datetime.now() self.text = text @@ -24,7 +25,7 @@ def __init__(self, journal, date=None, text="", starred=False): self.modified = False @property - def fulltext(self): + def fulltext(self) -> str: return self.title + " " + self.body def _parse_text(self): @@ -68,11 +69,11 @@ def tags(self, x): self._tags = x @staticmethod - def tag_regex(tagsymbols): + def tag_regex(tagsymbols: str) -> re.Pattern: pattern = rf"(? set[str]: tagsymbols = self.journal.config["tagsymbols"] return { tag.lower() for tag in re.findall(Entry.tag_regex(tagsymbols), self.text) @@ -90,7 +91,7 @@ def __str__(self): body=self.body.rstrip("\n "), ) - def pprint(self, short=False): + def pprint(self, short: bool = False) -> str: """Returns a pretty-printed version of the entry. If short is true, only print the title.""" # Handle indentation @@ -197,7 +198,7 @@ def __repr__(self): def __hash__(self): return hash(self.__repr__()) - def __eq__(self, other): + def __eq__(self, other: "Entry"): if ( not isinstance(other, Entry) or self.title.strip() != other.title.strip() @@ -230,7 +231,7 @@ def __ne__(self, other): SENTENCE_SPLITTER_ONLY_NEWLINE = re.compile("\n") -def split_title(text): +def split_title(text: str) -> tuple[str, str]: """Splits the first sentence off from a text.""" sep = SENTENCE_SPLITTER_ONLY_NEWLINE.search(text.lstrip()) if not sep: diff --git a/jrnl/FolderJournal.py b/jrnl/FolderJournal.py index 25a927e12..44fb48871 100644 --- a/jrnl/FolderJournal.py +++ b/jrnl/FolderJournal.py @@ -7,9 +7,10 @@ from jrnl import Journal from jrnl import time +from jrnl.Entry import Entry -def get_files(journal_config): +def get_files(journal_config: str) -> list[str]: """Searches through sub directories starting with journal_config and find all text files""" filenames = [] for root, dirnames, f in os.walk(journal_config): @@ -21,13 +22,13 @@ def get_files(journal_config): class Folder(Journal.Journal): """A Journal handling multiple files in a folder""" - def __init__(self, name="default", **kwargs): + def __init__(self, name: str = "default", **kwargs): self.entries = [] self._diff_entry_dates = [] self.can_be_encrypted = False super().__init__(name, **kwargs) - def open(self): + def open(self) -> "Folder": filenames = [] self.entries = [] filenames = get_files(self.config["journal"]) @@ -38,7 +39,7 @@ def open(self): self.sort() return self - def write(self): + def write(self) -> None: """Writes only the entries that have been modified into proper files.""" # Create a list of dates of modified entries. Start with diff_entry_dates modified_dates = self._diff_entry_dates @@ -81,13 +82,13 @@ def write(self): if os.stat(filename).st_size <= 0: os.remove(filename) - def delete_entries(self, entries_to_delete): + def delete_entries(self, entries_to_delete: list[Entry]) -> None: """Deletes specific entries from a journal.""" for entry in entries_to_delete: self.entries.remove(entry) self._diff_entry_dates.append(entry.date) - def change_date_entries(self, date): + def change_date_entries(self, date: str) -> None: """Changes entry dates to given date.""" date = time.parse(date) @@ -98,7 +99,7 @@ def change_date_entries(self, date): self._diff_entry_dates.append(entry.date) entry.date = date - def parse_editable_str(self, edited): + def parse_editable_str(self, edited: str) -> None: """Parses the output of self.editable_str and updates its entries.""" mod_entries = self._parse(edited) diff_entries = set(self.entries) - set(mod_entries) diff --git a/jrnl/args.py b/jrnl/args.py index c6b0f1a0d..f7f0eb3a9 100644 --- a/jrnl/args.py +++ b/jrnl/args.py @@ -20,7 +20,7 @@ class WrappingFormatter(argparse.RawTextHelpFormatter): """Used in help screen""" - def _split_lines(self, text, width): + def _split_lines(self, text: str, width: int) -> list[str]: text = text.split("\n\n") text = map(lambda t: self._whitespace_matcher.sub(" ", t).strip(), text) text = map(lambda t: textwrap.wrap(t, width=56), text) @@ -28,7 +28,7 @@ def _split_lines(self, text, width): return text -def parse_args(args=[]): +def parse_args(args: list[str] = []) -> argparse.Namespace: """ Argument parsing that is doable before the config is available. Everything else goes into "text" for later parsing. diff --git a/jrnl/cli.py b/jrnl/cli.py index d8009df63..609a8aab8 100644 --- a/jrnl/cli.py +++ b/jrnl/cli.py @@ -16,7 +16,7 @@ from jrnl.output import print_msg -def configure_logger(debug=False): +def configure_logger(debug: bool = False) -> None: if not debug: logging.disable() return @@ -31,7 +31,7 @@ def configure_logger(debug=False): logging.getLogger("keyring.backend").setLevel(logging.ERROR) -def cli(manual_args=None): +def cli(manual_args: list[str] | None = None) -> int: try: if manual_args is None: manual_args = sys.argv[1:] diff --git a/jrnl/color.py b/jrnl/color.py index f5634bbd0..d92d113a3 100644 --- a/jrnl/color.py +++ b/jrnl/color.py @@ -7,13 +7,14 @@ import colorama +from jrnl.Entry import Entry from jrnl.os_compat import on_windows if on_windows(): colorama.init() -def colorize(string, color, bold=False): +def colorize(string: str, color: str, bold: bool = False) -> str: """Returns the string colored with colorama.Fore.color. If the color set by the user is "NONE" or the color doesn't exist in the colorama.Fore attributes, it returns the string without any modification.""" @@ -26,7 +27,9 @@ def colorize(string, color, bold=False): return colorama.Style.BRIGHT + color_escape + string + colorama.Style.RESET_ALL -def highlight_tags_with_background_color(entry, text, color, is_title=False): +def highlight_tags_with_background_color( + entry: Entry, text: str, color: str, is_title: bool = False +) -> str: """ Takes a string and colorizes the tags in it based upon the config value for color.tags, while colorizing the rest of the text based on `color`. @@ -45,9 +48,9 @@ def colorized_text_generator(fragments): :returns [(colorized_str, original_str)]""" for part in fragments: if part and part[0] not in config["tagsymbols"]: - yield (colorize(part, color, bold=is_title), part) + yield colorize(part, color, bold=is_title), part elif part: - yield (colorize(part, config["colors"]["tags"], bold=True), part) + yield colorize(part, config["colors"]["tags"], bold=True), part config = entry.journal.config if config["highlight"]: # highlight tags diff --git a/jrnl/config.py b/jrnl/config.py index e3290d8b7..e787d6956 100644 --- a/jrnl/config.py +++ b/jrnl/config.py @@ -4,6 +4,7 @@ import argparse import logging import os +from typing import Any from typing import Callable import colorama @@ -57,7 +58,7 @@ def make_yaml_valid_dict(input: list) -> dict: return runtime_modifications -def save_config(config, alt_config_path=None): +def save_config(config: dict, alt_config_path: str | None = None) -> None: """Supply alt_config_path if using an alternate config through --config-file.""" config["version"] = __version__ @@ -72,7 +73,7 @@ def save_config(config, alt_config_path=None): yaml.dump(config, f) -def get_config_path(): +def get_config_path() -> str: try: config_directory_path = xdg.BaseDirectory.save_config_path(XDG_RESOURCE) except FileExistsError: @@ -91,7 +92,7 @@ def get_config_path(): return os.path.join(config_directory_path or home_dir(), DEFAULT_CONFIG_NAME) -def get_default_config(): +def get_default_config() -> dict[str, Any]: return { "version": __version__, "journals": {"default": {"journal": get_default_journal_path()}}, @@ -114,12 +115,12 @@ def get_default_config(): } -def get_default_journal_path(): +def get_default_journal_path() -> str: journal_data_path = xdg.BaseDirectory.save_data_path(XDG_RESOURCE) or home_dir() return os.path.join(journal_data_path, DEFAULT_JOURNAL_NAME) -def scope_config(config, journal_name): +def scope_config(config: dict, journal_name: str) -> dict: if journal_name not in config["journals"]: return config config = config.copy() @@ -139,7 +140,7 @@ def scope_config(config, journal_name): return config -def verify_config_colors(config): +def verify_config_colors(config: dict) -> bool: """ Ensures the keys set for colors are valid colorama.Fore attributes, or "None" :return: True if all keys are set correctly, False otherwise @@ -164,7 +165,7 @@ def verify_config_colors(config): return all_valid_colors -def load_config(config_path): +def load_config(config_path: str) -> dict: """Tries to load a config file from YAML.""" try: with open(config_path, encoding=YAML_FILE_ENCODING) as f: @@ -187,13 +188,13 @@ def load_config(config_path): return yaml.load(f) -def is_config_json(config_path): +def is_config_json(config_path: str) -> bool: with open(config_path, "r", encoding="utf-8") as f: config_file = f.read() return config_file.strip().startswith("{") -def update_config(config, new_config, scope, force_local=False): +def update_config(config: dict, new_config: dict, scope: str | None, force_local: bool = False) -> None: """Updates a config dict with new values - either global if scope is None or config['journals'][scope] is just a string pointing to a journal file, or within the scope""" @@ -206,7 +207,7 @@ def update_config(config, new_config, scope, force_local=False): config.update(new_config) -def get_journal_name(args, config): +def get_journal_name(args: argparse.Namespace, config: dict) -> argparse.Namespace: args.journal_name = DEFAULT_JOURNAL_KEY # The first arg might be a journal name diff --git a/jrnl/editor.py b/jrnl/editor.py index fd063f44e..d578e2d8b 100644 --- a/jrnl/editor.py +++ b/jrnl/editor.py @@ -17,7 +17,7 @@ from jrnl.output import print_msg -def get_text_from_editor(config, template=""): +def get_text_from_editor(config: dict, template: str = "") -> str: suffix = ".jrnl" if config["template"]: template_filename = Path(config["template"]).name @@ -50,7 +50,7 @@ def get_text_from_editor(config, template=""): return raw -def get_text_from_stdin(): +def get_text_from_stdin() -> str: print_msg( Message( MsgText.WritingEntryStart, diff --git a/jrnl/install.py b/jrnl/install.py index be0c7bc3b..a37e51f9e 100644 --- a/jrnl/install.py +++ b/jrnl/install.py @@ -27,7 +27,7 @@ from jrnl.upgrade import is_old_version -def upgrade_config(config_data, alt_config_path=None): +def upgrade_config(config_data: dict, alt_config_path: str | None = None) -> None: """Checks if there are keys missing in a given config dict, and if so, updates the config file accordingly. This essentially automatically ports jrnl installations if new config parameters are introduced in later versions. @@ -46,7 +46,7 @@ def upgrade_config(config_data, alt_config_path=None): ) -def find_default_config(): +def find_default_config() -> str: config_path = ( get_config_path() if os.path.exists(get_config_path()) @@ -55,7 +55,7 @@ def find_default_config(): return config_path -def find_alt_config(alt_config): +def find_alt_config(alt_config: str) -> str: if not os.path.exists(alt_config): raise JrnlException( Message( @@ -66,7 +66,7 @@ def find_alt_config(alt_config): return alt_config -def load_or_install_jrnl(alt_config_path): +def load_or_install_jrnl(alt_config_path: str) -> dict: """ If jrnl is already installed, loads and returns a default config object. If alternate config is specified via --config-file flag, it will be used. @@ -107,7 +107,7 @@ def load_or_install_jrnl(alt_config_path): return config -def install(): +def install() -> dict: _initialize_autocomplete() # Where to create the journal? @@ -143,7 +143,7 @@ def install(): return default_config -def _initialize_autocomplete(): +def _initialize_autocomplete() -> None: # readline is not included in Windows Active Python and perhaps some other distributions if sys.modules.get("readline"): import readline @@ -153,7 +153,7 @@ def _initialize_autocomplete(): readline.set_completer(_autocomplete_path) -def _autocomplete_path(text, state): +def _autocomplete_path(text: str, state: int) -> list[str | None]: expansions = glob.glob(expand_path(text) + "*") expansions = [e + "/" if os.path.isdir(e) else e for e in expansions] expansions.append(None) diff --git a/jrnl/jrnl.py b/jrnl/jrnl.py index 5c9ae9ac8..abf6c4c87 100644 --- a/jrnl/jrnl.py +++ b/jrnl/jrnl.py @@ -1,6 +1,6 @@ # Copyright © 2012-2022 jrnl contributors # License: https://www.gnu.org/licenses/gpl-3.0.html - +from argparse import Namespace import logging import sys @@ -13,8 +13,10 @@ from jrnl.config import scope_config from jrnl.editor import get_text_from_editor from jrnl.editor import get_text_from_stdin +from jrnl.Entry import Entry from jrnl.exception import JrnlException from jrnl.Journal import open_journal +from jrnl.Journal import Journal from jrnl.messages import Message from jrnl.messages import MsgStyle from jrnl.messages import MsgText @@ -24,7 +26,7 @@ from jrnl.path import expand_path -def run(args): +def run(args: Namespace): """ Flow: 1. Run standalone command if it doesn't require config (help, version, etc), then exit @@ -72,10 +74,8 @@ def run(args): search_mode(**kwargs) -def _is_write_mode(args, config, **kwargs): +def _is_write_mode(args: Namespace, config: dict, **kwargs) -> bool: """Determines if we are in write mode (as opposed to search mode)""" - write_mode = True - # Are any search filters present? If so, then search mode. write_mode = not any( ( @@ -115,7 +115,7 @@ def _is_write_mode(args, config, **kwargs): return write_mode -def write_mode(args, config, journal, **kwargs): +def write_mode(args: Namespace, config: dict, journal: Journal, **kwargs) -> None: """ Gets input from the user to write to the journal 1. Check for input from cli @@ -159,7 +159,7 @@ def write_mode(args, config, journal, **kwargs): logging.debug("Write mode: completed journal.write()") -def search_mode(args, journal, **kwargs): +def search_mode(args: Namespace, journal: Journal, **kwargs) -> None: """ Search for entries in a journal, then either: 1. Send them to configured editor for user manipulation (and also @@ -213,7 +213,7 @@ def search_mode(args, journal, **kwargs): _display_search_results(**kwargs) -def _write_in_editor(config, template=None): +def _write_in_editor(config: dict, template: str | None = None) -> str: if config["editor"]: logging.debug("Write mode: opening editor") if not template: @@ -226,7 +226,7 @@ def _write_in_editor(config, template=None): return raw -def _get_editor_template(config, **kwargs): +def _get_editor_template(config: dict, **kwargs) -> str: logging.debug("Write mode: loading template for entry") if not config["template"]: @@ -251,7 +251,7 @@ def _get_editor_template(config, **kwargs): return template -def _has_search_args(args): +def _has_search_args(args: Namespace) -> bool: return any( ( args.on_date, @@ -271,7 +271,7 @@ def _has_search_args(args): ) -def _filter_journal_entries(args, journal, **kwargs): +def _filter_journal_entries(args: Namespace, journal: Journal, **kwargs) -> None: """Filter journal entries in-place based upon search args""" if args.on_date: args.start_date = args.end_date = args.on_date @@ -296,7 +296,7 @@ def _filter_journal_entries(args, journal, **kwargs): journal.limit(args.limit) -def _print_entries_found_count(count, args): +def _print_entries_found_count(count: int, args: Namespace) -> None: if count == 0: if args.edit or args.change_time: print_msg(Message(MsgText.NothingToModify, MsgStyle.WARNING)) @@ -317,12 +317,12 @@ def _print_entries_found_count(count, args): print_msg(Message(my_msg, MsgStyle.NORMAL, {"num": count})) -def _other_entries(journal, entries): +def _other_entries(journal: Journal, entries: list[Entry]) -> list[Entry]: """Find entries that are not in journal""" return [e for e in entries if e not in journal.entries] -def _edit_search_results(config, journal, old_entries, **kwargs): +def _edit_search_results(config: dict, journal: Journal, old_entries: list[Entry], **kwargs) -> None: """ 1. Send the given journal entries to the user-configured editor 2. Print out stats on any modifications to journal @@ -356,7 +356,7 @@ def _edit_search_results(config, journal, old_entries, **kwargs): journal.write() -def _print_edited_summary(journal, old_stats, **kwargs): +def _print_edited_summary(journal: Journal, old_stats: dict[str, int], **kwargs) -> None: stats = { "added": len(journal) - old_stats["count"], "deleted": old_stats["count"] - len(journal), @@ -395,11 +395,11 @@ def _print_edited_summary(journal, old_stats, **kwargs): print_msgs(msgs) -def _get_predit_stats(journal): +def _get_predit_stats(journal: Journal) -> dict[str, int]: return {"count": len(journal)} -def _delete_search_results(journal, old_entries, **kwargs): +def _delete_search_results(journal: Journal, old_entries: list[Entry], **kwargs) -> None: entries_to_delete = journal.prompt_action_entries(MsgText.DeleteEntryQuestion) if entries_to_delete: @@ -409,7 +409,7 @@ def _delete_search_results(journal, old_entries, **kwargs): journal.write() -def _change_time_search_results(args, journal, old_entries, no_prompt=False, **kwargs): +def _change_time_search_results(args: Namespace, journal: Journal, old_entries: list[Entry], no_prompt: bool = False, **kwargs) -> None: # separate entries we are not editing other_entries = _other_entries(journal, old_entries) @@ -432,7 +432,7 @@ def _change_time_search_results(args, journal, old_entries, no_prompt=False, **k journal.write() -def _display_search_results(args, journal, **kwargs): +def _display_search_results(args: Namespace, journal: Journal, **kwargs) -> None: # Get export format from config file if not provided at the command line args.export = args.export or kwargs["config"].get("display_format") diff --git a/jrnl/os_compat.py b/jrnl/os_compat.py index 2bb46bc5d..ef6d878a3 100644 --- a/jrnl/os_compat.py +++ b/jrnl/os_compat.py @@ -5,14 +5,14 @@ from sys import platform -def on_windows(): +def on_windows() -> bool: return "win32" in platform -def on_posix(): +def on_posix() -> bool: return not on_windows() -def split_args(args): +def split_args(args: str) -> list[str]: """Split arguments and add escape characters as appropriate for the OS""" return shlex.split(args, posix=on_posix()) diff --git a/jrnl/output.py b/jrnl/output.py index 2db0362e7..bdf53dcd0 100644 --- a/jrnl/output.py +++ b/jrnl/output.py @@ -2,7 +2,7 @@ # License: https://www.gnu.org/licenses/gpl-3.0.html import textwrap -from typing import Union +from typing import Callable from rich.console import Console from rich.text import Text @@ -12,7 +12,7 @@ from jrnl.messages import MsgText -def deprecated_cmd(old_cmd, new_cmd, callback=None, **kwargs): +def deprecated_cmd(old_cmd: str, new_cmd: str, callback: Callable | None = None, **kwargs) -> None: print_msg( Message( MsgText.DeprecatedCommand, @@ -25,13 +25,13 @@ def deprecated_cmd(old_cmd, new_cmd, callback=None, **kwargs): callback(**kwargs) -def journal_list_to_json(journal_list): +def journal_list_to_json(journal_list: dict) -> str: import json return json.dumps(journal_list) -def journal_list_to_yaml(journal_list): +def journal_list_to_yaml(journal_list: dict) -> str: from io import StringIO from ruamel.yaml import YAML @@ -41,7 +41,7 @@ def journal_list_to_yaml(journal_list): return output.getvalue() -def journal_list_to_stdout(journal_list): +def journal_list_to_stdout(journal_list: dict) -> str: result = f"Journals defined in config ({journal_list['config_path']})\n" ml = min(max(len(k) for k in journal_list["journals"]), 20) for journal, cfg in journal_list["journals"].items(): @@ -51,7 +51,7 @@ def journal_list_to_stdout(journal_list): return result -def list_journals(configuration, format=None): +def list_journals(configuration: dict, format: str | None = None) -> str: from jrnl import config """List the journals specified in the configuration file""" @@ -69,7 +69,7 @@ def list_journals(configuration, format=None): return journal_list_to_stdout(journal_list) -def print_msg(msg: Message, **kwargs) -> Union[None, str]: +def print_msg(msg: Message, **kwargs) -> str | None: """Helper function to print a single message""" kwargs["style"] = msg.style return print_msgs([msg], **kwargs) @@ -81,7 +81,7 @@ def print_msgs( style: MsgStyle = MsgStyle.NORMAL, get_input: bool = False, hide_input: bool = False, -) -> Union[None, str]: +) -> str | None: # Same as print_msg, but for a list text = Text("", end="") kwargs = style.decoration.args @@ -113,7 +113,7 @@ def _get_console(stderr: bool = True) -> Console: return Console(stderr=stderr) -def _add_extra_style_args_if_needed(args, msg): +def _add_extra_style_args_if_needed(args: dict, msg: Message): args["border_style"] = msg.style.color args["title"] = msg.style.box_title return args diff --git a/jrnl/override.py b/jrnl/override.py index 75a400b90..932add85b 100644 --- a/jrnl/override.py +++ b/jrnl/override.py @@ -37,12 +37,12 @@ def apply_overrides(args: "Namespace", base_config: dict) -> dict: return base_config -def _get_key_and_value_from_pair(pairs): +def _get_key_and_value_from_pair(pairs: dict) -> tuple: key_as_dots, override_value = list(pairs.items())[0] return key_as_dots, override_value -def _convert_dots_to_list(key_as_dots): +def _convert_dots_to_list(key_as_dots: str) -> list[str]: keys = key_as_dots.split(".") keys = [k for k in keys if k != ""] # remove empty elements return keys diff --git a/jrnl/path.py b/jrnl/path.py index 0ec3492fc..97e04ffe7 100644 --- a/jrnl/path.py +++ b/jrnl/path.py @@ -4,13 +4,13 @@ import os.path -def home_dir(): +def home_dir() -> str: return os.path.expanduser("~") -def expand_path(path): +def expand_path(path: str) -> str: return os.path.expanduser(os.path.expandvars(path)) -def absolute_path(path): +def absolute_path(path: str) -> str: return os.path.abspath(expand_path(path)) diff --git a/jrnl/prompt.py b/jrnl/prompt.py index f4d62ae4d..8f7e36c99 100644 --- a/jrnl/prompt.py +++ b/jrnl/prompt.py @@ -42,7 +42,7 @@ def create_password(journal_name: str) -> str: return pw -def yesno(prompt: Message, default: bool = True) -> bool: +def yesno(prompt: Message | str, default: bool = True) -> bool: response = print_msgs( [ prompt, diff --git a/jrnl/time.py b/jrnl/time.py index fd17ca0a7..dbd2685d9 100644 --- a/jrnl/time.py +++ b/jrnl/time.py @@ -8,7 +8,7 @@ DEFAULT_PAST = datetime.datetime(FAKE_YEAR, 1, 1, 0, 0) -def __get_pdt_calendar(): +def __get_pdt_calendar() -> "pdt.Calendar": try: import parsedatetime.parsedatetime_consts as pdt except ImportError: @@ -22,8 +22,8 @@ def __get_pdt_calendar(): def parse( - date_str, inclusive=False, default_hour=None, default_minute=None, bracketed=False -): + date_str: str | datetime.datetime, inclusive: bool = False, default_hour: int | None = None, default_minute: int | None = None, bracketed: bool = False +) -> datetime.datetime | None: """Parses a string containing a fuzzy date and returns a datetime.datetime object""" if not date_str: return None diff --git a/jrnl/upgrade.py b/jrnl/upgrade.py index 206b9405f..e620537da 100644 --- a/jrnl/upgrade.py +++ b/jrnl/upgrade.py @@ -19,7 +19,7 @@ from jrnl.prompt import yesno -def backup(filename, binary=False): +def backup(filename: str, binary: bool = False): filename = expand_path(filename) try: @@ -42,14 +42,14 @@ def backup(filename, binary=False): raise JrnlException(Message(MsgText.UpgradeAborted, MsgStyle.WARNING)) -def check_exists(path): +def check_exists(path: str) -> bool: """ Checks if a given path exists. """ return os.path.exists(path) -def upgrade_jrnl(config_path): +def upgrade_jrnl(config_path: str) -> None: config = load_config(config_path) print_msg(Message(MsgText.WelcomeToJrnl, MsgStyle.NORMAL, {"version": __version__})) @@ -115,7 +115,7 @@ def upgrade_jrnl(config_path): cont = yesno(Message(MsgText.ContinueUpgrade), default=False) if not cont: - raise JrnlException(Message(MsgText.UpgradeAborted), MsgStyle.WARNING) + raise JrnlException(Message(MsgText.UpgradeAborted, MsgStyle.WARNING)) for journal_name, path in encrypted_journals.items(): print_msg( @@ -178,7 +178,7 @@ def upgrade_jrnl(config_path): print_msg(Message(MsgText.AllDoneUpgrade, MsgStyle.NORMAL)) -def is_old_version(config_path): +def is_old_version(config_path: str) -> bool: return is_config_json(config_path) From c87af823662f1169de067548f859989dad09fb2e Mon Sep 17 00:00:00 2001 From: outa Date: Tue, 11 Oct 2022 18:11:35 +0200 Subject: [PATCH 2/5] Fix linters --- jrnl/Entry.py | 13 +++++++++++-- jrnl/color.py | 7 +++++-- jrnl/config.py | 4 +++- jrnl/jrnl.py | 24 ++++++++++++++++++------ jrnl/output.py | 4 +++- jrnl/time.py | 8 ++++++-- 6 files changed, 46 insertions(+), 14 deletions(-) diff --git a/jrnl/Entry.py b/jrnl/Entry.py index 0d17ad47b..9dfdf00f1 100644 --- a/jrnl/Entry.py +++ b/jrnl/Entry.py @@ -5,16 +5,25 @@ import logging import os import re +from typing import TYPE_CHECKING import ansiwrap -from .Journal import Journal from .color import colorize from .color import highlight_tags_with_background_color +if TYPE_CHECKING: + from .Journal import Journal + class Entry: - def __init__(self, journal: Journal, date: datetime.datetime | None = None, text: str = "", starred: bool = False): + def __init__( + self, + journal: "Journal", + date: datetime.datetime | None = None, + text: str = "", + starred: bool = False, + ): self.journal = journal # Reference to journal mainly to access its config self.date = date or datetime.datetime.now() self.text = text diff --git a/jrnl/color.py b/jrnl/color.py index d92d113a3..91d56254a 100644 --- a/jrnl/color.py +++ b/jrnl/color.py @@ -4,12 +4,15 @@ import re from string import punctuation from string import whitespace +from typing import TYPE_CHECKING import colorama -from jrnl.Entry import Entry from jrnl.os_compat import on_windows +if TYPE_CHECKING: + from jrnl.Entry import Entry + if on_windows(): colorama.init() @@ -28,7 +31,7 @@ def colorize(string: str, color: str, bold: bool = False) -> str: def highlight_tags_with_background_color( - entry: Entry, text: str, color: str, is_title: bool = False + entry: "Entry", text: str, color: str, is_title: bool = False ) -> str: """ Takes a string and colorizes the tags in it based upon the config value for diff --git a/jrnl/config.py b/jrnl/config.py index e787d6956..bcd67e2c4 100644 --- a/jrnl/config.py +++ b/jrnl/config.py @@ -194,7 +194,9 @@ def is_config_json(config_path: str) -> bool: return config_file.strip().startswith("{") -def update_config(config: dict, new_config: dict, scope: str | None, force_local: bool = False) -> None: +def update_config( + config: dict, new_config: dict, scope: str | None, force_local: bool = False +) -> None: """Updates a config dict with new values - either global if scope is None or config['journals'][scope] is just a string pointing to a journal file, or within the scope""" diff --git a/jrnl/jrnl.py b/jrnl/jrnl.py index abf6c4c87..7f8fcc6ed 100644 --- a/jrnl/jrnl.py +++ b/jrnl/jrnl.py @@ -1,8 +1,8 @@ # Copyright © 2012-2022 jrnl contributors # License: https://www.gnu.org/licenses/gpl-3.0.html -from argparse import Namespace import logging import sys +from argparse import Namespace from jrnl import install from jrnl import plugins @@ -15,8 +15,8 @@ from jrnl.editor import get_text_from_stdin from jrnl.Entry import Entry from jrnl.exception import JrnlException -from jrnl.Journal import open_journal from jrnl.Journal import Journal +from jrnl.Journal import open_journal from jrnl.messages import Message from jrnl.messages import MsgStyle from jrnl.messages import MsgText @@ -322,7 +322,9 @@ def _other_entries(journal: Journal, entries: list[Entry]) -> list[Entry]: return [e for e in entries if e not in journal.entries] -def _edit_search_results(config: dict, journal: Journal, old_entries: list[Entry], **kwargs) -> None: +def _edit_search_results( + config: dict, journal: Journal, old_entries: list[Entry], **kwargs +) -> None: """ 1. Send the given journal entries to the user-configured editor 2. Print out stats on any modifications to journal @@ -356,7 +358,9 @@ def _edit_search_results(config: dict, journal: Journal, old_entries: list[Entry journal.write() -def _print_edited_summary(journal: Journal, old_stats: dict[str, int], **kwargs) -> None: +def _print_edited_summary( + journal: Journal, old_stats: dict[str, int], **kwargs +) -> None: stats = { "added": len(journal) - old_stats["count"], "deleted": old_stats["count"] - len(journal), @@ -399,7 +403,9 @@ def _get_predit_stats(journal: Journal) -> dict[str, int]: return {"count": len(journal)} -def _delete_search_results(journal: Journal, old_entries: list[Entry], **kwargs) -> None: +def _delete_search_results( + journal: Journal, old_entries: list[Entry], **kwargs +) -> None: entries_to_delete = journal.prompt_action_entries(MsgText.DeleteEntryQuestion) if entries_to_delete: @@ -409,7 +415,13 @@ def _delete_search_results(journal: Journal, old_entries: list[Entry], **kwargs) journal.write() -def _change_time_search_results(args: Namespace, journal: Journal, old_entries: list[Entry], no_prompt: bool = False, **kwargs) -> None: +def _change_time_search_results( + args: Namespace, + journal: Journal, + old_entries: list[Entry], + no_prompt: bool = False, + **kwargs +) -> None: # separate entries we are not editing other_entries = _other_entries(journal, old_entries) diff --git a/jrnl/output.py b/jrnl/output.py index bdf53dcd0..0781263cd 100644 --- a/jrnl/output.py +++ b/jrnl/output.py @@ -12,7 +12,9 @@ from jrnl.messages import MsgText -def deprecated_cmd(old_cmd: str, new_cmd: str, callback: Callable | None = None, **kwargs) -> None: +def deprecated_cmd( + old_cmd: str, new_cmd: str, callback: Callable | None = None, **kwargs +) -> None: print_msg( Message( MsgText.DeprecatedCommand, diff --git a/jrnl/time.py b/jrnl/time.py index dbd2685d9..ca1668b39 100644 --- a/jrnl/time.py +++ b/jrnl/time.py @@ -8,7 +8,7 @@ DEFAULT_PAST = datetime.datetime(FAKE_YEAR, 1, 1, 0, 0) -def __get_pdt_calendar() -> "pdt.Calendar": +def __get_pdt_calendar(): try: import parsedatetime.parsedatetime_consts as pdt except ImportError: @@ -22,7 +22,11 @@ def __get_pdt_calendar() -> "pdt.Calendar": def parse( - date_str: str | datetime.datetime, inclusive: bool = False, default_hour: int | None = None, default_minute: int | None = None, bracketed: bool = False + date_str: str | datetime.datetime, + inclusive: bool = False, + default_hour: int | None = None, + default_minute: int | None = None, + bracketed: bool = False, ) -> datetime.datetime | None: """Parses a string containing a fuzzy date and returns a datetime.datetime object""" if not date_str: From 029ba446d85f5fb68418895155501a87a653f7dc Mon Sep 17 00:00:00 2001 From: outa Date: Wed, 12 Oct 2022 12:51:09 +0200 Subject: [PATCH 3/5] Add remaining type hints --- jrnl/plugins/__init__.py | 6 ++++-- jrnl/plugins/dates_exporter.py | 6 ++++-- jrnl/plugins/fancy_exporter.py | 8 +++++--- jrnl/plugins/jrnl_importer.py | 3 ++- jrnl/plugins/json_exporter.py | 8 +++++--- jrnl/plugins/markdown_exporter.py | 6 ++++-- jrnl/plugins/tag_exporter.py | 6 ++++-- jrnl/plugins/text_exporter.py | 16 +++++++++------- jrnl/plugins/util.py | 6 ++++-- jrnl/plugins/xml_exporter.py | 10 +++++++--- jrnl/plugins/yaml_exporter.py | 6 ++++-- 11 files changed, 52 insertions(+), 29 deletions(-) diff --git a/jrnl/plugins/__init__.py b/jrnl/plugins/__init__.py index ebfe5d3f6..f67cebafe 100644 --- a/jrnl/plugins/__init__.py +++ b/jrnl/plugins/__init__.py @@ -1,6 +1,8 @@ # Copyright © 2012-2022 jrnl contributors # License: https://www.gnu.org/licenses/gpl-3.0.html +from typing import Type + from jrnl.plugins.dates_exporter import DatesExporter from jrnl.plugins.fancy_exporter import FancyExporter from jrnl.plugins.jrnl_importer import JRNLImporter @@ -32,14 +34,14 @@ IMPORT_FORMATS = sorted(__importer_types.keys()) -def get_exporter(format): +def get_exporter(format: str) -> Type[TextExporter] | None: for exporter in __exporters: if hasattr(exporter, "names") and format in exporter.names: return exporter return None -def get_importer(format): +def get_importer(format: str) -> Type[JRNLImporter] | None: for importer in __importers: if hasattr(importer, "names") and format in importer.names: return importer diff --git a/jrnl/plugins/dates_exporter.py b/jrnl/plugins/dates_exporter.py index a5032f49b..778ec06fb 100644 --- a/jrnl/plugins/dates_exporter.py +++ b/jrnl/plugins/dates_exporter.py @@ -3,6 +3,8 @@ from collections import Counter +from jrnl.Entry import Entry +from jrnl.Journal import Journal from jrnl.plugins.text_exporter import TextExporter @@ -13,11 +15,11 @@ class DatesExporter(TextExporter): extension = "dates" @classmethod - def export_entry(cls, entry): + def export_entry(cls, entry: Entry): raise NotImplementedError @classmethod - def export_journal(cls, journal): + def export_journal(cls, journal: Journal) -> str: """Returns dates and their frequencies for an entire journal.""" date_counts = Counter() for entry in journal.entries: diff --git a/jrnl/plugins/fancy_exporter.py b/jrnl/plugins/fancy_exporter.py index 1eaf74c03..253a0d616 100644 --- a/jrnl/plugins/fancy_exporter.py +++ b/jrnl/plugins/fancy_exporter.py @@ -5,7 +5,9 @@ import os from textwrap import TextWrapper +from jrnl.Entry import Entry from jrnl.exception import JrnlException +from jrnl.Journal import Journal from jrnl.messages import Message from jrnl.messages import MsgStyle from jrnl.messages import MsgText @@ -35,7 +37,7 @@ class FancyExporter(TextExporter): border_m = "┘" @classmethod - def export_entry(cls, entry): + def export_entry(cls, entry: Entry) -> str: """Returns a fancy unicode representation of a single entry.""" date_str = entry.date.strftime(entry.journal.config["timeformat"]) @@ -95,12 +97,12 @@ def export_entry(cls, entry): return "\n".join(card) @classmethod - def export_journal(cls, journal): + def export_journal(cls, journal) -> str: """Returns a unicode representation of an entire journal.""" return "\n".join(cls.export_entry(entry) for entry in journal) -def check_provided_linewrap_viability(linewrap, card, journal): +def check_provided_linewrap_viability(linewrap: int, card: list[str], journal: Journal): if len(card[0]) > linewrap: width_violation = len(card[0]) - linewrap raise JrnlException( diff --git a/jrnl/plugins/jrnl_importer.py b/jrnl/plugins/jrnl_importer.py index c69d4673a..907ece4ca 100644 --- a/jrnl/plugins/jrnl_importer.py +++ b/jrnl/plugins/jrnl_importer.py @@ -4,6 +4,7 @@ import sys from jrnl.exception import JrnlException +from jrnl.Journal import Journal from jrnl.messages import Message from jrnl.messages import MsgStyle from jrnl.messages import MsgText @@ -16,7 +17,7 @@ class JRNLImporter: names = ["jrnl"] @staticmethod - def import_(journal, input=None): + def import_(journal: Journal, input: str | None = None) -> None: """Imports from an existing file if input is specified, and standard input otherwise.""" old_cnt = len(journal.entries) diff --git a/jrnl/plugins/json_exporter.py b/jrnl/plugins/json_exporter.py index ae153b703..dd0a4a4d2 100644 --- a/jrnl/plugins/json_exporter.py +++ b/jrnl/plugins/json_exporter.py @@ -3,6 +3,8 @@ import json +from jrnl.Entry import Entry +from jrnl.Journal import Journal from jrnl.plugins.text_exporter import TextExporter from jrnl.plugins.util import get_tags_count @@ -14,7 +16,7 @@ class JSONExporter(TextExporter): extension = "json" @classmethod - def entry_to_dict(cls, entry): + def entry_to_dict(cls, entry: Entry) -> dict: entry_dict = { "title": entry.title, "body": entry.body, @@ -49,12 +51,12 @@ def entry_to_dict(cls, entry): return entry_dict @classmethod - def export_entry(cls, entry): + def export_entry(cls, entry: Entry) -> str: """Returns a json representation of a single entry.""" return json.dumps(cls.entry_to_dict(entry), indent=2) + "\n" @classmethod - def export_journal(cls, journal): + def export_journal(cls, journal: Journal) -> str: """Returns a json representation of an entire journal.""" tags = get_tags_count(journal) result = { diff --git a/jrnl/plugins/markdown_exporter.py b/jrnl/plugins/markdown_exporter.py index c3476d51d..860646ff8 100644 --- a/jrnl/plugins/markdown_exporter.py +++ b/jrnl/plugins/markdown_exporter.py @@ -4,6 +4,8 @@ import os import re +from jrnl.Entry import Entry +from jrnl.Journal import Journal from jrnl.messages import Message from jrnl.messages import MsgStyle from jrnl.messages import MsgText @@ -18,7 +20,7 @@ class MarkdownExporter(TextExporter): extension = "md" @classmethod - def export_entry(cls, entry, to_multifile=True): + def export_entry(cls, entry: Entry, to_multifile: bool = True) -> str: """Returns a markdown representation of a single entry.""" date_str = entry.date.strftime(entry.journal.config["timeformat"]) body_wrapper = "\n" if entry.body else "" @@ -73,7 +75,7 @@ def export_entry(cls, entry, to_multifile=True): return f"{heading} {date_str} {entry.title}\n{newbody} " @classmethod - def export_journal(cls, journal): + def export_journal(cls, journal: Journal) -> str: """Returns a Markdown representation of an entire journal.""" out = [] year, month = -1, -1 diff --git a/jrnl/plugins/tag_exporter.py b/jrnl/plugins/tag_exporter.py index b9ab45b34..b9d40836c 100644 --- a/jrnl/plugins/tag_exporter.py +++ b/jrnl/plugins/tag_exporter.py @@ -1,6 +1,8 @@ # Copyright © 2012-2022 jrnl contributors # License: https://www.gnu.org/licenses/gpl-3.0.html +from jrnl.Entry import Entry +from jrnl.Journal import Journal from jrnl.plugins.text_exporter import TextExporter from jrnl.plugins.util import get_tags_count @@ -12,12 +14,12 @@ class TagExporter(TextExporter): extension = "tags" @classmethod - def export_entry(cls, entry): + def export_entry(cls, entry: Entry) -> str: """Returns a list of tags for a single entry.""" return ", ".join(entry.tags) @classmethod - def export_journal(cls, journal): + def export_journal(cls, journal: Journal) -> str: """Returns a list of tags and their frequency for an entire journal.""" tag_counts = get_tags_count(journal) result = "" diff --git a/jrnl/plugins/text_exporter.py b/jrnl/plugins/text_exporter.py index 4451cfef7..fe85f0022 100644 --- a/jrnl/plugins/text_exporter.py +++ b/jrnl/plugins/text_exporter.py @@ -6,6 +6,8 @@ import re import unicodedata +from jrnl.Entry import Entry +from jrnl.Journal import Journal from jrnl.messages import Message from jrnl.messages import MsgStyle from jrnl.messages import MsgText @@ -19,17 +21,17 @@ class TextExporter: extension = "txt" @classmethod - def export_entry(cls, entry): + def export_entry(cls, entry: Entry) -> str: """Returns a string representation of a single entry.""" return str(entry) @classmethod - def export_journal(cls, journal): + def export_journal(cls, journal: Journal) -> str: """Returns a string representation of an entire journal.""" return "\n".join(cls.export_entry(entry) for entry in journal) @classmethod - def write_file(cls, journal, path): + def write_file(cls, journal: Journal, path: str) -> str: """Exports a journal into a single file.""" export_str = cls.export_journal(journal) with open(path, "w", encoding="utf-8") as f: @@ -46,13 +48,13 @@ def write_file(cls, journal, path): return "" @classmethod - def make_filename(cls, entry): + def make_filename(cls, entry: Entry) -> str: return entry.date.strftime("%Y-%m-%d") + "_{}.{}".format( cls._slugify(str(entry.title)), cls.extension ) @classmethod - def write_files(cls, journal, path): + def write_files(cls, journal: Journal, path: str) -> str: """Exports a journal into individual files for each entry.""" for entry in journal.entries: entry_is_written = False @@ -82,7 +84,7 @@ def write_files(cls, journal, path): ) return "" - def _slugify(string): + def _slugify(string: str) -> str: """Slugifies a string. Based on public domain code from https://github.com/zacharyvoase/slugify """ @@ -92,7 +94,7 @@ def _slugify(string): return slug @classmethod - def export(cls, journal, output=None): + def export(cls, journal: Journal, output: str | None = None) -> str: """Exports to individual files if output is an existing path, or into a single file if output is a file name, or returns the exporter's representation as string if output is None.""" diff --git a/jrnl/plugins/util.py b/jrnl/plugins/util.py index 55ae73c58..0d6d08ed9 100644 --- a/jrnl/plugins/util.py +++ b/jrnl/plugins/util.py @@ -1,8 +1,10 @@ # Copyright © 2012-2022 jrnl contributors # License: https://www.gnu.org/licenses/gpl-3.0.html +from jrnl.Journal import Journal -def get_tags_count(journal): + +def get_tags_count(journal: Journal) -> set[tuple[int, str]]: """Returns a set of tuples (count, tag) for all tags present in the journal.""" # Astute reader: should the following line leave you as puzzled as me the first time # I came across this construction, worry not and embrace the ensuing moment of enlightment. @@ -12,7 +14,7 @@ def get_tags_count(journal): return tag_counts -def oxford_list(lst): +def oxford_list(lst: list) -> str: """Return Human-readable list of things obeying the object comma)""" lst = sorted(lst) if not lst: diff --git a/jrnl/plugins/xml_exporter.py b/jrnl/plugins/xml_exporter.py index a6c2fe79f..c041bbd6c 100644 --- a/jrnl/plugins/xml_exporter.py +++ b/jrnl/plugins/xml_exporter.py @@ -3,6 +3,8 @@ from xml.dom import minidom +from jrnl.Entry import Entry +from jrnl.Journal import Journal from jrnl.plugins.json_exporter import JSONExporter from jrnl.plugins.util import get_tags_count @@ -14,7 +16,9 @@ class XMLExporter(JSONExporter): extension = "xml" @classmethod - def export_entry(cls, entry, doc=None): + def export_entry( + cls, entry: Entry, doc: minidom.Document | None = None + ) -> minidom.Element | str: """Returns an XML representation of a single entry.""" doc_el = doc or minidom.Document() entry_el = doc_el.createElement("entry") @@ -29,7 +33,7 @@ def export_entry(cls, entry, doc=None): return entry_el @classmethod - def entry_to_xml(cls, entry, doc): + def entry_to_xml(cls, entry: Entry, doc: minidom.Document) -> minidom.Element: entry_el = doc.createElement("entry") entry_el.setAttribute("date", entry.date.isoformat()) if hasattr(entry, "uuid"): @@ -44,7 +48,7 @@ def entry_to_xml(cls, entry, doc): return entry_el @classmethod - def export_journal(cls, journal): + def export_journal(cls, journal: Journal) -> str: """Returns an XML representation of an entire journal.""" tags = get_tags_count(journal) doc = minidom.Document() diff --git a/jrnl/plugins/yaml_exporter.py b/jrnl/plugins/yaml_exporter.py index c97692ad5..bd815365f 100644 --- a/jrnl/plugins/yaml_exporter.py +++ b/jrnl/plugins/yaml_exporter.py @@ -4,7 +4,9 @@ import os import re +from jrnl.Entry import Entry from jrnl.exception import JrnlException +from jrnl.Journal import Journal from jrnl.messages import Message from jrnl.messages import MsgStyle from jrnl.messages import MsgText @@ -19,7 +21,7 @@ class YAMLExporter(TextExporter): extension = "md" @classmethod - def export_entry(cls, entry, to_multifile=True): + def export_entry(cls, entry: Entry, to_multifile: bool = True) -> str: """Returns a markdown representation of a single entry, with YAML front matter.""" if to_multifile is False: raise JrnlException(Message(MsgText.YamlMustBeDirectory, MsgStyle.ERROR)) @@ -124,6 +126,6 @@ def export_entry(cls, entry, to_multifile=True): ) @classmethod - def export_journal(cls, journal): + def export_journal(cls, journal: Journal): """Returns an error, as YAML export requires a directory as a target.""" raise JrnlException(Message(MsgText.YamlMustBeDirectory, MsgStyle.ERROR)) From 03c8f2d7a536fda95d22aadfc367e9c3ed6ab925 Mon Sep 17 00:00:00 2001 From: outa Date: Thu, 3 Nov 2022 21:29:58 +0100 Subject: [PATCH 4/5] Fix type-checking linter --- jrnl/FolderJournal.py | 7 +++++-- jrnl/jrnl.py | 34 +++++++++++++++++-------------- jrnl/plugins/dates_exporter.py | 11 ++++++---- jrnl/plugins/fancy_exporter.py | 11 ++++++---- jrnl/plugins/jrnl_importer.py | 7 +++++-- jrnl/plugins/json_exporter.py | 13 +++++++----- jrnl/plugins/markdown_exporter.py | 11 ++++++---- jrnl/plugins/tag_exporter.py | 12 +++++++---- jrnl/plugins/text_exporter.py | 19 +++++++++-------- jrnl/plugins/util.py | 7 +++++-- jrnl/plugins/xml_exporter.py | 13 +++++++----- jrnl/plugins/yaml_exporter.py | 11 ++++++---- 12 files changed, 97 insertions(+), 59 deletions(-) diff --git a/jrnl/FolderJournal.py b/jrnl/FolderJournal.py index 44fb48871..ab9547eda 100644 --- a/jrnl/FolderJournal.py +++ b/jrnl/FolderJournal.py @@ -4,10 +4,13 @@ import codecs import fnmatch import os +from typing import TYPE_CHECKING from jrnl import Journal from jrnl import time -from jrnl.Entry import Entry + +if TYPE_CHECKING: + from jrnl.Entry import Entry def get_files(journal_config: str) -> list[str]: @@ -82,7 +85,7 @@ def write(self) -> None: if os.stat(filename).st_size <= 0: os.remove(filename) - def delete_entries(self, entries_to_delete: list[Entry]) -> None: + def delete_entries(self, entries_to_delete: list["Entry"]) -> None: """Deletes specific entries from a journal.""" for entry in entries_to_delete: self.entries.remove(entry) diff --git a/jrnl/jrnl.py b/jrnl/jrnl.py index 7f8fcc6ed..39c25b3f7 100644 --- a/jrnl/jrnl.py +++ b/jrnl/jrnl.py @@ -2,7 +2,7 @@ # License: https://www.gnu.org/licenses/gpl-3.0.html import logging import sys -from argparse import Namespace +from typing import TYPE_CHECKING from jrnl import install from jrnl import plugins @@ -13,7 +13,6 @@ from jrnl.config import scope_config from jrnl.editor import get_text_from_editor from jrnl.editor import get_text_from_stdin -from jrnl.Entry import Entry from jrnl.exception import JrnlException from jrnl.Journal import Journal from jrnl.Journal import open_journal @@ -25,8 +24,13 @@ from jrnl.override import apply_overrides from jrnl.path import expand_path +if TYPE_CHECKING: + from argparse import Namespace -def run(args: Namespace): + from jrnl.Entry import Entry + + +def run(args: "Namespace"): """ Flow: 1. Run standalone command if it doesn't require config (help, version, etc), then exit @@ -74,7 +78,7 @@ def run(args: Namespace): search_mode(**kwargs) -def _is_write_mode(args: Namespace, config: dict, **kwargs) -> bool: +def _is_write_mode(args: "Namespace", config: dict, **kwargs) -> bool: """Determines if we are in write mode (as opposed to search mode)""" # Are any search filters present? If so, then search mode. write_mode = not any( @@ -115,7 +119,7 @@ def _is_write_mode(args: Namespace, config: dict, **kwargs) -> bool: return write_mode -def write_mode(args: Namespace, config: dict, journal: Journal, **kwargs) -> None: +def write_mode(args: "Namespace", config: dict, journal: Journal, **kwargs) -> None: """ Gets input from the user to write to the journal 1. Check for input from cli @@ -159,7 +163,7 @@ def write_mode(args: Namespace, config: dict, journal: Journal, **kwargs) -> Non logging.debug("Write mode: completed journal.write()") -def search_mode(args: Namespace, journal: Journal, **kwargs) -> None: +def search_mode(args: "Namespace", journal: Journal, **kwargs) -> None: """ Search for entries in a journal, then either: 1. Send them to configured editor for user manipulation (and also @@ -251,7 +255,7 @@ def _get_editor_template(config: dict, **kwargs) -> str: return template -def _has_search_args(args: Namespace) -> bool: +def _has_search_args(args: "Namespace") -> bool: return any( ( args.on_date, @@ -271,7 +275,7 @@ def _has_search_args(args: Namespace) -> bool: ) -def _filter_journal_entries(args: Namespace, journal: Journal, **kwargs) -> None: +def _filter_journal_entries(args: "Namespace", journal: Journal, **kwargs) -> None: """Filter journal entries in-place based upon search args""" if args.on_date: args.start_date = args.end_date = args.on_date @@ -296,7 +300,7 @@ def _filter_journal_entries(args: Namespace, journal: Journal, **kwargs) -> None journal.limit(args.limit) -def _print_entries_found_count(count: int, args: Namespace) -> None: +def _print_entries_found_count(count: int, args: "Namespace") -> None: if count == 0: if args.edit or args.change_time: print_msg(Message(MsgText.NothingToModify, MsgStyle.WARNING)) @@ -317,13 +321,13 @@ def _print_entries_found_count(count: int, args: Namespace) -> None: print_msg(Message(my_msg, MsgStyle.NORMAL, {"num": count})) -def _other_entries(journal: Journal, entries: list[Entry]) -> list[Entry]: +def _other_entries(journal: Journal, entries: list["Entry"]) -> list["Entry"]: """Find entries that are not in journal""" return [e for e in entries if e not in journal.entries] def _edit_search_results( - config: dict, journal: Journal, old_entries: list[Entry], **kwargs + config: dict, journal: Journal, old_entries: list["Entry"], **kwargs ) -> None: """ 1. Send the given journal entries to the user-configured editor @@ -404,7 +408,7 @@ def _get_predit_stats(journal: Journal) -> dict[str, int]: def _delete_search_results( - journal: Journal, old_entries: list[Entry], **kwargs + journal: Journal, old_entries: list["Entry"], **kwargs ) -> None: entries_to_delete = journal.prompt_action_entries(MsgText.DeleteEntryQuestion) @@ -416,9 +420,9 @@ def _delete_search_results( def _change_time_search_results( - args: Namespace, + args: "Namespace", journal: Journal, - old_entries: list[Entry], + old_entries: list["Entry"], no_prompt: bool = False, **kwargs ) -> None: @@ -444,7 +448,7 @@ def _change_time_search_results( journal.write() -def _display_search_results(args: Namespace, journal: Journal, **kwargs) -> None: +def _display_search_results(args: "Namespace", journal: Journal, **kwargs) -> None: # Get export format from config file if not provided at the command line args.export = args.export or kwargs["config"].get("display_format") diff --git a/jrnl/plugins/dates_exporter.py b/jrnl/plugins/dates_exporter.py index 778ec06fb..920c6ff98 100644 --- a/jrnl/plugins/dates_exporter.py +++ b/jrnl/plugins/dates_exporter.py @@ -2,11 +2,14 @@ # License: https://www.gnu.org/licenses/gpl-3.0.html from collections import Counter +from typing import TYPE_CHECKING -from jrnl.Entry import Entry -from jrnl.Journal import Journal from jrnl.plugins.text_exporter import TextExporter +if TYPE_CHECKING: + from jrnl.Entry import Entry + from jrnl.Journal import Journal + class DatesExporter(TextExporter): """This Exporter lists dates and their respective counts, for heatingmapping etc.""" @@ -15,11 +18,11 @@ class DatesExporter(TextExporter): extension = "dates" @classmethod - def export_entry(cls, entry: Entry): + def export_entry(cls, entry: "Entry"): raise NotImplementedError @classmethod - def export_journal(cls, journal: Journal) -> str: + def export_journal(cls, journal: "Journal") -> str: """Returns dates and their frequencies for an entire journal.""" date_counts = Counter() for entry in journal.entries: diff --git a/jrnl/plugins/fancy_exporter.py b/jrnl/plugins/fancy_exporter.py index 253a0d616..50189ab31 100644 --- a/jrnl/plugins/fancy_exporter.py +++ b/jrnl/plugins/fancy_exporter.py @@ -4,15 +4,18 @@ import logging import os from textwrap import TextWrapper +from typing import TYPE_CHECKING -from jrnl.Entry import Entry from jrnl.exception import JrnlException -from jrnl.Journal import Journal from jrnl.messages import Message from jrnl.messages import MsgStyle from jrnl.messages import MsgText from jrnl.plugins.text_exporter import TextExporter +if TYPE_CHECKING: + from jrnl.Entry import Entry + from jrnl.Journal import Journal + class FancyExporter(TextExporter): """This Exporter can convert entries and journals into text with unicode box drawing characters.""" @@ -37,7 +40,7 @@ class FancyExporter(TextExporter): border_m = "┘" @classmethod - def export_entry(cls, entry: Entry) -> str: + def export_entry(cls, entry: "Entry") -> str: """Returns a fancy unicode representation of a single entry.""" date_str = entry.date.strftime(entry.journal.config["timeformat"]) @@ -102,7 +105,7 @@ def export_journal(cls, journal) -> str: return "\n".join(cls.export_entry(entry) for entry in journal) -def check_provided_linewrap_viability(linewrap: int, card: list[str], journal: Journal): +def check_provided_linewrap_viability(linewrap: int, card: list[str], journal: "Journal"): if len(card[0]) > linewrap: width_violation = len(card[0]) - linewrap raise JrnlException( diff --git a/jrnl/plugins/jrnl_importer.py b/jrnl/plugins/jrnl_importer.py index 907ece4ca..e93792de6 100644 --- a/jrnl/plugins/jrnl_importer.py +++ b/jrnl/plugins/jrnl_importer.py @@ -2,14 +2,17 @@ # License: https://www.gnu.org/licenses/gpl-3.0.html import sys +from typing import TYPE_CHECKING from jrnl.exception import JrnlException -from jrnl.Journal import Journal from jrnl.messages import Message from jrnl.messages import MsgStyle from jrnl.messages import MsgText from jrnl.output import print_msg +if TYPE_CHECKING: + from jrnl.Journal import Journal + class JRNLImporter: """This plugin imports entries from other jrnl files.""" @@ -17,7 +20,7 @@ class JRNLImporter: names = ["jrnl"] @staticmethod - def import_(journal: Journal, input: str | None = None) -> None: + def import_(journal: "Journal", input: str | None = None) -> None: """Imports from an existing file if input is specified, and standard input otherwise.""" old_cnt = len(journal.entries) diff --git a/jrnl/plugins/json_exporter.py b/jrnl/plugins/json_exporter.py index dd0a4a4d2..1a3a5670c 100644 --- a/jrnl/plugins/json_exporter.py +++ b/jrnl/plugins/json_exporter.py @@ -2,12 +2,15 @@ # License: https://www.gnu.org/licenses/gpl-3.0.html import json +from typing import TYPE_CHECKING -from jrnl.Entry import Entry -from jrnl.Journal import Journal from jrnl.plugins.text_exporter import TextExporter from jrnl.plugins.util import get_tags_count +if TYPE_CHECKING: + from jrnl.Entry import Entry + from jrnl.Journal import Journal + class JSONExporter(TextExporter): """This Exporter can convert entries and journals into json.""" @@ -16,7 +19,7 @@ class JSONExporter(TextExporter): extension = "json" @classmethod - def entry_to_dict(cls, entry: Entry) -> dict: + def entry_to_dict(cls, entry: "Entry") -> dict: entry_dict = { "title": entry.title, "body": entry.body, @@ -51,12 +54,12 @@ def entry_to_dict(cls, entry: Entry) -> dict: return entry_dict @classmethod - def export_entry(cls, entry: Entry) -> str: + def export_entry(cls, entry: "Entry") -> str: """Returns a json representation of a single entry.""" return json.dumps(cls.entry_to_dict(entry), indent=2) + "\n" @classmethod - def export_journal(cls, journal: Journal) -> str: + def export_journal(cls, journal: "Journal") -> str: """Returns a json representation of an entire journal.""" tags = get_tags_count(journal) result = { diff --git a/jrnl/plugins/markdown_exporter.py b/jrnl/plugins/markdown_exporter.py index 860646ff8..8f0d07b48 100644 --- a/jrnl/plugins/markdown_exporter.py +++ b/jrnl/plugins/markdown_exporter.py @@ -3,15 +3,18 @@ import os import re +from typing import TYPE_CHECKING -from jrnl.Entry import Entry -from jrnl.Journal import Journal from jrnl.messages import Message from jrnl.messages import MsgStyle from jrnl.messages import MsgText from jrnl.output import print_msg from jrnl.plugins.text_exporter import TextExporter +if TYPE_CHECKING: + from jrnl.Entry import Entry + from jrnl.Journal import Journal + class MarkdownExporter(TextExporter): """This Exporter can convert entries and journals into Markdown.""" @@ -20,7 +23,7 @@ class MarkdownExporter(TextExporter): extension = "md" @classmethod - def export_entry(cls, entry: Entry, to_multifile: bool = True) -> str: + def export_entry(cls, entry: "Entry", to_multifile: bool = True) -> str: """Returns a markdown representation of a single entry.""" date_str = entry.date.strftime(entry.journal.config["timeformat"]) body_wrapper = "\n" if entry.body else "" @@ -75,7 +78,7 @@ def export_entry(cls, entry: Entry, to_multifile: bool = True) -> str: return f"{heading} {date_str} {entry.title}\n{newbody} " @classmethod - def export_journal(cls, journal: Journal) -> str: + def export_journal(cls, journal: "Journal") -> str: """Returns a Markdown representation of an entire journal.""" out = [] year, month = -1, -1 diff --git a/jrnl/plugins/tag_exporter.py b/jrnl/plugins/tag_exporter.py index b9d40836c..250f05c75 100644 --- a/jrnl/plugins/tag_exporter.py +++ b/jrnl/plugins/tag_exporter.py @@ -1,11 +1,15 @@ # Copyright © 2012-2022 jrnl contributors # License: https://www.gnu.org/licenses/gpl-3.0.html -from jrnl.Entry import Entry -from jrnl.Journal import Journal +from typing import TYPE_CHECKING + from jrnl.plugins.text_exporter import TextExporter from jrnl.plugins.util import get_tags_count +if TYPE_CHECKING: + from jrnl.Entry import Entry + from jrnl.Journal import Journal + class TagExporter(TextExporter): """This Exporter can lists the tags for entries and journals, exported as a plain text file.""" @@ -14,12 +18,12 @@ class TagExporter(TextExporter): extension = "tags" @classmethod - def export_entry(cls, entry: Entry) -> str: + def export_entry(cls, entry: "Entry") -> str: """Returns a list of tags for a single entry.""" return ", ".join(entry.tags) @classmethod - def export_journal(cls, journal: Journal) -> str: + def export_journal(cls, journal: "Journal") -> str: """Returns a list of tags and their frequency for an entire journal.""" tag_counts = get_tags_count(journal) result = "" diff --git a/jrnl/plugins/text_exporter.py b/jrnl/plugins/text_exporter.py index fe85f0022..7f2321e70 100644 --- a/jrnl/plugins/text_exporter.py +++ b/jrnl/plugins/text_exporter.py @@ -5,14 +5,17 @@ import os import re import unicodedata +from typing import TYPE_CHECKING -from jrnl.Entry import Entry -from jrnl.Journal import Journal from jrnl.messages import Message from jrnl.messages import MsgStyle from jrnl.messages import MsgText from jrnl.output import print_msg +if TYPE_CHECKING: + from jrnl.Entry import Entry + from jrnl.Journal import Journal + class TextExporter: """This Exporter can convert entries and journals into text files.""" @@ -21,17 +24,17 @@ class TextExporter: extension = "txt" @classmethod - def export_entry(cls, entry: Entry) -> str: + def export_entry(cls, entry: "Entry") -> str: """Returns a string representation of a single entry.""" return str(entry) @classmethod - def export_journal(cls, journal: Journal) -> str: + def export_journal(cls, journal: "Journal") -> str: """Returns a string representation of an entire journal.""" return "\n".join(cls.export_entry(entry) for entry in journal) @classmethod - def write_file(cls, journal: Journal, path: str) -> str: + def write_file(cls, journal: "Journal", path: str) -> str: """Exports a journal into a single file.""" export_str = cls.export_journal(journal) with open(path, "w", encoding="utf-8") as f: @@ -48,13 +51,13 @@ def write_file(cls, journal: Journal, path: str) -> str: return "" @classmethod - def make_filename(cls, entry: Entry) -> str: + def make_filename(cls, entry: "Entry") -> str: return entry.date.strftime("%Y-%m-%d") + "_{}.{}".format( cls._slugify(str(entry.title)), cls.extension ) @classmethod - def write_files(cls, journal: Journal, path: str) -> str: + def write_files(cls, journal: "Journal", path: str) -> str: """Exports a journal into individual files for each entry.""" for entry in journal.entries: entry_is_written = False @@ -94,7 +97,7 @@ def _slugify(string: str) -> str: return slug @classmethod - def export(cls, journal: Journal, output: str | None = None) -> str: + def export(cls, journal: "Journal", output: str | None = None) -> str: """Exports to individual files if output is an existing path, or into a single file if output is a file name, or returns the exporter's representation as string if output is None.""" diff --git a/jrnl/plugins/util.py b/jrnl/plugins/util.py index 0d6d08ed9..009651e98 100644 --- a/jrnl/plugins/util.py +++ b/jrnl/plugins/util.py @@ -1,10 +1,13 @@ # Copyright © 2012-2022 jrnl contributors # License: https://www.gnu.org/licenses/gpl-3.0.html -from jrnl.Journal import Journal +from typing import TYPE_CHECKING +if TYPE_CHECKING: + from jrnl.Journal import Journal -def get_tags_count(journal: Journal) -> set[tuple[int, str]]: + +def get_tags_count(journal: "Journal") -> set[tuple[int, str]]: """Returns a set of tuples (count, tag) for all tags present in the journal.""" # Astute reader: should the following line leave you as puzzled as me the first time # I came across this construction, worry not and embrace the ensuing moment of enlightment. diff --git a/jrnl/plugins/xml_exporter.py b/jrnl/plugins/xml_exporter.py index c041bbd6c..61b6b2971 100644 --- a/jrnl/plugins/xml_exporter.py +++ b/jrnl/plugins/xml_exporter.py @@ -1,13 +1,16 @@ # Copyright © 2012-2022 jrnl contributors # License: https://www.gnu.org/licenses/gpl-3.0.html +from typing import TYPE_CHECKING from xml.dom import minidom -from jrnl.Entry import Entry -from jrnl.Journal import Journal from jrnl.plugins.json_exporter import JSONExporter from jrnl.plugins.util import get_tags_count +if TYPE_CHECKING: + from jrnl.Entry import Entry + from jrnl.Journal import Journal + class XMLExporter(JSONExporter): """This Exporter can convert entries and journals into XML.""" @@ -17,7 +20,7 @@ class XMLExporter(JSONExporter): @classmethod def export_entry( - cls, entry: Entry, doc: minidom.Document | None = None + cls, entry: "Entry", doc: minidom.Document | None = None ) -> minidom.Element | str: """Returns an XML representation of a single entry.""" doc_el = doc or minidom.Document() @@ -33,7 +36,7 @@ def export_entry( return entry_el @classmethod - def entry_to_xml(cls, entry: Entry, doc: minidom.Document) -> minidom.Element: + def entry_to_xml(cls, entry: "Entry", doc: minidom.Document) -> minidom.Element: entry_el = doc.createElement("entry") entry_el.setAttribute("date", entry.date.isoformat()) if hasattr(entry, "uuid"): @@ -48,7 +51,7 @@ def entry_to_xml(cls, entry: Entry, doc: minidom.Document) -> minidom.Element: return entry_el @classmethod - def export_journal(cls, journal: Journal) -> str: + def export_journal(cls, journal: "Journal") -> str: """Returns an XML representation of an entire journal.""" tags = get_tags_count(journal) doc = minidom.Document() diff --git a/jrnl/plugins/yaml_exporter.py b/jrnl/plugins/yaml_exporter.py index bd815365f..5f5d5b212 100644 --- a/jrnl/plugins/yaml_exporter.py +++ b/jrnl/plugins/yaml_exporter.py @@ -3,16 +3,19 @@ import os import re +from typing import TYPE_CHECKING -from jrnl.Entry import Entry from jrnl.exception import JrnlException -from jrnl.Journal import Journal from jrnl.messages import Message from jrnl.messages import MsgStyle from jrnl.messages import MsgText from jrnl.output import print_msg from jrnl.plugins.text_exporter import TextExporter +if TYPE_CHECKING: + from jrnl.Entry import Entry + from jrnl.Journal import Journal + class YAMLExporter(TextExporter): """This Exporter can convert entries and journals into Markdown formatted text with YAML front matter.""" @@ -21,7 +24,7 @@ class YAMLExporter(TextExporter): extension = "md" @classmethod - def export_entry(cls, entry: Entry, to_multifile: bool = True) -> str: + def export_entry(cls, entry: "Entry", to_multifile: bool = True) -> str: """Returns a markdown representation of a single entry, with YAML front matter.""" if to_multifile is False: raise JrnlException(Message(MsgText.YamlMustBeDirectory, MsgStyle.ERROR)) @@ -126,6 +129,6 @@ def export_entry(cls, entry: Entry, to_multifile: bool = True) -> str: ) @classmethod - def export_journal(cls, journal: Journal): + def export_journal(cls, journal: "Journal"): """Returns an error, as YAML export requires a directory as a target.""" raise JrnlException(Message(MsgText.YamlMustBeDirectory, MsgStyle.ERROR)) From e964ecf619b9fb989653e6b7a82ccaf5a8d92327 Mon Sep 17 00:00:00 2001 From: Jonathan Wren Date: Sat, 5 Nov 2022 15:24:40 -0700 Subject: [PATCH 5/5] Update jrnl/DayOneJournal.py --- jrnl/DayOneJournal.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jrnl/DayOneJournal.py b/jrnl/DayOneJournal.py index 4e827cedc..4806bdbf6 100644 --- a/jrnl/DayOneJournal.py +++ b/jrnl/DayOneJournal.py @@ -210,7 +210,7 @@ def parse_editable_str(self, edited: str) -> None: entries_from_editor = self._parse(edited) for entry in entries_from_editor: - self._get_and_remove_uuid_from_entry(entry) + entry = self._get_and_remove_uuid_from_entry(entry) # Remove deleted entries edited_uuids = [e.uuid for e in entries_from_editor]