Skip to content

Commit 050a2c2

Browse files
authored
Merge pull request #242 from joe733/workshop
maint: simplified `hostname` module
2 parents 9fe2411 + 0daa303 commit 050a2c2

File tree

1 file changed

+22
-13
lines changed

1 file changed

+22
-13
lines changed

validators/hostname.py

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,21 @@ def _simple_hostname_regex():
2626
return re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]$")
2727

2828

29+
def _port_validator(value: str):
30+
"""Returns host segment if port is valid."""
31+
if value.count("]:") == 1:
32+
# with ipv6
33+
host_seg, port_seg = value.rsplit(":", 1)
34+
if _port_regex().match(f":{port_seg}"):
35+
return host_seg.lstrip("[").rstrip("]")
36+
37+
if value.count(":") == 1:
38+
# with ipv4 or simple hostname
39+
host_seg, port_seg = value.rsplit(":", 1)
40+
if _port_regex().match(f":{port_seg}"):
41+
return host_seg
42+
43+
2944
@validator
3045
def hostname(
3146
value: str,
@@ -85,19 +100,13 @@ def hostname(
85100
86101
> *New in version 0.21.0*.
87102
"""
88-
if may_have_port:
89-
if value.count("]:") == 1 and not skip_ip_addr:
90-
host_seg, port_seg = value.rsplit(":", 1)
91-
return _port_regex().match(f":{port_seg}") and ipv6(
92-
host_seg.lstrip("[").rstrip("]"), cidr=False
93-
)
94-
if value.count(":") == 1:
95-
host_seg, port_seg = value.rsplit(":", 1)
96-
return _port_regex().match(f":{port_seg}") and (
97-
(_simple_hostname_regex().match(host_seg) if maybe_simple else False)
98-
or domain(host_seg, rfc_1034=rfc_1034, rfc_2782=rfc_2782)
99-
or (False if skip_ip_addr else ipv4(host_seg, cidr=False))
100-
)
103+
if may_have_port and (host_seg := _port_validator(value)):
104+
return (
105+
(_simple_hostname_regex().match(host_seg) if maybe_simple else False)
106+
or domain(host_seg, rfc_1034=rfc_1034, rfc_2782=rfc_2782)
107+
or (False if skip_ip_addr else ipv4(host_seg, cidr=False))
108+
or (False if skip_ip_addr else ipv6(host_seg, cidr=False))
109+
)
101110

102111
return (
103112
(_simple_hostname_regex().match(value) if maybe_simple else False)

0 commit comments

Comments
 (0)