blob: 9e4cff7a6c003a749f37b13ffd1f7795e56b44c1 [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",
Guido van Rossumd8faa362007-04-27 19:54:29 +000019 "extsep","devnull","realpath","supports_unicode_filenames","relpath"]
Guido van Rossum555915a1994-02-24 11:32:59 +000020
Skip Montanaro117910d2003-02-14 19:35:31 +000021# strings representing various path-related bits and pieces
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +000022# These are primarily for export; internally, they are hardcoded.
Skip Montanaro117910d2003-02-14 19:35:31 +000023curdir = '.'
24pardir = '..'
25extsep = '.'
26sep = '\\'
27pathsep = ';'
Skip Montanaro9ddac3e2003-03-28 22:23:24 +000028altsep = '/'
Andrew MacIntyre437966c2003-02-17 09:17:50 +000029defpath = '.;C:\\bin'
Skip Montanaro117910d2003-02-14 19:35:31 +000030if 'ce' in sys.builtin_module_names:
31 defpath = '\\Windows'
32elif 'os2' in sys.builtin_module_names:
Andrew MacIntyre437966c2003-02-17 09:17:50 +000033 # OS/2 w/ VACPP
Skip Montanaro117910d2003-02-14 19:35:31 +000034 altsep = '/'
Martin v. Löwisbdec50f2004-06-08 08:29:33 +000035devnull = 'nul'
Skip Montanaro117910d2003-02-14 19:35:31 +000036
Mark Hammond5a607a32009-05-06 08:04:54 +000037def _get_empty(path):
38 if isinstance(path, bytes):
39 return b''
40 else:
41 return ''
42
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +000043def _get_sep(path):
44 if isinstance(path, bytes):
45 return b'\\'
46 else:
47 return '\\'
48
49def _get_altsep(path):
50 if isinstance(path, bytes):
51 return b'/'
52 else:
53 return '/'
54
55def _get_bothseps(path):
56 if isinstance(path, bytes):
57 return b'\\/'
58 else:
59 return '\\/'
60
61def _get_dot(path):
62 if isinstance(path, bytes):
63 return b'.'
64 else:
65 return '.'
66
67def _get_colon(path):
68 if isinstance(path, bytes):
69 return b':'
70 else:
71 return ':'
72
Georg Brandl611f8f52010-08-01 19:17:57 +000073def _get_special(path):
74 if isinstance(path, bytes):
75 return (b'\\\\.\\', b'\\\\?\\')
76 else:
77 return ('\\\\.\\', '\\\\?\\')
78
Guido van Rossume2ad88c1997-08-12 14:46:58 +000079# Normalize the case of a pathname and map slashes to backslashes.
80# Other normalizations (such as optimizing '../' away) are not done
Guido van Rossum555915a1994-02-24 11:32:59 +000081# (this is done by normpath).
Guido van Rossume2ad88c1997-08-12 14:46:58 +000082
Guido van Rossum555915a1994-02-24 11:32:59 +000083def normcase(s):
Guido van Rossum16a0bc21998-02-18 13:48:31 +000084 """Normalize case of pathname.
85
Guido van Rossum534972b1999-02-03 17:20:50 +000086 Makes all characters lowercase and all slashes into backslashes."""
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +000087 return s.replace(_get_altsep(s), _get_sep(s)).lower()
Guido van Rossum555915a1994-02-24 11:32:59 +000088
Guido van Rossum77e1db31997-06-02 23:11:57 +000089
Fred Drakeef0b5dd2000-02-17 17:30:40 +000090# Return whether a path is absolute.
Mark Hammond5a607a32009-05-06 08:04:54 +000091# Trivial in Posix, harder on Windows.
92# For Windows it is absolute if it starts with a slash or backslash (current
93# volume), or if a pathname after the volume-letter-and-colon or UNC-resource
Guido van Rossum534972b1999-02-03 17:20:50 +000094# starts with a slash or backslash.
Guido van Rossum555915a1994-02-24 11:32:59 +000095
96def isabs(s):
Guido van Rossum15e22e11997-12-05 19:03:01 +000097 """Test whether a path is absolute"""
98 s = splitdrive(s)[1]
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +000099 return len(s) > 0 and s[:1] in _get_bothseps(s)
Guido van Rossum555915a1994-02-24 11:32:59 +0000100
101
Guido van Rossum77e1db31997-06-02 23:11:57 +0000102# Join two (or more) paths.
103
Barry Warsaw384d2491997-02-18 21:53:25 +0000104def join(a, *p):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000105 """Join two or more pathname components, inserting "\\" as needed.
106 If any component is an absolute path, all previous path components
107 will be discarded."""
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000108 sep = _get_sep(a)
109 seps = _get_bothseps(a)
110 colon = _get_colon(a)
Guido van Rossum15e22e11997-12-05 19:03:01 +0000111 path = a
112 for b in p:
Tim Peters33dc0a12001-07-27 08:09:54 +0000113 b_wins = 0 # set to 1 iff b makes path irrelevant
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000114 if not path:
Tim Peters33dc0a12001-07-27 08:09:54 +0000115 b_wins = 1
Tim Peters1bdd0f22001-07-19 17:18:18 +0000116
Tim Peters33dc0a12001-07-27 08:09:54 +0000117 elif isabs(b):
118 # This probably wipes out path so far. However, it's more
Mark Hammond5a607a32009-05-06 08:04:54 +0000119 # complicated if path begins with a drive letter. You get a+b
120 # (minus redundant slashes) in these four cases:
Tim Peters33dc0a12001-07-27 08:09:54 +0000121 # 1. join('c:', '/a') == 'c:/a'
Mark Hammond5a607a32009-05-06 08:04:54 +0000122 # 2. join('//computer/share', '/a') == '//computer/share/a'
123 # 3. join('c:/', '/a') == 'c:/a'
124 # 4. join('//computer/share/', '/a') == '//computer/share/a'
125 # But b wins in all of these cases:
126 # 5. join('c:/a', '/b') == '/b'
127 # 6. join('//computer/share/a', '/b') == '/b'
128 # 7. join('c:', 'd:/') == 'd:/'
129 # 8. join('c:', '//computer/share/') == '//computer/share/'
130 # 9. join('//computer/share', 'd:/') == 'd:/'
131 # 10. join('//computer/share', '//computer/share/') == '//computer/share/'
132 # 11. join('c:/', 'd:/') == 'd:/'
133 # 12. join('c:/', '//computer/share/') == '//computer/share/'
134 # 13. join('//computer/share/', 'd:/') == 'd:/'
135 # 14. join('//computer/share/', '//computer/share/') == '//computer/share/'
136 b_prefix, b_rest = splitdrive(b)
Tim Peters1bdd0f22001-07-19 17:18:18 +0000137
Mark Hammond5a607a32009-05-06 08:04:54 +0000138 # if b has a prefix, it always wins.
139 if b_prefix:
Tim Peters33dc0a12001-07-27 08:09:54 +0000140 b_wins = 1
Mark Hammond5a607a32009-05-06 08:04:54 +0000141 else:
142 # b doesn't have a prefix.
143 # but isabs(b) returned true.
144 # and therefore b_rest[0] must be a slash.
145 # (but let's check that.)
146 assert(b_rest and b_rest[0] in seps)
147
148 # so, b still wins if path has a rest that's more than a sep.
149 # you get a+b if path_rest is empty or only has a sep.
150 # (see cases 1-4 for times when b loses.)
151 path_rest = splitdrive(path)[1]
152 b_wins = path_rest and path_rest not in seps
Tim Peters1bdd0f22001-07-19 17:18:18 +0000153
Tim Peters33dc0a12001-07-27 08:09:54 +0000154 if b_wins:
155 path = b
156 else:
157 # Join, and ensure there's a separator.
158 assert len(path) > 0
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000159 if path[-1:] in seps:
160 if b and b[:1] in seps:
Tim Peters33dc0a12001-07-27 08:09:54 +0000161 path += b[1:]
162 else:
163 path += b
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000164 elif path[-1:] == colon:
Tim Peters33dc0a12001-07-27 08:09:54 +0000165 path += b
166 elif b:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000167 if b[:1] in seps:
Tim Peters33dc0a12001-07-27 08:09:54 +0000168 path += b
169 else:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000170 path += sep + b
Tim Peters6a3e5f12001-11-05 21:25:02 +0000171 else:
172 # path is not empty and does not end with a backslash,
173 # but b is empty; since, e.g., split('a/') produces
174 # ('a', ''), it's best if join() adds a backslash in
175 # this case.
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000176 path += sep
Tim Peters1bdd0f22001-07-19 17:18:18 +0000177
Guido van Rossum15e22e11997-12-05 19:03:01 +0000178 return path
Guido van Rossum555915a1994-02-24 11:32:59 +0000179
180
181# Split a path in a drive specification (a drive letter followed by a
Guido van Rossumf3c695c1999-04-06 19:32:19 +0000182# colon) and the path specification.
Guido van Rossum555915a1994-02-24 11:32:59 +0000183# It is always true that drivespec + pathspec == p
184def splitdrive(p):
Mark Hammond5a607a32009-05-06 08:04:54 +0000185 """Split a pathname into drive/UNC sharepoint and relative path specifiers.
186 Returns a 2-tuple (drive_or_unc, path); either part may be empty.
187
188 If you assign
189 result = splitdrive(p)
190 It is always true that:
191 result[0] + result[1] == p
192
193 If the path contained a drive letter, drive_or_unc will contain everything
194 up to and including the colon. e.g. splitdrive("c:/dir") returns ("c:", "/dir")
195
196 If the path contained a UNC path, the drive_or_unc will contain the host name
197 and share up to but not including the fourth directory separator character.
198 e.g. splitdrive("//host/computer/dir") returns ("//host/computer", "/dir")
199
200 Paths cannot contain both a drive letter and a UNC path.
201
202 """
203 empty = _get_empty(p)
204 if len(p) > 1:
205 sep = _get_sep(p)
206 normp = normcase(p)
207 if (normp[0:2] == sep*2) and (normp[2:3] != sep):
208 # is a UNC path:
209 # vvvvvvvvvvvvvvvvvvvv drive letter or UNC path
210 # \\machine\mountpoint\directory\etc\...
211 # directory ^^^^^^^^^^^^^^^
212 index = normp.find(sep, 2)
213 if index == -1:
214 return empty, p
215 index2 = normp.find(sep, index + 1)
216 # a UNC path can't have two slashes in a row
217 # (after the initial two)
218 if index2 == index + 1:
219 return empty, p
220 if index2 == -1:
221 index2 = len(p)
222 return p[:index2], p[index2:]
223 if normp[1:2] == _get_colon(p):
224 return p[:2], p[2:]
225 return empty, p
Guido van Rossumf3c695c1999-04-06 19:32:19 +0000226
227
228# Parse UNC paths
229def splitunc(p):
Mark Hammond5a607a32009-05-06 08:04:54 +0000230 """Deprecated since Python 3.1. Please use splitdrive() instead;
231 it now handles UNC paths.
232
233 Split a pathname into UNC mount point and relative path specifiers.
Guido van Rossumf3c695c1999-04-06 19:32:19 +0000234
235 Return a 2-tuple (unc, rest); either part may be empty.
236 If unc is not empty, it has the form '//host/mount' (or similar
237 using backslashes). unc+rest is always the input path.
238 Paths containing drive letters never have an UNC part.
239 """
Mark Hammond5a607a32009-05-06 08:04:54 +0000240 import warnings
241 warnings.warn("ntpath.splitunc is deprecated, use ntpath.splitdrive instead",
242 PendingDeprecationWarning)
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000243 sep = _get_sep(p)
244 if not p[1:2]:
245 return p[:0], p # Drive letter present
Guido van Rossum534972b1999-02-03 17:20:50 +0000246 firstTwo = p[0:2]
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000247 if normcase(firstTwo) == sep + sep:
Guido van Rossum534972b1999-02-03 17:20:50 +0000248 # is a UNC path:
249 # vvvvvvvvvvvvvvvvvvvv equivalent to drive letter
250 # \\machine\mountpoint\directories...
251 # directory ^^^^^^^^^^^^^^^
252 normp = normcase(p)
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000253 index = normp.find(sep, 2)
Guido van Rossum534972b1999-02-03 17:20:50 +0000254 if index == -1:
255 ##raise RuntimeError, 'illegal UNC path: "' + p + '"'
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000256 return (p[:0], p)
257 index = normp.find(sep, index + 1)
Guido van Rossum534972b1999-02-03 17:20:50 +0000258 if index == -1:
259 index = len(p)
260 return p[:index], p[index:]
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000261 return p[:0], p
Guido van Rossum555915a1994-02-24 11:32:59 +0000262
263
264# Split a path in head (everything up to the last '/') and tail (the
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000265# rest). After the trailing '/' is stripped, the invariant
Guido van Rossum555915a1994-02-24 11:32:59 +0000266# join(head, tail) == p holds.
267# The resulting head won't end in '/' unless it is the root.
268
269def split(p):
Guido van Rossum534972b1999-02-03 17:20:50 +0000270 """Split a pathname.
271
272 Return tuple (head, tail) where tail is everything after the final slash.
273 Either part may be empty."""
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000274
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000275 seps = _get_bothseps(p)
Guido van Rossum15e22e11997-12-05 19:03:01 +0000276 d, p = splitdrive(p)
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000277 # set i to index beyond p's last slash
278 i = len(p)
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000279 while i and p[i-1] not in seps:
Georg Brandl422b5452010-08-01 21:27:48 +0000280 i -= 1
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000281 head, tail = p[:i], p[i:] # now tail has no slashes
282 # remove trailing slashes from head, unless it's all slashes
283 head2 = head
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000284 while head2 and head2[-1:] in seps:
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000285 head2 = head2[:-1]
286 head = head2 or head
Guido van Rossum15e22e11997-12-05 19:03:01 +0000287 return d + head, tail
Guido van Rossum555915a1994-02-24 11:32:59 +0000288
289
290# Split a path in root and extension.
Guido van Rossum73e122f1997-01-22 00:17:26 +0000291# The extension is everything starting at the last dot in the last
Guido van Rossum555915a1994-02-24 11:32:59 +0000292# pathname component; the root is everything before that.
293# It is always true that root + ext == p.
294
295def splitext(p):
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000296 return genericpath._splitext(p, _get_sep(p), _get_altsep(p),
297 _get_dot(p))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000298splitext.__doc__ = genericpath._splitext.__doc__
Guido van Rossum555915a1994-02-24 11:32:59 +0000299
300
301# Return the tail (basename) part of a path.
302
303def basename(p):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000304 """Returns the final component of a pathname"""
305 return split(p)[1]
Guido van Rossum555915a1994-02-24 11:32:59 +0000306
307
308# Return the head (dirname) part of a path.
309
310def dirname(p):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000311 """Returns the directory component of a pathname"""
312 return split(p)[0]
Guido van Rossum555915a1994-02-24 11:32:59 +0000313
Guido van Rossum555915a1994-02-24 11:32:59 +0000314# Is a path a symbolic link?
315# This will always return false on systems where posix.lstat doesn't exist.
316
317def islink(path):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000318 """Test for symbolic link.
319 On WindowsNT/95 and OS/2 always returns false
320 """
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000321 return False
Guido van Rossum555915a1994-02-24 11:32:59 +0000322
Thomas Wouters89f507f2006-12-13 04:49:30 +0000323# alias exists to lexists
Johannes Gijsbersae882f72004-08-30 10:19:56 +0000324lexists = exists
325
Guido van Rossumf3c695c1999-04-06 19:32:19 +0000326# Is a path a mount point? Either a root (with or without drive letter)
327# or an UNC path with at most a / or \ after the mount point.
Guido van Rossum555915a1994-02-24 11:32:59 +0000328
329def ismount(path):
Guido van Rossumca99c2c1998-01-19 22:25:59 +0000330 """Test whether a path is a mount point (defined as root of drive)"""
Benjamin Peterson48e24782009-03-29 13:02:52 +0000331 seps = _get_bothseps(path)
Mark Hammond5a607a32009-05-06 08:04:54 +0000332 root, rest = splitdrive(path)
333 if root and root[0] in seps:
334 return (not rest) or (rest in seps)
335 return rest in seps
Guido van Rossum555915a1994-02-24 11:32:59 +0000336
337
Guido van Rossum555915a1994-02-24 11:32:59 +0000338# Expand paths beginning with '~' or '~user'.
339# '~' means $HOME; '~user' means that user's home directory.
340# If the path doesn't begin with '~', or if the user or $HOME is unknown,
341# the path is returned unchanged (leaving error reporting to whatever
342# function is called with the expanded path as argument).
343# See also module 'glob' for expansion of *, ? and [...] in pathnames.
344# (A function should also be defined to do full *sh-style environment
345# variable expansion.)
346
347def expanduser(path):
Guido van Rossum534972b1999-02-03 17:20:50 +0000348 """Expand ~ and ~user constructs.
349
350 If user or $HOME is unknown, do nothing."""
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000351 if isinstance(path, bytes):
352 tilde = b'~'
353 else:
354 tilde = '~'
355 if not path.startswith(tilde):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000356 return path
357 i, n = 1, len(path)
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000358 while i < n and path[i] not in _get_bothseps(path):
Georg Brandl422b5452010-08-01 21:27:48 +0000359 i += 1
Guido van Rossumd8faa362007-04-27 19:54:29 +0000360
361 if 'HOME' in os.environ:
362 userhome = os.environ['HOME']
363 elif 'USERPROFILE' in os.environ:
364 userhome = os.environ['USERPROFILE']
365 elif not 'HOMEPATH' in os.environ:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000366 return path
Guido van Rossumd8faa362007-04-27 19:54:29 +0000367 else:
368 try:
369 drive = os.environ['HOMEDRIVE']
370 except KeyError:
371 drive = ''
372 userhome = join(drive, os.environ['HOMEPATH'])
373
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000374 if isinstance(path, bytes):
375 userhome = userhome.encode(sys.getfilesystemencoding())
376
Guido van Rossumd8faa362007-04-27 19:54:29 +0000377 if i != 1: #~user
378 userhome = join(dirname(userhome), path[1:i])
379
Guido van Rossum15e22e11997-12-05 19:03:01 +0000380 return userhome + path[i:]
Guido van Rossum555915a1994-02-24 11:32:59 +0000381
382
383# Expand paths containing shell variable substitutions.
384# The following rules apply:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000385# - no expansion within single quotes
Guido van Rossumd8faa362007-04-27 19:54:29 +0000386# - '$$' is translated into '$'
387# - '%%' is translated into '%' if '%%' are not seen in %var1%%var2%
Guido van Rossum15e22e11997-12-05 19:03:01 +0000388# - ${varname} is accepted.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000389# - $varname is accepted.
390# - %varname% is accepted.
391# - varnames can be made out of letters, digits and the characters '_-'
392# (though is not verifed in the ${varname} and %varname% cases)
Guido van Rossum555915a1994-02-24 11:32:59 +0000393# XXX With COMMAND.COM you can use any characters in a variable name,
394# XXX except '^|<>='.
395
Tim Peters2344fae2001-01-15 00:50:52 +0000396def expandvars(path):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000397 """Expand shell variables of the forms $var, ${var} and %var%.
Guido van Rossum534972b1999-02-03 17:20:50 +0000398
399 Unknown variables are left unchanged."""
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000400 if isinstance(path, bytes):
401 if ord('$') not in path and ord('%') not in path:
402 return path
403 import string
404 varchars = bytes(string.ascii_letters + string.digits + '_-', 'ascii')
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000405 quote = b'\''
406 percent = b'%'
407 brace = b'{'
408 dollar = b'$'
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000409 else:
410 if '$' not in path and '%' not in path:
411 return path
412 import string
413 varchars = string.ascii_letters + string.digits + '_-'
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000414 quote = '\''
415 percent = '%'
416 brace = '{'
417 dollar = '$'
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000418 res = path[:0]
Guido van Rossum15e22e11997-12-05 19:03:01 +0000419 index = 0
420 pathlen = len(path)
421 while index < pathlen:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000422 c = path[index:index+1]
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000423 if c == quote: # no expansion within single quotes
Guido van Rossum15e22e11997-12-05 19:03:01 +0000424 path = path[index + 1:]
425 pathlen = len(path)
426 try:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000427 index = path.index(c)
Georg Brandl422b5452010-08-01 21:27:48 +0000428 res += c + path[:index + 1]
Fred Drakeb4e460a2000-09-28 16:25:20 +0000429 except ValueError:
Georg Brandl422b5452010-08-01 21:27:48 +0000430 res += path
Fred Drakeb4e460a2000-09-28 16:25:20 +0000431 index = pathlen - 1
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000432 elif c == percent: # variable or '%'
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000433 if path[index + 1:index + 2] == percent:
Georg Brandl422b5452010-08-01 21:27:48 +0000434 res += c
435 index += 1
Guido van Rossumd8faa362007-04-27 19:54:29 +0000436 else:
437 path = path[index+1:]
438 pathlen = len(path)
439 try:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000440 index = path.index(percent)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000441 except ValueError:
Georg Brandl422b5452010-08-01 21:27:48 +0000442 res += percent + path
Guido van Rossumd8faa362007-04-27 19:54:29 +0000443 index = pathlen - 1
444 else:
445 var = path[:index]
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000446 if isinstance(path, bytes):
447 var = var.decode('ascii')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000448 if var in os.environ:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000449 value = os.environ[var]
Guido van Rossumd8faa362007-04-27 19:54:29 +0000450 else:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000451 value = '%' + var + '%'
452 if isinstance(path, bytes):
453 value = value.encode('ascii')
Georg Brandl422b5452010-08-01 21:27:48 +0000454 res += value
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000455 elif c == dollar: # variable or '$$'
456 if path[index + 1:index + 2] == dollar:
Georg Brandl422b5452010-08-01 21:27:48 +0000457 res += c
458 index += 1
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000459 elif path[index + 1:index + 2] == brace:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000460 path = path[index+2:]
461 pathlen = len(path)
462 try:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000463 if isinstance(path, bytes):
464 index = path.index(b'}')
Thomas Woutersb2137042007-02-01 18:02:27 +0000465 else:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000466 index = path.index('}')
467 var = path[:index]
468 if isinstance(path, bytes):
469 var = var.decode('ascii')
470 if var in os.environ:
471 value = os.environ[var]
472 else:
473 value = '${' + var + '}'
474 if isinstance(path, bytes):
475 value = value.encode('ascii')
Georg Brandl422b5452010-08-01 21:27:48 +0000476 res += value
Fred Drakeb4e460a2000-09-28 16:25:20 +0000477 except ValueError:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000478 if isinstance(path, bytes):
Georg Brandl422b5452010-08-01 21:27:48 +0000479 res += b'${' + path
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000480 else:
Georg Brandl422b5452010-08-01 21:27:48 +0000481 res += '${' + path
Guido van Rossum15e22e11997-12-05 19:03:01 +0000482 index = pathlen - 1
483 else:
484 var = ''
Georg Brandl422b5452010-08-01 21:27:48 +0000485 index += 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000486 c = path[index:index + 1]
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000487 while c and c in varchars:
488 if isinstance(path, bytes):
Georg Brandl422b5452010-08-01 21:27:48 +0000489 var += c.decode('ascii')
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000490 else:
Georg Brandl422b5452010-08-01 21:27:48 +0000491 var += c
492 index += 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000493 c = path[index:index + 1]
Raymond Hettinger54f02222002-06-01 14:18:47 +0000494 if var in os.environ:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000495 value = os.environ[var]
Thomas Woutersb2137042007-02-01 18:02:27 +0000496 else:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000497 value = '$' + var
498 if isinstance(path, bytes):
499 value = value.encode('ascii')
Georg Brandl422b5452010-08-01 21:27:48 +0000500 res += value
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000501 if c:
Georg Brandl422b5452010-08-01 21:27:48 +0000502 index -= 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000503 else:
Georg Brandl422b5452010-08-01 21:27:48 +0000504 res += c
505 index += 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000506 return res
Guido van Rossum555915a1994-02-24 11:32:59 +0000507
508
Tim Peters54a14a32001-08-30 22:05:26 +0000509# 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 +0000510# Previously, this function also truncated pathnames to 8+3 format,
511# but as this module is called "ntpath", that's obviously wrong!
Guido van Rossum555915a1994-02-24 11:32:59 +0000512
513def normpath(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000514 """Normalize path, eliminating double slashes, etc."""
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000515 sep = _get_sep(path)
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000516 dotdot = _get_dot(path) * 2
Georg Brandl611f8f52010-08-01 19:17:57 +0000517 special_prefixes = _get_special(path)
518 if path.startswith(special_prefixes):
519 # in the case of paths with these prefixes:
520 # \\.\ -> device names
521 # \\?\ -> literal paths
522 # do not do any normalization, but return the path unchanged
523 return path
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000524 path = path.replace(_get_altsep(path), sep)
Guido van Rossum15e22e11997-12-05 19:03:01 +0000525 prefix, path = splitdrive(path)
Mark Hammond5a607a32009-05-06 08:04:54 +0000526
527 # collapse initial backslashes
528 if path.startswith(sep):
Georg Brandl422b5452010-08-01 21:27:48 +0000529 prefix += sep
Mark Hammond5a607a32009-05-06 08:04:54 +0000530 path = path.lstrip(sep)
531
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000532 comps = path.split(sep)
Guido van Rossum15e22e11997-12-05 19:03:01 +0000533 i = 0
534 while i < len(comps):
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000535 if not comps[i] or comps[i] == _get_dot(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000536 del comps[i]
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000537 elif comps[i] == dotdot:
538 if i > 0 and comps[i-1] != dotdot:
Tim Peters54a14a32001-08-30 22:05:26 +0000539 del comps[i-1:i+1]
540 i -= 1
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000541 elif i == 0 and prefix.endswith(_get_sep(path)):
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000542 del comps[i]
543 else:
544 i += 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000545 else:
Tim Peters54a14a32001-08-30 22:05:26 +0000546 i += 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000547 # If the path is now empty, substitute '.'
548 if not prefix and not comps:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000549 comps.append(_get_dot(path))
550 return prefix + sep.join(comps)
Guido van Rossume294cf61999-01-29 18:05:18 +0000551
552
553# Return an absolute path.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000554try:
555 from nt import _getfullpathname
Mark Hammondf717f052002-01-17 00:44:26 +0000556
Thomas Wouters477c8d52006-05-27 19:21:47 +0000557except ImportError: # not running on Windows - mock up something sensible
558 def abspath(path):
559 """Return the absolute version of a path."""
560 if not isabs(path):
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000561 if isinstance(path, bytes):
562 cwd = os.getcwdb()
563 else:
564 cwd = os.getcwd()
565 path = join(cwd, path)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000566 return normpath(path)
567
568else: # use native Windows method on Windows
569 def abspath(path):
570 """Return the absolute version of a path."""
571
572 if path: # Empty path must return current working directory.
573 try:
574 path = _getfullpathname(path)
575 except WindowsError:
576 pass # Bad path - return unchanged.
Florent Xicluna9b0e9182010-03-28 11:42:38 +0000577 elif isinstance(path, bytes):
578 path = os.getcwdb()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000579 else:
580 path = os.getcwd()
581 return normpath(path)
Guido van Rossum83eeef42001-09-17 15:16:09 +0000582
583# realpath is a no-op on systems without islink support
584realpath = abspath
Mark Hammond8696ebc2002-10-08 02:44:31 +0000585# Win9x family and earlier have no Unicode filename support.
Tim Peters26bc25a2002-10-09 07:56:04 +0000586supports_unicode_filenames = (hasattr(sys, "getwindowsversion") and
587 sys.getwindowsversion()[3] >= 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000588
589def relpath(path, start=curdir):
590 """Return a relative version of a path"""
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000591 sep = _get_sep(path)
592
593 if start is curdir:
594 start = _get_dot(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000595
596 if not path:
597 raise ValueError("no path specified")
Mark Hammond5a607a32009-05-06 08:04:54 +0000598
599 start_abs = abspath(normpath(start))
600 path_abs = abspath(normpath(path))
601 start_drive, start_rest = splitdrive(start_abs)
602 path_drive, path_rest = splitdrive(path_abs)
Hirokazu Yamamoto089144e2010-10-18 13:49:09 +0000603 if normcase(start_drive) != normcase(path_drive):
Mark Hammond5a607a32009-05-06 08:04:54 +0000604 error = "path is on mount '{0}', start on mount '{1}'".format(
605 path_drive, start_drive)
606 raise ValueError(error)
607
608 start_list = [x for x in start_rest.split(sep) if x]
609 path_list = [x for x in path_rest.split(sep) if x]
Guido van Rossumd8faa362007-04-27 19:54:29 +0000610 # Work out how much of the filepath is shared by start and path.
Mark Hammond5a607a32009-05-06 08:04:54 +0000611 i = 0
612 for e1, e2 in zip(start_list, path_list):
Hirokazu Yamamoto089144e2010-10-18 13:49:09 +0000613 if normcase(e1) != normcase(e2):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000614 break
Guido van Rossumd8faa362007-04-27 19:54:29 +0000615 i += 1
616
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000617 if isinstance(path, bytes):
618 pardir = b'..'
619 else:
620 pardir = '..'
Guido van Rossumd8faa362007-04-27 19:54:29 +0000621 rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
Christian Heimesfaf2f632008-01-06 16:59:19 +0000622 if not rel_list:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000623 return _get_dot(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000624 return join(*rel_list)