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

try setting black on 120 length #422

Closed
wants to merge 1 commit into from
Closed
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
92 changes: 24 additions & 68 deletions caldav/davclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,7 @@ class DAVResponse:
davclient = None
huge_tree: bool = False

def __init__(
self, response: Response, davclient: Optional["DAVClient"] = None
) -> None:
def __init__(self, response: Response, davclient: Optional["DAVClient"] = None) -> None:
self.headers = response.headers
log.debug("response headers: " + str(self.headers))
log.debug("response status: " + str(self.status))
Expand All @@ -75,9 +73,9 @@ def __init__(
## TODO: this if/else/elif could possibly be refactored, or we should
## consider to do streaming into the xmltree library as originally
## intended. It only makes sense for really huge payloads though.
if self.headers.get("Content-Type", "").startswith(
"text/xml"
) or self.headers.get("Content-Type", "").startswith("application/xml"):
if self.headers.get("Content-Type", "").startswith("text/xml") or self.headers.get(
"Content-Type", ""
).startswith("application/xml"):
try:
content_length = int(self.headers["Content-Length"])
except:
Expand All @@ -94,22 +92,19 @@ def __init__(
try:
self.tree = etree.XML(
self._raw,
parser=etree.XMLParser(
remove_blank_text=True, huge_tree=self.huge_tree
),
parser=etree.XMLParser(remove_blank_text=True, huge_tree=self.huge_tree),
)
except:
logging.critical(
"Expected some valid XML from the server, but got this: \n"
+ str(self._raw),
"Expected some valid XML from the server, but got this: \n" + str(self._raw),
exc_info=True,
)
raise
if log.level <= logging.DEBUG:
log.debug(etree.tostring(self.tree, pretty_print=True))
elif self.headers.get("Content-Type", "").startswith(
"text/calendar"
) or self.headers.get("Content-Type", "").startswith("text/plain"):
elif self.headers.get("Content-Type", "").startswith("text/calendar") or self.headers.get(
"Content-Type", ""
).startswith("text/plain"):
## text/plain is typically for errors, we shouldn't see it on 200/207 responses.
## TODO: may want to log an error if it's text/plain and 200/207.
## Logic here was moved when refactoring
Expand All @@ -124,9 +119,7 @@ def __init__(
try:
self.tree = etree.XML(
self._raw,
parser=etree.XMLParser(
remove_blank_text=True, huge_tree=self.huge_tree
),
parser=etree.XMLParser(remove_blank_text=True, huge_tree=self.huge_tree),
)
except:
pass
Expand Down Expand Up @@ -193,12 +186,7 @@ def validate_status(self, status: str) -> None:
makes sense to me, but I've only seen it from SOGo, and it's
not in accordance with the examples in rfc6578.
"""
if (
" 200 " not in status
and " 201 " not in status
and " 207 " not in status
and " 404 " not in status
):
if " 200 " not in status and " 201 " not in status and " 207 " not in status and " 404 " not in status:
raise error.ResponseError(status)

def _parse_response(self, response) -> Tuple[str, List[_Element], Optional[Any]]:
Expand Down Expand Up @@ -280,9 +268,7 @@ def find_objects_and_props(self) -> Dict[str, Dict[str, _Element]]:

return self.objects

def _expand_simple_prop(
self, proptag, props_found, multi_value_allowed=False, xpath=None
):
def _expand_simple_prop(self, proptag, props_found, multi_value_allowed=False, xpath=None):
values = []
if proptag in props_found:
prop_xml = props_found[proptag]
Expand Down Expand Up @@ -334,9 +320,7 @@ def expand_simple_props(
if prop.tag is None:
continue

props_found[prop.tag] = self._expand_simple_prop(
prop.tag, props_found, xpath=xpath
)
props_found[prop.tag] = self._expand_simple_prop(prop.tag, props_found, xpath=xpath)
for prop in multi_value_props:
if prop.tag is None:
continue
Expand Down Expand Up @@ -503,9 +487,7 @@ def check_scheduling_support(self) -> bool:
support_list = self.check_dav_support()
return support_list is not None and "calendar-auto-schedule" in support_list

def propfind(
self, url: Optional[str] = None, props: str = "", depth: int = 0
) -> DAVResponse:
def propfind(self, url: Optional[str] = None, props: str = "", depth: int = 0) -> DAVResponse:
"""
Send a propfind request.

Expand All @@ -517,9 +499,7 @@ def propfind(
Returns
* DAVResponse
"""
return self.request(
url or str(self.url), "PROPFIND", props, {"Depth": str(depth)}
)
return self.request(url or str(self.url), "PROPFIND", props, {"Depth": str(depth)})

def proppatch(self, url: str, body: str, dummy: None = None) -> DAVResponse:
"""
Expand Down Expand Up @@ -591,17 +571,13 @@ def mkcalendar(self, url: str, body: str = "", dummy: None = None) -> DAVRespons
"""
return self.request(url, "MKCALENDAR", body)

def put(
self, url: str, body: str, headers: Mapping[str, str] = None
) -> DAVResponse:
def put(self, url: str, body: str, headers: Mapping[str, str] = None) -> DAVResponse:
"""
Send a put request.
"""
return self.request(url, "PUT", body, headers or {})

def post(
self, url: str, body: str, headers: Mapping[str, str] = None
) -> DAVResponse:
def post(self, url: str, body: str, headers: Mapping[str, str] = None) -> DAVResponse:
"""
Send a POST request.
"""
Expand Down Expand Up @@ -684,12 +660,7 @@ def request(
if not r.status_code == 401:
raise

if (
r.status_code == 401
and "WWW-Authenticate" in r.headers
and not self.auth
and self.username
):
if r.status_code == 401 and "WWW-Authenticate" in r.headers and not self.auth and self.username:
auth_types = self.extract_auth_types(r.headers["WWW-Authenticate"])

if self.password and self.username and "digest" in auth_types:
Expand Down Expand Up @@ -725,13 +696,9 @@ def request(
auth_types = self.extract_auth_types(r.headers["WWW-Authenticate"])

if self.password and self.username and "digest" in auth_types:
self.auth = requests.auth.HTTPDigestAuth(
self.username, self.password.decode()
)
self.auth = requests.auth.HTTPDigestAuth(self.username, self.password.decode())
elif self.password and self.username and "basic" in auth_types:
self.auth = requests.auth.HTTPBasicAuth(
self.username, self.password.decode()
)
self.auth = requests.auth.HTTPBasicAuth(self.username, self.password.decode())
elif self.password and "bearer" in auth_types:
self.auth = HTTPBearerAuth(self.password.decode())

Expand All @@ -740,10 +707,7 @@ def request(
return self.request(str(url_obj), method, body, headers)

# this is an error condition that should be raised to the application
if (
response.status == requests.codes.forbidden
or response.status == requests.codes.unauthorized
):
if response.status == requests.codes.forbidden or response.status == requests.codes.unauthorized:
try:
reason = response.reason
except AttributeError:
Expand All @@ -759,24 +723,16 @@ def request(
commlog.write(f"{datetime.datetime.now():%FT%H:%M:%S}".encode("utf-8"))
commlog.write(b"\n====>\n")
commlog.write(f"{method} {url}\n".encode("utf-8"))
commlog.write(
b"\n".join(to_wire(f"{x}: {headers[x]}") for x in headers)
)
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(
b"\n".join(
to_wire(f"{x}: {response.headers[x]}") for x in response.headers
)
)
commlog.write(b"\n".join(to_wire(f"{x}: {response.headers[x]}") for x in response.headers))
commlog.write(b"\n\n")
ct = response.headers.get("Content-Type", "")
if response.tree is not None:
commlog.write(
to_wire(etree.tostring(response.tree, pretty_print=True))
)
commlog.write(to_wire(etree.tostring(response.tree, pretty_print=True)))
else:
commlog.write(to_wire(response._raw))
commlog.write(b"\n")
Expand Down
12 changes: 3 additions & 9 deletions caldav/elements/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,7 @@ class BaseElement:
attributes: Optional[dict] = None
caldav_class = None

def __init__(
self, name: Optional[str] = None, value: Union[str, bytes, None] = None
) -> None:
def __init__(self, name: Optional[str] = None, value: Union[str, bytes, None] = None) -> None:
self.children = []
self.attributes = {}
value = to_unicode(value)
Expand All @@ -41,15 +39,11 @@ def __init__(
if value is not None:
self.value = value

def __add__(
self, other: Union["BaseElement", Iterable["BaseElement"]]
) -> "BaseElement":
def __add__(self, other: Union["BaseElement", Iterable["BaseElement"]]) -> "BaseElement":
return self.append(other)

def __str__(self) -> str:
utf8 = etree.tostring(
self.xmlelement(), encoding="utf-8", xml_declaration=True, pretty_print=True
)
utf8 = etree.tostring(self.xmlelement(), encoding="utf-8", xml_declaration=True, pretty_print=True)
return str(utf8, "utf-8")

def xmlelement(self) -> _Element:
Expand Down
16 changes: 4 additions & 12 deletions caldav/elements/cdav.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,10 @@ def _to_utc_date_string(ts):
mindate = datetime.min.replace(tzinfo=utc_tz)
maxdate = datetime.max.replace(tzinfo=utc_tz)
if mindate + ts.tzinfo.utcoffset(ts) > ts:
logging.error(
"Cannot coerce datetime %s to UTC. Changed to min-date.", ts
)
logging.error("Cannot coerce datetime %s to UTC. Changed to min-date.", ts)
ts = mindate
elif ts > maxdate - ts.tzinfo.utcoffset(ts):
logging.error(
"Cannot coerce datetime %s to UTC. Changed to max-date.", ts
)
logging.error("Cannot coerce datetime %s to UTC. Changed to max-date.", ts)
ts = maxdate
else:
ts = ts.astimezone(utc_tz)
Expand Down Expand Up @@ -108,9 +104,7 @@ def __init__(self, value, collation: str = "i;octet", negate: bool = False) -> N
class TimeRange(BaseElement):
tag: ClassVar[str] = ns("C", "time-range")

def __init__(
self, start: Optional[datetime] = None, end: Optional[datetime] = None
) -> None:
def __init__(self, start: Optional[datetime] = None, end: Optional[datetime] = None) -> None:
## start and end should be an icalendar "date with UTC time",
## ref https://tools.ietf.org/html/rfc4791#section-9.9
super(TimeRange, self).__init__()
Expand All @@ -136,9 +130,7 @@ class CalendarData(BaseElement):
class Expand(BaseElement):
tag: ClassVar[str] = ns("C", "expand")

def __init__(
self, start: Optional[datetime], end: Optional[datetime] = None
) -> None:
def __init__(self, start: Optional[datetime], end: Optional[datetime] = None) -> None:
super(Expand, self).__init__()

if self.attributes is None:
Expand Down
4 changes: 1 addition & 3 deletions caldav/lib/error.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,7 @@ def assert_(condition: object) -> None:
assert condition
except AssertionError:
if debugmode == "PRODUCTION":
log.error(
"Deviation from expectations found. %s" % ERR_FRAGMENT, exc_info=True
)
log.error("Deviation from expectations found. %s" % ERR_FRAGMENT, exc_info=True)
elif debugmode == "DEBUG_PDB":
log.error("Deviation from expectations found. Dropping into debugger")
import pdb
Expand Down
3 changes: 1 addition & 2 deletions caldav/lib/url.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,7 @@ def unauth(self) -> "URL":
return URL.objectify(
ParseResult(
self.scheme,
"%s:%s"
% (self.hostname, self.port or {"https": 443, "http": 80}[self.scheme]),
"%s:%s" % (self.hostname, self.port or {"https": 443, "http": 80}[self.scheme]),
self.path.replace("//", "/"),
self.params,
self.query,
Expand Down
29 changes: 5 additions & 24 deletions caldav/lib/vcal.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,7 @@ def fix(event):

## TODO: add ^ before COMPLETED and CREATED?
## 1) Add an arbitrary time if completed is given as date
fixed = re.sub(
r"COMPLETED(?:;VALUE=DATE)?:(\d+)\s", r"COMPLETED:\g<1>T120000Z", event
)
fixed = re.sub(r"COMPLETED(?:;VALUE=DATE)?:(\d+)\s", r"COMPLETED:\g<1>T120000Z", event)

## 2) CREATED timestamps prior to epoch does not make sense,
## change from year 0001 to epoch.
Expand All @@ -81,10 +79,7 @@ def fix(event):
## 5 prepare to remove DURATION or DTEND/DUE if both DURATION and
## DTEND/DUE is set.
## remove duplication of DTSTAMP
fixed2 = (
"\n".join(filter(LineFilterDiscardingDuplicates(), fixed.strip().split("\n")))
+ "\n"
)
fixed2 = "\n".join(filter(LineFilterDiscardingDuplicates(), fixed.strip().split("\n"))) + "\n"

if fixed2 != event:
global fixup_error_loggings
Expand All @@ -105,13 +100,7 @@ def fix(event):
try:
import difflib

log(
"\n".join(
difflib.unified_diff(
event.split("\n"), fixed2.split("\n"), lineterm=""
)
)
)
log("\n".join(difflib.unified_diff(event.split("\n"), fixed2.split("\n"), lineterm="")))
except:
log("Original: \n" + event)
log("Modified: \n" + fixed2)
Expand Down Expand Up @@ -168,20 +157,12 @@ def create_ical(ical_fragment=None, objtype=None, language="en_DK", **props):
## 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 "\nSTATUS:" not in (ical_fragment or "")
and objtype == "VTODO"
):
if not props.get("status") and "\nSTATUS:" not in (ical_fragment or "") and objtype == "VTODO":
props["status"] = "NEEDS-ACTION"

else:
if not ical_fragment.strip().startswith("BEGIN:VCALENDAR"):
ical_fragment = (
"BEGIN:VCALENDAR\n"
+ to_normal_str(ical_fragment.strip())
+ "\nEND:VCALENDAR\n"
)
ical_fragment = "BEGIN:VCALENDAR\n" + to_normal_str(ical_fragment.strip()) + "\nEND:VCALENDAR\n"
my_instance = icalendar.Calendar.from_ical(ical_fragment)
component = my_instance.subcomponents[0]
ical_fragment = None
Expand Down
Loading
Loading