blob: f6b5cd7b0cef40aa60adb1ccfd8470eb1f385497 [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 Storchakac369c2c2014-01-27 23:15:14 +020083 result_drive, result_path = splitdrive(path)
84 for p in paths:
85 p_drive, p_path = splitdrive(p)
86 if p_path and p_path[0] in seps:
87 # Second path is absolute
88 if p_drive or not result_drive:
89 result_drive = p_drive
90 result_path = p_path
91 continue
92 elif p_drive and p_drive != result_drive:
93 if p_drive.lower() != result_drive.lower():
94 # Different drives => ignore the first path entirely
95 result_drive = p_drive
96 result_path = p_path
97 continue
98 # Same drive in different case
99 result_drive = p_drive
100 # Second path is relative to the first
101 if result_path and result_path[-1] not in seps:
102 result_path = result_path + sep
103 result_path = result_path + p_path
104 ## add separator between UNC and non-absolute path
105 if (result_path and result_path[0] not in seps and
106 result_drive and result_drive[-1:] != colon):
107 return result_drive + sep + result_path
108 return result_drive + result_path
Guido van Rossum555915a1994-02-24 11:32:59 +0000109
110
111# Split a path in a drive specification (a drive letter followed by a
Guido van Rossumf3c695c1999-04-06 19:32:19 +0000112# colon) and the path specification.
Guido van Rossum555915a1994-02-24 11:32:59 +0000113# It is always true that drivespec + pathspec == p
114def splitdrive(p):
Mark Hammond5a607a32009-05-06 08:04:54 +0000115 """Split a pathname into drive/UNC sharepoint and relative path specifiers.
116 Returns a 2-tuple (drive_or_unc, path); either part may be empty.
117
118 If you assign
119 result = splitdrive(p)
120 It is always true that:
121 result[0] + result[1] == p
122
123 If the path contained a drive letter, drive_or_unc will contain everything
124 up to and including the colon. e.g. splitdrive("c:/dir") returns ("c:", "/dir")
125
126 If the path contained a UNC path, the drive_or_unc will contain the host name
127 and share up to but not including the fourth directory separator character.
128 e.g. splitdrive("//host/computer/dir") returns ("//host/computer", "/dir")
129
130 Paths cannot contain both a drive letter and a UNC path.
131
132 """
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300133 if len(p) >= 2:
134 if isinstance(p, bytes):
135 sep = b'\\'
136 altsep = b'/'
137 colon = b':'
138 else:
139 sep = '\\'
140 altsep = '/'
141 colon = ':'
142 normp = p.replace(altsep, sep)
Mark Hammond5a607a32009-05-06 08:04:54 +0000143 if (normp[0:2] == sep*2) and (normp[2:3] != sep):
144 # is a UNC path:
145 # vvvvvvvvvvvvvvvvvvvv drive letter or UNC path
146 # \\machine\mountpoint\directory\etc\...
147 # directory ^^^^^^^^^^^^^^^
148 index = normp.find(sep, 2)
149 if index == -1:
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300150 return p[:0], p
Mark Hammond5a607a32009-05-06 08:04:54 +0000151 index2 = normp.find(sep, index + 1)
152 # a UNC path can't have two slashes in a row
153 # (after the initial two)
154 if index2 == index + 1:
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300155 return p[:0], p
Mark Hammond5a607a32009-05-06 08:04:54 +0000156 if index2 == -1:
157 index2 = len(p)
158 return p[:index2], p[index2:]
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300159 if normp[1:2] == colon:
Mark Hammond5a607a32009-05-06 08:04:54 +0000160 return p[:2], p[2:]
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300161 return p[:0], p
Guido van Rossumf3c695c1999-04-06 19:32:19 +0000162
163
164# Parse UNC paths
165def splitunc(p):
Mark Hammond5a607a32009-05-06 08:04:54 +0000166 """Deprecated since Python 3.1. Please use splitdrive() instead;
167 it now handles UNC paths.
168
169 Split a pathname into UNC mount point and relative path specifiers.
Guido van Rossumf3c695c1999-04-06 19:32:19 +0000170
171 Return a 2-tuple (unc, rest); either part may be empty.
172 If unc is not empty, it has the form '//host/mount' (or similar
173 using backslashes). unc+rest is always the input path.
174 Paths containing drive letters never have an UNC part.
175 """
Mark Hammond5a607a32009-05-06 08:04:54 +0000176 import warnings
177 warnings.warn("ntpath.splitunc is deprecated, use ntpath.splitdrive instead",
Serhiy Storchaka593568b2013-12-16 15:13:28 +0200178 DeprecationWarning, 2)
179 drive, path = splitdrive(p)
180 if len(drive) == 2:
181 # Drive letter present
182 return p[:0], p
183 return drive, path
Guido van Rossum555915a1994-02-24 11:32:59 +0000184
185
186# Split a path in head (everything up to the last '/') and tail (the
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000187# rest). After the trailing '/' is stripped, the invariant
Guido van Rossum555915a1994-02-24 11:32:59 +0000188# join(head, tail) == p holds.
189# The resulting head won't end in '/' unless it is the root.
190
191def split(p):
Guido van Rossum534972b1999-02-03 17:20:50 +0000192 """Split a pathname.
193
194 Return tuple (head, tail) where tail is everything after the final slash.
195 Either part may be empty."""
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000196
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000197 seps = _get_bothseps(p)
Guido van Rossum15e22e11997-12-05 19:03:01 +0000198 d, p = splitdrive(p)
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000199 # set i to index beyond p's last slash
200 i = len(p)
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000201 while i and p[i-1] not in seps:
Georg Brandl599b65d2010-07-23 08:46:35 +0000202 i -= 1
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000203 head, tail = p[:i], p[i:] # now tail has no slashes
204 # remove trailing slashes from head, unless it's all slashes
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300205 head = head.rstrip(seps) or head
Guido van Rossum15e22e11997-12-05 19:03:01 +0000206 return d + head, tail
Guido van Rossum555915a1994-02-24 11:32:59 +0000207
208
209# Split a path in root and extension.
Guido van Rossum73e122f1997-01-22 00:17:26 +0000210# The extension is everything starting at the last dot in the last
Guido van Rossum555915a1994-02-24 11:32:59 +0000211# pathname component; the root is everything before that.
212# It is always true that root + ext == p.
213
214def splitext(p):
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300215 if isinstance(p, bytes):
216 return genericpath._splitext(p, b'\\', b'/', b'.')
217 else:
218 return genericpath._splitext(p, '\\', '/', '.')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000219splitext.__doc__ = genericpath._splitext.__doc__
Guido van Rossum555915a1994-02-24 11:32:59 +0000220
221
222# Return the tail (basename) part of a path.
223
224def basename(p):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000225 """Returns the final component of a pathname"""
226 return split(p)[1]
Guido van Rossum555915a1994-02-24 11:32:59 +0000227
228
229# Return the head (dirname) part of a path.
230
231def dirname(p):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000232 """Returns the directory component of a pathname"""
233 return split(p)[0]
Guido van Rossum555915a1994-02-24 11:32:59 +0000234
Guido van Rossum555915a1994-02-24 11:32:59 +0000235# Is a path a symbolic link?
Brian Curtind40e6f72010-07-08 21:39:08 +0000236# This will always return false on systems where os.lstat doesn't exist.
Guido van Rossum555915a1994-02-24 11:32:59 +0000237
238def islink(path):
Brian Curtind40e6f72010-07-08 21:39:08 +0000239 """Test whether a path is a symbolic link.
Jesus Ceaf1af7052012-10-05 02:48:46 +0200240 This will always return false for Windows prior to 6.0.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000241 """
Brian Curtind40e6f72010-07-08 21:39:08 +0000242 try:
243 st = os.lstat(path)
Andrew Svetlovad28c7f2012-12-18 22:02:39 +0200244 except (OSError, AttributeError):
Brian Curtind40e6f72010-07-08 21:39:08 +0000245 return False
246 return stat.S_ISLNK(st.st_mode)
Guido van Rossum555915a1994-02-24 11:32:59 +0000247
Brian Curtind40e6f72010-07-08 21:39:08 +0000248# Being true for dangling symbolic links is also useful.
249
250def lexists(path):
251 """Test whether a path exists. Returns True for broken symbolic links"""
252 try:
253 st = os.lstat(path)
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200254 except OSError:
Brian Curtind40e6f72010-07-08 21:39:08 +0000255 return False
256 return True
Johannes Gijsbersae882f72004-08-30 10:19:56 +0000257
Tim Golden6b528062013-08-01 12:44:00 +0100258# Is a path a mount point?
259# Any drive letter root (eg c:\)
260# Any share UNC (eg \\server\share)
261# Any volume mounted on a filesystem folder
262#
263# No one method detects all three situations. Historically we've lexically
264# detected drive letter roots and share UNCs. The canonical approach to
265# detecting mounted volumes (querying the reparse tag) fails for the most
266# common case: drive letter roots. The alternative which uses GetVolumePathName
267# fails if the drive letter is the result of a SUBST.
268try:
269 from nt import _getvolumepathname
270except ImportError:
271 _getvolumepathname = None
Guido van Rossum555915a1994-02-24 11:32:59 +0000272def ismount(path):
Tim Golden6b528062013-08-01 12:44:00 +0100273 """Test whether a path is a mount point (a drive root, the root of a
274 share, or a mounted volume)"""
Benjamin Peterson48e24782009-03-29 13:02:52 +0000275 seps = _get_bothseps(path)
Tim Golden6b528062013-08-01 12:44:00 +0100276 path = abspath(path)
Mark Hammond5a607a32009-05-06 08:04:54 +0000277 root, rest = splitdrive(path)
278 if root and root[0] in seps:
279 return (not rest) or (rest in seps)
Tim Golden6b528062013-08-01 12:44:00 +0100280 if rest in seps:
281 return True
282
283 if _getvolumepathname:
284 return path.rstrip(seps) == _getvolumepathname(path).rstrip(seps)
285 else:
286 return False
Guido van Rossum555915a1994-02-24 11:32:59 +0000287
288
Guido van Rossum555915a1994-02-24 11:32:59 +0000289# Expand paths beginning with '~' or '~user'.
290# '~' means $HOME; '~user' means that user's home directory.
291# If the path doesn't begin with '~', or if the user or $HOME is unknown,
292# the path is returned unchanged (leaving error reporting to whatever
293# function is called with the expanded path as argument).
294# See also module 'glob' for expansion of *, ? and [...] in pathnames.
295# (A function should also be defined to do full *sh-style environment
296# variable expansion.)
297
298def expanduser(path):
Guido van Rossum534972b1999-02-03 17:20:50 +0000299 """Expand ~ and ~user constructs.
300
301 If user or $HOME is unknown, do nothing."""
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000302 if isinstance(path, bytes):
303 tilde = b'~'
304 else:
305 tilde = '~'
306 if not path.startswith(tilde):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000307 return path
308 i, n = 1, len(path)
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000309 while i < n and path[i] not in _get_bothseps(path):
Georg Brandl599b65d2010-07-23 08:46:35 +0000310 i += 1
Guido van Rossumd8faa362007-04-27 19:54:29 +0000311
312 if 'HOME' in os.environ:
313 userhome = os.environ['HOME']
314 elif 'USERPROFILE' in os.environ:
315 userhome = os.environ['USERPROFILE']
316 elif not 'HOMEPATH' in os.environ:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000317 return path
Guido van Rossumd8faa362007-04-27 19:54:29 +0000318 else:
319 try:
320 drive = os.environ['HOMEDRIVE']
321 except KeyError:
322 drive = ''
323 userhome = join(drive, os.environ['HOMEPATH'])
324
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000325 if isinstance(path, bytes):
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300326 userhome = os.fsencode(userhome)
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000327
Guido van Rossumd8faa362007-04-27 19:54:29 +0000328 if i != 1: #~user
329 userhome = join(dirname(userhome), path[1:i])
330
Guido van Rossum15e22e11997-12-05 19:03:01 +0000331 return userhome + path[i:]
Guido van Rossum555915a1994-02-24 11:32:59 +0000332
333
334# Expand paths containing shell variable substitutions.
335# The following rules apply:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000336# - no expansion within single quotes
Guido van Rossumd8faa362007-04-27 19:54:29 +0000337# - '$$' is translated into '$'
338# - '%%' is translated into '%' if '%%' are not seen in %var1%%var2%
Guido van Rossum15e22e11997-12-05 19:03:01 +0000339# - ${varname} is accepted.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000340# - $varname is accepted.
341# - %varname% is accepted.
342# - varnames can be made out of letters, digits and the characters '_-'
Ezio Melotti13925002011-03-16 11:05:33 +0200343# (though is not verified in the ${varname} and %varname% cases)
Guido van Rossum555915a1994-02-24 11:32:59 +0000344# XXX With COMMAND.COM you can use any characters in a variable name,
345# XXX except '^|<>='.
346
Tim Peters2344fae2001-01-15 00:50:52 +0000347def expandvars(path):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000348 """Expand shell variables of the forms $var, ${var} and %var%.
Guido van Rossum534972b1999-02-03 17:20:50 +0000349
350 Unknown variables are left unchanged."""
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000351 if isinstance(path, bytes):
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300352 if b'$' not in path and b'%' not in path:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000353 return path
354 import string
355 varchars = bytes(string.ascii_letters + string.digits + '_-', 'ascii')
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000356 quote = b'\''
357 percent = b'%'
358 brace = b'{'
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300359 rbrace = b'}'
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000360 dollar = b'$'
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200361 environ = getattr(os, 'environb', None)
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000362 else:
363 if '$' not in path and '%' not in path:
364 return path
365 import string
366 varchars = string.ascii_letters + string.digits + '_-'
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000367 quote = '\''
368 percent = '%'
369 brace = '{'
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300370 rbrace = '}'
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000371 dollar = '$'
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200372 environ = os.environ
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000373 res = path[:0]
Guido van Rossum15e22e11997-12-05 19:03:01 +0000374 index = 0
375 pathlen = len(path)
376 while index < pathlen:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000377 c = path[index:index+1]
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000378 if c == quote: # no expansion within single quotes
Guido van Rossum15e22e11997-12-05 19:03:01 +0000379 path = path[index + 1:]
380 pathlen = len(path)
381 try:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000382 index = path.index(c)
Georg Brandl599b65d2010-07-23 08:46:35 +0000383 res += c + path[:index + 1]
Fred Drakeb4e460a2000-09-28 16:25:20 +0000384 except ValueError:
Georg Brandl599b65d2010-07-23 08:46:35 +0000385 res += path
Fred Drakeb4e460a2000-09-28 16:25:20 +0000386 index = pathlen - 1
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000387 elif c == percent: # variable or '%'
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000388 if path[index + 1:index + 2] == percent:
Georg Brandl599b65d2010-07-23 08:46:35 +0000389 res += c
390 index += 1
Guido van Rossumd8faa362007-04-27 19:54:29 +0000391 else:
392 path = path[index+1:]
393 pathlen = len(path)
394 try:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000395 index = path.index(percent)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000396 except ValueError:
Georg Brandl599b65d2010-07-23 08:46:35 +0000397 res += percent + path
Guido van Rossumd8faa362007-04-27 19:54:29 +0000398 index = pathlen - 1
399 else:
400 var = path[:index]
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200401 try:
402 if environ is None:
403 value = os.fsencode(os.environ[os.fsdecode(var)])
404 else:
405 value = environ[var]
406 except KeyError:
407 value = percent + var + percent
Georg Brandl599b65d2010-07-23 08:46:35 +0000408 res += value
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000409 elif c == dollar: # variable or '$$'
410 if path[index + 1:index + 2] == dollar:
Georg Brandl599b65d2010-07-23 08:46:35 +0000411 res += c
412 index += 1
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000413 elif path[index + 1:index + 2] == brace:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000414 path = path[index+2:]
415 pathlen = len(path)
416 try:
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300417 index = path.index(rbrace)
Fred Drakeb4e460a2000-09-28 16:25:20 +0000418 except ValueError:
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300419 res += dollar + brace + path
Guido van Rossum15e22e11997-12-05 19:03:01 +0000420 index = pathlen - 1
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200421 else:
422 var = path[:index]
423 try:
424 if environ is None:
425 value = os.fsencode(os.environ[os.fsdecode(var)])
426 else:
427 value = environ[var]
428 except KeyError:
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300429 value = dollar + brace + var + rbrace
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200430 res += value
Guido van Rossum15e22e11997-12-05 19:03:01 +0000431 else:
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200432 var = path[:0]
Georg Brandl599b65d2010-07-23 08:46:35 +0000433 index += 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000434 c = path[index:index + 1]
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000435 while c and c in varchars:
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200436 var += c
Georg Brandl599b65d2010-07-23 08:46:35 +0000437 index += 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000438 c = path[index:index + 1]
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200439 try:
440 if environ is None:
441 value = os.fsencode(os.environ[os.fsdecode(var)])
442 else:
443 value = environ[var]
444 except KeyError:
445 value = dollar + var
Georg Brandl599b65d2010-07-23 08:46:35 +0000446 res += value
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000447 if c:
Georg Brandl599b65d2010-07-23 08:46:35 +0000448 index -= 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000449 else:
Georg Brandl599b65d2010-07-23 08:46:35 +0000450 res += c
451 index += 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000452 return res
Guido van Rossum555915a1994-02-24 11:32:59 +0000453
454
Tim Peters54a14a32001-08-30 22:05:26 +0000455# 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 +0000456# Previously, this function also truncated pathnames to 8+3 format,
457# but as this module is called "ntpath", that's obviously wrong!
Guido van Rossum555915a1994-02-24 11:32:59 +0000458
459def normpath(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000460 """Normalize path, eliminating double slashes, etc."""
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300461 if isinstance(path, bytes):
462 sep = b'\\'
463 altsep = b'/'
464 curdir = b'.'
465 pardir = b'..'
466 special_prefixes = (b'\\\\.\\', b'\\\\?\\')
467 else:
468 sep = '\\'
469 altsep = '/'
470 curdir = '.'
471 pardir = '..'
472 special_prefixes = ('\\\\.\\', '\\\\?\\')
Georg Brandlcfb68212010-07-31 21:40:15 +0000473 if path.startswith(special_prefixes):
474 # in the case of paths with these prefixes:
475 # \\.\ -> device names
476 # \\?\ -> literal paths
477 # do not do any normalization, but return the path unchanged
478 return path
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300479 path = path.replace(altsep, sep)
Guido van Rossum15e22e11997-12-05 19:03:01 +0000480 prefix, path = splitdrive(path)
Mark Hammond5a607a32009-05-06 08:04:54 +0000481
482 # collapse initial backslashes
483 if path.startswith(sep):
Georg Brandl599b65d2010-07-23 08:46:35 +0000484 prefix += sep
Mark Hammond5a607a32009-05-06 08:04:54 +0000485 path = path.lstrip(sep)
486
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000487 comps = path.split(sep)
Guido van Rossum15e22e11997-12-05 19:03:01 +0000488 i = 0
489 while i < len(comps):
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300490 if not comps[i] or comps[i] == curdir:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000491 del comps[i]
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300492 elif comps[i] == pardir:
493 if i > 0 and comps[i-1] != pardir:
Tim Peters54a14a32001-08-30 22:05:26 +0000494 del comps[i-1:i+1]
495 i -= 1
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300496 elif i == 0 and prefix.endswith(sep):
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000497 del comps[i]
498 else:
499 i += 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000500 else:
Tim Peters54a14a32001-08-30 22:05:26 +0000501 i += 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000502 # If the path is now empty, substitute '.'
503 if not prefix and not comps:
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300504 comps.append(curdir)
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000505 return prefix + sep.join(comps)
Guido van Rossume294cf61999-01-29 18:05:18 +0000506
507
508# Return an absolute path.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000509try:
510 from nt import _getfullpathname
Mark Hammondf717f052002-01-17 00:44:26 +0000511
Brett Cannoncd171c82013-07-04 17:43:24 -0400512except ImportError: # not running on Windows - mock up something sensible
Thomas Wouters477c8d52006-05-27 19:21:47 +0000513 def abspath(path):
514 """Return the absolute version of a path."""
515 if not isabs(path):
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000516 if isinstance(path, bytes):
517 cwd = os.getcwdb()
518 else:
519 cwd = os.getcwd()
520 path = join(cwd, path)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000521 return normpath(path)
522
523else: # use native Windows method on Windows
524 def abspath(path):
525 """Return the absolute version of a path."""
526
527 if path: # Empty path must return current working directory.
528 try:
529 path = _getfullpathname(path)
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200530 except OSError:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000531 pass # Bad path - return unchanged.
Florent Xiclunaad8c5ca2010-03-08 14:44:41 +0000532 elif isinstance(path, bytes):
533 path = os.getcwdb()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000534 else:
535 path = os.getcwd()
536 return normpath(path)
Guido van Rossum83eeef42001-09-17 15:16:09 +0000537
538# realpath is a no-op on systems without islink support
539realpath = abspath
Mark Hammond8696ebc2002-10-08 02:44:31 +0000540# Win9x family and earlier have no Unicode filename support.
Tim Peters26bc25a2002-10-09 07:56:04 +0000541supports_unicode_filenames = (hasattr(sys, "getwindowsversion") and
542 sys.getwindowsversion()[3] >= 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000543
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300544def relpath(path, start=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000545 """Return a relative version of a path"""
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300546 if isinstance(path, bytes):
547 sep = b'\\'
548 curdir = b'.'
549 pardir = b'..'
550 else:
551 sep = '\\'
552 curdir = '.'
553 pardir = '..'
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000554
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300555 if start is None:
556 start = curdir
Guido van Rossumd8faa362007-04-27 19:54:29 +0000557
558 if not path:
559 raise ValueError("no path specified")
Mark Hammond5a607a32009-05-06 08:04:54 +0000560
561 start_abs = abspath(normpath(start))
562 path_abs = abspath(normpath(path))
563 start_drive, start_rest = splitdrive(start_abs)
564 path_drive, path_rest = splitdrive(path_abs)
Hirokazu Yamamotob08820a2010-10-18 12:13:18 +0000565 if normcase(start_drive) != normcase(path_drive):
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300566 raise ValueError("path is on mount %r, start on mount %r" % (
567 path_drive, start_drive))
Mark Hammond5a607a32009-05-06 08:04:54 +0000568
569 start_list = [x for x in start_rest.split(sep) if x]
570 path_list = [x for x in path_rest.split(sep) if x]
Guido van Rossumd8faa362007-04-27 19:54:29 +0000571 # Work out how much of the filepath is shared by start and path.
Mark Hammond5a607a32009-05-06 08:04:54 +0000572 i = 0
573 for e1, e2 in zip(start_list, path_list):
Hirokazu Yamamotob08820a2010-10-18 12:13:18 +0000574 if normcase(e1) != normcase(e2):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000575 break
Guido van Rossumd8faa362007-04-27 19:54:29 +0000576 i += 1
577
578 rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
Christian Heimesfaf2f632008-01-06 16:59:19 +0000579 if not rel_list:
Serhiy Storchaka8518b792014-07-23 20:43:13 +0300580 return curdir
Guido van Rossumd8faa362007-04-27 19:54:29 +0000581 return join(*rel_list)
Brian Curtind40e6f72010-07-08 21:39:08 +0000582
583
584# determine if two files are in fact the same file
Brian Curtin0dac8082010-09-23 20:38:14 +0000585try:
Brian Curtine8e80422010-09-24 13:56:34 +0000586 # GetFinalPathNameByHandle is available starting with Windows 6.0.
587 # Windows XP and non-Windows OS'es will mock _getfinalpathname.
588 if sys.getwindowsversion()[:2] >= (6, 0):
589 from nt import _getfinalpathname
590 else:
591 raise ImportError
592except (AttributeError, ImportError):
Brian Curtin0dac8082010-09-23 20:38:14 +0000593 # On Windows XP and earlier, two files are the same if their absolute
594 # pathnames are the same.
Brian Curtine8e80422010-09-24 13:56:34 +0000595 # Non-Windows operating systems fake this method with an XP
596 # approximation.
Brian Curtin0dac8082010-09-23 20:38:14 +0000597 def _getfinalpathname(f):
Ronald Oussoren6355c162011-05-06 17:11:07 +0200598 return normcase(abspath(f))
Brian Curtin0dac8082010-09-23 20:38:14 +0000599
Brian Curtin9c669cc2011-06-08 18:17:18 -0500600
601try:
602 # The genericpath.isdir implementation uses os.stat and checks the mode
603 # attribute to tell whether or not the path is a directory.
604 # This is overkill on Windows - just pass the path to GetFileAttributes
605 # and check the attribute from there.
Brian Curtin95d028f2011-06-09 09:10:38 -0500606 from nt import _isdir as isdir
Brett Cannoncd171c82013-07-04 17:43:24 -0400607except ImportError:
Brian Curtin95d028f2011-06-09 09:10:38 -0500608 # Use genericpath.isdir as imported above.
609 pass