Skip to content

Commit

Permalink
fix: refactoring cleanup, add type hints/ignores and fix an error
Browse files Browse the repository at this point in the history
* mypy helped find an error, but we still need to ignore the optional
  munch YAML attributes

Signed-off-by: Stephen Arnold <[email protected]>
  • Loading branch information
sarnold committed Sep 1, 2024
1 parent 42b590f commit 8928af9
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 26 deletions.
24 changes: 14 additions & 10 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ repos:
- id: check-useless-excludes
- id: check-hooks-apply
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
rev: v4.6.0
hooks:
- id: check-added-large-files
- id: check-case-conflict
Expand All @@ -28,31 +28,35 @@ repos:
- id: check-toml

- repo: https://github.com/ambv/black
rev: 23.3.0
rev: 24.8.0
hooks:
- id: black
name: "Format code"
language_version: python3

- repo: https://github.com/pycqa/isort
rev: 5.12.0
rev: 5.13.2
hooks:
- id: isort
args: [--settings-path=pyproject.toml]

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.5.0
rev: v1.11.2
hooks:
- id: mypy
args:
- --follow-imports=normal
- --install-types
- --non-interactive
- --ignore-missing-imports
#files: src/
- --implicit-reexport
additional_dependencies:
- "PyYAML"
- "munch"
- "munch-stubs"
#files: src/

- repo: "https://github.com/asottile/blacken-docs"
rev: "1.15.0"
rev: "1.18.0"
hooks:
- id: "blacken-docs"
name: "Format docs (blacken-docs)"
Expand All @@ -76,7 +80,7 @@ repos:
- id: rst-inline-touching-normal

- repo: https://github.com/myint/autoflake
rev: v2.2.0
rev: v2.3.1
hooks:
- id: autoflake
#files: src/
Expand All @@ -87,14 +91,14 @@ repos:
- --remove-unused-variables

- repo: https://github.com/PyCQA/flake8
rev: 6.1.0
rev: 7.1.1
hooks:
- id: flake8
#files: src/
additional_dependencies: ["flake8-bugbear"]

- repo: https://github.com/PyCQA/bandit
rev: 1.7.5
rev: 1.7.9
hooks:
- id: bandit
args: ["-ll", "-q"]
Expand Down
2 changes: 1 addition & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ exclude =
docs,
tests

max-line-length = 99
max-line-length = 100
max-complexity = 10
addons = file,open,basestring,xrange,unicode,long,cmp
ignore =
Expand Down
36 changes: 21 additions & 15 deletions src/timew_status/utils.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
"""
Base configuration and app helper functions.
"""

import datetime
import os
import subprocess
from datetime import timedelta
from pathlib import Path
from typing import Dict, NewType, Optional

from munch import Munch

TimeDelta = NewType("TimeDelta", datetime.timedelta)
APP_NAME = 'timew_status_indicator'
CFG = {
# time strings are HH:MM (no seconds)
Expand All @@ -30,7 +34,7 @@
}


def do_install(cfg):
def do_install(cfg: Dict):
"""
Install report extensions to timew extensions directory. The default src
paths are preconfigured and should probably not be changed unless you
Expand Down Expand Up @@ -60,7 +64,7 @@ def do_install(cfg):
return files


def get_config(file_encoding='utf-8'):
def get_config(file_encoding: str = 'utf-8'):
"""
Load configuration file and munchify the data. If local file is not
found in config directory, the default will be loaded and saved to
Expand All @@ -74,14 +78,14 @@ def get_config(file_encoding='utf-8'):
cfgdir = get_userdirs()
cfgfile = cfgdir.joinpath('config.yaml')
if not cfgfile.exists():
print(f"Saving initial config data to {cfgfile}")
cfgfile.write_text(Munch.toYAML(CFG), encoding=file_encoding)
cfgobj = Munch.fromYAML(cfgfile.read_text(encoding=file_encoding))

print(f"Saving initial config data to {cfgfile}") # fmt: off
cfgfile.write_text(Munch.toYAML(CFG), encoding=file_encoding) # type: ignore[attr-defined]
cfgobj = Munch.fromYAML(cfgfile.read_text(encoding=file_encoding)) # type: ignore[attr-defined]
# fmt: on
return cfgobj, cfgfile


def get_delta_limits(ucfg):
def get_delta_limits(ucfg: Dict):
"""
Return config max/snooze limits as timedeltas. Everything comes from
static config values and gets padded with seconds.
Expand All @@ -101,7 +105,7 @@ def get_delta_limits(ucfg):
return day_max, day_limit, seat_max, seat_limit


def get_state_icon(state, cfg):
def get_state_icon(state: str, cfg: Dict):
"""
Look up the state msg and return the icon name. Use builtin symbolic
icons as fallback.
Expand Down Expand Up @@ -139,7 +143,9 @@ def get_state_icon(state, cfg):
return state_dict.get(state, state_dict['INACTIVE'])


def get_state_str(cmproc, count, cfg):
def get_state_str(
cmproc: subprocess.CompletedProcess[bytes], count: TimeDelta, cfg: Dict
):
"""
Return timew state message and tracking state, ie, the key for dict
with icons.
Expand Down Expand Up @@ -207,7 +213,7 @@ def get_userdirs():
return configdir


def parse_for_tag(text):
def parse_for_tag(text: str):
"""
Parse the output of timew start/stop commands for the tag string.
Expand All @@ -219,17 +225,17 @@ def parse_for_tag(text):
return line.split('"')[1]


def run_cmd(action='status', tag=None):
def run_cmd(cfg: Dict, action: str = 'status', tag: Optional[str] = None):
"""
Run timew command subject to the given action.
:param action: one of <start|stop|status>
:return: completed proc obj and result msg
"""

extension = cfg["extension_script"]
actions = ['start', 'stop', 'status']
svc_list = ['timew']
sts_list = [CFG["extension_script"], "today"]
sts_list = [extension, "today"]
cmd = svc_list
act_list = [action]

Expand Down Expand Up @@ -261,12 +267,12 @@ def run_cmd(action='status', tag=None):
print(f'run_cmd exception: {exc}')


def to_td(hms):
def to_td(hms: str):
"""
Convert a time string in HH:MM:SS format to a timedelta object.
:param hms: time string
:return: timedelta obj
:return: timedelta
"""
hrs, mins, secs = hms.split(':')
return timedelta(hours=int(hrs), minutes=int(mins), seconds=int(secs))
Expand Down
3 changes: 3 additions & 0 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,9 @@ setenv = PYTHONPATH = {toxinidir}

deps =
pip>=23.1
munch[yaml]
munch-stubs
PyYAML
timew-report
mypy

Expand Down

0 comments on commit 8928af9

Please sign in to comment.