Guido van Rossum | 54f22ed | 2000-02-04 15:10:34 +0000 | [diff] [blame] | 1 | """Common operations on Posix pathnames. |
| 2 | |
| 3 | Instead of importing this module directly, import os and refer to |
| 4 | this module as os.path. The "os.path" name is an alias for this |
| 5 | module on Posix systems; on other systems (e.g. Mac, Windows), |
| 6 | os.path provides the same operations in a manner specific to that |
| 7 | platform, and is an alias to another module (e.g. macpath, ntpath). |
| 8 | |
| 9 | Some of this can actually be useful on non-Posix systems too, e.g. |
| 10 | for manipulation of the pathname component of URLs. |
Guido van Rossum | 346f7af | 1997-12-05 19:04:51 +0000 | [diff] [blame] | 11 | """ |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 12 | |
Guido van Rossum | d3876d3 | 1996-07-23 03:47:28 +0000 | [diff] [blame] | 13 | import os |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 14 | import sys |
Guido van Rossum | 40d9304 | 1990-10-21 16:17:34 +0000 | [diff] [blame] | 15 | import stat |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 16 | import genericpath |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 17 | from genericpath import * |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 18 | |
Skip Montanaro | c62c81e | 2001-02-12 02:00:42 +0000 | [diff] [blame] | 19 | __all__ = ["normcase","isabs","join","splitdrive","split","splitext", |
| 20 | "basename","dirname","commonprefix","getsize","getmtime", |
Georg Brandl | f0de6a1 | 2005-08-22 18:02:59 +0000 | [diff] [blame] | 21 | "getatime","getctime","islink","exists","lexists","isdir","isfile", |
Benjamin Peterson | d71ca41 | 2008-05-08 23:44:58 +0000 | [diff] [blame] | 22 | "ismount", "expanduser","expandvars","normpath","abspath", |
Neal Norwitz | 61cdac6 | 2003-01-03 18:01:57 +0000 | [diff] [blame] | 23 | "samefile","sameopenfile","samestat", |
Skip Montanaro | 117910d | 2003-02-14 19:35:31 +0000 | [diff] [blame] | 24 | "curdir","pardir","sep","pathsep","defpath","altsep","extsep", |
Serhiy Storchaka | 3822093 | 2015-03-31 15:31:53 +0300 | [diff] [blame] | 25 | "devnull","realpath","supports_unicode_filenames","relpath", |
| 26 | "commonpath"] |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 27 | |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 28 | # Strings representing various path-related bits and pieces. |
| 29 | # These are primarily for export; internally, they are hardcoded. |
Skip Montanaro | 117910d | 2003-02-14 19:35:31 +0000 | [diff] [blame] | 30 | curdir = '.' |
| 31 | pardir = '..' |
| 32 | extsep = '.' |
| 33 | sep = '/' |
| 34 | pathsep = ':' |
| 35 | defpath = ':/bin:/usr/bin' |
| 36 | altsep = None |
Martin v. Löwis | bdec50f | 2004-06-08 08:29:33 +0000 | [diff] [blame] | 37 | devnull = '/dev/null' |
Skip Montanaro | 117910d | 2003-02-14 19:35:31 +0000 | [diff] [blame] | 38 | |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 39 | def _get_sep(path): |
| 40 | if isinstance(path, bytes): |
| 41 | return b'/' |
| 42 | else: |
| 43 | return '/' |
| 44 | |
Guido van Rossum | 7ac4878 | 1992-01-14 18:29:32 +0000 | [diff] [blame] | 45 | # 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 | |
| 50 | def normcase(s): |
Guido van Rossum | 346f7af | 1997-12-05 19:04:51 +0000 | [diff] [blame] | 51 | """Normalize case of pathname. Has no effect under Posix""" |
Ezio Melotti | 5a3ef5b | 2010-06-25 10:56:11 +0000 | [diff] [blame] | 52 | if not isinstance(s, (bytes, str)): |
| 53 | raise TypeError("normcase() argument must be str or bytes, " |
| 54 | "not '{}'".format(s.__class__.__name__)) |
Guido van Rossum | 346f7af | 1997-12-05 19:04:51 +0000 | [diff] [blame] | 55 | return s |
Guido van Rossum | 7ac4878 | 1992-01-14 18:29:32 +0000 | [diff] [blame] | 56 | |
| 57 | |
Jeremy Hylton | a05e293 | 2000-06-28 14:48:01 +0000 | [diff] [blame] | 58 | # Return whether a path is absolute. |
Guido van Rossum | 7ac4878 | 1992-01-14 18:29:32 +0000 | [diff] [blame] | 59 | # Trivial in Posix, harder on the Mac or MS-DOS. |
| 60 | |
| 61 | def isabs(s): |
Guido van Rossum | 346f7af | 1997-12-05 19:04:51 +0000 | [diff] [blame] | 62 | """Test whether a path is absolute""" |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 63 | sep = _get_sep(s) |
| 64 | return s.startswith(sep) |
Guido van Rossum | 7ac4878 | 1992-01-14 18:29:32 +0000 | [diff] [blame] | 65 | |
| 66 | |
Barry Warsaw | 384d249 | 1997-02-18 21:53:25 +0000 | [diff] [blame] | 67 | # Join pathnames. |
| 68 | # Ignore the previous parts if a part is absolute. |
Guido van Rossum | 4d0fdc3 | 1991-08-16 13:27:58 +0000 | [diff] [blame] | 69 | # Insert a '/' unless the first part is empty or already ends in '/'. |
Guido van Rossum | 7ac4878 | 1992-01-14 18:29:32 +0000 | [diff] [blame] | 70 | |
Barry Warsaw | 384d249 | 1997-02-18 21:53:25 +0000 | [diff] [blame] | 71 | def join(a, *p): |
Guido van Rossum | 04110fb | 2007-08-24 16:32:05 +0000 | [diff] [blame] | 72 | """Join two or more pathname components, inserting '/' as needed. |
| 73 | If any component is an absolute path, all previous path components |
R David Murray | e3de175 | 2012-07-21 14:33:56 -0400 | [diff] [blame] | 74 | will be discarded. An empty last part will result in a path that |
| 75 | ends with a separator.""" |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 76 | sep = _get_sep(a) |
Guido van Rossum | 346f7af | 1997-12-05 19:04:51 +0000 | [diff] [blame] | 77 | path = a |
Hynek Schlawack | 4774946 | 2012-07-15 16:21:30 +0200 | [diff] [blame] | 78 | try: |
Serhiy Storchaka | 5bfc03f | 2015-05-19 11:00:07 +0300 | [diff] [blame] | 79 | if not p: |
| 80 | path[:0] + sep #23780: Ensure compatible data type even if p is null. |
Hynek Schlawack | 4774946 | 2012-07-15 16:21:30 +0200 | [diff] [blame] | 81 | for b in p: |
| 82 | if b.startswith(sep): |
| 83 | path = b |
| 84 | elif not path or path.endswith(sep): |
| 85 | path += b |
| 86 | else: |
| 87 | path += sep + b |
Serhiy Storchaka | 3deeeb0 | 2014-10-04 14:58:43 +0300 | [diff] [blame] | 88 | except (TypeError, AttributeError, BytesWarning): |
| 89 | genericpath._check_arg_types('join', a, *p) |
| 90 | raise |
Guido van Rossum | 346f7af | 1997-12-05 19:04:51 +0000 | [diff] [blame] | 91 | return path |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 92 | |
| 93 | |
Guido van Rossum | 2684738 | 1992-03-31 18:54:35 +0000 | [diff] [blame] | 94 | # Split a path in head (everything up to the last '/') and tail (the |
Guido van Rossum | a89b1ba | 1995-09-01 20:32:21 +0000 | [diff] [blame] | 95 | # rest). If the path ends in '/', tail will be empty. If there is no |
| 96 | # '/' in the path, head will be empty. |
| 97 | # Trailing '/'es are stripped from head unless it is the root. |
Guido van Rossum | 7ac4878 | 1992-01-14 18:29:32 +0000 | [diff] [blame] | 98 | |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 99 | def split(p): |
Tim Peters | 2344fae | 2001-01-15 00:50:52 +0000 | [diff] [blame] | 100 | """Split a pathname. Returns tuple "(head, tail)" where "tail" is |
Fred Drake | c0ab93e | 2000-09-28 16:22:52 +0000 | [diff] [blame] | 101 | everything after the final slash. Either part may be empty.""" |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 102 | sep = _get_sep(p) |
| 103 | i = p.rfind(sep) + 1 |
Guido van Rossum | 346f7af | 1997-12-05 19:04:51 +0000 | [diff] [blame] | 104 | head, tail = p[:i], p[i:] |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 105 | if head and head != sep*len(head): |
| 106 | head = head.rstrip(sep) |
Guido van Rossum | 346f7af | 1997-12-05 19:04:51 +0000 | [diff] [blame] | 107 | return head, tail |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 108 | |
| 109 | |
Guido van Rossum | 4d0fdc3 | 1991-08-16 13:27:58 +0000 | [diff] [blame] | 110 | # Split a path in root and extension. |
Guido van Rossum | 422869a | 1996-08-20 20:24:17 +0000 | [diff] [blame] | 111 | # The extension is everything starting at the last dot in the last |
Guido van Rossum | 4d0fdc3 | 1991-08-16 13:27:58 +0000 | [diff] [blame] | 112 | # pathname component; the root is everything before that. |
Guido van Rossum | 7ac4878 | 1992-01-14 18:29:32 +0000 | [diff] [blame] | 113 | # It is always true that root + ext == p. |
| 114 | |
Guido van Rossum | 4d0fdc3 | 1991-08-16 13:27:58 +0000 | [diff] [blame] | 115 | def splitext(p): |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 116 | if isinstance(p, bytes): |
| 117 | sep = b'/' |
| 118 | extsep = b'.' |
| 119 | else: |
| 120 | sep = '/' |
| 121 | extsep = '.' |
| 122 | return genericpath._splitext(p, sep, None, extsep) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 123 | splitext.__doc__ = genericpath._splitext.__doc__ |
Guido van Rossum | 4d0fdc3 | 1991-08-16 13:27:58 +0000 | [diff] [blame] | 124 | |
Guido van Rossum | 221df24 | 1995-08-07 20:17:55 +0000 | [diff] [blame] | 125 | # Split a pathname into a drive specification and the rest of the |
| 126 | # path. Useful on DOS/Windows/NT; on Unix, the drive is always empty. |
| 127 | |
| 128 | def splitdrive(p): |
Tim Peters | 2344fae | 2001-01-15 00:50:52 +0000 | [diff] [blame] | 129 | """Split a pathname into drive and path. On Posix, drive is always |
Fred Drake | c0ab93e | 2000-09-28 16:22:52 +0000 | [diff] [blame] | 130 | empty.""" |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 131 | return p[:0], p |
Guido van Rossum | 221df24 | 1995-08-07 20:17:55 +0000 | [diff] [blame] | 132 | |
| 133 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 134 | # Return the tail (basename) part of a path, same as split(path)[1]. |
Guido van Rossum | 7ac4878 | 1992-01-14 18:29:32 +0000 | [diff] [blame] | 135 | |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 136 | def basename(p): |
Guido van Rossum | 346f7af | 1997-12-05 19:04:51 +0000 | [diff] [blame] | 137 | """Returns the final component of a pathname""" |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 138 | sep = _get_sep(p) |
| 139 | i = p.rfind(sep) + 1 |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 140 | return p[i:] |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 141 | |
| 142 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 143 | # Return the head (dirname) part of a path, same as split(path)[0]. |
Guido van Rossum | c629d34 | 1992-11-05 10:43:02 +0000 | [diff] [blame] | 144 | |
| 145 | def dirname(p): |
Guido van Rossum | 346f7af | 1997-12-05 19:04:51 +0000 | [diff] [blame] | 146 | """Returns the directory component of a pathname""" |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 147 | sep = _get_sep(p) |
| 148 | i = p.rfind(sep) + 1 |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 149 | head = p[:i] |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 150 | if head and head != sep*len(head): |
| 151 | head = head.rstrip(sep) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 152 | return head |
Guido van Rossum | c629d34 | 1992-11-05 10:43:02 +0000 | [diff] [blame] | 153 | |
| 154 | |
Guido van Rossum | 7ac4878 | 1992-01-14 18:29:32 +0000 | [diff] [blame] | 155 | # Is a path a symbolic link? |
Guido van Rossum | d3876d3 | 1996-07-23 03:47:28 +0000 | [diff] [blame] | 156 | # This will always return false on systems where os.lstat doesn't exist. |
Guido van Rossum | 7ac4878 | 1992-01-14 18:29:32 +0000 | [diff] [blame] | 157 | |
| 158 | def islink(path): |
Guido van Rossum | 346f7af | 1997-12-05 19:04:51 +0000 | [diff] [blame] | 159 | """Test whether a path is a symbolic link""" |
| 160 | try: |
| 161 | st = os.lstat(path) |
Andrew Svetlov | ad28c7f | 2012-12-18 22:02:39 +0200 | [diff] [blame] | 162 | except (OSError, AttributeError): |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 163 | return False |
Raymond Hettinger | 32200ae | 2002-06-01 19:51:15 +0000 | [diff] [blame] | 164 | return stat.S_ISLNK(st.st_mode) |
Guido van Rossum | 7ac4878 | 1992-01-14 18:29:32 +0000 | [diff] [blame] | 165 | |
Johannes Gijsbers | ae882f7 | 2004-08-30 10:19:56 +0000 | [diff] [blame] | 166 | # Being true for dangling symbolic links is also useful. |
| 167 | |
| 168 | def lexists(path): |
| 169 | """Test whether a path exists. Returns True for broken symbolic links""" |
| 170 | try: |
Georg Brandl | 89fad14 | 2010-03-14 10:23:39 +0000 | [diff] [blame] | 171 | os.lstat(path) |
Andrew Svetlov | ad28c7f | 2012-12-18 22:02:39 +0200 | [diff] [blame] | 172 | except OSError: |
Johannes Gijsbers | ae882f7 | 2004-08-30 10:19:56 +0000 | [diff] [blame] | 173 | return False |
| 174 | return True |
| 175 | |
| 176 | |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 177 | # Is a path a mount point? |
Guido van Rossum | d3876d3 | 1996-07-23 03:47:28 +0000 | [diff] [blame] | 178 | # (Does this work for all UNIXes? Is it even guaranteed to work by Posix?) |
Guido van Rossum | 7ac4878 | 1992-01-14 18:29:32 +0000 | [diff] [blame] | 179 | |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 180 | def ismount(path): |
Guido van Rossum | 346f7af | 1997-12-05 19:04:51 +0000 | [diff] [blame] | 181 | """Test whether a path is a mount point""" |
| 182 | try: |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 183 | s1 = os.lstat(path) |
Brian Curtin | 06f6fbf | 2013-07-22 13:07:52 -0500 | [diff] [blame] | 184 | except OSError: |
| 185 | # It doesn't exist -- so not a mount point. :-) |
| 186 | return False |
| 187 | else: |
Brian Curtin | a3852ff | 2013-07-22 19:05:48 -0500 | [diff] [blame] | 188 | # A symlink can never be a mount point |
Brian Curtin | 06f6fbf | 2013-07-22 13:07:52 -0500 | [diff] [blame] | 189 | if stat.S_ISLNK(s1.st_mode): |
| 190 | return False |
| 191 | |
| 192 | if isinstance(path, bytes): |
| 193 | parent = join(path, b'..') |
| 194 | else: |
| 195 | parent = join(path, '..') |
| 196 | try: |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 197 | s2 = os.lstat(parent) |
Andrew Svetlov | ad28c7f | 2012-12-18 22:02:39 +0200 | [diff] [blame] | 198 | except OSError: |
Brian Curtin | 06f6fbf | 2013-07-22 13:07:52 -0500 | [diff] [blame] | 199 | return False |
| 200 | |
Raymond Hettinger | 32200ae | 2002-06-01 19:51:15 +0000 | [diff] [blame] | 201 | dev1 = s1.st_dev |
| 202 | dev2 = s2.st_dev |
Guido van Rossum | 346f7af | 1997-12-05 19:04:51 +0000 | [diff] [blame] | 203 | if dev1 != dev2: |
Tim Peters | bc0e910 | 2002-04-04 22:55:58 +0000 | [diff] [blame] | 204 | return True # path/.. on a different device as path |
Raymond Hettinger | 32200ae | 2002-06-01 19:51:15 +0000 | [diff] [blame] | 205 | ino1 = s1.st_ino |
| 206 | ino2 = s2.st_ino |
Guido van Rossum | 346f7af | 1997-12-05 19:04:51 +0000 | [diff] [blame] | 207 | if ino1 == ino2: |
Tim Peters | bc0e910 | 2002-04-04 22:55:58 +0000 | [diff] [blame] | 208 | return True # path/.. is the same i-node as path |
| 209 | return False |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 210 | |
| 211 | |
Guido van Rossum | 7ac4878 | 1992-01-14 18:29:32 +0000 | [diff] [blame] | 212 | # Expand paths beginning with '~' or '~user'. |
| 213 | # '~' means $HOME; '~user' means that user's home directory. |
| 214 | # If the path doesn't begin with '~', or if the user or $HOME is unknown, |
| 215 | # the path is returned unchanged (leaving error reporting to whatever |
| 216 | # function is called with the expanded path as argument). |
| 217 | # See also module 'glob' for expansion of *, ? and [...] in pathnames. |
| 218 | # (A function should also be defined to do full *sh-style environment |
| 219 | # variable expansion.) |
| 220 | |
| 221 | def expanduser(path): |
Tim Peters | 2344fae | 2001-01-15 00:50:52 +0000 | [diff] [blame] | 222 | """Expand ~ and ~user constructions. If user or $HOME is unknown, |
Fred Drake | c0ab93e | 2000-09-28 16:22:52 +0000 | [diff] [blame] | 223 | do nothing.""" |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 224 | if isinstance(path, bytes): |
| 225 | tilde = b'~' |
| 226 | else: |
| 227 | tilde = '~' |
| 228 | if not path.startswith(tilde): |
Guido van Rossum | 346f7af | 1997-12-05 19:04:51 +0000 | [diff] [blame] | 229 | return path |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 230 | sep = _get_sep(path) |
| 231 | i = path.find(sep, 1) |
Walter Dörwald | a9da5ae | 2003-06-19 10:21:14 +0000 | [diff] [blame] | 232 | if i < 0: |
| 233 | i = len(path) |
Guido van Rossum | 346f7af | 1997-12-05 19:04:51 +0000 | [diff] [blame] | 234 | if i == 1: |
Walter Dörwald | a9da5ae | 2003-06-19 10:21:14 +0000 | [diff] [blame] | 235 | if 'HOME' not in os.environ: |
Neal Norwitz | 609ba81 | 2002-09-05 21:08:25 +0000 | [diff] [blame] | 236 | import pwd |
Walter Dörwald | 77cdeaf | 2003-06-17 13:13:40 +0000 | [diff] [blame] | 237 | userhome = pwd.getpwuid(os.getuid()).pw_dir |
Neal Norwitz | 609ba81 | 2002-09-05 21:08:25 +0000 | [diff] [blame] | 238 | else: |
| 239 | userhome = os.environ['HOME'] |
Guido van Rossum | 346f7af | 1997-12-05 19:04:51 +0000 | [diff] [blame] | 240 | else: |
| 241 | import pwd |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 242 | name = path[1:i] |
| 243 | if isinstance(name, bytes): |
| 244 | name = str(name, 'ASCII') |
Guido van Rossum | 346f7af | 1997-12-05 19:04:51 +0000 | [diff] [blame] | 245 | try: |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 246 | pwent = pwd.getpwnam(name) |
Guido van Rossum | 346f7af | 1997-12-05 19:04:51 +0000 | [diff] [blame] | 247 | except KeyError: |
| 248 | return path |
Walter Dörwald | 77cdeaf | 2003-06-17 13:13:40 +0000 | [diff] [blame] | 249 | userhome = pwent.pw_dir |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 250 | if isinstance(path, bytes): |
Victor Stinner | 16004ac | 2010-09-29 16:59:18 +0000 | [diff] [blame] | 251 | userhome = os.fsencode(userhome) |
Benjamin Peterson | ef3e4c2 | 2009-04-11 19:48:14 +0000 | [diff] [blame] | 252 | root = b'/' |
| 253 | else: |
| 254 | root = '/' |
Jesus Cea | 7f0d888 | 2012-05-10 05:10:50 +0200 | [diff] [blame] | 255 | userhome = userhome.rstrip(root) |
| 256 | return (userhome + path[i:]) or root |
Guido van Rossum | 4732ccf | 1992-08-09 13:54:50 +0000 | [diff] [blame] | 257 | |
| 258 | |
| 259 | # Expand paths containing shell variable substitutions. |
Guido van Rossum | b6775db | 1994-08-01 11:34:53 +0000 | [diff] [blame] | 260 | # This expands the forms $variable and ${variable} only. |
Jeremy Hylton | a05e293 | 2000-06-28 14:48:01 +0000 | [diff] [blame] | 261 | # Non-existent variables are left unchanged. |
Guido van Rossum | b6775db | 1994-08-01 11:34:53 +0000 | [diff] [blame] | 262 | |
| 263 | _varprog = None |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 264 | _varprogb = None |
Guido van Rossum | 4732ccf | 1992-08-09 13:54:50 +0000 | [diff] [blame] | 265 | |
| 266 | def expandvars(path): |
Guido van Rossum | 346f7af | 1997-12-05 19:04:51 +0000 | [diff] [blame] | 267 | """Expand shell variables of form $var and ${var}. Unknown variables |
Fred Drake | c0ab93e | 2000-09-28 16:22:52 +0000 | [diff] [blame] | 268 | are left unchanged.""" |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 269 | global _varprog, _varprogb |
| 270 | if isinstance(path, bytes): |
| 271 | if b'$' not in path: |
| 272 | return path |
| 273 | if not _varprogb: |
| 274 | import re |
| 275 | _varprogb = re.compile(br'\$(\w+|\{[^}]*\})', re.ASCII) |
| 276 | search = _varprogb.search |
| 277 | start = b'{' |
| 278 | end = b'}' |
Serhiy Storchaka | dbb1019 | 2014-02-13 10:13:53 +0200 | [diff] [blame] | 279 | environ = getattr(os, 'environb', None) |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 280 | else: |
| 281 | if '$' not in path: |
| 282 | return path |
| 283 | if not _varprog: |
| 284 | import re |
| 285 | _varprog = re.compile(r'\$(\w+|\{[^}]*\})', re.ASCII) |
| 286 | search = _varprog.search |
| 287 | start = '{' |
| 288 | end = '}' |
Serhiy Storchaka | dbb1019 | 2014-02-13 10:13:53 +0200 | [diff] [blame] | 289 | environ = os.environ |
Guido van Rossum | 346f7af | 1997-12-05 19:04:51 +0000 | [diff] [blame] | 290 | i = 0 |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 291 | while True: |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 292 | m = search(path, i) |
Guido van Rossum | 346f7af | 1997-12-05 19:04:51 +0000 | [diff] [blame] | 293 | if not m: |
| 294 | break |
| 295 | i, j = m.span(0) |
| 296 | name = m.group(1) |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 297 | if name.startswith(start) and name.endswith(end): |
Guido van Rossum | 346f7af | 1997-12-05 19:04:51 +0000 | [diff] [blame] | 298 | name = name[1:-1] |
Serhiy Storchaka | dbb1019 | 2014-02-13 10:13:53 +0200 | [diff] [blame] | 299 | try: |
| 300 | if environ is None: |
Serhiy Storchaka | ffadbb7 | 2014-02-13 10:45:14 +0200 | [diff] [blame] | 301 | value = os.fsencode(os.environ[os.fsdecode(name)]) |
Serhiy Storchaka | dbb1019 | 2014-02-13 10:13:53 +0200 | [diff] [blame] | 302 | else: |
| 303 | value = environ[name] |
| 304 | except KeyError: |
| 305 | i = j |
| 306 | else: |
Guido van Rossum | 346f7af | 1997-12-05 19:04:51 +0000 | [diff] [blame] | 307 | tail = path[j:] |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 308 | path = path[:i] + value |
Guido van Rossum | 346f7af | 1997-12-05 19:04:51 +0000 | [diff] [blame] | 309 | i = len(path) |
Walter Dörwald | 77cdeaf | 2003-06-17 13:13:40 +0000 | [diff] [blame] | 310 | path += tail |
Guido van Rossum | 346f7af | 1997-12-05 19:04:51 +0000 | [diff] [blame] | 311 | return path |
Guido van Rossum | c629d34 | 1992-11-05 10:43:02 +0000 | [diff] [blame] | 312 | |
| 313 | |
| 314 | # Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B. |
| 315 | # It should be understood that this may change the meaning of the path |
| 316 | # if it contains symbolic links! |
| 317 | |
| 318 | def normpath(path): |
Guido van Rossum | 346f7af | 1997-12-05 19:04:51 +0000 | [diff] [blame] | 319 | """Normalize path, eliminating double slashes, etc.""" |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 320 | if isinstance(path, bytes): |
| 321 | sep = b'/' |
| 322 | empty = b'' |
| 323 | dot = b'.' |
| 324 | dotdot = b'..' |
| 325 | else: |
| 326 | sep = '/' |
| 327 | empty = '' |
| 328 | dot = '.' |
| 329 | dotdot = '..' |
| 330 | if path == empty: |
| 331 | return dot |
| 332 | initial_slashes = path.startswith(sep) |
Marc-André Lemburg | bf222c9 | 2001-01-29 11:29:44 +0000 | [diff] [blame] | 333 | # POSIX allows one or two initial slashes, but treats three or more |
| 334 | # as single slash. |
Tim Peters | 658cba6 | 2001-02-09 20:06:00 +0000 | [diff] [blame] | 335 | if (initial_slashes and |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 336 | path.startswith(sep*2) and not path.startswith(sep*3)): |
Marc-André Lemburg | bf222c9 | 2001-01-29 11:29:44 +0000 | [diff] [blame] | 337 | initial_slashes = 2 |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 338 | comps = path.split(sep) |
Skip Montanaro | 018dfae | 2000-07-19 17:09:51 +0000 | [diff] [blame] | 339 | new_comps = [] |
| 340 | for comp in comps: |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 341 | if comp in (empty, dot): |
Skip Montanaro | 018dfae | 2000-07-19 17:09:51 +0000 | [diff] [blame] | 342 | continue |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 343 | if (comp != dotdot or (not initial_slashes and not new_comps) or |
| 344 | (new_comps and new_comps[-1] == dotdot)): |
Skip Montanaro | 018dfae | 2000-07-19 17:09:51 +0000 | [diff] [blame] | 345 | new_comps.append(comp) |
| 346 | elif new_comps: |
| 347 | new_comps.pop() |
| 348 | comps = new_comps |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 349 | path = sep.join(comps) |
Marc-André Lemburg | bf222c9 | 2001-01-29 11:29:44 +0000 | [diff] [blame] | 350 | if initial_slashes: |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 351 | path = sep*initial_slashes + path |
| 352 | return path or dot |
Guido van Rossum | e294cf6 | 1999-01-29 18:05:18 +0000 | [diff] [blame] | 353 | |
| 354 | |
Guido van Rossum | e294cf6 | 1999-01-29 18:05:18 +0000 | [diff] [blame] | 355 | def abspath(path): |
Guido van Rossum | 54f22ed | 2000-02-04 15:10:34 +0000 | [diff] [blame] | 356 | """Return an absolute path.""" |
Guido van Rossum | e294cf6 | 1999-01-29 18:05:18 +0000 | [diff] [blame] | 357 | if not isabs(path): |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 358 | if isinstance(path, bytes): |
| 359 | cwd = os.getcwdb() |
| 360 | else: |
| 361 | cwd = os.getcwd() |
| 362 | path = join(cwd, path) |
Guido van Rossum | e294cf6 | 1999-01-29 18:05:18 +0000 | [diff] [blame] | 363 | return normpath(path) |
Guido van Rossum | 83eeef4 | 2001-09-17 15:16:09 +0000 | [diff] [blame] | 364 | |
| 365 | |
| 366 | # Return a canonical path (i.e. the absolute location of a file on the |
| 367 | # filesystem). |
| 368 | |
| 369 | def realpath(filename): |
| 370 | """Return the canonical path of the specified filename, eliminating any |
| 371 | symbolic links encountered in the path.""" |
Serhiy Storchaka | df32691 | 2013-02-10 12:22:07 +0200 | [diff] [blame] | 372 | path, ok = _joinrealpath(filename[:0], filename, {}) |
| 373 | return abspath(path) |
| 374 | |
Martin Panter | 119e502 | 2016-04-16 09:28:57 +0000 | [diff] [blame] | 375 | # Join two paths, normalizing and eliminating any symbolic links |
Serhiy Storchaka | df32691 | 2013-02-10 12:22:07 +0200 | [diff] [blame] | 376 | # encountered in the second path. |
| 377 | def _joinrealpath(path, rest, seen): |
| 378 | if isinstance(path, bytes): |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 379 | sep = b'/' |
Serhiy Storchaka | df32691 | 2013-02-10 12:22:07 +0200 | [diff] [blame] | 380 | curdir = b'.' |
| 381 | pardir = b'..' |
Johannes Gijsbers | 4ec4064 | 2004-08-14 15:01:53 +0000 | [diff] [blame] | 382 | else: |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 383 | sep = '/' |
Serhiy Storchaka | df32691 | 2013-02-10 12:22:07 +0200 | [diff] [blame] | 384 | curdir = '.' |
| 385 | pardir = '..' |
Tim Peters | a45cacf | 2004-08-20 03:47:14 +0000 | [diff] [blame] | 386 | |
Serhiy Storchaka | df32691 | 2013-02-10 12:22:07 +0200 | [diff] [blame] | 387 | if isabs(rest): |
| 388 | rest = rest[1:] |
| 389 | path = sep |
| 390 | |
| 391 | while rest: |
| 392 | name, _, rest = rest.partition(sep) |
| 393 | if not name or name == curdir: |
| 394 | # current dir |
| 395 | continue |
| 396 | if name == pardir: |
| 397 | # parent dir |
| 398 | if path: |
Serhiy Storchaka | 467393d | 2013-02-18 12:21:04 +0200 | [diff] [blame] | 399 | path, name = split(path) |
| 400 | if name == pardir: |
| 401 | path = join(path, pardir, pardir) |
Brett Cannon | f50299c | 2004-07-10 22:55:15 +0000 | [diff] [blame] | 402 | else: |
Serhiy Storchaka | 467393d | 2013-02-18 12:21:04 +0200 | [diff] [blame] | 403 | path = pardir |
Serhiy Storchaka | df32691 | 2013-02-10 12:22:07 +0200 | [diff] [blame] | 404 | continue |
| 405 | newpath = join(path, name) |
| 406 | if not islink(newpath): |
| 407 | path = newpath |
| 408 | continue |
| 409 | # Resolve the symbolic link |
| 410 | if newpath in seen: |
| 411 | # Already seen this path |
| 412 | path = seen[newpath] |
| 413 | if path is not None: |
| 414 | # use cached value |
| 415 | continue |
| 416 | # The symlink is not resolved, so we must have a symlink loop. |
| 417 | # Return already resolved part + rest of the path unchanged. |
| 418 | return join(newpath, rest), False |
| 419 | seen[newpath] = None # not resolved symlink |
| 420 | path, ok = _joinrealpath(path, os.readlink(newpath), seen) |
| 421 | if not ok: |
| 422 | return join(path, rest), False |
| 423 | seen[newpath] = path # resolved symlink |
Tim Peters | b64bec3 | 2001-09-18 02:26:39 +0000 | [diff] [blame] | 424 | |
Serhiy Storchaka | df32691 | 2013-02-10 12:22:07 +0200 | [diff] [blame] | 425 | return path, True |
Tim Peters | a45cacf | 2004-08-20 03:47:14 +0000 | [diff] [blame] | 426 | |
Brett Cannon | f50299c | 2004-07-10 22:55:15 +0000 | [diff] [blame] | 427 | |
Victor Stinner | e797c16 | 2010-09-17 23:34:26 +0000 | [diff] [blame] | 428 | supports_unicode_filenames = (sys.platform == 'darwin') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 429 | |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 430 | def relpath(path, start=None): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 431 | """Return a relative version of a path""" |
| 432 | |
| 433 | if not path: |
| 434 | raise ValueError("no path specified") |
| 435 | |
Guido van Rossum | f0af3e3 | 2008-10-02 18:55:37 +0000 | [diff] [blame] | 436 | if isinstance(path, bytes): |
| 437 | curdir = b'.' |
| 438 | sep = b'/' |
| 439 | pardir = b'..' |
| 440 | else: |
| 441 | curdir = '.' |
| 442 | sep = '/' |
| 443 | pardir = '..' |
| 444 | |
| 445 | if start is None: |
| 446 | start = curdir |
| 447 | |
Serhiy Storchaka | 3deeeb0 | 2014-10-04 14:58:43 +0300 | [diff] [blame] | 448 | try: |
| 449 | start_list = [x for x in abspath(start).split(sep) if x] |
| 450 | path_list = [x for x in abspath(path).split(sep) if x] |
| 451 | # Work out how much of the filepath is shared by start and path. |
| 452 | i = len(commonprefix([start_list, path_list])) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 453 | |
Serhiy Storchaka | 3deeeb0 | 2014-10-04 14:58:43 +0300 | [diff] [blame] | 454 | rel_list = [pardir] * (len(start_list)-i) + path_list[i:] |
| 455 | if not rel_list: |
| 456 | return curdir |
| 457 | return join(*rel_list) |
Serhiy Storchaka | e4f4708 | 2014-10-04 16:09:02 +0300 | [diff] [blame] | 458 | except (TypeError, AttributeError, BytesWarning, DeprecationWarning): |
Serhiy Storchaka | 3deeeb0 | 2014-10-04 14:58:43 +0300 | [diff] [blame] | 459 | genericpath._check_arg_types('relpath', path, start) |
| 460 | raise |
Serhiy Storchaka | 3822093 | 2015-03-31 15:31:53 +0300 | [diff] [blame] | 461 | |
| 462 | |
| 463 | # Return the longest common sub-path of the sequence of paths given as input. |
| 464 | # The paths are not normalized before comparing them (this is the |
| 465 | # responsibility of the caller). Any trailing separator is stripped from the |
| 466 | # returned path. |
| 467 | |
| 468 | def commonpath(paths): |
| 469 | """Given a sequence of path names, returns the longest common sub-path.""" |
| 470 | |
| 471 | if not paths: |
| 472 | raise ValueError('commonpath() arg is an empty sequence') |
| 473 | |
| 474 | if isinstance(paths[0], bytes): |
| 475 | sep = b'/' |
| 476 | curdir = b'.' |
| 477 | else: |
| 478 | sep = '/' |
| 479 | curdir = '.' |
| 480 | |
| 481 | try: |
| 482 | split_paths = [path.split(sep) for path in paths] |
| 483 | |
| 484 | try: |
| 485 | isabs, = set(p[:1] == sep for p in paths) |
| 486 | except ValueError: |
| 487 | raise ValueError("Can't mix absolute and relative paths") from None |
| 488 | |
| 489 | split_paths = [[c for c in s if c and c != curdir] for s in split_paths] |
| 490 | s1 = min(split_paths) |
| 491 | s2 = max(split_paths) |
| 492 | common = s1 |
| 493 | for i, c in enumerate(s1): |
| 494 | if c != s2[i]: |
| 495 | common = s1[:i] |
| 496 | break |
| 497 | |
| 498 | prefix = sep if isabs else sep[:0] |
| 499 | return prefix + sep.join(common) |
| 500 | except (TypeError, AttributeError): |
| 501 | genericpath._check_arg_types('commonpath', *paths) |
| 502 | raise |