Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modernize Python versions #524

Merged
merged 2 commits into from
Apr 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ jobs:
steps:
- name: Clone repo
uses: actions/checkout@v4
- name: Set up Python 3.11
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.11"
python-version: "3.12"
- name: Install native dependencies
run: sudo apt-get update && sudo apt-get -y install libdbus-1-dev libgirepository1.0-dev
- name: Cache Python packages
Expand All @@ -47,10 +47,10 @@ jobs:
steps:
- name: Clone repo
uses: actions/checkout@v4
- name: Set up Python 3.11
- name: Set up Python 3.12
uses: actions/setup-python@v5
with:
python-version: "3.11"
python-version: "3.12"
- name: Install native dependencies
run: sudo apt-get update && sudo apt-get -y install libdbus-1-dev libgirepository1.0-dev plantuml
- name: Cache Python packages
Expand All @@ -71,10 +71,10 @@ jobs:
steps:
- name: Clone repo
uses: actions/checkout@v4
- name: Set up Python 3.9
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: 3.9
python-version: "3.10"
- name: Cache Python packages
uses: actions/cache@v4
with:
Expand All @@ -93,7 +93,7 @@ jobs:
strategy:
max-parallel: 4
matrix:
python-version: ["3.9", "3.10", "3.11"]
python-version: ["3.10", "3.11", "3.12"]

steps:
- name: Clone repo
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ requires = ["setuptools", "wheel"]

[tool.ruff]
src = ["src"]
target-version = "py39"
target-version = "py310"

[tool.ruff.lint]
select = [
Expand Down
42 changes: 21 additions & 21 deletions src/autosuspend/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"""A daemon to suspend a system on inactivity."""

import argparse
from collections.abc import Iterable, Sequence
from collections.abc import Callable, Iterable, Sequence
import configparser
from contextlib import suppress
from datetime import datetime, timedelta, timezone
Expand All @@ -13,7 +13,7 @@
from pathlib import Path
import subprocess
import time
from typing import Callable, IO, Optional, Union
from typing import IO

import portalocker

Expand All @@ -27,8 +27,8 @@


def execute_suspend(
command: Union[str, Sequence[str]],
wakeup_at: Optional[datetime],
command: str | Sequence[str],
wakeup_at: datetime | None,
) -> None:
"""Suspend the system by calling the specified command.

Expand All @@ -49,9 +49,9 @@ def execute_suspend(


def notify_suspend(
command_wakeup_template: Optional[str],
command_no_wakeup: Optional[str],
wakeup_at: Optional[datetime],
command_wakeup_template: str | None,
command_no_wakeup: str | None,
wakeup_at: datetime | None,
) -> None:
"""Call a command to notify on suspending.

Expand Down Expand Up @@ -92,10 +92,10 @@ def safe_exec(command: str) -> None:


def notify_and_suspend(
suspend_cmd: Union[str, Sequence[str]],
notify_cmd_wakeup_template: Optional[str],
notify_cmd_no_wakeup: Optional[str],
wakeup_at: Optional[datetime],
suspend_cmd: str | Sequence[str],
notify_cmd_wakeup_template: str | None,
notify_cmd_no_wakeup: str | None,
wakeup_at: datetime | None,
) -> None:
notify_suspend(notify_cmd_wakeup_template, notify_cmd_no_wakeup, wakeup_at)
execute_suspend(suspend_cmd, wakeup_at)
Expand All @@ -114,7 +114,7 @@ def schedule_wakeup(command_template: str, wakeup_at: datetime) -> None:
)


def _safe_execute_activity(check: Activity, logger: logging.Logger) -> Optional[str]:
def _safe_execute_activity(check: Activity, logger: logging.Logger) -> str | None:
try:
return check.check()
except TemporaryCheckError:
Expand Down Expand Up @@ -154,7 +154,7 @@ def execute_checks(

def _safe_execute_wakeup(
check: Wakeup, timestamp: datetime, logger: logging.Logger
) -> Optional[datetime]:
) -> datetime | None:
try:
return check.check(timestamp)
except TemporaryCheckError:
Expand All @@ -164,7 +164,7 @@ def _safe_execute_wakeup(

def execute_wakeups(
wakeups: Iterable[Wakeup], timestamp: datetime, logger: logging.Logger
) -> Optional[datetime]:
) -> datetime | None:
wakeup_at = None
for wakeup in wakeups:
this_at = _safe_execute_wakeup(wakeup, timestamp, logger)
Expand Down Expand Up @@ -238,7 +238,7 @@ def __init__(
self._sleep_fn = sleep_fn
self._wakeup_fn = wakeup_fn
self._all_activities = all_activities
self._idle_since = None # type: Optional[datetime]
self._idle_since = None # type: datetime | None

def _reset_state(self, reason: str) -> None:
self._logger.info("%s. Resetting state", reason)
Expand Down Expand Up @@ -314,7 +314,7 @@ def iteration(self, timestamp: datetime, just_woke_up: bool) -> None:
self._sleep_fn(wakeup_at)


def _continue_looping(run_for: Optional[int], start_time: datetime) -> bool:
def _continue_looping(run_for: int | None, start_time: datetime) -> bool:
return (run_for is None) or (
datetime.now(timezone.utc) < (start_time + timedelta(seconds=run_for))
)
Expand Down Expand Up @@ -348,7 +348,7 @@ def _do_loop_iteration(
def loop(
processor: Processor,
interval: float,
run_for: Optional[int],
run_for: int | None,
woke_up_file: Path,
lock_file: Path,
lock_timeout: float,
Expand Down Expand Up @@ -504,7 +504,7 @@ def parse_config(config_file: Iterable[str]) -> configparser.ConfigParser:
return config


def parse_arguments(args: Optional[Sequence[str]]) -> argparse.Namespace:
def parse_arguments(args: Sequence[str] | None) -> argparse.Namespace:
"""Parse command line arguments.

Args:
Expand All @@ -517,7 +517,7 @@ def parse_arguments(args: Optional[Sequence[str]]) -> argparse.Namespace:
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)

default_config: Optional[IO[str]] = None
default_config: IO[str] | None = None
with suppress(FileNotFoundError, IsADirectoryError, PermissionError):
# The open file is required after this function finishes inside the argparse
# result. Therefore, a context manager is not easily usable here.
Expand Down Expand Up @@ -596,7 +596,7 @@ def parse_arguments(args: Optional[Sequence[str]]) -> argparse.Namespace:
return result


def configure_logging(config_file: Optional[IO], debug: bool) -> None:
def configure_logging(config_file: IO | None, debug: bool) -> None:
"""Configure the python :mod:`logging` system.

Assumes that either a config file is provided, or debugging is enabled.
Expand Down Expand Up @@ -794,7 +794,7 @@ def main_daemon(args: argparse.Namespace, config: configparser.ConfigParser) ->
)


def main(argv: Optional[Sequence[str]] = None) -> None:
def main(argv: Sequence[str] | None = None) -> None:
"""Run the daemon."""
args = parse_arguments(argv)

Expand Down
8 changes: 4 additions & 4 deletions src/autosuspend/checks/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from collections.abc import Mapping
import configparser
from datetime import datetime
from typing import Any, Optional, TypeVar
from typing import Any, TypeVar

from autosuspend.util import logger_by_class_instance

Expand Down Expand Up @@ -60,7 +60,7 @@ def create(
"""

def __init__(self, name: Optional[str] = None) -> None:
def __init__(self, name: str | None = None) -> None:
if name:
self.name = name
else:
Expand All @@ -87,7 +87,7 @@ class Activity(Check):
"""

@abc.abstractmethod
def check(self) -> Optional[str]:
def check(self) -> str | None:
"""Determine if system activity exists that prevents suspending.
Returns:
Expand All @@ -108,7 +108,7 @@ class Wakeup(Check):
"""Represents a check for potential wake up points."""

@abc.abstractmethod
def check(self, timestamp: datetime) -> Optional[datetime]:
def check(self, timestamp: datetime) -> datetime | None:
"""Indicate if a wakeup has to be scheduled for this check.
Args:
Expand Down
5 changes: 2 additions & 3 deletions src/autosuspend/checks/command.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import configparser
from datetime import datetime, timezone
import subprocess
from typing import Optional

from . import (
Activity,
Expand Down Expand Up @@ -38,7 +37,7 @@ def __init__(self, name: str, command: str) -> None:
CommandMixin.__init__(self, command)
Activity.__init__(self, name)

def check(self) -> Optional[str]:
def check(self) -> str | None:
try:
subprocess.check_call(self._command, shell=True)
return f"Command {self._command} succeeded"
Expand All @@ -58,7 +57,7 @@ def __init__(self, name: str, command: str) -> None:
CommandMixin.__init__(self, command)
Wakeup.__init__(self, name)

def check(self, timestamp: datetime) -> Optional[datetime]: # noqa: ARG002
def check(self, timestamp: datetime) -> datetime | None: # noqa: ARG002
try:
output = subprocess.check_output(
self._command,
Expand Down
16 changes: 8 additions & 8 deletions src/autosuspend/checks/ical.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from dataclasses import dataclass
from datetime import date, datetime, timedelta, timezone, tzinfo
from io import BytesIO
from typing import Any, cast, IO, Optional, TypeVar, Union
from typing import Any, cast, IO, TypeVar

from dateutil.rrule import rrule, rruleset, rrulestr
import icalendar
Expand All @@ -19,12 +19,12 @@
@dataclass
class CalendarEvent:
summary: str
start: Union[datetime, date]
end: Union[datetime, date]
start: datetime | date
end: datetime | date

def __str__(self) -> str:
return "CalendarEvent[summary={}, start={}, end={}]".format(
self.summary, self.start, self.end
return (
f"CalendarEvent[summary={self.summary}, start={self.start}, end={self.end}]"
)


Expand Down Expand Up @@ -60,7 +60,7 @@ def _prepare_rruleset_for_expanding(
start: datetime,
exclusions: Iterable,
changes: Iterable[icalendar.cal.Event],
tz: Optional[tzinfo],
tz: tzinfo | None,
) -> rruleset:
"""Prepare an rruleset for expanding.
Expand Down Expand Up @@ -291,7 +291,7 @@ def __init__(self, name: str, **kwargs: Any) -> None:
NetworkMixin.__init__(self, **kwargs)
Activity.__init__(self, name)

def check(self) -> Optional[str]:
def check(self) -> str | None:
response = self.request()
start = datetime.now(timezone.utc)
end = start + timedelta(minutes=1)
Expand All @@ -315,7 +315,7 @@ def __init__(self, name: str, **kwargs: Any) -> None:
NetworkMixin.__init__(self, **kwargs)
Wakeup.__init__(self, name)

def check(self, timestamp: datetime) -> Optional[datetime]:
def check(self, timestamp: datetime) -> datetime | None:
response = self.request()

end = timestamp + timedelta(weeks=6 * 4)
Expand Down
4 changes: 2 additions & 2 deletions src/autosuspend/checks/json.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import configparser
import json
from textwrap import shorten
from typing import Any, Optional
from typing import Any

from jsonpath_ng import JSONPath
import requests
Expand Down Expand Up @@ -32,7 +32,7 @@ def __init__(self, name: str, jsonpath: JSONPath, **kwargs: Any) -> None:
NetworkMixin.__init__(self, accept="application/json", **kwargs)
self._jsonpath = jsonpath

def check(self) -> Optional[str]:
def check(self) -> str | None:
try:
reply = self.request().json()
matched = self._jsonpath.find(reply)
Expand Down
6 changes: 3 additions & 3 deletions src/autosuspend/checks/kodi.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import configparser
import json
from typing import Any, Optional
from typing import Any

from . import Activity, ConfigurationError, TemporaryCheckError
from .util import NetworkMixin
Expand Down Expand Up @@ -52,7 +52,7 @@ def _safe_request_result(self) -> dict:
except (KeyError, TypeError, json.JSONDecodeError) as error:
raise TemporaryCheckError("Unable to get or parse Kodi state") from error

def check(self) -> Optional[str]:
def check(self) -> str | None:
reply = self._safe_request_result()
if self._suspend_while_paused:
return (
Expand Down Expand Up @@ -87,7 +87,7 @@ def __init__(self, name: str, url: str, idle_time: int, **kwargs: Any) -> None:
Activity.__init__(self, name)
self._idle_time = idle_time

def check(self) -> Optional[str]:
def check(self) -> str | None:
try:
reply = self.request().json()
if not reply["result"][f"System.IdleTime({self._idle_time})"]:
Expand Down
Loading