Skip to content

Commit

Permalink
build!: drop Python 3.9 support
Browse files Browse the repository at this point in the history
BREAKING CHANGE: Python 3.9 is not supported officially anymore. Python
    3.10 is the supported minimum version.
  • Loading branch information
languitar committed Apr 25, 2024
1 parent de2f180 commit 22474d8
Show file tree
Hide file tree
Showing 29 changed files with 96 additions and 105 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ jobs:
- 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", "3.12"]
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
40 changes: 20 additions & 20 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 @@ -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
15 changes: 7 additions & 8 deletions src/autosuspend/checks/linux.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
import socket
import subprocess
import time
from typing import Optional
import warnings

import psutil
Expand Down Expand Up @@ -60,7 +59,7 @@ def normalize_address(
else:
return family, address

def check(self) -> Optional[str]:
def check(self) -> str | None:
# Find the addresses of the system
own_addresses = [
self.normalize_address(item.family, item.address)
Expand Down Expand Up @@ -98,7 +97,7 @@ def __init__(self, name: str, threshold: float) -> None:
Activity.__init__(self, name)
self._threshold = threshold

def check(self) -> Optional[str]:
def check(self) -> str | None:
loadcurrent = os.getloadavg()[1]
self.logger.debug("Load: %s", loadcurrent)
if loadcurrent > self._threshold:
Expand Down Expand Up @@ -188,7 +187,7 @@ def _check_interface(
f"higher than threshold {self._threshold_receive}"
)

def check(self) -> Optional[str]:
def check(self) -> str | None:
# acquire the previous state and preserve it
old_values = self._previous_values
old_time = self._previous_time
Expand Down Expand Up @@ -237,7 +236,7 @@ def __init__(self, name: str, hosts: Iterable[str]) -> None:
Activity.__init__(self, name)
self._hosts = hosts

def check(self) -> Optional[str]:
def check(self) -> str | None:
try:
for host in self._hosts:
cmd = ["ping", "-q", "-c", "1", host]
Expand Down Expand Up @@ -270,7 +269,7 @@ def __init__(self, name: str, processes: Iterable[str]) -> None:
Activity.__init__(self, name)
self._processes = processes

def check(self) -> Optional[str]:
def check(self) -> str | None:
for proc in psutil.process_iter():
with suppress(psutil.NoSuchProcess):
pinfo = proc.name()
Expand Down Expand Up @@ -306,7 +305,7 @@ def __init__(
self._terminal_regex = terminal_regex
self._host_regex = host_regex

def check(self) -> Optional[str]:
def check(self) -> str | None:
for entry in psutil.users():
if (
self._user_regex.fullmatch(entry.name) is not None
Expand Down Expand Up @@ -344,7 +343,7 @@ def __init__(self, name: str, path: Path) -> None:
Wakeup.__init__(self, name)
self._path = path

def check(self, timestamp: datetime) -> Optional[datetime]: # noqa: ARG002
def check(self, timestamp: datetime) -> datetime | None: # noqa: ARG002
try:
first_line = self._path.read_text().splitlines()[0]
return datetime.fromtimestamp(float(first_line.strip()), timezone.utc)
Expand Down
Loading

0 comments on commit 22474d8

Please sign in to comment.