blob: 64fe9dfc5dafc529db6dfab6309b9a848b48ee28 [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"""
Guido van Rossumf0af3e32008-10-02 18:55:37 +000051 # TODO: on Mac OS X, this should really return s.lower().
Guido van Rossum346f7af1997-12-05 19:04:51 +000052 return s
Guido van Rossum7ac48781992-01-14 18:29:32 +000053
54
Jeremy Hyltona05e2932000-06-28 14:48:01 +000055# Return whether a path is absolute.
Guido van Rossum7ac48781992-01-14 18:29:32 +000056# Trivial in Posix, harder on the Mac or MS-DOS.
57
58def isabs(s):
Guido van Rossum346f7af1997-12-05 19:04:51 +000059 """Test whether a path is absolute"""
Guido van Rossumf0af3e32008-10-02 18:55:37 +000060 sep = _get_sep(s)
61 return s.startswith(sep)
Guido van Rossum7ac48781992-01-14 18:29:32 +000062
63
Barry Warsaw384d2491997-02-18 21:53:25 +000064# Join pathnames.
65# Ignore the previous parts if a part is absolute.
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000066# Insert a '/' unless the first part is empty or already ends in '/'.
Guido van Rossum7ac48781992-01-14 18:29:32 +000067
Barry Warsaw384d2491997-02-18 21:53:25 +000068def join(a, *p):
Guido van Rossum04110fb2007-08-24 16:32:05 +000069 """Join two or more pathname components, inserting '/' as needed.
70 If any component is an absolute path, all previous path components
71 will be discarded."""
Guido van Rossumf0af3e32008-10-02 18:55:37 +000072 sep = _get_sep(a)
Guido van Rossum346f7af1997-12-05 19:04:51 +000073 path = a
74 for b in p:
Guido van Rossumf0af3e32008-10-02 18:55:37 +000075 if b.startswith(sep):
Guido van Rossum346f7af1997-12-05 19:04:51 +000076 path = b
Guido van Rossumf0af3e32008-10-02 18:55:37 +000077 elif not path or path.endswith(sep):
Walter Dörwald77cdeaf2003-06-17 13:13:40 +000078 path += b
Guido van Rossum346f7af1997-12-05 19:04:51 +000079 else:
Guido van Rossumf0af3e32008-10-02 18:55:37 +000080 path += sep + b
Guido van Rossum346f7af1997-12-05 19:04:51 +000081 return path
Guido van Rossumc6360141990-10-13 19:23:40 +000082
83
Guido van Rossum26847381992-03-31 18:54:35 +000084# Split a path in head (everything up to the last '/') and tail (the
Guido van Rossuma89b1ba1995-09-01 20:32:21 +000085# rest). If the path ends in '/', tail will be empty. If there is no
86# '/' in the path, head will be empty.
87# Trailing '/'es are stripped from head unless it is the root.
Guido van Rossum7ac48781992-01-14 18:29:32 +000088
Guido van Rossumc6360141990-10-13 19:23:40 +000089def split(p):
Tim Peters2344fae2001-01-15 00:50:52 +000090 """Split a pathname. Returns tuple "(head, tail)" where "tail" is
Fred Drakec0ab93e2000-09-28 16:22:52 +000091 everything after the final slash. Either part may be empty."""
Guido van Rossumf0af3e32008-10-02 18:55:37 +000092 sep = _get_sep(p)
93 i = p.rfind(sep) + 1
Guido van Rossum346f7af1997-12-05 19:04:51 +000094 head, tail = p[:i], p[i:]
Guido van Rossumf0af3e32008-10-02 18:55:37 +000095 if head and head != sep*len(head):
96 head = head.rstrip(sep)
Guido van Rossum346f7af1997-12-05 19:04:51 +000097 return head, tail
Guido van Rossumc6360141990-10-13 19:23:40 +000098
99
Guido van Rossum4d0fdc31991-08-16 13:27:58 +0000100# Split a path in root and extension.
Guido van Rossum422869a1996-08-20 20:24:17 +0000101# The extension is everything starting at the last dot in the last
Guido van Rossum4d0fdc31991-08-16 13:27:58 +0000102# pathname component; the root is everything before that.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000103# It is always true that root + ext == p.
104
Guido van Rossum4d0fdc31991-08-16 13:27:58 +0000105def splitext(p):
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000106 if isinstance(p, bytes):
107 sep = b'/'
108 extsep = b'.'
109 else:
110 sep = '/'
111 extsep = '.'
112 return genericpath._splitext(p, sep, None, extsep)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000113splitext.__doc__ = genericpath._splitext.__doc__
Guido van Rossum4d0fdc31991-08-16 13:27:58 +0000114
Guido van Rossum221df241995-08-07 20:17:55 +0000115# Split a pathname into a drive specification and the rest of the
116# path. Useful on DOS/Windows/NT; on Unix, the drive is always empty.
117
118def splitdrive(p):
Tim Peters2344fae2001-01-15 00:50:52 +0000119 """Split a pathname into drive and path. On Posix, drive is always
Fred Drakec0ab93e2000-09-28 16:22:52 +0000120 empty."""
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000121 return p[:0], p
Guido van Rossum221df241995-08-07 20:17:55 +0000122
123
Thomas Wouters89f507f2006-12-13 04:49:30 +0000124# Return the tail (basename) part of a path, same as split(path)[1].
Guido van Rossum7ac48781992-01-14 18:29:32 +0000125
Guido van Rossumc6360141990-10-13 19:23:40 +0000126def basename(p):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000127 """Returns the final component of a pathname"""
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000128 sep = _get_sep(p)
129 i = p.rfind(sep) + 1
Thomas Wouters89f507f2006-12-13 04:49:30 +0000130 return p[i:]
Guido van Rossumc6360141990-10-13 19:23:40 +0000131
132
Thomas Wouters89f507f2006-12-13 04:49:30 +0000133# Return the head (dirname) part of a path, same as split(path)[0].
Guido van Rossumc629d341992-11-05 10:43:02 +0000134
135def dirname(p):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000136 """Returns the directory component of a pathname"""
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000137 sep = _get_sep(p)
138 i = p.rfind(sep) + 1
Thomas Wouters89f507f2006-12-13 04:49:30 +0000139 head = p[:i]
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000140 if head and head != sep*len(head):
141 head = head.rstrip(sep)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000142 return head
Guido van Rossumc629d341992-11-05 10:43:02 +0000143
144
Guido van Rossum7ac48781992-01-14 18:29:32 +0000145# Is a path a symbolic link?
Guido van Rossumd3876d31996-07-23 03:47:28 +0000146# This will always return false on systems where os.lstat doesn't exist.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000147
148def islink(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000149 """Test whether a path is a symbolic link"""
150 try:
151 st = os.lstat(path)
152 except (os.error, AttributeError):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000153 return False
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000154 return stat.S_ISLNK(st.st_mode)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000155
Johannes Gijsbersae882f72004-08-30 10:19:56 +0000156# Being true for dangling symbolic links is also useful.
157
158def lexists(path):
159 """Test whether a path exists. Returns True for broken symbolic links"""
160 try:
161 st = os.lstat(path)
162 except os.error:
163 return False
164 return True
165
166
Guido van Rossumd3778f91991-11-12 15:37:40 +0000167# Are two filenames really pointing to the same file?
Guido van Rossum7ac48781992-01-14 18:29:32 +0000168
Guido van Rossumd3778f91991-11-12 15:37:40 +0000169def samefile(f1, f2):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000170 """Test whether two pathnames reference the same actual file"""
171 s1 = os.stat(f1)
172 s2 = os.stat(f2)
173 return samestat(s1, s2)
Guido van Rossumd3778f91991-11-12 15:37:40 +0000174
175
176# Are two open files really referencing the same file?
177# (Not necessarily the same file descriptor!)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000178
Guido van Rossumd3778f91991-11-12 15:37:40 +0000179def sameopenfile(fp1, fp2):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000180 """Test whether two open file objects reference the same file"""
181 s1 = os.fstat(fp1)
182 s2 = os.fstat(fp2)
183 return samestat(s1, s2)
Guido van Rossumd3778f91991-11-12 15:37:40 +0000184
185
186# Are two stat buffers (obtained from stat, fstat or lstat)
187# describing the same file?
Guido van Rossum7ac48781992-01-14 18:29:32 +0000188
Guido van Rossumd3778f91991-11-12 15:37:40 +0000189def samestat(s1, s2):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000190 """Test whether two stat buffers reference the same file"""
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000191 return s1.st_ino == s2.st_ino and \
192 s1.st_dev == s2.st_dev
Guido van Rossumc6360141990-10-13 19:23:40 +0000193
194
195# Is a path a mount point?
Guido van Rossumd3876d31996-07-23 03:47:28 +0000196# (Does this work for all UNIXes? Is it even guaranteed to work by Posix?)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000197
Guido van Rossumc6360141990-10-13 19:23:40 +0000198def ismount(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000199 """Test whether a path is a mount point"""
Georg Brandlcea7e552010-08-01 18:56:30 +0000200 if islink(path):
201 # A symlink can never be a mount point
202 return False
Guido van Rossum346f7af1997-12-05 19:04:51 +0000203 try:
Christian Heimesfaf2f632008-01-06 16:59:19 +0000204 s1 = os.lstat(path)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000205 if isinstance(path, bytes):
206 parent = join(path, b'..')
207 else:
208 parent = join(path, '..')
209 s2 = os.lstat(parent)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000210 except os.error:
Tim Petersbc0e9102002-04-04 22:55:58 +0000211 return False # It doesn't exist -- so not a mount point :-)
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000212 dev1 = s1.st_dev
213 dev2 = s2.st_dev
Guido van Rossum346f7af1997-12-05 19:04:51 +0000214 if dev1 != dev2:
Tim Petersbc0e9102002-04-04 22:55:58 +0000215 return True # path/.. on a different device as path
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000216 ino1 = s1.st_ino
217 ino2 = s2.st_ino
Guido van Rossum346f7af1997-12-05 19:04:51 +0000218 if ino1 == ino2:
Tim Petersbc0e9102002-04-04 22:55:58 +0000219 return True # path/.. is the same i-node as path
220 return False
Guido van Rossumc6360141990-10-13 19:23:40 +0000221
222
Guido van Rossum7ac48781992-01-14 18:29:32 +0000223# Expand paths beginning with '~' or '~user'.
224# '~' means $HOME; '~user' means that user's home directory.
225# If the path doesn't begin with '~', or if the user or $HOME is unknown,
226# the path is returned unchanged (leaving error reporting to whatever
227# function is called with the expanded path as argument).
228# See also module 'glob' for expansion of *, ? and [...] in pathnames.
229# (A function should also be defined to do full *sh-style environment
230# variable expansion.)
231
232def expanduser(path):
Tim Peters2344fae2001-01-15 00:50:52 +0000233 """Expand ~ and ~user constructions. If user or $HOME is unknown,
Fred Drakec0ab93e2000-09-28 16:22:52 +0000234 do nothing."""
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000235 if isinstance(path, bytes):
236 tilde = b'~'
237 else:
238 tilde = '~'
239 if not path.startswith(tilde):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000240 return path
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000241 sep = _get_sep(path)
242 i = path.find(sep, 1)
Walter Dörwalda9da5ae2003-06-19 10:21:14 +0000243 if i < 0:
244 i = len(path)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000245 if i == 1:
Walter Dörwalda9da5ae2003-06-19 10:21:14 +0000246 if 'HOME' not in os.environ:
Neal Norwitz609ba812002-09-05 21:08:25 +0000247 import pwd
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000248 userhome = pwd.getpwuid(os.getuid()).pw_dir
Neal Norwitz609ba812002-09-05 21:08:25 +0000249 else:
250 userhome = os.environ['HOME']
Guido van Rossum346f7af1997-12-05 19:04:51 +0000251 else:
252 import pwd
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000253 name = path[1:i]
254 if isinstance(name, bytes):
255 name = str(name, 'ASCII')
Guido van Rossum346f7af1997-12-05 19:04:51 +0000256 try:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000257 pwent = pwd.getpwnam(name)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000258 except KeyError:
259 return path
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000260 userhome = pwent.pw_dir
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000261 if isinstance(path, bytes):
262 userhome = userhome.encode(sys.getfilesystemencoding())
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000263 root = b'/'
264 else:
265 root = '/'
266 userhome = userhome.rstrip(root) or userhome
Guido van Rossum346f7af1997-12-05 19:04:51 +0000267 return userhome + path[i:]
Guido van Rossum4732ccf1992-08-09 13:54:50 +0000268
269
270# Expand paths containing shell variable substitutions.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000271# This expands the forms $variable and ${variable} only.
Jeremy Hyltona05e2932000-06-28 14:48:01 +0000272# Non-existent variables are left unchanged.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000273
274_varprog = None
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000275_varprogb = None
Guido van Rossum4732ccf1992-08-09 13:54:50 +0000276
277def expandvars(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000278 """Expand shell variables of form $var and ${var}. Unknown variables
Fred Drakec0ab93e2000-09-28 16:22:52 +0000279 are left unchanged."""
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000280 global _varprog, _varprogb
281 if isinstance(path, bytes):
282 if b'$' not in path:
283 return path
284 if not _varprogb:
285 import re
286 _varprogb = re.compile(br'\$(\w+|\{[^}]*\})', re.ASCII)
287 search = _varprogb.search
288 start = b'{'
289 end = b'}'
290 else:
291 if '$' not in path:
292 return path
293 if not _varprog:
294 import re
295 _varprog = re.compile(r'\$(\w+|\{[^}]*\})', re.ASCII)
296 search = _varprog.search
297 start = '{'
298 end = '}'
Guido van Rossum346f7af1997-12-05 19:04:51 +0000299 i = 0
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000300 while True:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000301 m = search(path, i)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000302 if not m:
303 break
304 i, j = m.span(0)
305 name = m.group(1)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000306 if name.startswith(start) and name.endswith(end):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000307 name = name[1:-1]
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000308 if isinstance(name, bytes):
309 name = str(name, 'ASCII')
Raymond Hettinger54f02222002-06-01 14:18:47 +0000310 if name in os.environ:
Guido van Rossum346f7af1997-12-05 19:04:51 +0000311 tail = path[j:]
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000312 value = os.environ[name]
313 if isinstance(path, bytes):
314 value = value.encode('ASCII')
315 path = path[:i] + value
Guido van Rossum346f7af1997-12-05 19:04:51 +0000316 i = len(path)
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000317 path += tail
Guido van Rossum346f7af1997-12-05 19:04:51 +0000318 else:
319 i = j
320 return path
Guido van Rossumc629d341992-11-05 10:43:02 +0000321
322
323# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
324# It should be understood that this may change the meaning of the path
325# if it contains symbolic links!
326
327def normpath(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000328 """Normalize path, eliminating double slashes, etc."""
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000329 if isinstance(path, bytes):
330 sep = b'/'
331 empty = b''
332 dot = b'.'
333 dotdot = b'..'
334 else:
335 sep = '/'
336 empty = ''
337 dot = '.'
338 dotdot = '..'
339 if path == empty:
340 return dot
341 initial_slashes = path.startswith(sep)
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000342 # POSIX allows one or two initial slashes, but treats three or more
343 # as single slash.
Tim Peters658cba62001-02-09 20:06:00 +0000344 if (initial_slashes and
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000345 path.startswith(sep*2) and not path.startswith(sep*3)):
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000346 initial_slashes = 2
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000347 comps = path.split(sep)
Skip Montanaro018dfae2000-07-19 17:09:51 +0000348 new_comps = []
349 for comp in comps:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000350 if comp in (empty, dot):
Skip Montanaro018dfae2000-07-19 17:09:51 +0000351 continue
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000352 if (comp != dotdot or (not initial_slashes and not new_comps) or
353 (new_comps and new_comps[-1] == dotdot)):
Skip Montanaro018dfae2000-07-19 17:09:51 +0000354 new_comps.append(comp)
355 elif new_comps:
356 new_comps.pop()
357 comps = new_comps
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000358 path = sep.join(comps)
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000359 if initial_slashes:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000360 path = sep*initial_slashes + path
361 return path or dot
Guido van Rossume294cf61999-01-29 18:05:18 +0000362
363
Guido van Rossume294cf61999-01-29 18:05:18 +0000364def abspath(path):
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000365 """Return an absolute path."""
Guido van Rossume294cf61999-01-29 18:05:18 +0000366 if not isabs(path):
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000367 if isinstance(path, bytes):
368 cwd = os.getcwdb()
369 else:
370 cwd = os.getcwd()
371 path = join(cwd, path)
Guido van Rossume294cf61999-01-29 18:05:18 +0000372 return normpath(path)
Guido van Rossum83eeef42001-09-17 15:16:09 +0000373
374
375# Return a canonical path (i.e. the absolute location of a file on the
376# filesystem).
377
378def realpath(filename):
379 """Return the canonical path of the specified filename, eliminating any
380symbolic links encountered in the path."""
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000381 if isinstance(filename, bytes):
382 sep = b'/'
383 empty = b''
Johannes Gijsbers4ec40642004-08-14 15:01:53 +0000384 else:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000385 sep = '/'
386 empty = ''
387 if isabs(filename):
388 bits = [sep] + filename.split(sep)[1:]
389 else:
390 bits = [empty] + filename.split(sep)
Tim Petersa45cacf2004-08-20 03:47:14 +0000391
Guido van Rossum83eeef42001-09-17 15:16:09 +0000392 for i in range(2, len(bits)+1):
393 component = join(*bits[0:i])
Brett Cannonf50299c2004-07-10 22:55:15 +0000394 # Resolve symbolic links.
Brett Cannondfa5d952004-07-11 19:16:21 +0000395 if islink(component):
Brett Cannonf50299c2004-07-10 22:55:15 +0000396 resolved = _resolve_link(component)
397 if resolved is None:
398 # Infinite loop -- return original component + rest of the path
Johannes Gijsbers4ec40642004-08-14 15:01:53 +0000399 return abspath(join(*([component] + bits[i:])))
Brett Cannonf50299c2004-07-10 22:55:15 +0000400 else:
401 newpath = join(*([resolved] + bits[i:]))
Tim Petersa45cacf2004-08-20 03:47:14 +0000402 return realpath(newpath)
Tim Petersb64bec32001-09-18 02:26:39 +0000403
Johannes Gijsbers4ec40642004-08-14 15:01:53 +0000404 return abspath(filename)
Tim Petersa45cacf2004-08-20 03:47:14 +0000405
Brett Cannonf50299c2004-07-10 22:55:15 +0000406
407def _resolve_link(path):
408 """Internal helper function. Takes a path and follows symlinks
Tim Peters182b5ac2004-07-18 06:16:08 +0000409 until we either arrive at something that isn't a symlink, or
Brett Cannonf50299c2004-07-10 22:55:15 +0000410 encounter a path we've seen before (meaning that there's a loop).
411 """
Benjamin Petersonc4bbc8d2009-01-30 03:39:35 +0000412 paths_seen = set()
Brett Cannonf50299c2004-07-10 22:55:15 +0000413 while islink(path):
Brett Cannondfa5d952004-07-11 19:16:21 +0000414 if path in paths_seen:
Brett Cannonf50299c2004-07-10 22:55:15 +0000415 # Already seen this path, so we must have a symlink loop
416 return None
Benjamin Petersonc4bbc8d2009-01-30 03:39:35 +0000417 paths_seen.add(path)
Brett Cannonf50299c2004-07-10 22:55:15 +0000418 # Resolve where the link points to
Brett Cannondfa5d952004-07-11 19:16:21 +0000419 resolved = os.readlink(path)
Andrew M. Kuchlingc75f1122004-08-02 14:54:16 +0000420 if not isabs(resolved):
Brett Cannonf50299c2004-07-10 22:55:15 +0000421 dir = dirname(path)
422 path = normpath(join(dir, resolved))
423 else:
424 path = normpath(resolved)
425 return path
426
Just van Rossum2d4e9882003-07-17 15:11:49 +0000427supports_unicode_filenames = False
Guido van Rossumd8faa362007-04-27 19:54:29 +0000428
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000429def relpath(path, start=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000430 """Return a relative version of a path"""
431
432 if not path:
433 raise ValueError("no path specified")
434
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000435 if isinstance(path, bytes):
436 curdir = b'.'
437 sep = b'/'
438 pardir = b'..'
439 else:
440 curdir = '.'
441 sep = '/'
442 pardir = '..'
443
444 if start is None:
445 start = curdir
446
Hirokazu Yamamoto089144e2010-10-18 13:49:09 +0000447 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]
Guido van Rossumd8faa362007-04-27 19:54:29 +0000449
450 # Work out how much of the filepath is shared by start and path.
451 i = len(commonprefix([start_list, path_list]))
452
453 rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
Christian Heimesfaf2f632008-01-06 16:59:19 +0000454 if not rel_list:
455 return curdir
Guido van Rossumd8faa362007-04-27 19:54:29 +0000456 return join(*rel_list)