ntpath.py 27 KB

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