MCPcopy Create free account
hub / github.com/aboutcode-org/scancode-toolkit / safe_path

Function safe_path

src/commoncode/paths.py:29–65  ·  view source on GitHub ↗

Convert `path` to a safe and portable POSIX path usable on multiple OSes. The returned path is an ASCII-only byte string, resolved for relative segments and itself relative. The `path` is treated as a POSIX path if `posix` is True or as a Windows path with blackslash separators

(path, posix=False, preserve_spaces=False, posix_only=False)

Source from the content-addressed store, hash-verified

27
28
29def safe_path(path, posix=False, preserve_spaces=False, posix_only=False):
30 """
31 Convert `path` to a safe and portable POSIX path usable on multiple OSes.
32 The returned path is an ASCII-only byte string, resolved for relative
33 segments and itself relative.
34
35 The `path` is treated as a POSIX path if `posix` is True or as a Windows
36 path with blackslash separators otherwise.
37
38 If `preserve_spaces` is True, then the spaces in `path` will not be replaced.
39 """
40 # if the path is UTF, try to use unicode instead
41 if not isinstance(path, str):
42 path = as_unicode(path)
43
44 path = path.strip()
45
46 if not is_posixpath(path):
47 path = as_winpath(path)
48 posix = False
49
50 path = resolve(path, posix)
51
52 _pathmod, path_sep = path_handlers(path, posix)
53
54 segments = [s.strip() for s in path.split(path_sep) if s.strip()]
55 segments = [
56 portable_filename(s, preserve_spaces=preserve_spaces, posix_only=posix_only)
57 for s in segments
58 ]
59
60 if not segments:
61 return "_"
62
63 # always return posix
64 path = "/".join(segments)
65 return as_posixpath(path)
66
67
68def path_handlers(path, posix=True):

Callers

nothing calls this directly

Calls 9

as_unicodeFunction · 0.90
is_posixpathFunction · 0.90
as_winpathFunction · 0.90
as_posixpathFunction · 0.90
path_handlersFunction · 0.85
portable_filenameFunction · 0.85
resolveFunction · 0.70
splitMethod · 0.45
joinMethod · 0.45

Tested by

no test coverage detected