__init__.py 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. from __future__ import annotations
  2. import os
  3. import pathlib
  4. from typing import Sequence
  5. # vestigal things from IPython_genutils.
  6. def cast_unicode(s: str | bytes, encoding: str = "utf-8") -> str:
  7. if isinstance(s, bytes):
  8. return s.decode(encoding, "replace")
  9. return s
  10. def filefind(filename: str, path_dirs: Sequence[str] | None = None) -> str:
  11. """Find a file by looking through a sequence of paths.
  12. This iterates through a sequence of paths looking for a file and returns
  13. the full, absolute path of the first occurrence of the file. If no set of
  14. path dirs is given, the filename is tested as is, after running through
  15. :func:`expandvars` and :func:`expanduser`. Thus a simple call::
  16. filefind('myfile.txt')
  17. will find the file in the current working dir, but::
  18. filefind('~/myfile.txt')
  19. Will find the file in the users home directory. This function does not
  20. automatically try any paths, such as the cwd or the user's home directory.
  21. Parameters
  22. ----------
  23. filename : str
  24. The filename to look for.
  25. path_dirs : str, None or sequence of str
  26. The sequence of paths to look for the file in. If None, the filename
  27. need to be absolute or be in the cwd. If a string, the string is
  28. put into a sequence and the searched. If a sequence, walk through
  29. each element and join with ``filename``, calling :func:`expandvars`
  30. and :func:`expanduser` before testing for existence.
  31. Returns
  32. -------
  33. Raises :exc:`IOError` or returns absolute path to file.
  34. """
  35. # If paths are quoted, abspath gets confused, strip them...
  36. filename = filename.strip('"').strip("'")
  37. # If the input is an absolute path, just check it exists
  38. if os.path.isabs(filename) and os.path.isfile(filename):
  39. return filename
  40. if path_dirs is None:
  41. path_dirs = ("",)
  42. elif isinstance(path_dirs, str):
  43. path_dirs = (path_dirs,)
  44. elif isinstance(path_dirs, pathlib.Path):
  45. path_dirs = (str(path_dirs),)
  46. for path in path_dirs:
  47. if path == ".":
  48. path = os.getcwd()
  49. testname = expand_path(os.path.join(path, filename))
  50. if os.path.isfile(testname):
  51. return os.path.abspath(testname)
  52. raise OSError(f"File {filename!r} does not exist in any of the search paths: {path_dirs!r}")
  53. def expand_path(s: str) -> str:
  54. """Expand $VARS and ~names in a string, like a shell
  55. :Examples:
  56. In [2]: os.environ['FOO']='test'
  57. In [3]: expand_path('variable FOO is $FOO')
  58. Out[3]: 'variable FOO is test'
  59. """
  60. # This is a pretty subtle hack. When expand user is given a UNC path
  61. # on Windows (\\server\share$\%username%), os.path.expandvars, removes
  62. # the $ to get (\\server\share\%username%). I think it considered $
  63. # alone an empty var. But, we need the $ to remains there (it indicates
  64. # a hidden share).
  65. if os.name == "nt":
  66. s = s.replace("$\\", "IPYTHON_TEMP")
  67. s = os.path.expandvars(os.path.expanduser(s))
  68. if os.name == "nt":
  69. s = s.replace("IPYTHON_TEMP", "$\\")
  70. return s