fix: improve join_url - use walrus op, remove posixpath.normpath
Co-authored-by: christianlouis <361235+christianlouis@users.noreply.github.com> Agent-Logs-Url: https://github.com/christianlouis/DocuElevate/sessions/54fd29b1-b600-4e60-aa0a-a069836ad129
This commit is contained in:
+10
-13
@@ -1,6 +1,5 @@
|
|||||||
import ipaddress
|
import ipaddress
|
||||||
import logging
|
import logging
|
||||||
import posixpath
|
|
||||||
import socket
|
import socket
|
||||||
from urllib.parse import urlsplit, urlunsplit
|
from urllib.parse import urlsplit, urlunsplit
|
||||||
|
|
||||||
@@ -41,23 +40,21 @@ def join_url(base: str, *parts: str) -> str:
|
|||||||
Safely join a base URL with one or more path parts.
|
Safely join a base URL with one or more path parts.
|
||||||
|
|
||||||
Uses urllib.parse to correctly handle scheme/netloc/query/fragment so that
|
Uses urllib.parse to correctly handle scheme/netloc/query/fragment so that
|
||||||
only the path component is normalised (double slashes removed via
|
only the path component is modified. Leading and trailing slashes are
|
||||||
posixpath.join). The scheme separator ``://`` is therefore never at risk
|
stripped from each part before joining, preventing double-slash sequences
|
||||||
of being collapsed.
|
at segment boundaries without touching the scheme separator or query string.
|
||||||
|
|
||||||
Examples:
|
Examples:
|
||||||
join_url("https://example.com/dav/", "/remote/", "file.pdf")
|
join_url("https://example.com/dav/", "/remote/", "file.pdf")
|
||||||
-> "https://example.com/dav/remote/file.pdf"
|
-> "https://example.com/dav/remote/file.pdf"
|
||||||
"""
|
"""
|
||||||
parsed = urlsplit(base)
|
parsed = urlsplit(base)
|
||||||
# Strip leading/trailing slashes from every part so posixpath.join
|
# Strip each part once and filter out empty segments; use walrus operator
|
||||||
# produces a clean joined path without accidental double slashes.
|
# to avoid calling strip twice per iteration.
|
||||||
stripped_parts = [p.strip("/") for p in parts if p.strip("/")]
|
stripped_parts = [s for p in parts if (s := p.strip("/"))]
|
||||||
base_path = parsed.path.rstrip("/")
|
base_path = parsed.path.rstrip("/")
|
||||||
if stripped_parts:
|
new_path = base_path + "/" + "/".join(stripped_parts) if stripped_parts else base_path
|
||||||
new_path = base_path + "/" + "/".join(stripped_parts)
|
# Ensure path is non-empty so the reconstructed URL is valid.
|
||||||
else:
|
if not new_path:
|
||||||
new_path = base_path
|
new_path = "/"
|
||||||
# Normalise any remaining double slashes in the path only.
|
|
||||||
new_path = posixpath.normpath(new_path) if new_path else "/"
|
|
||||||
return urlunsplit((parsed.scheme, parsed.netloc, new_path, parsed.query, parsed.fragment))
|
return urlunsplit((parsed.scheme, parsed.netloc, new_path, parsed.query, parsed.fragment))
|
||||||
|
|||||||
Reference in New Issue
Block a user