diff --git a/src/fsutil/paths.py b/src/fsutil/paths.py index e009edd..d0c8215 100644 --- a/src/fsutil/paths.py +++ b/src/fsutil/paths.py @@ -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 diff --git a/tests/test_operations.py b/tests/test_operations.py index ee8051e..07ddac4 100644 --- a/tests/test_operations.py +++ b/tests/test_operations.py @@ -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) diff --git a/tests/test_paths.py b/tests/test_paths.py index a8bf57d..b387068 100644 --- a/tests/test_paths.py +++ b/tests/test_paths.py @@ -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():