Skip to content

Commit

Permalink
Fix more ruff-highlighted errors
Browse files Browse the repository at this point in the history
  • Loading branch information
bergercookie committed Aug 11, 2024
1 parent d4b2208 commit 5667b0d
Show file tree
Hide file tree
Showing 43 changed files with 169 additions and 181 deletions.
34 changes: 0 additions & 34 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,6 @@ exclude = []
select = ["ALL"]
ignore = [
# remove them in phases
"A002",
"ANN001",
"ANN002",
"ANN003",
Expand All @@ -201,17 +200,8 @@ ignore = [
"ANN202",
"ANN204",
"ANN206",
"ANN401",
"ARG001",
"ARG002",
"B007",
"B008",
"B012",
"B904",
"C405",
"C408",
"C419",
"C901",
"D100",
"D100",
"D101",
Expand All @@ -220,8 +210,6 @@ ignore = [
"D102",
"D103",
"D103",
"D104",
"D104",
"D105",
"D107",
"D107",
Expand All @@ -232,54 +220,32 @@ ignore = [
"D401",
"D415",
"DTZ004",
"DTZ006",
"E501",
"E712",
"EM101",
"EM102",
"ERA001",
"EXE002",
"F403",
"F841",
"FA100",
"FA102",
"FBT001",
"FBT002",
"FIX002",
"INP001",
"N802",
"N803",
"N806",
"PGH003",
"PLR0912",
"PLR0913",
"PLR2004",
"PT009",
"PT018",
"PTH118",
"PTH123",
"RET503",
"RET504",
"RET505",
"RUF012",
"S101",
"S101",
"S301",
"S506",
"S602",
"SIM108",
"SIM110",
"SIM118",
"SLF001",
"T100",
"T201",
"TCH001",
"TCH002",
"TD002",
"TD003",
"TD004",
"TRY003",
"TRY004",
"UP007",
]
exclude = []
Expand Down
7 changes: 5 additions & 2 deletions syncall/aggregator.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,9 @@ def __init__(
side_B: SyncSide,
converter_B_to_A: ConverterFn,
converter_A_to_B: ConverterFn,
resolution_strategy: ResolutionStrategy = AlwaysSecondRS(),
resolution_strategy: ResolutionStrategy | None = None,
config_fname: Optional[str] = None,
ignore_keys: tuple[Sequence[str], Sequence[str]] = tuple(),
ignore_keys: tuple[Sequence[str], Sequence[str]] = (),
catch_exceptions: bool = True,
):
# Preferences manager
Expand All @@ -58,6 +58,9 @@ def __init__(
else:
logger.debug(f"Using a custom configuration file ... -> {config_fname}")

if resolution_strategy is None:
resolution_strategy = AlwaysSecondRS()

self.prefs_manager = PrefsManager(app_name=app_name(), config_fname=config_fname)

# Own config
Expand Down
11 changes: 8 additions & 3 deletions syncall/app_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
import sys
from datetime import datetime
from pathlib import Path
from typing import Any, Iterable, Mapping, NoReturn, Optional, Sequence, cast
from typing import TYPE_CHECKING, Any, Iterable, Mapping, NoReturn, Optional, Sequence, cast
from urllib.parse import quote

from bubop import (
Expand All @@ -38,7 +38,10 @@
)

from syncall.constants import COMBINATION_FLAGS, ISSUES_URL
from syncall.sync_side import SyncSide

if TYPE_CHECKING:
from syncall.sync_side import SyncSide
from syncall.types import SupportsStr

# Various resolution strategies with their respective names so that the user can choose which
# one they want. ------------------------------------------------------------------------------
Expand Down Expand Up @@ -126,7 +129,7 @@ def get_config_name_for_args(*args) -> str:
def quote_(obj: str) -> str:
return quote(obj, safe="+,")

def format_(obj: Any) -> str:
def format_(obj: SupportsStr) -> str:
if isinstance(obj, str):
return quote_(obj)
elif isinstance(obj, Iterable):
Expand Down Expand Up @@ -385,6 +388,8 @@ def teardown():
if inform_about_config:
inform_about_combination_name_usage(combination_name)

return 0

if pdb_on_error:
logger.warning(
"pdb_on_error is enabled. Disabling exit hooks / not taking actions at the end "
Expand Down
1 change: 1 addition & 0 deletions syncall/asana/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Asana side subpackage."""
3 changes: 0 additions & 3 deletions syncall/asana/asana_side.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,6 @@ def update_item(self, item_id: AsanaGID, **changes):
# - If the remote Asana task 'due_on' field is empty, update 'due_at'.
# - If the remote Asana task 'due_on' field is not empty and the
# 'due_at' field is empty, update 'due_on'.
# TODO: find a way to store this information locally, so we don't have
# to fetch the task from Asana to determine this.
remote_task = self.get_item(item_id)
if remote_task.get("due_on", None) is None:
raw_task.pop("due_on", None)
Expand Down Expand Up @@ -155,7 +153,6 @@ def items_are_identical(
compare_keys.remove(key)

# Special handling for 'due_at' and 'due_on'
# TODO: reduce ['due_at','due_on'] to 'due_at', compare and remove both
# keys.
if item1.get("due_at", None) is not None and item2.get("due_at", None) is not None:
compare_keys.remove("due_on")
Expand Down
2 changes: 1 addition & 1 deletion syncall/asana/asana_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class AsanaTask(Mapping):
"modified_at",
}

def __getitem__(self, key) -> Any:
def __getitem__(self, key) -> Any: # noqa: ANN401
return getattr(self, key)

def __iter__(self):
Expand Down
16 changes: 11 additions & 5 deletions syncall/caldav/caldav_side.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
from typing import Any, Optional, Sequence
from __future__ import annotations

from typing import TYPE_CHECKING, Any, Optional, Sequence

import caldav
from bubop import logger
from caldav.lib.error import NotFoundError
from icalendar.prop import vCategory, vDatetime, vText
from item_synchronizer.types import ID

if TYPE_CHECKING:
import caldav
from item_synchronizer.types import ID

from syncall.app_utils import error_and_exit
from syncall.caldav.caldav_utils import calendar_todos, icalendar_component, map_ics_to_item
Expand Down Expand Up @@ -90,11 +94,13 @@ def _find_todo_by_id_raw(self, item_id: ID) -> Optional[caldav.CalendarObjectRes

return item

def _find_todo_by_id(self, item_id: ID) -> Optional[dict]:
def _find_todo_by_id(self, item_id: ID) -> dict | None:
raw_item = self._find_todo_by_id_raw(item_id=item_id)
if raw_item:
return map_ics_to_item(icalendar_component(raw_item))

return None

def delete_single_item(self, item_id: ID):
todo = self._find_todo_by_id_raw(item_id=item_id)
if todo is not None:
Expand All @@ -110,7 +116,7 @@ def update_item(self, item_id: ID, **changes):
logger.opt(lazy=True).debug(f"Can't update item {item_id}\n\nchanges: {changes}")
return

def set_(key: str, val: Any):
def set_(key: str, val: Any): # noqa: ANN401
icalendar_component(todo)[key] = val

# pop the key:value (s) that we're intending to potentially update
Expand Down
28 changes: 15 additions & 13 deletions syncall/caldav/caldav_utils.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
from __future__ import annotations

import traceback
from typing import Optional, Sequence
from typing import TYPE_CHECKING, Optional, Sequence
from uuid import UUID

import caldav
from bubop import logger
from icalendar.prop import vCategory
from item_synchronizer.resolution_strategy import Item

if TYPE_CHECKING:
import caldav
from icalendar.prop import vCategory
from item_synchronizer.resolution_strategy import Item


def icalendar_component(obj: caldav.CalendarObjectResource):
Expand Down Expand Up @@ -55,13 +57,13 @@ def _convert_one(name: str) -> str:
# return a List[vCategory], each vCategory with a single name
# Option 1:
#
# CATEGORIES:bugwarrior
# CATEGORIES:github_working_on_it
# CATEGORIES:programming
# CATEGORIES:remindme
# | CATEGORIES:bugwarrior
# | CATEGORIES:github_working_on_it
# | CATEGORIES:programming
# | CATEGORIES:remindme
#
# Option 2:
# CATEGORIES:bugwarrior,github_bug,github_help_wanted,github_tw_gcal_sync,pro
# | CATEGORIES:bugwarrior,github_bug,github_help_wanted,github_tw_gcal_sync,pro
all_categories = []
if isinstance(vcategories, Sequence):
for vcategory in vcategories:
Expand Down Expand Up @@ -91,19 +93,19 @@ def parse_caldav_item_desc(
lines = [line.strip() for line in caldav_desc.split("\n") if line][1:]

# annotations
i = 0
for i, line in enumerate(lines):
_i = 0
for _i, line in enumerate(lines):
parts = line.split(":", maxsplit=1)
if len(parts) == 2 and parts[0].lower().startswith("* annotation"):
annotations.append(parts[1].strip())
else:
break

if i == len(lines):
if _i == len(lines):
return annotations, uuid

# Iterate through rest of lines, find only the uuid
for line in lines[i:]:
for line in lines[_i:]:
parts = line.split(":", maxsplit=1)
if len(parts) == 2 and parts[0].lower().startswith("* uuid"):
try:
Expand Down
2 changes: 1 addition & 1 deletion syncall/concrete_item.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def id(self) -> Optional[ID]:
def _id(self) -> Optional[str]:
pass

def __getitem__(self, key: str) -> Any:
def __getitem__(self, key: str) -> Any: # noqa: ANN401
return getattr(self, key)

def __iter__(self) -> Iterator[str]:
Expand Down
9 changes: 6 additions & 3 deletions syncall/filesystem/filesystem_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,11 +179,14 @@ def title(self, new_title):

@property
def last_modified_date(self) -> datetime.datetime:
# TODO Amend this.
tzinfo = datetime.datetime.now().astimezone().tzinfo
try:
return datetime.datetime.fromtimestamp(self._path.stat().st_mtime)
return datetime.datetime.fromtimestamp(
self._path.stat().st_mtime,
tz=tzinfo,
)
except FileNotFoundError:
return datetime.datetime.utcfromtimestamp(0)
return datetime.datetime.fromtimestamp(0, tz=tzinfo)

def delete(self) -> None:
"""Mark this file for deletion."""
Expand Down
1 change: 1 addition & 0 deletions syncall/google/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Google-related subpackage."""
22 changes: 13 additions & 9 deletions syncall/google/gcal_side.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from __future__ import annotations

import datetime
import os
from pathlib import Path
from typing import Literal, Optional, Sequence, Union, cast
from typing import TYPE_CHECKING, Literal, Optional, Sequence, cast

import dateutil
import pkg_resources
Expand All @@ -12,9 +13,12 @@
from syncall.google.google_side import GoogleSide
from syncall.sync_side import SyncSide

if TYPE_CHECKING:
from syncall.types import GoogleDateT

DEFAULT_CLIENT_SECRET = pkg_resources.resource_filename(
"syncall",
os.path.join("res", "gcal_client_secret.json"),
"res/gcal_client_secret.json",
)


Expand All @@ -41,7 +45,7 @@ def __init__(
self,
*,
calendar_summary="TaskWarrior Reminders",
client_secret,
client_secret: str | None,
**kargs,
):
if client_secret is None:
Expand All @@ -52,7 +56,7 @@ def __init__(
fullname="Google Calendar",
scopes=["https://www.googleapis.com/auth/calendar"],
credentials_cache=Path.home() / ".gcal_credentials.pickle",
client_secret=Path(client_secret),
client_secret=client_secret,
**kargs,
)

Expand Down Expand Up @@ -150,8 +154,8 @@ def _get_item_refresh(self, item_id: str) -> Optional[dict]:
self._items_cache[item_id] = ret
except HttpError:
pass
finally:
return ret

return ret

def update_item(self, item_id, **changes):
# Check if item is there
Expand Down Expand Up @@ -218,7 +222,7 @@ def format_datetime(dt: datetime.datetime) -> str:
return format_datetime_tz(dt)

@classmethod
def parse_datetime(cls, dt: Union[str, dict, datetime.datetime]) -> datetime.datetime:
def parse_datetime(cls, dt: GoogleDateT) -> datetime.datetime:
"""Parse datetime given in the GCal format(s):
- string with ('T', 'Z' separators).
- (dateTime, dateZone) dictionary
Expand All @@ -238,7 +242,7 @@ def parse_datetime(cls, dt: Union[str, dict, datetime.datetime]) -> datetime.dat
elif isinstance(dt, datetime.datetime):
return assume_local_tz_if_none(dt)
else:
raise RuntimeError(
raise TypeError(
f"Unexpected type of a given date item, type: {type(dt)}, contents: {dt}",
)

Expand Down
Loading

0 comments on commit 5667b0d

Please sign in to comment.