blob: d81f7285aee8683f22d61a7f6e3339aebf6bac52 [file] [log] [blame]
Guido van Rossum15e22e11997-12-05 19:03:01 +00001# Module 'ntpath' -- common operations on WinNT/Win95 pathnames
Tim Peters2344fae2001-01-15 00:50:52 +00002"""Common pathname manipulations, WindowsNT/95 version.
Guido van Rossum534972b1999-02-03 17:20:50 +00003
4Instead of importing this module directly, import os and refer to this
5module as os.path.
Guido van Rossum15e22e11997-12-05 19:03:01 +00006"""
Guido van Rossum555915a1994-02-24 11:32:59 +00007
8import os
Mark Hammond8696ebc2002-10-08 02:44:31 +00009import sys
Christian Heimes05e8be12008-02-23 18:30:17 +000010import stat
Guido van Rossumd8faa362007-04-27 19:54:29 +000011import genericpath
Thomas Wouters89f507f2006-12-13 04:49:30 +000012from genericpath import *
Skip Montanaro4d5d5bf2000-07-13 01:01:03 +000013
Skip Montanaro269b83b2001-02-06 01:07:02 +000014__all__ = ["normcase","isabs","join","splitdrive","split","splitext",
15 "basename","dirname","commonprefix","getsize","getmtime",
Georg Brandlf0de6a12005-08-22 18:02:59 +000016 "getatime","getctime", "islink","exists","lexists","isdir","isfile",
Benjamin Petersond71ca412008-05-08 23:44:58 +000017 "ismount", "expanduser","expandvars","normpath","abspath",
Georg Brandlf0de6a12005-08-22 18:02:59 +000018 "splitunc","curdir","pardir","sep","pathsep","defpath","altsep",
Brian Curtind40e6f72010-07-08 21:39:08 +000019 "extsep","devnull","realpath","supports_unicode_filenames","relpath",
Brian Curtinae57cec2012-12-26 08:22:00 -060020 "samefile", "sameopenfile", "samestat",]
Guido van Rossum555915a1994-02-24 11:32:59 +000021
Skip Montanaro117910d2003-02-14 19:35:31 +000022# strings representing various path-related bits and pieces
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +000023# These are primarily for export; internally, they are hardcoded.
Skip Montanaro117910d2003-02-14 19:35:31 +000024curdir = '.'
25pardir = '..'
26extsep = '.'
27sep = '\\'
28pathsep = ';'
Skip Montanaro9ddac3e2003-03-28 22:23:24 +000029altsep = '/'
Andrew MacIntyre437966c2003-02-17 09:17:50 +000030defpath = '.;C:\\bin'
Skip Montanaro117910d2003-02-14 19:35:31 +000031if 'ce' in sys.builtin_module_names:
32 defpath = '\\Windows'
Martin v. Löwisbdec50f2004-06-08 08:29:33 +000033devnull = 'nul'
Skip Montanaro117910d2003-02-14 19:35:31 +000034
Mark Hammond5a607a32009-05-06 08:04:54 +000035def _get_empty(path):
36 if isinstance(path, bytes):
37 return b''
38 else:
39 return ''
40
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +000041def _get_sep(path):
42 if isinstance(path, bytes):
43 return b'\\'
44 else:
45 return '\\'
46
47def _get_altsep(path):
48 if isinstance(path, bytes):
49 return b'/'
50 else:
51 return '/'
52
53def _get_bothseps(path):
54 if isinstance(path, bytes):
55 return b'\\/'
56 else:
57 return '\\/'
58
59def _get_dot(path):
60 if isinstance(path, bytes):
61 return b'.'
62 else:
63 return '.'
64
65def _get_colon(path):
66 if isinstance(path, bytes):
67 return b':'
68 else:
69 return ':'
70
Georg Brandlcfb68212010-07-31 21:40:15 +000071def _get_special(path):
72 if isinstance(path, bytes):
73 return (b'\\\\.\\', b'\\\\?\\')
74 else:
75 return ('\\\\.\\', '\\\\?\\')
76
Guido van Rossume2ad88c1997-08-12 14:46:58 +000077# Normalize the case of a pathname and map slashes to backslashes.
78# Other normalizations (such as optimizing '../' away) are not done
Guido van Rossum555915a1994-02-24 11:32:59 +000079# (this is done by normpath).
Guido van Rossume2ad88c1997-08-12 14:46:58 +000080
Guido van Rossum555915a1994-02-24 11:32:59 +000081def normcase(s):
Guido van Rossum16a0bc21998-02-18 13:48:31 +000082 """Normalize case of pathname.
83
Guido van Rossum534972b1999-02-03 17:20:50 +000084 Makes all characters lowercase and all slashes into backslashes."""
Ezio Melotti5a3ef5b2010-06-25 10:56:11 +000085 if not isinstance(s, (bytes, str)):
86 raise TypeError("normcase() argument must be str or bytes, "
87 "not '{}'".format(s.__class__.__name__))
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +000088 return s.replace(_get_altsep(s), _get_sep(s)).lower()
Guido van Rossum555915a1994-02-24 11:32:59 +000089
Guido van Rossum77e1db31997-06-02 23:11:57 +000090
Fred Drakeef0b5dd2000-02-17 17:30:40 +000091# Return whether a path is absolute.
Mark Hammond5a607a32009-05-06 08:04:54 +000092# Trivial in Posix, harder on Windows.
93# For Windows it is absolute if it starts with a slash or backslash (current
94# volume), or if a pathname after the volume-letter-and-colon or UNC-resource
Guido van Rossum534972b1999-02-03 17:20:50 +000095# starts with a slash or backslash.
Guido van Rossum555915a1994-02-24 11:32:59 +000096
97def isabs(s):
Guido van Rossum15e22e11997-12-05 19:03:01 +000098 """Test whether a path is absolute"""
99 s = splitdrive(s)[1]
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000100 return len(s) > 0 and s[:1] in _get_bothseps(s)
Guido van Rossum555915a1994-02-24 11:32:59 +0000101
102
Guido van Rossum77e1db31997-06-02 23:11:57 +0000103# Join two (or more) paths.
104
Barry Warsaw384d2491997-02-18 21:53:25 +0000105def join(a, *p):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000106 """Join two or more pathname components, inserting "\\" as needed.
107 If any component is an absolute path, all previous path components
108 will be discarded."""
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000109 sep = _get_sep(a)
110 seps = _get_bothseps(a)
111 colon = _get_colon(a)
Guido van Rossum15e22e11997-12-05 19:03:01 +0000112 path = a
113 for b in p:
Tim Peters33dc0a12001-07-27 08:09:54 +0000114 b_wins = 0 # set to 1 iff b makes path irrelevant
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000115 if not path:
Tim Peters33dc0a12001-07-27 08:09:54 +0000116 b_wins = 1
Tim Peters1bdd0f22001-07-19 17:18:18 +0000117
Tim Peters33dc0a12001-07-27 08:09:54 +0000118 elif isabs(b):
119 # This probably wipes out path so far. However, it's more
Mark Hammond5a607a32009-05-06 08:04:54 +0000120 # complicated if path begins with a drive letter. You get a+b
121 # (minus redundant slashes) in these four cases:
Tim Peters33dc0a12001-07-27 08:09:54 +0000122 # 1. join('c:', '/a') == 'c:/a'
Mark Hammond5a607a32009-05-06 08:04:54 +0000123 # 2. join('//computer/share', '/a') == '//computer/share/a'
124 # 3. join('c:/', '/a') == 'c:/a'
125 # 4. join('//computer/share/', '/a') == '//computer/share/a'
126 # But b wins in all of these cases:
127 # 5. join('c:/a', '/b') == '/b'
128 # 6. join('//computer/share/a', '/b') == '/b'
129 # 7. join('c:', 'd:/') == 'd:/'
130 # 8. join('c:', '//computer/share/') == '//computer/share/'
131 # 9. join('//computer/share', 'd:/') == 'd:/'
132 # 10. join('//computer/share', '//computer/share/') == '//computer/share/'
133 # 11. join('c:/', 'd:/') == 'd:/'
134 # 12. join('c:/', '//computer/share/') == '//computer/share/'
135 # 13. join('//computer/share/', 'd:/') == 'd:/'
136 # 14. join('//computer/share/', '//computer/share/') == '//computer/share/'
137 b_prefix, b_rest = splitdrive(b)
Tim Peters1bdd0f22001-07-19 17:18:18 +0000138
Mark Hammond5a607a32009-05-06 08:04:54 +0000139 # if b has a prefix, it always wins.
140 if b_prefix:
Tim Peters33dc0a12001-07-27 08:09:54 +0000141 b_wins = 1
Mark Hammond5a607a32009-05-06 08:04:54 +0000142 else:
143 # b doesn't have a prefix.
144 # but isabs(b) returned true.
145 # and therefore b_rest[0] must be a slash.
146 # (but let's check that.)
147 assert(b_rest and b_rest[0] in seps)
148
149 # so, b still wins if path has a rest that's more than a sep.
150 # you get a+b if path_rest is empty or only has a sep.
151 # (see cases 1-4 for times when b loses.)
152 path_rest = splitdrive(path)[1]
153 b_wins = path_rest and path_rest not in seps
Tim Peters1bdd0f22001-07-19 17:18:18 +0000154
Tim Peters33dc0a12001-07-27 08:09:54 +0000155 if b_wins:
156 path = b
157 else:
158 # Join, and ensure there's a separator.
159 assert len(path) > 0
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000160 if path[-1:] in seps:
161 if b and b[:1] in seps:
Tim Peters33dc0a12001-07-27 08:09:54 +0000162 path += b[1:]
163 else:
164 path += b
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000165 elif path[-1:] == colon:
Tim Peters33dc0a12001-07-27 08:09:54 +0000166 path += b
167 elif b:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000168 if b[:1] in seps:
Tim Peters33dc0a12001-07-27 08:09:54 +0000169 path += b
170 else:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000171 path += sep + b
Tim Peters6a3e5f12001-11-05 21:25:02 +0000172 else:
173 # path is not empty and does not end with a backslash,
174 # but b is empty; since, e.g., split('a/') produces
175 # ('a', ''), it's best if join() adds a backslash in
176 # this case.
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000177 path += sep
Tim Peters1bdd0f22001-07-19 17:18:18 +0000178
Guido van Rossum15e22e11997-12-05 19:03:01 +0000179 return path
Guido van Rossum555915a1994-02-24 11:32:59 +0000180
181
182# Split a path in a drive specification (a drive letter followed by a
Guido van Rossumf3c695c1999-04-06 19:32:19 +0000183# colon) and the path specification.
Guido van Rossum555915a1994-02-24 11:32:59 +0000184# It is always true that drivespec + pathspec == p
185def splitdrive(p):
Mark Hammond5a607a32009-05-06 08:04:54 +0000186 """Split a pathname into drive/UNC sharepoint and relative path specifiers.
187 Returns a 2-tuple (drive_or_unc, path); either part may be empty.
188
189 If you assign
190 result = splitdrive(p)
191 It is always true that:
192 result[0] + result[1] == p
193
194 If the path contained a drive letter, drive_or_unc will contain everything
195 up to and including the colon. e.g. splitdrive("c:/dir") returns ("c:", "/dir")
196
197 If the path contained a UNC path, the drive_or_unc will contain the host name
198 and share up to but not including the fourth directory separator character.
199 e.g. splitdrive("//host/computer/dir") returns ("//host/computer", "/dir")
200
201 Paths cannot contain both a drive letter and a UNC path.
202
203 """
204 empty = _get_empty(p)
205 if len(p) > 1:
206 sep = _get_sep(p)
207 normp = normcase(p)
208 if (normp[0:2] == sep*2) and (normp[2:3] != sep):
209 # is a UNC path:
210 # vvvvvvvvvvvvvvvvvvvv drive letter or UNC path
211 # \\machine\mountpoint\directory\etc\...
212 # directory ^^^^^^^^^^^^^^^
213 index = normp.find(sep, 2)
214 if index == -1:
215 return empty, p
216 index2 = normp.find(sep, index + 1)
217 # a UNC path can't have two slashes in a row
218 # (after the initial two)
219 if index2 == index + 1:
220 return empty, p
221 if index2 == -1:
222 index2 = len(p)
223 return p[:index2], p[index2:]
224 if normp[1:2] == _get_colon(p):
225 return p[:2], p[2:]
226 return empty, p
Guido van Rossumf3c695c1999-04-06 19:32:19 +0000227
228
229# Parse UNC paths
230def splitunc(p):
Mark Hammond5a607a32009-05-06 08:04:54 +0000231 """Deprecated since Python 3.1. Please use splitdrive() instead;
232 it now handles UNC paths.
233
234 Split a pathname into UNC mount point and relative path specifiers.
Guido van Rossumf3c695c1999-04-06 19:32:19 +0000235
236 Return a 2-tuple (unc, rest); either part may be empty.
237 If unc is not empty, it has the form '//host/mount' (or similar
238 using backslashes). unc+rest is always the input path.
239 Paths containing drive letters never have an UNC part.
240 """
Mark Hammond5a607a32009-05-06 08:04:54 +0000241 import warnings
242 warnings.warn("ntpath.splitunc is deprecated, use ntpath.splitdrive instead",
Gregory P. Smithaa3b5b82009-06-30 05:33:50 +0000243 DeprecationWarning)
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000244 sep = _get_sep(p)
245 if not p[1:2]:
246 return p[:0], p # Drive letter present
Guido van Rossum534972b1999-02-03 17:20:50 +0000247 firstTwo = p[0:2]
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000248 if normcase(firstTwo) == sep + sep:
Guido van Rossum534972b1999-02-03 17:20:50 +0000249 # is a UNC path:
250 # vvvvvvvvvvvvvvvvvvvv equivalent to drive letter
251 # \\machine\mountpoint\directories...
252 # directory ^^^^^^^^^^^^^^^
253 normp = normcase(p)
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000254 index = normp.find(sep, 2)
Guido van Rossum534972b1999-02-03 17:20:50 +0000255 if index == -1:
256 ##raise RuntimeError, 'illegal UNC path: "' + p + '"'
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000257 return (p[:0], p)
258 index = normp.find(sep, index + 1)
Guido van Rossum534972b1999-02-03 17:20:50 +0000259 if index == -1:
260 index = len(p)
261 return p[:index], p[index:]
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000262 return p[:0], p
Guido van Rossum555915a1994-02-24 11:32:59 +0000263
264
265# Split a path in head (everything up to the last '/') and tail (the
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000266# rest). After the trailing '/' is stripped, the invariant
Guido van Rossum555915a1994-02-24 11:32:59 +0000267# join(head, tail) == p holds.
268# The resulting head won't end in '/' unless it is the root.
269
270def split(p):
Guido van Rossum534972b1999-02-03 17:20:50 +0000271 """Split a pathname.
272
273 Return tuple (head, tail) where tail is everything after the final slash.
274 Either part may be empty."""
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000275
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000276 seps = _get_bothseps(p)
Guido van Rossum15e22e11997-12-05 19:03:01 +0000277 d, p = splitdrive(p)
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000278 # set i to index beyond p's last slash
279 i = len(p)
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000280 while i and p[i-1] not in seps:
Georg Brandl599b65d2010-07-23 08:46:35 +0000281 i -= 1
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000282 head, tail = p[:i], p[i:] # now tail has no slashes
283 # remove trailing slashes from head, unless it's all slashes
284 head2 = head
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000285 while head2 and head2[-1:] in seps:
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000286 head2 = head2[:-1]
287 head = head2 or head
Guido van Rossum15e22e11997-12-05 19:03:01 +0000288 return d + head, tail
Guido van Rossum555915a1994-02-24 11:32:59 +0000289
290
291# Split a path in root and extension.
Guido van Rossum73e122f1997-01-22 00:17:26 +0000292# The extension is everything starting at the last dot in the last
Guido van Rossum555915a1994-02-24 11:32:59 +0000293# pathname component; the root is everything before that.
294# It is always true that root + ext == p.
295
296def splitext(p):
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000297 return genericpath._splitext(p, _get_sep(p), _get_altsep(p),
298 _get_dot(p))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000299splitext.__doc__ = genericpath._splitext.__doc__
Guido van Rossum555915a1994-02-24 11:32:59 +0000300
301
302# Return the tail (basename) part of a path.
303
304def basename(p):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000305 """Returns the final component of a pathname"""
306 return split(p)[1]
Guido van Rossum555915a1994-02-24 11:32:59 +0000307
308
309# Return the head (dirname) part of a path.
310
311def dirname(p):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000312 """Returns the directory component of a pathname"""
313 return split(p)[0]
Guido van Rossum555915a1994-02-24 11:32:59 +0000314
Guido van Rossum555915a1994-02-24 11:32:59 +0000315# Is a path a symbolic link?
Brian Curtind40e6f72010-07-08 21:39:08 +0000316# This will always return false on systems where os.lstat doesn't exist.
Guido van Rossum555915a1994-02-24 11:32:59 +0000317
318def islink(path):
Brian Curtind40e6f72010-07-08 21:39:08 +0000319 """Test whether a path is a symbolic link.
Jesus Ceaf1af7052012-10-05 02:48:46 +0200320 This will always return false for Windows prior to 6.0.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000321 """
Brian Curtind40e6f72010-07-08 21:39:08 +0000322 try:
323 st = os.lstat(path)
Andrew Svetlovad28c7f2012-12-18 22:02:39 +0200324 except (OSError, AttributeError):
Brian Curtind40e6f72010-07-08 21:39:08 +0000325 return False
326 return stat.S_ISLNK(st.st_mode)
Guido van Rossum555915a1994-02-24 11:32:59 +0000327
Brian Curtind40e6f72010-07-08 21:39:08 +0000328# Being true for dangling symbolic links is also useful.
329
330def lexists(path):
331 """Test whether a path exists. Returns True for broken symbolic links"""
332 try:
333 st = os.lstat(path)
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200334 except OSError:
Brian Curtind40e6f72010-07-08 21:39:08 +0000335 return False
336 return True
Johannes Gijsbersae882f72004-08-30 10:19:56 +0000337
Guido van Rossumf3c695c1999-04-06 19:32:19 +0000338# Is a path a mount point? Either a root (with or without drive letter)
339# or an UNC path with at most a / or \ after the mount point.
Guido van Rossum555915a1994-02-24 11:32:59 +0000340
341def ismount(path):
Guido van Rossumca99c2c1998-01-19 22:25:59 +0000342 """Test whether a path is a mount point (defined as root of drive)"""
Benjamin Peterson48e24782009-03-29 13:02:52 +0000343 seps = _get_bothseps(path)
Mark Hammond5a607a32009-05-06 08:04:54 +0000344 root, rest = splitdrive(path)
345 if root and root[0] in seps:
346 return (not rest) or (rest in seps)
347 return rest in seps
Guido van Rossum555915a1994-02-24 11:32:59 +0000348
349
Guido van Rossum555915a1994-02-24 11:32:59 +0000350# Expand paths beginning with '~' or '~user'.
351# '~' means $HOME; '~user' means that user's home directory.
352# If the path doesn't begin with '~', or if the user or $HOME is unknown,
353# the path is returned unchanged (leaving error reporting to whatever
354# function is called with the expanded path as argument).
355# See also module 'glob' for expansion of *, ? and [...] in pathnames.
356# (A function should also be defined to do full *sh-style environment
357# variable expansion.)
358
359def expanduser(path):
Guido van Rossum534972b1999-02-03 17:20:50 +0000360 """Expand ~ and ~user constructs.
361
362 If user or $HOME is unknown, do nothing."""
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000363 if isinstance(path, bytes):
364 tilde = b'~'
365 else:
366 tilde = '~'
367 if not path.startswith(tilde):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000368 return path
369 i, n = 1, len(path)
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000370 while i < n and path[i] not in _get_bothseps(path):
Georg Brandl599b65d2010-07-23 08:46:35 +0000371 i += 1
Guido van Rossumd8faa362007-04-27 19:54:29 +0000372
373 if 'HOME' in os.environ:
374 userhome = os.environ['HOME']
375 elif 'USERPROFILE' in os.environ:
376 userhome = os.environ['USERPROFILE']
377 elif not 'HOMEPATH' in os.environ:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000378 return path
Guido van Rossumd8faa362007-04-27 19:54:29 +0000379 else:
380 try:
381 drive = os.environ['HOMEDRIVE']
382 except KeyError:
383 drive = ''
384 userhome = join(drive, os.environ['HOMEPATH'])
385
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000386 if isinstance(path, bytes):
387 userhome = userhome.encode(sys.getfilesystemencoding())
388
Guido van Rossumd8faa362007-04-27 19:54:29 +0000389 if i != 1: #~user
390 userhome = join(dirname(userhome), path[1:i])
391
Guido van Rossum15e22e11997-12-05 19:03:01 +0000392 return userhome + path[i:]
Guido van Rossum555915a1994-02-24 11:32:59 +0000393
394
395# Expand paths containing shell variable substitutions.
396# The following rules apply:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000397# - no expansion within single quotes
Guido van Rossumd8faa362007-04-27 19:54:29 +0000398# - '$$' is translated into '$'
399# - '%%' is translated into '%' if '%%' are not seen in %var1%%var2%
Guido van Rossum15e22e11997-12-05 19:03:01 +0000400# - ${varname} is accepted.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000401# - $varname is accepted.
402# - %varname% is accepted.
403# - varnames can be made out of letters, digits and the characters '_-'
Ezio Melotti13925002011-03-16 11:05:33 +0200404# (though is not verified in the ${varname} and %varname% cases)
Guido van Rossum555915a1994-02-24 11:32:59 +0000405# XXX With COMMAND.COM you can use any characters in a variable name,
406# XXX except '^|<>='.
407
Tim Peters2344fae2001-01-15 00:50:52 +0000408def expandvars(path):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000409 """Expand shell variables of the forms $var, ${var} and %var%.
Guido van Rossum534972b1999-02-03 17:20:50 +0000410
411 Unknown variables are left unchanged."""
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000412 if isinstance(path, bytes):
413 if ord('$') not in path and ord('%') not in path:
414 return path
415 import string
416 varchars = bytes(string.ascii_letters + string.digits + '_-', 'ascii')
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000417 quote = b'\''
418 percent = b'%'
419 brace = b'{'
420 dollar = b'$'
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000421 else:
422 if '$' not in path and '%' not in path:
423 return path
424 import string
425 varchars = string.ascii_letters + string.digits + '_-'
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000426 quote = '\''
427 percent = '%'
428 brace = '{'
429 dollar = '$'
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000430 res = path[:0]
Guido van Rossum15e22e11997-12-05 19:03:01 +0000431 index = 0
432 pathlen = len(path)
433 while index < pathlen:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000434 c = path[index:index+1]
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000435 if c == quote: # no expansion within single quotes
Guido van Rossum15e22e11997-12-05 19:03:01 +0000436 path = path[index + 1:]
437 pathlen = len(path)
438 try:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000439 index = path.index(c)
Georg Brandl599b65d2010-07-23 08:46:35 +0000440 res += c + path[:index + 1]
Fred Drakeb4e460a2000-09-28 16:25:20 +0000441 except ValueError:
Georg Brandl599b65d2010-07-23 08:46:35 +0000442 res += path
Fred Drakeb4e460a2000-09-28 16:25:20 +0000443 index = pathlen - 1
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000444 elif c == percent: # variable or '%'
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000445 if path[index + 1:index + 2] == percent:
Georg Brandl599b65d2010-07-23 08:46:35 +0000446 res += c
447 index += 1
Guido van Rossumd8faa362007-04-27 19:54:29 +0000448 else:
449 path = path[index+1:]
450 pathlen = len(path)
451 try:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000452 index = path.index(percent)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000453 except ValueError:
Georg Brandl599b65d2010-07-23 08:46:35 +0000454 res += percent + path
Guido van Rossumd8faa362007-04-27 19:54:29 +0000455 index = pathlen - 1
456 else:
457 var = path[:index]
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000458 if isinstance(path, bytes):
459 var = var.decode('ascii')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000460 if var in os.environ:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000461 value = os.environ[var]
Guido van Rossumd8faa362007-04-27 19:54:29 +0000462 else:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000463 value = '%' + var + '%'
464 if isinstance(path, bytes):
465 value = value.encode('ascii')
Georg Brandl599b65d2010-07-23 08:46:35 +0000466 res += value
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000467 elif c == dollar: # variable or '$$'
468 if path[index + 1:index + 2] == dollar:
Georg Brandl599b65d2010-07-23 08:46:35 +0000469 res += c
470 index += 1
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000471 elif path[index + 1:index + 2] == brace:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000472 path = path[index+2:]
473 pathlen = len(path)
474 try:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000475 if isinstance(path, bytes):
476 index = path.index(b'}')
Thomas Woutersb2137042007-02-01 18:02:27 +0000477 else:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000478 index = path.index('}')
479 var = path[:index]
480 if isinstance(path, bytes):
481 var = var.decode('ascii')
482 if var in os.environ:
483 value = os.environ[var]
484 else:
485 value = '${' + var + '}'
486 if isinstance(path, bytes):
487 value = value.encode('ascii')
Georg Brandl599b65d2010-07-23 08:46:35 +0000488 res += value
Fred Drakeb4e460a2000-09-28 16:25:20 +0000489 except ValueError:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000490 if isinstance(path, bytes):
Georg Brandl599b65d2010-07-23 08:46:35 +0000491 res += b'${' + path
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000492 else:
Georg Brandl599b65d2010-07-23 08:46:35 +0000493 res += '${' + path
Guido van Rossum15e22e11997-12-05 19:03:01 +0000494 index = pathlen - 1
495 else:
496 var = ''
Georg Brandl599b65d2010-07-23 08:46:35 +0000497 index += 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000498 c = path[index:index + 1]
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000499 while c and c in varchars:
500 if isinstance(path, bytes):
Georg Brandl599b65d2010-07-23 08:46:35 +0000501 var += c.decode('ascii')
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000502 else:
Georg Brandl599b65d2010-07-23 08:46:35 +0000503 var += c
504 index += 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000505 c = path[index:index + 1]
Raymond Hettinger54f02222002-06-01 14:18:47 +0000506 if var in os.environ:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000507 value = os.environ[var]
Thomas Woutersb2137042007-02-01 18:02:27 +0000508 else:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000509 value = '$' + var
510 if isinstance(path, bytes):
511 value = value.encode('ascii')
Georg Brandl599b65d2010-07-23 08:46:35 +0000512 res += value
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000513 if c:
Georg Brandl599b65d2010-07-23 08:46:35 +0000514 index -= 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000515 else:
Georg Brandl599b65d2010-07-23 08:46:35 +0000516 res += c
517 index += 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000518 return res
Guido van Rossum555915a1994-02-24 11:32:59 +0000519
520
Tim Peters54a14a32001-08-30 22:05:26 +0000521# 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 +0000522# Previously, this function also truncated pathnames to 8+3 format,
523# but as this module is called "ntpath", that's obviously wrong!
Guido van Rossum555915a1994-02-24 11:32:59 +0000524
525def normpath(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000526 """Normalize path, eliminating double slashes, etc."""
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000527 sep = _get_sep(path)
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000528 dotdot = _get_dot(path) * 2
Georg Brandlcfb68212010-07-31 21:40:15 +0000529 special_prefixes = _get_special(path)
530 if path.startswith(special_prefixes):
531 # in the case of paths with these prefixes:
532 # \\.\ -> device names
533 # \\?\ -> literal paths
534 # do not do any normalization, but return the path unchanged
535 return path
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000536 path = path.replace(_get_altsep(path), sep)
Guido van Rossum15e22e11997-12-05 19:03:01 +0000537 prefix, path = splitdrive(path)
Mark Hammond5a607a32009-05-06 08:04:54 +0000538
539 # collapse initial backslashes
540 if path.startswith(sep):
Georg Brandl599b65d2010-07-23 08:46:35 +0000541 prefix += sep
Mark Hammond5a607a32009-05-06 08:04:54 +0000542 path = path.lstrip(sep)
543
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000544 comps = path.split(sep)
Guido van Rossum15e22e11997-12-05 19:03:01 +0000545 i = 0
546 while i < len(comps):
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000547 if not comps[i] or comps[i] == _get_dot(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000548 del comps[i]
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000549 elif comps[i] == dotdot:
550 if i > 0 and comps[i-1] != dotdot:
Tim Peters54a14a32001-08-30 22:05:26 +0000551 del comps[i-1:i+1]
552 i -= 1
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000553 elif i == 0 and prefix.endswith(_get_sep(path)):
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000554 del comps[i]
555 else:
556 i += 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000557 else:
Tim Peters54a14a32001-08-30 22:05:26 +0000558 i += 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000559 # If the path is now empty, substitute '.'
560 if not prefix and not comps:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000561 comps.append(_get_dot(path))
562 return prefix + sep.join(comps)
Guido van Rossume294cf61999-01-29 18:05:18 +0000563
564
565# Return an absolute path.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000566try:
567 from nt import _getfullpathname
Mark Hammondf717f052002-01-17 00:44:26 +0000568
Thomas Wouters477c8d52006-05-27 19:21:47 +0000569except ImportError: # not running on Windows - mock up something sensible
570 def abspath(path):
571 """Return the absolute version of a path."""
572 if not isabs(path):
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000573 if isinstance(path, bytes):
574 cwd = os.getcwdb()
575 else:
576 cwd = os.getcwd()
577 path = join(cwd, path)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000578 return normpath(path)
579
580else: # use native Windows method on Windows
581 def abspath(path):
582 """Return the absolute version of a path."""
583
584 if path: # Empty path must return current working directory.
585 try:
586 path = _getfullpathname(path)
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200587 except OSError:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000588 pass # Bad path - return unchanged.
Florent Xiclunaad8c5ca2010-03-08 14:44:41 +0000589 elif isinstance(path, bytes):
590 path = os.getcwdb()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000591 else:
592 path = os.getcwd()
593 return normpath(path)
Guido van Rossum83eeef42001-09-17 15:16:09 +0000594
595# realpath is a no-op on systems without islink support
596realpath = abspath
Mark Hammond8696ebc2002-10-08 02:44:31 +0000597# Win9x family and earlier have no Unicode filename support.
Tim Peters26bc25a2002-10-09 07:56:04 +0000598supports_unicode_filenames = (hasattr(sys, "getwindowsversion") and
599 sys.getwindowsversion()[3] >= 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000600
601def relpath(path, start=curdir):
602 """Return a relative version of a path"""
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000603 sep = _get_sep(path)
604
605 if start is curdir:
606 start = _get_dot(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000607
608 if not path:
609 raise ValueError("no path specified")
Mark Hammond5a607a32009-05-06 08:04:54 +0000610
611 start_abs = abspath(normpath(start))
612 path_abs = abspath(normpath(path))
613 start_drive, start_rest = splitdrive(start_abs)
614 path_drive, path_rest = splitdrive(path_abs)
Hirokazu Yamamotob08820a2010-10-18 12:13:18 +0000615 if normcase(start_drive) != normcase(path_drive):
Mark Hammond5a607a32009-05-06 08:04:54 +0000616 error = "path is on mount '{0}', start on mount '{1}'".format(
617 path_drive, start_drive)
618 raise ValueError(error)
619
620 start_list = [x for x in start_rest.split(sep) if x]
621 path_list = [x for x in path_rest.split(sep) if x]
Guido van Rossumd8faa362007-04-27 19:54:29 +0000622 # Work out how much of the filepath is shared by start and path.
Mark Hammond5a607a32009-05-06 08:04:54 +0000623 i = 0
624 for e1, e2 in zip(start_list, path_list):
Hirokazu Yamamotob08820a2010-10-18 12:13:18 +0000625 if normcase(e1) != normcase(e2):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000626 break
Guido van Rossumd8faa362007-04-27 19:54:29 +0000627 i += 1
628
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000629 if isinstance(path, bytes):
630 pardir = b'..'
631 else:
632 pardir = '..'
Guido van Rossumd8faa362007-04-27 19:54:29 +0000633 rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
Christian Heimesfaf2f632008-01-06 16:59:19 +0000634 if not rel_list:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000635 return _get_dot(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000636 return join(*rel_list)
Brian Curtind40e6f72010-07-08 21:39:08 +0000637
638
639# determine if two files are in fact the same file
Brian Curtin0dac8082010-09-23 20:38:14 +0000640try:
Brian Curtine8e80422010-09-24 13:56:34 +0000641 # GetFinalPathNameByHandle is available starting with Windows 6.0.
642 # Windows XP and non-Windows OS'es will mock _getfinalpathname.
643 if sys.getwindowsversion()[:2] >= (6, 0):
644 from nt import _getfinalpathname
645 else:
646 raise ImportError
647except (AttributeError, ImportError):
Brian Curtin0dac8082010-09-23 20:38:14 +0000648 # On Windows XP and earlier, two files are the same if their absolute
649 # pathnames are the same.
Brian Curtine8e80422010-09-24 13:56:34 +0000650 # Non-Windows operating systems fake this method with an XP
651 # approximation.
Brian Curtin0dac8082010-09-23 20:38:14 +0000652 def _getfinalpathname(f):
Ronald Oussoren6355c162011-05-06 17:11:07 +0200653 return normcase(abspath(f))
Brian Curtin0dac8082010-09-23 20:38:14 +0000654
Brian Curtin9c669cc2011-06-08 18:17:18 -0500655
656try:
657 # The genericpath.isdir implementation uses os.stat and checks the mode
658 # attribute to tell whether or not the path is a directory.
659 # This is overkill on Windows - just pass the path to GetFileAttributes
660 # and check the attribute from there.
Brian Curtin95d028f2011-06-09 09:10:38 -0500661 from nt import _isdir as isdir
Brian Curtin9c669cc2011-06-08 18:17:18 -0500662except ImportError:
Brian Curtin95d028f2011-06-09 09:10:38 -0500663 # Use genericpath.isdir as imported above.
664 pass