path.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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):
  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):
  54. """Reverse of :func:`os.path.expanduser`
  55. """
  56. home = os.path.expanduser('~')
  57. if path.startswith(home):
  58. path = "~" + path[len(home):]
  59. return path
  60. def get_py_filename(name):
  61. """Return a valid python filename in the current directory.
  62. If the given name is not a file, it adds '.py' and searches again.
  63. Raises IOError with an informative message if the file isn't found.
  64. """
  65. name = os.path.expanduser(name)
  66. if os.path.isfile(name):
  67. return name
  68. if not name.endswith(".py"):
  69. py_name = name + ".py"
  70. if os.path.isfile(py_name):
  71. return py_name
  72. raise IOError("File `%r` not found." % name)
  73. def filefind(filename: str, path_dirs=None) -> str:
  74. """Find a file by looking through a sequence of paths.
  75. This iterates through a sequence of paths looking for a file and returns
  76. the full, absolute path of the first occurrence of the file. If no set of
  77. path dirs is given, the filename is tested as is, after running through
  78. :func:`expandvars` and :func:`expanduser`. Thus a simple call::
  79. filefind('myfile.txt')
  80. will find the file in the current working dir, but::
  81. filefind('~/myfile.txt')
  82. Will find the file in the users home directory. This function does not
  83. automatically try any paths, such as the cwd or the user's home directory.
  84. Parameters
  85. ----------
  86. filename : str
  87. The filename to look for.
  88. path_dirs : str, None or sequence of str
  89. The sequence of paths to look for the file in. If None, the filename
  90. need to be absolute or be in the cwd. If a string, the string is
  91. put into a sequence and the searched. If a sequence, walk through
  92. each element and join with ``filename``, calling :func:`expandvars`
  93. and :func:`expanduser` before testing for existence.
  94. Returns
  95. -------
  96. path : str
  97. returns absolute path to file.
  98. Raises
  99. ------
  100. IOError
  101. """
  102. # If paths are quoted, abspath gets confused, strip them...
  103. filename = filename.strip('"').strip("'")
  104. # If the input is an absolute path, just check it exists
  105. if os.path.isabs(filename) and os.path.isfile(filename):
  106. return filename
  107. if path_dirs is None:
  108. path_dirs = ("",)
  109. elif isinstance(path_dirs, str):
  110. path_dirs = (path_dirs,)
  111. for path in path_dirs:
  112. if path == '.': path = os.getcwd()
  113. testname = expand_path(os.path.join(path, filename))
  114. if os.path.isfile(testname):
  115. return os.path.abspath(testname)
  116. raise IOError("File %r does not exist in any of the search paths: %r" %
  117. (filename, path_dirs) )
  118. class HomeDirError(Exception):
  119. pass
  120. def get_home_dir(require_writable=False) -> str:
  121. """Return the 'home' directory, as a unicode string.
  122. Uses os.path.expanduser('~'), and checks for writability.
  123. See stdlib docs for how this is determined.
  124. For Python <3.8, $HOME is first priority on *ALL* platforms.
  125. For Python >=3.8 on Windows, %HOME% is no longer considered.
  126. Parameters
  127. ----------
  128. require_writable : bool [default: False]
  129. if True:
  130. guarantees the return value is a writable directory, otherwise
  131. raises HomeDirError
  132. if False:
  133. The path is resolved, but it is not guaranteed to exist or be writable.
  134. """
  135. homedir = os.path.expanduser('~')
  136. # Next line will make things work even when /home/ is a symlink to
  137. # /usr/home as it is on FreeBSD, for example
  138. homedir = os.path.realpath(homedir)
  139. if not _writable_dir(homedir) and os.name == 'nt':
  140. # expanduser failed, use the registry to get the 'My Documents' folder.
  141. try:
  142. import winreg as wreg
  143. with wreg.OpenKey(
  144. wreg.HKEY_CURRENT_USER,
  145. r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
  146. ) as key:
  147. homedir = wreg.QueryValueEx(key,'Personal')[0]
  148. except:
  149. pass
  150. if (not require_writable) or _writable_dir(homedir):
  151. assert isinstance(homedir, str), "Homedir should be unicode not bytes"
  152. return homedir
  153. else:
  154. raise HomeDirError('%s is not a writable dir, '
  155. 'set $HOME environment variable to override' % homedir)
  156. def get_xdg_dir():
  157. """Return the XDG_CONFIG_HOME, if it is defined and exists, else None.
  158. This is only for non-OS X posix (Linux,Unix,etc.) systems.
  159. """
  160. env = os.environ
  161. if os.name == "posix":
  162. # Linux, Unix, AIX, etc.
  163. # use ~/.config if empty OR not set
  164. xdg = env.get("XDG_CONFIG_HOME", None) or os.path.join(get_home_dir(), '.config')
  165. if xdg and _writable_dir(xdg):
  166. assert isinstance(xdg, str)
  167. return xdg
  168. return None
  169. def get_xdg_cache_dir():
  170. """Return the XDG_CACHE_HOME, if it is defined and exists, else None.
  171. This is only for non-OS X posix (Linux,Unix,etc.) systems.
  172. """
  173. env = os.environ
  174. if os.name == "posix":
  175. # Linux, Unix, AIX, etc.
  176. # use ~/.cache if empty OR not set
  177. xdg = env.get("XDG_CACHE_HOME", None) or os.path.join(get_home_dir(), '.cache')
  178. if xdg and _writable_dir(xdg):
  179. assert isinstance(xdg, str)
  180. return xdg
  181. return None
  182. def expand_path(s):
  183. """Expand $VARS and ~names in a string, like a shell
  184. :Examples:
  185. In [2]: os.environ['FOO']='test'
  186. In [3]: expand_path('variable FOO is $FOO')
  187. Out[3]: 'variable FOO is test'
  188. """
  189. # This is a pretty subtle hack. When expand user is given a UNC path
  190. # on Windows (\\server\share$\%username%), os.path.expandvars, removes
  191. # the $ to get (\\server\share\%username%). I think it considered $
  192. # alone an empty var. But, we need the $ to remains there (it indicates
  193. # a hidden share).
  194. if os.name=='nt':
  195. s = s.replace('$\\', 'IPYTHON_TEMP')
  196. s = os.path.expandvars(os.path.expanduser(s))
  197. if os.name=='nt':
  198. s = s.replace('IPYTHON_TEMP', '$\\')
  199. return s
  200. def unescape_glob(string):
  201. """Unescape glob pattern in `string`."""
  202. def unescape(s):
  203. for pattern in '*[]!?':
  204. s = s.replace(r'\{0}'.format(pattern), pattern)
  205. return s
  206. return '\\'.join(map(unescape, string.split('\\\\')))
  207. def shellglob(args):
  208. """
  209. Do glob expansion for each element in `args` and return a flattened list.
  210. Unmatched glob pattern will remain as-is in the returned list.
  211. """
  212. expanded = []
  213. # Do not unescape backslash in Windows as it is interpreted as
  214. # path separator:
  215. unescape = unescape_glob if sys.platform != 'win32' else lambda x: x
  216. for a in args:
  217. expanded.extend(glob.glob(a) or [unescape(a)])
  218. return expanded
  219. def target_outdated(target,deps):
  220. """Determine whether a target is out of date.
  221. target_outdated(target,deps) -> 1/0
  222. deps: list of filenames which MUST exist.
  223. target: single filename which may or may not exist.
  224. If target doesn't exist or is older than any file listed in deps, return
  225. true, otherwise return false.
  226. .. deprecated:: 8.22
  227. """
  228. warnings.warn(
  229. "`target_outdated` is deprecated since IPython 8.22 and will be removed in future versions",
  230. DeprecationWarning,
  231. stacklevel=2,
  232. )
  233. try:
  234. target_time = os.path.getmtime(target)
  235. except os.error:
  236. return 1
  237. for dep in deps:
  238. dep_time = os.path.getmtime(dep)
  239. if dep_time > target_time:
  240. # print("For target",target,"Dep failed:",dep) # dbg
  241. # print("times (dep,tar):",dep_time,target_time) # dbg
  242. return 1
  243. return 0
  244. def target_update(target,deps,cmd):
  245. """Update a target with a given command given a list of dependencies.
  246. target_update(target,deps,cmd) -> runs cmd if target is outdated.
  247. This is just a wrapper around target_outdated() which calls the given
  248. command if target is outdated.
  249. .. deprecated:: 8.22
  250. """
  251. warnings.warn(
  252. "`target_update` is deprecated since IPython 8.22 and will be removed in future versions",
  253. DeprecationWarning,
  254. stacklevel=2,
  255. )
  256. if target_outdated(target, deps):
  257. system(cmd)
  258. ENOLINK = 1998
  259. def link(src, dst):
  260. """Hard links ``src`` to ``dst``, returning 0 or errno.
  261. Note that the special errno ``ENOLINK`` will be returned if ``os.link`` isn't
  262. supported by the operating system.
  263. """
  264. if not hasattr(os, "link"):
  265. return ENOLINK
  266. link_errno = 0
  267. try:
  268. os.link(src, dst)
  269. except OSError as e:
  270. link_errno = e.errno
  271. return link_errno
  272. def link_or_copy(src, dst):
  273. """Attempts to hardlink ``src`` to ``dst``, copying if the link fails.
  274. Attempts to maintain the semantics of ``shutil.copy``.
  275. Because ``os.link`` does not overwrite files, a unique temporary file
  276. will be used if the target already exists, then that file will be moved
  277. into place.
  278. """
  279. if os.path.isdir(dst):
  280. dst = os.path.join(dst, os.path.basename(src))
  281. link_errno = link(src, dst)
  282. if link_errno == errno.EEXIST:
  283. if os.stat(src).st_ino == os.stat(dst).st_ino:
  284. # dst is already a hard link to the correct file, so we don't need
  285. # to do anything else. If we try to link and rename the file
  286. # anyway, we get duplicate files - see http://bugs.python.org/issue21876
  287. return
  288. new_dst = dst + "-temp-%04X" %(random.randint(1, 16**4), )
  289. try:
  290. link_or_copy(src, new_dst)
  291. except:
  292. try:
  293. os.remove(new_dst)
  294. except OSError:
  295. pass
  296. raise
  297. os.rename(new_dst, dst)
  298. elif link_errno != 0:
  299. # Either link isn't supported, or the filesystem doesn't support
  300. # linking, or 'src' and 'dst' are on different filesystems.
  301. shutil.copy(src, dst)
  302. def ensure_dir_exists(path, mode=0o755):
  303. """ensure that a directory exists
  304. If it doesn't exist, try to create it and protect against a race condition
  305. if another process is doing the same.
  306. The default permissions are 755, which differ from os.makedirs default of 777.
  307. """
  308. if not os.path.exists(path):
  309. try:
  310. os.makedirs(path, mode=mode)
  311. except OSError as e:
  312. if e.errno != errno.EEXIST:
  313. raise
  314. elif not os.path.isdir(path):
  315. raise IOError("%r exists but is not a directory" % path)