path.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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. from warnings import warn
  14. from hashlib import md5
  15. from IPython.utils.process import system
  16. from IPython.utils import py3compat
  17. from IPython.utils.decorators import undoc
  18. #-----------------------------------------------------------------------------
  19. # Code
  20. #-----------------------------------------------------------------------------
  21. fs_encoding = sys.getfilesystemencoding()
  22. def _writable_dir(path):
  23. """Whether `path` is a directory, to which the user has write access."""
  24. return os.path.isdir(path) and os.access(path, os.W_OK)
  25. if sys.platform == 'win32':
  26. def _get_long_path_name(path):
  27. """Get a long path name (expand ~) on Windows using ctypes.
  28. Examples
  29. --------
  30. >>> get_long_path_name('c:\\docume~1')
  31. u'c:\\\\Documents and Settings'
  32. """
  33. try:
  34. import ctypes
  35. except ImportError:
  36. raise ImportError('you need to have ctypes installed for this to work')
  37. _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW
  38. _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p,
  39. ctypes.c_uint ]
  40. buf = ctypes.create_unicode_buffer(260)
  41. rv = _GetLongPathName(path, buf, 260)
  42. if rv == 0 or rv > 260:
  43. return path
  44. else:
  45. return buf.value
  46. else:
  47. def _get_long_path_name(path):
  48. """Dummy no-op."""
  49. return path
  50. def get_long_path_name(path):
  51. """Expand a path into its long form.
  52. On Windows this expands any ~ in the paths. On other platforms, it is
  53. a null operation.
  54. """
  55. return _get_long_path_name(path)
  56. def unquote_filename(name, win32=(sys.platform=='win32')):
  57. """ On Windows, remove leading and trailing quotes from filenames.
  58. This function has been deprecated and should not be used any more:
  59. unquoting is now taken care of by :func:`IPython.utils.process.arg_split`.
  60. """
  61. warn("'unquote_filename' is deprecated since IPython 5.0 and should not "
  62. "be used anymore", DeprecationWarning, stacklevel=2)
  63. if win32:
  64. if name.startswith(("'", '"')) and name.endswith(("'", '"')):
  65. name = name[1:-1]
  66. return name
  67. def compress_user(path):
  68. """Reverse of :func:`os.path.expanduser`
  69. """
  70. path = py3compat.unicode_to_str(path, sys.getfilesystemencoding())
  71. home = os.path.expanduser('~')
  72. if path.startswith(home):
  73. path = "~" + path[len(home):]
  74. return path
  75. def get_py_filename(name, force_win32=None):
  76. """Return a valid python filename in the current directory.
  77. If the given name is not a file, it adds '.py' and searches again.
  78. Raises IOError with an informative message if the file isn't found.
  79. """
  80. name = os.path.expanduser(name)
  81. if force_win32 is not None:
  82. warn("The 'force_win32' argument to 'get_py_filename' is deprecated "
  83. "since IPython 5.0 and should not be used anymore",
  84. DeprecationWarning, stacklevel=2)
  85. if not os.path.isfile(name) and not name.endswith('.py'):
  86. name += '.py'
  87. if os.path.isfile(name):
  88. return name
  89. else:
  90. raise IOError('File `%r` not found.' % name)
  91. def filefind(filename, path_dirs=None):
  92. """Find a file by looking through a sequence of paths.
  93. This iterates through a sequence of paths looking for a file and returns
  94. the full, absolute path of the first occurence of the file. If no set of
  95. path dirs is given, the filename is tested as is, after running through
  96. :func:`expandvars` and :func:`expanduser`. Thus a simple call::
  97. filefind('myfile.txt')
  98. will find the file in the current working dir, but::
  99. filefind('~/myfile.txt')
  100. Will find the file in the users home directory. This function does not
  101. automatically try any paths, such as the cwd or the user's home directory.
  102. Parameters
  103. ----------
  104. filename : str
  105. The filename to look for.
  106. path_dirs : str, None or sequence of str
  107. The sequence of paths to look for the file in. If None, the filename
  108. need to be absolute or be in the cwd. If a string, the string is
  109. put into a sequence and the searched. If a sequence, walk through
  110. each element and join with ``filename``, calling :func:`expandvars`
  111. and :func:`expanduser` before testing for existence.
  112. Returns
  113. -------
  114. Raises :exc:`IOError` or returns absolute path to file.
  115. """
  116. # If paths are quoted, abspath gets confused, strip them...
  117. filename = filename.strip('"').strip("'")
  118. # If the input is an absolute path, just check it exists
  119. if os.path.isabs(filename) and os.path.isfile(filename):
  120. return filename
  121. if path_dirs is None:
  122. path_dirs = ("",)
  123. elif isinstance(path_dirs, py3compat.string_types):
  124. path_dirs = (path_dirs,)
  125. for path in path_dirs:
  126. if path == '.': path = py3compat.getcwd()
  127. testname = expand_path(os.path.join(path, filename))
  128. if os.path.isfile(testname):
  129. return os.path.abspath(testname)
  130. raise IOError("File %r does not exist in any of the search paths: %r" %
  131. (filename, path_dirs) )
  132. class HomeDirError(Exception):
  133. pass
  134. def get_home_dir(require_writable=False):
  135. """Return the 'home' directory, as a unicode string.
  136. Uses os.path.expanduser('~'), and checks for writability.
  137. See stdlib docs for how this is determined.
  138. $HOME is first priority on *ALL* platforms.
  139. Parameters
  140. ----------
  141. require_writable : bool [default: False]
  142. if True:
  143. guarantees the return value is a writable directory, otherwise
  144. raises HomeDirError
  145. if False:
  146. The path is resolved, but it is not guaranteed to exist or be writable.
  147. """
  148. homedir = os.path.expanduser('~')
  149. # Next line will make things work even when /home/ is a symlink to
  150. # /usr/home as it is on FreeBSD, for example
  151. homedir = os.path.realpath(homedir)
  152. if not _writable_dir(homedir) and os.name == 'nt':
  153. # expanduser failed, use the registry to get the 'My Documents' folder.
  154. try:
  155. try:
  156. import winreg as wreg # Py 3
  157. except ImportError:
  158. import _winreg as wreg # Py 2
  159. key = wreg.OpenKey(
  160. wreg.HKEY_CURRENT_USER,
  161. "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
  162. )
  163. homedir = wreg.QueryValueEx(key,'Personal')[0]
  164. key.Close()
  165. except:
  166. pass
  167. if (not require_writable) or _writable_dir(homedir):
  168. return py3compat.cast_unicode(homedir, fs_encoding)
  169. else:
  170. raise HomeDirError('%s is not a writable dir, '
  171. 'set $HOME environment variable to override' % homedir)
  172. def get_xdg_dir():
  173. """Return the XDG_CONFIG_HOME, if it is defined and exists, else None.
  174. This is only for non-OS X posix (Linux,Unix,etc.) systems.
  175. """
  176. env = os.environ
  177. if os.name == 'posix' and sys.platform != 'darwin':
  178. # Linux, Unix, AIX, etc.
  179. # use ~/.config if empty OR not set
  180. xdg = env.get("XDG_CONFIG_HOME", None) or os.path.join(get_home_dir(), '.config')
  181. if xdg and _writable_dir(xdg):
  182. return py3compat.cast_unicode(xdg, fs_encoding)
  183. return None
  184. def get_xdg_cache_dir():
  185. """Return the XDG_CACHE_HOME, if it is defined and exists, else None.
  186. This is only for non-OS X posix (Linux,Unix,etc.) systems.
  187. """
  188. env = os.environ
  189. if os.name == 'posix' and sys.platform != 'darwin':
  190. # Linux, Unix, AIX, etc.
  191. # use ~/.cache if empty OR not set
  192. xdg = env.get("XDG_CACHE_HOME", None) or os.path.join(get_home_dir(), '.cache')
  193. if xdg and _writable_dir(xdg):
  194. return py3compat.cast_unicode(xdg, fs_encoding)
  195. return None
  196. @undoc
  197. def get_ipython_dir():
  198. warn("get_ipython_dir has moved to the IPython.paths module since IPython 4.0.", stacklevel=2)
  199. from IPython.paths import get_ipython_dir
  200. return get_ipython_dir()
  201. @undoc
  202. def get_ipython_cache_dir():
  203. warn("get_ipython_cache_dir has moved to the IPython.paths module since IPython 4.0.", stacklevel=2)
  204. from IPython.paths import get_ipython_cache_dir
  205. return get_ipython_cache_dir()
  206. @undoc
  207. def get_ipython_package_dir():
  208. warn("get_ipython_package_dir has moved to the IPython.paths module since IPython 4.0.", stacklevel=2)
  209. from IPython.paths import get_ipython_package_dir
  210. return get_ipython_package_dir()
  211. @undoc
  212. def get_ipython_module_path(module_str):
  213. warn("get_ipython_module_path has moved to the IPython.paths module since IPython 4.0.", stacklevel=2)
  214. from IPython.paths import get_ipython_module_path
  215. return get_ipython_module_path(module_str)
  216. @undoc
  217. def locate_profile(profile='default'):
  218. warn("locate_profile has moved to the IPython.paths module since IPython 4.0.", stacklevel=2)
  219. from IPython.paths import locate_profile
  220. return locate_profile(profile=profile)
  221. def expand_path(s):
  222. """Expand $VARS and ~names in a string, like a shell
  223. :Examples:
  224. In [2]: os.environ['FOO']='test'
  225. In [3]: expand_path('variable FOO is $FOO')
  226. Out[3]: 'variable FOO is test'
  227. """
  228. # This is a pretty subtle hack. When expand user is given a UNC path
  229. # on Windows (\\server\share$\%username%), os.path.expandvars, removes
  230. # the $ to get (\\server\share\%username%). I think it considered $
  231. # alone an empty var. But, we need the $ to remains there (it indicates
  232. # a hidden share).
  233. if os.name=='nt':
  234. s = s.replace('$\\', 'IPYTHON_TEMP')
  235. s = os.path.expandvars(os.path.expanduser(s))
  236. if os.name=='nt':
  237. s = s.replace('IPYTHON_TEMP', '$\\')
  238. return s
  239. def unescape_glob(string):
  240. """Unescape glob pattern in `string`."""
  241. def unescape(s):
  242. for pattern in '*[]!?':
  243. s = s.replace(r'\{0}'.format(pattern), pattern)
  244. return s
  245. return '\\'.join(map(unescape, string.split('\\\\')))
  246. def shellglob(args):
  247. """
  248. Do glob expansion for each element in `args` and return a flattened list.
  249. Unmatched glob pattern will remain as-is in the returned list.
  250. """
  251. expanded = []
  252. # Do not unescape backslash in Windows as it is interpreted as
  253. # path separator:
  254. unescape = unescape_glob if sys.platform != 'win32' else lambda x: x
  255. for a in args:
  256. expanded.extend(glob.glob(a) or [unescape(a)])
  257. return expanded
  258. def target_outdated(target,deps):
  259. """Determine whether a target is out of date.
  260. target_outdated(target,deps) -> 1/0
  261. deps: list of filenames which MUST exist.
  262. target: single filename which may or may not exist.
  263. If target doesn't exist or is older than any file listed in deps, return
  264. true, otherwise return false.
  265. """
  266. try:
  267. target_time = os.path.getmtime(target)
  268. except os.error:
  269. return 1
  270. for dep in deps:
  271. dep_time = os.path.getmtime(dep)
  272. if dep_time > target_time:
  273. #print "For target",target,"Dep failed:",dep # dbg
  274. #print "times (dep,tar):",dep_time,target_time # dbg
  275. return 1
  276. return 0
  277. def target_update(target,deps,cmd):
  278. """Update a target with a given command given a list of dependencies.
  279. target_update(target,deps,cmd) -> runs cmd if target is outdated.
  280. This is just a wrapper around target_outdated() which calls the given
  281. command if target is outdated."""
  282. if target_outdated(target,deps):
  283. system(cmd)
  284. @undoc
  285. def filehash(path):
  286. """Make an MD5 hash of a file, ignoring any differences in line
  287. ending characters."""
  288. warn("filehash() is deprecated since IPython 4.0", DeprecationWarning, stacklevel=2)
  289. with open(path, "rU") as f:
  290. return md5(py3compat.str_to_bytes(f.read())).hexdigest()
  291. ENOLINK = 1998
  292. def link(src, dst):
  293. """Hard links ``src`` to ``dst``, returning 0 or errno.
  294. Note that the special errno ``ENOLINK`` will be returned if ``os.link`` isn't
  295. supported by the operating system.
  296. """
  297. if not hasattr(os, "link"):
  298. return ENOLINK
  299. link_errno = 0
  300. try:
  301. os.link(src, dst)
  302. except OSError as e:
  303. link_errno = e.errno
  304. return link_errno
  305. def link_or_copy(src, dst):
  306. """Attempts to hardlink ``src`` to ``dst``, copying if the link fails.
  307. Attempts to maintain the semantics of ``shutil.copy``.
  308. Because ``os.link`` does not overwrite files, a unique temporary file
  309. will be used if the target already exists, then that file will be moved
  310. into place.
  311. """
  312. if os.path.isdir(dst):
  313. dst = os.path.join(dst, os.path.basename(src))
  314. link_errno = link(src, dst)
  315. if link_errno == errno.EEXIST:
  316. if os.stat(src).st_ino == os.stat(dst).st_ino:
  317. # dst is already a hard link to the correct file, so we don't need
  318. # to do anything else. If we try to link and rename the file
  319. # anyway, we get duplicate files - see http://bugs.python.org/issue21876
  320. return
  321. new_dst = dst + "-temp-%04X" %(random.randint(1, 16**4), )
  322. try:
  323. link_or_copy(src, new_dst)
  324. except:
  325. try:
  326. os.remove(new_dst)
  327. except OSError:
  328. pass
  329. raise
  330. os.rename(new_dst, dst)
  331. elif link_errno != 0:
  332. # Either link isn't supported, or the filesystem doesn't support
  333. # linking, or 'src' and 'dst' are on different filesystems.
  334. shutil.copy(src, dst)
  335. def ensure_dir_exists(path, mode=0o755):
  336. """ensure that a directory exists
  337. If it doesn't exist, try to create it and protect against a race condition
  338. if another process is doing the same.
  339. The default permissions are 755, which differ from os.makedirs default of 777.
  340. """
  341. if not os.path.exists(path):
  342. try:
  343. os.makedirs(path, mode=mode)
  344. except OSError as e:
  345. if e.errno != errno.EEXIST:
  346. raise
  347. elif not os.path.isdir(path):
  348. raise IOError("%r exists but is not a directory" % path)