blob: 44ed8383f2e4509e75298cc19fad1245d1eddcf4 [file] [log] [blame]
Guido van Rossum54f22ed2000-02-04 15:10:34 +00001"""Common operations on Posix pathnames.
2
3Instead of importing this module directly, import os and refer to
4this module as os.path. The "os.path" name is an alias for this
5module on Posix systems; on other systems (e.g. Mac, Windows),
6os.path provides the same operations in a manner specific to that
7platform, and is an alias to another module (e.g. macpath, ntpath).
8
9Some of this can actually be useful on non-Posix systems too, e.g.
10for manipulation of the pathname component of URLs.
Guido van Rossum346f7af1997-12-05 19:04:51 +000011"""
Guido van Rossumc6360141990-10-13 19:23:40 +000012
Guido van Rossumd3876d31996-07-23 03:47:28 +000013import os
Guido van Rossumf0af3e32008-10-02 18:55:37 +000014import sys
Guido van Rossum40d93041990-10-21 16:17:34 +000015import stat
Guido van Rossumd8faa362007-04-27 19:54:29 +000016import genericpath
Thomas Wouters89f507f2006-12-13 04:49:30 +000017from genericpath import *
Guido van Rossumc6360141990-10-13 19:23:40 +000018
Skip Montanaroc62c81e2001-02-12 02:00:42 +000019__all__ = ["normcase","isabs","join","splitdrive","split","splitext",
20 "basename","dirname","commonprefix","getsize","getmtime",
Georg Brandlf0de6a12005-08-22 18:02:59 +000021 "getatime","getctime","islink","exists","lexists","isdir","isfile",
Benjamin Petersond71ca412008-05-08 23:44:58 +000022 "ismount", "expanduser","expandvars","normpath","abspath",
Neal Norwitz61cdac62003-01-03 18:01:57 +000023 "samefile","sameopenfile","samestat",
Skip Montanaro117910d2003-02-14 19:35:31 +000024 "curdir","pardir","sep","pathsep","defpath","altsep","extsep",
Guido van Rossumd8faa362007-04-27 19:54:29 +000025 "devnull","realpath","supports_unicode_filenames","relpath"]
Guido van Rossumc6360141990-10-13 19:23:40 +000026
Guido van Rossumf0af3e32008-10-02 18:55:37 +000027# Strings representing various path-related bits and pieces.
28# These are primarily for export; internally, they are hardcoded.
Skip Montanaro117910d2003-02-14 19:35:31 +000029curdir = '.'
30pardir = '..'
31extsep = '.'
32sep = '/'
33pathsep = ':'
34defpath = ':/bin:/usr/bin'
35altsep = None
Martin v. Löwisbdec50f2004-06-08 08:29:33 +000036devnull = '/dev/null'
Skip Montanaro117910d2003-02-14 19:35:31 +000037
Guido van Rossumf0af3e32008-10-02 18:55:37 +000038def _get_sep(path):
39 if isinstance(path, bytes):
40 return b'/'
41 else:
42 return '/'
43
Guido van Rossum7ac48781992-01-14 18:29:32 +000044# Normalize the case of a pathname. Trivial in Posix, string.lower on Mac.
45# On MS-DOS this may also turn slashes into backslashes; however, other
46# normalizations (such as optimizing '../' away) are not allowed
47# (another function should be defined to do that).
48
49def normcase(s):
Guido van Rossum346f7af1997-12-05 19:04:51 +000050 """Normalize case of pathname. Has no effect under Posix"""
Ezio Melotti5a3ef5b2010-06-25 10:56:11 +000051 if not isinstance(s, (bytes, str)):
52 raise TypeError("normcase() argument must be str or bytes, "
53 "not '{}'".format(s.__class__.__name__))
Guido van Rossum346f7af1997-12-05 19:04:51 +000054 return s
Guido van Rossum7ac48781992-01-14 18:29:32 +000055
56
Jeremy Hyltona05e2932000-06-28 14:48:01 +000057# Return whether a path is absolute.
Guido van Rossum7ac48781992-01-14 18:29:32 +000058# Trivial in Posix, harder on the Mac or MS-DOS.
59
60def isabs(s):
Guido van Rossum346f7af1997-12-05 19:04:51 +000061 """Test whether a path is absolute"""
Guido van Rossumf0af3e32008-10-02 18:55:37 +000062 sep = _get_sep(s)
63 return s.startswith(sep)
Guido van Rossum7ac48781992-01-14 18:29:32 +000064
65
Barry Warsaw384d2491997-02-18 21:53:25 +000066# Join pathnames.
67# Ignore the previous parts if a part is absolute.
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000068# Insert a '/' unless the first part is empty or already ends in '/'.
Guido van Rossum7ac48781992-01-14 18:29:32 +000069
Barry Warsaw384d2491997-02-18 21:53:25 +000070def join(a, *p):
Guido van Rossum04110fb2007-08-24 16:32:05 +000071 """Join two or more pathname components, inserting '/' as needed.
72 If any component is an absolute path, all previous path components
R David Murraye3de1752012-07-21 14:33:56 -040073 will be discarded. An empty last part will result in a path that
74 ends with a separator."""
Guido van Rossumf0af3e32008-10-02 18:55:37 +000075 sep = _get_sep(a)
Guido van Rossum346f7af1997-12-05 19:04:51 +000076 path = a
Hynek Schlawack47749462012-07-15 16:21:30 +020077 try:
78 for b in p:
79 if b.startswith(sep):
80 path = b
81 elif not path or path.endswith(sep):
82 path += b
83 else:
84 path += sep + b
Serhiy Storchaka3deeeb02014-10-04 14:58:43 +030085 except (TypeError, AttributeError, BytesWarning):
86 genericpath._check_arg_types('join', a, *p)
87 raise
Guido van Rossum346f7af1997-12-05 19:04:51 +000088 return path
Guido van Rossumc6360141990-10-13 19:23:40 +000089
90
Guido van Rossum26847381992-03-31 18:54:35 +000091# Split a path in head (everything up to the last '/') and tail (the
Guido van Rossuma89b1ba1995-09-01 20:32:21 +000092# rest). If the path ends in '/', tail will be empty. If there is no
93# '/' in the path, head will be empty.
94# Trailing '/'es are stripped from head unless it is the root.
Guido van Rossum7ac48781992-01-14 18:29:32 +000095
Guido van Rossumc6360141990-10-13 19:23:40 +000096def split(p):
Tim Peters2344fae2001-01-15 00:50:52 +000097 """Split a pathname. Returns tuple "(head, tail)" where "tail" is
Fred Drakec0ab93e2000-09-28 16:22:52 +000098 everything after the final slash. Either part may be empty."""
Guido van Rossumf0af3e32008-10-02 18:55:37 +000099 sep = _get_sep(p)
100 i = p.rfind(sep) + 1
Guido van Rossum346f7af1997-12-05 19:04:51 +0000101 head, tail = p[:i], p[i:]
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000102 if head and head != sep*len(head):
103 head = head.rstrip(sep)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000104 return head, tail
Guido van Rossumc6360141990-10-13 19:23:40 +0000105
106
Guido van Rossum4d0fdc31991-08-16 13:27:58 +0000107# Split a path in root and extension.
Guido van Rossum422869a1996-08-20 20:24:17 +0000108# The extension is everything starting at the last dot in the last
Guido van Rossum4d0fdc31991-08-16 13:27:58 +0000109# pathname component; the root is everything before that.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000110# It is always true that root + ext == p.
111
Guido van Rossum4d0fdc31991-08-16 13:27:58 +0000112def splitext(p):
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000113 if isinstance(p, bytes):
114 sep = b'/'
115 extsep = b'.'
116 else:
117 sep = '/'
118 extsep = '.'
119 return genericpath._splitext(p, sep, None, extsep)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000120splitext.__doc__ = genericpath._splitext.__doc__
Guido van Rossum4d0fdc31991-08-16 13:27:58 +0000121
Guido van Rossum221df241995-08-07 20:17:55 +0000122# Split a pathname into a drive specification and the rest of the
123# path. Useful on DOS/Windows/NT; on Unix, the drive is always empty.
124
125def splitdrive(p):
Tim Peters2344fae2001-01-15 00:50:52 +0000126 """Split a pathname into drive and path. On Posix, drive is always
Fred Drakec0ab93e2000-09-28 16:22:52 +0000127 empty."""
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000128 return p[:0], p
Guido van Rossum221df241995-08-07 20:17:55 +0000129
130
Thomas Wouters89f507f2006-12-13 04:49:30 +0000131# Return the tail (basename) part of a path, same as split(path)[1].
Guido van Rossum7ac48781992-01-14 18:29:32 +0000132
Guido van Rossumc6360141990-10-13 19:23:40 +0000133def basename(p):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000134 """Returns the final component of a pathname"""
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000135 sep = _get_sep(p)
136 i = p.rfind(sep) + 1
Thomas Wouters89f507f2006-12-13 04:49:30 +0000137 return p[i:]
Guido van Rossumc6360141990-10-13 19:23:40 +0000138
139
Thomas Wouters89f507f2006-12-13 04:49:30 +0000140# Return the head (dirname) part of a path, same as split(path)[0].
Guido van Rossumc629d341992-11-05 10:43:02 +0000141
142def dirname(p):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000143 """Returns the directory component of a pathname"""
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000144 sep = _get_sep(p)
145 i = p.rfind(sep) + 1
Thomas Wouters89f507f2006-12-13 04:49:30 +0000146 head = p[:i]
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000147 if head and head != sep*len(head):
148 head = head.rstrip(sep)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000149 return head
Guido van Rossumc629d341992-11-05 10:43:02 +0000150
151
Guido van Rossum7ac48781992-01-14 18:29:32 +0000152# Is a path a symbolic link?
Guido van Rossumd3876d31996-07-23 03:47:28 +0000153# This will always return false on systems where os.lstat doesn't exist.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000154
155def islink(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000156 """Test whether a path is a symbolic link"""
157 try:
158 st = os.lstat(path)
Andrew Svetlovad28c7f2012-12-18 22:02:39 +0200159 except (OSError, AttributeError):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000160 return False
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000161 return stat.S_ISLNK(st.st_mode)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000162
Johannes Gijsbersae882f72004-08-30 10:19:56 +0000163# Being true for dangling symbolic links is also useful.
164
165def lexists(path):
166 """Test whether a path exists. Returns True for broken symbolic links"""
167 try:
Georg Brandl89fad142010-03-14 10:23:39 +0000168 os.lstat(path)
Andrew Svetlovad28c7f2012-12-18 22:02:39 +0200169 except OSError:
Johannes Gijsbersae882f72004-08-30 10:19:56 +0000170 return False
171 return True
172
173
Guido van Rossumc6360141990-10-13 19:23:40 +0000174# Is a path a mount point?
Guido van Rossumd3876d31996-07-23 03:47:28 +0000175# (Does this work for all UNIXes? Is it even guaranteed to work by Posix?)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000176
Guido van Rossumc6360141990-10-13 19:23:40 +0000177def ismount(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000178 """Test whether a path is a mount point"""
179 try:
Christian Heimesfaf2f632008-01-06 16:59:19 +0000180 s1 = os.lstat(path)
Brian Curtin06f6fbf2013-07-22 13:07:52 -0500181 except OSError:
182 # It doesn't exist -- so not a mount point. :-)
183 return False
184 else:
Brian Curtina3852ff2013-07-22 19:05:48 -0500185 # A symlink can never be a mount point
Brian Curtin06f6fbf2013-07-22 13:07:52 -0500186 if stat.S_ISLNK(s1.st_mode):
187 return False
188
189 if isinstance(path, bytes):
190 parent = join(path, b'..')
191 else:
192 parent = join(path, '..')
193 try:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000194 s2 = os.lstat(parent)
Andrew Svetlovad28c7f2012-12-18 22:02:39 +0200195 except OSError:
Brian Curtin06f6fbf2013-07-22 13:07:52 -0500196 return False
197
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000198 dev1 = s1.st_dev
199 dev2 = s2.st_dev
Guido van Rossum346f7af1997-12-05 19:04:51 +0000200 if dev1 != dev2:
Tim Petersbc0e9102002-04-04 22:55:58 +0000201 return True # path/.. on a different device as path
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000202 ino1 = s1.st_ino
203 ino2 = s2.st_ino
Guido van Rossum346f7af1997-12-05 19:04:51 +0000204 if ino1 == ino2:
Tim Petersbc0e9102002-04-04 22:55:58 +0000205 return True # path/.. is the same i-node as path
206 return False
Guido van Rossumc6360141990-10-13 19:23:40 +0000207
208
Guido van Rossum7ac48781992-01-14 18:29:32 +0000209# Expand paths beginning with '~' or '~user'.
210# '~' means $HOME; '~user' means that user's home directory.
211# If the path doesn't begin with '~', or if the user or $HOME is unknown,
212# the path is returned unchanged (leaving error reporting to whatever
213# function is called with the expanded path as argument).
214# See also module 'glob' for expansion of *, ? and [...] in pathnames.
215# (A function should also be defined to do full *sh-style environment
216# variable expansion.)
217
218def expanduser(path):
Tim Peters2344fae2001-01-15 00:50:52 +0000219 """Expand ~ and ~user constructions. If user or $HOME is unknown,
Fred Drakec0ab93e2000-09-28 16:22:52 +0000220 do nothing."""
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000221 if isinstance(path, bytes):
222 tilde = b'~'
223 else:
224 tilde = '~'
225 if not path.startswith(tilde):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000226 return path
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000227 sep = _get_sep(path)
228 i = path.find(sep, 1)
Walter Dörwalda9da5ae2003-06-19 10:21:14 +0000229 if i < 0:
230 i = len(path)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000231 if i == 1:
Walter Dörwalda9da5ae2003-06-19 10:21:14 +0000232 if 'HOME' not in os.environ:
Neal Norwitz609ba812002-09-05 21:08:25 +0000233 import pwd
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000234 userhome = pwd.getpwuid(os.getuid()).pw_dir
Neal Norwitz609ba812002-09-05 21:08:25 +0000235 else:
236 userhome = os.environ['HOME']
Guido van Rossum346f7af1997-12-05 19:04:51 +0000237 else:
238 import pwd
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000239 name = path[1:i]
240 if isinstance(name, bytes):
241 name = str(name, 'ASCII')
Guido van Rossum346f7af1997-12-05 19:04:51 +0000242 try:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000243 pwent = pwd.getpwnam(name)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000244 except KeyError:
245 return path
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000246 userhome = pwent.pw_dir
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000247 if isinstance(path, bytes):
Victor Stinner16004ac2010-09-29 16:59:18 +0000248 userhome = os.fsencode(userhome)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000249 root = b'/'
250 else:
251 root = '/'
Jesus Cea7f0d8882012-05-10 05:10:50 +0200252 userhome = userhome.rstrip(root)
253 return (userhome + path[i:]) or root
Guido van Rossum4732ccf1992-08-09 13:54:50 +0000254
255
256# Expand paths containing shell variable substitutions.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000257# This expands the forms $variable and ${variable} only.
Jeremy Hyltona05e2932000-06-28 14:48:01 +0000258# Non-existent variables are left unchanged.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000259
260_varprog = None
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000261_varprogb = None
Guido van Rossum4732ccf1992-08-09 13:54:50 +0000262
263def expandvars(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000264 """Expand shell variables of form $var and ${var}. Unknown variables
Fred Drakec0ab93e2000-09-28 16:22:52 +0000265 are left unchanged."""
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000266 global _varprog, _varprogb
267 if isinstance(path, bytes):
268 if b'$' not in path:
269 return path
270 if not _varprogb:
271 import re
272 _varprogb = re.compile(br'\$(\w+|\{[^}]*\})', re.ASCII)
273 search = _varprogb.search
274 start = b'{'
275 end = b'}'
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200276 environ = getattr(os, 'environb', None)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000277 else:
278 if '$' not in path:
279 return path
280 if not _varprog:
281 import re
282 _varprog = re.compile(r'\$(\w+|\{[^}]*\})', re.ASCII)
283 search = _varprog.search
284 start = '{'
285 end = '}'
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200286 environ = os.environ
Guido van Rossum346f7af1997-12-05 19:04:51 +0000287 i = 0
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000288 while True:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000289 m = search(path, i)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000290 if not m:
291 break
292 i, j = m.span(0)
293 name = m.group(1)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000294 if name.startswith(start) and name.endswith(end):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000295 name = name[1:-1]
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200296 try:
297 if environ is None:
Serhiy Storchakaffadbb72014-02-13 10:45:14 +0200298 value = os.fsencode(os.environ[os.fsdecode(name)])
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200299 else:
300 value = environ[name]
301 except KeyError:
302 i = j
303 else:
Guido van Rossum346f7af1997-12-05 19:04:51 +0000304 tail = path[j:]
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000305 path = path[:i] + value
Guido van Rossum346f7af1997-12-05 19:04:51 +0000306 i = len(path)
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000307 path += tail
Guido van Rossum346f7af1997-12-05 19:04:51 +0000308 return path
Guido van Rossumc629d341992-11-05 10:43:02 +0000309
310
311# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
312# It should be understood that this may change the meaning of the path
313# if it contains symbolic links!
314
315def normpath(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000316 """Normalize path, eliminating double slashes, etc."""
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000317 if isinstance(path, bytes):
318 sep = b'/'
319 empty = b''
320 dot = b'.'
321 dotdot = b'..'
322 else:
323 sep = '/'
324 empty = ''
325 dot = '.'
326 dotdot = '..'
327 if path == empty:
328 return dot
329 initial_slashes = path.startswith(sep)
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000330 # POSIX allows one or two initial slashes, but treats three or more
331 # as single slash.
Tim Peters658cba62001-02-09 20:06:00 +0000332 if (initial_slashes and
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000333 path.startswith(sep*2) and not path.startswith(sep*3)):
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000334 initial_slashes = 2
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000335 comps = path.split(sep)
Skip Montanaro018dfae2000-07-19 17:09:51 +0000336 new_comps = []
337 for comp in comps:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000338 if comp in (empty, dot):
Skip Montanaro018dfae2000-07-19 17:09:51 +0000339 continue
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000340 if (comp != dotdot or (not initial_slashes and not new_comps) or
341 (new_comps and new_comps[-1] == dotdot)):
Skip Montanaro018dfae2000-07-19 17:09:51 +0000342 new_comps.append(comp)
343 elif new_comps:
344 new_comps.pop()
345 comps = new_comps
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000346 path = sep.join(comps)
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000347 if initial_slashes:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000348 path = sep*initial_slashes + path
349 return path or dot
Guido van Rossume294cf61999-01-29 18:05:18 +0000350
351
Guido van Rossume294cf61999-01-29 18:05:18 +0000352def abspath(path):
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000353 """Return an absolute path."""
Guido van Rossume294cf61999-01-29 18:05:18 +0000354 if not isabs(path):
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000355 if isinstance(path, bytes):
356 cwd = os.getcwdb()
357 else:
358 cwd = os.getcwd()
359 path = join(cwd, path)
Guido van Rossume294cf61999-01-29 18:05:18 +0000360 return normpath(path)
Guido van Rossum83eeef42001-09-17 15:16:09 +0000361
362
363# Return a canonical path (i.e. the absolute location of a file on the
364# filesystem).
365
366def realpath(filename):
367 """Return the canonical path of the specified filename, eliminating any
368symbolic links encountered in the path."""
Serhiy Storchakadf326912013-02-10 12:22:07 +0200369 path, ok = _joinrealpath(filename[:0], filename, {})
370 return abspath(path)
371
372# Join two paths, normalizing ang eliminating any symbolic links
373# encountered in the second path.
374def _joinrealpath(path, rest, seen):
375 if isinstance(path, bytes):
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000376 sep = b'/'
Serhiy Storchakadf326912013-02-10 12:22:07 +0200377 curdir = b'.'
378 pardir = b'..'
Johannes Gijsbers4ec40642004-08-14 15:01:53 +0000379 else:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000380 sep = '/'
Serhiy Storchakadf326912013-02-10 12:22:07 +0200381 curdir = '.'
382 pardir = '..'
Tim Petersa45cacf2004-08-20 03:47:14 +0000383
Serhiy Storchakadf326912013-02-10 12:22:07 +0200384 if isabs(rest):
385 rest = rest[1:]
386 path = sep
387
388 while rest:
389 name, _, rest = rest.partition(sep)
390 if not name or name == curdir:
391 # current dir
392 continue
393 if name == pardir:
394 # parent dir
395 if path:
Serhiy Storchaka467393d2013-02-18 12:21:04 +0200396 path, name = split(path)
397 if name == pardir:
398 path = join(path, pardir, pardir)
Brett Cannonf50299c2004-07-10 22:55:15 +0000399 else:
Serhiy Storchaka467393d2013-02-18 12:21:04 +0200400 path = pardir
Serhiy Storchakadf326912013-02-10 12:22:07 +0200401 continue
402 newpath = join(path, name)
403 if not islink(newpath):
404 path = newpath
405 continue
406 # Resolve the symbolic link
407 if newpath in seen:
408 # Already seen this path
409 path = seen[newpath]
410 if path is not None:
411 # use cached value
412 continue
413 # The symlink is not resolved, so we must have a symlink loop.
414 # Return already resolved part + rest of the path unchanged.
415 return join(newpath, rest), False
416 seen[newpath] = None # not resolved symlink
417 path, ok = _joinrealpath(path, os.readlink(newpath), seen)
418 if not ok:
419 return join(path, rest), False
420 seen[newpath] = path # resolved symlink
Tim Petersb64bec32001-09-18 02:26:39 +0000421
Serhiy Storchakadf326912013-02-10 12:22:07 +0200422 return path, True
Tim Petersa45cacf2004-08-20 03:47:14 +0000423
Brett Cannonf50299c2004-07-10 22:55:15 +0000424
Victor Stinnere797c162010-09-17 23:34:26 +0000425supports_unicode_filenames = (sys.platform == 'darwin')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000426
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000427def relpath(path, start=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000428 """Return a relative version of a path"""
429
430 if not path:
431 raise ValueError("no path specified")
432
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000433 if isinstance(path, bytes):
434 curdir = b'.'
435 sep = b'/'
436 pardir = b'..'
437 else:
438 curdir = '.'
439 sep = '/'
440 pardir = '..'
441
442 if start is None:
443 start = curdir
444
Serhiy Storchaka3deeeb02014-10-04 14:58:43 +0300445 try:
446 start_list = [x for x in abspath(start).split(sep) if x]
447 path_list = [x for x in abspath(path).split(sep) if x]
448 # Work out how much of the filepath is shared by start and path.
449 i = len(commonprefix([start_list, path_list]))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000450
Serhiy Storchaka3deeeb02014-10-04 14:58:43 +0300451 rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
452 if not rel_list:
453 return curdir
454 return join(*rel_list)
Serhiy Storchakae4f47082014-10-04 16:09:02 +0300455 except (TypeError, AttributeError, BytesWarning, DeprecationWarning):
Serhiy Storchaka3deeeb02014-10-04 14:58:43 +0300456 genericpath._check_arg_types('relpath', path, start)
457 raise