Skip to content

Commit

Permalink
Code formatting / style fixes:
Browse files Browse the repository at this point in the history
- autoformat
- update config
- remove encoding line; sort imports
- comparison to `True` should be `cond is True` or `if cond:`
- linter fixes; cleanup __init__.py
  • Loading branch information
sim0nx authored and tobixen committed Dec 20, 2023
1 parent d21a173 commit 0758419
Show file tree
Hide file tree
Showing 19 changed files with 45 additions and 68 deletions.
6 changes: 3 additions & 3 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
---
repos:
- repo: https://github.com/asottile/reorder_python_imports
rev: v3.1.0
rev: v3.12.0
hooks:
- id: reorder-python-imports
args: ["--application-directories", "src"]
- repo: https://github.com/psf/black
rev: 22.6.0
rev: 23.12.0
hooks:
- id: black
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.3.0
rev: v4.5.0
hooks:
- id: check-byte-order-marker
- id: trailing-whitespace
Expand Down
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ This project should more or less adhere to [Semantic Versioning](https://semver.

## [1.4.0] - unreleased

* Georges Toth did a lot of efforts lifting up the project to more modern standards.
* Georges Toth (@sim0nx) did a lot of efforts lifting up the project to more modern standards.
* A hook for collecting debug information has been in the pull request for ages. I've decided to include it in 1.4.0.
* Code formatting / style fixes.

### Added

Expand Down
10 changes: 2 additions & 8 deletions caldav/__init__.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,8 @@
#!/usr/bin/env python
import logging

import vobject.icalendar

from ._version import __version__
from .davclient import DAVClient
from .objects import *

## Notes:
##
## * The vobject.icalendar has (or had?) to be explicitly imported due to some bug in the tBaxter fork of vobject.
## * The "import *" looks quite ugly, should be revisited at some point

# Silence notification of no default logging handler
log = logging.getLogger("caldav")
Expand All @@ -22,3 +14,5 @@ def emit(self, record) -> None:


log.addHandler(NullHandler())

__all__ = ["__version__", "DAVClient"]
5 changes: 2 additions & 3 deletions caldav/davclient.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import logging
import sys
import typing
Expand Down Expand Up @@ -253,7 +252,7 @@ def find_objects_and_props(self) -> typing.Dict[str, typing.Dict[str, _Element]]
## I would like to do this assert here ...
# error.assert_(not href in self.objects)
## but then there was https://github.com/python-caldav/caldav/issues/136
if not href in self.objects:
if href not in self.objects:
self.objects[href] = {}

## The properties may be delivered either in one
Expand Down Expand Up @@ -745,8 +744,8 @@ def request(
raise error.AuthorizationError(url=str(url_obj), reason=reason)

if error.debug_dump_communication:
from tempfile import NamedTemporaryFile
import datetime
from tempfile import NamedTemporaryFile

with NamedTemporaryFile(prefix="caldavcomm", delete=False) as commlog:
commlog.write(b"=" * 80 + b"\n")
Expand Down
1 change: 0 additions & 1 deletion caldav/elements/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
2 changes: 0 additions & 2 deletions caldav/elements/base.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import sys
import typing
from typing import ClassVar
Expand All @@ -12,7 +11,6 @@
from lxml import etree
from lxml.etree import _Element


if sys.version_info < (3, 9):
from typing import Iterable
else:
Expand Down
1 change: 0 additions & 1 deletion caldav/elements/cdav.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import logging
from datetime import datetime
from datetime import timezone
Expand Down
2 changes: 1 addition & 1 deletion caldav/elements/dav.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from typing import ClassVar

from caldav.lib.namespace import ns
Expand Down Expand Up @@ -27,6 +26,7 @@ class SyncCollection(BaseElement):

# Filters


# Conditions
class SyncToken(BaseElement):
tag: ClassVar[str] = ns("D", "sync-token")
Expand Down
3 changes: 1 addition & 2 deletions caldav/elements/ical.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from typing import ClassVar

from caldav.lib.namespace import ns

from .base import BaseElement
from .base import ValuedBaseElement


# Properties
class CalendarColor(ValuedBaseElement):
tag: ClassVar[str] = ns("I", "calendar-color")
Expand Down
1 change: 0 additions & 1 deletion caldav/lib/error.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import logging
import typing
from collections import defaultdict
Expand Down
1 change: 0 additions & 1 deletion caldav/lib/namespace.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import typing
from typing import Dict
from typing import Optional
Expand Down
3 changes: 1 addition & 2 deletions caldav/lib/url.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import sys
import typing
import urllib.parse
Expand Down Expand Up @@ -158,7 +157,7 @@ def canonical(self) -> "URL":
## sensible defaults
if not arr[0]:
arr[0] = "https"
if arr[1] and not ":" in arr[1]:
if arr[1] and ":" not in arr[1]:
if arr[0] == "https":
portpart = ":443"
elif arr[0] == "http":
Expand Down
6 changes: 3 additions & 3 deletions caldav/lib/vcal.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import datetime
import logging
import re
Expand All @@ -23,6 +22,7 @@
## check if this can be done in vobject or icalendar libraries instead
## of here


## TODO: would be nice with proper documentation on what systems are
## generating broken data. Compatibility issues should also be collected
## in the documentation. somewhere.
Expand Down Expand Up @@ -158,15 +158,15 @@ def create_ical(ical_fragment=None, objtype=None, language="en_DK", **props):
objtype = "VEVENT"
component = icalendar.cal.component_factory[objtype]()
component.add("dtstamp", datetime.datetime.now(tz=datetime.timezone.utc))
if not props.get("uid") and not "\nUID:" in (ical_fragment or ""):
if not props.get("uid") and "\nUID:" not in (ical_fragment or ""):
component.add("uid", uuid.uuid1())
my_instance.add_component(component)
## STATUS should default to NEEDS-ACTION for tasks, if it's not set
## (otherwise we cannot easily add a task to a davical calendar and
## then find it again - ref https://gitlab.com/davical-project/davical/-/issues/281
if (
not props.get("status")
and not "\nSTATUS:" in (ical_fragment or "")
and "\nSTATUS:" not in (ical_fragment or "")
and objtype == "VTODO"
):
props["status"] = "NEEDS-ACTION"
Expand Down
61 changes: 27 additions & 34 deletions caldav/objects.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
A "DAV object" is anything we get from the caldav server or push into the
caldav server, notably principal, calendars and calendar events.
Expand Down Expand Up @@ -42,36 +41,30 @@ class hierarchy into a separate file)
from .elements.cdav import CompFilter

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

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

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


import logging

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

if typing.TYPE_CHECKING:
from .davclient import DAVClient
from icalendar import vCalAddress

from .davclient import DAVClient

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

from typing_extensions import DefaultDict, Literal
else:
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 collections import defaultdict as DefaultDict
from collections.abc import Callable, Container, Iterable, Iterator, Sequence
from typing import Literal

if sys.version_info < (3, 11):
Expand Down Expand Up @@ -254,7 +247,7 @@ def _query(
body = to_wire(body)
if (
ret.status == 500
and not b"getetag" in body
and b"getetag" not in body
and b"<C:calendar-data/>" in body
):
body = body.replace(
Expand Down Expand Up @@ -659,7 +652,7 @@ def calendar_home_set(self):
if (
calendar_home_set_url is not None
and "@" in calendar_home_set_url
and not "://" in calendar_home_set_url
and "://" not in calendar_home_set_url
):
calendar_home_set_url = quote(calendar_home_set_url)
self.calendar_home_set = calendar_home_set_url
Expand Down Expand Up @@ -846,10 +839,10 @@ def save_with_invites(self, ical: str, attendees, **attendeeoptions) -> None:
def _use_or_create_ics(self, ical, objtype, **ical_data):
if ical_data or (
(isinstance(ical, str) or isinstance(ical, bytes))
and not b"BEGIN:VCALENDAR" in to_wire(ical)
and b"BEGIN:VCALENDAR" not in to_wire(ical)
):
## TODO: the ical_fragment code is not much tested
if ical and not "ical_fragment" in ical_data:
if ical and "ical_fragment" not in ical_data:
ical_data["ical_fragment"] = ical
return vcal.create_ical(objtype=objtype, **ical_data)
return ical
Expand Down Expand Up @@ -1203,15 +1196,15 @@ def search(
objects = []
match_set = set()
for item in matches1 + matches2 + matches3:
if not item.url in match_set:
if item.url not in match_set:
match_set.add(item.url)
## and still, Zimbra seems to deliver too many TODOs in the
## matches2 ... let's do some post-filtering in case the
## server fails in filtering things the right way
if "STATUS:NEEDS-ACTION" in item.data or (
not "\nCOMPLETED:" in item.data
and not "\nSTATUS:COMPLETED" in item.data
and not "\nSTATUS:CANCELLED" in item.data
"\nCOMPLETED:" not in item.data
and "\nSTATUS:COMPLETED" not in item.data
and "\nSTATUS:CANCELLED" not in item.data
):
objects.append(item)
else:
Expand Down Expand Up @@ -1457,7 +1450,7 @@ def build_search_xml_query(
if find_not_defined:
match = cdav.NotDefined()
elif find_defined:
raise NotImplemented(
raise NotImplementedError(
"Seems not to be supported by the CalDAV protocol? or we can negate? not supported yet, in any case"
)
else:
Expand Down Expand Up @@ -2091,7 +2084,7 @@ def get_relatives(
if relfilter and not relfilter(rel):
continue
reltype = rel.params.get("RELTYPE", "PARENT")
if reltypes and not reltype in reltypes:
if reltypes and reltype not in reltypes:
continue
ret[reltype].add(str(rel))

Expand Down Expand Up @@ -2222,7 +2215,7 @@ def add_attendee(
)
elif attendee.startswith("mailto:"):
attendee_obj = vCalAddress(attendee)
elif "@" in attendee and not ":" in attendee and not ";" in attendee:
elif "@" in attendee and ":" not in attendee and ";" not in attendee:
attendee_obj = vCalAddress("mailto:" + attendee)
else:
error.assert_(False)
Expand All @@ -2233,14 +2226,14 @@ def add_attendee(
if not no_default_parameters:
## Sensible defaults:
attendee_obj.params["partstat"] = "NEEDS-ACTION"
if not "cutype" in attendee_obj.params:
if "cutype" not in attendee_obj.params:
attendee_obj.params["cutype"] = "UNKNOWN"
attendee_obj.params["rsvp"] = "TRUE"
attendee_obj.params["role"] = "REQ-PARTICIPANT"
params = {}
for key in parameters:
new_key = key.replace("_", "-")
if parameters[key] == True:
if parameters[key] is True:
params[new_key] = "TRUE"
else:
params[new_key] = parameters[key]
Expand Down Expand Up @@ -2274,7 +2267,7 @@ def _reply_to_invite_request(self, partstat, calendar) -> None:
self.get_property(cdav.ScheduleTag(), use_cached=True)
try:
calendar.save_event(self.data)
except Exception as some_exception:
except Exception:
## TODO - TODO - TODO
## RFC6638 does not seem to be very clear (or
## perhaps I should read it more thoroughly) neither on
Expand Down Expand Up @@ -2381,7 +2374,7 @@ def _put(self, retry_on_failure=True):
)
if r.status == 302:
path = [x[1] for x in r.headers if x[0] == "location"][0]
elif not (r.status in (204, 201)):
elif r.status not in (204, 201):
if retry_on_failure:
## This looks like a noop, but the object may be "cleaned".
## See https://github.com/python-caldav/caldav/issues/43
Expand Down Expand Up @@ -2899,7 +2892,7 @@ def _complete_recurring_thisandfuture(self, completion_timestamp) -> None:
"""
recurrences = self.icalendar_instance.subcomponents
orig = recurrences[0]
if not "STATUS" in orig:
if "STATUS" not in orig:
orig["STATUS"] = "NEEDS-ACTION"

if len(recurrences) == 1:
Expand Down Expand Up @@ -3014,7 +3007,7 @@ def _is_pending(self, i=None) -> Optional[bool]:
return True
if i.get("STATUS", None) in ("CANCELLED", "COMPLETED"):
return False
if not "STATUS" in i:
if "STATUS" not in i:
return True
## input data does not conform to the RFC
assert False
Expand Down
1 change: 0 additions & 1 deletion examples/basic_usage_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ def run_examples():
password=password,
headers=headers, # Optional parameter to set HTTP headers on each request if needed
) as client:

## Typically the next step is to fetch a principal object.
## This will cause communication with the server.
my_principal = client.principal()
Expand Down
1 change: 1 addition & 0 deletions examples/scheduling_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
except:
rfc6638_users = None


## Some initial setup. We'll need three caldav client objects, with
## corresponding principal objects and calendars.
class TestUser:
Expand Down
1 change: 0 additions & 1 deletion tests/_test_absolute.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@


class TestRadicale(object):

SUMMARIES = set(
(
"Godspeed You! Black Emperor at " "Cirque Royal / Koninklijk Circus",
Expand Down
Loading

0 comments on commit 0758419

Please sign in to comment.