path.py 14 KB

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