Add remaining type hints

This commit is contained in:
outa 2022-10-12 12:51:09 +02:00
parent c87af82366
commit 029ba446d8
11 changed files with 52 additions and 29 deletions

View file

@ -1,6 +1,8 @@
# Copyright © 2012-2022 jrnl contributors # Copyright © 2012-2022 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html # License: https://www.gnu.org/licenses/gpl-3.0.html
from typing import Type
from jrnl.plugins.dates_exporter import DatesExporter from jrnl.plugins.dates_exporter import DatesExporter
from jrnl.plugins.fancy_exporter import FancyExporter from jrnl.plugins.fancy_exporter import FancyExporter
from jrnl.plugins.jrnl_importer import JRNLImporter from jrnl.plugins.jrnl_importer import JRNLImporter
@ -32,14 +34,14 @@ EXPORT_FORMATS = sorted(__exporter_types.keys())
IMPORT_FORMATS = sorted(__importer_types.keys()) IMPORT_FORMATS = sorted(__importer_types.keys())
def get_exporter(format): def get_exporter(format: str) -> Type[TextExporter] | None:
for exporter in __exporters: for exporter in __exporters:
if hasattr(exporter, "names") and format in exporter.names: if hasattr(exporter, "names") and format in exporter.names:
return exporter return exporter
return None return None
def get_importer(format): def get_importer(format: str) -> Type[JRNLImporter] | None:
for importer in __importers: for importer in __importers:
if hasattr(importer, "names") and format in importer.names: if hasattr(importer, "names") and format in importer.names:
return importer return importer

View file

@ -3,6 +3,8 @@
from collections import Counter from collections import Counter
from jrnl.Entry import Entry
from jrnl.Journal import Journal
from jrnl.plugins.text_exporter import TextExporter from jrnl.plugins.text_exporter import TextExporter
@ -13,11 +15,11 @@ class DatesExporter(TextExporter):
extension = "dates" extension = "dates"
@classmethod @classmethod
def export_entry(cls, entry): def export_entry(cls, entry: Entry):
raise NotImplementedError raise NotImplementedError
@classmethod @classmethod
def export_journal(cls, journal): def export_journal(cls, journal: Journal) -> str:
"""Returns dates and their frequencies for an entire journal.""" """Returns dates and their frequencies for an entire journal."""
date_counts = Counter() date_counts = Counter()
for entry in journal.entries: for entry in journal.entries:

View file

@ -5,7 +5,9 @@ import logging
import os import os
from textwrap import TextWrapper from textwrap import TextWrapper
from jrnl.Entry import Entry
from jrnl.exception import JrnlException from jrnl.exception import JrnlException
from jrnl.Journal import Journal
from jrnl.messages import Message from jrnl.messages import Message
from jrnl.messages import MsgStyle from jrnl.messages import MsgStyle
from jrnl.messages import MsgText from jrnl.messages import MsgText
@ -35,7 +37,7 @@ class FancyExporter(TextExporter):
border_m = "" border_m = ""
@classmethod @classmethod
def export_entry(cls, entry): def export_entry(cls, entry: Entry) -> str:
"""Returns a fancy unicode representation of a single entry.""" """Returns a fancy unicode representation of a single entry."""
date_str = entry.date.strftime(entry.journal.config["timeformat"]) date_str = entry.date.strftime(entry.journal.config["timeformat"])
@ -95,12 +97,12 @@ class FancyExporter(TextExporter):
return "\n".join(card) return "\n".join(card)
@classmethod @classmethod
def export_journal(cls, journal): def export_journal(cls, journal) -> str:
"""Returns a unicode representation of an entire journal.""" """Returns a unicode representation of an entire journal."""
return "\n".join(cls.export_entry(entry) for entry in 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: if len(card[0]) > linewrap:
width_violation = len(card[0]) - linewrap width_violation = len(card[0]) - linewrap
raise JrnlException( raise JrnlException(

View file

@ -4,6 +4,7 @@
import sys import sys
from jrnl.exception import JrnlException from jrnl.exception import JrnlException
from jrnl.Journal import Journal
from jrnl.messages import Message from jrnl.messages import Message
from jrnl.messages import MsgStyle from jrnl.messages import MsgStyle
from jrnl.messages import MsgText from jrnl.messages import MsgText
@ -16,7 +17,7 @@ class JRNLImporter:
names = ["jrnl"] names = ["jrnl"]
@staticmethod @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 """Imports from an existing file if input is specified, and
standard input otherwise.""" standard input otherwise."""
old_cnt = len(journal.entries) old_cnt = len(journal.entries)

View file

@ -3,6 +3,8 @@
import json import json
from jrnl.Entry import Entry
from jrnl.Journal import Journal
from jrnl.plugins.text_exporter import TextExporter from jrnl.plugins.text_exporter import TextExporter
from jrnl.plugins.util import get_tags_count from jrnl.plugins.util import get_tags_count
@ -14,7 +16,7 @@ class JSONExporter(TextExporter):
extension = "json" extension = "json"
@classmethod @classmethod
def entry_to_dict(cls, entry): def entry_to_dict(cls, entry: Entry) -> dict:
entry_dict = { entry_dict = {
"title": entry.title, "title": entry.title,
"body": entry.body, "body": entry.body,
@ -49,12 +51,12 @@ class JSONExporter(TextExporter):
return entry_dict return entry_dict
@classmethod @classmethod
def export_entry(cls, entry): def export_entry(cls, entry: Entry) -> str:
"""Returns a json representation of a single entry.""" """Returns a json representation of a single entry."""
return json.dumps(cls.entry_to_dict(entry), indent=2) + "\n" return json.dumps(cls.entry_to_dict(entry), indent=2) + "\n"
@classmethod @classmethod
def export_journal(cls, journal): def export_journal(cls, journal: Journal) -> str:
"""Returns a json representation of an entire journal.""" """Returns a json representation of an entire journal."""
tags = get_tags_count(journal) tags = get_tags_count(journal)
result = { result = {

View file

@ -4,6 +4,8 @@
import os import os
import re import re
from jrnl.Entry import Entry
from jrnl.Journal import Journal
from jrnl.messages import Message from jrnl.messages import Message
from jrnl.messages import MsgStyle from jrnl.messages import MsgStyle
from jrnl.messages import MsgText from jrnl.messages import MsgText
@ -18,7 +20,7 @@ class MarkdownExporter(TextExporter):
extension = "md" extension = "md"
@classmethod @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.""" """Returns a markdown representation of a single entry."""
date_str = entry.date.strftime(entry.journal.config["timeformat"]) date_str = entry.date.strftime(entry.journal.config["timeformat"])
body_wrapper = "\n" if entry.body else "" body_wrapper = "\n" if entry.body else ""
@ -73,7 +75,7 @@ class MarkdownExporter(TextExporter):
return f"{heading} {date_str} {entry.title}\n{newbody} " return f"{heading} {date_str} {entry.title}\n{newbody} "
@classmethod @classmethod
def export_journal(cls, journal): def export_journal(cls, journal: Journal) -> str:
"""Returns a Markdown representation of an entire journal.""" """Returns a Markdown representation of an entire journal."""
out = [] out = []
year, month = -1, -1 year, month = -1, -1

View file

@ -1,6 +1,8 @@
# Copyright © 2012-2022 jrnl contributors # Copyright © 2012-2022 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html # 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.text_exporter import TextExporter
from jrnl.plugins.util import get_tags_count from jrnl.plugins.util import get_tags_count
@ -12,12 +14,12 @@ class TagExporter(TextExporter):
extension = "tags" extension = "tags"
@classmethod @classmethod
def export_entry(cls, entry): def export_entry(cls, entry: Entry) -> str:
"""Returns a list of tags for a single entry.""" """Returns a list of tags for a single entry."""
return ", ".join(entry.tags) return ", ".join(entry.tags)
@classmethod @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.""" """Returns a list of tags and their frequency for an entire journal."""
tag_counts = get_tags_count(journal) tag_counts = get_tags_count(journal)
result = "" result = ""

View file

@ -6,6 +6,8 @@ import os
import re import re
import unicodedata import unicodedata
from jrnl.Entry import Entry
from jrnl.Journal import Journal
from jrnl.messages import Message from jrnl.messages import Message
from jrnl.messages import MsgStyle from jrnl.messages import MsgStyle
from jrnl.messages import MsgText from jrnl.messages import MsgText
@ -19,17 +21,17 @@ class TextExporter:
extension = "txt" extension = "txt"
@classmethod @classmethod
def export_entry(cls, entry): def export_entry(cls, entry: Entry) -> str:
"""Returns a string representation of a single entry.""" """Returns a string representation of a single entry."""
return str(entry) return str(entry)
@classmethod @classmethod
def export_journal(cls, journal): def export_journal(cls, journal: Journal) -> str:
"""Returns a string representation of an entire journal.""" """Returns a string representation of an entire journal."""
return "\n".join(cls.export_entry(entry) for entry in journal) return "\n".join(cls.export_entry(entry) for entry in journal)
@classmethod @classmethod
def write_file(cls, journal, path): def write_file(cls, journal: Journal, path: str) -> str:
"""Exports a journal into a single file.""" """Exports a journal into a single file."""
export_str = cls.export_journal(journal) export_str = cls.export_journal(journal)
with open(path, "w", encoding="utf-8") as f: with open(path, "w", encoding="utf-8") as f:
@ -46,13 +48,13 @@ class TextExporter:
return "" return ""
@classmethod @classmethod
def make_filename(cls, entry): def make_filename(cls, entry: Entry) -> str:
return entry.date.strftime("%Y-%m-%d") + "_{}.{}".format( return entry.date.strftime("%Y-%m-%d") + "_{}.{}".format(
cls._slugify(str(entry.title)), cls.extension cls._slugify(str(entry.title)), cls.extension
) )
@classmethod @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.""" """Exports a journal into individual files for each entry."""
for entry in journal.entries: for entry in journal.entries:
entry_is_written = False entry_is_written = False
@ -82,7 +84,7 @@ class TextExporter:
) )
return "" return ""
def _slugify(string): def _slugify(string: str) -> str:
"""Slugifies a string. """Slugifies a string.
Based on public domain code from https://github.com/zacharyvoase/slugify Based on public domain code from https://github.com/zacharyvoase/slugify
""" """
@ -92,7 +94,7 @@ class TextExporter:
return slug return slug
@classmethod @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 """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 a single file if output is a file name, or returns the exporter's
representation as string if output is None.""" representation as string if output is None."""

View file

@ -1,8 +1,10 @@
# Copyright © 2012-2022 jrnl contributors # Copyright © 2012-2022 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html # 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.""" """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 # 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. # 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 return tag_counts
def oxford_list(lst): def oxford_list(lst: list) -> str:
"""Return Human-readable list of things obeying the object comma)""" """Return Human-readable list of things obeying the object comma)"""
lst = sorted(lst) lst = sorted(lst)
if not lst: if not lst:

View file

@ -3,6 +3,8 @@
from xml.dom import minidom 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.json_exporter import JSONExporter
from jrnl.plugins.util import get_tags_count from jrnl.plugins.util import get_tags_count
@ -14,7 +16,9 @@ class XMLExporter(JSONExporter):
extension = "xml" extension = "xml"
@classmethod @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.""" """Returns an XML representation of a single entry."""
doc_el = doc or minidom.Document() doc_el = doc or minidom.Document()
entry_el = doc_el.createElement("entry") entry_el = doc_el.createElement("entry")
@ -29,7 +33,7 @@ class XMLExporter(JSONExporter):
return entry_el return entry_el
@classmethod @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 = doc.createElement("entry")
entry_el.setAttribute("date", entry.date.isoformat()) entry_el.setAttribute("date", entry.date.isoformat())
if hasattr(entry, "uuid"): if hasattr(entry, "uuid"):
@ -44,7 +48,7 @@ class XMLExporter(JSONExporter):
return entry_el return entry_el
@classmethod @classmethod
def export_journal(cls, journal): def export_journal(cls, journal: Journal) -> str:
"""Returns an XML representation of an entire journal.""" """Returns an XML representation of an entire journal."""
tags = get_tags_count(journal) tags = get_tags_count(journal)
doc = minidom.Document() doc = minidom.Document()

View file

@ -4,7 +4,9 @@
import os import os
import re import re
from jrnl.Entry import Entry
from jrnl.exception import JrnlException from jrnl.exception import JrnlException
from jrnl.Journal import Journal
from jrnl.messages import Message from jrnl.messages import Message
from jrnl.messages import MsgStyle from jrnl.messages import MsgStyle
from jrnl.messages import MsgText from jrnl.messages import MsgText
@ -19,7 +21,7 @@ class YAMLExporter(TextExporter):
extension = "md" extension = "md"
@classmethod @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.""" """Returns a markdown representation of a single entry, with YAML front matter."""
if to_multifile is False: if to_multifile is False:
raise JrnlException(Message(MsgText.YamlMustBeDirectory, MsgStyle.ERROR)) raise JrnlException(Message(MsgText.YamlMustBeDirectory, MsgStyle.ERROR))
@ -124,6 +126,6 @@ class YAMLExporter(TextExporter):
) )
@classmethod @classmethod
def export_journal(cls, journal): def export_journal(cls, journal: Journal):
"""Returns an error, as YAML export requires a directory as a target.""" """Returns an error, as YAML export requires a directory as a target."""
raise JrnlException(Message(MsgText.YamlMustBeDirectory, MsgStyle.ERROR)) raise JrnlException(Message(MsgText.YamlMustBeDirectory, MsgStyle.ERROR))