blob: ea51e1183384b2f293a96594a30ebef38d7c2c97 [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",
Serhiy Storchaka38220932015-03-31 15:31:53 +030025 "devnull","realpath","supports_unicode_filenames","relpath",
26 "commonpath"]
Guido van Rossumc6360141990-10-13 19:23:40 +000027
Guido van Rossumf0af3e32008-10-02 18:55:37 +000028# Strings representing various path-related bits and pieces.
29# These are primarily for export; internally, they are hardcoded.
Skip Montanaro117910d2003-02-14 19:35:31 +000030curdir = '.'
31pardir = '..'
32extsep = '.'
33sep = '/'
34pathsep = ':'
35defpath = ':/bin:/usr/bin'
36altsep = None
Martin v. Löwisbdec50f2004-06-08 08:29:33 +000037devnull = '/dev/null'
Skip Montanaro117910d2003-02-14 19:35:31 +000038
Guido van Rossumf0af3e32008-10-02 18:55:37 +000039def _get_sep(path):
40 if isinstance(path, bytes):
41 return b'/'
42 else:
43 return '/'
44
Guido van Rossum7ac48781992-01-14 18:29:32 +000045# Normalize the case of a pathname. Trivial in Posix, string.lower on Mac.
46# On MS-DOS this may also turn slashes into backslashes; however, other
47# normalizations (such as optimizing '../' away) are not allowed
48# (another function should be defined to do that).
49
50def normcase(s):
Guido van Rossum346f7af1997-12-05 19:04:51 +000051 """Normalize case of pathname. Has no effect under Posix"""
Ezio Melotti5a3ef5b2010-06-25 10:56:11 +000052 if not isinstance(s, (bytes, str)):
53 raise TypeError("normcase() argument must be str or bytes, "
54 "not '{}'".format(s.__class__.__name__))
Guido van Rossum346f7af1997-12-05 19:04:51 +000055 return s
Guido van Rossum7ac48781992-01-14 18:29:32 +000056
57
Jeremy Hyltona05e2932000-06-28 14:48:01 +000058# Return whether a path is absolute.
Guido van Rossum7ac48781992-01-14 18:29:32 +000059# Trivial in Posix, harder on the Mac or MS-DOS.
60
61def isabs(s):
Guido van Rossum346f7af1997-12-05 19:04:51 +000062 """Test whether a path is absolute"""
Guido van Rossumf0af3e32008-10-02 18:55:37 +000063 sep = _get_sep(s)
64 return s.startswith(sep)
Guido van Rossum7ac48781992-01-14 18:29:32 +000065
66
Barry Warsaw384d2491997-02-18 21:53:25 +000067# Join pathnames.
68# Ignore the previous parts if a part is absolute.
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000069# Insert a '/' unless the first part is empty or already ends in '/'.
Guido van Rossum7ac48781992-01-14 18:29:32 +000070
Barry Warsaw384d2491997-02-18 21:53:25 +000071def join(a, *p):
Guido van Rossum04110fb2007-08-24 16:32:05 +000072 """Join two or more pathname components, inserting '/' as needed.
73 If any component is an absolute path, all previous path components
R David Murraye3de1752012-07-21 14:33:56 -040074 will be discarded. An empty last part will result in a path that
75 ends with a separator."""
Guido van Rossumf0af3e32008-10-02 18:55:37 +000076 sep = _get_sep(a)
Guido van Rossum346f7af1997-12-05 19:04:51 +000077 path = a
Hynek Schlawack47749462012-07-15 16:21:30 +020078 try:
79 for b in p:
80 if b.startswith(sep):
81 path = b
82 elif not path or path.endswith(sep):
83 path += b
84 else:
85 path += sep + b
Serhiy Storchaka3deeeb02014-10-04 14:58:43 +030086 except (TypeError, AttributeError, BytesWarning):
87 genericpath._check_arg_types('join', a, *p)
88 raise
Guido van Rossum346f7af1997-12-05 19:04:51 +000089 return path
Guido van Rossumc6360141990-10-13 19:23:40 +000090
91
Guido van Rossum26847381992-03-31 18:54:35 +000092# Split a path in head (everything up to the last '/') and tail (the
Guido van Rossuma89b1ba1995-09-01 20:32:21 +000093# rest). If the path ends in '/', tail will be empty. If there is no
94# '/' in the path, head will be empty.
95# Trailing '/'es are stripped from head unless it is the root.
Guido van Rossum7ac48781992-01-14 18:29:32 +000096
Guido van Rossumc6360141990-10-13 19:23:40 +000097def split(p):
Tim Peters2344fae2001-01-15 00:50:52 +000098 """Split a pathname. Returns tuple "(head, tail)" where "tail" is
Fred Drakec0ab93e2000-09-28 16:22:52 +000099 everything after the final slash. Either part may be empty."""
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000100 sep = _get_sep(p)
101 i = p.rfind(sep) + 1
Guido van Rossum346f7af1997-12-05 19:04:51 +0000102 head, tail = p[:i], p[i:]
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000103 if head and head != sep*len(head):
104 head = head.rstrip(sep)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000105 return head, tail
Guido van Rossumc6360141990-10-13 19:23:40 +0000106
107
Guido van Rossum4d0fdc31991-08-16 13:27:58 +0000108# Split a path in root and extension.
Guido van Rossum422869a1996-08-20 20:24:17 +0000109# The extension is everything starting at the last dot in the last
Guido van Rossum4d0fdc31991-08-16 13:27:58 +0000110# pathname component; the root is everything before that.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000111# It is always true that root + ext == p.
112
Guido van Rossum4d0fdc31991-08-16 13:27:58 +0000113def splitext(p):
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000114 if isinstance(p, bytes):
115 sep = b'/'
116 extsep = b'.'
117 else:
118 sep = '/'
119 extsep = '.'
120 return genericpath._splitext(p, sep, None, extsep)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000121splitext.__doc__ = genericpath._splitext.__doc__
Guido van Rossum4d0fdc31991-08-16 13:27:58 +0000122
Guido van Rossum221df241995-08-07 20:17:55 +0000123# Split a pathname into a drive specification and the rest of the
124# path. Useful on DOS/Windows/NT; on Unix, the drive is always empty.
125
126def splitdrive(p):
Tim Peters2344fae2001-01-15 00:50:52 +0000127 """Split a pathname into drive and path. On Posix, drive is always
Fred Drakec0ab93e2000-09-28 16:22:52 +0000128 empty."""
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000129 return p[:0], p
Guido van Rossum221df241995-08-07 20:17:55 +0000130
131
Thomas Wouters89f507f2006-12-13 04:49:30 +0000132# Return the tail (basename) part of a path, same as split(path)[1].
Guido van Rossum7ac48781992-01-14 18:29:32 +0000133
Guido van Rossumc6360141990-10-13 19:23:40 +0000134def basename(p):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000135 """Returns the final component of a pathname"""
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000136 sep = _get_sep(p)
137 i = p.rfind(sep) + 1
Thomas Wouters89f507f2006-12-13 04:49:30 +0000138 return p[i:]
Guido van Rossumc6360141990-10-13 19:23:40 +0000139
140
Thomas Wouters89f507f2006-12-13 04:49:30 +0000141# Return the head (dirname) part of a path, same as split(path)[0].
Guido van Rossumc629d341992-11-05 10:43:02 +0000142
143def dirname(p):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000144 """Returns the directory component of a pathname"""
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000145 sep = _get_sep(p)
146 i = p.rfind(sep) + 1
Thomas Wouters89f507f2006-12-13 04:49:30 +0000147 head = p[:i]
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000148 if head and head != sep*len(head):
149 head = head.rstrip(sep)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000150 return head
Guido van Rossumc629d341992-11-05 10:43:02 +0000151
152
Guido van Rossum7ac48781992-01-14 18:29:32 +0000153# Is a path a symbolic link?
Guido van Rossumd3876d31996-07-23 03:47:28 +0000154# This will always return false on systems where os.lstat doesn't exist.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000155
156def islink(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000157 """Test whether a path is a symbolic link"""
158 try:
159 st = os.lstat(path)
Andrew Svetlovad28c7f2012-12-18 22:02:39 +0200160 except (OSError, AttributeError):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000161 return False
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000162 return stat.S_ISLNK(st.st_mode)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000163
Johannes Gijsbersae882f72004-08-30 10:19:56 +0000164# Being true for dangling symbolic links is also useful.
165
166def lexists(path):
167 """Test whether a path exists. Returns True for broken symbolic links"""
168 try:
Georg Brandl89fad142010-03-14 10:23:39 +0000169 os.lstat(path)
Andrew Svetlovad28c7f2012-12-18 22:02:39 +0200170 except OSError:
Johannes Gijsbersae882f72004-08-30 10:19:56 +0000171 return False
172 return True
173
174
Guido van Rossumc6360141990-10-13 19:23:40 +0000175# Is a path a mount point?
Guido van Rossumd3876d31996-07-23 03:47:28 +0000176# (Does this work for all UNIXes? Is it even guaranteed to work by Posix?)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000177
Guido van Rossumc6360141990-10-13 19:23:40 +0000178def ismount(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000179 """Test whether a path is a mount point"""
180 try:
Christian Heimesfaf2f632008-01-06 16:59:19 +0000181 s1 = os.lstat(path)
Brian Curtin06f6fbf2013-07-22 13:07:52 -0500182 except OSError:
183 # It doesn't exist -- so not a mount point. :-)
184 return False
185 else:
Brian Curtina3852ff2013-07-22 19:05:48 -0500186 # A symlink can never be a mount point
Brian Curtin06f6fbf2013-07-22 13:07:52 -0500187 if stat.S_ISLNK(s1.st_mode):
188 return False
189
190 if isinstance(path, bytes):
191 parent = join(path, b'..')
192 else:
193 parent = join(path, '..')
194 try:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000195 s2 = os.lstat(parent)
Andrew Svetlovad28c7f2012-12-18 22:02:39 +0200196 except OSError:
Brian Curtin06f6fbf2013-07-22 13:07:52 -0500197 return False
198
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000199 dev1 = s1.st_dev
200 dev2 = s2.st_dev
Guido van Rossum346f7af1997-12-05 19:04:51 +0000201 if dev1 != dev2:
Tim Petersbc0e9102002-04-04 22:55:58 +0000202 return True # path/.. on a different device as path
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000203 ino1 = s1.st_ino
204 ino2 = s2.st_ino
Guido van Rossum346f7af1997-12-05 19:04:51 +0000205 if ino1 == ino2:
Tim Petersbc0e9102002-04-04 22:55:58 +0000206 return True # path/.. is the same i-node as path
207 return False
Guido van Rossumc6360141990-10-13 19:23:40 +0000208
209
Guido van Rossum7ac48781992-01-14 18:29:32 +0000210# Expand paths beginning with '~' or '~user'.
211# '~' means $HOME; '~user' means that user's home directory.
212# If the path doesn't begin with '~', or if the user or $HOME is unknown,
213# the path is returned unchanged (leaving error reporting to whatever
214# function is called with the expanded path as argument).
215# See also module 'glob' for expansion of *, ? and [...] in pathnames.
216# (A function should also be defined to do full *sh-style environment
217# variable expansion.)
218
219def expanduser(path):
Tim Peters2344fae2001-01-15 00:50:52 +0000220 """Expand ~ and ~user constructions. If user or $HOME is unknown,
Fred Drakec0ab93e2000-09-28 16:22:52 +0000221 do nothing."""
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000222 if isinstance(path, bytes):
223 tilde = b'~'
224 else:
225 tilde = '~'
226 if not path.startswith(tilde):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000227 return path
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000228 sep = _get_sep(path)
229 i = path.find(sep, 1)
Walter Dörwalda9da5ae2003-06-19 10:21:14 +0000230 if i < 0:
231 i = len(path)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000232 if i == 1:
Walter Dörwalda9da5ae2003-06-19 10:21:14 +0000233 if 'HOME' not in os.environ:
Neal Norwitz609ba812002-09-05 21:08:25 +0000234 import pwd
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000235 userhome = pwd.getpwuid(os.getuid()).pw_dir
Neal Norwitz609ba812002-09-05 21:08:25 +0000236 else:
237 userhome = os.environ['HOME']
Guido van Rossum346f7af1997-12-05 19:04:51 +0000238 else:
239 import pwd
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000240 name = path[1:i]
241 if isinstance(name, bytes):
242 name = str(name, 'ASCII')
Guido van Rossum346f7af1997-12-05 19:04:51 +0000243 try:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000244 pwent = pwd.getpwnam(name)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000245 except KeyError:
246 return path
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000247 userhome = pwent.pw_dir
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000248 if isinstance(path, bytes):
Victor Stinner16004ac2010-09-29 16:59:18 +0000249 userhome = os.fsencode(userhome)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000250 root = b'/'
251 else:
252 root = '/'
Jesus Cea7f0d8882012-05-10 05:10:50 +0200253 userhome = userhome.rstrip(root)
254 return (userhome + path[i:]) or root
Guido van Rossum4732ccf1992-08-09 13:54:50 +0000255
256
257# Expand paths containing shell variable substitutions.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000258# This expands the forms $variable and ${variable} only.
Jeremy Hyltona05e2932000-06-28 14:48:01 +0000259# Non-existent variables are left unchanged.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000260
261_varprog = None
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000262_varprogb = None
Guido van Rossum4732ccf1992-08-09 13:54:50 +0000263
264def expandvars(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000265 """Expand shell variables of form $var and ${var}. Unknown variables
Fred Drakec0ab93e2000-09-28 16:22:52 +0000266 are left unchanged."""
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000267 global _varprog, _varprogb
268 if isinstance(path, bytes):
269 if b'$' not in path:
270 return path
271 if not _varprogb:
272 import re
273 _varprogb = re.compile(br'\$(\w+|\{[^}]*\})', re.ASCII)
274 search = _varprogb.search
275 start = b'{'
276 end = b'}'
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200277 environ = getattr(os, 'environb', None)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000278 else:
279 if '$' not in path:
280 return path
281 if not _varprog:
282 import re
283 _varprog = re.compile(r'\$(\w+|\{[^}]*\})', re.ASCII)
284 search = _varprog.search
285 start = '{'
286 end = '}'
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200287 environ = os.environ
Guido van Rossum346f7af1997-12-05 19:04:51 +0000288 i = 0
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000289 while True:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000290 m = search(path, i)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000291 if not m:
292 break
293 i, j = m.span(0)
294 name = m.group(1)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000295 if name.startswith(start) and name.endswith(end):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000296 name = name[1:-1]
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200297 try:
298 if environ is None:
Serhiy Storchakaffadbb72014-02-13 10:45:14 +0200299 value = os.fsencode(os.environ[os.fsdecode(name)])
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200300 else:
301 value = environ[name]
302 except KeyError:
303 i = j
304 else:
Guido van Rossum346f7af1997-12-05 19:04:51 +0000305 tail = path[j:]
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000306 path = path[:i] + value
Guido van Rossum346f7af1997-12-05 19:04:51 +0000307 i = len(path)
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000308 path += tail
Guido van Rossum346f7af1997-12-05 19:04:51 +0000309 return path
Guido van Rossumc629d341992-11-05 10:43:02 +0000310
311
312# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
313# It should be understood that this may change the meaning of the path
314# if it contains symbolic links!
315
316def normpath(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000317 """Normalize path, eliminating double slashes, etc."""
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000318 if isinstance(path, bytes):
319 sep = b'/'
320 empty = b''
321 dot = b'.'
322 dotdot = b'..'
323 else:
324 sep = '/'
325 empty = ''
326 dot = '.'
327 dotdot = '..'
328 if path == empty:
329 return dot
330 initial_slashes = path.startswith(sep)
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000331 # POSIX allows one or two initial slashes, but treats three or more
332 # as single slash.
Tim Peters658cba62001-02-09 20:06:00 +0000333 if (initial_slashes and
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000334 path.startswith(sep*2) and not path.startswith(sep*3)):
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000335 initial_slashes = 2
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000336 comps = path.split(sep)
Skip Montanaro018dfae2000-07-19 17:09:51 +0000337 new_comps = []
338 for comp in comps:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000339 if comp in (empty, dot):
Skip Montanaro018dfae2000-07-19 17:09:51 +0000340 continue
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000341 if (comp != dotdot or (not initial_slashes and not new_comps) or
342 (new_comps and new_comps[-1] == dotdot)):
Skip Montanaro018dfae2000-07-19 17:09:51 +0000343 new_comps.append(comp)
344 elif new_comps:
345 new_comps.pop()
346 comps = new_comps
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000347 path = sep.join(comps)
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000348 if initial_slashes:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000349 path = sep*initial_slashes + path
350 return path or dot
Guido van Rossume294cf61999-01-29 18:05:18 +0000351
352
Guido van Rossume294cf61999-01-29 18:05:18 +0000353def abspath(path):
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000354 """Return an absolute path."""
Guido van Rossume294cf61999-01-29 18:05:18 +0000355 if not isabs(path):
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000356 if isinstance(path, bytes):
357 cwd = os.getcwdb()
358 else:
359 cwd = os.getcwd()
360 path = join(cwd, path)
Guido van Rossume294cf61999-01-29 18:05:18 +0000361 return normpath(path)
Guido van Rossum83eeef42001-09-17 15:16:09 +0000362
363
364# Return a canonical path (i.e. the absolute location of a file on the
365# filesystem).
366
367def realpath(filename):
368 """Return the canonical path of the specified filename, eliminating any
369symbolic links encountered in the path."""
Serhiy Storchakadf326912013-02-10 12:22:07 +0200370 path, ok = _joinrealpath(filename[:0], filename, {})
371 return abspath(path)
372
373# Join two paths, normalizing ang eliminating any symbolic links
374# encountered in the second path.
375def _joinrealpath(path, rest, seen):
376 if isinstance(path, bytes):
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000377 sep = b'/'
Serhiy Storchakadf326912013-02-10 12:22:07 +0200378 curdir = b'.'
379 pardir = b'..'
Johannes Gijsbers4ec40642004-08-14 15:01:53 +0000380 else:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000381 sep = '/'
Serhiy Storchakadf326912013-02-10 12:22:07 +0200382 curdir = '.'
383 pardir = '..'
Tim Petersa45cacf2004-08-20 03:47:14 +0000384
Serhiy Storchakadf326912013-02-10 12:22:07 +0200385 if isabs(rest):
386 rest = rest[1:]
387 path = sep
388
389 while rest:
390 name, _, rest = rest.partition(sep)
391 if not name or name == curdir:
392 # current dir
393 continue
394 if name == pardir:
395 # parent dir
396 if path:
Serhiy Storchaka467393d2013-02-18 12:21:04 +0200397 path, name = split(path)
398 if name == pardir:
399 path = join(path, pardir, pardir)
Brett Cannonf50299c2004-07-10 22:55:15 +0000400 else:
Serhiy Storchaka467393d2013-02-18 12:21:04 +0200401 path = pardir
Serhiy Storchakadf326912013-02-10 12:22:07 +0200402 continue
403 newpath = join(path, name)
404 if not islink(newpath):
405 path = newpath
406 continue
407 # Resolve the symbolic link
408 if newpath in seen:
409 # Already seen this path
410 path = seen[newpath]
411 if path is not None:
412 # use cached value
413 continue
414 # The symlink is not resolved, so we must have a symlink loop.
415 # Return already resolved part + rest of the path unchanged.
416 return join(newpath, rest), False
417 seen[newpath] = None # not resolved symlink
418 path, ok = _joinrealpath(path, os.readlink(newpath), seen)
419 if not ok:
420 return join(path, rest), False
421 seen[newpath] = path # resolved symlink
Tim Petersb64bec32001-09-18 02:26:39 +0000422
Serhiy Storchakadf326912013-02-10 12:22:07 +0200423 return path, True
Tim Petersa45cacf2004-08-20 03:47:14 +0000424
Brett Cannonf50299c2004-07-10 22:55:15 +0000425
Victor Stinnere797c162010-09-17 23:34:26 +0000426supports_unicode_filenames = (sys.platform == 'darwin')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000427
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000428def relpath(path, start=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000429 """Return a relative version of a path"""
430
431 if not path:
432 raise ValueError("no path specified")
433
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000434 if isinstance(path, bytes):
435 curdir = b'.'
436 sep = b'/'
437 pardir = b'..'
438 else:
439 curdir = '.'
440 sep = '/'
441 pardir = '..'
442
443 if start is None:
444 start = curdir
445
Serhiy Storchaka3deeeb02014-10-04 14:58:43 +0300446 try:
447 start_list = [x for x in abspath(start).split(sep) if x]
448 path_list = [x for x in abspath(path).split(sep) if x]
449 # Work out how much of the filepath is shared by start and path.
450 i = len(commonprefix([start_list, path_list]))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000451
Serhiy Storchaka3deeeb02014-10-04 14:58:43 +0300452 rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
453 if not rel_list:
454 return curdir
455 return join(*rel_list)
Serhiy Storchakae4f47082014-10-04 16:09:02 +0300456 except (TypeError, AttributeError, BytesWarning, DeprecationWarning):
Serhiy Storchaka3deeeb02014-10-04 14:58:43 +0300457 genericpath._check_arg_types('relpath', path, start)
458 raise
Serhiy Storchaka38220932015-03-31 15:31:53 +0300459
460
461# Return the longest common sub-path of the sequence of paths given as input.
462# The paths are not normalized before comparing them (this is the
463# responsibility of the caller). Any trailing separator is stripped from the
464# returned path.
465
466def commonpath(paths):
467 """Given a sequence of path names, returns the longest common sub-path."""
468
469 if not paths:
470 raise ValueError('commonpath() arg is an empty sequence')
471
472 if isinstance(paths[0], bytes):
473 sep = b'/'
474 curdir = b'.'
475 else:
476 sep = '/'
477 curdir = '.'
478
479 try:
480 split_paths = [path.split(sep) for path in paths]
481
482 try:
483 isabs, = set(p[:1] == sep for p in paths)
484 except ValueError:
485 raise ValueError("Can't mix absolute and relative paths") from None
486
487 split_paths = [[c for c in s if c and c != curdir] for s in split_paths]
488 s1 = min(split_paths)
489 s2 = max(split_paths)
490 common = s1
491 for i, c in enumerate(s1):
492 if c != s2[i]:
493 common = s1[:i]
494 break
495
496 prefix = sep if isabs else sep[:0]
497 return prefix + sep.join(common)
498 except (TypeError, AttributeError):
499 genericpath._check_arg_types('commonpath', *paths)
500 raise