Skip to content
Open
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
29 changes: 24 additions & 5 deletions src/zimscraperlib/uri.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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(
(
Expand Down
8 changes: 8 additions & 0 deletions tests/uri/test_uri.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down