blob: 62afbd0ccf0f0f70f9393bc6a6ff88bc55a702e1 [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
Victor Stinnerd7538dd2018-12-14 13:37:26 +01005module on Posix systems; on other systems (e.g. Windows),
Guido van Rossum54f22ed2000-02-04 15:10:34 +00006os.path provides the same operations in a manner specific to that
Victor Stinnerd7538dd2018-12-14 13:37:26 +01007platform, and is an alias to another module (e.g. ntpath).
Guido van Rossum54f22ed2000-02-04 15:10:34 +00008
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 = ':'
Victor Stinner2c4c02f2019-04-17 17:05:30 +020021defpath = '/bin:/usr/bin'
Serhiy Storchaka34601982018-01-07 17:54:31 +020022altsep = 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"""
Wolfgang Maier74510e22019-03-28 22:47:18 +010054 return os.fspath(s)
Guido van Rossum7ac48781992-01-14 18:29:32 +000055
56
Jeremy Hyltona05e2932000-06-28 14:48:01 +000057# Return whether a path is absolute.
Guido van Rossum7ac48781992-01-14 18:29:32 +000058# Trivial in Posix, harder on the Mac or MS-DOS.
59
60def isabs(s):
Guido van Rossum346f7af1997-12-05 19:04:51 +000061 """Test whether a path is absolute"""
Brett Cannon3f9183b2016-08-26 14:44:48 -070062 s = os.fspath(s)
Guido van Rossumf0af3e32008-10-02 18:55:37 +000063 sep = _get_sep(s)
64 return s.startswith(sep)
Guido van Rossum7ac48781992-01-14 18:29:32 +000065
66
Barry Warsaw384d2491997-02-18 21:53:25 +000067# Join pathnames.
68# Ignore the previous parts if a part is absolute.
Guido van Rossum4d0fdc31991-08-16 13:27:58 +000069# Insert a '/' unless the first part is empty or already ends in '/'.
Guido van Rossum7ac48781992-01-14 18:29:32 +000070
Barry Warsaw384d2491997-02-18 21:53:25 +000071def join(a, *p):
Guido van Rossum04110fb2007-08-24 16:32:05 +000072 """Join two or more pathname components, inserting '/' as needed.
73 If any component is an absolute path, all previous path components
R David Murraye3de1752012-07-21 14:33:56 -040074 will be discarded. An empty last part will result in a path that
75 ends with a separator."""
Brett Cannon3f9183b2016-08-26 14:44:48 -070076 a = os.fspath(a)
Guido van Rossumf0af3e32008-10-02 18:55:37 +000077 sep = _get_sep(a)
Guido van Rossum346f7af1997-12-05 19:04:51 +000078 path = a
Hynek Schlawack47749462012-07-15 16:21:30 +020079 try:
Serhiy Storchaka5bfc03f2015-05-19 11:00:07 +030080 if not p:
81 path[:0] + sep #23780: Ensure compatible data type even if p is null.
Brett Cannon3f9183b2016-08-26 14:44:48 -070082 for b in map(os.fspath, p):
Hynek Schlawack47749462012-07-15 16:21:30 +020083 if b.startswith(sep):
84 path = b
85 elif not path or path.endswith(sep):
86 path += b
87 else:
88 path += sep + b
Serhiy Storchaka3deeeb02014-10-04 14:58:43 +030089 except (TypeError, AttributeError, BytesWarning):
90 genericpath._check_arg_types('join', a, *p)
91 raise
Guido van Rossum346f7af1997-12-05 19:04:51 +000092 return path
Guido van Rossumc6360141990-10-13 19:23:40 +000093
94
Guido van Rossum26847381992-03-31 18:54:35 +000095# Split a path in head (everything up to the last '/') and tail (the
Guido van Rossuma89b1ba1995-09-01 20:32:21 +000096# rest). If the path ends in '/', tail will be empty. If there is no
97# '/' in the path, head will be empty.
98# Trailing '/'es are stripped from head unless it is the root.
Guido van Rossum7ac48781992-01-14 18:29:32 +000099
Guido van Rossumc6360141990-10-13 19:23:40 +0000100def split(p):
Tim Peters2344fae2001-01-15 00:50:52 +0000101 """Split a pathname. Returns tuple "(head, tail)" where "tail" is
Fred Drakec0ab93e2000-09-28 16:22:52 +0000102 everything after the final slash. Either part may be empty."""
Brett Cannon3f9183b2016-08-26 14:44:48 -0700103 p = os.fspath(p)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000104 sep = _get_sep(p)
105 i = p.rfind(sep) + 1
Guido van Rossum346f7af1997-12-05 19:04:51 +0000106 head, tail = p[:i], p[i:]
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000107 if head and head != sep*len(head):
108 head = head.rstrip(sep)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000109 return head, tail
Guido van Rossumc6360141990-10-13 19:23:40 +0000110
111
Guido van Rossum4d0fdc31991-08-16 13:27:58 +0000112# Split a path in root and extension.
Guido van Rossum422869a1996-08-20 20:24:17 +0000113# The extension is everything starting at the last dot in the last
Guido van Rossum4d0fdc31991-08-16 13:27:58 +0000114# pathname component; the root is everything before that.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000115# It is always true that root + ext == p.
116
Guido van Rossum4d0fdc31991-08-16 13:27:58 +0000117def splitext(p):
Brett Cannon3f9183b2016-08-26 14:44:48 -0700118 p = os.fspath(p)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000119 if isinstance(p, bytes):
120 sep = b'/'
121 extsep = b'.'
122 else:
123 sep = '/'
124 extsep = '.'
125 return genericpath._splitext(p, sep, None, extsep)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000126splitext.__doc__ = genericpath._splitext.__doc__
Guido van Rossum4d0fdc31991-08-16 13:27:58 +0000127
Guido van Rossum221df241995-08-07 20:17:55 +0000128# Split a pathname into a drive specification and the rest of the
129# path. Useful on DOS/Windows/NT; on Unix, the drive is always empty.
130
131def splitdrive(p):
Tim Peters2344fae2001-01-15 00:50:52 +0000132 """Split a pathname into drive and path. On Posix, drive is always
Fred Drakec0ab93e2000-09-28 16:22:52 +0000133 empty."""
Brett Cannon3f9183b2016-08-26 14:44:48 -0700134 p = os.fspath(p)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000135 return p[:0], p
Guido van Rossum221df241995-08-07 20:17:55 +0000136
137
Thomas Wouters89f507f2006-12-13 04:49:30 +0000138# Return the tail (basename) part of a path, same as split(path)[1].
Guido van Rossum7ac48781992-01-14 18:29:32 +0000139
Guido van Rossumc6360141990-10-13 19:23:40 +0000140def basename(p):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000141 """Returns the final component of a pathname"""
Brett Cannon3f9183b2016-08-26 14:44:48 -0700142 p = os.fspath(p)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000143 sep = _get_sep(p)
144 i = p.rfind(sep) + 1
Thomas Wouters89f507f2006-12-13 04:49:30 +0000145 return p[i:]
Guido van Rossumc6360141990-10-13 19:23:40 +0000146
147
Thomas Wouters89f507f2006-12-13 04:49:30 +0000148# Return the head (dirname) part of a path, same as split(path)[0].
Guido van Rossumc629d341992-11-05 10:43:02 +0000149
150def dirname(p):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000151 """Returns the directory component of a pathname"""
Brett Cannon3f9183b2016-08-26 14:44:48 -0700152 p = os.fspath(p)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000153 sep = _get_sep(p)
154 i = p.rfind(sep) + 1
Thomas Wouters89f507f2006-12-13 04:49:30 +0000155 head = p[:i]
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000156 if head and head != sep*len(head):
157 head = head.rstrip(sep)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000158 return head
Guido van Rossumc629d341992-11-05 10:43:02 +0000159
160
Guido van Rossum7ac48781992-01-14 18:29:32 +0000161# Is a path a symbolic link?
Guido van Rossumd3876d31996-07-23 03:47:28 +0000162# This will always return false on systems where os.lstat doesn't exist.
Guido van Rossum7ac48781992-01-14 18:29:32 +0000163
164def islink(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000165 """Test whether a path is a symbolic link"""
166 try:
167 st = os.lstat(path)
Serhiy Storchaka0185f342018-09-18 11:28:51 +0300168 except (OSError, ValueError, AttributeError):
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000169 return False
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000170 return stat.S_ISLNK(st.st_mode)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000171
Johannes Gijsbersae882f72004-08-30 10:19:56 +0000172# Being true for dangling symbolic links is also useful.
173
174def lexists(path):
175 """Test whether a path exists. Returns True for broken symbolic links"""
176 try:
Georg Brandl89fad142010-03-14 10:23:39 +0000177 os.lstat(path)
Serhiy Storchaka0185f342018-09-18 11:28:51 +0300178 except (OSError, ValueError):
Johannes Gijsbersae882f72004-08-30 10:19:56 +0000179 return False
180 return True
181
182
Guido van Rossumc6360141990-10-13 19:23:40 +0000183# Is a path a mount point?
Guido van Rossumd3876d31996-07-23 03:47:28 +0000184# (Does this work for all UNIXes? Is it even guaranteed to work by Posix?)
Guido van Rossum7ac48781992-01-14 18:29:32 +0000185
Guido van Rossumc6360141990-10-13 19:23:40 +0000186def ismount(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000187 """Test whether a path is a mount point"""
188 try:
Christian Heimesfaf2f632008-01-06 16:59:19 +0000189 s1 = os.lstat(path)
Serhiy Storchaka0185f342018-09-18 11:28:51 +0300190 except (OSError, ValueError):
Brian Curtin06f6fbf2013-07-22 13:07:52 -0500191 # It doesn't exist -- so not a mount point. :-)
192 return False
193 else:
Brian Curtina3852ff2013-07-22 19:05:48 -0500194 # A symlink can never be a mount point
Brian Curtin06f6fbf2013-07-22 13:07:52 -0500195 if stat.S_ISLNK(s1.st_mode):
196 return False
197
198 if isinstance(path, bytes):
199 parent = join(path, b'..')
200 else:
201 parent = join(path, '..')
R David Murray750018b2016-08-18 21:27:48 -0400202 parent = realpath(parent)
Brian Curtin06f6fbf2013-07-22 13:07:52 -0500203 try:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000204 s2 = os.lstat(parent)
Serhiy Storchaka0185f342018-09-18 11:28:51 +0300205 except (OSError, ValueError):
Brian Curtin06f6fbf2013-07-22 13:07:52 -0500206 return False
207
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000208 dev1 = s1.st_dev
209 dev2 = s2.st_dev
Guido van Rossum346f7af1997-12-05 19:04:51 +0000210 if dev1 != dev2:
Tim Petersbc0e9102002-04-04 22:55:58 +0000211 return True # path/.. on a different device as path
Raymond Hettinger32200ae2002-06-01 19:51:15 +0000212 ino1 = s1.st_ino
213 ino2 = s2.st_ino
Guido van Rossum346f7af1997-12-05 19:04:51 +0000214 if ino1 == ino2:
Tim Petersbc0e9102002-04-04 22:55:58 +0000215 return True # path/.. is the same i-node as path
216 return False
Guido van Rossumc6360141990-10-13 19:23:40 +0000217
218
Guido van Rossum7ac48781992-01-14 18:29:32 +0000219# Expand paths beginning with '~' or '~user'.
220# '~' means $HOME; '~user' means that user's home directory.
221# If the path doesn't begin with '~', or if the user or $HOME is unknown,
222# the path is returned unchanged (leaving error reporting to whatever
223# function is called with the expanded path as argument).
224# See also module 'glob' for expansion of *, ? and [...] in pathnames.
225# (A function should also be defined to do full *sh-style environment
226# variable expansion.)
227
228def expanduser(path):
Tim Peters2344fae2001-01-15 00:50:52 +0000229 """Expand ~ and ~user constructions. If user or $HOME is unknown,
Fred Drakec0ab93e2000-09-28 16:22:52 +0000230 do nothing."""
Brett Cannon3f9183b2016-08-26 14:44:48 -0700231 path = os.fspath(path)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000232 if isinstance(path, bytes):
233 tilde = b'~'
234 else:
235 tilde = '~'
236 if not path.startswith(tilde):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000237 return path
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000238 sep = _get_sep(path)
239 i = path.find(sep, 1)
Walter Dörwalda9da5ae2003-06-19 10:21:14 +0000240 if i < 0:
241 i = len(path)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000242 if i == 1:
Walter Dörwalda9da5ae2003-06-19 10:21:14 +0000243 if 'HOME' not in os.environ:
Neal Norwitz609ba812002-09-05 21:08:25 +0000244 import pwd
Victor Stinnerf2f45552018-12-05 16:49:35 +0100245 try:
246 userhome = pwd.getpwuid(os.getuid()).pw_dir
247 except KeyError:
248 # bpo-10496: if the current user identifier doesn't exist in the
249 # password database, return the path unchanged
250 return path
Neal Norwitz609ba812002-09-05 21:08:25 +0000251 else:
252 userhome = os.environ['HOME']
Guido van Rossum346f7af1997-12-05 19:04:51 +0000253 else:
254 import pwd
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000255 name = path[1:i]
256 if isinstance(name, bytes):
257 name = str(name, 'ASCII')
Guido van Rossum346f7af1997-12-05 19:04:51 +0000258 try:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000259 pwent = pwd.getpwnam(name)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000260 except KeyError:
Victor Stinnerf2f45552018-12-05 16:49:35 +0100261 # bpo-10496: if the user name from the path doesn't exist in the
262 # password database, return the path unchanged
Guido van Rossum346f7af1997-12-05 19:04:51 +0000263 return path
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000264 userhome = pwent.pw_dir
pxinwr75dabfe2020-12-18 03:22:29 +0800265 # if no user home, return the path unchanged on VxWorks
266 if userhome is None and sys.platform == "vxworks":
267 return path
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000268 if isinstance(path, bytes):
Victor Stinner16004ac2010-09-29 16:59:18 +0000269 userhome = os.fsencode(userhome)
Benjamin Petersonef3e4c22009-04-11 19:48:14 +0000270 root = b'/'
271 else:
272 root = '/'
Jesus Cea7f0d8882012-05-10 05:10:50 +0200273 userhome = userhome.rstrip(root)
274 return (userhome + path[i:]) or root
Guido van Rossum4732ccf1992-08-09 13:54:50 +0000275
276
277# Expand paths containing shell variable substitutions.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000278# This expands the forms $variable and ${variable} only.
Jeremy Hyltona05e2932000-06-28 14:48:01 +0000279# Non-existent variables are left unchanged.
Guido van Rossumb6775db1994-08-01 11:34:53 +0000280
281_varprog = None
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000282_varprogb = None
Guido van Rossum4732ccf1992-08-09 13:54:50 +0000283
284def expandvars(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000285 """Expand shell variables of form $var and ${var}. Unknown variables
Fred Drakec0ab93e2000-09-28 16:22:52 +0000286 are left unchanged."""
Brett Cannon3f9183b2016-08-26 14:44:48 -0700287 path = os.fspath(path)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000288 global _varprog, _varprogb
289 if isinstance(path, bytes):
290 if b'$' not in path:
291 return path
292 if not _varprogb:
293 import re
294 _varprogb = re.compile(br'\$(\w+|\{[^}]*\})', re.ASCII)
295 search = _varprogb.search
296 start = b'{'
297 end = b'}'
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200298 environ = getattr(os, 'environb', None)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000299 else:
300 if '$' not in path:
301 return path
302 if not _varprog:
303 import re
304 _varprog = re.compile(r'\$(\w+|\{[^}]*\})', re.ASCII)
305 search = _varprog.search
306 start = '{'
307 end = '}'
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200308 environ = os.environ
Guido van Rossum346f7af1997-12-05 19:04:51 +0000309 i = 0
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000310 while True:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000311 m = search(path, i)
Guido van Rossum346f7af1997-12-05 19:04:51 +0000312 if not m:
313 break
314 i, j = m.span(0)
315 name = m.group(1)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000316 if name.startswith(start) and name.endswith(end):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000317 name = name[1:-1]
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200318 try:
319 if environ is None:
Serhiy Storchakaffadbb72014-02-13 10:45:14 +0200320 value = os.fsencode(os.environ[os.fsdecode(name)])
Serhiy Storchakadbb10192014-02-13 10:13:53 +0200321 else:
322 value = environ[name]
323 except KeyError:
324 i = j
325 else:
Guido van Rossum346f7af1997-12-05 19:04:51 +0000326 tail = path[j:]
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000327 path = path[:i] + value
Guido van Rossum346f7af1997-12-05 19:04:51 +0000328 i = len(path)
Walter Dörwald77cdeaf2003-06-17 13:13:40 +0000329 path += tail
Guido van Rossum346f7af1997-12-05 19:04:51 +0000330 return path
Guido van Rossumc629d341992-11-05 10:43:02 +0000331
332
333# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
334# It should be understood that this may change the meaning of the path
335# if it contains symbolic links!
336
337def normpath(path):
Guido van Rossum346f7af1997-12-05 19:04:51 +0000338 """Normalize path, eliminating double slashes, etc."""
Brett Cannon3f9183b2016-08-26 14:44:48 -0700339 path = os.fspath(path)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000340 if isinstance(path, bytes):
341 sep = b'/'
342 empty = b''
343 dot = b'.'
344 dotdot = b'..'
345 else:
346 sep = '/'
347 empty = ''
348 dot = '.'
349 dotdot = '..'
350 if path == empty:
351 return dot
352 initial_slashes = path.startswith(sep)
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000353 # POSIX allows one or two initial slashes, but treats three or more
354 # as single slash.
Tim Peters658cba62001-02-09 20:06:00 +0000355 if (initial_slashes and
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000356 path.startswith(sep*2) and not path.startswith(sep*3)):
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000357 initial_slashes = 2
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000358 comps = path.split(sep)
Skip Montanaro018dfae2000-07-19 17:09:51 +0000359 new_comps = []
360 for comp in comps:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000361 if comp in (empty, dot):
Skip Montanaro018dfae2000-07-19 17:09:51 +0000362 continue
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000363 if (comp != dotdot or (not initial_slashes and not new_comps) or
364 (new_comps and new_comps[-1] == dotdot)):
Skip Montanaro018dfae2000-07-19 17:09:51 +0000365 new_comps.append(comp)
366 elif new_comps:
367 new_comps.pop()
368 comps = new_comps
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000369 path = sep.join(comps)
Marc-André Lemburgbf222c92001-01-29 11:29:44 +0000370 if initial_slashes:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000371 path = sep*initial_slashes + path
372 return path or dot
Guido van Rossume294cf61999-01-29 18:05:18 +0000373
374
Guido van Rossume294cf61999-01-29 18:05:18 +0000375def abspath(path):
Guido van Rossum54f22ed2000-02-04 15:10:34 +0000376 """Return an absolute path."""
Brett Cannon3f9183b2016-08-26 14:44:48 -0700377 path = os.fspath(path)
Guido van Rossume294cf61999-01-29 18:05:18 +0000378 if not isabs(path):
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000379 if isinstance(path, bytes):
380 cwd = os.getcwdb()
381 else:
382 cwd = os.getcwd()
383 path = join(cwd, path)
Guido van Rossume294cf61999-01-29 18:05:18 +0000384 return normpath(path)
Guido van Rossum83eeef42001-09-17 15:16:09 +0000385
386
387# Return a canonical path (i.e. the absolute location of a file on the
388# filesystem).
389
390def realpath(filename):
391 """Return the canonical path of the specified filename, eliminating any
392symbolic links encountered in the path."""
Brett Cannon3f9183b2016-08-26 14:44:48 -0700393 filename = os.fspath(filename)
Serhiy Storchakadf326912013-02-10 12:22:07 +0200394 path, ok = _joinrealpath(filename[:0], filename, {})
395 return abspath(path)
396
Martin Panter119e5022016-04-16 09:28:57 +0000397# Join two paths, normalizing and eliminating any symbolic links
Serhiy Storchakadf326912013-02-10 12:22:07 +0200398# encountered in the second path.
399def _joinrealpath(path, rest, seen):
400 if isinstance(path, bytes):
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000401 sep = b'/'
Serhiy Storchakadf326912013-02-10 12:22:07 +0200402 curdir = b'.'
403 pardir = b'..'
Johannes Gijsbers4ec40642004-08-14 15:01:53 +0000404 else:
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000405 sep = '/'
Serhiy Storchakadf326912013-02-10 12:22:07 +0200406 curdir = '.'
407 pardir = '..'
Tim Petersa45cacf2004-08-20 03:47:14 +0000408
Serhiy Storchakadf326912013-02-10 12:22:07 +0200409 if isabs(rest):
410 rest = rest[1:]
411 path = sep
412
413 while rest:
414 name, _, rest = rest.partition(sep)
415 if not name or name == curdir:
416 # current dir
417 continue
418 if name == pardir:
419 # parent dir
420 if path:
Serhiy Storchaka467393d2013-02-18 12:21:04 +0200421 path, name = split(path)
422 if name == pardir:
423 path = join(path, pardir, pardir)
Brett Cannonf50299c2004-07-10 22:55:15 +0000424 else:
Serhiy Storchaka467393d2013-02-18 12:21:04 +0200425 path = pardir
Serhiy Storchakadf326912013-02-10 12:22:07 +0200426 continue
427 newpath = join(path, name)
428 if not islink(newpath):
429 path = newpath
430 continue
431 # Resolve the symbolic link
432 if newpath in seen:
433 # Already seen this path
434 path = seen[newpath]
435 if path is not None:
436 # use cached value
437 continue
438 # The symlink is not resolved, so we must have a symlink loop.
439 # Return already resolved part + rest of the path unchanged.
440 return join(newpath, rest), False
441 seen[newpath] = None # not resolved symlink
442 path, ok = _joinrealpath(path, os.readlink(newpath), seen)
443 if not ok:
444 return join(path, rest), False
445 seen[newpath] = path # resolved symlink
Tim Petersb64bec32001-09-18 02:26:39 +0000446
Serhiy Storchakadf326912013-02-10 12:22:07 +0200447 return path, True
Tim Petersa45cacf2004-08-20 03:47:14 +0000448
Brett Cannonf50299c2004-07-10 22:55:15 +0000449
Victor Stinnere797c162010-09-17 23:34:26 +0000450supports_unicode_filenames = (sys.platform == 'darwin')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000451
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000452def relpath(path, start=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000453 """Return a relative version of a path"""
454
455 if not path:
456 raise ValueError("no path specified")
457
Brett Cannon3f9183b2016-08-26 14:44:48 -0700458 path = os.fspath(path)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000459 if isinstance(path, bytes):
460 curdir = b'.'
461 sep = b'/'
462 pardir = b'..'
463 else:
464 curdir = '.'
465 sep = '/'
466 pardir = '..'
467
468 if start is None:
469 start = curdir
Brett Cannon3f9183b2016-08-26 14:44:48 -0700470 else:
471 start = os.fspath(start)
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000472
Serhiy Storchaka3deeeb02014-10-04 14:58:43 +0300473 try:
474 start_list = [x for x in abspath(start).split(sep) if x]
475 path_list = [x for x in abspath(path).split(sep) if x]
476 # Work out how much of the filepath is shared by start and path.
477 i = len(commonprefix([start_list, path_list]))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000478
Serhiy Storchaka3deeeb02014-10-04 14:58:43 +0300479 rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
480 if not rel_list:
481 return curdir
482 return join(*rel_list)
Serhiy Storchakae4f47082014-10-04 16:09:02 +0300483 except (TypeError, AttributeError, BytesWarning, DeprecationWarning):
Serhiy Storchaka3deeeb02014-10-04 14:58:43 +0300484 genericpath._check_arg_types('relpath', path, start)
485 raise
Serhiy Storchaka38220932015-03-31 15:31:53 +0300486
487
488# Return the longest common sub-path of the sequence of paths given as input.
489# The paths are not normalized before comparing them (this is the
490# responsibility of the caller). Any trailing separator is stripped from the
491# returned path.
492
493def commonpath(paths):
494 """Given a sequence of path names, returns the longest common sub-path."""
495
496 if not paths:
497 raise ValueError('commonpath() arg is an empty sequence')
498
Brett Cannon3f9183b2016-08-26 14:44:48 -0700499 paths = tuple(map(os.fspath, paths))
Serhiy Storchaka38220932015-03-31 15:31:53 +0300500 if isinstance(paths[0], bytes):
501 sep = b'/'
502 curdir = b'.'
503 else:
504 sep = '/'
505 curdir = '.'
506
507 try:
508 split_paths = [path.split(sep) for path in paths]
509
510 try:
511 isabs, = set(p[:1] == sep for p in paths)
512 except ValueError:
513 raise ValueError("Can't mix absolute and relative paths") from None
514
515 split_paths = [[c for c in s if c and c != curdir] for s in split_paths]
516 s1 = min(split_paths)
517 s2 = max(split_paths)
518 common = s1
519 for i, c in enumerate(s1):
520 if c != s2[i]:
521 common = s1[:i]
522 break
523
524 prefix = sep if isabs else sep[:0]
525 return prefix + sep.join(common)
526 except (TypeError, AttributeError):
527 genericpath._check_arg_types('commonpath', *paths)
528 raise