blob: 163c00c445ca1233165ef124c2b2cf7ee701a73d [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
Hirokazu Yamamotoc3937f52010-09-18 05:40:44 +000014import sys
Guido van Rossum40d93041990-10-21 16:17:34 +000015import stat
Martin v. Löwis05c075d2007-03-07 11:04:33 +000016import genericpath
Benjamin Peterson0893a0a2008-05-09 00:27:01 +000017import warnings
Jack Diederich7b604642006-08-26 18:42:06 +000018from genericpath import *
Guido van Rossumc6360141990-10-13 19:23:40 +000019
Skip Montanaroc62c81e2001-02-12 02:00:42 +000020__all__ = ["normcase","isabs","join","splitdrive","split","splitext",
21 "basename","dirname","commonprefix","getsize","getmtime",
Georg Brandlf0de6a12005-08-22 18:02:59 +000022 "getatime","getctime","islink","exists","lexists","isdir","isfile",
23 "ismount","walk","expanduser","expandvars","normpath","abspath",
Neal Norwitz61cdac62003-01-03 18:01:57 +000024 "samefile","sameopenfile","samestat",
Skip Montanaro117910d2003-02-14 19:35:31 +000025 "curdir","pardir","sep","pathsep","defpath","altsep","extsep",
Collin Winter6f187742007-03-16 22:16:08 +000026 "devnull","realpath","supports_unicode_filenames","relpath"]
Guido van Rossumc6360141990-10-13 19:23:40 +000027
Skip Montanaro117910d2003-02-14 19:35:31 +000028# strings representing various path-related bits and pieces
29curdir = '.'
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 Rossum7ac48781992-01-14 18:29:32 +000038# Normalize the case of a pathname. Trivial in Posix, string.lower on Mac.
39# On MS-DOS this may also turn slashes into backslashes; however, other
40# normalizations (such as optimizing '../' away) are not allowed
41# (another function should be defined to do that).
42
43def normcase(s):
Guido van Rossum346f7af1997-12-05 19:04:51 +000044 """Normalize case of pathname. Has no effect under Posix"""
45 return s
Guido van Rossum7ac48781992-01-14 18:29:32 +000046
47
Jeremy Hyltona05e2932000-06-28 14:48:01 +000048# Return whether a path is absolute.
Guido van Rossum7ac48781992-01-14 18:29:32 +000049# Trivial in Posix, harder on the Mac or MS-DOS.
50
51def isabs(s):
Guido van Rossum346f7af1997-12-05 19:04:51 +000052 """Test whether a path is absolute"""
Walter Dörwald77cdeaf2003-06-17 13:13:40 +000053 return s.startswith('/')
Guido van Rossum7ac48781992-01-14 18:29:32 +000054
55
Barry Warsaw384d2491997-02-18 21:53:25 +000056# Join pathnames.
57# Ignore the previous parts if a part is absolute.
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000058# Insert a '/' unless the first part is empty or already ends in '/'.
Guido van Rossum7ac48781992-01-14 18:29:32 +000059
Barry Warsaw384d2491997-02-18 21:53:25 +000060def join(a, *p):
Georg Brandlda5f16a2007-08-23 21:27:57 +000061 """Join two or more pathname components, inserting '/' as needed.
62 If any component is an absolute path, all previous path components
63 will be discarded."""
Guido van Rossum346f7af1997-12-05 19:04:51 +000064 path = a
65 for b in p:
Walter Dörwald77cdeaf2003-06-17 13:13:40 +000066 if b.startswith('/'):
Guido van Rossum346f7af1997-12-05 19:04:51 +000067 path = b
Walter Dörwald77cdeaf2003-06-17 13:13:40 +000068 elif path == '' or path.endswith('/'):
69 path += b
Guido van Rossum346f7af1997-12-05 19:04:51 +000070 else:
Walter Dörwald77cdeaf2003-06-17 13:13:40 +000071 path += '/' + b
Guido van Rossum346f7af1997-12-05 19:04:51 +000072 return path
Guido van Rossumc6360141990-10-13 19:23:40 +000073
74
Guido van Rossum26847381992-03-31 18:54:35 +000075# Split a path in head (everything up to the last '/') and tail (the
Guido van Rossuma89b1ba1995-09-01 20:32:21 +000076# rest). If the path ends in '/', tail will be empty. If there is no
77# '/' in the path, head will be empty.
78# Trailing '/'es are stripped from head unless it is the root.
Guido van Rossum7ac48781992-01-14 18:29:32 +000079
Guido van Rossumc6360141990-10-13 19:23:40 +000080def split(p):
Tim Peters2344fae2001-01-15 00:50:52 +000081 """Split a pathname. Returns tuple "(head, tail)" where "tail" is
Fred Drakec0ab93e2000-09-28 16:22:52 +000082 everything after the final slash. Either part may be empty."""
Fred Drake22fb8392000-09-28 15:04:39 +000083 i = p.rfind('/') + 1
Guido van Rossum346f7af1997-12-05 19:04:51 +000084 head, tail = p[:i], p[i:]
Fred Drake8152d322000-12-12 23:20:45 +000085 if head and head != '/'*len(head):
Walter Dörwald77cdeaf2003-06-17 13:13:40 +000086 head = head.rstrip('/')
Guido van Rossum346f7af1997-12-05 19:04:51 +000087 return head, tail
Guido van Rossumc6360141990-10-13 19:23:40 +000088
89
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000090# Split a path in root and extension.
Guido van Rossum422869a1996-08-20 20:24:17 +000091# The extension is everything starting at the last dot in the last
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000092# pathname component; the root is everything before that.
Guido van Rossum7ac48781992-01-14 18:29:32 +000093# It is always true that root + ext == p.
94
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000095def splitext(p):
Martin v. Löwis05c075d2007-03-07 11:04:33 +000096 return genericpath._splitext(p, sep, altsep, extsep)
97splitext.__doc__ = genericpath._splitext.__doc__
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000098
Guido van Rossum221df241995-08-07 20:17:55 +000099# Split a pathname into a drive specification and the rest of the
100# path. Useful on DOS/Windows/NT; on Unix, the drive is always empty.
101
102def splitdrive(p):
Tim Peters2344fae2001-01-15 00:50:52 +0000103 """Split a pathname into drive and path. On Posix, drive is always
Fred Drakec0ab93e2000-09-28 16:22:52 +0000104 empty."""
Guido van Rossum346f7af1997-12-05 19:04:51 +0000105 return '', p
Guido van Rossum221df241995-08-07 20:17:55 +0000106
107
Georg Brandl65ad0432006-10-12 13:08:16 +0000108# Return the tail (basename) part of a path, same as split(path)[1].
Guido van Rossum7ac48781992-01-14 18:29:32 +0000109
Guido van Rossumc6360141990-10-13 19:23:40 +0000110def basename(p):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000111 """Returns the final component of a pathname"""
Georg Brandl65ad0432006-10-12 13:08:16 +0000112 i = p.rfind('/') + 1
113 return p[i:]
Guido van Rossumc6360141990-10-13 19:23:40 +0000114
115
Georg Brandl65ad0432006-10-12 13:08:16 +0000116# Return the head (dirname) part of a path, same as split(path)[0].
Guido van Rossumc629d341992-11-05 10:43:02 +0000117
118def dirname(p):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000119 """Returns the directory component of a pathname"""
Georg Brandl65ad0432006-10-12 13:08:16 +0000120 i = p.rfind('/') + 1
121 head = p[:i]
122 if head and head != '/'*len(head):
123 head = head.rstrip('/')
124 return head
Guido van Rossumc629d341992-11-05 10:43:02 +0000125
126
Guido van Rossum7ac48781992-01-14 18:29:32 +0000127# Is a path a symbolic link?
Guido van Rossumd3876d31996-07-23 03:47:28 +0000128# This will always return false on systems where os.lstat doesn't exist.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000129
130def islink(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000131 """Test whether a path is a symbolic link"""
132 try:
133 st = os.lstat(path)
134 except (os.error, AttributeError):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000135 return False
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000136 return stat.S_ISLNK(st.st_mode)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000137
Johannes Gijsbersae882f72004-08-30 10:19:56 +0000138# Being true for dangling symbolic links is also useful.
139
140def lexists(path):
141 """Test whether a path exists. Returns True for broken symbolic links"""
142 try:
Georg Brandl84fedf72010-02-06 22:59:15 +0000143 os.lstat(path)
Johannes Gijsbersae882f72004-08-30 10:19:56 +0000144 except os.error:
145 return False
146 return True
147
148
Guido van Rossumd3778f91991-11-12 15:37:40 +0000149# Are two filenames really pointing to the same file?
Guido van Rossum7ac48781992-01-14 18:29:32 +0000150
Guido van Rossumd3778f91991-11-12 15:37:40 +0000151def samefile(f1, f2):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000152 """Test whether two pathnames reference the same actual file"""
153 s1 = os.stat(f1)
154 s2 = os.stat(f2)
155 return samestat(s1, s2)
Guido van Rossumd3778f91991-11-12 15:37:40 +0000156
157
158# Are two open files really referencing the same file?
159# (Not necessarily the same file descriptor!)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000160
Guido van Rossumd3778f91991-11-12 15:37:40 +0000161def sameopenfile(fp1, fp2):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000162 """Test whether two open file objects reference the same file"""
163 s1 = os.fstat(fp1)
164 s2 = os.fstat(fp2)
165 return samestat(s1, s2)
Guido van Rossumd3778f91991-11-12 15:37:40 +0000166
167
168# Are two stat buffers (obtained from stat, fstat or lstat)
169# describing the same file?
Guido van Rossum7ac48781992-01-14 18:29:32 +0000170
Guido van Rossumd3778f91991-11-12 15:37:40 +0000171def samestat(s1, s2):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000172 """Test whether two stat buffers reference the same file"""
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000173 return s1.st_ino == s2.st_ino and \
174 s1.st_dev == s2.st_dev
Guido van Rossumc6360141990-10-13 19:23:40 +0000175
176
177# Is a path a mount point?
Guido van Rossumd3876d31996-07-23 03:47:28 +0000178# (Does this work for all UNIXes? Is it even guaranteed to work by Posix?)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000179
Guido van Rossumc6360141990-10-13 19:23:40 +0000180def ismount(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000181 """Test whether a path is a mount point"""
Georg Brandl78e69572010-08-01 18:52:52 +0000182 if islink(path):
183 # A symlink can never be a mount point
184 return False
Guido van Rossum346f7af1997-12-05 19:04:51 +0000185 try:
Christian Heimes06875612008-01-04 13:21:07 +0000186 s1 = os.lstat(path)
187 s2 = os.lstat(join(path, '..'))
Guido van Rossum346f7af1997-12-05 19:04:51 +0000188 except os.error:
Tim Petersbc0e9102002-04-04 22:55:58 +0000189 return False # It doesn't exist -- so not a mount point :-)
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000190 dev1 = s1.st_dev
191 dev2 = s2.st_dev
Guido van Rossum346f7af1997-12-05 19:04:51 +0000192 if dev1 != dev2:
Tim Petersbc0e9102002-04-04 22:55:58 +0000193 return True # path/.. on a different device as path
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000194 ino1 = s1.st_ino
195 ino2 = s2.st_ino
Guido van Rossum346f7af1997-12-05 19:04:51 +0000196 if ino1 == ino2:
Tim Petersbc0e9102002-04-04 22:55:58 +0000197 return True # path/.. is the same i-node as path
198 return False
Guido van Rossumc6360141990-10-13 19:23:40 +0000199
200
201# Directory tree walk.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000202# For each directory under top (including top itself, but excluding
203# '.' and '..'), func(arg, dirname, filenames) is called, where
204# dirname is the name of the directory and filenames is the list
Guido van Rossum346f7af1997-12-05 19:04:51 +0000205# of files (and subdirectories etc.) in the directory.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000206# The func may modify the filenames list, to implement a filter,
Guido van Rossumc6360141990-10-13 19:23:40 +0000207# or to impose a different order of visiting.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000208
Guido van Rossumc6360141990-10-13 19:23:40 +0000209def walk(top, func, arg):
Tim Peterscf5e6a42001-10-10 04:16:20 +0000210 """Directory tree walk with callback function.
211
212 For each directory in the directory tree rooted at top (including top
213 itself, but excluding '.' and '..'), call func(arg, dirname, fnames).
214 dirname is the name of the directory, and fnames a list of the names of
215 the files and subdirectories in dirname (excluding '.' and '..'). func
216 may modify the fnames list in-place (e.g. via del or slice assignment),
217 and walk will only recurse into the subdirectories whose names remain in
218 fnames; this can be used to implement a filter, or to impose a specific
219 order of visiting. No semantics are defined for, or required of, arg,
220 beyond that arg is always passed to func. It can be used, e.g., to pass
221 a filename pattern, or a mutable object designed to accumulate
222 statistics. Passing None for arg is common."""
Philip Jenveyd846f1d2009-05-08 02:28:39 +0000223 warnings.warnpy3k("In 3.x, os.path.walk is removed in favor of os.walk.",
224 stacklevel=2)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000225 try:
226 names = os.listdir(top)
227 except os.error:
228 return
229 func(arg, top, names)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000230 for name in names:
Tim Peters2344fae2001-01-15 00:50:52 +0000231 name = join(top, name)
Guido van Rossuma490d582001-04-16 18:12:04 +0000232 try:
233 st = os.lstat(name)
234 except os.error:
235 continue
Neal Norwitzec7cf132002-06-06 18:16:14 +0000236 if stat.S_ISDIR(st.st_mode):
Tim Peters2344fae2001-01-15 00:50:52 +0000237 walk(name, func, arg)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000238
239
240# Expand paths beginning with '~' or '~user'.
241# '~' means $HOME; '~user' means that user's home directory.
242# If the path doesn't begin with '~', or if the user or $HOME is unknown,
243# the path is returned unchanged (leaving error reporting to whatever
244# function is called with the expanded path as argument).
245# See also module 'glob' for expansion of *, ? and [...] in pathnames.
246# (A function should also be defined to do full *sh-style environment
247# variable expansion.)
248
249def expanduser(path):
Tim Peters2344fae2001-01-15 00:50:52 +0000250 """Expand ~ and ~user constructions. If user or $HOME is unknown,
Fred Drakec0ab93e2000-09-28 16:22:52 +0000251 do nothing."""
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000252 if not path.startswith('~'):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000253 return path
Walter Dörwalda9da5ae2003-06-19 10:21:14 +0000254 i = path.find('/', 1)
255 if i < 0:
256 i = len(path)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000257 if i == 1:
Walter Dörwalda9da5ae2003-06-19 10:21:14 +0000258 if 'HOME' not in os.environ:
Neal Norwitz609ba812002-09-05 21:08:25 +0000259 import pwd
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000260 userhome = pwd.getpwuid(os.getuid()).pw_dir
Neal Norwitz609ba812002-09-05 21:08:25 +0000261 else:
262 userhome = os.environ['HOME']
Guido van Rossum346f7af1997-12-05 19:04:51 +0000263 else:
264 import pwd
265 try:
266 pwent = pwd.getpwnam(path[1:i])
267 except KeyError:
268 return path
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000269 userhome = pwent.pw_dir
Jesus Ceaf2011e32012-05-10 05:01:11 +0200270 userhome = userhome.rstrip('/')
271 return (userhome + path[i:]) or '/'
Guido van Rossum4732ccf1992-08-09 13:54:50 +0000272
273
274# Expand paths containing shell variable substitutions.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000275# This expands the forms $variable and ${variable} only.
Jeremy Hyltona05e2932000-06-28 14:48:01 +0000276# Non-existent variables are left unchanged.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000277
278_varprog = None
Guido van Rossum4732ccf1992-08-09 13:54:50 +0000279
280def expandvars(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000281 """Expand shell variables of form $var and ${var}. Unknown variables
Fred Drakec0ab93e2000-09-28 16:22:52 +0000282 are left unchanged."""
Guido van Rossum346f7af1997-12-05 19:04:51 +0000283 global _varprog
284 if '$' not in path:
285 return path
286 if not _varprog:
287 import re
288 _varprog = re.compile(r'\$(\w+|\{[^}]*\})')
289 i = 0
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000290 while True:
Guido van Rossum346f7af1997-12-05 19:04:51 +0000291 m = _varprog.search(path, i)
292 if not m:
293 break
294 i, j = m.span(0)
295 name = m.group(1)
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000296 if name.startswith('{') and name.endswith('}'):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000297 name = name[1:-1]
Raymond Hettinger54f02222002-06-01 14:18:47 +0000298 if name in os.environ:
Guido van Rossum346f7af1997-12-05 19:04:51 +0000299 tail = path[j:]
300 path = path[:i] + os.environ[name]
301 i = len(path)
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000302 path += tail
Guido van Rossum346f7af1997-12-05 19:04:51 +0000303 else:
304 i = j
305 return path
Guido van Rossumc629d341992-11-05 10:43:02 +0000306
307
308# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
309# It should be understood that this may change the meaning of the path
310# if it contains symbolic links!
311
312def normpath(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000313 """Normalize path, eliminating double slashes, etc."""
Ezio Melottib5689de2010-01-12 03:32:05 +0000314 # Preserve unicode (if path is unicode)
315 slash, dot = (u'/', u'.') if isinstance(path, unicode) else ('/', '.')
Skip Montanaro018dfae2000-07-19 17:09:51 +0000316 if path == '':
Ezio Melottib5689de2010-01-12 03:32:05 +0000317 return dot
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000318 initial_slashes = path.startswith('/')
319 # POSIX allows one or two initial slashes, but treats three or more
320 # as single slash.
Tim Peters658cba62001-02-09 20:06:00 +0000321 if (initial_slashes and
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000322 path.startswith('//') and not path.startswith('///')):
323 initial_slashes = 2
Fred Drake22fb8392000-09-28 15:04:39 +0000324 comps = path.split('/')
Skip Montanaro018dfae2000-07-19 17:09:51 +0000325 new_comps = []
326 for comp in comps:
327 if comp in ('', '.'):
328 continue
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000329 if (comp != '..' or (not initial_slashes and not new_comps) or
Skip Montanaro018dfae2000-07-19 17:09:51 +0000330 (new_comps and new_comps[-1] == '..')):
331 new_comps.append(comp)
332 elif new_comps:
333 new_comps.pop()
334 comps = new_comps
Ezio Melottib5689de2010-01-12 03:32:05 +0000335 path = slash.join(comps)
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000336 if initial_slashes:
Ezio Melottib5689de2010-01-12 03:32:05 +0000337 path = slash*initial_slashes + path
338 return path or dot
Guido van Rossume294cf61999-01-29 18:05:18 +0000339
340
Guido van Rossume294cf61999-01-29 18:05:18 +0000341def abspath(path):
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000342 """Return an absolute path."""
Guido van Rossume294cf61999-01-29 18:05:18 +0000343 if not isabs(path):
Ezio Melotti4cc80ca2010-02-20 08:09:39 +0000344 if isinstance(path, unicode):
345 cwd = os.getcwdu()
346 else:
347 cwd = os.getcwd()
348 path = join(cwd, path)
Guido van Rossume294cf61999-01-29 18:05:18 +0000349 return normpath(path)
Guido van Rossum83eeef42001-09-17 15:16:09 +0000350
351
352# Return a canonical path (i.e. the absolute location of a file on the
353# filesystem).
354
355def realpath(filename):
356 """Return the canonical path of the specified filename, eliminating any
357symbolic links encountered in the path."""
Johannes Gijsbers4ec40642004-08-14 15:01:53 +0000358 if isabs(filename):
359 bits = ['/'] + filename.split('/')[1:]
360 else:
Georg Brandl268e61c2005-06-03 14:28:50 +0000361 bits = [''] + filename.split('/')
Tim Petersa45cacf2004-08-20 03:47:14 +0000362
Guido van Rossum83eeef42001-09-17 15:16:09 +0000363 for i in range(2, len(bits)+1):
364 component = join(*bits[0:i])
Brett Cannonf50299c2004-07-10 22:55:15 +0000365 # Resolve symbolic links.
Brett Cannondfa5d952004-07-11 19:16:21 +0000366 if islink(component):
Brett Cannonf50299c2004-07-10 22:55:15 +0000367 resolved = _resolve_link(component)
368 if resolved is None:
369 # Infinite loop -- return original component + rest of the path
Johannes Gijsbers4ec40642004-08-14 15:01:53 +0000370 return abspath(join(*([component] + bits[i:])))
Brett Cannonf50299c2004-07-10 22:55:15 +0000371 else:
372 newpath = join(*([resolved] + bits[i:]))
Tim Petersa45cacf2004-08-20 03:47:14 +0000373 return realpath(newpath)
Tim Petersb64bec32001-09-18 02:26:39 +0000374
Johannes Gijsbers4ec40642004-08-14 15:01:53 +0000375 return abspath(filename)
Tim Petersa45cacf2004-08-20 03:47:14 +0000376
Brett Cannonf50299c2004-07-10 22:55:15 +0000377
378def _resolve_link(path):
379 """Internal helper function. Takes a path and follows symlinks
Tim Peters182b5ac2004-07-18 06:16:08 +0000380 until we either arrive at something that isn't a symlink, or
Brett Cannonf50299c2004-07-10 22:55:15 +0000381 encounter a path we've seen before (meaning that there's a loop).
382 """
Benjamin Peterson1763f8a2009-01-27 03:07:53 +0000383 paths_seen = set()
Brett Cannonf50299c2004-07-10 22:55:15 +0000384 while islink(path):
Brett Cannondfa5d952004-07-11 19:16:21 +0000385 if path in paths_seen:
Brett Cannonf50299c2004-07-10 22:55:15 +0000386 # Already seen this path, so we must have a symlink loop
387 return None
Benjamin Peterson1763f8a2009-01-27 03:07:53 +0000388 paths_seen.add(path)
Brett Cannonf50299c2004-07-10 22:55:15 +0000389 # Resolve where the link points to
Brett Cannondfa5d952004-07-11 19:16:21 +0000390 resolved = os.readlink(path)
Andrew M. Kuchlingc75f1122004-08-02 14:54:16 +0000391 if not isabs(resolved):
Brett Cannonf50299c2004-07-10 22:55:15 +0000392 dir = dirname(path)
393 path = normpath(join(dir, resolved))
394 else:
395 path = normpath(resolved)
396 return path
397
Victor Stinner8fc843b2010-09-17 23:35:50 +0000398supports_unicode_filenames = (sys.platform == 'darwin')
Collin Winter6f187742007-03-16 22:16:08 +0000399
400def relpath(path, start=curdir):
401 """Return a relative version of a path"""
402
403 if not path:
404 raise ValueError("no path specified")
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000405
Hirokazu Yamamoto50f7d7e2010-10-18 13:55:29 +0000406 start_list = [x for x in abspath(start).split(sep) if x]
407 path_list = [x for x in abspath(path).split(sep) if x]
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000408
Collin Winter6f187742007-03-16 22:16:08 +0000409 # Work out how much of the filepath is shared by start and path.
410 i = len(commonprefix([start_list, path_list]))
411
412 rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
Georg Brandl183a0842008-01-06 14:27:15 +0000413 if not rel_list:
414 return curdir
Collin Winter6f187742007-03-16 22:16:08 +0000415 return join(*rel_list)