ntpath.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  1. # Module 'ntpath' -- common operations on WinNT/Win95 pathnames
  2. """Common pathname manipulations, WindowsNT/95 version.
  3. Instead of importing this module directly, import os and refer to this
  4. module as os.path.
  5. """
  6. # strings representing various path-related bits and pieces
  7. # These are primarily for export; internally, they are hardcoded.
  8. # Should be set before imports for resolving cyclic dependency.
  9. curdir = '.'
  10. pardir = '..'
  11. extsep = '.'
  12. sep = '\\'
  13. pathsep = ';'
  14. altsep = '/'
  15. defpath = '.;C:\\bin'
  16. devnull = 'nul'
  17. import os
  18. import sys
  19. import stat
  20. import genericpath
  21. from genericpath import *
  22. __all__ = ["normcase","isabs","join","splitdrive","split","splitext",
  23. "basename","dirname","commonprefix","getsize","getmtime",
  24. "getatime","getctime", "islink","exists","lexists","isdir","isfile",
  25. "ismount", "expanduser","expandvars","normpath","abspath",
  26. "curdir","pardir","sep","pathsep","defpath","altsep",
  27. "extsep","devnull","realpath","supports_unicode_filenames","relpath",
  28. "samefile", "sameopenfile", "samestat", "commonpath"]
  29. def _get_bothseps(path):
  30. if isinstance(path, bytes):
  31. return b'\\/'
  32. else:
  33. return '\\/'
  34. # Normalize the case of a pathname and map slashes to backslashes.
  35. # Other normalizations (such as optimizing '../' away) are not done
  36. # (this is done by normpath).
  37. try:
  38. from _winapi import (
  39. LCMapStringEx as _LCMapStringEx,
  40. LOCALE_NAME_INVARIANT as _LOCALE_NAME_INVARIANT,
  41. LCMAP_LOWERCASE as _LCMAP_LOWERCASE)
  42. def normcase(s):
  43. """Normalize case of pathname.
  44. Makes all characters lowercase and all slashes into backslashes.
  45. """
  46. s = os.fspath(s)
  47. if not s:
  48. return s
  49. if isinstance(s, bytes):
  50. encoding = sys.getfilesystemencoding()
  51. s = s.decode(encoding, 'surrogateescape').replace('/', '\\')
  52. s = _LCMapStringEx(_LOCALE_NAME_INVARIANT,
  53. _LCMAP_LOWERCASE, s)
  54. return s.encode(encoding, 'surrogateescape')
  55. else:
  56. return _LCMapStringEx(_LOCALE_NAME_INVARIANT,
  57. _LCMAP_LOWERCASE,
  58. s.replace('/', '\\'))
  59. except ImportError:
  60. def normcase(s):
  61. """Normalize case of pathname.
  62. Makes all characters lowercase and all slashes into backslashes.
  63. """
  64. s = os.fspath(s)
  65. if isinstance(s, bytes):
  66. return os.fsencode(os.fsdecode(s).replace('/', '\\').lower())
  67. return s.replace('/', '\\').lower()
  68. # Return whether a path is absolute.
  69. # Trivial in Posix, harder on Windows.
  70. # For Windows it is absolute if it starts with a slash or backslash (current
  71. # volume), or if a pathname after the volume-letter-and-colon or UNC-resource
  72. # starts with a slash or backslash.
  73. def isabs(s):
  74. """Test whether a path is absolute"""
  75. s = os.fspath(s)
  76. if isinstance(s, bytes):
  77. sep = b'\\'
  78. altsep = b'/'
  79. colon_sep = b':\\'
  80. else:
  81. sep = '\\'
  82. altsep = '/'
  83. colon_sep = ':\\'
  84. s = s[:3].replace(altsep, sep)
  85. # Absolute: UNC, device, and paths with a drive and root.
  86. # LEGACY BUG: isabs("/x") should be false since the path has no drive.
  87. if s.startswith(sep) or s.startswith(colon_sep, 1):
  88. return True
  89. return False
  90. # Join two (or more) paths.
  91. def join(path, *paths):
  92. path = os.fspath(path)
  93. if isinstance(path, bytes):
  94. sep = b'\\'
  95. seps = b'\\/'
  96. colon = b':'
  97. else:
  98. sep = '\\'
  99. seps = '\\/'
  100. colon = ':'
  101. try:
  102. if not paths:
  103. path[:0] + sep #23780: Ensure compatible data type even if p is null.
  104. result_drive, result_path = splitdrive(path)
  105. for p in map(os.fspath, paths):
  106. p_drive, p_path = splitdrive(p)
  107. if p_path and p_path[0] in seps:
  108. # Second path is absolute
  109. if p_drive or not result_drive:
  110. result_drive = p_drive
  111. result_path = p_path
  112. continue
  113. elif p_drive and p_drive != result_drive:
  114. if p_drive.lower() != result_drive.lower():
  115. # Different drives => ignore the first path entirely
  116. result_drive = p_drive
  117. result_path = p_path
  118. continue
  119. # Same drive in different case
  120. result_drive = p_drive
  121. # Second path is relative to the first
  122. if result_path and result_path[-1] not in seps:
  123. result_path = result_path + sep
  124. result_path = result_path + p_path
  125. ## add separator between UNC and non-absolute path
  126. if (result_path and result_path[0] not in seps and
  127. result_drive and result_drive[-1:] != colon):
  128. return result_drive + sep + result_path
  129. return result_drive + result_path
  130. except (TypeError, AttributeError, BytesWarning):
  131. genericpath._check_arg_types('join', path, *paths)
  132. raise
  133. # Split a path in a drive specification (a drive letter followed by a
  134. # colon) and the path specification.
  135. # It is always true that drivespec + pathspec == p
  136. def splitdrive(p):
  137. """Split a pathname into drive/UNC sharepoint and relative path specifiers.
  138. Returns a 2-tuple (drive_or_unc, path); either part may be empty.
  139. If you assign
  140. result = splitdrive(p)
  141. It is always true that:
  142. result[0] + result[1] == p
  143. If the path contained a drive letter, drive_or_unc will contain everything
  144. up to and including the colon. e.g. splitdrive("c:/dir") returns ("c:", "/dir")
  145. If the path contained a UNC path, the drive_or_unc will contain the host name
  146. and share up to but not including the fourth directory separator character.
  147. e.g. splitdrive("//host/computer/dir") returns ("//host/computer", "/dir")
  148. Paths cannot contain both a drive letter and a UNC path.
  149. """
  150. p = os.fspath(p)
  151. if len(p) >= 2:
  152. if isinstance(p, bytes):
  153. sep = b'\\'
  154. altsep = b'/'
  155. colon = b':'
  156. unc_prefix = b'\\\\?\\UNC\\'
  157. else:
  158. sep = '\\'
  159. altsep = '/'
  160. colon = ':'
  161. unc_prefix = '\\\\?\\UNC\\'
  162. normp = p.replace(altsep, sep)
  163. if normp[0:2] == sep * 2:
  164. # UNC drives, e.g. \\server\share or \\?\UNC\server\share
  165. # Device drives, e.g. \\.\device or \\?\device
  166. start = 8 if normp[:8].upper() == unc_prefix else 2
  167. index = normp.find(sep, start)
  168. if index == -1:
  169. return p, p[:0]
  170. index2 = normp.find(sep, index + 1)
  171. if index2 == -1:
  172. return p, p[:0]
  173. return p[:index2], p[index2:]
  174. if normp[1:2] == colon:
  175. # Drive-letter drives, e.g. X:
  176. return p[:2], p[2:]
  177. return p[:0], p
  178. # Split a path in head (everything up to the last '/') and tail (the
  179. # rest). After the trailing '/' is stripped, the invariant
  180. # join(head, tail) == p holds.
  181. # The resulting head won't end in '/' unless it is the root.
  182. def split(p):
  183. """Split a pathname.
  184. Return tuple (head, tail) where tail is everything after the final slash.
  185. Either part may be empty."""
  186. p = os.fspath(p)
  187. seps = _get_bothseps(p)
  188. d, p = splitdrive(p)
  189. # set i to index beyond p's last slash
  190. i = len(p)
  191. while i and p[i-1] not in seps:
  192. i -= 1
  193. head, tail = p[:i], p[i:] # now tail has no slashes
  194. # remove trailing slashes from head, unless it's all slashes
  195. head = head.rstrip(seps) or head
  196. return d + head, tail
  197. # Split a path in root and extension.
  198. # The extension is everything starting at the last dot in the last
  199. # pathname component; the root is everything before that.
  200. # It is always true that root + ext == p.
  201. def splitext(p):
  202. p = os.fspath(p)
  203. if isinstance(p, bytes):
  204. return genericpath._splitext(p, b'\\', b'/', b'.')
  205. else:
  206. return genericpath._splitext(p, '\\', '/', '.')
  207. splitext.__doc__ = genericpath._splitext.__doc__
  208. # Return the tail (basename) part of a path.
  209. def basename(p):
  210. """Returns the final component of a pathname"""
  211. return split(p)[1]
  212. # Return the head (dirname) part of a path.
  213. def dirname(p):
  214. """Returns the directory component of a pathname"""
  215. return split(p)[0]
  216. # Is a path a symbolic link?
  217. # This will always return false on systems where os.lstat doesn't exist.
  218. def islink(path):
  219. """Test whether a path is a symbolic link.
  220. This will always return false for Windows prior to 6.0.
  221. """
  222. try:
  223. st = os.lstat(path)
  224. except (OSError, ValueError, AttributeError):
  225. return False
  226. return stat.S_ISLNK(st.st_mode)
  227. # Being true for dangling symbolic links is also useful.
  228. def lexists(path):
  229. """Test whether a path exists. Returns True for broken symbolic links"""
  230. try:
  231. st = os.lstat(path)
  232. except (OSError, ValueError):
  233. return False
  234. return True
  235. # Is a path a mount point?
  236. # Any drive letter root (eg c:\)
  237. # Any share UNC (eg \\server\share)
  238. # Any volume mounted on a filesystem folder
  239. #
  240. # No one method detects all three situations. Historically we've lexically
  241. # detected drive letter roots and share UNCs. The canonical approach to
  242. # detecting mounted volumes (querying the reparse tag) fails for the most
  243. # common case: drive letter roots. The alternative which uses GetVolumePathName
  244. # fails if the drive letter is the result of a SUBST.
  245. try:
  246. from nt import _getvolumepathname
  247. except ImportError:
  248. _getvolumepathname = None
  249. def ismount(path):
  250. """Test whether a path is a mount point (a drive root, the root of a
  251. share, or a mounted volume)"""
  252. path = os.fspath(path)
  253. seps = _get_bothseps(path)
  254. path = abspath(path)
  255. root, rest = splitdrive(path)
  256. if root and root[0] in seps:
  257. return (not rest) or (rest in seps)
  258. if rest and rest in seps:
  259. return True
  260. if _getvolumepathname:
  261. x = path.rstrip(seps)
  262. y =_getvolumepathname(path).rstrip(seps)
  263. return x.casefold() == y.casefold()
  264. else:
  265. return False
  266. # Expand paths beginning with '~' or '~user'.
  267. # '~' means $HOME; '~user' means that user's home directory.
  268. # If the path doesn't begin with '~', or if the user or $HOME is unknown,
  269. # the path is returned unchanged (leaving error reporting to whatever
  270. # function is called with the expanded path as argument).
  271. # See also module 'glob' for expansion of *, ? and [...] in pathnames.
  272. # (A function should also be defined to do full *sh-style environment
  273. # variable expansion.)
  274. def expanduser(path):
  275. """Expand ~ and ~user constructs.
  276. If user or $HOME is unknown, do nothing."""
  277. path = os.fspath(path)
  278. if isinstance(path, bytes):
  279. tilde = b'~'
  280. else:
  281. tilde = '~'
  282. if not path.startswith(tilde):
  283. return path
  284. i, n = 1, len(path)
  285. while i < n and path[i] not in _get_bothseps(path):
  286. i += 1
  287. if 'USERPROFILE' in os.environ:
  288. userhome = os.environ['USERPROFILE']
  289. elif not 'HOMEPATH' in os.environ:
  290. return path
  291. else:
  292. try:
  293. drive = os.environ['HOMEDRIVE']
  294. except KeyError:
  295. drive = ''
  296. userhome = join(drive, os.environ['HOMEPATH'])
  297. if i != 1: #~user
  298. target_user = path[1:i]
  299. if isinstance(target_user, bytes):
  300. target_user = os.fsdecode(target_user)
  301. current_user = os.environ.get('USERNAME')
  302. if target_user != current_user:
  303. # Try to guess user home directory. By default all user
  304. # profile directories are located in the same place and are
  305. # named by corresponding usernames. If userhome isn't a
  306. # normal profile directory, this guess is likely wrong,
  307. # so we bail out.
  308. if current_user != basename(userhome):
  309. return path
  310. userhome = join(dirname(userhome), target_user)
  311. if isinstance(path, bytes):
  312. userhome = os.fsencode(userhome)
  313. return userhome + path[i:]
  314. # Expand paths containing shell variable substitutions.
  315. # The following rules apply:
  316. # - no expansion within single quotes
  317. # - '$$' is translated into '$'
  318. # - '%%' is translated into '%' if '%%' are not seen in %var1%%var2%
  319. # - ${varname} is accepted.
  320. # - $varname is accepted.
  321. # - %varname% is accepted.
  322. # - varnames can be made out of letters, digits and the characters '_-'
  323. # (though is not verified in the ${varname} and %varname% cases)
  324. # XXX With COMMAND.COM you can use any characters in a variable name,
  325. # XXX except '^|<>='.
  326. def expandvars(path):
  327. """Expand shell variables of the forms $var, ${var} and %var%.
  328. Unknown variables are left unchanged."""
  329. path = os.fspath(path)
  330. if isinstance(path, bytes):
  331. if b'$' not in path and b'%' not in path:
  332. return path
  333. import string
  334. varchars = bytes(string.ascii_letters + string.digits + '_-', 'ascii')
  335. quote = b'\''
  336. percent = b'%'
  337. brace = b'{'
  338. rbrace = b'}'
  339. dollar = b'$'
  340. environ = getattr(os, 'environb', None)
  341. else:
  342. if '$' not in path and '%' not in path:
  343. return path
  344. import string
  345. varchars = string.ascii_letters + string.digits + '_-'
  346. quote = '\''
  347. percent = '%'
  348. brace = '{'
  349. rbrace = '}'
  350. dollar = '$'
  351. environ = os.environ
  352. res = path[:0]
  353. index = 0
  354. pathlen = len(path)
  355. while index < pathlen:
  356. c = path[index:index+1]
  357. if c == quote: # no expansion within single quotes
  358. path = path[index + 1:]
  359. pathlen = len(path)
  360. try:
  361. index = path.index(c)
  362. res += c + path[:index + 1]
  363. except ValueError:
  364. res += c + path
  365. index = pathlen - 1
  366. elif c == percent: # variable or '%'
  367. if path[index + 1:index + 2] == percent:
  368. res += c
  369. index += 1
  370. else:
  371. path = path[index+1:]
  372. pathlen = len(path)
  373. try:
  374. index = path.index(percent)
  375. except ValueError:
  376. res += percent + path
  377. index = pathlen - 1
  378. else:
  379. var = path[:index]
  380. try:
  381. if environ is None:
  382. value = os.fsencode(os.environ[os.fsdecode(var)])
  383. else:
  384. value = environ[var]
  385. except KeyError:
  386. value = percent + var + percent
  387. res += value
  388. elif c == dollar: # variable or '$$'
  389. if path[index + 1:index + 2] == dollar:
  390. res += c
  391. index += 1
  392. elif path[index + 1:index + 2] == brace:
  393. path = path[index+2:]
  394. pathlen = len(path)
  395. try:
  396. index = path.index(rbrace)
  397. except ValueError:
  398. res += dollar + brace + path
  399. index = pathlen - 1
  400. else:
  401. var = path[:index]
  402. try:
  403. if environ is None:
  404. value = os.fsencode(os.environ[os.fsdecode(var)])
  405. else:
  406. value = environ[var]
  407. except KeyError:
  408. value = dollar + brace + var + rbrace
  409. res += value
  410. else:
  411. var = path[:0]
  412. index += 1
  413. c = path[index:index + 1]
  414. while c and c in varchars:
  415. var += c
  416. index += 1
  417. c = path[index:index + 1]
  418. try:
  419. if environ is None:
  420. value = os.fsencode(os.environ[os.fsdecode(var)])
  421. else:
  422. value = environ[var]
  423. except KeyError:
  424. value = dollar + var
  425. res += value
  426. if c:
  427. index -= 1
  428. else:
  429. res += c
  430. index += 1
  431. return res
  432. # Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A\B.
  433. # Previously, this function also truncated pathnames to 8+3 format,
  434. # but as this module is called "ntpath", that's obviously wrong!
  435. try:
  436. from nt import _path_normpath
  437. except ImportError:
  438. def normpath(path):
  439. """Normalize path, eliminating double slashes, etc."""
  440. path = os.fspath(path)
  441. if isinstance(path, bytes):
  442. sep = b'\\'
  443. altsep = b'/'
  444. curdir = b'.'
  445. pardir = b'..'
  446. else:
  447. sep = '\\'
  448. altsep = '/'
  449. curdir = '.'
  450. pardir = '..'
  451. path = path.replace(altsep, sep)
  452. prefix, path = splitdrive(path)
  453. # collapse initial backslashes
  454. if path.startswith(sep):
  455. prefix += sep
  456. path = path.lstrip(sep)
  457. comps = path.split(sep)
  458. i = 0
  459. while i < len(comps):
  460. if not comps[i] or comps[i] == curdir:
  461. del comps[i]
  462. elif comps[i] == pardir:
  463. if i > 0 and comps[i-1] != pardir:
  464. del comps[i-1:i+1]
  465. i -= 1
  466. elif i == 0 and prefix.endswith(sep):
  467. del comps[i]
  468. else:
  469. i += 1
  470. else:
  471. i += 1
  472. # If the path is now empty, substitute '.'
  473. if not prefix and not comps:
  474. comps.append(curdir)
  475. return prefix + sep.join(comps)
  476. else:
  477. def normpath(path):
  478. """Normalize path, eliminating double slashes, etc."""
  479. path = os.fspath(path)
  480. if isinstance(path, bytes):
  481. return os.fsencode(_path_normpath(os.fsdecode(path))) or b"."
  482. return _path_normpath(path) or "."
  483. def _abspath_fallback(path):
  484. """Return the absolute version of a path as a fallback function in case
  485. `nt._getfullpathname` is not available or raises OSError. See bpo-31047 for
  486. more.
  487. """
  488. path = os.fspath(path)
  489. if not isabs(path):
  490. if isinstance(path, bytes):
  491. cwd = os.getcwdb()
  492. else:
  493. cwd = os.getcwd()
  494. path = join(cwd, path)
  495. return normpath(path)
  496. # Return an absolute path.
  497. try:
  498. from nt import _getfullpathname
  499. except ImportError: # not running on Windows - mock up something sensible
  500. abspath = _abspath_fallback
  501. else: # use native Windows method on Windows
  502. def abspath(path):
  503. """Return the absolute version of a path."""
  504. try:
  505. return _getfullpathname(normpath(path))
  506. except (OSError, ValueError):
  507. return _abspath_fallback(path)
  508. try:
  509. from nt import _getfinalpathname, readlink as _nt_readlink
  510. except ImportError:
  511. # realpath is a no-op on systems without _getfinalpathname support.
  512. realpath = abspath
  513. else:
  514. def _readlink_deep(path):
  515. # These error codes indicate that we should stop reading links and
  516. # return the path we currently have.
  517. # 1: ERROR_INVALID_FUNCTION
  518. # 2: ERROR_FILE_NOT_FOUND
  519. # 3: ERROR_DIRECTORY_NOT_FOUND
  520. # 5: ERROR_ACCESS_DENIED
  521. # 21: ERROR_NOT_READY (implies drive with no media)
  522. # 32: ERROR_SHARING_VIOLATION (probably an NTFS paging file)
  523. # 50: ERROR_NOT_SUPPORTED (implies no support for reparse points)
  524. # 67: ERROR_BAD_NET_NAME (implies remote server unavailable)
  525. # 87: ERROR_INVALID_PARAMETER
  526. # 4390: ERROR_NOT_A_REPARSE_POINT
  527. # 4392: ERROR_INVALID_REPARSE_DATA
  528. # 4393: ERROR_REPARSE_TAG_INVALID
  529. allowed_winerror = 1, 2, 3, 5, 21, 32, 50, 67, 87, 4390, 4392, 4393
  530. seen = set()
  531. while normcase(path) not in seen:
  532. seen.add(normcase(path))
  533. try:
  534. old_path = path
  535. path = _nt_readlink(path)
  536. # Links may be relative, so resolve them against their
  537. # own location
  538. if not isabs(path):
  539. # If it's something other than a symlink, we don't know
  540. # what it's actually going to be resolved against, so
  541. # just return the old path.
  542. if not islink(old_path):
  543. path = old_path
  544. break
  545. path = normpath(join(dirname(old_path), path))
  546. except OSError as ex:
  547. if ex.winerror in allowed_winerror:
  548. break
  549. raise
  550. except ValueError:
  551. # Stop on reparse points that are not symlinks
  552. break
  553. return path
  554. def _getfinalpathname_nonstrict(path):
  555. # These error codes indicate that we should stop resolving the path
  556. # and return the value we currently have.
  557. # 1: ERROR_INVALID_FUNCTION
  558. # 2: ERROR_FILE_NOT_FOUND
  559. # 3: ERROR_DIRECTORY_NOT_FOUND
  560. # 5: ERROR_ACCESS_DENIED
  561. # 21: ERROR_NOT_READY (implies drive with no media)
  562. # 32: ERROR_SHARING_VIOLATION (probably an NTFS paging file)
  563. # 50: ERROR_NOT_SUPPORTED
  564. # 53: ERROR_BAD_NETPATH
  565. # 65: ERROR_NETWORK_ACCESS_DENIED
  566. # 67: ERROR_BAD_NET_NAME (implies remote server unavailable)
  567. # 87: ERROR_INVALID_PARAMETER
  568. # 123: ERROR_INVALID_NAME
  569. # 161: ERROR_BAD_PATHNAME
  570. # 1920: ERROR_CANT_ACCESS_FILE
  571. # 1921: ERROR_CANT_RESOLVE_FILENAME (implies unfollowable symlink)
  572. allowed_winerror = 1, 2, 3, 5, 21, 32, 50, 53, 65, 67, 87, 123, 161, 1920, 1921
  573. # Non-strict algorithm is to find as much of the target directory
  574. # as we can and join the rest.
  575. tail = ''
  576. while path:
  577. try:
  578. path = _getfinalpathname(path)
  579. return join(path, tail) if tail else path
  580. except OSError as ex:
  581. if ex.winerror not in allowed_winerror:
  582. raise
  583. try:
  584. # The OS could not resolve this path fully, so we attempt
  585. # to follow the link ourselves. If we succeed, join the tail
  586. # and return.
  587. new_path = _readlink_deep(path)
  588. if new_path != path:
  589. return join(new_path, tail) if tail else new_path
  590. except OSError:
  591. # If we fail to readlink(), let's keep traversing
  592. pass
  593. path, name = split(path)
  594. # TODO (bpo-38186): Request the real file name from the directory
  595. # entry using FindFirstFileW. For now, we will return the path
  596. # as best we have it
  597. if path and not name:
  598. return path + tail
  599. tail = join(name, tail) if tail else name
  600. return tail
  601. def realpath(path, *, strict=False):
  602. path = normpath(path)
  603. if isinstance(path, bytes):
  604. prefix = b'\\\\?\\'
  605. unc_prefix = b'\\\\?\\UNC\\'
  606. new_unc_prefix = b'\\\\'
  607. cwd = os.getcwdb()
  608. # bpo-38081: Special case for realpath(b'nul')
  609. if normcase(path) == normcase(os.fsencode(devnull)):
  610. return b'\\\\.\\NUL'
  611. else:
  612. prefix = '\\\\?\\'
  613. unc_prefix = '\\\\?\\UNC\\'
  614. new_unc_prefix = '\\\\'
  615. cwd = os.getcwd()
  616. # bpo-38081: Special case for realpath('nul')
  617. if normcase(path) == normcase(devnull):
  618. return '\\\\.\\NUL'
  619. had_prefix = path.startswith(prefix)
  620. if not had_prefix and not isabs(path):
  621. path = join(cwd, path)
  622. try:
  623. path = _getfinalpathname(path)
  624. initial_winerror = 0
  625. except OSError as ex:
  626. if strict:
  627. raise
  628. initial_winerror = ex.winerror
  629. path = _getfinalpathname_nonstrict(path)
  630. # The path returned by _getfinalpathname will always start with \\?\ -
  631. # strip off that prefix unless it was already provided on the original
  632. # path.
  633. if not had_prefix and path.startswith(prefix):
  634. # For UNC paths, the prefix will actually be \\?\UNC\
  635. # Handle that case as well.
  636. if path.startswith(unc_prefix):
  637. spath = new_unc_prefix + path[len(unc_prefix):]
  638. else:
  639. spath = path[len(prefix):]
  640. # Ensure that the non-prefixed path resolves to the same path
  641. try:
  642. if _getfinalpathname(spath) == path:
  643. path = spath
  644. except OSError as ex:
  645. # If the path does not exist and originally did not exist, then
  646. # strip the prefix anyway.
  647. if ex.winerror == initial_winerror:
  648. path = spath
  649. return path
  650. # Win9x family and earlier have no Unicode filename support.
  651. supports_unicode_filenames = (hasattr(sys, "getwindowsversion") and
  652. sys.getwindowsversion()[3] >= 2)
  653. def relpath(path, start=None):
  654. """Return a relative version of a path"""
  655. path = os.fspath(path)
  656. if isinstance(path, bytes):
  657. sep = b'\\'
  658. curdir = b'.'
  659. pardir = b'..'
  660. else:
  661. sep = '\\'
  662. curdir = '.'
  663. pardir = '..'
  664. if start is None:
  665. start = curdir
  666. if not path:
  667. raise ValueError("no path specified")
  668. start = os.fspath(start)
  669. try:
  670. start_abs = abspath(normpath(start))
  671. path_abs = abspath(normpath(path))
  672. start_drive, start_rest = splitdrive(start_abs)
  673. path_drive, path_rest = splitdrive(path_abs)
  674. if normcase(start_drive) != normcase(path_drive):
  675. raise ValueError("path is on mount %r, start on mount %r" % (
  676. path_drive, start_drive))
  677. start_list = [x for x in start_rest.split(sep) if x]
  678. path_list = [x for x in path_rest.split(sep) if x]
  679. # Work out how much of the filepath is shared by start and path.
  680. i = 0
  681. for e1, e2 in zip(start_list, path_list):
  682. if normcase(e1) != normcase(e2):
  683. break
  684. i += 1
  685. rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
  686. if not rel_list:
  687. return curdir
  688. return join(*rel_list)
  689. except (TypeError, ValueError, AttributeError, BytesWarning, DeprecationWarning):
  690. genericpath._check_arg_types('relpath', path, start)
  691. raise
  692. # Return the longest common sub-path of the sequence of paths given as input.
  693. # The function is case-insensitive and 'separator-insensitive', i.e. if the
  694. # only difference between two paths is the use of '\' versus '/' as separator,
  695. # they are deemed to be equal.
  696. #
  697. # However, the returned path will have the standard '\' separator (even if the
  698. # given paths had the alternative '/' separator) and will have the case of the
  699. # first path given in the sequence. Additionally, any trailing separator is
  700. # stripped from the returned path.
  701. def commonpath(paths):
  702. """Given a sequence of path names, returns the longest common sub-path."""
  703. if not paths:
  704. raise ValueError('commonpath() arg is an empty sequence')
  705. paths = tuple(map(os.fspath, paths))
  706. if isinstance(paths[0], bytes):
  707. sep = b'\\'
  708. altsep = b'/'
  709. curdir = b'.'
  710. else:
  711. sep = '\\'
  712. altsep = '/'
  713. curdir = '.'
  714. try:
  715. drivesplits = [splitdrive(p.replace(altsep, sep).lower()) for p in paths]
  716. split_paths = [p.split(sep) for d, p in drivesplits]
  717. try:
  718. isabs, = set(p[:1] == sep for d, p in drivesplits)
  719. except ValueError:
  720. raise ValueError("Can't mix absolute and relative paths") from None
  721. # Check that all drive letters or UNC paths match. The check is made only
  722. # now otherwise type errors for mixing strings and bytes would not be
  723. # caught.
  724. if len(set(d for d, p in drivesplits)) != 1:
  725. raise ValueError("Paths don't have the same drive")
  726. drive, path = splitdrive(paths[0].replace(altsep, sep))
  727. common = path.split(sep)
  728. common = [c for c in common if c and c != curdir]
  729. split_paths = [[c for c in s if c and c != curdir] for s in split_paths]
  730. s1 = min(split_paths)
  731. s2 = max(split_paths)
  732. for i, c in enumerate(s1):
  733. if c != s2[i]:
  734. common = common[:i]
  735. break
  736. else:
  737. common = common[:len(s1)]
  738. prefix = drive + sep if isabs else drive
  739. return prefix + sep.join(common)
  740. except (TypeError, AttributeError):
  741. genericpath._check_arg_types('commonpath', *paths)
  742. raise
  743. try:
  744. # The genericpath.isdir implementation uses os.stat and checks the mode
  745. # attribute to tell whether or not the path is a directory.
  746. # This is overkill on Windows - just pass the path to GetFileAttributes
  747. # and check the attribute from there.
  748. from nt import _isdir as isdir
  749. except ImportError:
  750. # Use genericpath.isdir as imported above.
  751. pass