path.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. # encoding: utf-8
  2. """
  3. Utilities for path handling.
  4. """
  5. # Copyright (c) IPython Development Team.
  6. # Distributed under the terms of the Modified BSD License.
  7. import os
  8. import sys
  9. import errno
  10. import shutil
  11. import random
  12. import glob
  13. import warnings
  14. from IPython.utils.process import system
  15. #-----------------------------------------------------------------------------
  16. # Code
  17. #-----------------------------------------------------------------------------
  18. fs_encoding = sys.getfilesystemencoding()
  19. def _writable_dir(path: str) -> bool:
  20. """Whether `path` is a directory, to which the user has write access."""
  21. return os.path.isdir(path) and os.access(path, os.W_OK)
  22. if sys.platform == 'win32':
  23. def _get_long_path_name(path):
  24. """Get a long path name (expand ~) on Windows using ctypes.
  25. Examples
  26. --------
  27. >>> get_long_path_name('c:\\\\docume~1')
  28. 'c:\\\\Documents and Settings'
  29. """
  30. try:
  31. import ctypes
  32. except ImportError as e:
  33. raise ImportError('you need to have ctypes installed for this to work') from e
  34. _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW
  35. _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p,
  36. ctypes.c_uint ]
  37. buf = ctypes.create_unicode_buffer(260)
  38. rv = _GetLongPathName(path, buf, 260)
  39. if rv == 0 or rv > 260:
  40. return path
  41. else:
  42. return buf.value
  43. else:
  44. def _get_long_path_name(path):
  45. """Dummy no-op."""
  46. return path
  47. def get_long_path_name(path):
  48. """Expand a path into its long form.
  49. On Windows this expands any ~ in the paths. On other platforms, it is
  50. a null operation.
  51. """
  52. return _get_long_path_name(path)
  53. def compress_user(path: str) -> str:
  54. """Reverse of :func:`os.path.expanduser`"""
  55. home = os.path.expanduser("~")
  56. if path.startswith(home):
  57. path = "~" + path[len(home):]
  58. return path
  59. def get_py_filename(name):
  60. """Return a valid python filename in the current directory.
  61. If the given name is not a file, it adds '.py' and searches again.
  62. Raises IOError with an informative message if the file isn't found.
  63. """
  64. name = os.path.expanduser(name)
  65. if os.path.isfile(name):
  66. return name
  67. if not name.endswith(".py"):
  68. py_name = name + ".py"
  69. if os.path.isfile(py_name):
  70. return py_name
  71. raise IOError("File `%r` not found." % name)
  72. def filefind(filename: str, path_dirs=None) -> str:
  73. """Find a file by looking through a sequence of paths.
  74. This iterates through a sequence of paths looking for a file and returns
  75. the full, absolute path of the first occurrence of the file. If no set of
  76. path dirs is given, the filename is tested as is, after running through
  77. :func:`expandvars` and :func:`expanduser`. Thus a simple call::
  78. filefind('myfile.txt')
  79. will find the file in the current working dir, but::
  80. filefind('~/myfile.txt')
  81. Will find the file in the users home directory. This function does not
  82. automatically try any paths, such as the cwd or the user's home directory.
  83. Parameters
  84. ----------
  85. filename : str
  86. The filename to look for.
  87. path_dirs : str, None or sequence of str
  88. The sequence of paths to look for the file in. If None, the filename
  89. need to be absolute or be in the cwd. If a string, the string is
  90. put into a sequence and the searched. If a sequence, walk through
  91. each element and join with ``filename``, calling :func:`expandvars`
  92. and :func:`expanduser` before testing for existence.
  93. Returns
  94. -------
  95. path : str
  96. returns absolute path to file.
  97. Raises
  98. ------
  99. IOError
  100. """
  101. # If paths are quoted, abspath gets confused, strip them...
  102. filename = filename.strip('"').strip("'")
  103. # If the input is an absolute path, just check it exists
  104. if os.path.isabs(filename) and os.path.isfile(filename):
  105. return filename
  106. if path_dirs is None:
  107. path_dirs = ("",)
  108. elif isinstance(path_dirs, str):
  109. path_dirs = (path_dirs,)
  110. for path in path_dirs:
  111. if path == '.': path = os.getcwd()
  112. testname = expand_path(os.path.join(path, filename))
  113. if os.path.isfile(testname):
  114. return os.path.abspath(testname)
  115. raise IOError("File %r does not exist in any of the search paths: %r" %
  116. (filename, path_dirs) )
  117. class HomeDirError(Exception):
  118. pass
  119. def get_home_dir(require_writable: bool=False) -> str:
  120. """Return the 'home' directory, as a unicode string.
  121. Uses os.path.expanduser('~'), and checks for writability.
  122. See stdlib docs for how this is determined.
  123. For Python <3.8, $HOME is first priority on *ALL* platforms.
  124. For Python >=3.8 on Windows, %HOME% is no longer considered.
  125. Parameters
  126. ----------
  127. require_writable : bool [default: False]
  128. if True:
  129. guarantees the return value is a writable directory, otherwise
  130. raises HomeDirError
  131. if False:
  132. The path is resolved, but it is not guaranteed to exist or be writable.
  133. """
  134. homedir = os.path.expanduser('~')
  135. # Next line will make things work even when /home/ is a symlink to
  136. # /usr/home as it is on FreeBSD, for example
  137. homedir = os.path.realpath(homedir)
  138. if not _writable_dir(homedir) and os.name == 'nt':
  139. # expanduser failed, use the registry to get the 'My Documents' folder.
  140. try:
  141. import winreg as wreg
  142. with wreg.OpenKey(
  143. wreg.HKEY_CURRENT_USER,
  144. r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
  145. ) as key:
  146. homedir = wreg.QueryValueEx(key,'Personal')[0]
  147. except:
  148. pass
  149. if (not require_writable) or _writable_dir(homedir):
  150. assert isinstance(homedir, str), "Homedir should be unicode not bytes"
  151. return homedir
  152. else:
  153. raise HomeDirError('%s is not a writable dir, '
  154. 'set $HOME environment variable to override' % homedir)
  155. def get_xdg_dir() -> str | None:
  156. """Return the XDG_CONFIG_HOME, if it is defined and exists, else None.
  157. This is only for non-OS X posix (Linux,Unix,etc.) systems.
  158. """
  159. env = os.environ
  160. if os.name == "posix":
  161. # Linux, Unix, AIX, etc.
  162. # use ~/.config if empty OR not set
  163. xdg = env.get("XDG_CONFIG_HOME", None) or os.path.join(get_home_dir(), '.config')
  164. if xdg and _writable_dir(xdg):
  165. assert isinstance(xdg, str)
  166. return xdg
  167. return None
  168. def get_xdg_cache_dir():
  169. """Return the XDG_CACHE_HOME, if it is defined and exists, else None.
  170. This is only for non-OS X posix (Linux,Unix,etc.) systems.
  171. """
  172. env = os.environ
  173. if os.name == "posix":
  174. # Linux, Unix, AIX, etc.
  175. # use ~/.cache if empty OR not set
  176. xdg = env.get("XDG_CACHE_HOME", None) or os.path.join(get_home_dir(), '.cache')
  177. if xdg and _writable_dir(xdg):
  178. assert isinstance(xdg, str)
  179. return xdg
  180. return None
  181. def expand_path(s: str) -> str:
  182. """Expand $VARS and ~names in a string, like a shell
  183. :Examples:
  184. In [2]: os.environ['FOO']='test'
  185. In [3]: expand_path('variable FOO is $FOO')
  186. Out[3]: 'variable FOO is test'
  187. """
  188. # This is a pretty subtle hack. When expand user is given a UNC path
  189. # on Windows (\\server\share$\%username%), os.path.expandvars, removes
  190. # the $ to get (\\server\share\%username%). I think it considered $
  191. # alone an empty var. But, we need the $ to remains there (it indicates
  192. # a hidden share).
  193. if os.name=='nt':
  194. s = s.replace('$\\', 'IPYTHON_TEMP')
  195. s = os.path.expandvars(os.path.expanduser(s))
  196. if os.name=='nt':
  197. s = s.replace('IPYTHON_TEMP', '$\\')
  198. return s
  199. def unescape_glob(string):
  200. """Unescape glob pattern in `string`."""
  201. def unescape(s):
  202. for pattern in '*[]!?':
  203. s = s.replace(r'\{0}'.format(pattern), pattern)
  204. return s
  205. return '\\'.join(map(unescape, string.split('\\\\')))
  206. def shellglob(args):
  207. """
  208. Do glob expansion for each element in `args` and return a flattened list.
  209. Unmatched glob pattern will remain as-is in the returned list.
  210. """
  211. expanded = []
  212. # Do not unescape backslash in Windows as it is interpreted as
  213. # path separator:
  214. unescape = unescape_glob if sys.platform != 'win32' else lambda x: x
  215. for a in args:
  216. expanded.extend(glob.glob(a) or [unescape(a)])
  217. return expanded
  218. ENOLINK = 1998
  219. def link(src, dst):
  220. """Hard links ``src`` to ``dst``, returning 0 or errno.
  221. Note that the special errno ``ENOLINK`` will be returned if ``os.link`` isn't
  222. supported by the operating system.
  223. """
  224. if not hasattr(os, "link"):
  225. return ENOLINK
  226. link_errno = 0
  227. try:
  228. os.link(src, dst)
  229. except OSError as e:
  230. link_errno = e.errno
  231. return link_errno
  232. def link_or_copy(src, dst):
  233. """Attempts to hardlink ``src`` to ``dst``, copying if the link fails.
  234. Attempts to maintain the semantics of ``shutil.copy``.
  235. Because ``os.link`` does not overwrite files, a unique temporary file
  236. will be used if the target already exists, then that file will be moved
  237. into place.
  238. """
  239. if os.path.isdir(dst):
  240. dst = os.path.join(dst, os.path.basename(src))
  241. link_errno = link(src, dst)
  242. if link_errno == errno.EEXIST:
  243. if os.stat(src).st_ino == os.stat(dst).st_ino:
  244. # dst is already a hard link to the correct file, so we don't need
  245. # to do anything else. If we try to link and rename the file
  246. # anyway, we get duplicate files - see http://bugs.python.org/issue21876
  247. return
  248. new_dst = dst + "-temp-%04X" %(random.randint(1, 16**4), )
  249. try:
  250. link_or_copy(src, new_dst)
  251. except:
  252. try:
  253. os.remove(new_dst)
  254. except OSError:
  255. pass
  256. raise
  257. os.rename(new_dst, dst)
  258. elif link_errno != 0:
  259. # Either link isn't supported, or the filesystem doesn't support
  260. # linking, or 'src' and 'dst' are on different filesystems.
  261. shutil.copy(src, dst)
  262. def ensure_dir_exists(path: str, mode: int=0o755):
  263. """ensure that a directory exists
  264. If it doesn't exist, try to create it and protect against a race condition
  265. if another process is doing the same.
  266. The default permissions are 755, which differ from os.makedirs default of 777.
  267. """
  268. if not os.path.exists(path):
  269. try:
  270. os.makedirs(path, mode=mode)
  271. except OSError as e:
  272. if e.errno != errno.EEXIST:
  273. raise
  274. elif not os.path.isdir(path):
  275. raise IOError("%r exists but is not a directory" % path)