blob: ab0b318cf91e6eddf6df4bd508e7fb04d1c45c4e [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",
20 "samefile",]
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
Guido van Rossume2ad88c1997-08-12 14:46:58 +000074# Normalize the case of a pathname and map slashes to backslashes.
75# Other normalizations (such as optimizing '../' away) are not done
Guido van Rossum555915a1994-02-24 11:32:59 +000076# (this is done by normpath).
Guido van Rossume2ad88c1997-08-12 14:46:58 +000077
Guido van Rossum555915a1994-02-24 11:32:59 +000078def normcase(s):
Guido van Rossum16a0bc21998-02-18 13:48:31 +000079 """Normalize case of pathname.
80
Guido van Rossum534972b1999-02-03 17:20:50 +000081 Makes all characters lowercase and all slashes into backslashes."""
Ezio Melotti5a3ef5b2010-06-25 10:56:11 +000082 if not isinstance(s, (bytes, str)):
83 raise TypeError("normcase() argument must be str or bytes, "
84 "not '{}'".format(s.__class__.__name__))
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +000085 return s.replace(_get_altsep(s), _get_sep(s)).lower()
Guido van Rossum555915a1994-02-24 11:32:59 +000086
Guido van Rossum77e1db31997-06-02 23:11:57 +000087
Fred Drakeef0b5dd2000-02-17 17:30:40 +000088# Return whether a path is absolute.
Mark Hammond5a607a32009-05-06 08:04:54 +000089# Trivial in Posix, harder on Windows.
90# For Windows it is absolute if it starts with a slash or backslash (current
91# volume), or if a pathname after the volume-letter-and-colon or UNC-resource
Guido van Rossum534972b1999-02-03 17:20:50 +000092# starts with a slash or backslash.
Guido van Rossum555915a1994-02-24 11:32:59 +000093
94def isabs(s):
Guido van Rossum15e22e11997-12-05 19:03:01 +000095 """Test whether a path is absolute"""
96 s = splitdrive(s)[1]
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +000097 return len(s) > 0 and s[:1] in _get_bothseps(s)
Guido van Rossum555915a1994-02-24 11:32:59 +000098
99
Guido van Rossum77e1db31997-06-02 23:11:57 +0000100# Join two (or more) paths.
101
Barry Warsaw384d2491997-02-18 21:53:25 +0000102def join(a, *p):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000103 """Join two or more pathname components, inserting "\\" as needed.
104 If any component is an absolute path, all previous path components
105 will be discarded."""
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000106 sep = _get_sep(a)
107 seps = _get_bothseps(a)
108 colon = _get_colon(a)
Guido van Rossum15e22e11997-12-05 19:03:01 +0000109 path = a
110 for b in p:
Tim Peters33dc0a12001-07-27 08:09:54 +0000111 b_wins = 0 # set to 1 iff b makes path irrelevant
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000112 if not path:
Tim Peters33dc0a12001-07-27 08:09:54 +0000113 b_wins = 1
Tim Peters1bdd0f22001-07-19 17:18:18 +0000114
Tim Peters33dc0a12001-07-27 08:09:54 +0000115 elif isabs(b):
116 # This probably wipes out path so far. However, it's more
Mark Hammond5a607a32009-05-06 08:04:54 +0000117 # complicated if path begins with a drive letter. You get a+b
118 # (minus redundant slashes) in these four cases:
Tim Peters33dc0a12001-07-27 08:09:54 +0000119 # 1. join('c:', '/a') == 'c:/a'
Mark Hammond5a607a32009-05-06 08:04:54 +0000120 # 2. join('//computer/share', '/a') == '//computer/share/a'
121 # 3. join('c:/', '/a') == 'c:/a'
122 # 4. join('//computer/share/', '/a') == '//computer/share/a'
123 # But b wins in all of these cases:
124 # 5. join('c:/a', '/b') == '/b'
125 # 6. join('//computer/share/a', '/b') == '/b'
126 # 7. join('c:', 'd:/') == 'd:/'
127 # 8. join('c:', '//computer/share/') == '//computer/share/'
128 # 9. join('//computer/share', 'd:/') == 'd:/'
129 # 10. join('//computer/share', '//computer/share/') == '//computer/share/'
130 # 11. join('c:/', 'd:/') == 'd:/'
131 # 12. join('c:/', '//computer/share/') == '//computer/share/'
132 # 13. join('//computer/share/', 'd:/') == 'd:/'
133 # 14. join('//computer/share/', '//computer/share/') == '//computer/share/'
134 b_prefix, b_rest = splitdrive(b)
Tim Peters1bdd0f22001-07-19 17:18:18 +0000135
Mark Hammond5a607a32009-05-06 08:04:54 +0000136 # if b has a prefix, it always wins.
137 if b_prefix:
Tim Peters33dc0a12001-07-27 08:09:54 +0000138 b_wins = 1
Mark Hammond5a607a32009-05-06 08:04:54 +0000139 else:
140 # b doesn't have a prefix.
141 # but isabs(b) returned true.
142 # and therefore b_rest[0] must be a slash.
143 # (but let's check that.)
144 assert(b_rest and b_rest[0] in seps)
145
146 # so, b still wins if path has a rest that's more than a sep.
147 # you get a+b if path_rest is empty or only has a sep.
148 # (see cases 1-4 for times when b loses.)
149 path_rest = splitdrive(path)[1]
150 b_wins = path_rest and path_rest not in seps
Tim Peters1bdd0f22001-07-19 17:18:18 +0000151
Tim Peters33dc0a12001-07-27 08:09:54 +0000152 if b_wins:
153 path = b
154 else:
155 # Join, and ensure there's a separator.
156 assert len(path) > 0
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000157 if path[-1:] in seps:
158 if b and b[:1] in seps:
Tim Peters33dc0a12001-07-27 08:09:54 +0000159 path += b[1:]
160 else:
161 path += b
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000162 elif path[-1:] == colon:
Tim Peters33dc0a12001-07-27 08:09:54 +0000163 path += b
164 elif b:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000165 if b[:1] in seps:
Tim Peters33dc0a12001-07-27 08:09:54 +0000166 path += b
167 else:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000168 path += sep + b
Tim Peters6a3e5f12001-11-05 21:25:02 +0000169 else:
170 # path is not empty and does not end with a backslash,
171 # but b is empty; since, e.g., split('a/') produces
172 # ('a', ''), it's best if join() adds a backslash in
173 # this case.
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000174 path += sep
Tim Peters1bdd0f22001-07-19 17:18:18 +0000175
Guido van Rossum15e22e11997-12-05 19:03:01 +0000176 return path
Guido van Rossum555915a1994-02-24 11:32:59 +0000177
178
179# Split a path in a drive specification (a drive letter followed by a
Guido van Rossumf3c695c1999-04-06 19:32:19 +0000180# colon) and the path specification.
Guido van Rossum555915a1994-02-24 11:32:59 +0000181# It is always true that drivespec + pathspec == p
182def splitdrive(p):
Mark Hammond5a607a32009-05-06 08:04:54 +0000183 """Split a pathname into drive/UNC sharepoint and relative path specifiers.
184 Returns a 2-tuple (drive_or_unc, path); either part may be empty.
185
186 If you assign
187 result = splitdrive(p)
188 It is always true that:
189 result[0] + result[1] == p
190
191 If the path contained a drive letter, drive_or_unc will contain everything
192 up to and including the colon. e.g. splitdrive("c:/dir") returns ("c:", "/dir")
193
194 If the path contained a UNC path, the drive_or_unc will contain the host name
195 and share up to but not including the fourth directory separator character.
196 e.g. splitdrive("//host/computer/dir") returns ("//host/computer", "/dir")
197
198 Paths cannot contain both a drive letter and a UNC path.
199
200 """
201 empty = _get_empty(p)
202 if len(p) > 1:
203 sep = _get_sep(p)
204 normp = normcase(p)
205 if (normp[0:2] == sep*2) and (normp[2:3] != sep):
206 # is a UNC path:
207 # vvvvvvvvvvvvvvvvvvvv drive letter or UNC path
208 # \\machine\mountpoint\directory\etc\...
209 # directory ^^^^^^^^^^^^^^^
210 index = normp.find(sep, 2)
211 if index == -1:
212 return empty, p
213 index2 = normp.find(sep, index + 1)
214 # a UNC path can't have two slashes in a row
215 # (after the initial two)
216 if index2 == index + 1:
217 return empty, p
218 if index2 == -1:
219 index2 = len(p)
220 return p[:index2], p[index2:]
221 if normp[1:2] == _get_colon(p):
222 return p[:2], p[2:]
223 return empty, p
Guido van Rossumf3c695c1999-04-06 19:32:19 +0000224
225
226# Parse UNC paths
227def splitunc(p):
Mark Hammond5a607a32009-05-06 08:04:54 +0000228 """Deprecated since Python 3.1. Please use splitdrive() instead;
229 it now handles UNC paths.
230
231 Split a pathname into UNC mount point and relative path specifiers.
Guido van Rossumf3c695c1999-04-06 19:32:19 +0000232
233 Return a 2-tuple (unc, rest); either part may be empty.
234 If unc is not empty, it has the form '//host/mount' (or similar
235 using backslashes). unc+rest is always the input path.
236 Paths containing drive letters never have an UNC part.
237 """
Mark Hammond5a607a32009-05-06 08:04:54 +0000238 import warnings
239 warnings.warn("ntpath.splitunc is deprecated, use ntpath.splitdrive instead",
Gregory P. Smithaa3b5b82009-06-30 05:33:50 +0000240 DeprecationWarning)
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000241 sep = _get_sep(p)
242 if not p[1:2]:
243 return p[:0], p # Drive letter present
Guido van Rossum534972b1999-02-03 17:20:50 +0000244 firstTwo = p[0:2]
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000245 if normcase(firstTwo) == sep + sep:
Guido van Rossum534972b1999-02-03 17:20:50 +0000246 # is a UNC path:
247 # vvvvvvvvvvvvvvvvvvvv equivalent to drive letter
248 # \\machine\mountpoint\directories...
249 # directory ^^^^^^^^^^^^^^^
250 normp = normcase(p)
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000251 index = normp.find(sep, 2)
Guido van Rossum534972b1999-02-03 17:20:50 +0000252 if index == -1:
253 ##raise RuntimeError, 'illegal UNC path: "' + p + '"'
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000254 return (p[:0], p)
255 index = normp.find(sep, index + 1)
Guido van Rossum534972b1999-02-03 17:20:50 +0000256 if index == -1:
257 index = len(p)
258 return p[:index], p[index:]
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000259 return p[:0], p
Guido van Rossum555915a1994-02-24 11:32:59 +0000260
261
262# Split a path in head (everything up to the last '/') and tail (the
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000263# rest). After the trailing '/' is stripped, the invariant
Guido van Rossum555915a1994-02-24 11:32:59 +0000264# join(head, tail) == p holds.
265# The resulting head won't end in '/' unless it is the root.
266
267def split(p):
Guido van Rossum534972b1999-02-03 17:20:50 +0000268 """Split a pathname.
269
270 Return tuple (head, tail) where tail is everything after the final slash.
271 Either part may be empty."""
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000272
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000273 seps = _get_bothseps(p)
Guido van Rossum15e22e11997-12-05 19:03:01 +0000274 d, p = splitdrive(p)
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000275 # set i to index beyond p's last slash
276 i = len(p)
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000277 while i and p[i-1] not in seps:
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000278 i = i - 1
279 head, tail = p[:i], p[i:] # now tail has no slashes
280 # remove trailing slashes from head, unless it's all slashes
281 head2 = head
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000282 while head2 and head2[-1:] in seps:
Guido van Rossum8f0fa9e1999-03-19 21:05:12 +0000283 head2 = head2[:-1]
284 head = head2 or head
Guido van Rossum15e22e11997-12-05 19:03:01 +0000285 return d + head, tail
Guido van Rossum555915a1994-02-24 11:32:59 +0000286
287
288# Split a path in root and extension.
Guido van Rossum73e122f1997-01-22 00:17:26 +0000289# The extension is everything starting at the last dot in the last
Guido van Rossum555915a1994-02-24 11:32:59 +0000290# pathname component; the root is everything before that.
291# It is always true that root + ext == p.
292
293def splitext(p):
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000294 return genericpath._splitext(p, _get_sep(p), _get_altsep(p),
295 _get_dot(p))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000296splitext.__doc__ = genericpath._splitext.__doc__
Guido van Rossum555915a1994-02-24 11:32:59 +0000297
298
299# Return the tail (basename) part of a path.
300
301def basename(p):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000302 """Returns the final component of a pathname"""
303 return split(p)[1]
Guido van Rossum555915a1994-02-24 11:32:59 +0000304
305
306# Return the head (dirname) part of a path.
307
308def dirname(p):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000309 """Returns the directory component of a pathname"""
310 return split(p)[0]
Guido van Rossum555915a1994-02-24 11:32:59 +0000311
Guido van Rossum555915a1994-02-24 11:32:59 +0000312# Is a path a symbolic link?
Brian Curtind40e6f72010-07-08 21:39:08 +0000313# This will always return false on systems where os.lstat doesn't exist.
Guido van Rossum555915a1994-02-24 11:32:59 +0000314
315def islink(path):
Brian Curtind40e6f72010-07-08 21:39:08 +0000316 """Test whether a path is a symbolic link.
317 This will always return false for Windows prior to 6.0
318 and for OS/2.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000319 """
Brian Curtind40e6f72010-07-08 21:39:08 +0000320 try:
321 st = os.lstat(path)
322 except (os.error, AttributeError):
323 return False
324 return stat.S_ISLNK(st.st_mode)
Guido van Rossum555915a1994-02-24 11:32:59 +0000325
Brian Curtind40e6f72010-07-08 21:39:08 +0000326# Being true for dangling symbolic links is also useful.
327
328def lexists(path):
329 """Test whether a path exists. Returns True for broken symbolic links"""
330 try:
331 st = os.lstat(path)
332 except (os.error, WindowsError):
333 return False
334 return True
Johannes Gijsbersae882f72004-08-30 10:19:56 +0000335
Guido van Rossumf3c695c1999-04-06 19:32:19 +0000336# Is a path a mount point? Either a root (with or without drive letter)
337# or an UNC path with at most a / or \ after the mount point.
Guido van Rossum555915a1994-02-24 11:32:59 +0000338
339def ismount(path):
Guido van Rossumca99c2c1998-01-19 22:25:59 +0000340 """Test whether a path is a mount point (defined as root of drive)"""
Benjamin Peterson48e24782009-03-29 13:02:52 +0000341 seps = _get_bothseps(path)
Mark Hammond5a607a32009-05-06 08:04:54 +0000342 root, rest = splitdrive(path)
343 if root and root[0] in seps:
344 return (not rest) or (rest in seps)
345 return rest in seps
Guido van Rossum555915a1994-02-24 11:32:59 +0000346
347
Guido van Rossum555915a1994-02-24 11:32:59 +0000348# Expand paths beginning with '~' or '~user'.
349# '~' means $HOME; '~user' means that user's home directory.
350# If the path doesn't begin with '~', or if the user or $HOME is unknown,
351# the path is returned unchanged (leaving error reporting to whatever
352# function is called with the expanded path as argument).
353# See also module 'glob' for expansion of *, ? and [...] in pathnames.
354# (A function should also be defined to do full *sh-style environment
355# variable expansion.)
356
357def expanduser(path):
Guido van Rossum534972b1999-02-03 17:20:50 +0000358 """Expand ~ and ~user constructs.
359
360 If user or $HOME is unknown, do nothing."""
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000361 if isinstance(path, bytes):
362 tilde = b'~'
363 else:
364 tilde = '~'
365 if not path.startswith(tilde):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000366 return path
367 i, n = 1, len(path)
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000368 while i < n and path[i] not in _get_bothseps(path):
Fred Drakeb4e460a2000-09-28 16:25:20 +0000369 i = i + 1
Guido van Rossumd8faa362007-04-27 19:54:29 +0000370
371 if 'HOME' in os.environ:
372 userhome = os.environ['HOME']
373 elif 'USERPROFILE' in os.environ:
374 userhome = os.environ['USERPROFILE']
375 elif not 'HOMEPATH' in os.environ:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000376 return path
Guido van Rossumd8faa362007-04-27 19:54:29 +0000377 else:
378 try:
379 drive = os.environ['HOMEDRIVE']
380 except KeyError:
381 drive = ''
382 userhome = join(drive, os.environ['HOMEPATH'])
383
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000384 if isinstance(path, bytes):
385 userhome = userhome.encode(sys.getfilesystemencoding())
386
Guido van Rossumd8faa362007-04-27 19:54:29 +0000387 if i != 1: #~user
388 userhome = join(dirname(userhome), path[1:i])
389
Guido van Rossum15e22e11997-12-05 19:03:01 +0000390 return userhome + path[i:]
Guido van Rossum555915a1994-02-24 11:32:59 +0000391
392
393# Expand paths containing shell variable substitutions.
394# The following rules apply:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000395# - no expansion within single quotes
Guido van Rossumd8faa362007-04-27 19:54:29 +0000396# - '$$' is translated into '$'
397# - '%%' is translated into '%' if '%%' are not seen in %var1%%var2%
Guido van Rossum15e22e11997-12-05 19:03:01 +0000398# - ${varname} is accepted.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000399# - $varname is accepted.
400# - %varname% is accepted.
401# - varnames can be made out of letters, digits and the characters '_-'
402# (though is not verifed in the ${varname} and %varname% cases)
Guido van Rossum555915a1994-02-24 11:32:59 +0000403# XXX With COMMAND.COM you can use any characters in a variable name,
404# XXX except '^|<>='.
405
Tim Peters2344fae2001-01-15 00:50:52 +0000406def expandvars(path):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000407 """Expand shell variables of the forms $var, ${var} and %var%.
Guido van Rossum534972b1999-02-03 17:20:50 +0000408
409 Unknown variables are left unchanged."""
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000410 if isinstance(path, bytes):
411 if ord('$') not in path and ord('%') not in path:
412 return path
413 import string
414 varchars = bytes(string.ascii_letters + string.digits + '_-', 'ascii')
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000415 quote = b'\''
416 percent = b'%'
417 brace = b'{'
418 dollar = b'$'
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000419 else:
420 if '$' not in path and '%' not in path:
421 return path
422 import string
423 varchars = string.ascii_letters + string.digits + '_-'
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000424 quote = '\''
425 percent = '%'
426 brace = '{'
427 dollar = '$'
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000428 res = path[:0]
Guido van Rossum15e22e11997-12-05 19:03:01 +0000429 index = 0
430 pathlen = len(path)
431 while index < pathlen:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000432 c = path[index:index+1]
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000433 if c == quote: # no expansion within single quotes
Guido van Rossum15e22e11997-12-05 19:03:01 +0000434 path = path[index + 1:]
435 pathlen = len(path)
436 try:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000437 index = path.index(c)
438 res = res + c + path[:index + 1]
Fred Drakeb4e460a2000-09-28 16:25:20 +0000439 except ValueError:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000440 res = res + path
Fred Drakeb4e460a2000-09-28 16:25:20 +0000441 index = pathlen - 1
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000442 elif c == percent: # variable or '%'
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000443 if path[index + 1:index + 2] == percent:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000444 res = res + c
445 index = index + 1
446 else:
447 path = path[index+1:]
448 pathlen = len(path)
449 try:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000450 index = path.index(percent)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000451 except ValueError:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000452 res = res + percent + path
Guido van Rossumd8faa362007-04-27 19:54:29 +0000453 index = pathlen - 1
454 else:
455 var = path[:index]
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000456 if isinstance(path, bytes):
457 var = var.decode('ascii')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000458 if var in os.environ:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000459 value = os.environ[var]
Guido van Rossumd8faa362007-04-27 19:54:29 +0000460 else:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000461 value = '%' + var + '%'
462 if isinstance(path, bytes):
463 value = value.encode('ascii')
464 res = res + value
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000465 elif c == dollar: # variable or '$$'
466 if path[index + 1:index + 2] == dollar:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000467 res = res + c
468 index = index + 1
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000469 elif path[index + 1:index + 2] == brace:
Guido van Rossum15e22e11997-12-05 19:03:01 +0000470 path = path[index+2:]
471 pathlen = len(path)
472 try:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000473 if isinstance(path, bytes):
474 index = path.index(b'}')
Thomas Woutersb2137042007-02-01 18:02:27 +0000475 else:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000476 index = path.index('}')
477 var = path[:index]
478 if isinstance(path, bytes):
479 var = var.decode('ascii')
480 if var in os.environ:
481 value = os.environ[var]
482 else:
483 value = '${' + var + '}'
484 if isinstance(path, bytes):
485 value = value.encode('ascii')
486 res = res + value
Fred Drakeb4e460a2000-09-28 16:25:20 +0000487 except ValueError:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000488 if isinstance(path, bytes):
489 res = res + b'${' + path
490 else:
491 res = res + '${' + path
Guido van Rossum15e22e11997-12-05 19:03:01 +0000492 index = pathlen - 1
493 else:
494 var = ''
495 index = index + 1
496 c = path[index:index + 1]
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000497 while c and c in varchars:
498 if isinstance(path, bytes):
499 var = var + c.decode('ascii')
500 else:
501 var = var + c
Guido van Rossum15e22e11997-12-05 19:03:01 +0000502 index = index + 1
503 c = path[index:index + 1]
Raymond Hettinger54f02222002-06-01 14:18:47 +0000504 if var in os.environ:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000505 value = os.environ[var]
Thomas Woutersb2137042007-02-01 18:02:27 +0000506 else:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000507 value = '$' + var
508 if isinstance(path, bytes):
509 value = value.encode('ascii')
510 res = res + value
511 if c:
Thomas Woutersb2137042007-02-01 18:02:27 +0000512 index = index - 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000513 else:
514 res = res + c
515 index = index + 1
516 return res
Guido van Rossum555915a1994-02-24 11:32:59 +0000517
518
Tim Peters54a14a32001-08-30 22:05:26 +0000519# 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 +0000520# Previously, this function also truncated pathnames to 8+3 format,
521# but as this module is called "ntpath", that's obviously wrong!
Guido van Rossum555915a1994-02-24 11:32:59 +0000522
523def normpath(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000524 """Normalize path, eliminating double slashes, etc."""
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000525 sep = _get_sep(path)
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000526 dotdot = _get_dot(path) * 2
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000527 path = path.replace(_get_altsep(path), sep)
Guido van Rossum15e22e11997-12-05 19:03:01 +0000528 prefix, path = splitdrive(path)
Mark Hammond5a607a32009-05-06 08:04:54 +0000529
530 # collapse initial backslashes
531 if path.startswith(sep):
532 prefix = prefix + sep
533 path = path.lstrip(sep)
534
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000535 comps = path.split(sep)
Guido van Rossum15e22e11997-12-05 19:03:01 +0000536 i = 0
537 while i < len(comps):
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000538 if not comps[i] or comps[i] == _get_dot(path):
Guido van Rossum15e22e11997-12-05 19:03:01 +0000539 del comps[i]
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000540 elif comps[i] == dotdot:
541 if i > 0 and comps[i-1] != dotdot:
Tim Peters54a14a32001-08-30 22:05:26 +0000542 del comps[i-1:i+1]
543 i -= 1
Amaury Forgeot d'Arc3b44e612008-10-03 20:32:33 +0000544 elif i == 0 and prefix.endswith(_get_sep(path)):
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000545 del comps[i]
546 else:
547 i += 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000548 else:
Tim Peters54a14a32001-08-30 22:05:26 +0000549 i += 1
Guido van Rossum15e22e11997-12-05 19:03:01 +0000550 # If the path is now empty, substitute '.'
551 if not prefix and not comps:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000552 comps.append(_get_dot(path))
553 return prefix + sep.join(comps)
Guido van Rossume294cf61999-01-29 18:05:18 +0000554
555
556# Return an absolute path.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000557try:
558 from nt import _getfullpathname
Mark Hammondf717f052002-01-17 00:44:26 +0000559
Thomas Wouters477c8d52006-05-27 19:21:47 +0000560except ImportError: # not running on Windows - mock up something sensible
561 def abspath(path):
562 """Return the absolute version of a path."""
563 if not isabs(path):
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000564 if isinstance(path, bytes):
565 cwd = os.getcwdb()
566 else:
567 cwd = os.getcwd()
568 path = join(cwd, path)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000569 return normpath(path)
570
571else: # use native Windows method on Windows
572 def abspath(path):
573 """Return the absolute version of a path."""
574
575 if path: # Empty path must return current working directory.
576 try:
577 path = _getfullpathname(path)
578 except WindowsError:
579 pass # Bad path - return unchanged.
Florent Xiclunaad8c5ca2010-03-08 14:44:41 +0000580 elif isinstance(path, bytes):
581 path = os.getcwdb()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000582 else:
583 path = os.getcwd()
584 return normpath(path)
Guido van Rossum83eeef42001-09-17 15:16:09 +0000585
586# realpath is a no-op on systems without islink support
587realpath = abspath
Mark Hammond8696ebc2002-10-08 02:44:31 +0000588# Win9x family and earlier have no Unicode filename support.
Tim Peters26bc25a2002-10-09 07:56:04 +0000589supports_unicode_filenames = (hasattr(sys, "getwindowsversion") and
590 sys.getwindowsversion()[3] >= 2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000591
592def relpath(path, start=curdir):
593 """Return a relative version of a path"""
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000594 sep = _get_sep(path)
595
596 if start is curdir:
597 start = _get_dot(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000598
599 if not path:
600 raise ValueError("no path specified")
Mark Hammond5a607a32009-05-06 08:04:54 +0000601
602 start_abs = abspath(normpath(start))
603 path_abs = abspath(normpath(path))
604 start_drive, start_rest = splitdrive(start_abs)
605 path_drive, path_rest = splitdrive(path_abs)
606 if start_drive != path_drive:
607 error = "path is on mount '{0}', start on mount '{1}'".format(
608 path_drive, start_drive)
609 raise ValueError(error)
610
611 start_list = [x for x in start_rest.split(sep) if x]
612 path_list = [x for x in path_rest.split(sep) if x]
Guido van Rossumd8faa362007-04-27 19:54:29 +0000613 # Work out how much of the filepath is shared by start and path.
Mark Hammond5a607a32009-05-06 08:04:54 +0000614 i = 0
615 for e1, e2 in zip(start_list, path_list):
616 if e1 != e2:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000617 break
Guido van Rossumd8faa362007-04-27 19:54:29 +0000618 i += 1
619
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000620 if isinstance(path, bytes):
621 pardir = b'..'
622 else:
623 pardir = '..'
Guido van Rossumd8faa362007-04-27 19:54:29 +0000624 rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
Christian Heimesfaf2f632008-01-06 16:59:19 +0000625 if not rel_list:
Amaury Forgeot d'Arcc72ef8b2008-10-03 18:38:26 +0000626 return _get_dot(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000627 return join(*rel_list)
Brian Curtind40e6f72010-07-08 21:39:08 +0000628
629
630# determine if two files are in fact the same file
631def samefile(f1, f2):
632 "Test whether two pathnames reference the same actual file"
633 try:
634 from nt import _getfinalpathname
635 return _getfinalpathname(f1) == _getfinalpathname(f2)
636 except (NotImplementedError, ImportError):
637 # On Windows XP and earlier, two files are the same if their
638 # absolute pathnames are the same.
639 # Also, on other operating systems, fake this method with a
640 # Windows-XP approximation.
641 return abspath(f1) == abspath(f2)