blob: eae3cf3098a4eeca01311f6b779bd3c08baf246a [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 *
Brian Curtin62857742010-09-06 17:07:27 +000013from nt import _getfileinformation
Skip Montanaro4d5d5bf2000-07-13 01:01:03 +000014
Skip Montanaro269b83b2001-02-06 01:07:02 +000015__all__ = ["normcase","isabs","join","splitdrive","split","splitext",
16 "basename","dirname","commonprefix","getsize","getmtime",
Georg Brandlf0de6a12005-08-22 18:02:59 +000017 "getatime","getctime", "islink","exists","lexists","isdir","isfile",
Benjamin Petersond71ca412008-05-08 23:44:58 +000018 "ismount", "expanduser","expandvars","normpath","abspath",
Georg Brandlf0de6a12005-08-22 18:02:59 +000019 "splitunc","curdir","pardir","sep","pathsep","defpath","altsep",
Brian Curtind40e6f72010-07-08 21:39:08 +000020 "extsep","devnull","realpath","supports_unicode_filenames","relpath",
Brian Curtin62857742010-09-06 17:07:27 +000021 "samefile", "sameopenfile",]
Guido van Rossum555915a1994-02-24 11:32:59 +000022
Skip Montanaro117910d2003-02-14 19:35:31 +000023# strings representing various path-related bits and pieces
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +000024# These are primarily for export; internally, they are hardcoded.
Skip Montanaro117910d2003-02-14 19:35:31 +000025curdir = '.'
26pardir = '..'
27extsep = '.'
28sep = '\\'
29pathsep = ';'
Skip Montanaro9ddac3e2003-03-28 22:23:24 +000030altsep = '/'
Andrew MacIntyre437966c2003-02-17 09:17:50 +000031defpath = '.;C:\\bin'
Skip Montanaro117910d2003-02-14 19:35:31 +000032if 'ce' in sys.builtin_module_names:
33 defpath = '\\Windows'
34elif 'os2' in sys.builtin_module_names:
Andrew MacIntyre437966c2003-02-17 09:17:50 +000035 # OS/2 w/ VACPP
Skip Montanaro117910d2003-02-14 19:35:31 +000036 altsep = '/'
Martin v. Löwisbdec50f2004-06-08 08:29:33 +000037devnull = 'nul'
Skip Montanaro117910d2003-02-14 19:35:31 +000038
Mark Hammond5a607a32009-05-06 08:04:54 +000039def _get_empty(path):
40 if isinstance(path, bytes):
41 return b''
42 else:
43 return ''
44
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +000045def _get_sep(path):
46 if isinstance(path, bytes):
47 return b'\\'
48 else:
49 return '\\'
50
51def _get_altsep(path):
52 if isinstance(path, bytes):
53 return b'/'
54 else:
55 return '/'
56
57def _get_bothseps(path):
58 if isinstance(path, bytes):
59 return b'\\/'
60 else:
61 return '\\/'
62
63def _get_dot(path):
64 if isinstance(path, bytes):
65 return b'.'
66 else:
67 return '.'
68
69def _get_colon(path):
70 if isinstance(path, bytes):
71 return b':'
72 else:
73 return ':'
74
Georg Brandlcfb68212010-07-31 21:40:15 +000075def _get_special(path):
76 if isinstance(path, bytes):
77 return (b'\\\\.\\', b'\\\\?\\')
78 else:
79 return ('\\\\.\\', '\\\\?\\')
80
Guido van Rossume2ad88c1997-08-12 14:46:58 +000081# Normalize the case of a pathname and map slashes to backslashes.
82# Other normalizations (such as optimizing '../' away) are not done
Guido van Rossum555915a1994-02-24 11:32:59 +000083# (this is done by normpath).
Guido van Rossume2ad88c1997-08-12 14:46:58 +000084
Guido van Rossum555915a1994-02-24 11:32:59 +000085def normcase(s):
Guido van Rossum16a0bc21998-02-18 13:48:31 +000086 """Normalize case of pathname.
87
Guido van Rossum534972b1999-02-03 17:20:50 +000088 Makes all characters lowercase and all slashes into backslashes."""
Ezio Melotti5a3ef5b2010-06-25 10:56:11 +000089 if not isinstance(s, (bytes, str)):
90 raise TypeError("normcase() argument must be str or bytes, "
91 "not '{}'".format(s.__class__.__name__))
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +000092 return s.replace(_get_altsep(s), _get_sep(s)).lower()
Guido van Rossum555915a1994-02-24 11:32:59 +000093
Guido van Rossum77e1db31997-06-02 23:11:57 +000094
Fred Drakeef0b5dd2000-02-17 17:30:40 +000095# Return whether a path is absolute.
Mark Hammond5a607a32009-05-06 08:04:54 +000096# Trivial in Posix, harder on Windows.
97# For Windows it is absolute if it starts with a slash or backslash (current
98# volume), or if a pathname after the volume-letter-and-colon or UNC-resource
Guido van Rossum534972b1999-02-03 17:20:50 +000099# starts with a slash or backslash.
Guido van Rossum555915a1994-02-24 11:32:59 +0000100
101def isabs(s):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000102 """Test whether a path is absolute"""
103 s = splitdrive(s)[1]
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000104 return len(s) > 0 and s[:1] in _get_bothseps(s)
Guido van Rossum555915a1994-02-24 11:32:59 +0000105
106
Guido van Rossum77e1db31997-06-02 23:11:57 +0000107# Join two (or more) paths.
108
Barry Warsaw384d2491997-02-18 21:53:25 +0000109def join(a, *p):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000110 """Join two or more pathname components, inserting "\\" as needed.
111 If any component is an absolute path, all previous path components
112 will be discarded."""
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000113 sep = _get_sep(a)
114 seps = _get_bothseps(a)
115 colon = _get_colon(a)
Guido van Rossum15e22e11997-12-05 19:03:01 +0000116 path = a
117 for b in p:
Tim Peters33dc0a12001-07-27 08:09:54 +0000118 b_wins = 0 # set to 1 iff b makes path irrelevant
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000119 if not path:
Tim Peters33dc0a12001-07-27 08:09:54 +0000120 b_wins = 1
Tim Peters1bdd0f22001-07-19 17:18:18 +0000121
Tim Peters33dc0a12001-07-27 08:09:54 +0000122 elif isabs(b):
123 # This probably wipes out path so far. However, it's more
Mark Hammond5a607a32009-05-06 08:04:54 +0000124 # complicated if path begins with a drive letter. You get a+b
125 # (minus redundant slashes) in these four cases:
Tim Peters33dc0a12001-07-27 08:09:54 +0000126 # 1. join('c:', '/a') == 'c:/a'
Mark Hammond5a607a32009-05-06 08:04:54 +0000127 # 2. join('//computer/share', '/a') == '//computer/share/a'
128 # 3. join('c:/', '/a') == 'c:/a'
129 # 4. join('//computer/share/', '/a') == '//computer/share/a'
130 # But b wins in all of these cases:
131 # 5. join('c:/a', '/b') == '/b'
132 # 6. join('//computer/share/a', '/b') == '/b'
133 # 7. join('c:', 'd:/') == 'd:/'
134 # 8. join('c:', '//computer/share/') == '//computer/share/'
135 # 9. join('//computer/share', 'd:/') == 'd:/'
136 # 10. join('//computer/share', '//computer/share/') == '//computer/share/'
137 # 11. join('c:/', 'd:/') == 'd:/'
138 # 12. join('c:/', '//computer/share/') == '//computer/share/'
139 # 13. join('//computer/share/', 'd:/') == 'd:/'
140 # 14. join('//computer/share/', '//computer/share/') == '//computer/share/'
141 b_prefix, b_rest = splitdrive(b)
Tim Peters1bdd0f22001-07-19 17:18:18 +0000142
Mark Hammond5a607a32009-05-06 08:04:54 +0000143 # if b has a prefix, it always wins.
144 if b_prefix:
Tim Peters33dc0a12001-07-27 08:09:54 +0000145 b_wins = 1
Mark Hammond5a607a32009-05-06 08:04:54 +0000146 else:
147 # b doesn't have a prefix.
148 # but isabs(b) returned true.
149 # and therefore b_rest[0] must be a slash.
150 # (but let's check that.)
151 assert(b_rest and b_rest[0] in seps)
152
153 # so, b still wins if path has a rest that's more than a sep.
154 # you get a+b if path_rest is empty or only has a sep.
155 # (see cases 1-4 for times when b loses.)
156 path_rest = splitdrive(path)[1]
157 b_wins = path_rest and path_rest not in seps
Tim Peters1bdd0f22001-07-19 17:18:18 +0000158
Tim Peters33dc0a12001-07-27 08:09:54 +0000159 if b_wins:
160 path = b
161 else:
162 # Join, and ensure there's a separator.
163 assert len(path) > 0
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000164 if path[-1:] in seps:
165 if b and b[:1] in seps:
Tim Peters33dc0a12001-07-27 08:09:54 +0000166 path += b[1:]
167 else:
168 path += b
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000169 elif path[-1:] == colon:
Tim Peters33dc0a12001-07-27 08:09:54 +0000170 path += b
171 elif b:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000172 if b[:1] in seps:
Tim Peters33dc0a12001-07-27 08:09:54 +0000173 path += b
174 else:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000175 path += sep + b
Tim Peters6a3e5f12001-11-05 21:25:02 +0000176 else:
177 # path is not empty and does not end with a backslash,
178 # but b is empty; since, e.g., split('a/') produces
179 # ('a', ''), it's best if join() adds a backslash in
180 # this case.
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000181 path += sep
Tim Peters1bdd0f22001-07-19 17:18:18 +0000182
Guido van Rossum15e22e11997-12-05 19:03:01 +0000183 return path
Guido van Rossum555915a1994-02-24 11:32:59 +0000184
185
186# Split a path in a drive specification (a drive letter followed by a
Guido van Rossumf3c695c1999-04-06 19:32:19 +0000187# colon) and the path specification.
Guido van Rossum555915a1994-02-24 11:32:59 +0000188# It is always true that drivespec + pathspec == p
189def splitdrive(p):
Mark Hammond5a607a32009-05-06 08:04:54 +0000190 """Split a pathname into drive/UNC sharepoint and relative path specifiers.
191 Returns a 2-tuple (drive_or_unc, path); either part may be empty.
192
193 If you assign
194 result = splitdrive(p)
195 It is always true that:
196 result[0] + result[1] == p
197
198 If the path contained a drive letter, drive_or_unc will contain everything
199 up to and including the colon. e.g. splitdrive("c:/dir") returns ("c:", "/dir")
200
201 If the path contained a UNC path, the drive_or_unc will contain the host name
202 and share up to but not including the fourth directory separator character.
203 e.g. splitdrive("//host/computer/dir") returns ("//host/computer", "/dir")
204
205 Paths cannot contain both a drive letter and a UNC path.
206
207 """
208 empty = _get_empty(p)
209 if len(p) > 1:
210 sep = _get_sep(p)
211 normp = normcase(p)
212 if (normp[0:2] == sep*2) and (normp[2:3] != sep):
213 # is a UNC path:
214 # vvvvvvvvvvvvvvvvvvvv drive letter or UNC path
215 # \\machine\mountpoint\directory\etc\...
216 # directory ^^^^^^^^^^^^^^^
217 index = normp.find(sep, 2)
218 if index == -1:
219 return empty, p
220 index2 = normp.find(sep, index + 1)
221 # a UNC path can't have two slashes in a row
222 # (after the initial two)
223 if index2 == index + 1:
224 return empty, p
225 if index2 == -1:
226 index2 = len(p)
227 return p[:index2], p[index2:]
228 if normp[1:2] == _get_colon(p):
229 return p[:2], p[2:]
230 return empty, p
Guido van Rossumf3c695c1999-04-06 19:32:19 +0000231
232
233# Parse UNC paths
234def splitunc(p):
Mark Hammond5a607a32009-05-06 08:04:54 +0000235 """Deprecated since Python 3.1. Please use splitdrive() instead;
236 it now handles UNC paths.
237
238 Split a pathname into UNC mount point and relative path specifiers.
Guido van Rossumf3c695c1999-04-06 19:32:19 +0000239
240 Return a 2-tuple (unc, rest); either part may be empty.
241 If unc is not empty, it has the form '//host/mount' (or similar
242 using backslashes). unc+rest is always the input path.
243 Paths containing drive letters never have an UNC part.
244 """
Mark Hammond5a607a32009-05-06 08:04:54 +0000245 import warnings
246 warnings.warn("ntpath.splitunc is deprecated, use ntpath.splitdrive instead",
Gregory P. Smithaa3b5b82009-06-30 05:33:50 +0000247 DeprecationWarning)
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000248 sep = _get_sep(p)
249 if not p[1:2]:
250 return p[:0], p # Drive letter present
Guido van Rossum534972b1999-02-03 17:20:50 +0000251 firstTwo = p[0:2]
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000252 if normcase(firstTwo) == sep + sep:
Guido van Rossum534972b1999-02-03 17:20:50 +0000253 # is a UNC path:
254 # vvvvvvvvvvvvvvvvvvvv equivalent to drive letter
255 # \\machine\mountpoint\directories...
256 # directory ^^^^^^^^^^^^^^^
257 normp = normcase(p)
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000258 index = normp.find(sep, 2)
Guido van Rossum534972b1999-02-03 17:20:50 +0000259 if index == -1:
260 ##raise RuntimeError, 'illegal UNC path: "' + p + '"'
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000261 return (p[:0], p)
262 index = normp.find(sep, index + 1)
Guido van Rossum534972b1999-02-03 17:20:50 +0000263 if index == -1:
264 index = len(p)
265 return p[:index], p[index:]
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000266 return p[:0], p
Guido van Rossum555915a1994-02-24 11:32:59 +0000267
268
269# Split a path in head (everything up to the last '/') and tail (the
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000270# rest). After the trailing '/' is stripped, the invariant
Guido van Rossum555915a1994-02-24 11:32:59 +0000271# join(head, tail) == p holds.
272# The resulting head won't end in '/' unless it is the root.
273
274def split(p):
Guido van Rossum534972b1999-02-03 17:20:50 +0000275 """Split a pathname.
276
277 Return tuple (head, tail) where tail is everything after the final slash.
278 Either part may be empty."""
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000279
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000280 seps = _get_bothseps(p)
Guido van Rossum15e22e11997-12-05 19:03:01 +0000281 d, p = splitdrive(p)
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000282 # set i to index beyond p's last slash
283 i = len(p)
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000284 while i and p[i-1] not in seps:
Georg Brandl599b65d2010-07-23 08:46:35 +0000285 i -= 1
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000286 head, tail = p[:i], p[i:] # now tail has no slashes
287 # remove trailing slashes from head, unless it's all slashes
288 head2 = head
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000289 while head2 and head2[-1:] in seps:
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000290 head2 = head2[:-1]
291 head = head2 or head
Guido van Rossum15e22e11997-12-05 19:03:01 +0000292 return d + head, tail
Guido van Rossum555915a1994-02-24 11:32:59 +0000293
294
295# Split a path in root and extension.
Guido van Rossum73e122f1997-01-22 00:17:26 +0000296# The extension is everything starting at the last dot in the last
Guido van Rossum555915a1994-02-24 11:32:59 +0000297# pathname component; the root is everything before that.
298# It is always true that root + ext == p.
299
300def splitext(p):
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000301 return genericpath._splitext(p, _get_sep(p), _get_altsep(p),
302 _get_dot(p))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000303splitext.__doc__ = genericpath._splitext.__doc__
Guido van Rossum555915a1994-02-24 11:32:59 +0000304
305
306# Return the tail (basename) part of a path.
307
308def basename(p):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000309 """Returns the final component of a pathname"""
310 return split(p)[1]
Guido van Rossum555915a1994-02-24 11:32:59 +0000311
312
313# Return the head (dirname) part of a path.
314
315def dirname(p):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000316 """Returns the directory component of a pathname"""
317 return split(p)[0]
Guido van Rossum555915a1994-02-24 11:32:59 +0000318
Guido van Rossum555915a1994-02-24 11:32:59 +0000319# Is a path a symbolic link?
Brian Curtind40e6f72010-07-08 21:39:08 +0000320# This will always return false on systems where os.lstat doesn't exist.
Guido van Rossum555915a1994-02-24 11:32:59 +0000321
322def islink(path):
Brian Curtind40e6f72010-07-08 21:39:08 +0000323 """Test whether a path is a symbolic link.
324 This will always return false for Windows prior to 6.0
325 and for OS/2.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000326 """
Brian Curtind40e6f72010-07-08 21:39:08 +0000327 try:
328 st = os.lstat(path)
329 except (os.error, AttributeError):
330 return False
331 return stat.S_ISLNK(st.st_mode)
Guido van Rossum555915a1994-02-24 11:32:59 +0000332
Brian Curtind40e6f72010-07-08 21:39:08 +0000333# Being true for dangling symbolic links is also useful.
334
335def lexists(path):
336 """Test whether a path exists. Returns True for broken symbolic links"""
337 try:
338 st = os.lstat(path)
339 except (os.error, WindowsError):
340 return False
341 return True
Johannes Gijsbersae882f72004-08-30 10:19:56 +0000342
Guido van Rossumf3c695c1999-04-06 19:32:19 +0000343# Is a path a mount point? Either a root (with or without drive letter)
344# or an UNC path with at most a / or \ after the mount point.
Guido van Rossum555915a1994-02-24 11:32:59 +0000345
346def ismount(path):
Guido van Rossumca99c2c1998-01-19 22:25:59 +0000347 """Test whether a path is a mount point (defined as root of drive)"""
Benjamin Peterson48e24782009-03-29 13:02:52 +0000348 seps = _get_bothseps(path)
Mark Hammond5a607a32009-05-06 08:04:54 +0000349 root, rest = splitdrive(path)
350 if root and root[0] in seps:
351 return (not rest) or (rest in seps)
352 return rest in seps
Guido van Rossum555915a1994-02-24 11:32:59 +0000353
354
Guido van Rossum555915a1994-02-24 11:32:59 +0000355# Expand paths beginning with '~' or '~user'.
356# '~' means $HOME; '~user' means that user's home directory.
357# If the path doesn't begin with '~', or if the user or $HOME is unknown,
358# the path is returned unchanged (leaving error reporting to whatever
359# function is called with the expanded path as argument).
360# See also module 'glob' for expansion of *, ? and [...] in pathnames.
361# (A function should also be defined to do full *sh-style environment
362# variable expansion.)
363
364def expanduser(path):
Guido van Rossum534972b1999-02-03 17:20:50 +0000365 """Expand ~ and ~user constructs.
366
367 If user or $HOME is unknown, do nothing."""
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000368 if isinstance(path, bytes):
369 tilde = b'~'
370 else:
371 tilde = '~'
372 if not path.startswith(tilde):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000373 return path
374 i, n = 1, len(path)
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000375 while i < n and path[i] not in _get_bothseps(path):
Georg Brandl599b65d2010-07-23 08:46:35 +0000376 i += 1
Guido van Rossumd8faa362007-04-27 19:54:29 +0000377
378 if 'HOME' in os.environ:
379 userhome = os.environ['HOME']
380 elif 'USERPROFILE' in os.environ:
381 userhome = os.environ['USERPROFILE']
382 elif not 'HOMEPATH' in os.environ:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000383 return path
Guido van Rossumd8faa362007-04-27 19:54:29 +0000384 else:
385 try:
386 drive = os.environ['HOMEDRIVE']
387 except KeyError:
388 drive = ''
389 userhome = join(drive, os.environ['HOMEPATH'])
390
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000391 if isinstance(path, bytes):
392 userhome = userhome.encode(sys.getfilesystemencoding())
393
Guido van Rossumd8faa362007-04-27 19:54:29 +0000394 if i != 1: #~user
395 userhome = join(dirname(userhome), path[1:i])
396
Guido van Rossum15e22e11997-12-05 19:03:01 +0000397 return userhome + path[i:]
Guido van Rossum555915a1994-02-24 11:32:59 +0000398
399
400# Expand paths containing shell variable substitutions.
401# The following rules apply:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000402# - no expansion within single quotes
Guido van Rossumd8faa362007-04-27 19:54:29 +0000403# - '$$' is translated into '$'
404# - '%%' is translated into '%' if '%%' are not seen in %var1%%var2%
Guido van Rossum15e22e11997-12-05 19:03:01 +0000405# - ${varname} is accepted.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000406# - $varname is accepted.
407# - %varname% is accepted.
408# - varnames can be made out of letters, digits and the characters '_-'
409# (though is not verifed in the ${varname} and %varname% cases)
Guido van Rossum555915a1994-02-24 11:32:59 +0000410# XXX With COMMAND.COM you can use any characters in a variable name,
411# XXX except '^|<>='.
412
Tim Peters2344fae2001-01-15 00:50:52 +0000413def expandvars(path):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000414 """Expand shell variables of the forms $var, ${var} and %var%.
Guido van Rossum534972b1999-02-03 17:20:50 +0000415
416 Unknown variables are left unchanged."""
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000417 if isinstance(path, bytes):
418 if ord('$') not in path and ord('%') not in path:
419 return path
420 import string
421 varchars = bytes(string.ascii_letters + string.digits + '_-', 'ascii')
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000422 quote = b'\''
423 percent = b'%'
424 brace = b'{'
425 dollar = b'$'
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000426 else:
427 if '$' not in path and '%' not in path:
428 return path
429 import string
430 varchars = string.ascii_letters + string.digits + '_-'
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000431 quote = '\''
432 percent = '%'
433 brace = '{'
434 dollar = '$'
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000435 res = path[:0]
Guido van Rossum15e22e11997-12-05 19:03:01 +0000436 index = 0
437 pathlen = len(path)
438 while index < pathlen:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000439 c = path[index:index+1]
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000440 if c == quote: # no expansion within single quotes
Guido van Rossum15e22e11997-12-05 19:03:01 +0000441 path = path[index + 1:]
442 pathlen = len(path)
443 try:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000444 index = path.index(c)
Georg Brandl599b65d2010-07-23 08:46:35 +0000445 res += c + path[:index + 1]
Fred Drakeb4e460a2000-09-28 16:25:20 +0000446 except ValueError:
Georg Brandl599b65d2010-07-23 08:46:35 +0000447 res += path
Fred Drakeb4e460a2000-09-28 16:25:20 +0000448 index = pathlen - 1
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000449 elif c == percent: # variable or '%'
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000450 if path[index + 1:index + 2] == percent:
Georg Brandl599b65d2010-07-23 08:46:35 +0000451 res += c
452 index += 1
Guido van Rossumd8faa362007-04-27 19:54:29 +0000453 else:
454 path = path[index+1:]
455 pathlen = len(path)
456 try:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000457 index = path.index(percent)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000458 except ValueError:
Georg Brandl599b65d2010-07-23 08:46:35 +0000459 res += percent + path
Guido van Rossumd8faa362007-04-27 19:54:29 +0000460 index = pathlen - 1
461 else:
462 var = path[:index]
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000463 if isinstance(path, bytes):
464 var = var.decode('ascii')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000465 if var in os.environ:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000466 value = os.environ[var]
Guido van Rossumd8faa362007-04-27 19:54:29 +0000467 else:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000468 value = '%' + var + '%'
469 if isinstance(path, bytes):
470 value = value.encode('ascii')
Georg Brandl599b65d2010-07-23 08:46:35 +0000471 res += value
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000472 elif c == dollar: # variable or '$$'
473 if path[index + 1:index + 2] == dollar:
Georg Brandl599b65d2010-07-23 08:46:35 +0000474 res += c
475 index += 1
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000476 elif path[index + 1:index + 2] == brace:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000477 path = path[index+2:]
478 pathlen = len(path)
479 try:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000480 if isinstance(path, bytes):
481 index = path.index(b'}')
Thomas Woutersb2137042007-02-01 18:02:27 +0000482 else:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000483 index = path.index('}')
484 var = path[:index]
485 if isinstance(path, bytes):
486 var = var.decode('ascii')
487 if var in os.environ:
488 value = os.environ[var]
489 else:
490 value = '${' + var + '}'
491 if isinstance(path, bytes):
492 value = value.encode('ascii')
Georg Brandl599b65d2010-07-23 08:46:35 +0000493 res += value
Fred Drakeb4e460a2000-09-28 16:25:20 +0000494 except ValueError:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000495 if isinstance(path, bytes):
Georg Brandl599b65d2010-07-23 08:46:35 +0000496 res += b'${' + path
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000497 else:
Georg Brandl599b65d2010-07-23 08:46:35 +0000498 res += '${' + path
Guido van Rossum15e22e11997-12-05 19:03:01 +0000499 index = pathlen - 1
500 else:
501 var = ''
Georg Brandl599b65d2010-07-23 08:46:35 +0000502 index += 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000503 c = path[index:index + 1]
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000504 while c and c in varchars:
505 if isinstance(path, bytes):
Georg Brandl599b65d2010-07-23 08:46:35 +0000506 var += c.decode('ascii')
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000507 else:
Georg Brandl599b65d2010-07-23 08:46:35 +0000508 var += c
509 index += 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000510 c = path[index:index + 1]
Raymond Hettinger54f02222002-06-01 14:18:47 +0000511 if var in os.environ:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000512 value = os.environ[var]
Thomas Woutersb2137042007-02-01 18:02:27 +0000513 else:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000514 value = '$' + var
515 if isinstance(path, bytes):
516 value = value.encode('ascii')
Georg Brandl599b65d2010-07-23 08:46:35 +0000517 res += value
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000518 if c:
Georg Brandl599b65d2010-07-23 08:46:35 +0000519 index -= 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000520 else:
Georg Brandl599b65d2010-07-23 08:46:35 +0000521 res += c
522 index += 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000523 return res
Guido van Rossum555915a1994-02-24 11:32:59 +0000524
525
Tim Peters54a14a32001-08-30 22:05:26 +0000526# 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 +0000527# Previously, this function also truncated pathnames to 8+3 format,
528# but as this module is called "ntpath", that's obviously wrong!
Guido van Rossum555915a1994-02-24 11:32:59 +0000529
530def normpath(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000531 """Normalize path, eliminating double slashes, etc."""
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000532 sep = _get_sep(path)
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000533 dotdot = _get_dot(path) * 2
Georg Brandlcfb68212010-07-31 21:40:15 +0000534 special_prefixes = _get_special(path)
535 if path.startswith(special_prefixes):
536 # in the case of paths with these prefixes:
537 # \\.\ -> device names
538 # \\?\ -> literal paths
539 # do not do any normalization, but return the path unchanged
540 return path
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000541 path = path.replace(_get_altsep(path), sep)
Guido van Rossum15e22e11997-12-05 19:03:01 +0000542 prefix, path = splitdrive(path)
Mark Hammond5a607a32009-05-06 08:04:54 +0000543
544 # collapse initial backslashes
545 if path.startswith(sep):
Georg Brandl599b65d2010-07-23 08:46:35 +0000546 prefix += sep
Mark Hammond5a607a32009-05-06 08:04:54 +0000547 path = path.lstrip(sep)
548
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000549 comps = path.split(sep)
Guido van Rossum15e22e11997-12-05 19:03:01 +0000550 i = 0
551 while i < len(comps):
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000552 if not comps[i] or comps[i] == _get_dot(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000553 del comps[i]
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000554 elif comps[i] == dotdot:
555 if i > 0 and comps[i-1] != dotdot:
Tim Peters54a14a32001-08-30 22:05:26 +0000556 del comps[i-1:i+1]
557 i -= 1
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000558 elif i == 0 and prefix.endswith(_get_sep(path)):
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000559 del comps[i]
560 else:
561 i += 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000562 else:
Tim Peters54a14a32001-08-30 22:05:26 +0000563 i += 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000564 # If the path is now empty, substitute '.'
565 if not prefix and not comps:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000566 comps.append(_get_dot(path))
567 return prefix + sep.join(comps)
Guido van Rossume294cf61999-01-29 18:05:18 +0000568
569
570# Return an absolute path.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000571try:
572 from nt import _getfullpathname
Mark Hammondf717f052002-01-17 00:44:26 +0000573
Thomas Wouters477c8d52006-05-27 19:21:47 +0000574except ImportError: # not running on Windows - mock up something sensible
575 def abspath(path):
576 """Return the absolute version of a path."""
577 if not isabs(path):
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000578 if isinstance(path, bytes):
579 cwd = os.getcwdb()
580 else:
581 cwd = os.getcwd()
582 path = join(cwd, path)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000583 return normpath(path)
584
585else: # use native Windows method on Windows
586 def abspath(path):
587 """Return the absolute version of a path."""
588
589 if path: # Empty path must return current working directory.
590 try:
591 path = _getfullpathname(path)
592 except WindowsError:
593 pass # Bad path - return unchanged.
Florent Xiclunaad8c5ca2010-03-08 14:44:41 +0000594 elif isinstance(path, bytes):
595 path = os.getcwdb()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000596 else:
597 path = os.getcwd()
598 return normpath(path)
Guido van Rossum83eeef42001-09-17 15:16:09 +0000599
600# realpath is a no-op on systems without islink support
601realpath = abspath
Mark Hammond8696ebc2002-10-08 02:44:31 +0000602# Win9x family and earlier have no Unicode filename support.
Tim Peters26bc25a2002-10-09 07:56:04 +0000603supports_unicode_filenames = (hasattr(sys, "getwindowsversion") and
604 sys.getwindowsversion()[3] >= 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000605
606def relpath(path, start=curdir):
607 """Return a relative version of a path"""
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000608 sep = _get_sep(path)
609
610 if start is curdir:
611 start = _get_dot(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000612
613 if not path:
614 raise ValueError("no path specified")
Mark Hammond5a607a32009-05-06 08:04:54 +0000615
616 start_abs = abspath(normpath(start))
617 path_abs = abspath(normpath(path))
618 start_drive, start_rest = splitdrive(start_abs)
619 path_drive, path_rest = splitdrive(path_abs)
620 if start_drive != path_drive:
621 error = "path is on mount '{0}', start on mount '{1}'".format(
622 path_drive, start_drive)
623 raise ValueError(error)
624
625 start_list = [x for x in start_rest.split(sep) if x]
626 path_list = [x for x in path_rest.split(sep) if x]
Guido van Rossumd8faa362007-04-27 19:54:29 +0000627 # Work out how much of the filepath is shared by start and path.
Mark Hammond5a607a32009-05-06 08:04:54 +0000628 i = 0
629 for e1, e2 in zip(start_list, path_list):
630 if e1 != e2:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000631 break
Guido van Rossumd8faa362007-04-27 19:54:29 +0000632 i += 1
633
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000634 if isinstance(path, bytes):
635 pardir = b'..'
636 else:
637 pardir = '..'
Guido van Rossumd8faa362007-04-27 19:54:29 +0000638 rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
Christian Heimesfaf2f632008-01-06 16:59:19 +0000639 if not rel_list:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000640 return _get_dot(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000641 return join(*rel_list)
Brian Curtind40e6f72010-07-08 21:39:08 +0000642
643
644# determine if two files are in fact the same file
645def samefile(f1, f2):
646 "Test whether two pathnames reference the same actual file"
647 try:
648 from nt import _getfinalpathname
649 return _getfinalpathname(f1) == _getfinalpathname(f2)
650 except (NotImplementedError, ImportError):
651 # On Windows XP and earlier, two files are the same if their
652 # absolute pathnames are the same.
653 # Also, on other operating systems, fake this method with a
654 # Windows-XP approximation.
655 return abspath(f1) == abspath(f2)
Brian Curtin62857742010-09-06 17:07:27 +0000656
657def sameopenfile(f1, f2):
658 """Test whether two file objects reference the same file"""
659 return _getfileinformation(f1) == _getfileinformation(f2)