Skip to content
Closed
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
10 changes: 8 additions & 2 deletions src/fsutil/paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,14 @@ def get_filename(path: PathIn) -> str:
"""
Get the filename from the given path/url.
"""
path = _get_path(path)
filepath = urlsplit(path).path
raw_path = str(path) if path is not None else ""
url_split = urlsplit(raw_path) if raw_path else None
if url_split and url_split.scheme:
# url (eg. "https://domain.com/file.txt?query=param")
filepath = url_split.path
else:
# filesystem path (its filename can contain "?" / "#" chars)
filepath = _get_path(path)
filename = os.path.basename(filepath)
return filename

Expand Down
13 changes: 13 additions & 0 deletions tests/test_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,19 @@ def test_move_file(temp_path):
assert fsutil.is_file(temp_path("a/c.txt"))


def test_move_file_with_special_chars_in_filename(temp_path):
"""
Regression test: filenames containing "?" / "#" characters
must not be truncated when moving the file.
"""
fsutil.create_file(temp_path("file?v1.txt"), content="Hello")
fsutil.create_file(temp_path("file#2.txt"), content="World")
fsutil.move_file(temp_path("file?v1.txt"), temp_path("dest/"))
fsutil.move_file(temp_path("file#2.txt"), temp_path("dest/"))
assert fsutil.read_file(temp_path("dest/file?v1.txt")) == "Hello"
assert fsutil.read_file(temp_path("dest/file#2.txt")) == "World"


def test_rename_dir(temp_path):
path = temp_path("a/b/c")
fsutil.make_dirs(path)
Expand Down
3 changes: 3 additions & 0 deletions tests/test_paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ def test_get_filename():
fsutil.get_filename("https://domain-name.com/Document.txt?p=1")
== "Document.txt"
)
# filenames can contain "?" / "#" characters (not URL query/fragment)
assert fsutil.get_filename("/root/a/b/c/Document?v1.txt") == "Document?v1.txt"
assert fsutil.get_filename("/root/a/b/c/Document#1.txt") == "Document#1.txt"


def test_get_parent_dir():
Expand Down
Loading