blob: e92186c64e0ddbece53ed11a6e5f1537a162ea01 [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
Serhiy Storchaka34601982018-01-07 17:54:31 +020013# Strings representing various path-related bits and pieces.
14# These are primarily for export; internally, they are hardcoded.
15# Should be set before imports for resolving cyclic dependency.
16curdir = '.'
17pardir = '..'
18extsep = '.'
19sep = '/'
20pathsep = ':'
21defpath = ':/bin:/usr/bin'
22altsep = None
23devnull = '/dev/null'
24
Guido van Rossumd3876d31996-07-23 03:47:28 +000025import os
Guido van Rossumf0af3e32008-10-02 18:55:37 +000026import sys
Guido van Rossum40d93041990-10-21 16:17:34 +000027import stat
Guido van Rossumd8faa362007-04-27 19:54:29 +000028import genericpath
Thomas Wouters89f507f2006-12-13 04:49:30 +000029from genericpath import *
Guido van Rossumc6360141990-10-13 19:23:40 +000030
Skip Montanaroc62c81e2001-02-12 02:00:42 +000031__all__ = ["normcase","isabs","join","splitdrive","split","splitext",
32 "basename","dirname","commonprefix","getsize","getmtime",
Georg Brandlf0de6a12005-08-22 18:02:59 +000033 "getatime","getctime","islink","exists","lexists","isdir","isfile",
Benjamin Petersond71ca412008-05-08 23:44:58 +000034 "ismount", "expanduser","expandvars","normpath","abspath",
Neal Norwitz61cdac62003-01-03 18:01:57 +000035 "samefile","sameopenfile","samestat",
Skip Montanaro117910d2003-02-14 19:35:31 +000036 "curdir","pardir","sep","pathsep","defpath","altsep","extsep",
Serhiy Storchaka38220932015-03-31 15:31:53 +030037 "devnull","realpath","supports_unicode_filenames","relpath",
38 "commonpath"]
Guido van Rossumc6360141990-10-13 19:23:40 +000039
Skip Montanaro117910d2003-02-14 19:35:31 +000040
Guido van Rossumf0af3e32008-10-02 18:55:37 +000041def _get_sep(path):
42 if isinstance(path, bytes):
43 return b'/'
44 else:
45 return '/'
46
Guido van Rossum7ac48781992-01-14 18:29:32 +000047# Normalize the case of a pathname. Trivial in Posix, string.lower on Mac.
48# On MS-DOS this may also turn slashes into backslashes; however, other
49# normalizations (such as optimizing '../' away) are not allowed
50# (another function should be defined to do that).
51
52def normcase(s):
Guido van Rossum346f7af1997-12-05 19:04:51 +000053 """Normalize case of pathname. Has no effect under Posix"""
Brett Cannon3f9183b2016-08-26 14:44:48 -070054 s = os.fspath(s)
Ezio Melotti5a3ef5b2010-06-25 10:56:11 +000055 if not isinstance(s, (bytes, str)):
56 raise TypeError("normcase() argument must be str or bytes, "
57 "not '{}'".format(s.__class__.__name__))
Guido van Rossum346f7af1997-12-05 19:04:51 +000058 return s
Guido van Rossum7ac48781992-01-14 18:29:32 +000059
60
Jeremy Hyltona05e2932000-06-28 14:48:01 +000061# Return whether a path is absolute.
Guido van Rossum7ac48781992-01-14 18:29:32 +000062# Trivial in Posix, harder on the Mac or MS-DOS.
63
64def isabs(s):
Guido van Rossum346f7af1997-12-05 19:04:51 +000065 """Test whether a path is absolute"""
Brett Cannon3f9183b2016-08-26 14:44:48 -070066 s = os.fspath(s)
Guido van Rossumf0af3e32008-10-02 18:55:37 +000067 sep = _get_sep(s)
68 return s.startswith(sep)
Guido van Rossum7ac48781992-01-14 18:29:32 +000069
70
Barry Warsaw384d2491997-02-18 21:53:25 +000071# Join pathnames.
72# Ignore the previous parts if a part is absolute.
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000073# Insert a '/' unless the first part is empty or already ends in '/'.
Guido van Rossum7ac48781992-01-14 18:29:32 +000074
Barry Warsaw384d2491997-02-18 21:53:25 +000075def join(a, *p):
Guido van Rossum04110fb2007-08-24 16:32:05 +000076 """Join two or more pathname components, inserting '/' as needed.
77 If any component is an absolute path, all previous path components
R David Murraye3de1752012-07-21 14:33:56 -040078 will be discarded. An empty last part will result in a path that
79 ends with a separator."""
Brett Cannon3f9183b2016-08-26 14:44:48 -070080 a = os.fspath(a)
Guido van Rossumf0af3e32008-10-02 18:55:37 +000081 sep = _get_sep(a)
Guido van Rossum346f7af1997-12-05 19:04:51 +000082 path = a
Hynek Schlawack47749462012-07-15 16:21:30 +020083 try:
Serhiy Storchaka5bfc03f2015-05-19 11:00:07 +030084 if not p:
85 path[:0] + sep #23780: Ensure compatible data type even if p is null.
Brett Cannon3f9183b2016-08-26 14:44:48 -070086 for b in map(os.fspath, p):
Hynek Schlawack47749462012-07-15 16:21:30 +020087 if b.startswith(sep):
88 path = b
89 elif not path or path.endswith(sep):
90 path += b
91 else:
92 path += sep + b
Serhiy Storchaka3deeeb02014-10-04 14:58:43 +030093 except (TypeError, AttributeError, BytesWarning):
94 genericpath._check_arg_types('join', a, *p)
95 raise
Guido van Rossum346f7af1997-12-05 19:04:51 +000096 return path
Guido van Rossumc6360141990-10-13 19:23:40 +000097
98
Guido van Rossum26847381992-03-31 18:54:35 +000099# Split a path in head (everything up to the last '/') and tail (the
Guido van Rossuma89b1ba1995-09-01 20:32:21 +0000100# rest). If the path ends in '/', tail will be empty. If there is no
101# '/' in the path, head will be empty.
102# Trailing '/'es are stripped from head unless it is the root.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000103
Guido van Rossumc6360141990-10-13 19:23:40 +0000104def split(p):
Tim Peters2344fae2001-01-15 00:50:52 +0000105 """Split a pathname. Returns tuple "(head, tail)" where "tail" is
Fred Drakec0ab93e2000-09-28 16:22:52 +0000106 everything after the final slash. Either part may be empty."""
Brett Cannon3f9183b2016-08-26 14:44:48 -0700107 p = os.fspath(p)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000108 sep = _get_sep(p)
109 i = p.rfind(sep) + 1
Guido van Rossum346f7af1997-12-05 19:04:51 +0000110 head, tail = p[:i], p[i:]
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000111 if head and head != sep*len(head):
112 head = head.rstrip(sep)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000113 return head, tail
Guido van Rossumc6360141990-10-13 19:23:40 +0000114
115
Guido van Rossum4d0fdc31991-08-16 13:27:58 +0000116# Split a path in root and extension.
Guido van Rossum422869a1996-08-20 20:24:17 +0000117# The extension is everything starting at the last dot in the last
Guido van Rossum4d0fdc31991-08-16 13:27:58 +0000118# pathname component; the root is everything before that.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000119# It is always true that root + ext == p.
120
Guido van Rossum4d0fdc31991-08-16 13:27:58 +0000121def splitext(p):
Brett Cannon3f9183b2016-08-26 14:44:48 -0700122 p = os.fspath(p)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000123 if isinstance(p, bytes):
124 sep = b'/'
125 extsep = b'.'
126 else:
127 sep = '/'
128 extsep = '.'
129 return genericpath._splitext(p, sep, None, extsep)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000130splitext.__doc__ = genericpath._splitext.__doc__
Guido van Rossum4d0fdc31991-08-16 13:27:58 +0000131
Guido van Rossum221df241995-08-07 20:17:55 +0000132# Split a pathname into a drive specification and the rest of the
133# path. Useful on DOS/Windows/NT; on Unix, the drive is always empty.
134
135def splitdrive(p):
Tim Peters2344fae2001-01-15 00:50:52 +0000136 """Split a pathname into drive and path. On Posix, drive is always
Fred Drakec0ab93e2000-09-28 16:22:52 +0000137 empty."""
Brett Cannon3f9183b2016-08-26 14:44:48 -0700138 p = os.fspath(p)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000139 return p[:0], p
Guido van Rossum221df241995-08-07 20:17:55 +0000140
141
Thomas Wouters89f507f2006-12-13 04:49:30 +0000142# Return the tail (basename) part of a path, same as split(path)[1].
Guido van Rossum7ac48781992-01-14 18:29:32 +0000143
Guido van Rossumc6360141990-10-13 19:23:40 +0000144def basename(p):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000145 """Returns the final component of a pathname"""
Brett Cannon3f9183b2016-08-26 14:44:48 -0700146 p = os.fspath(p)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000147 sep = _get_sep(p)
148 i = p.rfind(sep) + 1
Thomas Wouters89f507f2006-12-13 04:49:30 +0000149 return p[i:]
Guido van Rossumc6360141990-10-13 19:23:40 +0000150
151
Thomas Wouters89f507f2006-12-13 04:49:30 +0000152# Return the head (dirname) part of a path, same as split(path)[0].
Guido van Rossumc629d341992-11-05 10:43:02 +0000153
154def dirname(p):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000155 """Returns the directory component of a pathname"""
Brett Cannon3f9183b2016-08-26 14:44:48 -0700156 p = os.fspath(p)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000157 sep = _get_sep(p)
158 i = p.rfind(sep) + 1
Thomas Wouters89f507f2006-12-13 04:49:30 +0000159 head = p[:i]
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000160 if head and head != sep*len(head):
161 head = head.rstrip(sep)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000162 return head
Guido van Rossumc629d341992-11-05 10:43:02 +0000163
164
Guido van Rossum7ac48781992-01-14 18:29:32 +0000165# Is a path a symbolic link?
Guido van Rossumd3876d31996-07-23 03:47:28 +0000166# This will always return false on systems where os.lstat doesn't exist.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000167
168def islink(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000169 """Test whether a path is a symbolic link"""
170 try:
171 st = os.lstat(path)
Andrew Svetlovad28c7f2012-12-18 22:02:39 +0200172 except (OSError, AttributeError):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000173 return False
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000174 return stat.S_ISLNK(st.st_mode)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000175
Johannes Gijsbersae882f72004-08-30 10:19:56 +0000176# Being true for dangling symbolic links is also useful.
177
178def lexists(path):
179 """Test whether a path exists. Returns True for broken symbolic links"""
180 try:
Georg Brandl89fad142010-03-14 10:23:39 +0000181 os.lstat(path)
Andrew Svetlovad28c7f2012-12-18 22:02:39 +0200182 except OSError:
Johannes Gijsbersae882f72004-08-30 10:19:56 +0000183 return False
184 return True
185
186
Guido van Rossumc6360141990-10-13 19:23:40 +0000187# Is a path a mount point?
Guido van Rossumd3876d31996-07-23 03:47:28 +0000188# (Does this work for all UNIXes? Is it even guaranteed to work by Posix?)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000189
Guido van Rossumc6360141990-10-13 19:23:40 +0000190def ismount(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000191 """Test whether a path is a mount point"""
192 try:
Christian Heimesfaf2f632008-01-06 16:59:19 +0000193 s1 = os.lstat(path)
Brian Curtin06f6fbf2013-07-22 13:07:52 -0500194 except OSError:
195 # It doesn't exist -- so not a mount point. :-)
196 return False
197 else:
Brian Curtina3852ff2013-07-22 19:05:48 -0500198 # A symlink can never be a mount point
Brian Curtin06f6fbf2013-07-22 13:07:52 -0500199 if stat.S_ISLNK(s1.st_mode):
200 return False
201
202 if isinstance(path, bytes):
203 parent = join(path, b'..')
204 else:
205 parent = join(path, '..')
R David Murray750018b2016-08-18 21:27:48 -0400206 parent = realpath(parent)
Brian Curtin06f6fbf2013-07-22 13:07:52 -0500207 try:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000208 s2 = os.lstat(parent)
Andrew Svetlovad28c7f2012-12-18 22:02:39 +0200209 except OSError:
Brian Curtin06f6fbf2013-07-22 13:07:52 -0500210 return False
211
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."""
Brett Cannon3f9183b2016-08-26 14:44:48 -0700235 path = os.fspath(path)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000236 if isinstance(path, bytes):
237 tilde = b'~'
238 else:
239 tilde = '~'
240 if not path.startswith(tilde):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000241 return path
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000242 sep = _get_sep(path)
243 i = path.find(sep, 1)
Walter Dörwalda9da5ae2003-06-19 10:21:14 +0000244 if i < 0:
245 i = len(path)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000246 if i == 1:
Walter Dörwalda9da5ae2003-06-19 10:21:14 +0000247 if 'HOME' not in os.environ:
Neal Norwitz609ba812002-09-05 21:08:25 +0000248 import pwd
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000249 userhome = pwd.getpwuid(os.getuid()).pw_dir
Neal Norwitz609ba812002-09-05 21:08:25 +0000250 else:
251 userhome = os.environ['HOME']
Guido van Rossum346f7af1997-12-05 19:04:51 +0000252 else:
253 import pwd
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000254 name = path[1:i]
255 if isinstance(name, bytes):
256 name = str(name, 'ASCII')
Guido van Rossum346f7af1997-12-05 19:04:51 +0000257 try:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000258 pwent = pwd.getpwnam(name)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000259 except KeyError:
260 return path
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000261 userhome = pwent.pw_dir
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000262 if isinstance(path, bytes):
Victor Stinner16004ac2010-09-29 16:59:18 +0000263 userhome = os.fsencode(userhome)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000264 root = b'/'
265 else:
266 root = '/'
Jesus Cea7f0d8882012-05-10 05:10:50 +0200267 userhome = userhome.rstrip(root)
268 return (userhome + path[i:]) or root
Guido van Rossum4732ccf1992-08-09 13:54:50 +0000269
270
271# Expand paths containing shell variable substitutions.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000272# This expands the forms $variable and ${variable} only.
Jeremy Hyltona05e2932000-06-28 14:48:01 +0000273# Non-existent variables are left unchanged.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000274
275_varprog = None
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000276_varprogb = None
Guido van Rossum4732ccf1992-08-09 13:54:50 +0000277
278def expandvars(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000279 """Expand shell variables of form $var and ${var}. Unknown variables
Fred Drakec0ab93e2000-09-28 16:22:52 +0000280 are left unchanged."""
Brett Cannon3f9183b2016-08-26 14:44:48 -0700281 path = os.fspath(path)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000282 global _varprog, _varprogb
283 if isinstance(path, bytes):
284 if b'$' not in path:
285 return path
286 if not _varprogb:
287 import re
288 _varprogb = re.compile(br'\$(\w+|\{[^}]*\})', re.ASCII)
289 search = _varprogb.search
290 start = b'{'
291 end = b'}'
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200292 environ = getattr(os, 'environb', None)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000293 else:
294 if '$' not in path:
295 return path
296 if not _varprog:
297 import re
298 _varprog = re.compile(r'\$(\w+|\{[^}]*\})', re.ASCII)
299 search = _varprog.search
300 start = '{'
301 end = '}'
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200302 environ = os.environ
Guido van Rossum346f7af1997-12-05 19:04:51 +0000303 i = 0
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000304 while True:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000305 m = search(path, i)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000306 if not m:
307 break
308 i, j = m.span(0)
309 name = m.group(1)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000310 if name.startswith(start) and name.endswith(end):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000311 name = name[1:-1]
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200312 try:
313 if environ is None:
Serhiy Storchakaffadbb72014-02-13 10:45:14 +0200314 value = os.fsencode(os.environ[os.fsdecode(name)])
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200315 else:
316 value = environ[name]
317 except KeyError:
318 i = j
319 else:
Guido van Rossum346f7af1997-12-05 19:04:51 +0000320 tail = path[j:]
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000321 path = path[:i] + value
Guido van Rossum346f7af1997-12-05 19:04:51 +0000322 i = len(path)
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000323 path += tail
Guido van Rossum346f7af1997-12-05 19:04:51 +0000324 return path
Guido van Rossumc629d341992-11-05 10:43:02 +0000325
326
327# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
328# It should be understood that this may change the meaning of the path
329# if it contains symbolic links!
330
331def normpath(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000332 """Normalize path, eliminating double slashes, etc."""
Brett Cannon3f9183b2016-08-26 14:44:48 -0700333 path = os.fspath(path)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000334 if isinstance(path, bytes):
335 sep = b'/'
336 empty = b''
337 dot = b'.'
338 dotdot = b'..'
339 else:
340 sep = '/'
341 empty = ''
342 dot = '.'
343 dotdot = '..'
344 if path == empty:
345 return dot
346 initial_slashes = path.startswith(sep)
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000347 # POSIX allows one or two initial slashes, but treats three or more
348 # as single slash.
Tim Peters658cba62001-02-09 20:06:00 +0000349 if (initial_slashes and
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000350 path.startswith(sep*2) and not path.startswith(sep*3)):
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000351 initial_slashes = 2
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000352 comps = path.split(sep)
Skip Montanaro018dfae2000-07-19 17:09:51 +0000353 new_comps = []
354 for comp in comps:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000355 if comp in (empty, dot):
Skip Montanaro018dfae2000-07-19 17:09:51 +0000356 continue
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000357 if (comp != dotdot or (not initial_slashes and not new_comps) or
358 (new_comps and new_comps[-1] == dotdot)):
Skip Montanaro018dfae2000-07-19 17:09:51 +0000359 new_comps.append(comp)
360 elif new_comps:
361 new_comps.pop()
362 comps = new_comps
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000363 path = sep.join(comps)
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000364 if initial_slashes:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000365 path = sep*initial_slashes + path
366 return path or dot
Guido van Rossume294cf61999-01-29 18:05:18 +0000367
368
Guido van Rossume294cf61999-01-29 18:05:18 +0000369def abspath(path):
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000370 """Return an absolute path."""
Brett Cannon3f9183b2016-08-26 14:44:48 -0700371 path = os.fspath(path)
Guido van Rossume294cf61999-01-29 18:05:18 +0000372 if not isabs(path):
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000373 if isinstance(path, bytes):
374 cwd = os.getcwdb()
375 else:
376 cwd = os.getcwd()
377 path = join(cwd, path)
Guido van Rossume294cf61999-01-29 18:05:18 +0000378 return normpath(path)
Guido van Rossum83eeef42001-09-17 15:16:09 +0000379
380
381# Return a canonical path (i.e. the absolute location of a file on the
382# filesystem).
383
384def realpath(filename):
385 """Return the canonical path of the specified filename, eliminating any
386symbolic links encountered in the path."""
Brett Cannon3f9183b2016-08-26 14:44:48 -0700387 filename = os.fspath(filename)
Serhiy Storchakadf326912013-02-10 12:22:07 +0200388 path, ok = _joinrealpath(filename[:0], filename, {})
389 return abspath(path)
390
Martin Panter119e5022016-04-16 09:28:57 +0000391# Join two paths, normalizing and eliminating any symbolic links
Serhiy Storchakadf326912013-02-10 12:22:07 +0200392# encountered in the second path.
393def _joinrealpath(path, rest, seen):
394 if isinstance(path, bytes):
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000395 sep = b'/'
Serhiy Storchakadf326912013-02-10 12:22:07 +0200396 curdir = b'.'
397 pardir = b'..'
Johannes Gijsbers4ec40642004-08-14 15:01:53 +0000398 else:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000399 sep = '/'
Serhiy Storchakadf326912013-02-10 12:22:07 +0200400 curdir = '.'
401 pardir = '..'
Tim Petersa45cacf2004-08-20 03:47:14 +0000402
Serhiy Storchakadf326912013-02-10 12:22:07 +0200403 if isabs(rest):
404 rest = rest[1:]
405 path = sep
406
407 while rest:
408 name, _, rest = rest.partition(sep)
409 if not name or name == curdir:
410 # current dir
411 continue
412 if name == pardir:
413 # parent dir
414 if path:
Serhiy Storchaka467393d2013-02-18 12:21:04 +0200415 path, name = split(path)
416 if name == pardir:
417 path = join(path, pardir, pardir)
Brett Cannonf50299c2004-07-10 22:55:15 +0000418 else:
Serhiy Storchaka467393d2013-02-18 12:21:04 +0200419 path = pardir
Serhiy Storchakadf326912013-02-10 12:22:07 +0200420 continue
421 newpath = join(path, name)
422 if not islink(newpath):
423 path = newpath
424 continue
425 # Resolve the symbolic link
426 if newpath in seen:
427 # Already seen this path
428 path = seen[newpath]
429 if path is not None:
430 # use cached value
431 continue
432 # The symlink is not resolved, so we must have a symlink loop.
433 # Return already resolved part + rest of the path unchanged.
434 return join(newpath, rest), False
435 seen[newpath] = None # not resolved symlink
436 path, ok = _joinrealpath(path, os.readlink(newpath), seen)
437 if not ok:
438 return join(path, rest), False
439 seen[newpath] = path # resolved symlink
Tim Petersb64bec32001-09-18 02:26:39 +0000440
Serhiy Storchakadf326912013-02-10 12:22:07 +0200441 return path, True
Tim Petersa45cacf2004-08-20 03:47:14 +0000442
Brett Cannonf50299c2004-07-10 22:55:15 +0000443
Victor Stinnere797c162010-09-17 23:34:26 +0000444supports_unicode_filenames = (sys.platform == 'darwin')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000445
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000446def relpath(path, start=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000447 """Return a relative version of a path"""
448
449 if not path:
450 raise ValueError("no path specified")
451
Brett Cannon3f9183b2016-08-26 14:44:48 -0700452 path = os.fspath(path)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000453 if isinstance(path, bytes):
454 curdir = b'.'
455 sep = b'/'
456 pardir = b'..'
457 else:
458 curdir = '.'
459 sep = '/'
460 pardir = '..'
461
462 if start is None:
463 start = curdir
Brett Cannon3f9183b2016-08-26 14:44:48 -0700464 else:
465 start = os.fspath(start)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000466
Serhiy Storchaka3deeeb02014-10-04 14:58:43 +0300467 try:
468 start_list = [x for x in abspath(start).split(sep) if x]
469 path_list = [x for x in abspath(path).split(sep) if x]
470 # Work out how much of the filepath is shared by start and path.
471 i = len(commonprefix([start_list, path_list]))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000472
Serhiy Storchaka3deeeb02014-10-04 14:58:43 +0300473 rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
474 if not rel_list:
475 return curdir
476 return join(*rel_list)
Serhiy Storchakae4f47082014-10-04 16:09:02 +0300477 except (TypeError, AttributeError, BytesWarning, DeprecationWarning):
Serhiy Storchaka3deeeb02014-10-04 14:58:43 +0300478 genericpath._check_arg_types('relpath', path, start)
479 raise
Serhiy Storchaka38220932015-03-31 15:31:53 +0300480
481
482# Return the longest common sub-path of the sequence of paths given as input.
483# The paths are not normalized before comparing them (this is the
484# responsibility of the caller). Any trailing separator is stripped from the
485# returned path.
486
487def commonpath(paths):
488 """Given a sequence of path names, returns the longest common sub-path."""
489
490 if not paths:
491 raise ValueError('commonpath() arg is an empty sequence')
492
Brett Cannon3f9183b2016-08-26 14:44:48 -0700493 paths = tuple(map(os.fspath, paths))
Serhiy Storchaka38220932015-03-31 15:31:53 +0300494 if isinstance(paths[0], bytes):
495 sep = b'/'
496 curdir = b'.'
497 else:
498 sep = '/'
499 curdir = '.'
500
501 try:
502 split_paths = [path.split(sep) for path in paths]
503
504 try:
505 isabs, = set(p[:1] == sep for p in paths)
506 except ValueError:
507 raise ValueError("Can't mix absolute and relative paths") from None
508
509 split_paths = [[c for c in s if c and c != curdir] for s in split_paths]
510 s1 = min(split_paths)
511 s2 = max(split_paths)
512 common = s1
513 for i, c in enumerate(s1):
514 if c != s2[i]:
515 common = s1[:i]
516 break
517
518 prefix = sep if isabs else sep[:0]
519 return prefix + sep.join(common)
520 except (TypeError, AttributeError):
521 genericpath._check_arg_types('commonpath', *paths)
522 raise