blob: 8f5dc55bec5815dcc8f2b9f66113e687a7791d58 [file] [log] [blame]
Guido van Rossum15e22e11997-12-05 19:03:01 +00001# Module 'ntpath' -- common operations on WinNT/Win95 pathnames
Tim Peters2344fae2001-01-15 00:50:52 +00002"""Common pathname manipulations, WindowsNT/95 version.
Guido van Rossum534972b1999-02-03 17:20:50 +00003
4Instead of importing this module directly, import os and refer to this
5module as os.path.
Guido van Rossum15e22e11997-12-05 19:03:01 +00006"""
Guido van Rossum555915a1994-02-24 11:32:59 +00007
8import os
Mark Hammond8696ebc2002-10-08 02:44:31 +00009import sys
Christian Heimes05e8be12008-02-23 18:30:17 +000010import stat
Guido van Rossumd8faa362007-04-27 19:54:29 +000011import genericpath
Thomas Wouters89f507f2006-12-13 04:49:30 +000012from genericpath import *
Skip Montanaro4d5d5bf2000-07-13 01:01:03 +000013
Skip Montanaro269b83b2001-02-06 01:07:02 +000014__all__ = ["normcase","isabs","join","splitdrive","split","splitext",
15 "basename","dirname","commonprefix","getsize","getmtime",
Georg Brandlf0de6a12005-08-22 18:02:59 +000016 "getatime","getctime", "islink","exists","lexists","isdir","isfile",
Benjamin Petersond71ca412008-05-08 23:44:58 +000017 "ismount", "expanduser","expandvars","normpath","abspath",
Georg Brandlf0de6a12005-08-22 18:02:59 +000018 "splitunc","curdir","pardir","sep","pathsep","defpath","altsep",
Brian Curtind40e6f72010-07-08 21:39:08 +000019 "extsep","devnull","realpath","supports_unicode_filenames","relpath",
Brian Curtinae57cec2012-12-26 08:22:00 -060020 "samefile", "sameopenfile", "samestat",]
Guido van Rossum555915a1994-02-24 11:32:59 +000021
Skip Montanaro117910d2003-02-14 19:35:31 +000022# strings representing various path-related bits and pieces
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +000023# These are primarily for export; internally, they are hardcoded.
Skip Montanaro117910d2003-02-14 19:35:31 +000024curdir = '.'
25pardir = '..'
26extsep = '.'
27sep = '\\'
28pathsep = ';'
Skip Montanaro9ddac3e2003-03-28 22:23:24 +000029altsep = '/'
Andrew MacIntyre437966c2003-02-17 09:17:50 +000030defpath = '.;C:\\bin'
Skip Montanaro117910d2003-02-14 19:35:31 +000031if 'ce' in sys.builtin_module_names:
32 defpath = '\\Windows'
Martin v. Löwisbdec50f2004-06-08 08:29:33 +000033devnull = 'nul'
Skip Montanaro117910d2003-02-14 19:35:31 +000034
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +000035def _get_bothseps(path):
36 if isinstance(path, bytes):
37 return b'\\/'
38 else:
39 return '\\/'
40
Guido van Rossume2ad88c1997-08-12 14:46:58 +000041# Normalize the case of a pathname and map slashes to backslashes.
42# Other normalizations (such as optimizing '../' away) are not done
Guido van Rossum555915a1994-02-24 11:32:59 +000043# (this is done by normpath).
Guido van Rossume2ad88c1997-08-12 14:46:58 +000044
Guido van Rossum555915a1994-02-24 11:32:59 +000045def normcase(s):
Guido van Rossum16a0bc21998-02-18 13:48:31 +000046 """Normalize case of pathname.
47
Guido van Rossum534972b1999-02-03 17:20:50 +000048 Makes all characters lowercase and all slashes into backslashes."""
Serhiy Storchaka8518b792014-07-23 20:43:13 +030049 try:
50 if isinstance(s, bytes):
51 return s.replace(b'/', b'\\').lower()
52 else:
53 return s.replace('/', '\\').lower()
54 except (TypeError, AttributeError):
55 if not isinstance(s, (bytes, str)):
56 raise TypeError("normcase() argument must be str or bytes, "
57 "not %r" % s.__class__.__name__) from None
58 raise
Guido van Rossum555915a1994-02-24 11:32:59 +000059
Guido van Rossum77e1db31997-06-02 23:11:57 +000060
Fred Drakeef0b5dd2000-02-17 17:30:40 +000061# Return whether a path is absolute.
Mark Hammond5a607a32009-05-06 08:04:54 +000062# Trivial in Posix, harder on Windows.
63# For Windows it is absolute if it starts with a slash or backslash (current
64# volume), or if a pathname after the volume-letter-and-colon or UNC-resource
Guido van Rossum534972b1999-02-03 17:20:50 +000065# starts with a slash or backslash.
Guido van Rossum555915a1994-02-24 11:32:59 +000066
67def isabs(s):
Guido van Rossum15e22e11997-12-05 19:03:01 +000068 """Test whether a path is absolute"""
69 s = splitdrive(s)[1]
Serhiy Storchaka8518b792014-07-23 20:43:13 +030070 return len(s) > 0 and s[0] in _get_bothseps(s)
Guido van Rossum555915a1994-02-24 11:32:59 +000071
72
Guido van Rossum77e1db31997-06-02 23:11:57 +000073# Join two (or more) paths.
Serhiy Storchakac369c2c2014-01-27 23:15:14 +020074def join(path, *paths):
Serhiy Storchaka8518b792014-07-23 20:43:13 +030075 if isinstance(path, bytes):
76 sep = b'\\'
77 seps = b'\\/'
78 colon = b':'
79 else:
80 sep = '\\'
81 seps = '\\/'
82 colon = ':'
Serhiy Storchaka3deeeb02014-10-04 14:58:43 +030083 try:
84 result_drive, result_path = splitdrive(path)
85 for p in paths:
86 p_drive, p_path = splitdrive(p)
87 if p_path and p_path[0] in seps:
88 # Second path is absolute
89 if p_drive or not result_drive:
90 result_drive = p_drive
Serhiy Storchakac369c2c2014-01-27 23:15:14 +020091 result_path = p_path
92 continue
Serhiy Storchaka3deeeb02014-10-04 14:58:43 +030093 elif p_drive and p_drive != result_drive:
94 if p_drive.lower() != result_drive.lower():
95 # Different drives => ignore the first path entirely
96 result_drive = p_drive
97 result_path = p_path
98 continue
99 # Same drive in different case
100 result_drive = p_drive
101 # Second path is relative to the first
102 if result_path and result_path[-1] not in seps:
103 result_path = result_path + sep
104 result_path = result_path + p_path
105 ## add separator between UNC and non-absolute path
106 if (result_path and result_path[0] not in seps and
107 result_drive and result_drive[-1:] != colon):
108 return result_drive + sep + result_path
109 return result_drive + result_path
110 except (TypeError, AttributeError, BytesWarning):
111 genericpath._check_arg_types('join', path, *paths)
112 raise
Guido van Rossum555915a1994-02-24 11:32:59 +0000113
114
115# Split a path in a drive specification (a drive letter followed by a
Guido van Rossumf3c695c1999-04-06 19:32:19 +0000116# colon) and the path specification.
Guido van Rossum555915a1994-02-24 11:32:59 +0000117# It is always true that drivespec + pathspec == p
118def splitdrive(p):
Mark Hammond5a607a32009-05-06 08:04:54 +0000119 """Split a pathname into drive/UNC sharepoint and relative path specifiers.
120 Returns a 2-tuple (drive_or_unc, path); either part may be empty.
121
122 If you assign
123 result = splitdrive(p)
124 It is always true that:
125 result[0] + result[1] == p
126
127 If the path contained a drive letter, drive_or_unc will contain everything
128 up to and including the colon. e.g. splitdrive("c:/dir") returns ("c:", "/dir")
129
130 If the path contained a UNC path, the drive_or_unc will contain the host name
131 and share up to but not including the fourth directory separator character.
132 e.g. splitdrive("//host/computer/dir") returns ("//host/computer", "/dir")
133
134 Paths cannot contain both a drive letter and a UNC path.
135
136 """
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300137 if len(p) >= 2:
138 if isinstance(p, bytes):
139 sep = b'\\'
140 altsep = b'/'
141 colon = b':'
142 else:
143 sep = '\\'
144 altsep = '/'
145 colon = ':'
146 normp = p.replace(altsep, sep)
Mark Hammond5a607a32009-05-06 08:04:54 +0000147 if (normp[0:2] == sep*2) and (normp[2:3] != sep):
148 # is a UNC path:
149 # vvvvvvvvvvvvvvvvvvvv drive letter or UNC path
150 # \\machine\mountpoint\directory\etc\...
151 # directory ^^^^^^^^^^^^^^^
152 index = normp.find(sep, 2)
153 if index == -1:
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300154 return p[:0], p
Mark Hammond5a607a32009-05-06 08:04:54 +0000155 index2 = normp.find(sep, index + 1)
156 # a UNC path can't have two slashes in a row
157 # (after the initial two)
158 if index2 == index + 1:
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300159 return p[:0], p
Mark Hammond5a607a32009-05-06 08:04:54 +0000160 if index2 == -1:
161 index2 = len(p)
162 return p[:index2], p[index2:]
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300163 if normp[1:2] == colon:
Mark Hammond5a607a32009-05-06 08:04:54 +0000164 return p[:2], p[2:]
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300165 return p[:0], p
Guido van Rossumf3c695c1999-04-06 19:32:19 +0000166
167
168# Parse UNC paths
169def splitunc(p):
Mark Hammond5a607a32009-05-06 08:04:54 +0000170 """Deprecated since Python 3.1. Please use splitdrive() instead;
171 it now handles UNC paths.
172
173 Split a pathname into UNC mount point and relative path specifiers.
Guido van Rossumf3c695c1999-04-06 19:32:19 +0000174
175 Return a 2-tuple (unc, rest); either part may be empty.
176 If unc is not empty, it has the form '//host/mount' (or similar
177 using backslashes). unc+rest is always the input path.
178 Paths containing drive letters never have an UNC part.
179 """
Mark Hammond5a607a32009-05-06 08:04:54 +0000180 import warnings
181 warnings.warn("ntpath.splitunc is deprecated, use ntpath.splitdrive instead",
Serhiy Storchaka593568b2013-12-16 15:13:28 +0200182 DeprecationWarning, 2)
183 drive, path = splitdrive(p)
184 if len(drive) == 2:
185 # Drive letter present
186 return p[:0], p
187 return drive, path
Guido van Rossum555915a1994-02-24 11:32:59 +0000188
189
190# Split a path in head (everything up to the last '/') and tail (the
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000191# rest). After the trailing '/' is stripped, the invariant
Guido van Rossum555915a1994-02-24 11:32:59 +0000192# join(head, tail) == p holds.
193# The resulting head won't end in '/' unless it is the root.
194
195def split(p):
Guido van Rossum534972b1999-02-03 17:20:50 +0000196 """Split a pathname.
197
198 Return tuple (head, tail) where tail is everything after the final slash.
199 Either part may be empty."""
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000200
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000201 seps = _get_bothseps(p)
Guido van Rossum15e22e11997-12-05 19:03:01 +0000202 d, p = splitdrive(p)
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000203 # set i to index beyond p's last slash
204 i = len(p)
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000205 while i and p[i-1] not in seps:
Georg Brandl599b65d2010-07-23 08:46:35 +0000206 i -= 1
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000207 head, tail = p[:i], p[i:] # now tail has no slashes
208 # remove trailing slashes from head, unless it's all slashes
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300209 head = head.rstrip(seps) or head
Guido van Rossum15e22e11997-12-05 19:03:01 +0000210 return d + head, tail
Guido van Rossum555915a1994-02-24 11:32:59 +0000211
212
213# Split a path in root and extension.
Guido van Rossum73e122f1997-01-22 00:17:26 +0000214# The extension is everything starting at the last dot in the last
Guido van Rossum555915a1994-02-24 11:32:59 +0000215# pathname component; the root is everything before that.
216# It is always true that root + ext == p.
217
218def splitext(p):
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300219 if isinstance(p, bytes):
220 return genericpath._splitext(p, b'\\', b'/', b'.')
221 else:
222 return genericpath._splitext(p, '\\', '/', '.')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000223splitext.__doc__ = genericpath._splitext.__doc__
Guido van Rossum555915a1994-02-24 11:32:59 +0000224
225
226# Return the tail (basename) part of a path.
227
228def basename(p):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000229 """Returns the final component of a pathname"""
230 return split(p)[1]
Guido van Rossum555915a1994-02-24 11:32:59 +0000231
232
233# Return the head (dirname) part of a path.
234
235def dirname(p):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000236 """Returns the directory component of a pathname"""
237 return split(p)[0]
Guido van Rossum555915a1994-02-24 11:32:59 +0000238
Guido van Rossum555915a1994-02-24 11:32:59 +0000239# Is a path a symbolic link?
Brian Curtind40e6f72010-07-08 21:39:08 +0000240# This will always return false on systems where os.lstat doesn't exist.
Guido van Rossum555915a1994-02-24 11:32:59 +0000241
242def islink(path):
Brian Curtind40e6f72010-07-08 21:39:08 +0000243 """Test whether a path is a symbolic link.
Jesus Ceaf1af7052012-10-05 02:48:46 +0200244 This will always return false for Windows prior to 6.0.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000245 """
Brian Curtind40e6f72010-07-08 21:39:08 +0000246 try:
247 st = os.lstat(path)
Andrew Svetlovad28c7f2012-12-18 22:02:39 +0200248 except (OSError, AttributeError):
Brian Curtind40e6f72010-07-08 21:39:08 +0000249 return False
250 return stat.S_ISLNK(st.st_mode)
Guido van Rossum555915a1994-02-24 11:32:59 +0000251
Brian Curtind40e6f72010-07-08 21:39:08 +0000252# Being true for dangling symbolic links is also useful.
253
254def lexists(path):
255 """Test whether a path exists. Returns True for broken symbolic links"""
256 try:
257 st = os.lstat(path)
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200258 except OSError:
Brian Curtind40e6f72010-07-08 21:39:08 +0000259 return False
260 return True
Johannes Gijsbersae882f72004-08-30 10:19:56 +0000261
Tim Golden6b528062013-08-01 12:44:00 +0100262# Is a path a mount point?
263# Any drive letter root (eg c:\)
264# Any share UNC (eg \\server\share)
265# Any volume mounted on a filesystem folder
266#
267# No one method detects all three situations. Historically we've lexically
268# detected drive letter roots and share UNCs. The canonical approach to
269# detecting mounted volumes (querying the reparse tag) fails for the most
270# common case: drive letter roots. The alternative which uses GetVolumePathName
271# fails if the drive letter is the result of a SUBST.
272try:
273 from nt import _getvolumepathname
274except ImportError:
275 _getvolumepathname = None
Guido van Rossum555915a1994-02-24 11:32:59 +0000276def ismount(path):
Tim Golden6b528062013-08-01 12:44:00 +0100277 """Test whether a path is a mount point (a drive root, the root of a
278 share, or a mounted volume)"""
Benjamin Peterson48e24782009-03-29 13:02:52 +0000279 seps = _get_bothseps(path)
Tim Golden6b528062013-08-01 12:44:00 +0100280 path = abspath(path)
Mark Hammond5a607a32009-05-06 08:04:54 +0000281 root, rest = splitdrive(path)
282 if root and root[0] in seps:
283 return (not rest) or (rest in seps)
Tim Golden6b528062013-08-01 12:44:00 +0100284 if rest in seps:
285 return True
286
287 if _getvolumepathname:
288 return path.rstrip(seps) == _getvolumepathname(path).rstrip(seps)
289 else:
290 return False
Guido van Rossum555915a1994-02-24 11:32:59 +0000291
292
Guido van Rossum555915a1994-02-24 11:32:59 +0000293# Expand paths beginning with '~' or '~user'.
294# '~' means $HOME; '~user' means that user's home directory.
295# If the path doesn't begin with '~', or if the user or $HOME is unknown,
296# the path is returned unchanged (leaving error reporting to whatever
297# function is called with the expanded path as argument).
298# See also module 'glob' for expansion of *, ? and [...] in pathnames.
299# (A function should also be defined to do full *sh-style environment
300# variable expansion.)
301
302def expanduser(path):
Guido van Rossum534972b1999-02-03 17:20:50 +0000303 """Expand ~ and ~user constructs.
304
305 If user or $HOME is unknown, do nothing."""
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000306 if isinstance(path, bytes):
307 tilde = b'~'
308 else:
309 tilde = '~'
310 if not path.startswith(tilde):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000311 return path
312 i, n = 1, len(path)
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000313 while i < n and path[i] not in _get_bothseps(path):
Georg Brandl599b65d2010-07-23 08:46:35 +0000314 i += 1
Guido van Rossumd8faa362007-04-27 19:54:29 +0000315
316 if 'HOME' in os.environ:
317 userhome = os.environ['HOME']
318 elif 'USERPROFILE' in os.environ:
319 userhome = os.environ['USERPROFILE']
320 elif not 'HOMEPATH' in os.environ:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000321 return path
Guido van Rossumd8faa362007-04-27 19:54:29 +0000322 else:
323 try:
324 drive = os.environ['HOMEDRIVE']
325 except KeyError:
326 drive = ''
327 userhome = join(drive, os.environ['HOMEPATH'])
328
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000329 if isinstance(path, bytes):
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300330 userhome = os.fsencode(userhome)
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000331
Guido van Rossumd8faa362007-04-27 19:54:29 +0000332 if i != 1: #~user
333 userhome = join(dirname(userhome), path[1:i])
334
Guido van Rossum15e22e11997-12-05 19:03:01 +0000335 return userhome + path[i:]
Guido van Rossum555915a1994-02-24 11:32:59 +0000336
337
338# Expand paths containing shell variable substitutions.
339# The following rules apply:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000340# - no expansion within single quotes
Guido van Rossumd8faa362007-04-27 19:54:29 +0000341# - '$$' is translated into '$'
342# - '%%' is translated into '%' if '%%' are not seen in %var1%%var2%
Guido van Rossum15e22e11997-12-05 19:03:01 +0000343# - ${varname} is accepted.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000344# - $varname is accepted.
345# - %varname% is accepted.
346# - varnames can be made out of letters, digits and the characters '_-'
Ezio Melotti13925002011-03-16 11:05:33 +0200347# (though is not verified in the ${varname} and %varname% cases)
Guido van Rossum555915a1994-02-24 11:32:59 +0000348# XXX With COMMAND.COM you can use any characters in a variable name,
349# XXX except '^|<>='.
350
Tim Peters2344fae2001-01-15 00:50:52 +0000351def expandvars(path):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000352 """Expand shell variables of the forms $var, ${var} and %var%.
Guido van Rossum534972b1999-02-03 17:20:50 +0000353
354 Unknown variables are left unchanged."""
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000355 if isinstance(path, bytes):
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300356 if b'$' not in path and b'%' not in path:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000357 return path
358 import string
359 varchars = bytes(string.ascii_letters + string.digits + '_-', 'ascii')
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000360 quote = b'\''
361 percent = b'%'
362 brace = b'{'
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300363 rbrace = b'}'
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000364 dollar = b'$'
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200365 environ = getattr(os, 'environb', None)
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000366 else:
367 if '$' not in path and '%' not in path:
368 return path
369 import string
370 varchars = string.ascii_letters + string.digits + '_-'
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000371 quote = '\''
372 percent = '%'
373 brace = '{'
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300374 rbrace = '}'
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000375 dollar = '$'
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200376 environ = os.environ
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000377 res = path[:0]
Guido van Rossum15e22e11997-12-05 19:03:01 +0000378 index = 0
379 pathlen = len(path)
380 while index < pathlen:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000381 c = path[index:index+1]
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000382 if c == quote: # no expansion within single quotes
Guido van Rossum15e22e11997-12-05 19:03:01 +0000383 path = path[index + 1:]
384 pathlen = len(path)
385 try:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000386 index = path.index(c)
Georg Brandl599b65d2010-07-23 08:46:35 +0000387 res += c + path[:index + 1]
Fred Drakeb4e460a2000-09-28 16:25:20 +0000388 except ValueError:
Georg Brandl599b65d2010-07-23 08:46:35 +0000389 res += path
Fred Drakeb4e460a2000-09-28 16:25:20 +0000390 index = pathlen - 1
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000391 elif c == percent: # variable or '%'
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000392 if path[index + 1:index + 2] == percent:
Georg Brandl599b65d2010-07-23 08:46:35 +0000393 res += c
394 index += 1
Guido van Rossumd8faa362007-04-27 19:54:29 +0000395 else:
396 path = path[index+1:]
397 pathlen = len(path)
398 try:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000399 index = path.index(percent)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000400 except ValueError:
Georg Brandl599b65d2010-07-23 08:46:35 +0000401 res += percent + path
Guido van Rossumd8faa362007-04-27 19:54:29 +0000402 index = pathlen - 1
403 else:
404 var = path[:index]
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200405 try:
406 if environ is None:
407 value = os.fsencode(os.environ[os.fsdecode(var)])
408 else:
409 value = environ[var]
410 except KeyError:
411 value = percent + var + percent
Georg Brandl599b65d2010-07-23 08:46:35 +0000412 res += value
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000413 elif c == dollar: # variable or '$$'
414 if path[index + 1:index + 2] == dollar:
Georg Brandl599b65d2010-07-23 08:46:35 +0000415 res += c
416 index += 1
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000417 elif path[index + 1:index + 2] == brace:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000418 path = path[index+2:]
419 pathlen = len(path)
420 try:
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300421 index = path.index(rbrace)
Fred Drakeb4e460a2000-09-28 16:25:20 +0000422 except ValueError:
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300423 res += dollar + brace + path
Guido van Rossum15e22e11997-12-05 19:03:01 +0000424 index = pathlen - 1
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200425 else:
426 var = path[:index]
427 try:
428 if environ is None:
429 value = os.fsencode(os.environ[os.fsdecode(var)])
430 else:
431 value = environ[var]
432 except KeyError:
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300433 value = dollar + brace + var + rbrace
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200434 res += value
Guido van Rossum15e22e11997-12-05 19:03:01 +0000435 else:
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200436 var = path[:0]
Georg Brandl599b65d2010-07-23 08:46:35 +0000437 index += 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000438 c = path[index:index + 1]
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000439 while c and c in varchars:
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200440 var += c
Georg Brandl599b65d2010-07-23 08:46:35 +0000441 index += 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000442 c = path[index:index + 1]
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200443 try:
444 if environ is None:
445 value = os.fsencode(os.environ[os.fsdecode(var)])
446 else:
447 value = environ[var]
448 except KeyError:
449 value = dollar + var
Georg Brandl599b65d2010-07-23 08:46:35 +0000450 res += value
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000451 if c:
Georg Brandl599b65d2010-07-23 08:46:35 +0000452 index -= 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000453 else:
Georg Brandl599b65d2010-07-23 08:46:35 +0000454 res += c
455 index += 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000456 return res
Guido van Rossum555915a1994-02-24 11:32:59 +0000457
458
Tim Peters54a14a32001-08-30 22:05:26 +0000459# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A\B.
Guido van Rossum3df7b5a1996-08-26 16:35:26 +0000460# Previously, this function also truncated pathnames to 8+3 format,
461# but as this module is called "ntpath", that's obviously wrong!
Guido van Rossum555915a1994-02-24 11:32:59 +0000462
463def normpath(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000464 """Normalize path, eliminating double slashes, etc."""
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300465 if isinstance(path, bytes):
466 sep = b'\\'
467 altsep = b'/'
468 curdir = b'.'
469 pardir = b'..'
470 special_prefixes = (b'\\\\.\\', b'\\\\?\\')
471 else:
472 sep = '\\'
473 altsep = '/'
474 curdir = '.'
475 pardir = '..'
476 special_prefixes = ('\\\\.\\', '\\\\?\\')
Georg Brandlcfb68212010-07-31 21:40:15 +0000477 if path.startswith(special_prefixes):
478 # in the case of paths with these prefixes:
479 # \\.\ -> device names
480 # \\?\ -> literal paths
481 # do not do any normalization, but return the path unchanged
482 return path
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300483 path = path.replace(altsep, sep)
Guido van Rossum15e22e11997-12-05 19:03:01 +0000484 prefix, path = splitdrive(path)
Mark Hammond5a607a32009-05-06 08:04:54 +0000485
486 # collapse initial backslashes
487 if path.startswith(sep):
Georg Brandl599b65d2010-07-23 08:46:35 +0000488 prefix += sep
Mark Hammond5a607a32009-05-06 08:04:54 +0000489 path = path.lstrip(sep)
490
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000491 comps = path.split(sep)
Guido van Rossum15e22e11997-12-05 19:03:01 +0000492 i = 0
493 while i < len(comps):
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300494 if not comps[i] or comps[i] == curdir:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000495 del comps[i]
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300496 elif comps[i] == pardir:
497 if i > 0 and comps[i-1] != pardir:
Tim Peters54a14a32001-08-30 22:05:26 +0000498 del comps[i-1:i+1]
499 i -= 1
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300500 elif i == 0 and prefix.endswith(sep):
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000501 del comps[i]
502 else:
503 i += 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000504 else:
Tim Peters54a14a32001-08-30 22:05:26 +0000505 i += 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000506 # If the path is now empty, substitute '.'
507 if not prefix and not comps:
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300508 comps.append(curdir)
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000509 return prefix + sep.join(comps)
Guido van Rossume294cf61999-01-29 18:05:18 +0000510
511
512# Return an absolute path.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000513try:
514 from nt import _getfullpathname
Mark Hammondf717f052002-01-17 00:44:26 +0000515
Brett Cannoncd171c82013-07-04 17:43:24 -0400516except ImportError: # not running on Windows - mock up something sensible
Thomas Wouters477c8d52006-05-27 19:21:47 +0000517 def abspath(path):
518 """Return the absolute version of a path."""
519 if not isabs(path):
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000520 if isinstance(path, bytes):
521 cwd = os.getcwdb()
522 else:
523 cwd = os.getcwd()
524 path = join(cwd, path)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000525 return normpath(path)
526
527else: # use native Windows method on Windows
528 def abspath(path):
529 """Return the absolute version of a path."""
530
531 if path: # Empty path must return current working directory.
532 try:
533 path = _getfullpathname(path)
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200534 except OSError:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000535 pass # Bad path - return unchanged.
Florent Xiclunaad8c5ca2010-03-08 14:44:41 +0000536 elif isinstance(path, bytes):
537 path = os.getcwdb()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000538 else:
539 path = os.getcwd()
540 return normpath(path)
Guido van Rossum83eeef42001-09-17 15:16:09 +0000541
542# realpath is a no-op on systems without islink support
543realpath = abspath
Mark Hammond8696ebc2002-10-08 02:44:31 +0000544# Win9x family and earlier have no Unicode filename support.
Tim Peters26bc25a2002-10-09 07:56:04 +0000545supports_unicode_filenames = (hasattr(sys, "getwindowsversion") and
546 sys.getwindowsversion()[3] >= 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000547
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300548def relpath(path, start=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000549 """Return a relative version of a path"""
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300550 if isinstance(path, bytes):
551 sep = b'\\'
552 curdir = b'.'
553 pardir = b'..'
554 else:
555 sep = '\\'
556 curdir = '.'
557 pardir = '..'
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000558
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300559 if start is None:
560 start = curdir
Guido van Rossumd8faa362007-04-27 19:54:29 +0000561
562 if not path:
563 raise ValueError("no path specified")
Mark Hammond5a607a32009-05-06 08:04:54 +0000564
Serhiy Storchaka3deeeb02014-10-04 14:58:43 +0300565 try:
566 start_abs = abspath(normpath(start))
567 path_abs = abspath(normpath(path))
568 start_drive, start_rest = splitdrive(start_abs)
569 path_drive, path_rest = splitdrive(path_abs)
570 if normcase(start_drive) != normcase(path_drive):
571 raise ValueError("path is on mount %r, start on mount %r" % (
572 path_drive, start_drive))
Mark Hammond5a607a32009-05-06 08:04:54 +0000573
Serhiy Storchaka3deeeb02014-10-04 14:58:43 +0300574 start_list = [x for x in start_rest.split(sep) if x]
575 path_list = [x for x in path_rest.split(sep) if x]
576 # Work out how much of the filepath is shared by start and path.
577 i = 0
578 for e1, e2 in zip(start_list, path_list):
579 if normcase(e1) != normcase(e2):
580 break
581 i += 1
Guido van Rossumd8faa362007-04-27 19:54:29 +0000582
Serhiy Storchaka3deeeb02014-10-04 14:58:43 +0300583 rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
584 if not rel_list:
585 return curdir
586 return join(*rel_list)
587 except (TypeError, ValueError, AttributeError, BytesWarning):
588 genericpath._check_arg_types('relpath', path, start)
589 raise
Brian Curtind40e6f72010-07-08 21:39:08 +0000590
591
592# determine if two files are in fact the same file
Brian Curtin0dac8082010-09-23 20:38:14 +0000593try:
Brian Curtine8e80422010-09-24 13:56:34 +0000594 # GetFinalPathNameByHandle is available starting with Windows 6.0.
595 # Windows XP and non-Windows OS'es will mock _getfinalpathname.
596 if sys.getwindowsversion()[:2] >= (6, 0):
597 from nt import _getfinalpathname
598 else:
599 raise ImportError
600except (AttributeError, ImportError):
Brian Curtin0dac8082010-09-23 20:38:14 +0000601 # On Windows XP and earlier, two files are the same if their absolute
602 # pathnames are the same.
Brian Curtine8e80422010-09-24 13:56:34 +0000603 # Non-Windows operating systems fake this method with an XP
604 # approximation.
Brian Curtin0dac8082010-09-23 20:38:14 +0000605 def _getfinalpathname(f):
Ronald Oussoren6355c162011-05-06 17:11:07 +0200606 return normcase(abspath(f))
Brian Curtin0dac8082010-09-23 20:38:14 +0000607
Brian Curtin9c669cc2011-06-08 18:17:18 -0500608
609try:
610 # The genericpath.isdir implementation uses os.stat and checks the mode
611 # attribute to tell whether or not the path is a directory.
612 # This is overkill on Windows - just pass the path to GetFileAttributes
613 # and check the attribute from there.
Brian Curtin95d028f2011-06-09 09:10:38 -0500614 from nt import _isdir as isdir
Brett Cannoncd171c82013-07-04 17:43:24 -0400615except ImportError:
Brian Curtin95d028f2011-06-09 09:10:38 -0500616 # Use genericpath.isdir as imported above.
617 pass