blob: 5a012bdfb288e73c40386cab2ace208c279b3a9b [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 Curtin62857742010-09-06 17:07:27 +000020 "samefile", "sameopenfile",]
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'
33elif 'os2' in sys.builtin_module_names:
Andrew MacIntyre437966c2003-02-17 09:17:50 +000034 # OS/2 w/ VACPP
Skip Montanaro117910d2003-02-14 19:35:31 +000035 altsep = '/'
Martin v. Löwisbdec50f2004-06-08 08:29:33 +000036devnull = 'nul'
Skip Montanaro117910d2003-02-14 19:35:31 +000037
Mark Hammond5a607a32009-05-06 08:04:54 +000038def _get_empty(path):
39 if isinstance(path, bytes):
40 return b''
41 else:
42 return ''
43
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +000044def _get_sep(path):
45 if isinstance(path, bytes):
46 return b'\\'
47 else:
48 return '\\'
49
50def _get_altsep(path):
51 if isinstance(path, bytes):
52 return b'/'
53 else:
54 return '/'
55
56def _get_bothseps(path):
57 if isinstance(path, bytes):
58 return b'\\/'
59 else:
60 return '\\/'
61
62def _get_dot(path):
63 if isinstance(path, bytes):
64 return b'.'
65 else:
66 return '.'
67
68def _get_colon(path):
69 if isinstance(path, bytes):
70 return b':'
71 else:
72 return ':'
73
Georg Brandlcfb68212010-07-31 21:40:15 +000074def _get_special(path):
75 if isinstance(path, bytes):
76 return (b'\\\\.\\', b'\\\\?\\')
77 else:
78 return ('\\\\.\\', '\\\\?\\')
79
Guido van Rossume2ad88c1997-08-12 14:46:58 +000080# Normalize the case of a pathname and map slashes to backslashes.
81# Other normalizations (such as optimizing '../' away) are not done
Guido van Rossum555915a1994-02-24 11:32:59 +000082# (this is done by normpath).
Guido van Rossume2ad88c1997-08-12 14:46:58 +000083
Guido van Rossum555915a1994-02-24 11:32:59 +000084def normcase(s):
Guido van Rossum16a0bc21998-02-18 13:48:31 +000085 """Normalize case of pathname.
86
Guido van Rossum534972b1999-02-03 17:20:50 +000087 Makes all characters lowercase and all slashes into backslashes."""
Ezio Melotti5a3ef5b2010-06-25 10:56:11 +000088 if not isinstance(s, (bytes, str)):
89 raise TypeError("normcase() argument must be str or bytes, "
90 "not '{}'".format(s.__class__.__name__))
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +000091 return s.replace(_get_altsep(s), _get_sep(s)).lower()
Guido van Rossum555915a1994-02-24 11:32:59 +000092
Guido van Rossum77e1db31997-06-02 23:11:57 +000093
Fred Drakeef0b5dd2000-02-17 17:30:40 +000094# Return whether a path is absolute.
Mark Hammond5a607a32009-05-06 08:04:54 +000095# Trivial in Posix, harder on Windows.
96# For Windows it is absolute if it starts with a slash or backslash (current
97# volume), or if a pathname after the volume-letter-and-colon or UNC-resource
Guido van Rossum534972b1999-02-03 17:20:50 +000098# starts with a slash or backslash.
Guido van Rossum555915a1994-02-24 11:32:59 +000099
100def isabs(s):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000101 """Test whether a path is absolute"""
102 s = splitdrive(s)[1]
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000103 return len(s) > 0 and s[:1] in _get_bothseps(s)
Guido van Rossum555915a1994-02-24 11:32:59 +0000104
105
Guido van Rossum77e1db31997-06-02 23:11:57 +0000106# Join two (or more) paths.
Serhiy Storchakac369c2c2014-01-27 23:15:14 +0200107def join(path, *paths):
108 sep = _get_sep(path)
109 seps = _get_bothseps(path)
110 colon = _get_colon(path)
111 result_drive, result_path = splitdrive(path)
112 for p in paths:
113 p_drive, p_path = splitdrive(p)
114 if p_path and p_path[0] in seps:
115 # Second path is absolute
116 if p_drive or not result_drive:
117 result_drive = p_drive
118 result_path = p_path
119 continue
120 elif p_drive and p_drive != result_drive:
121 if p_drive.lower() != result_drive.lower():
122 # Different drives => ignore the first path entirely
123 result_drive = p_drive
124 result_path = p_path
125 continue
126 # Same drive in different case
127 result_drive = p_drive
128 # Second path is relative to the first
129 if result_path and result_path[-1] not in seps:
130 result_path = result_path + sep
131 result_path = result_path + p_path
132 ## add separator between UNC and non-absolute path
133 if (result_path and result_path[0] not in seps and
134 result_drive and result_drive[-1:] != colon):
135 return result_drive + sep + result_path
136 return result_drive + result_path
Guido van Rossum555915a1994-02-24 11:32:59 +0000137
138
139# Split a path in a drive specification (a drive letter followed by a
Guido van Rossumf3c695c1999-04-06 19:32:19 +0000140# colon) and the path specification.
Guido van Rossum555915a1994-02-24 11:32:59 +0000141# It is always true that drivespec + pathspec == p
142def splitdrive(p):
Mark Hammond5a607a32009-05-06 08:04:54 +0000143 """Split a pathname into drive/UNC sharepoint and relative path specifiers.
144 Returns a 2-tuple (drive_or_unc, path); either part may be empty.
145
146 If you assign
147 result = splitdrive(p)
148 It is always true that:
149 result[0] + result[1] == p
150
151 If the path contained a drive letter, drive_or_unc will contain everything
152 up to and including the colon. e.g. splitdrive("c:/dir") returns ("c:", "/dir")
153
154 If the path contained a UNC path, the drive_or_unc will contain the host name
155 and share up to but not including the fourth directory separator character.
156 e.g. splitdrive("//host/computer/dir") returns ("//host/computer", "/dir")
157
158 Paths cannot contain both a drive letter and a UNC path.
159
160 """
161 empty = _get_empty(p)
162 if len(p) > 1:
163 sep = _get_sep(p)
Serhiy Storchaka3d7e1152013-12-16 14:34:55 +0200164 normp = p.replace(_get_altsep(p), sep)
Mark Hammond5a607a32009-05-06 08:04:54 +0000165 if (normp[0:2] == sep*2) and (normp[2:3] != sep):
166 # is a UNC path:
167 # vvvvvvvvvvvvvvvvvvvv drive letter or UNC path
168 # \\machine\mountpoint\directory\etc\...
169 # directory ^^^^^^^^^^^^^^^
170 index = normp.find(sep, 2)
171 if index == -1:
172 return empty, p
173 index2 = normp.find(sep, index + 1)
174 # a UNC path can't have two slashes in a row
175 # (after the initial two)
176 if index2 == index + 1:
177 return empty, p
178 if index2 == -1:
179 index2 = len(p)
180 return p[:index2], p[index2:]
181 if normp[1:2] == _get_colon(p):
182 return p[:2], p[2:]
183 return empty, p
Guido van Rossumf3c695c1999-04-06 19:32:19 +0000184
185
186# Parse UNC paths
187def splitunc(p):
Mark Hammond5a607a32009-05-06 08:04:54 +0000188 """Deprecated since Python 3.1. Please use splitdrive() instead;
189 it now handles UNC paths.
190
191 Split a pathname into UNC mount point and relative path specifiers.
Guido van Rossumf3c695c1999-04-06 19:32:19 +0000192
193 Return a 2-tuple (unc, rest); either part may be empty.
194 If unc is not empty, it has the form '//host/mount' (or similar
195 using backslashes). unc+rest is always the input path.
196 Paths containing drive letters never have an UNC part.
197 """
Mark Hammond5a607a32009-05-06 08:04:54 +0000198 import warnings
199 warnings.warn("ntpath.splitunc is deprecated, use ntpath.splitdrive instead",
Serhiy Storchaka593568b2013-12-16 15:13:28 +0200200 DeprecationWarning, 2)
201 drive, path = splitdrive(p)
202 if len(drive) == 2:
203 # Drive letter present
204 return p[:0], p
205 return drive, path
Guido van Rossum555915a1994-02-24 11:32:59 +0000206
207
208# Split a path in head (everything up to the last '/') and tail (the
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000209# rest). After the trailing '/' is stripped, the invariant
Guido van Rossum555915a1994-02-24 11:32:59 +0000210# join(head, tail) == p holds.
211# The resulting head won't end in '/' unless it is the root.
212
213def split(p):
Guido van Rossum534972b1999-02-03 17:20:50 +0000214 """Split a pathname.
215
216 Return tuple (head, tail) where tail is everything after the final slash.
217 Either part may be empty."""
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000218
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000219 seps = _get_bothseps(p)
Guido van Rossum15e22e11997-12-05 19:03:01 +0000220 d, p = splitdrive(p)
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000221 # set i to index beyond p's last slash
222 i = len(p)
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000223 while i and p[i-1] not in seps:
Georg Brandl599b65d2010-07-23 08:46:35 +0000224 i -= 1
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000225 head, tail = p[:i], p[i:] # now tail has no slashes
226 # remove trailing slashes from head, unless it's all slashes
227 head2 = head
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000228 while head2 and head2[-1:] in seps:
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000229 head2 = head2[:-1]
230 head = head2 or head
Guido van Rossum15e22e11997-12-05 19:03:01 +0000231 return d + head, tail
Guido van Rossum555915a1994-02-24 11:32:59 +0000232
233
234# Split a path in root and extension.
Guido van Rossum73e122f1997-01-22 00:17:26 +0000235# The extension is everything starting at the last dot in the last
Guido van Rossum555915a1994-02-24 11:32:59 +0000236# pathname component; the root is everything before that.
237# It is always true that root + ext == p.
238
239def splitext(p):
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000240 return genericpath._splitext(p, _get_sep(p), _get_altsep(p),
241 _get_dot(p))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000242splitext.__doc__ = genericpath._splitext.__doc__
Guido van Rossum555915a1994-02-24 11:32:59 +0000243
244
245# Return the tail (basename) part of a path.
246
247def basename(p):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000248 """Returns the final component of a pathname"""
249 return split(p)[1]
Guido van Rossum555915a1994-02-24 11:32:59 +0000250
251
252# Return the head (dirname) part of a path.
253
254def dirname(p):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000255 """Returns the directory component of a pathname"""
256 return split(p)[0]
Guido van Rossum555915a1994-02-24 11:32:59 +0000257
Guido van Rossum555915a1994-02-24 11:32:59 +0000258# Is a path a symbolic link?
Brian Curtind40e6f72010-07-08 21:39:08 +0000259# This will always return false on systems where os.lstat doesn't exist.
Guido van Rossum555915a1994-02-24 11:32:59 +0000260
261def islink(path):
Brian Curtind40e6f72010-07-08 21:39:08 +0000262 """Test whether a path is a symbolic link.
263 This will always return false for Windows prior to 6.0
264 and for OS/2.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000265 """
Brian Curtind40e6f72010-07-08 21:39:08 +0000266 try:
267 st = os.lstat(path)
268 except (os.error, AttributeError):
269 return False
270 return stat.S_ISLNK(st.st_mode)
Guido van Rossum555915a1994-02-24 11:32:59 +0000271
Brian Curtind40e6f72010-07-08 21:39:08 +0000272# Being true for dangling symbolic links is also useful.
273
274def lexists(path):
275 """Test whether a path exists. Returns True for broken symbolic links"""
276 try:
277 st = os.lstat(path)
278 except (os.error, WindowsError):
279 return False
280 return True
Johannes Gijsbersae882f72004-08-30 10:19:56 +0000281
Guido van Rossumf3c695c1999-04-06 19:32:19 +0000282# Is a path a mount point? Either a root (with or without drive letter)
283# or an UNC path with at most a / or \ after the mount point.
Guido van Rossum555915a1994-02-24 11:32:59 +0000284
285def ismount(path):
Guido van Rossumca99c2c1998-01-19 22:25:59 +0000286 """Test whether a path is a mount point (defined as root of drive)"""
Benjamin Peterson48e24782009-03-29 13:02:52 +0000287 seps = _get_bothseps(path)
Mark Hammond5a607a32009-05-06 08:04:54 +0000288 root, rest = splitdrive(path)
289 if root and root[0] in seps:
290 return (not rest) or (rest in seps)
291 return rest in seps
Guido van Rossum555915a1994-02-24 11:32:59 +0000292
293
Guido van Rossum555915a1994-02-24 11:32:59 +0000294# Expand paths beginning with '~' or '~user'.
295# '~' means $HOME; '~user' means that user's home directory.
296# If the path doesn't begin with '~', or if the user or $HOME is unknown,
297# the path is returned unchanged (leaving error reporting to whatever
298# function is called with the expanded path as argument).
299# See also module 'glob' for expansion of *, ? and [...] in pathnames.
300# (A function should also be defined to do full *sh-style environment
301# variable expansion.)
302
303def expanduser(path):
Guido van Rossum534972b1999-02-03 17:20:50 +0000304 """Expand ~ and ~user constructs.
305
306 If user or $HOME is unknown, do nothing."""
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000307 if isinstance(path, bytes):
308 tilde = b'~'
309 else:
310 tilde = '~'
311 if not path.startswith(tilde):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000312 return path
313 i, n = 1, len(path)
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000314 while i < n and path[i] not in _get_bothseps(path):
Georg Brandl599b65d2010-07-23 08:46:35 +0000315 i += 1
Guido van Rossumd8faa362007-04-27 19:54:29 +0000316
317 if 'HOME' in os.environ:
318 userhome = os.environ['HOME']
319 elif 'USERPROFILE' in os.environ:
320 userhome = os.environ['USERPROFILE']
321 elif not 'HOMEPATH' in os.environ:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000322 return path
Guido van Rossumd8faa362007-04-27 19:54:29 +0000323 else:
324 try:
325 drive = os.environ['HOMEDRIVE']
326 except KeyError:
327 drive = ''
328 userhome = join(drive, os.environ['HOMEPATH'])
329
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000330 if isinstance(path, bytes):
331 userhome = userhome.encode(sys.getfilesystemencoding())
332
Guido van Rossumd8faa362007-04-27 19:54:29 +0000333 if i != 1: #~user
334 userhome = join(dirname(userhome), path[1:i])
335
Guido van Rossum15e22e11997-12-05 19:03:01 +0000336 return userhome + path[i:]
Guido van Rossum555915a1994-02-24 11:32:59 +0000337
338
339# Expand paths containing shell variable substitutions.
340# The following rules apply:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000341# - no expansion within single quotes
Guido van Rossumd8faa362007-04-27 19:54:29 +0000342# - '$$' is translated into '$'
343# - '%%' is translated into '%' if '%%' are not seen in %var1%%var2%
Guido van Rossum15e22e11997-12-05 19:03:01 +0000344# - ${varname} is accepted.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000345# - $varname is accepted.
346# - %varname% is accepted.
347# - varnames can be made out of letters, digits and the characters '_-'
Ezio Melotti13925002011-03-16 11:05:33 +0200348# (though is not verified in the ${varname} and %varname% cases)
Guido van Rossum555915a1994-02-24 11:32:59 +0000349# XXX With COMMAND.COM you can use any characters in a variable name,
350# XXX except '^|<>='.
351
Tim Peters2344fae2001-01-15 00:50:52 +0000352def expandvars(path):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000353 """Expand shell variables of the forms $var, ${var} and %var%.
Guido van Rossum534972b1999-02-03 17:20:50 +0000354
355 Unknown variables are left unchanged."""
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000356 if isinstance(path, bytes):
357 if ord('$') not in path and ord('%') not in path:
358 return path
359 import string
360 varchars = bytes(string.ascii_letters + string.digits + '_-', 'ascii')
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000361 quote = b'\''
362 percent = b'%'
363 brace = b'{'
364 dollar = b'$'
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000365 else:
366 if '$' not in path and '%' not in path:
367 return path
368 import string
369 varchars = string.ascii_letters + string.digits + '_-'
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000370 quote = '\''
371 percent = '%'
372 brace = '{'
373 dollar = '$'
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000374 res = path[:0]
Guido van Rossum15e22e11997-12-05 19:03:01 +0000375 index = 0
376 pathlen = len(path)
377 while index < pathlen:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000378 c = path[index:index+1]
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000379 if c == quote: # no expansion within single quotes
Guido van Rossum15e22e11997-12-05 19:03:01 +0000380 path = path[index + 1:]
381 pathlen = len(path)
382 try:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000383 index = path.index(c)
Georg Brandl599b65d2010-07-23 08:46:35 +0000384 res += c + path[:index + 1]
Fred Drakeb4e460a2000-09-28 16:25:20 +0000385 except ValueError:
Georg Brandl599b65d2010-07-23 08:46:35 +0000386 res += path
Fred Drakeb4e460a2000-09-28 16:25:20 +0000387 index = pathlen - 1
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000388 elif c == percent: # variable or '%'
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000389 if path[index + 1:index + 2] == percent:
Georg Brandl599b65d2010-07-23 08:46:35 +0000390 res += c
391 index += 1
Guido van Rossumd8faa362007-04-27 19:54:29 +0000392 else:
393 path = path[index+1:]
394 pathlen = len(path)
395 try:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000396 index = path.index(percent)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000397 except ValueError:
Georg Brandl599b65d2010-07-23 08:46:35 +0000398 res += percent + path
Guido van Rossumd8faa362007-04-27 19:54:29 +0000399 index = pathlen - 1
400 else:
401 var = path[:index]
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000402 if isinstance(path, bytes):
403 var = var.decode('ascii')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000404 if var in os.environ:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000405 value = os.environ[var]
Guido van Rossumd8faa362007-04-27 19:54:29 +0000406 else:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000407 value = '%' + var + '%'
408 if isinstance(path, bytes):
409 value = value.encode('ascii')
Georg Brandl599b65d2010-07-23 08:46:35 +0000410 res += value
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000411 elif c == dollar: # variable or '$$'
412 if path[index + 1:index + 2] == dollar:
Georg Brandl599b65d2010-07-23 08:46:35 +0000413 res += c
414 index += 1
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000415 elif path[index + 1:index + 2] == brace:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000416 path = path[index+2:]
417 pathlen = len(path)
418 try:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000419 if isinstance(path, bytes):
420 index = path.index(b'}')
Thomas Woutersb2137042007-02-01 18:02:27 +0000421 else:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000422 index = path.index('}')
423 var = path[:index]
424 if isinstance(path, bytes):
425 var = var.decode('ascii')
426 if var in os.environ:
427 value = os.environ[var]
428 else:
429 value = '${' + var + '}'
430 if isinstance(path, bytes):
431 value = value.encode('ascii')
Georg Brandl599b65d2010-07-23 08:46:35 +0000432 res += value
Fred Drakeb4e460a2000-09-28 16:25:20 +0000433 except ValueError:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000434 if isinstance(path, bytes):
Georg Brandl599b65d2010-07-23 08:46:35 +0000435 res += b'${' + path
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000436 else:
Georg Brandl599b65d2010-07-23 08:46:35 +0000437 res += '${' + path
Guido van Rossum15e22e11997-12-05 19:03:01 +0000438 index = pathlen - 1
439 else:
440 var = ''
Georg Brandl599b65d2010-07-23 08:46:35 +0000441 index += 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000442 c = path[index:index + 1]
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000443 while c and c in varchars:
444 if isinstance(path, bytes):
Georg Brandl599b65d2010-07-23 08:46:35 +0000445 var += c.decode('ascii')
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000446 else:
Georg Brandl599b65d2010-07-23 08:46:35 +0000447 var += c
448 index += 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000449 c = path[index:index + 1]
Raymond Hettinger54f02222002-06-01 14:18:47 +0000450 if var in os.environ:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000451 value = os.environ[var]
Thomas Woutersb2137042007-02-01 18:02:27 +0000452 else:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000453 value = '$' + var
454 if isinstance(path, bytes):
455 value = value.encode('ascii')
Georg Brandl599b65d2010-07-23 08:46:35 +0000456 res += value
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000457 if c:
Georg Brandl599b65d2010-07-23 08:46:35 +0000458 index -= 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000459 else:
Georg Brandl599b65d2010-07-23 08:46:35 +0000460 res += c
461 index += 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000462 return res
Guido van Rossum555915a1994-02-24 11:32:59 +0000463
464
Tim Peters54a14a32001-08-30 22:05:26 +0000465# 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 +0000466# Previously, this function also truncated pathnames to 8+3 format,
467# but as this module is called "ntpath", that's obviously wrong!
Guido van Rossum555915a1994-02-24 11:32:59 +0000468
469def normpath(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000470 """Normalize path, eliminating double slashes, etc."""
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000471 sep = _get_sep(path)
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000472 dotdot = _get_dot(path) * 2
Georg Brandlcfb68212010-07-31 21:40:15 +0000473 special_prefixes = _get_special(path)
474 if path.startswith(special_prefixes):
475 # in the case of paths with these prefixes:
476 # \\.\ -> device names
477 # \\?\ -> literal paths
478 # do not do any normalization, but return the path unchanged
479 return path
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000480 path = path.replace(_get_altsep(path), sep)
Guido van Rossum15e22e11997-12-05 19:03:01 +0000481 prefix, path = splitdrive(path)
Mark Hammond5a607a32009-05-06 08:04:54 +0000482
483 # collapse initial backslashes
484 if path.startswith(sep):
Georg Brandl599b65d2010-07-23 08:46:35 +0000485 prefix += sep
Mark Hammond5a607a32009-05-06 08:04:54 +0000486 path = path.lstrip(sep)
487
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000488 comps = path.split(sep)
Guido van Rossum15e22e11997-12-05 19:03:01 +0000489 i = 0
490 while i < len(comps):
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000491 if not comps[i] or comps[i] == _get_dot(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000492 del comps[i]
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000493 elif comps[i] == dotdot:
494 if i > 0 and comps[i-1] != dotdot:
Tim Peters54a14a32001-08-30 22:05:26 +0000495 del comps[i-1:i+1]
496 i -= 1
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000497 elif i == 0 and prefix.endswith(_get_sep(path)):
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000498 del comps[i]
499 else:
500 i += 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000501 else:
Tim Peters54a14a32001-08-30 22:05:26 +0000502 i += 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000503 # If the path is now empty, substitute '.'
504 if not prefix and not comps:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000505 comps.append(_get_dot(path))
506 return prefix + sep.join(comps)
Guido van Rossume294cf61999-01-29 18:05:18 +0000507
508
509# Return an absolute path.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000510try:
511 from nt import _getfullpathname
Mark Hammondf717f052002-01-17 00:44:26 +0000512
Thomas Wouters477c8d52006-05-27 19:21:47 +0000513except ImportError: # not running on Windows - mock up something sensible
514 def abspath(path):
515 """Return the absolute version of a path."""
516 if not isabs(path):
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000517 if isinstance(path, bytes):
518 cwd = os.getcwdb()
519 else:
520 cwd = os.getcwd()
521 path = join(cwd, path)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000522 return normpath(path)
523
524else: # use native Windows method on Windows
525 def abspath(path):
526 """Return the absolute version of a path."""
527
528 if path: # Empty path must return current working directory.
529 try:
530 path = _getfullpathname(path)
531 except WindowsError:
532 pass # Bad path - return unchanged.
Florent Xiclunaad8c5ca2010-03-08 14:44:41 +0000533 elif isinstance(path, bytes):
534 path = os.getcwdb()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000535 else:
536 path = os.getcwd()
537 return normpath(path)
Guido van Rossum83eeef42001-09-17 15:16:09 +0000538
539# realpath is a no-op on systems without islink support
540realpath = abspath
Mark Hammond8696ebc2002-10-08 02:44:31 +0000541# Win9x family and earlier have no Unicode filename support.
Tim Peters26bc25a2002-10-09 07:56:04 +0000542supports_unicode_filenames = (hasattr(sys, "getwindowsversion") and
543 sys.getwindowsversion()[3] >= 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000544
545def relpath(path, start=curdir):
546 """Return a relative version of a path"""
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000547 sep = _get_sep(path)
548
549 if start is curdir:
550 start = _get_dot(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000551
552 if not path:
553 raise ValueError("no path specified")
Mark Hammond5a607a32009-05-06 08:04:54 +0000554
555 start_abs = abspath(normpath(start))
556 path_abs = abspath(normpath(path))
557 start_drive, start_rest = splitdrive(start_abs)
558 path_drive, path_rest = splitdrive(path_abs)
Hirokazu Yamamotob08820a2010-10-18 12:13:18 +0000559 if normcase(start_drive) != normcase(path_drive):
Mark Hammond5a607a32009-05-06 08:04:54 +0000560 error = "path is on mount '{0}', start on mount '{1}'".format(
561 path_drive, start_drive)
562 raise ValueError(error)
563
564 start_list = [x for x in start_rest.split(sep) if x]
565 path_list = [x for x in path_rest.split(sep) if x]
Guido van Rossumd8faa362007-04-27 19:54:29 +0000566 # Work out how much of the filepath is shared by start and path.
Mark Hammond5a607a32009-05-06 08:04:54 +0000567 i = 0
568 for e1, e2 in zip(start_list, path_list):
Hirokazu Yamamotob08820a2010-10-18 12:13:18 +0000569 if normcase(e1) != normcase(e2):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000570 break
Guido van Rossumd8faa362007-04-27 19:54:29 +0000571 i += 1
572
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000573 if isinstance(path, bytes):
574 pardir = b'..'
575 else:
576 pardir = '..'
Guido van Rossumd8faa362007-04-27 19:54:29 +0000577 rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
Christian Heimesfaf2f632008-01-06 16:59:19 +0000578 if not rel_list:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000579 return _get_dot(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000580 return join(*rel_list)
Brian Curtind40e6f72010-07-08 21:39:08 +0000581
582
583# determine if two files are in fact the same file
Brian Curtin0dac8082010-09-23 20:38:14 +0000584try:
Brian Curtine8e80422010-09-24 13:56:34 +0000585 # GetFinalPathNameByHandle is available starting with Windows 6.0.
586 # Windows XP and non-Windows OS'es will mock _getfinalpathname.
587 if sys.getwindowsversion()[:2] >= (6, 0):
588 from nt import _getfinalpathname
589 else:
590 raise ImportError
591except (AttributeError, ImportError):
Brian Curtin0dac8082010-09-23 20:38:14 +0000592 # On Windows XP and earlier, two files are the same if their absolute
593 # pathnames are the same.
Brian Curtine8e80422010-09-24 13:56:34 +0000594 # Non-Windows operating systems fake this method with an XP
595 # approximation.
Brian Curtin0dac8082010-09-23 20:38:14 +0000596 def _getfinalpathname(f):
Ronald Oussoren6355c162011-05-06 17:11:07 +0200597 return normcase(abspath(f))
Brian Curtin0dac8082010-09-23 20:38:14 +0000598
Brian Curtind40e6f72010-07-08 21:39:08 +0000599def samefile(f1, f2):
600 "Test whether two pathnames reference the same actual file"
Brian Curtin0dac8082010-09-23 20:38:14 +0000601 return _getfinalpathname(f1) == _getfinalpathname(f2)
602
603
604try:
605 from nt import _getfileinformation
606except ImportError:
607 # On other operating systems, just return the fd and see that
608 # it compares equal in sameopenfile.
609 def _getfileinformation(fd):
610 return fd
Brian Curtin62857742010-09-06 17:07:27 +0000611
612def sameopenfile(f1, f2):
613 """Test whether two file objects reference the same file"""
Brian Curtin0dac8082010-09-23 20:38:14 +0000614 return _getfileinformation(f1) == _getfileinformation(f2)
Brian Curtin9c669cc2011-06-08 18:17:18 -0500615
616
617try:
618 # The genericpath.isdir implementation uses os.stat and checks the mode
619 # attribute to tell whether or not the path is a directory.
620 # This is overkill on Windows - just pass the path to GetFileAttributes
621 # and check the attribute from there.
Brian Curtin95d028f2011-06-09 09:10:38 -0500622 from nt import _isdir as isdir
Brian Curtin9c669cc2011-06-08 18:17:18 -0500623except ImportError:
Brian Curtin95d028f2011-06-09 09:10:38 -0500624 # Use genericpath.isdir as imported above.
625 pass