Debian Codegraph @

lib-python/3/ntpath.py

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