path_utils.py 1.1 KB

1234567891011121314151617181920212223242526272829303132
  1. import pathlib
  2. import urllib
  3. """Cross-platform utilities for manipulating paths and URIs.
  4. NOTE: All functions in this file must support POSIX and Windows.
  5. """
  6. def is_path(path_or_uri: str) -> bool:
  7. """Returns True if uri_or_path is a path and False otherwise.
  8. Windows paths start with a drive name which can be interpreted as
  9. a URI scheme by urlparse and thus needs to be treated differently
  10. form POSIX paths.
  11. E.g. Creating a directory returns the path 'C:\\Users\\mp5n6ul72w\\working_dir'
  12. will have the scheme 'C:'.
  13. """
  14. if not isinstance(path_or_uri, str):
  15. raise TypeError(f" path_or_uri must be a string, got {type(path_or_uri)}.")
  16. parsed_path = pathlib.Path(path_or_uri)
  17. parsed_uri = urllib.parse.urlparse(path_or_uri)
  18. if isinstance(parsed_path, pathlib.PurePosixPath):
  19. return not parsed_uri.scheme
  20. elif isinstance(parsed_path, pathlib.PureWindowsPath):
  21. return parsed_uri.scheme == parsed_path.drive.strip(":").lower()
  22. else:
  23. # this should never happen.
  24. raise TypeError(f"Unsupported path type: {type(parsed_path).__name__}")