From 0ceb05205f1c6a5c67bcceaed73e250d23478de6 Mon Sep 17 00:00:00 2001 From: rajanpanth Date: Sat, 5 Dec 2026 10:23:17 +0545 Subject: [PATCH] fix(uri): keep IPv6 brackets when rebuilding a URL rebuild_uri copied the hostname without brackets, so an IPv6 address was no longer a valid URL. Port 0 was also dropped because it is falsy. Co-authored-by: Cursor --- src/zimscraperlib/uri.py | 29 ++++++++++++++++++++++++----- tests/uri/test_uri.py | 8 ++++++++ 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/src/zimscraperlib/uri.py b/src/zimscraperlib/uri.py index 52f3aacb..dd3ec845 100644 --- a/src/zimscraperlib/uri.py +++ b/src/zimscraperlib/uri.py @@ -5,6 +5,29 @@ from zimscraperlib.misc import first +def _netloc( + username: str | None, + password: str | None, + hostname: str | None, + port: str | int | None, +) -> str: + """Authority string. IPv6 hosts are bracketed, and port 0 is kept.""" + user = username or "" + secret = password or "" + if user or secret: + auth = f"{user}:{secret}@" if secret else f"{user}@" + else: + auth = "" + + host = hostname or "" + if ":" in host and not host.startswith("["): + host = f"[{host}]" + + if port is None or port == "": + return f"{auth}{host}" + return f"{auth}{host}:{port}" + + def rebuild_uri( # noqa: PLR0917 uri: urllib.parse.ParseResult, scheme: str | None = None, @@ -22,11 +45,7 @@ def rebuild_uri( # noqa: PLR0917 password = first(password, uri.password) hostname = first(hostname, uri.hostname) port = first(port, uri.port) - netloc = ( - f"{username}{':' if password else ''}{password}" - f"{'@' if username or password else ''}{hostname}" - f"{':' if port else ''}{port}" - ) + netloc = _netloc(username, password, hostname, port) return urllib.parse.urlparse( urllib.parse.urlunparse( ( diff --git a/tests/uri/test_uri.py b/tests/uri/test_uri.py index 802fca82..2fe39099 100644 --- a/tests/uri/test_uri.py +++ b/tests/uri/test_uri.py @@ -49,6 +49,14 @@ }, "http://localhost", ), + ("http://[::1]:8080/a", {}, "http://[::1]:8080/a"), + ("http://[::1]:8080/a", {"path": "/b"}, "http://[::1]:8080/b"), + ( + "http://user:pass@[::1]/a", + {"query": "q=1"}, + "http://user:pass@[::1]/a?q=1", + ), + ("http://localhost", {"port": 0}, "http://localhost:0"), ], ) def test_rebuild_uri(uri: str, changes: dict[str, Any], expected: str):