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

RFC/WIP: adopt ruff and its code upgrade/format methods #437

Draft
wants to merge 7 commits into
base: master
Choose a base branch
from
Draft
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
26 changes: 12 additions & 14 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
---
repos:
- repo: https://github.com/asottile/reorder_python_imports
rev: v3.12.0
hooks:
- id: reorder-python-imports
- repo: https://github.com/psf/black
rev: 23.12.0
hooks:
- id: black
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
- id: check-byte-order-marker
- id: trailing-whitespace
- id: end-of-file-fixer
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.6.7
hooks:
- id: ruff
args: [ --fix ]
- id: ruff-format
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0
hooks:
- id: check-byte-order-marker
- id: trailing-whitespace
- id: end-of-file-fixer
3 changes: 1 addition & 2 deletions caldav/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,10 @@
"You need to install the `build` package and do a `python -m build` to get caldav.__version__ set correctly"
)
from .davclient import DAVClient
from .objects import * ## This should go away in version 2.0. TODO: fix some system for deprecation notices

## TODO: this should go away in some future version of the library.
## How to make deprecation notices?
from .objects import *
from .objects import * ## This should go away in version 2.0. TODO: fix some system for deprecation notices

# Silence notification of no default logging handler
log = logging.getLogger("caldav")
Expand Down
24 changes: 13 additions & 11 deletions caldav/davclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@
import logging
import sys
from types import TracebackType
from typing import TYPE_CHECKING
from typing import Any
from typing import cast
from typing import Dict
from typing import List
from typing import Optional
from typing import Tuple
from typing import TYPE_CHECKING
from typing import Union
from typing import cast
from urllib.parse import unquote

import requests
Expand All @@ -27,17 +27,21 @@
from caldav.lib.python_utilities import to_wire
from caldav.lib.url import URL
from caldav.objects import Calendar
from caldav.objects import log
from caldav.objects import Principal
from caldav.objects import log
from caldav.requests import HTTPBearerAuth

from .elements.base import BaseElement

if TYPE_CHECKING:
pass

if sys.version_info < (3, 9):
from typing import Iterable, Mapping
from typing import Iterable
from typing import Mapping
else:
from collections.abc import Iterable, Mapping
from collections.abc import Iterable
from collections.abc import Mapping

if sys.version_info < (3, 11):
from typing_extensions import Self
Expand Down Expand Up @@ -653,9 +657,7 @@ def request(
log.debug("using proxy - %s" % (proxies))

log.debug(
"sending request - method={0}, url={1}, headers={2}\nbody:\n{3}".format(
method, str(url_obj), combined_headers, to_normal_str(body)
)
f"sending request - method={method}, url={str(url_obj)}, headers={combined_headers}\nbody:\n{to_normal_str(body)}"
)

try:
Expand Down Expand Up @@ -763,16 +765,16 @@ def request(

with NamedTemporaryFile(prefix="caldavcomm", delete=False) as commlog:
commlog.write(b"=" * 80 + b"\n")
commlog.write(f"{datetime.datetime.now():%FT%H:%M:%S}".encode("utf-8"))
commlog.write(f"{datetime.datetime.now():%FT%H:%M:%S}".encode())
commlog.write(b"\n====>\n")
commlog.write(f"{method} {url}\n".encode("utf-8"))
commlog.write(f"{method} {url}\n".encode())
commlog.write(
b"\n".join(to_wire(f"{x}: {headers[x]}") for x in headers)
)
commlog.write(b"\n\n")
commlog.write(to_wire(body))
commlog.write(b"<====\n")
commlog.write(f"{response.status} {response.reason}".encode("utf-8"))
commlog.write(f"{response.status} {response.reason}".encode())
commlog.write(
b"\n".join(
to_wire(f"{x}: {response.headers[x]}") for x in response.headers
Expand Down
3 changes: 2 additions & 1 deletion caldav/elements/cdav.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@
from typing import ClassVar
from typing import Optional

from caldav.lib.namespace import ns

from .base import BaseElement
from .base import NamedBaseElement
from .base import ValuedBaseElement
from caldav.lib.namespace import ns

utc_tz = timezone.utc

Expand Down
3 changes: 2 additions & 1 deletion caldav/elements/dav.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
#!/usr/bin/env python
from typing import ClassVar

from caldav.lib.namespace import ns

from .base import BaseElement
from .base import ValuedBaseElement
from caldav.lib.namespace import ns


# Operations
Expand Down
3 changes: 2 additions & 1 deletion caldav/elements/ical.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
#!/usr/bin/env python
from typing import ClassVar

from .base import ValuedBaseElement
from caldav.lib.namespace import ns

from .base import ValuedBaseElement


# Properties
class CalendarColor(ValuedBaseElement):
Expand Down
4 changes: 2 additions & 2 deletions caldav/lib/url.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@
import sys
import urllib.parse
from typing import Any
from typing import cast
from typing import Optional
from typing import Union
from typing import cast
from urllib.parse import ParseResult
from urllib.parse import quote
from urllib.parse import SplitResult
from urllib.parse import quote
from urllib.parse import unquote
from urllib.parse import urlparse
from urllib.parse import urlunparse
Expand Down
51 changes: 33 additions & 18 deletions caldav/objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
release. I think it makes sense moving the CalendarObjectResource
class hierarchy into a separate file)
"""

import re
import sys
import uuid
Expand All @@ -15,17 +16,17 @@ class hierarchy into a separate file)
from datetime import datetime
from datetime import timedelta
from datetime import timezone
from typing import TYPE_CHECKING
from typing import Any
from typing import List
from typing import Optional
from typing import Set
from typing import Tuple
from typing import TYPE_CHECKING
from typing import TypeVar
from typing import Union
from urllib.parse import ParseResult
from urllib.parse import quote
from urllib.parse import SplitResult
from urllib.parse import quote
from urllib.parse import unquote

import icalendar
Expand All @@ -35,24 +36,29 @@ class hierarchy into a separate file)
from lxml.etree import _Element
from vobject.base import VBase

from .elements.base import BaseElement
from .elements.cdav import CalendarData
from .elements.cdav import CompFilter
from caldav.lib.python_utilities import to_normal_str
from caldav.lib.python_utilities import to_unicode
from caldav.lib.python_utilities import to_wire

from .elements.base import BaseElement
from .elements.cdav import CalendarData
from .elements.cdav import CompFilter

try:
from typing import ClassVar, Optional, Union
from typing import ClassVar
from typing import Optional
from typing import Union

TimeStamp = Optional[Union[date, datetime]]
except:
pass

import logging

from caldav.elements import cdav, dav
from caldav.lib import error, vcal
from caldav.elements import cdav
from caldav.elements import dav
from caldav.lib import error
from caldav.lib import vcal
from caldav.lib.url import URL

if TYPE_CHECKING:
Expand All @@ -61,12 +67,21 @@ class hierarchy into a separate file)
from .davclient import DAVClient

if sys.version_info < (3, 9):
from typing import Callable, Container, Iterable, Iterator, Sequence

from typing_extensions import DefaultDict, Literal
from typing import Callable
from typing import Container
from typing import DefaultDict
from typing import Iterable
from typing import Iterator
from typing import Sequence

from typing_extensions import Literal
else:
from collections import defaultdict as DefaultDict
from collections.abc import Callable, Container, Iterable, Iterator, Sequence
from collections.abc import Callable
from collections.abc import Container
from collections.abc import Iterable
from collections.abc import Iterator
from collections.abc import Sequence
from typing import Literal

if sys.version_info < (3, 11):
Expand Down Expand Up @@ -631,7 +646,8 @@ def get_vcal_address(self) -> "vCalAddress":
"""
Returns the principal, as an icalendar.vCalAddress object
"""
from icalendar import vCalAddress, vText
from icalendar import vCalAddress
from icalendar import vText

cn = self.get_display_name()
ids = self.calendar_user_address_set()
Expand Down Expand Up @@ -2236,7 +2252,8 @@ def add_attendee(
role=REQ-PARTICIPANT
schedule-agent is not set
"""
from icalendar import vCalAddress, vText
from icalendar import vCalAddress
from icalendar import vText

if isinstance(attendee, Principal):
attendee_obj = attendee.get_vcal_address()
Expand Down Expand Up @@ -2575,9 +2592,7 @@ def has_component(self):
or (self._icalendar_instance and self.icalendar_component)
) and self.data.count("BEGIN:VEVENT") + self.data.count(
"BEGIN:VTODO"
) + self.data.count(
"BEGIN:VJOURNAL"
) > 0
) + self.data.count("BEGIN:VJOURNAL") > 0

def __str__(self) -> str:
return "%s: %s" % (self.__class__.__name__, self.url)
Expand Down Expand Up @@ -2867,7 +2882,7 @@ def _next(self, ts=None, i=None, dtstart=None, rrule=None, by=None, no_count=Tru
rrule = i["RRULE"]
if not dtstart:
if by is True or (
by is None and any((x for x in rrule if x.startswith("BY")))
by is None and any(x for x in rrule if x.startswith("BY"))
):
if "DTSTART" in i:
dtstart = i["DTSTART"].dt
Expand Down
1 change: 0 additions & 1 deletion docs/source/conf.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# python-caldav documentation build configuration file, created by
# sphinx-quickstart on Thu Jun 3 10:47:52 2010.
Expand Down
2 changes: 1 addition & 1 deletion examples/basic_usage_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ def read_modify_event_demo(event):
event.data = event.data
## So this will not affect the event anymore:
icalendar_component["summary"] = "do the needful"
assert not "do the needful" in event.data
assert "do the needful" not in event.data

## The mofifications are still only saved locally in memory -
## let's save it to the server:
Expand Down
1 change: 0 additions & 1 deletion examples/scheduling_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
from caldav import DAVClient
from caldav import error


###############
### SETUP START
### rfc6638_users should be a list with three dicts containing credential details.
Expand Down
7 changes: 5 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ classifiers = [
"License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
Expand All @@ -37,7 +36,7 @@ dependencies = [
"icalendar;python_version!='3.8'",
]
dynamic = ["version"]

requires-python = ">=3.8"
[project.optional-dependencies]
test = [
"pytest",
Expand All @@ -60,3 +59,7 @@ include-package-data = true
[tool.setuptools.packages.find]
exclude = ["tests"]
namespaces = false

[tool.ruff.lint]
extend-select = ["UP", "I"]
isort.force-single-line = true
4 changes: 0 additions & 4 deletions setup.py

This file was deleted.

5 changes: 2 additions & 3 deletions tests/_test_absolute.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
# encoding: utf-8
import datetime

import caldav


class TestRadicale(object):
class TestRadicale:
SUMMARIES = set(
(
"Godspeed You! Black Emperor at " "Cirque Royal / Koninklijk Circus",
Expand Down Expand Up @@ -35,7 +34,7 @@ def test_eventslist(self):
assert dtstart == self.DTSTART


class TestTryton(object):
class TestTryton:
def setup(self):
URL = "http://admin:admin@localhost:9080/caldav/Calendars/Test"
self.client = caldav.DAVClient(URL)
Expand Down
Loading
Loading