blob: 6dbdab27497f2b392484a5a08c3bc25e37cdba74 [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"""
Brett Cannon3f9183b2016-08-26 14:44:48 -070052 s = os.fspath(s)
Ezio Melotti5a3ef5b2010-06-25 10:56:11 +000053 if not isinstance(s, (bytes, str)):
54 raise TypeError("normcase() argument must be str or bytes, "
55 "not '{}'".format(s.__class__.__name__))
Guido van Rossum346f7af1997-12-05 19:04:51 +000056 return s
Guido van Rossum7ac48781992-01-14 18:29:32 +000057
58
Jeremy Hyltona05e2932000-06-28 14:48:01 +000059# Return whether a path is absolute.
Guido van Rossum7ac48781992-01-14 18:29:32 +000060# Trivial in Posix, harder on the Mac or MS-DOS.
61
62def isabs(s):
Guido van Rossum346f7af1997-12-05 19:04:51 +000063 """Test whether a path is absolute"""
Brett Cannon3f9183b2016-08-26 14:44:48 -070064 s = os.fspath(s)
Guido van Rossumf0af3e32008-10-02 18:55:37 +000065 sep = _get_sep(s)
66 return s.startswith(sep)
Guido van Rossum7ac48781992-01-14 18:29:32 +000067
68
Barry Warsaw384d2491997-02-18 21:53:25 +000069# Join pathnames.
70# Ignore the previous parts if a part is absolute.
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000071# Insert a '/' unless the first part is empty or already ends in '/'.
Guido van Rossum7ac48781992-01-14 18:29:32 +000072
Barry Warsaw384d2491997-02-18 21:53:25 +000073def join(a, *p):
Guido van Rossum04110fb2007-08-24 16:32:05 +000074 """Join two or more pathname components, inserting '/' as needed.
75 If any component is an absolute path, all previous path components
R David Murraye3de1752012-07-21 14:33:56 -040076 will be discarded. An empty last part will result in a path that
77 ends with a separator."""
Brett Cannon3f9183b2016-08-26 14:44:48 -070078 a = os.fspath(a)
Guido van Rossumf0af3e32008-10-02 18:55:37 +000079 sep = _get_sep(a)
Guido van Rossum346f7af1997-12-05 19:04:51 +000080 path = a
Hynek Schlawack47749462012-07-15 16:21:30 +020081 try:
Serhiy Storchaka5bfc03f2015-05-19 11:00:07 +030082 if not p:
83 path[:0] + sep #23780: Ensure compatible data type even if p is null.
Brett Cannon3f9183b2016-08-26 14:44:48 -070084 for b in map(os.fspath, p):
Hynek Schlawack47749462012-07-15 16:21:30 +020085 if b.startswith(sep):
86 path = b
87 elif not path or path.endswith(sep):
88 path += b
89 else:
90 path += sep + b
Serhiy Storchaka3deeeb02014-10-04 14:58:43 +030091 except (TypeError, AttributeError, BytesWarning):
92 genericpath._check_arg_types('join', a, *p)
93 raise
Guido van Rossum346f7af1997-12-05 19:04:51 +000094 return path
Guido van Rossumc6360141990-10-13 19:23:40 +000095
96
Guido van Rossum26847381992-03-31 18:54:35 +000097# Split a path in head (everything up to the last '/') and tail (the
Guido van Rossuma89b1ba1995-09-01 20:32:21 +000098# rest). If the path ends in '/', tail will be empty. If there is no
99# '/' in the path, head will be empty.
100# Trailing '/'es are stripped from head unless it is the root.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000101
Guido van Rossumc6360141990-10-13 19:23:40 +0000102def split(p):
Tim Peters2344fae2001-01-15 00:50:52 +0000103 """Split a pathname. Returns tuple "(head, tail)" where "tail" is
Fred Drakec0ab93e2000-09-28 16:22:52 +0000104 everything after the final slash. Either part may be empty."""
Brett Cannon3f9183b2016-08-26 14:44:48 -0700105 p = os.fspath(p)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000106 sep = _get_sep(p)
107 i = p.rfind(sep) + 1
Guido van Rossum346f7af1997-12-05 19:04:51 +0000108 head, tail = p[:i], p[i:]
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000109 if head and head != sep*len(head):
110 head = head.rstrip(sep)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000111 return head, tail
Guido van Rossumc6360141990-10-13 19:23:40 +0000112
113
Guido van Rossum4d0fdc31991-08-16 13:27:58 +0000114# Split a path in root and extension.
Guido van Rossum422869a1996-08-20 20:24:17 +0000115# The extension is everything starting at the last dot in the last
Guido van Rossum4d0fdc31991-08-16 13:27:58 +0000116# pathname component; the root is everything before that.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000117# It is always true that root + ext == p.
118
Guido van Rossum4d0fdc31991-08-16 13:27:58 +0000119def splitext(p):
Brett Cannon3f9183b2016-08-26 14:44:48 -0700120 p = os.fspath(p)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000121 if isinstance(p, bytes):
122 sep = b'/'
123 extsep = b'.'
124 else:
125 sep = '/'
126 extsep = '.'
127 return genericpath._splitext(p, sep, None, extsep)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000128splitext.__doc__ = genericpath._splitext.__doc__
Guido van Rossum4d0fdc31991-08-16 13:27:58 +0000129
Guido van Rossum221df241995-08-07 20:17:55 +0000130# Split a pathname into a drive specification and the rest of the
131# path. Useful on DOS/Windows/NT; on Unix, the drive is always empty.
132
133def splitdrive(p):
Tim Peters2344fae2001-01-15 00:50:52 +0000134 """Split a pathname into drive and path. On Posix, drive is always
Fred Drakec0ab93e2000-09-28 16:22:52 +0000135 empty."""
Brett Cannon3f9183b2016-08-26 14:44:48 -0700136 p = os.fspath(p)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000137 return p[:0], p
Guido van Rossum221df241995-08-07 20:17:55 +0000138
139
Thomas Wouters89f507f2006-12-13 04:49:30 +0000140# Return the tail (basename) part of a path, same as split(path)[1].
Guido van Rossum7ac48781992-01-14 18:29:32 +0000141
Guido van Rossumc6360141990-10-13 19:23:40 +0000142def basename(p):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000143 """Returns the final component of a pathname"""
Brett Cannon3f9183b2016-08-26 14:44:48 -0700144 p = os.fspath(p)
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 return p[i:]
Guido van Rossumc6360141990-10-13 19:23:40 +0000148
149
Thomas Wouters89f507f2006-12-13 04:49:30 +0000150# Return the head (dirname) part of a path, same as split(path)[0].
Guido van Rossumc629d341992-11-05 10:43:02 +0000151
152def dirname(p):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000153 """Returns the directory component of a pathname"""
Brett Cannon3f9183b2016-08-26 14:44:48 -0700154 p = os.fspath(p)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000155 sep = _get_sep(p)
156 i = p.rfind(sep) + 1
Thomas Wouters89f507f2006-12-13 04:49:30 +0000157 head = p[:i]
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000158 if head and head != sep*len(head):
159 head = head.rstrip(sep)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000160 return head
Guido van Rossumc629d341992-11-05 10:43:02 +0000161
162
Guido van Rossum7ac48781992-01-14 18:29:32 +0000163# Is a path a symbolic link?
Guido van Rossumd3876d31996-07-23 03:47:28 +0000164# This will always return false on systems where os.lstat doesn't exist.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000165
166def islink(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000167 """Test whether a path is a symbolic link"""
168 try:
169 st = os.lstat(path)
Andrew Svetlovad28c7f2012-12-18 22:02:39 +0200170 except (OSError, AttributeError):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000171 return False
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000172 return stat.S_ISLNK(st.st_mode)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000173
Johannes Gijsbersae882f72004-08-30 10:19:56 +0000174# Being true for dangling symbolic links is also useful.
175
176def lexists(path):
177 """Test whether a path exists. Returns True for broken symbolic links"""
178 try:
Georg Brandl89fad142010-03-14 10:23:39 +0000179 os.lstat(path)
Andrew Svetlovad28c7f2012-12-18 22:02:39 +0200180 except OSError:
Johannes Gijsbersae882f72004-08-30 10:19:56 +0000181 return False
182 return True
183
184
Guido van Rossumc6360141990-10-13 19:23:40 +0000185# Is a path a mount point?
Guido van Rossumd3876d31996-07-23 03:47:28 +0000186# (Does this work for all UNIXes? Is it even guaranteed to work by Posix?)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000187
Guido van Rossumc6360141990-10-13 19:23:40 +0000188def ismount(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000189 """Test whether a path is a mount point"""
190 try:
Christian Heimesfaf2f632008-01-06 16:59:19 +0000191 s1 = os.lstat(path)
Brian Curtin06f6fbf2013-07-22 13:07:52 -0500192 except OSError:
193 # It doesn't exist -- so not a mount point. :-)
194 return False
195 else:
Brian Curtina3852ff2013-07-22 19:05:48 -0500196 # A symlink can never be a mount point
Brian Curtin06f6fbf2013-07-22 13:07:52 -0500197 if stat.S_ISLNK(s1.st_mode):
198 return False
199
200 if isinstance(path, bytes):
201 parent = join(path, b'..')
202 else:
203 parent = join(path, '..')
R David Murray750018b2016-08-18 21:27:48 -0400204 parent = realpath(parent)
Brian Curtin06f6fbf2013-07-22 13:07:52 -0500205 try:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000206 s2 = os.lstat(parent)
Andrew Svetlovad28c7f2012-12-18 22:02:39 +0200207 except OSError:
Brian Curtin06f6fbf2013-07-22 13:07:52 -0500208 return False
209
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000210 dev1 = s1.st_dev
211 dev2 = s2.st_dev
Guido van Rossum346f7af1997-12-05 19:04:51 +0000212 if dev1 != dev2:
Tim Petersbc0e9102002-04-04 22:55:58 +0000213 return True # path/.. on a different device as path
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000214 ino1 = s1.st_ino
215 ino2 = s2.st_ino
Guido van Rossum346f7af1997-12-05 19:04:51 +0000216 if ino1 == ino2:
Tim Petersbc0e9102002-04-04 22:55:58 +0000217 return True # path/.. is the same i-node as path
218 return False
Guido van Rossumc6360141990-10-13 19:23:40 +0000219
220
Guido van Rossum7ac48781992-01-14 18:29:32 +0000221# Expand paths beginning with '~' or '~user'.
222# '~' means $HOME; '~user' means that user's home directory.
223# If the path doesn't begin with '~', or if the user or $HOME is unknown,
224# the path is returned unchanged (leaving error reporting to whatever
225# function is called with the expanded path as argument).
226# See also module 'glob' for expansion of *, ? and [...] in pathnames.
227# (A function should also be defined to do full *sh-style environment
228# variable expansion.)
229
230def expanduser(path):
Tim Peters2344fae2001-01-15 00:50:52 +0000231 """Expand ~ and ~user constructions. If user or $HOME is unknown,
Fred Drakec0ab93e2000-09-28 16:22:52 +0000232 do nothing."""
Brett Cannon3f9183b2016-08-26 14:44:48 -0700233 path = os.fspath(path)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000234 if isinstance(path, bytes):
235 tilde = b'~'
236 else:
237 tilde = '~'
238 if not path.startswith(tilde):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000239 return path
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000240 sep = _get_sep(path)
241 i = path.find(sep, 1)
Walter Dörwalda9da5ae2003-06-19 10:21:14 +0000242 if i < 0:
243 i = len(path)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000244 if i == 1:
Walter Dörwalda9da5ae2003-06-19 10:21:14 +0000245 if 'HOME' not in os.environ:
Neal Norwitz609ba812002-09-05 21:08:25 +0000246 import pwd
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000247 userhome = pwd.getpwuid(os.getuid()).pw_dir
Neal Norwitz609ba812002-09-05 21:08:25 +0000248 else:
249 userhome = os.environ['HOME']
Guido van Rossum346f7af1997-12-05 19:04:51 +0000250 else:
251 import pwd
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000252 name = path[1:i]
253 if isinstance(name, bytes):
254 name = str(name, 'ASCII')
Guido van Rossum346f7af1997-12-05 19:04:51 +0000255 try:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000256 pwent = pwd.getpwnam(name)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000257 except KeyError:
258 return path
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000259 userhome = pwent.pw_dir
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000260 if isinstance(path, bytes):
Victor Stinner16004ac2010-09-29 16:59:18 +0000261 userhome = os.fsencode(userhome)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000262 root = b'/'
263 else:
264 root = '/'
Jesus Cea7f0d8882012-05-10 05:10:50 +0200265 userhome = userhome.rstrip(root)
266 return (userhome + path[i:]) or root
Guido van Rossum4732ccf1992-08-09 13:54:50 +0000267
268
269# Expand paths containing shell variable substitutions.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000270# This expands the forms $variable and ${variable} only.
Jeremy Hyltona05e2932000-06-28 14:48:01 +0000271# Non-existent variables are left unchanged.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000272
273_varprog = None
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000274_varprogb = None
Guido van Rossum4732ccf1992-08-09 13:54:50 +0000275
276def expandvars(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000277 """Expand shell variables of form $var and ${var}. Unknown variables
Fred Drakec0ab93e2000-09-28 16:22:52 +0000278 are left unchanged."""
Brett Cannon3f9183b2016-08-26 14:44:48 -0700279 path = os.fspath(path)
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'}'
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200290 environ = getattr(os, 'environb', None)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000291 else:
292 if '$' not in path:
293 return path
294 if not _varprog:
295 import re
296 _varprog = re.compile(r'\$(\w+|\{[^}]*\})', re.ASCII)
297 search = _varprog.search
298 start = '{'
299 end = '}'
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200300 environ = os.environ
Guido van Rossum346f7af1997-12-05 19:04:51 +0000301 i = 0
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000302 while True:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000303 m = search(path, i)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000304 if not m:
305 break
306 i, j = m.span(0)
307 name = m.group(1)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000308 if name.startswith(start) and name.endswith(end):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000309 name = name[1:-1]
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200310 try:
311 if environ is None:
Serhiy Storchakaffadbb72014-02-13 10:45:14 +0200312 value = os.fsencode(os.environ[os.fsdecode(name)])
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200313 else:
314 value = environ[name]
315 except KeyError:
316 i = j
317 else:
Guido van Rossum346f7af1997-12-05 19:04:51 +0000318 tail = path[j:]
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000319 path = path[:i] + value
Guido van Rossum346f7af1997-12-05 19:04:51 +0000320 i = len(path)
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000321 path += tail
Guido van Rossum346f7af1997-12-05 19:04:51 +0000322 return path
Guido van Rossumc629d341992-11-05 10:43:02 +0000323
324
325# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
326# It should be understood that this may change the meaning of the path
327# if it contains symbolic links!
328
329def normpath(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000330 """Normalize path, eliminating double slashes, etc."""
Brett Cannon3f9183b2016-08-26 14:44:48 -0700331 path = os.fspath(path)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000332 if isinstance(path, bytes):
333 sep = b'/'
334 empty = b''
335 dot = b'.'
336 dotdot = b'..'
337 else:
338 sep = '/'
339 empty = ''
340 dot = '.'
341 dotdot = '..'
342 if path == empty:
343 return dot
344 initial_slashes = path.startswith(sep)
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000345 # POSIX allows one or two initial slashes, but treats three or more
346 # as single slash.
Tim Peters658cba62001-02-09 20:06:00 +0000347 if (initial_slashes and
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000348 path.startswith(sep*2) and not path.startswith(sep*3)):
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000349 initial_slashes = 2
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000350 comps = path.split(sep)
Skip Montanaro018dfae2000-07-19 17:09:51 +0000351 new_comps = []
352 for comp in comps:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000353 if comp in (empty, dot):
Skip Montanaro018dfae2000-07-19 17:09:51 +0000354 continue
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000355 if (comp != dotdot or (not initial_slashes and not new_comps) or
356 (new_comps and new_comps[-1] == dotdot)):
Skip Montanaro018dfae2000-07-19 17:09:51 +0000357 new_comps.append(comp)
358 elif new_comps:
359 new_comps.pop()
360 comps = new_comps
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000361 path = sep.join(comps)
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000362 if initial_slashes:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000363 path = sep*initial_slashes + path
364 return path or dot
Guido van Rossume294cf61999-01-29 18:05:18 +0000365
366
Guido van Rossume294cf61999-01-29 18:05:18 +0000367def abspath(path):
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000368 """Return an absolute path."""
Brett Cannon3f9183b2016-08-26 14:44:48 -0700369 path = os.fspath(path)
Guido van Rossume294cf61999-01-29 18:05:18 +0000370 if not isabs(path):
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000371 if isinstance(path, bytes):
372 cwd = os.getcwdb()
373 else:
374 cwd = os.getcwd()
375 path = join(cwd, path)
Guido van Rossume294cf61999-01-29 18:05:18 +0000376 return normpath(path)
Guido van Rossum83eeef42001-09-17 15:16:09 +0000377
378
379# Return a canonical path (i.e. the absolute location of a file on the
380# filesystem).
381
382def realpath(filename):
383 """Return the canonical path of the specified filename, eliminating any
384symbolic links encountered in the path."""
Brett Cannon3f9183b2016-08-26 14:44:48 -0700385 filename = os.fspath(filename)
Serhiy Storchakadf326912013-02-10 12:22:07 +0200386 path, ok = _joinrealpath(filename[:0], filename, {})
387 return abspath(path)
388
Martin Panter119e5022016-04-16 09:28:57 +0000389# Join two paths, normalizing and eliminating any symbolic links
Serhiy Storchakadf326912013-02-10 12:22:07 +0200390# encountered in the second path.
391def _joinrealpath(path, rest, seen):
392 if isinstance(path, bytes):
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000393 sep = b'/'
Serhiy Storchakadf326912013-02-10 12:22:07 +0200394 curdir = b'.'
395 pardir = b'..'
Johannes Gijsbers4ec40642004-08-14 15:01:53 +0000396 else:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000397 sep = '/'
Serhiy Storchakadf326912013-02-10 12:22:07 +0200398 curdir = '.'
399 pardir = '..'
Tim Petersa45cacf2004-08-20 03:47:14 +0000400
Serhiy Storchakadf326912013-02-10 12:22:07 +0200401 if isabs(rest):
402 rest = rest[1:]
403 path = sep
404
405 while rest:
406 name, _, rest = rest.partition(sep)
407 if not name or name == curdir:
408 # current dir
409 continue
410 if name == pardir:
411 # parent dir
412 if path:
Serhiy Storchaka467393d2013-02-18 12:21:04 +0200413 path, name = split(path)
414 if name == pardir:
415 path = join(path, pardir, pardir)
Brett Cannonf50299c2004-07-10 22:55:15 +0000416 else:
Serhiy Storchaka467393d2013-02-18 12:21:04 +0200417 path = pardir
Serhiy Storchakadf326912013-02-10 12:22:07 +0200418 continue
419 newpath = join(path, name)
420 if not islink(newpath):
421 path = newpath
422 continue
423 # Resolve the symbolic link
424 if newpath in seen:
425 # Already seen this path
426 path = seen[newpath]
427 if path is not None:
428 # use cached value
429 continue
430 # The symlink is not resolved, so we must have a symlink loop.
431 # Return already resolved part + rest of the path unchanged.
432 return join(newpath, rest), False
433 seen[newpath] = None # not resolved symlink
434 path, ok = _joinrealpath(path, os.readlink(newpath), seen)
435 if not ok:
436 return join(path, rest), False
437 seen[newpath] = path # resolved symlink
Tim Petersb64bec32001-09-18 02:26:39 +0000438
Serhiy Storchakadf326912013-02-10 12:22:07 +0200439 return path, True
Tim Petersa45cacf2004-08-20 03:47:14 +0000440
Brett Cannonf50299c2004-07-10 22:55:15 +0000441
Victor Stinnere797c162010-09-17 23:34:26 +0000442supports_unicode_filenames = (sys.platform == 'darwin')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000443
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000444def relpath(path, start=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000445 """Return a relative version of a path"""
446
447 if not path:
448 raise ValueError("no path specified")
449
Brett Cannon3f9183b2016-08-26 14:44:48 -0700450 path = os.fspath(path)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000451 if isinstance(path, bytes):
452 curdir = b'.'
453 sep = b'/'
454 pardir = b'..'
455 else:
456 curdir = '.'
457 sep = '/'
458 pardir = '..'
459
460 if start is None:
461 start = curdir
Brett Cannon3f9183b2016-08-26 14:44:48 -0700462 else:
463 start = os.fspath(start)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000464
Serhiy Storchaka3deeeb02014-10-04 14:58:43 +0300465 try:
466 start_list = [x for x in abspath(start).split(sep) if x]
467 path_list = [x for x in abspath(path).split(sep) if x]
468 # Work out how much of the filepath is shared by start and path.
469 i = len(commonprefix([start_list, path_list]))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000470
Serhiy Storchaka3deeeb02014-10-04 14:58:43 +0300471 rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
472 if not rel_list:
473 return curdir
474 return join(*rel_list)
Serhiy Storchakae4f47082014-10-04 16:09:02 +0300475 except (TypeError, AttributeError, BytesWarning, DeprecationWarning):
Serhiy Storchaka3deeeb02014-10-04 14:58:43 +0300476 genericpath._check_arg_types('relpath', path, start)
477 raise
Serhiy Storchaka38220932015-03-31 15:31:53 +0300478
479
480# Return the longest common sub-path of the sequence of paths given as input.
481# The paths are not normalized before comparing them (this is the
482# responsibility of the caller). Any trailing separator is stripped from the
483# returned path.
484
485def commonpath(paths):
486 """Given a sequence of path names, returns the longest common sub-path."""
487
488 if not paths:
489 raise ValueError('commonpath() arg is an empty sequence')
490
Brett Cannon3f9183b2016-08-26 14:44:48 -0700491 paths = tuple(map(os.fspath, paths))
Serhiy Storchaka38220932015-03-31 15:31:53 +0300492 if isinstance(paths[0], bytes):
493 sep = b'/'
494 curdir = b'.'
495 else:
496 sep = '/'
497 curdir = '.'
498
499 try:
500 split_paths = [path.split(sep) for path in paths]
501
502 try:
503 isabs, = set(p[:1] == sep for p in paths)
504 except ValueError:
505 raise ValueError("Can't mix absolute and relative paths") from None
506
507 split_paths = [[c for c in s if c and c != curdir] for s in split_paths]
508 s1 = min(split_paths)
509 s2 = max(split_paths)
510 common = s1
511 for i, c in enumerate(s1):
512 if c != s2[i]:
513 common = s1[:i]
514 break
515
516 prefix = sep if isabs else sep[:0]
517 return prefix + sep.join(common)
518 except (TypeError, AttributeError):
519 genericpath._check_arg_types('commonpath', *paths)
520 raise