Skip to content

Commit

Permalink
fix python-hyper#68: allow IPv6 literal in to_uri()
Browse files Browse the repository at this point in the history
  • Loading branch information
Lu Baumann committed Sep 25, 2024
1 parent ec7d172 commit 08ce1c3
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion src/hyperlink/_url.py
Original file line number Diff line number Diff line change
Expand Up @@ -1019,6 +1019,8 @@ def __init__(
)

_, self._host = parse_host(_textcheck("host", host, "/?#@"))
# Compute only if needed
self._host_is_ipv6_literal = None
if isinstance(path, Text):
raise TypeError(
"expected iterable of text for path, not: %r" % (path,)
Expand Down Expand Up @@ -1188,6 +1190,22 @@ def user(self):
"""
return self.userinfo.split(u":")[0]

@property
def _host_idna_error(self):
# type: () -> bool
"""Whether idna can encode the host
idna does not encode empty strings and ipv6 addresses.
This is by design.
"""
if self._host_is_ipv6_literal is None:
try:
socket.inet_pton(socket.AF_INET6, self.host)
self._host_is_ipv6_literal = True
except OSError:
self._host_is_ipv6_literal = False
return self._host_is_ipv6_literal or not self.host

def authority(self, with_password=False, **kw):
# type: (bool, Any) -> Text
"""Compute and return the appropriate host/port/userinfo combination.
Expand Down Expand Up @@ -1669,7 +1687,7 @@ def to_uri(self):
)
new_host = (
self.host
if not self.host
if self._host_idna_error
else idna_encode(self.host, uts46=True).decode("ascii")
)
return self.replace(
Expand Down

0 comments on commit 08ce1c3

Please sign in to comment.