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)
| 27 | |
| 28 | |
| 29 | def 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 | |
| 68 | def path_handlers(path, posix=True): |
nothing calls this directly
no test coverage detected