Skip to content

Commit

Permalink
chore: basic typing annotations (#428)
Browse files Browse the repository at this point in the history
Still contains some Any use, but progress is progress nevertheless.
  • Loading branch information
hairmare authored Mar 25, 2024
1 parent 274cfa3 commit b405d64
Show file tree
Hide file tree
Showing 6 changed files with 456 additions and 425 deletions.
4 changes: 1 addition & 3 deletions docs/gen_ref_pages.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@

parts = list(module_path.parts)

if parts[-1] == "__init__":
continue
elif parts[-1] == "__main__":
if parts[-1] == "__init__" or parts[-1] == "__main__":
continue

with mkdocs_gen_files.open(full_doc_path, "w") as fd:
Expand Down
File renamed without changes.
821 changes: 422 additions & 399 deletions poetry.lock

Large diffs are not rendered by default.

7 changes: 6 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,18 @@ mkdocs-literate-nav = "^0.6.1"
mkdocs-section-index = "^0.3.8"
mkdocs-autorefs = "^1.0.1"
mkdocstrings = {extras = ["python"], version = "^0.24.1"}
pytest-mypy = "^0.10.3"
types-openpyxl = "^3.1.0.20240311"
types-python-dateutil = "^2.9.0.20240316"
types-pytz = "^2024.1.0.20240203"
types-tqdm = "^4.66.0.20240106"

[tool.isort]
profile = "black"

[tool.pytest.ini_options]
minversion = "7.4"
addopts = "--doctest-modules --cov=suisa_sendemeldung --pylint --cov-fail-under=100 --ignore=docs/"
addopts = "--doctest-modules --cov=suisa_sendemeldung --pylint --cov-fail-under=100 --ignore=docs/ --mypy"
filterwarnings = [
"ignore::DeprecationWarning:pylint",
]
Expand Down
47 changes: 26 additions & 21 deletions suisa_sendemeldung/suisa_sendemeldung.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

from __future__ import annotations

from argparse import Namespace as ArgparseNamespace
from csv import reader, writer
from datetime import date, datetime, timedelta
from email.encoders import encode_base64
Expand All @@ -18,15 +19,17 @@
from os.path import basename, expanduser
from smtplib import SMTP
from string import Template
from typing import Any

import cridlib
import pytz
from babel.dates import format_date
from configargparse import ArgumentParser
from configargparse import ArgumentParser # type: ignore[import-untyped]
from dateutil.relativedelta import relativedelta
from iso3901 import ISRC
from openpyxl import Workbook
from openpyxl.styles import Border, Font, PatternFill, Side
from openpyxl.worksheet.worksheet import Worksheet
from tqdm import tqdm

from .acrclient import ACRClient
Expand Down Expand Up @@ -80,7 +83,7 @@
"""


def validate_arguments(parser, args):
def validate_arguments(parser: ArgumentParser, args: ArgparseNamespace) -> None:
"""Validate the arguments provided to the script.
After this function we are sure that there are no conflicts in the arguments.
Expand Down Expand Up @@ -123,7 +126,7 @@ def validate_arguments(parser, args):
parser.error("\n- " + "\n- ".join(msgs))


def get_arguments(parser: ArgumentParser): # pragma: no cover
def get_arguments(parser: ArgumentParser) -> ArgparseNamespace: # pragma: no cover
"""Create :class:`ArgumentParser` with arguments.
Arguments:
Expand Down Expand Up @@ -292,7 +295,7 @@ def get_arguments(parser: ArgumentParser): # pragma: no cover
return args


def parse_date(args):
def parse_date(args: ArgparseNamespace) -> tuple[date, date]:
"""Parse date from args.
Arguments:
Expand Down Expand Up @@ -327,7 +330,7 @@ def parse_date(args):
return start_date, end_date


def parse_filename(args, start_date):
def parse_filename(args: ArgparseNamespace, start_date: date) -> str:
"""Parse filename from args and start_date.
Arguments:
Expand All @@ -351,7 +354,7 @@ def parse_filename(args, start_date):
return filename


def check_duplicate(entry_a, entry_b):
def check_duplicate(entry_a: Any, entry_b: Any) -> bool:
"""Check if two entries are duplicates by checking their acrid in all music items.
Arguments:
Expand Down Expand Up @@ -379,7 +382,7 @@ def check_duplicate(entry_a, entry_b):
return False


def merge_duplicates(data):
def merge_duplicates(data: Any) -> Any:
"""Merge consecutive entries into one if they are duplicates.
Arguments:
Expand Down Expand Up @@ -409,7 +412,7 @@ def merge_duplicates(data):
return data


def funge_release_date(release_date: str = ""):
def funge_release_date(release_date: str = "") -> str:
"""Make a release_date from ACR conform to what seems to be the spec."""
if len(release_date) == 10:
# we can make it look like what suisa has in their examples if it's the right length
Expand All @@ -424,7 +427,7 @@ def funge_release_date(release_date: str = ""):
return ""


def get_artist(music):
def get_artist(music: Any) -> str:
"""Get artist from a given dict.
Arguments:
Expand Down Expand Up @@ -457,7 +460,7 @@ def get_artist(music):
return artist


def get_isrc(music):
def get_isrc(music: Any) -> str:
"""Get a valid ISRC from the music record or return an empty string."""
isrc = ""
if music.get("external_ids", {}).get("isrc"):
Expand All @@ -484,7 +487,7 @@ def get_isrc(music):

# all local vars are required, eight are already used for the csv entries
# pylint: disable-msg=too-many-locals
def get_csv(data, station_name=""):
def get_csv(data: dict, station_name: str = "") -> str:
"""Create SUISA compatible csv data.
Arguments:
Expand Down Expand Up @@ -616,7 +619,7 @@ def get_csv(data, station_name=""):
return csv.getvalue()


def get_xlsx(data, station_name=""):
def get_xlsx(data: Any, station_name: str = "") -> BytesIO:
"""Create SUISA compatible xlsx data.
Arguments:
Expand All @@ -633,8 +636,10 @@ def get_xlsx(data, station_name=""):
csv_reader = reader(StringIO(csv))

xlsx = BytesIO()
workbook = Workbook()
worksheet = workbook.active
workbook: Workbook = Workbook()
if not workbook.active: # pragma: no cover
raise RuntimeError
worksheet: Worksheet = workbook.active # type: ignore[assignment]

for row in csv_reader:
worksheet.append(row)
Expand Down Expand Up @@ -663,9 +668,9 @@ def get_xlsx(data, station_name=""):
cell.fill = fill

# Try to approximate the required width by finding the longest values per column
dims = {}
for row in worksheet.rows:
for cell in row:
dims: dict[str, int] = {}
for row in worksheet.rows: # type: ignore[assignment]
for cell in row: # type: ignore[assignment]
if cell.value:
dims[cell.column_letter] = max(
(dims.get(cell.column_letter, 0), len(str(cell.value))),
Expand All @@ -679,7 +684,7 @@ def get_xlsx(data, station_name=""):
return xlsx


def write_csv(filename, csv): # pragma: no cover
def write_csv(filename: str, csv: str) -> None: # pragma: no cover
"""Write contents of `csv` to file.
Arguments:
Expand All @@ -692,7 +697,7 @@ def write_csv(filename, csv): # pragma: no cover
csvfile.write(csv)


def write_xlsx(filename, xlsx): # pragma: no cover
def write_xlsx(filename: str, xlsx: BytesIO) -> None: # pragma: no cover
"""Write contents of `xlsx` to file.
Arguments:
Expand All @@ -705,7 +710,7 @@ def write_xlsx(filename, xlsx): # pragma: no cover
xlsxfile.write(xlsx.getvalue())


def get_email_attachment(filename: str, filetype: str, data) -> MIMEBase:
def get_email_attachment(filename: str, filetype: str, data: Any) -> MIMEBase:
"""Create attachment based on required filetype and data.
Arguments:
Expand Down Expand Up @@ -744,7 +749,7 @@ def create_message(
text: str,
filename: str,
filetype: str,
data,
data: Any,
cc: str | None = None,
bcc: str | None = None,
) -> MIMEMultipart:
Expand Down
2 changes: 1 addition & 1 deletion tests/test_suisa_sendemeldung.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from io import BytesIO
from unittest.mock import call, patch

from configargparse import ArgumentParser
from configargparse import ArgumentParser # type: ignore[import-untyped]
from freezegun import freeze_time
from openpyxl import load_workbook
from pytest import mark
Expand Down

0 comments on commit b405d64

Please sign in to comment.