-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathpath_to_string.py
More file actions
27 lines (23 loc) · 966 Bytes
/
path_to_string.py
File metadata and controls
27 lines (23 loc) · 966 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
"""Helper function file"""
from urllib.parse import urlparse
from pathlib import PurePath
def path_to_string(path):
"""Converts an obj that represents a path into a string"""
if isinstance(path, str):
try:
parsed_url = urlparse(path)
if parsed_url and parsed_url.scheme == "file":
return parsed_url.path
except Exception:
return None
return path
if isinstance(path, bytes):
# Use errors="replace" so invalid bytes (e.g. \xff, surrogate sequences)
# don't silently suppress path traversal detection — the replacement char
# preserves the traversal components that follow.
return path.decode("utf-8", errors="replace")
if isinstance(path, PurePath):
# Stringify PurePath. This can still allow path traversal but in extremely
# limited cases so it's safe to just stringify for now.
return str(path)
return None