Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1 | import fnmatch |
| 2 | import functools |
| 3 | import io |
| 4 | import ntpath |
| 5 | import os |
| 6 | import posixpath |
| 7 | import re |
| 8 | import sys |
Serhiy Storchaka | 8110837 | 2017-09-26 00:55:55 +0300 | [diff] [blame] | 9 | from _collections_abc import Sequence |
Jörg Stucke | d5c120f | 2019-05-21 19:44:40 +0200 | [diff] [blame] | 10 | from errno import EINVAL, ENOENT, ENOTDIR, EBADF, ELOOP |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 11 | from operator import attrgetter |
| 12 | from stat import S_ISDIR, S_ISLNK, S_ISREG, S_ISSOCK, S_ISBLK, S_ISCHR, S_ISFIFO |
Antoine Pitrou | 069a5e1 | 2013-12-03 09:41:35 +0100 | [diff] [blame] | 13 | from urllib.parse import quote_from_bytes as urlquote_from_bytes |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 14 | |
| 15 | |
| 16 | supports_symlinks = True |
Antoine Pitrou | db118f5 | 2014-11-19 00:32:08 +0100 | [diff] [blame] | 17 | if os.name == 'nt': |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 18 | import nt |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 19 | if sys.getwindowsversion()[:2] >= (6, 0): |
| 20 | from nt import _getfinalpathname |
| 21 | else: |
| 22 | supports_symlinks = False |
| 23 | _getfinalpathname = None |
Antoine Pitrou | db118f5 | 2014-11-19 00:32:08 +0100 | [diff] [blame] | 24 | else: |
| 25 | nt = None |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 26 | |
| 27 | |
| 28 | __all__ = [ |
| 29 | "PurePath", "PurePosixPath", "PureWindowsPath", |
| 30 | "Path", "PosixPath", "WindowsPath", |
| 31 | ] |
| 32 | |
| 33 | # |
| 34 | # Internals |
| 35 | # |
| 36 | |
penguindustin | 9646630 | 2019-05-06 14:57:17 -0400 | [diff] [blame] | 37 | # EBADF - guard against macOS `stat` throwing EBADF |
Jörg Stucke | d5c120f | 2019-05-21 19:44:40 +0200 | [diff] [blame] | 38 | _IGNORED_ERROS = (ENOENT, ENOTDIR, EBADF, ELOOP) |
Przemysław Spodymek | 216b745 | 2018-08-27 23:33:45 +0200 | [diff] [blame] | 39 | |
Steve Dower | 2f6fae6 | 2019-02-03 23:08:18 -0800 | [diff] [blame] | 40 | _IGNORED_WINERRORS = ( |
| 41 | 21, # ERROR_NOT_READY - drive exists but is not accessible |
Jörg Stucke | d5c120f | 2019-05-21 19:44:40 +0200 | [diff] [blame] | 42 | 1921, # ERROR_CANT_RESOLVE_FILENAME - fix for broken symlink pointing to itself |
Steve Dower | 2f6fae6 | 2019-02-03 23:08:18 -0800 | [diff] [blame] | 43 | ) |
| 44 | |
| 45 | def _ignore_error(exception): |
| 46 | return (getattr(exception, 'errno', None) in _IGNORED_ERROS or |
| 47 | getattr(exception, 'winerror', None) in _IGNORED_WINERRORS) |
| 48 | |
| 49 | |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 50 | def _is_wildcard_pattern(pat): |
| 51 | # Whether this pattern needs actual matching using fnmatch, or can |
| 52 | # be looked up directly as a file. |
| 53 | return "*" in pat or "?" in pat or "[" in pat |
| 54 | |
| 55 | |
| 56 | class _Flavour(object): |
| 57 | """A flavour implements a particular (platform-specific) set of path |
| 58 | semantics.""" |
| 59 | |
| 60 | def __init__(self): |
| 61 | self.join = self.sep.join |
| 62 | |
| 63 | def parse_parts(self, parts): |
| 64 | parsed = [] |
| 65 | sep = self.sep |
| 66 | altsep = self.altsep |
| 67 | drv = root = '' |
| 68 | it = reversed(parts) |
| 69 | for part in it: |
| 70 | if not part: |
| 71 | continue |
| 72 | if altsep: |
| 73 | part = part.replace(altsep, sep) |
| 74 | drv, root, rel = self.splitroot(part) |
| 75 | if sep in rel: |
| 76 | for x in reversed(rel.split(sep)): |
| 77 | if x and x != '.': |
| 78 | parsed.append(sys.intern(x)) |
| 79 | else: |
| 80 | if rel and rel != '.': |
| 81 | parsed.append(sys.intern(rel)) |
| 82 | if drv or root: |
| 83 | if not drv: |
| 84 | # If no drive is present, try to find one in the previous |
| 85 | # parts. This makes the result of parsing e.g. |
| 86 | # ("C:", "/", "a") reasonably intuitive. |
| 87 | for part in it: |
Antoine Pitrou | 57fffd6 | 2015-02-15 18:03:59 +0100 | [diff] [blame] | 88 | if not part: |
| 89 | continue |
| 90 | if altsep: |
| 91 | part = part.replace(altsep, sep) |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 92 | drv = self.splitroot(part)[0] |
| 93 | if drv: |
| 94 | break |
| 95 | break |
| 96 | if drv or root: |
| 97 | parsed.append(drv + root) |
| 98 | parsed.reverse() |
| 99 | return drv, root, parsed |
| 100 | |
| 101 | def join_parsed_parts(self, drv, root, parts, drv2, root2, parts2): |
| 102 | """ |
| 103 | Join the two paths represented by the respective |
| 104 | (drive, root, parts) tuples. Return a new (drive, root, parts) tuple. |
| 105 | """ |
| 106 | if root2: |
Serhiy Storchaka | a993902 | 2013-12-06 17:14:12 +0200 | [diff] [blame] | 107 | if not drv2 and drv: |
| 108 | return drv, root2, [drv + root2] + parts2[1:] |
| 109 | elif drv2: |
| 110 | if drv2 == drv or self.casefold(drv2) == self.casefold(drv): |
| 111 | # Same drive => second path is relative to the first |
| 112 | return drv, root, parts + parts2[1:] |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 113 | else: |
Serhiy Storchaka | a993902 | 2013-12-06 17:14:12 +0200 | [diff] [blame] | 114 | # Second path is non-anchored (common case) |
| 115 | return drv, root, parts + parts2 |
| 116 | return drv2, root2, parts2 |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 117 | |
| 118 | |
| 119 | class _WindowsFlavour(_Flavour): |
| 120 | # Reference for Windows paths can be found at |
| 121 | # http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx |
| 122 | |
| 123 | sep = '\\' |
| 124 | altsep = '/' |
| 125 | has_drv = True |
| 126 | pathmod = ntpath |
| 127 | |
Antoine Pitrou | db118f5 | 2014-11-19 00:32:08 +0100 | [diff] [blame] | 128 | is_supported = (os.name == 'nt') |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 129 | |
Jon Dufresne | 3972628 | 2017-05-18 07:35:54 -0700 | [diff] [blame] | 130 | drive_letters = set('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 131 | ext_namespace_prefix = '\\\\?\\' |
| 132 | |
| 133 | reserved_names = ( |
| 134 | {'CON', 'PRN', 'AUX', 'NUL'} | |
| 135 | {'COM%d' % i for i in range(1, 10)} | |
| 136 | {'LPT%d' % i for i in range(1, 10)} |
| 137 | ) |
| 138 | |
| 139 | # Interesting findings about extended paths: |
| 140 | # - '\\?\c:\a', '//?/c:\a' and '//?/c:/a' are all supported |
| 141 | # but '\\?\c:/a' is not |
| 142 | # - extended paths are always absolute; "relative" extended paths will |
| 143 | # fail. |
| 144 | |
| 145 | def splitroot(self, part, sep=sep): |
| 146 | first = part[0:1] |
| 147 | second = part[1:2] |
| 148 | if (second == sep and first == sep): |
| 149 | # XXX extended paths should also disable the collapsing of "." |
| 150 | # components (according to MSDN docs). |
| 151 | prefix, part = self._split_extended_path(part) |
| 152 | first = part[0:1] |
| 153 | second = part[1:2] |
| 154 | else: |
| 155 | prefix = '' |
| 156 | third = part[2:3] |
| 157 | if (second == sep and first == sep and third != sep): |
| 158 | # is a UNC path: |
| 159 | # vvvvvvvvvvvvvvvvvvvvv root |
| 160 | # \\machine\mountpoint\directory\etc\... |
| 161 | # directory ^^^^^^^^^^^^^^ |
| 162 | index = part.find(sep, 2) |
| 163 | if index != -1: |
| 164 | index2 = part.find(sep, index + 1) |
| 165 | # a UNC path can't have two slashes in a row |
| 166 | # (after the initial two) |
| 167 | if index2 != index + 1: |
| 168 | if index2 == -1: |
| 169 | index2 = len(part) |
| 170 | if prefix: |
| 171 | return prefix + part[1:index2], sep, part[index2+1:] |
| 172 | else: |
| 173 | return part[:index2], sep, part[index2+1:] |
| 174 | drv = root = '' |
| 175 | if second == ':' and first in self.drive_letters: |
| 176 | drv = part[:2] |
| 177 | part = part[2:] |
| 178 | first = third |
| 179 | if first == sep: |
| 180 | root = first |
| 181 | part = part.lstrip(sep) |
| 182 | return prefix + drv, root, part |
| 183 | |
| 184 | def casefold(self, s): |
| 185 | return s.lower() |
| 186 | |
| 187 | def casefold_parts(self, parts): |
| 188 | return [p.lower() for p in parts] |
| 189 | |
Serhiy Storchaka | 10ecbad | 2019-10-21 20:37:15 +0300 | [diff] [blame] | 190 | def compile_pattern(self, pattern): |
| 191 | return re.compile(fnmatch.translate(pattern), re.IGNORECASE).fullmatch |
| 192 | |
Steve Dower | 98eb360 | 2016-11-09 12:58:17 -0800 | [diff] [blame] | 193 | def resolve(self, path, strict=False): |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 194 | s = str(path) |
| 195 | if not s: |
| 196 | return os.getcwd() |
Steve Dower | 98eb360 | 2016-11-09 12:58:17 -0800 | [diff] [blame] | 197 | previous_s = None |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 198 | if _getfinalpathname is not None: |
Steve Dower | 98eb360 | 2016-11-09 12:58:17 -0800 | [diff] [blame] | 199 | if strict: |
| 200 | return self._ext_to_normal(_getfinalpathname(s)) |
| 201 | else: |
Antoine Pietri | add98eb | 2017-06-07 17:29:17 +0200 | [diff] [blame] | 202 | tail_parts = [] # End of the path after the first one not found |
Steve Dower | 98eb360 | 2016-11-09 12:58:17 -0800 | [diff] [blame] | 203 | while True: |
| 204 | try: |
| 205 | s = self._ext_to_normal(_getfinalpathname(s)) |
| 206 | except FileNotFoundError: |
| 207 | previous_s = s |
Antoine Pietri | add98eb | 2017-06-07 17:29:17 +0200 | [diff] [blame] | 208 | s, tail = os.path.split(s) |
| 209 | tail_parts.append(tail) |
Steve Dower | 4b1e98b | 2016-12-28 16:02:59 -0800 | [diff] [blame] | 210 | if previous_s == s: |
| 211 | return path |
Steve Dower | 98eb360 | 2016-11-09 12:58:17 -0800 | [diff] [blame] | 212 | else: |
Antoine Pietri | add98eb | 2017-06-07 17:29:17 +0200 | [diff] [blame] | 213 | return os.path.join(s, *reversed(tail_parts)) |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 214 | # Means fallback on absolute |
| 215 | return None |
| 216 | |
| 217 | def _split_extended_path(self, s, ext_prefix=ext_namespace_prefix): |
| 218 | prefix = '' |
| 219 | if s.startswith(ext_prefix): |
| 220 | prefix = s[:4] |
| 221 | s = s[4:] |
| 222 | if s.startswith('UNC\\'): |
| 223 | prefix += s[:3] |
| 224 | s = '\\' + s[3:] |
| 225 | return prefix, s |
| 226 | |
| 227 | def _ext_to_normal(self, s): |
| 228 | # Turn back an extended path into a normal DOS-like path |
| 229 | return self._split_extended_path(s)[1] |
| 230 | |
| 231 | def is_reserved(self, parts): |
| 232 | # NOTE: the rules for reserved names seem somewhat complicated |
| 233 | # (e.g. r"..\NUL" is reserved but not r"foo\NUL"). |
| 234 | # We err on the side of caution and return True for paths which are |
| 235 | # not considered reserved by Windows. |
| 236 | if not parts: |
| 237 | return False |
| 238 | if parts[0].startswith('\\\\'): |
| 239 | # UNC paths are never reserved |
| 240 | return False |
| 241 | return parts[-1].partition('.')[0].upper() in self.reserved_names |
| 242 | |
| 243 | def make_uri(self, path): |
| 244 | # Under Windows, file URIs use the UTF-8 encoding. |
| 245 | drive = path.drive |
| 246 | if len(drive) == 2 and drive[1] == ':': |
| 247 | # It's a path on a local drive => 'file:///c:/a/b' |
| 248 | rest = path.as_posix()[2:].lstrip('/') |
| 249 | return 'file:///%s/%s' % ( |
| 250 | drive, urlquote_from_bytes(rest.encode('utf-8'))) |
| 251 | else: |
| 252 | # It's a path on a network drive => 'file://host/share/a/b' |
| 253 | return 'file:' + urlquote_from_bytes(path.as_posix().encode('utf-8')) |
| 254 | |
Antoine Pitrou | 8477ed6 | 2014-12-30 20:54:45 +0100 | [diff] [blame] | 255 | def gethomedir(self, username): |
Christoph Reiter | c45a2aa | 2020-01-28 10:41:50 +0100 | [diff] [blame] | 256 | if 'USERPROFILE' in os.environ: |
Antoine Pitrou | 8477ed6 | 2014-12-30 20:54:45 +0100 | [diff] [blame] | 257 | userhome = os.environ['USERPROFILE'] |
| 258 | elif 'HOMEPATH' in os.environ: |
Antoine Pitrou | 5d4e27e | 2014-12-30 22:09:42 +0100 | [diff] [blame] | 259 | try: |
| 260 | drv = os.environ['HOMEDRIVE'] |
| 261 | except KeyError: |
| 262 | drv = '' |
| 263 | userhome = drv + os.environ['HOMEPATH'] |
Antoine Pitrou | 8477ed6 | 2014-12-30 20:54:45 +0100 | [diff] [blame] | 264 | else: |
| 265 | raise RuntimeError("Can't determine home directory") |
| 266 | |
| 267 | if username: |
| 268 | # Try to guess user home directory. By default all users |
| 269 | # directories are located in the same place and are named by |
| 270 | # corresponding usernames. If current user home directory points |
| 271 | # to nonstandard place, this guess is likely wrong. |
| 272 | if os.environ['USERNAME'] != username: |
| 273 | drv, root, parts = self.parse_parts((userhome,)) |
| 274 | if parts[-1] != os.environ['USERNAME']: |
| 275 | raise RuntimeError("Can't determine home directory " |
| 276 | "for %r" % username) |
| 277 | parts[-1] = username |
| 278 | if drv or root: |
| 279 | userhome = drv + root + self.join(parts[1:]) |
| 280 | else: |
| 281 | userhome = self.join(parts) |
| 282 | return userhome |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 283 | |
| 284 | class _PosixFlavour(_Flavour): |
| 285 | sep = '/' |
| 286 | altsep = '' |
| 287 | has_drv = False |
| 288 | pathmod = posixpath |
| 289 | |
| 290 | is_supported = (os.name != 'nt') |
| 291 | |
| 292 | def splitroot(self, part, sep=sep): |
| 293 | if part and part[0] == sep: |
| 294 | stripped_part = part.lstrip(sep) |
| 295 | # According to POSIX path resolution: |
| 296 | # http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap04.html#tag_04_11 |
| 297 | # "A pathname that begins with two successive slashes may be |
| 298 | # interpreted in an implementation-defined manner, although more |
| 299 | # than two leading slashes shall be treated as a single slash". |
| 300 | if len(part) - len(stripped_part) == 2: |
| 301 | return '', sep * 2, stripped_part |
| 302 | else: |
| 303 | return '', sep, stripped_part |
| 304 | else: |
| 305 | return '', '', part |
| 306 | |
| 307 | def casefold(self, s): |
| 308 | return s |
| 309 | |
| 310 | def casefold_parts(self, parts): |
| 311 | return parts |
| 312 | |
Serhiy Storchaka | 10ecbad | 2019-10-21 20:37:15 +0300 | [diff] [blame] | 313 | def compile_pattern(self, pattern): |
| 314 | return re.compile(fnmatch.translate(pattern)).fullmatch |
| 315 | |
Steve Dower | 98eb360 | 2016-11-09 12:58:17 -0800 | [diff] [blame] | 316 | def resolve(self, path, strict=False): |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 317 | sep = self.sep |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 318 | accessor = path._accessor |
Antoine Pitrou | c274fd2 | 2013-12-16 19:57:41 +0100 | [diff] [blame] | 319 | seen = {} |
| 320 | def _resolve(path, rest): |
| 321 | if rest.startswith(sep): |
| 322 | path = '' |
| 323 | |
| 324 | for name in rest.split(sep): |
| 325 | if not name or name == '.': |
| 326 | # current dir |
| 327 | continue |
| 328 | if name == '..': |
| 329 | # parent dir |
| 330 | path, _, _ = path.rpartition(sep) |
| 331 | continue |
| 332 | newpath = path + sep + name |
| 333 | if newpath in seen: |
| 334 | # Already seen this path |
| 335 | path = seen[newpath] |
| 336 | if path is not None: |
| 337 | # use cached value |
| 338 | continue |
| 339 | # The symlink is not resolved, so we must have a symlink loop. |
| 340 | raise RuntimeError("Symlink loop from %r" % newpath) |
| 341 | # Resolve the symbolic link |
| 342 | try: |
| 343 | target = accessor.readlink(newpath) |
| 344 | except OSError as e: |
Antoine Pietri | add98eb | 2017-06-07 17:29:17 +0200 | [diff] [blame] | 345 | if e.errno != EINVAL and strict: |
| 346 | raise |
| 347 | # Not a symlink, or non-strict mode. We just leave the path |
| 348 | # untouched. |
Antoine Pitrou | c274fd2 | 2013-12-16 19:57:41 +0100 | [diff] [blame] | 349 | path = newpath |
| 350 | else: |
| 351 | seen[newpath] = None # not resolved symlink |
| 352 | path = _resolve(path, target) |
| 353 | seen[newpath] = path # resolved symlink |
| 354 | |
| 355 | return path |
| 356 | # NOTE: according to POSIX, getcwd() cannot contain path components |
| 357 | # which are symlinks. |
| 358 | base = '' if path.is_absolute() else os.getcwd() |
| 359 | return _resolve(base, str(path)) or sep |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 360 | |
| 361 | def is_reserved(self, parts): |
| 362 | return False |
| 363 | |
| 364 | def make_uri(self, path): |
| 365 | # We represent the path using the local filesystem encoding, |
| 366 | # for portability to other applications. |
| 367 | bpath = bytes(path) |
| 368 | return 'file://' + urlquote_from_bytes(bpath) |
| 369 | |
Antoine Pitrou | 8477ed6 | 2014-12-30 20:54:45 +0100 | [diff] [blame] | 370 | def gethomedir(self, username): |
| 371 | if not username: |
| 372 | try: |
| 373 | return os.environ['HOME'] |
| 374 | except KeyError: |
| 375 | import pwd |
| 376 | return pwd.getpwuid(os.getuid()).pw_dir |
| 377 | else: |
| 378 | import pwd |
| 379 | try: |
| 380 | return pwd.getpwnam(username).pw_dir |
| 381 | except KeyError: |
| 382 | raise RuntimeError("Can't determine home directory " |
| 383 | "for %r" % username) |
| 384 | |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 385 | |
| 386 | _windows_flavour = _WindowsFlavour() |
| 387 | _posix_flavour = _PosixFlavour() |
| 388 | |
| 389 | |
| 390 | class _Accessor: |
| 391 | """An accessor implements a particular (system-specific or not) way of |
| 392 | accessing paths on the filesystem.""" |
| 393 | |
| 394 | |
| 395 | class _NormalAccessor(_Accessor): |
| 396 | |
Serhiy Storchaka | 62a9951 | 2017-03-25 13:42:11 +0200 | [diff] [blame] | 397 | stat = os.stat |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 398 | |
Serhiy Storchaka | 62a9951 | 2017-03-25 13:42:11 +0200 | [diff] [blame] | 399 | lstat = os.lstat |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 400 | |
Serhiy Storchaka | 62a9951 | 2017-03-25 13:42:11 +0200 | [diff] [blame] | 401 | open = os.open |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 402 | |
Serhiy Storchaka | 62a9951 | 2017-03-25 13:42:11 +0200 | [diff] [blame] | 403 | listdir = os.listdir |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 404 | |
Serhiy Storchaka | 62a9951 | 2017-03-25 13:42:11 +0200 | [diff] [blame] | 405 | scandir = os.scandir |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 406 | |
Serhiy Storchaka | 62a9951 | 2017-03-25 13:42:11 +0200 | [diff] [blame] | 407 | chmod = os.chmod |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 408 | |
| 409 | if hasattr(os, "lchmod"): |
Serhiy Storchaka | 62a9951 | 2017-03-25 13:42:11 +0200 | [diff] [blame] | 410 | lchmod = os.lchmod |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 411 | else: |
| 412 | def lchmod(self, pathobj, mode): |
| 413 | raise NotImplementedError("lchmod() not available on this system") |
| 414 | |
Serhiy Storchaka | 62a9951 | 2017-03-25 13:42:11 +0200 | [diff] [blame] | 415 | mkdir = os.mkdir |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 416 | |
Serhiy Storchaka | 62a9951 | 2017-03-25 13:42:11 +0200 | [diff] [blame] | 417 | unlink = os.unlink |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 418 | |
Toke Høiland-Jørgensen | 092435e | 2019-12-16 13:23:55 +0100 | [diff] [blame] | 419 | if hasattr(os, "link"): |
| 420 | link_to = os.link |
| 421 | else: |
| 422 | @staticmethod |
| 423 | def link_to(self, target): |
| 424 | raise NotImplementedError("os.link() not available on this system") |
Joannah Nanjekye | 6b5b013 | 2019-05-04 11:27:10 -0400 | [diff] [blame] | 425 | |
Serhiy Storchaka | 62a9951 | 2017-03-25 13:42:11 +0200 | [diff] [blame] | 426 | rmdir = os.rmdir |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 427 | |
Serhiy Storchaka | 62a9951 | 2017-03-25 13:42:11 +0200 | [diff] [blame] | 428 | rename = os.rename |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 429 | |
Serhiy Storchaka | 62a9951 | 2017-03-25 13:42:11 +0200 | [diff] [blame] | 430 | replace = os.replace |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 431 | |
| 432 | if nt: |
| 433 | if supports_symlinks: |
Serhiy Storchaka | 62a9951 | 2017-03-25 13:42:11 +0200 | [diff] [blame] | 434 | symlink = os.symlink |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 435 | else: |
| 436 | def symlink(a, b, target_is_directory): |
| 437 | raise NotImplementedError("symlink() not available on this system") |
| 438 | else: |
| 439 | # Under POSIX, os.symlink() takes two args |
| 440 | @staticmethod |
| 441 | def symlink(a, b, target_is_directory): |
Serhiy Storchaka | 62a9951 | 2017-03-25 13:42:11 +0200 | [diff] [blame] | 442 | return os.symlink(a, b) |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 443 | |
Serhiy Storchaka | 62a9951 | 2017-03-25 13:42:11 +0200 | [diff] [blame] | 444 | utime = os.utime |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 445 | |
| 446 | # Helper for resolve() |
| 447 | def readlink(self, path): |
| 448 | return os.readlink(path) |
| 449 | |
Barney Gale | 22386bb | 2020-04-17 17:41:07 +0100 | [diff] [blame] | 450 | def owner(self, path): |
| 451 | try: |
| 452 | import pwd |
| 453 | return pwd.getpwuid(self.stat(path).st_uid).pw_name |
| 454 | except ImportError: |
| 455 | raise NotImplementedError("Path.owner() is unsupported on this system") |
| 456 | |
| 457 | def group(self, path): |
| 458 | try: |
| 459 | import grp |
| 460 | return grp.getgrgid(self.stat(path).st_gid).gr_name |
| 461 | except ImportError: |
| 462 | raise NotImplementedError("Path.group() is unsupported on this system") |
| 463 | |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 464 | |
| 465 | _normal_accessor = _NormalAccessor() |
| 466 | |
| 467 | |
| 468 | # |
| 469 | # Globbing helpers |
| 470 | # |
| 471 | |
Serhiy Storchaka | 10ecbad | 2019-10-21 20:37:15 +0300 | [diff] [blame] | 472 | def _make_selector(pattern_parts, flavour): |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 473 | pat = pattern_parts[0] |
| 474 | child_parts = pattern_parts[1:] |
| 475 | if pat == '**': |
| 476 | cls = _RecursiveWildcardSelector |
| 477 | elif '**' in pat: |
| 478 | raise ValueError("Invalid pattern: '**' can only be an entire path component") |
| 479 | elif _is_wildcard_pattern(pat): |
| 480 | cls = _WildcardSelector |
| 481 | else: |
| 482 | cls = _PreciseSelector |
Serhiy Storchaka | 10ecbad | 2019-10-21 20:37:15 +0300 | [diff] [blame] | 483 | return cls(pat, child_parts, flavour) |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 484 | |
| 485 | if hasattr(functools, "lru_cache"): |
| 486 | _make_selector = functools.lru_cache()(_make_selector) |
| 487 | |
| 488 | |
| 489 | class _Selector: |
| 490 | """A selector matches a specific glob pattern part against the children |
| 491 | of a given path.""" |
| 492 | |
Serhiy Storchaka | 10ecbad | 2019-10-21 20:37:15 +0300 | [diff] [blame] | 493 | def __init__(self, child_parts, flavour): |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 494 | self.child_parts = child_parts |
| 495 | if child_parts: |
Serhiy Storchaka | 10ecbad | 2019-10-21 20:37:15 +0300 | [diff] [blame] | 496 | self.successor = _make_selector(child_parts, flavour) |
Serhiy Storchaka | 680cb15 | 2016-09-07 10:58:05 +0300 | [diff] [blame] | 497 | self.dironly = True |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 498 | else: |
| 499 | self.successor = _TerminatingSelector() |
Serhiy Storchaka | 680cb15 | 2016-09-07 10:58:05 +0300 | [diff] [blame] | 500 | self.dironly = False |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 501 | |
| 502 | def select_from(self, parent_path): |
| 503 | """Iterate over all child paths of `parent_path` matched by this |
| 504 | selector. This can contain parent_path itself.""" |
| 505 | path_cls = type(parent_path) |
| 506 | is_dir = path_cls.is_dir |
| 507 | exists = path_cls.exists |
Serhiy Storchaka | 680cb15 | 2016-09-07 10:58:05 +0300 | [diff] [blame] | 508 | scandir = parent_path._accessor.scandir |
| 509 | if not is_dir(parent_path): |
| 510 | return iter([]) |
| 511 | return self._select_from(parent_path, is_dir, exists, scandir) |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 512 | |
| 513 | |
| 514 | class _TerminatingSelector: |
| 515 | |
Serhiy Storchaka | 680cb15 | 2016-09-07 10:58:05 +0300 | [diff] [blame] | 516 | def _select_from(self, parent_path, is_dir, exists, scandir): |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 517 | yield parent_path |
| 518 | |
| 519 | |
| 520 | class _PreciseSelector(_Selector): |
| 521 | |
Serhiy Storchaka | 10ecbad | 2019-10-21 20:37:15 +0300 | [diff] [blame] | 522 | def __init__(self, name, child_parts, flavour): |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 523 | self.name = name |
Serhiy Storchaka | 10ecbad | 2019-10-21 20:37:15 +0300 | [diff] [blame] | 524 | _Selector.__init__(self, child_parts, flavour) |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 525 | |
Serhiy Storchaka | 680cb15 | 2016-09-07 10:58:05 +0300 | [diff] [blame] | 526 | def _select_from(self, parent_path, is_dir, exists, scandir): |
Guido van Rossum | 6c2d33a | 2016-01-06 09:42:07 -0800 | [diff] [blame] | 527 | try: |
Guido van Rossum | 6c2d33a | 2016-01-06 09:42:07 -0800 | [diff] [blame] | 528 | path = parent_path._make_child_relpath(self.name) |
Serhiy Storchaka | 680cb15 | 2016-09-07 10:58:05 +0300 | [diff] [blame] | 529 | if (is_dir if self.dironly else exists)(path): |
| 530 | for p in self.successor._select_from(path, is_dir, exists, scandir): |
Guido van Rossum | 6c2d33a | 2016-01-06 09:42:07 -0800 | [diff] [blame] | 531 | yield p |
| 532 | except PermissionError: |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 533 | return |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 534 | |
| 535 | |
| 536 | class _WildcardSelector(_Selector): |
| 537 | |
Serhiy Storchaka | 10ecbad | 2019-10-21 20:37:15 +0300 | [diff] [blame] | 538 | def __init__(self, pat, child_parts, flavour): |
| 539 | self.match = flavour.compile_pattern(pat) |
| 540 | _Selector.__init__(self, child_parts, flavour) |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 541 | |
Serhiy Storchaka | 680cb15 | 2016-09-07 10:58:05 +0300 | [diff] [blame] | 542 | def _select_from(self, parent_path, is_dir, exists, scandir): |
Guido van Rossum | 6c2d33a | 2016-01-06 09:42:07 -0800 | [diff] [blame] | 543 | try: |
Serhiy Storchaka | 704e206 | 2020-03-11 18:42:03 +0200 | [diff] [blame] | 544 | with scandir(parent_path) as scandir_it: |
| 545 | entries = list(scandir_it) |
Serhiy Storchaka | 680cb15 | 2016-09-07 10:58:05 +0300 | [diff] [blame] | 546 | for entry in entries: |
Pablo Galindo | eb7560a | 2020-03-07 17:53:20 +0000 | [diff] [blame] | 547 | if self.dironly: |
| 548 | try: |
| 549 | # "entry.is_dir()" can raise PermissionError |
| 550 | # in some cases (see bpo-38894), which is not |
| 551 | # among the errors ignored by _ignore_error() |
| 552 | if not entry.is_dir(): |
| 553 | continue |
| 554 | except OSError as e: |
| 555 | if not _ignore_error(e): |
| 556 | raise |
| 557 | continue |
| 558 | name = entry.name |
| 559 | if self.match(name): |
| 560 | path = parent_path._make_child_relpath(name) |
| 561 | for p in self.successor._select_from(path, is_dir, exists, scandir): |
| 562 | yield p |
Guido van Rossum | 6c2d33a | 2016-01-06 09:42:07 -0800 | [diff] [blame] | 563 | except PermissionError: |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 564 | return |
Guido van Rossum | 6c2d33a | 2016-01-06 09:42:07 -0800 | [diff] [blame] | 565 | |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 566 | |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 567 | class _RecursiveWildcardSelector(_Selector): |
| 568 | |
Serhiy Storchaka | 10ecbad | 2019-10-21 20:37:15 +0300 | [diff] [blame] | 569 | def __init__(self, pat, child_parts, flavour): |
| 570 | _Selector.__init__(self, child_parts, flavour) |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 571 | |
Serhiy Storchaka | 680cb15 | 2016-09-07 10:58:05 +0300 | [diff] [blame] | 572 | def _iterate_directories(self, parent_path, is_dir, scandir): |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 573 | yield parent_path |
Guido van Rossum | bc9fdda | 2016-01-07 10:56:36 -0800 | [diff] [blame] | 574 | try: |
Serhiy Storchaka | 704e206 | 2020-03-11 18:42:03 +0200 | [diff] [blame] | 575 | with scandir(parent_path) as scandir_it: |
| 576 | entries = list(scandir_it) |
Serhiy Storchaka | 680cb15 | 2016-09-07 10:58:05 +0300 | [diff] [blame] | 577 | for entry in entries: |
Przemysław Spodymek | 216b745 | 2018-08-27 23:33:45 +0200 | [diff] [blame] | 578 | entry_is_dir = False |
| 579 | try: |
| 580 | entry_is_dir = entry.is_dir() |
| 581 | except OSError as e: |
Steve Dower | 2f6fae6 | 2019-02-03 23:08:18 -0800 | [diff] [blame] | 582 | if not _ignore_error(e): |
Przemysław Spodymek | 216b745 | 2018-08-27 23:33:45 +0200 | [diff] [blame] | 583 | raise |
| 584 | if entry_is_dir and not entry.is_symlink(): |
Serhiy Storchaka | 680cb15 | 2016-09-07 10:58:05 +0300 | [diff] [blame] | 585 | path = parent_path._make_child_relpath(entry.name) |
| 586 | for p in self._iterate_directories(path, is_dir, scandir): |
Guido van Rossum | bc9fdda | 2016-01-07 10:56:36 -0800 | [diff] [blame] | 587 | yield p |
| 588 | except PermissionError: |
| 589 | return |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 590 | |
Serhiy Storchaka | 680cb15 | 2016-09-07 10:58:05 +0300 | [diff] [blame] | 591 | def _select_from(self, parent_path, is_dir, exists, scandir): |
Guido van Rossum | 6c2d33a | 2016-01-06 09:42:07 -0800 | [diff] [blame] | 592 | try: |
Serhiy Storchaka | 680cb15 | 2016-09-07 10:58:05 +0300 | [diff] [blame] | 593 | yielded = set() |
| 594 | try: |
| 595 | successor_select = self.successor._select_from |
| 596 | for starting_point in self._iterate_directories(parent_path, is_dir, scandir): |
| 597 | for p in successor_select(starting_point, is_dir, exists, scandir): |
| 598 | if p not in yielded: |
| 599 | yield p |
| 600 | yielded.add(p) |
| 601 | finally: |
| 602 | yielded.clear() |
Guido van Rossum | 6c2d33a | 2016-01-06 09:42:07 -0800 | [diff] [blame] | 603 | except PermissionError: |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 604 | return |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 605 | |
| 606 | |
| 607 | # |
| 608 | # Public API |
| 609 | # |
| 610 | |
| 611 | class _PathParents(Sequence): |
| 612 | """This object provides sequence-like access to the logical ancestors |
| 613 | of a path. Don't try to construct it yourself.""" |
| 614 | __slots__ = ('_pathcls', '_drv', '_root', '_parts') |
| 615 | |
| 616 | def __init__(self, path): |
| 617 | # We don't store the instance to avoid reference cycles |
| 618 | self._pathcls = type(path) |
| 619 | self._drv = path._drv |
| 620 | self._root = path._root |
| 621 | self._parts = path._parts |
| 622 | |
| 623 | def __len__(self): |
| 624 | if self._drv or self._root: |
| 625 | return len(self._parts) - 1 |
| 626 | else: |
| 627 | return len(self._parts) |
| 628 | |
| 629 | def __getitem__(self, idx): |
| 630 | if idx < 0 or idx >= len(self): |
| 631 | raise IndexError(idx) |
| 632 | return self._pathcls._from_parsed_parts(self._drv, self._root, |
| 633 | self._parts[:-idx - 1]) |
| 634 | |
| 635 | def __repr__(self): |
| 636 | return "<{}.parents>".format(self._pathcls.__name__) |
| 637 | |
| 638 | |
| 639 | class PurePath(object): |
chason | dfa015c | 2018-02-19 08:36:32 +0900 | [diff] [blame] | 640 | """Base class for manipulating paths without I/O. |
| 641 | |
| 642 | PurePath represents a filesystem path and offers operations which |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 643 | don't imply any actual filesystem I/O. Depending on your system, |
| 644 | instantiating a PurePath will return either a PurePosixPath or a |
| 645 | PureWindowsPath object. You can also instantiate either of these classes |
| 646 | directly, regardless of your system. |
| 647 | """ |
| 648 | __slots__ = ( |
| 649 | '_drv', '_root', '_parts', |
| 650 | '_str', '_hash', '_pparts', '_cached_cparts', |
| 651 | ) |
| 652 | |
| 653 | def __new__(cls, *args): |
| 654 | """Construct a PurePath from one or several strings and or existing |
| 655 | PurePath objects. The strings and path objects are combined so as |
| 656 | to yield a canonicalized path, which is incorporated into the |
| 657 | new PurePath object. |
| 658 | """ |
| 659 | if cls is PurePath: |
| 660 | cls = PureWindowsPath if os.name == 'nt' else PurePosixPath |
| 661 | return cls._from_parts(args) |
| 662 | |
| 663 | def __reduce__(self): |
| 664 | # Using the parts tuple helps share interned path parts |
| 665 | # when pickling related paths. |
| 666 | return (self.__class__, tuple(self._parts)) |
| 667 | |
| 668 | @classmethod |
| 669 | def _parse_args(cls, args): |
| 670 | # This is useful when you don't want to create an instance, just |
| 671 | # canonicalize some constructor arguments. |
| 672 | parts = [] |
| 673 | for a in args: |
| 674 | if isinstance(a, PurePath): |
| 675 | parts += a._parts |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 676 | else: |
Brett Cannon | 568be63 | 2016-06-10 12:20:49 -0700 | [diff] [blame] | 677 | a = os.fspath(a) |
| 678 | if isinstance(a, str): |
| 679 | # Force-cast str subclasses to str (issue #21127) |
| 680 | parts.append(str(a)) |
| 681 | else: |
| 682 | raise TypeError( |
| 683 | "argument should be a str object or an os.PathLike " |
| 684 | "object returning str, not %r" |
| 685 | % type(a)) |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 686 | return cls._flavour.parse_parts(parts) |
| 687 | |
| 688 | @classmethod |
| 689 | def _from_parts(cls, args, init=True): |
| 690 | # We need to call _parse_args on the instance, so as to get the |
| 691 | # right flavour. |
| 692 | self = object.__new__(cls) |
| 693 | drv, root, parts = self._parse_args(args) |
| 694 | self._drv = drv |
| 695 | self._root = root |
| 696 | self._parts = parts |
| 697 | if init: |
| 698 | self._init() |
| 699 | return self |
| 700 | |
| 701 | @classmethod |
| 702 | def _from_parsed_parts(cls, drv, root, parts, init=True): |
| 703 | self = object.__new__(cls) |
| 704 | self._drv = drv |
| 705 | self._root = root |
| 706 | self._parts = parts |
| 707 | if init: |
| 708 | self._init() |
| 709 | return self |
| 710 | |
| 711 | @classmethod |
| 712 | def _format_parsed_parts(cls, drv, root, parts): |
| 713 | if drv or root: |
| 714 | return drv + root + cls._flavour.join(parts[1:]) |
| 715 | else: |
| 716 | return cls._flavour.join(parts) |
| 717 | |
| 718 | def _init(self): |
Martin Panter | e26da7c | 2016-06-02 10:07:09 +0000 | [diff] [blame] | 719 | # Overridden in concrete Path |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 720 | pass |
| 721 | |
| 722 | def _make_child(self, args): |
| 723 | drv, root, parts = self._parse_args(args) |
| 724 | drv, root, parts = self._flavour.join_parsed_parts( |
| 725 | self._drv, self._root, self._parts, drv, root, parts) |
| 726 | return self._from_parsed_parts(drv, root, parts) |
| 727 | |
| 728 | def __str__(self): |
| 729 | """Return the string representation of the path, suitable for |
| 730 | passing to system calls.""" |
| 731 | try: |
| 732 | return self._str |
| 733 | except AttributeError: |
| 734 | self._str = self._format_parsed_parts(self._drv, self._root, |
| 735 | self._parts) or '.' |
| 736 | return self._str |
| 737 | |
Brett Cannon | 568be63 | 2016-06-10 12:20:49 -0700 | [diff] [blame] | 738 | def __fspath__(self): |
| 739 | return str(self) |
| 740 | |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 741 | def as_posix(self): |
| 742 | """Return the string representation of the path with forward (/) |
| 743 | slashes.""" |
| 744 | f = self._flavour |
| 745 | return str(self).replace(f.sep, '/') |
| 746 | |
| 747 | def __bytes__(self): |
| 748 | """Return the bytes representation of the path. This is only |
| 749 | recommended to use under Unix.""" |
Serhiy Storchaka | 62a9951 | 2017-03-25 13:42:11 +0200 | [diff] [blame] | 750 | return os.fsencode(self) |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 751 | |
| 752 | def __repr__(self): |
| 753 | return "{}({!r})".format(self.__class__.__name__, self.as_posix()) |
| 754 | |
| 755 | def as_uri(self): |
| 756 | """Return the path as a 'file' URI.""" |
| 757 | if not self.is_absolute(): |
| 758 | raise ValueError("relative path can't be expressed as a file URI") |
| 759 | return self._flavour.make_uri(self) |
| 760 | |
| 761 | @property |
| 762 | def _cparts(self): |
| 763 | # Cached casefolded parts, for hashing and comparison |
| 764 | try: |
| 765 | return self._cached_cparts |
| 766 | except AttributeError: |
| 767 | self._cached_cparts = self._flavour.casefold_parts(self._parts) |
| 768 | return self._cached_cparts |
| 769 | |
| 770 | def __eq__(self, other): |
| 771 | if not isinstance(other, PurePath): |
| 772 | return NotImplemented |
| 773 | return self._cparts == other._cparts and self._flavour is other._flavour |
| 774 | |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 775 | def __hash__(self): |
| 776 | try: |
| 777 | return self._hash |
| 778 | except AttributeError: |
| 779 | self._hash = hash(tuple(self._cparts)) |
| 780 | return self._hash |
| 781 | |
| 782 | def __lt__(self, other): |
| 783 | if not isinstance(other, PurePath) or self._flavour is not other._flavour: |
| 784 | return NotImplemented |
| 785 | return self._cparts < other._cparts |
| 786 | |
| 787 | def __le__(self, other): |
| 788 | if not isinstance(other, PurePath) or self._flavour is not other._flavour: |
| 789 | return NotImplemented |
| 790 | return self._cparts <= other._cparts |
| 791 | |
| 792 | def __gt__(self, other): |
| 793 | if not isinstance(other, PurePath) or self._flavour is not other._flavour: |
| 794 | return NotImplemented |
| 795 | return self._cparts > other._cparts |
| 796 | |
| 797 | def __ge__(self, other): |
| 798 | if not isinstance(other, PurePath) or self._flavour is not other._flavour: |
| 799 | return NotImplemented |
| 800 | return self._cparts >= other._cparts |
| 801 | |
Batuhan Taşkaya | 526606b | 2019-12-08 23:31:15 +0300 | [diff] [blame] | 802 | def __class_getitem__(cls, type): |
| 803 | return cls |
| 804 | |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 805 | drive = property(attrgetter('_drv'), |
| 806 | doc="""The drive prefix (letter or UNC path), if any.""") |
| 807 | |
| 808 | root = property(attrgetter('_root'), |
| 809 | doc="""The root of the path, if any.""") |
| 810 | |
| 811 | @property |
| 812 | def anchor(self): |
| 813 | """The concatenation of the drive and root, or ''.""" |
| 814 | anchor = self._drv + self._root |
| 815 | return anchor |
| 816 | |
| 817 | @property |
| 818 | def name(self): |
| 819 | """The final path component, if any.""" |
| 820 | parts = self._parts |
| 821 | if len(parts) == (1 if (self._drv or self._root) else 0): |
| 822 | return '' |
| 823 | return parts[-1] |
| 824 | |
| 825 | @property |
| 826 | def suffix(self): |
Ram Rachum | 8d4fef4 | 2019-11-02 18:46:24 +0200 | [diff] [blame] | 827 | """ |
| 828 | The final component's last suffix, if any. |
| 829 | |
| 830 | This includes the leading period. For example: '.txt' |
| 831 | """ |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 832 | name = self.name |
| 833 | i = name.rfind('.') |
| 834 | if 0 < i < len(name) - 1: |
| 835 | return name[i:] |
| 836 | else: |
| 837 | return '' |
| 838 | |
| 839 | @property |
| 840 | def suffixes(self): |
Ram Rachum | 8d4fef4 | 2019-11-02 18:46:24 +0200 | [diff] [blame] | 841 | """ |
| 842 | A list of the final component's suffixes, if any. |
| 843 | |
| 844 | These include the leading periods. For example: ['.tar', '.gz'] |
| 845 | """ |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 846 | name = self.name |
| 847 | if name.endswith('.'): |
| 848 | return [] |
| 849 | name = name.lstrip('.') |
| 850 | return ['.' + suffix for suffix in name.split('.')[1:]] |
| 851 | |
| 852 | @property |
| 853 | def stem(self): |
| 854 | """The final path component, minus its last suffix.""" |
| 855 | name = self.name |
| 856 | i = name.rfind('.') |
| 857 | if 0 < i < len(name) - 1: |
| 858 | return name[:i] |
| 859 | else: |
| 860 | return name |
| 861 | |
| 862 | def with_name(self, name): |
| 863 | """Return a new path with the file name changed.""" |
| 864 | if not self.name: |
| 865 | raise ValueError("%r has an empty name" % (self,)) |
Antoine Pitrou | 7084e73 | 2014-07-06 21:31:12 -0400 | [diff] [blame] | 866 | drv, root, parts = self._flavour.parse_parts((name,)) |
| 867 | if (not name or name[-1] in [self._flavour.sep, self._flavour.altsep] |
| 868 | or drv or root or len(parts) != 1): |
| 869 | raise ValueError("Invalid name %r" % (name)) |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 870 | return self._from_parsed_parts(self._drv, self._root, |
| 871 | self._parts[:-1] + [name]) |
| 872 | |
Tim Hoffmann | 8aea4b3 | 2020-04-19 17:29:49 +0200 | [diff] [blame^] | 873 | def with_stem(self, stem): |
| 874 | """Return a new path with the stem changed.""" |
| 875 | return self.with_name(stem + self.suffix) |
| 876 | |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 877 | def with_suffix(self, suffix): |
Stefan Otte | 46dc4e3 | 2018-08-03 22:49:42 +0200 | [diff] [blame] | 878 | """Return a new path with the file suffix changed. If the path |
| 879 | has no suffix, add given suffix. If the given suffix is an empty |
| 880 | string, remove the suffix from the path. |
| 881 | """ |
Antoine Pitrou | e50dafc | 2014-07-06 21:37:15 -0400 | [diff] [blame] | 882 | f = self._flavour |
| 883 | if f.sep in suffix or f.altsep and f.altsep in suffix: |
Berker Peksag | 423d05f | 2018-08-11 08:45:06 +0300 | [diff] [blame] | 884 | raise ValueError("Invalid suffix %r" % (suffix,)) |
Antoine Pitrou | e50dafc | 2014-07-06 21:37:15 -0400 | [diff] [blame] | 885 | if suffix and not suffix.startswith('.') or suffix == '.': |
Antoine Pitrou | 1b02da9 | 2014-01-03 00:07:17 +0100 | [diff] [blame] | 886 | raise ValueError("Invalid suffix %r" % (suffix)) |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 887 | name = self.name |
| 888 | if not name: |
| 889 | raise ValueError("%r has an empty name" % (self,)) |
| 890 | old_suffix = self.suffix |
| 891 | if not old_suffix: |
| 892 | name = name + suffix |
| 893 | else: |
| 894 | name = name[:-len(old_suffix)] + suffix |
| 895 | return self._from_parsed_parts(self._drv, self._root, |
| 896 | self._parts[:-1] + [name]) |
| 897 | |
| 898 | def relative_to(self, *other): |
| 899 | """Return the relative path to another path identified by the passed |
| 900 | arguments. If the operation is not possible (because this is not |
| 901 | a subpath of the other path), raise ValueError. |
| 902 | """ |
| 903 | # For the purpose of this method, drive and root are considered |
| 904 | # separate parts, i.e.: |
| 905 | # Path('c:/').relative_to('c:') gives Path('/') |
| 906 | # Path('c:/').relative_to('/') raise ValueError |
| 907 | if not other: |
| 908 | raise TypeError("need at least one argument") |
| 909 | parts = self._parts |
| 910 | drv = self._drv |
| 911 | root = self._root |
Antoine Pitrou | 156b361 | 2013-12-28 19:49:04 +0100 | [diff] [blame] | 912 | if root: |
| 913 | abs_parts = [drv, root] + parts[1:] |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 914 | else: |
| 915 | abs_parts = parts |
| 916 | to_drv, to_root, to_parts = self._parse_args(other) |
Antoine Pitrou | 156b361 | 2013-12-28 19:49:04 +0100 | [diff] [blame] | 917 | if to_root: |
| 918 | to_abs_parts = [to_drv, to_root] + to_parts[1:] |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 919 | else: |
| 920 | to_abs_parts = to_parts |
| 921 | n = len(to_abs_parts) |
Antoine Pitrou | 156b361 | 2013-12-28 19:49:04 +0100 | [diff] [blame] | 922 | cf = self._flavour.casefold_parts |
| 923 | if (root or drv) if n == 0 else cf(abs_parts[:n]) != cf(to_abs_parts): |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 924 | formatted = self._format_parsed_parts(to_drv, to_root, to_parts) |
| 925 | raise ValueError("{!r} does not start with {!r}" |
| 926 | .format(str(self), str(formatted))) |
Antoine Pitrou | 156b361 | 2013-12-28 19:49:04 +0100 | [diff] [blame] | 927 | return self._from_parsed_parts('', root if n == 1 else '', |
| 928 | abs_parts[n:]) |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 929 | |
Hai Shi | 82642a0 | 2019-08-13 14:54:02 -0500 | [diff] [blame] | 930 | def is_relative_to(self, *other): |
| 931 | """Return True if the path is relative to another path or False. |
| 932 | """ |
| 933 | try: |
| 934 | self.relative_to(*other) |
| 935 | return True |
| 936 | except ValueError: |
| 937 | return False |
| 938 | |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 939 | @property |
| 940 | def parts(self): |
| 941 | """An object providing sequence-like access to the |
| 942 | components in the filesystem path.""" |
| 943 | # We cache the tuple to avoid building a new one each time .parts |
| 944 | # is accessed. XXX is this necessary? |
| 945 | try: |
| 946 | return self._pparts |
| 947 | except AttributeError: |
| 948 | self._pparts = tuple(self._parts) |
| 949 | return self._pparts |
| 950 | |
| 951 | def joinpath(self, *args): |
| 952 | """Combine this path with one or several arguments, and return a |
| 953 | new path representing either a subpath (if all arguments are relative |
| 954 | paths) or a totally different path (if one of the arguments is |
| 955 | anchored). |
| 956 | """ |
| 957 | return self._make_child(args) |
| 958 | |
| 959 | def __truediv__(self, key): |
aiudirog | 4c69be2 | 2019-08-08 01:41:10 -0400 | [diff] [blame] | 960 | try: |
| 961 | return self._make_child((key,)) |
| 962 | except TypeError: |
| 963 | return NotImplemented |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 964 | |
| 965 | def __rtruediv__(self, key): |
aiudirog | 4c69be2 | 2019-08-08 01:41:10 -0400 | [diff] [blame] | 966 | try: |
| 967 | return self._from_parts([key] + self._parts) |
| 968 | except TypeError: |
| 969 | return NotImplemented |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 970 | |
| 971 | @property |
| 972 | def parent(self): |
| 973 | """The logical parent of the path.""" |
| 974 | drv = self._drv |
| 975 | root = self._root |
| 976 | parts = self._parts |
| 977 | if len(parts) == 1 and (drv or root): |
| 978 | return self |
| 979 | return self._from_parsed_parts(drv, root, parts[:-1]) |
| 980 | |
| 981 | @property |
| 982 | def parents(self): |
| 983 | """A sequence of this path's logical parents.""" |
| 984 | return _PathParents(self) |
| 985 | |
| 986 | def is_absolute(self): |
| 987 | """True if the path is absolute (has both a root and, if applicable, |
| 988 | a drive).""" |
| 989 | if not self._root: |
| 990 | return False |
| 991 | return not self._flavour.has_drv or bool(self._drv) |
| 992 | |
| 993 | def is_reserved(self): |
| 994 | """Return True if the path contains one of the special names reserved |
| 995 | by the system, if any.""" |
| 996 | return self._flavour.is_reserved(self._parts) |
| 997 | |
| 998 | def match(self, path_pattern): |
| 999 | """ |
| 1000 | Return True if this path matches the given pattern. |
| 1001 | """ |
| 1002 | cf = self._flavour.casefold |
| 1003 | path_pattern = cf(path_pattern) |
| 1004 | drv, root, pat_parts = self._flavour.parse_parts((path_pattern,)) |
| 1005 | if not pat_parts: |
| 1006 | raise ValueError("empty pattern") |
| 1007 | if drv and drv != cf(self._drv): |
| 1008 | return False |
| 1009 | if root and root != cf(self._root): |
| 1010 | return False |
| 1011 | parts = self._cparts |
| 1012 | if drv or root: |
| 1013 | if len(pat_parts) != len(parts): |
| 1014 | return False |
| 1015 | pat_parts = pat_parts[1:] |
| 1016 | elif len(pat_parts) > len(parts): |
| 1017 | return False |
| 1018 | for part, pat in zip(reversed(parts), reversed(pat_parts)): |
| 1019 | if not fnmatch.fnmatchcase(part, pat): |
| 1020 | return False |
| 1021 | return True |
| 1022 | |
Brett Cannon | 568be63 | 2016-06-10 12:20:49 -0700 | [diff] [blame] | 1023 | # Can't subclass os.PathLike from PurePath and keep the constructor |
| 1024 | # optimizations in PurePath._parse_args(). |
| 1025 | os.PathLike.register(PurePath) |
| 1026 | |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1027 | |
| 1028 | class PurePosixPath(PurePath): |
chason | dfa015c | 2018-02-19 08:36:32 +0900 | [diff] [blame] | 1029 | """PurePath subclass for non-Windows systems. |
| 1030 | |
| 1031 | On a POSIX system, instantiating a PurePath should return this object. |
| 1032 | However, you can also instantiate it directly on any system. |
| 1033 | """ |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1034 | _flavour = _posix_flavour |
| 1035 | __slots__ = () |
| 1036 | |
| 1037 | |
| 1038 | class PureWindowsPath(PurePath): |
chason | dfa015c | 2018-02-19 08:36:32 +0900 | [diff] [blame] | 1039 | """PurePath subclass for Windows systems. |
| 1040 | |
| 1041 | On a Windows system, instantiating a PurePath should return this object. |
| 1042 | However, you can also instantiate it directly on any system. |
| 1043 | """ |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1044 | _flavour = _windows_flavour |
| 1045 | __slots__ = () |
| 1046 | |
| 1047 | |
| 1048 | # Filesystem-accessing classes |
| 1049 | |
| 1050 | |
| 1051 | class Path(PurePath): |
chason | dfa015c | 2018-02-19 08:36:32 +0900 | [diff] [blame] | 1052 | """PurePath subclass that can make system calls. |
| 1053 | |
| 1054 | Path represents a filesystem path but unlike PurePath, also offers |
| 1055 | methods to do system calls on path objects. Depending on your system, |
| 1056 | instantiating a Path will return either a PosixPath or a WindowsPath |
| 1057 | object. You can also instantiate a PosixPath or WindowsPath directly, |
| 1058 | but cannot instantiate a WindowsPath on a POSIX system or vice versa. |
| 1059 | """ |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1060 | __slots__ = ( |
| 1061 | '_accessor', |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1062 | ) |
| 1063 | |
| 1064 | def __new__(cls, *args, **kwargs): |
| 1065 | if cls is Path: |
| 1066 | cls = WindowsPath if os.name == 'nt' else PosixPath |
| 1067 | self = cls._from_parts(args, init=False) |
| 1068 | if not self._flavour.is_supported: |
| 1069 | raise NotImplementedError("cannot instantiate %r on your system" |
| 1070 | % (cls.__name__,)) |
| 1071 | self._init() |
| 1072 | return self |
| 1073 | |
| 1074 | def _init(self, |
| 1075 | # Private non-constructor arguments |
| 1076 | template=None, |
| 1077 | ): |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1078 | if template is not None: |
| 1079 | self._accessor = template._accessor |
| 1080 | else: |
| 1081 | self._accessor = _normal_accessor |
| 1082 | |
| 1083 | def _make_child_relpath(self, part): |
| 1084 | # This is an optimization used for dir walking. `part` must be |
| 1085 | # a single part relative to this path. |
| 1086 | parts = self._parts + [part] |
| 1087 | return self._from_parsed_parts(self._drv, self._root, parts) |
| 1088 | |
| 1089 | def __enter__(self): |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1090 | return self |
| 1091 | |
| 1092 | def __exit__(self, t, v, tb): |
Barney Gale | 00002e6 | 2020-04-01 15:10:51 +0100 | [diff] [blame] | 1093 | # https://bugs.python.org/issue39682 |
| 1094 | # In previous versions of pathlib, this method marked this path as |
| 1095 | # closed; subsequent attempts to perform I/O would raise an IOError. |
| 1096 | # This functionality was never documented, and had the effect of |
| 1097 | # making Path objects mutable, contrary to PEP 428. In Python 3.9 the |
| 1098 | # _closed attribute was removed, and this method made a no-op. |
| 1099 | # This method and __enter__()/__exit__() should be deprecated and |
| 1100 | # removed in the future. |
| 1101 | pass |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1102 | |
| 1103 | def _opener(self, name, flags, mode=0o666): |
| 1104 | # A stub for the opener argument to built-in open() |
| 1105 | return self._accessor.open(self, flags, mode) |
| 1106 | |
Antoine Pitrou | 4a60d42 | 2013-12-02 21:25:18 +0100 | [diff] [blame] | 1107 | def _raw_open(self, flags, mode=0o777): |
| 1108 | """ |
| 1109 | Open the file pointed by this path and return a file descriptor, |
| 1110 | as os.open() does. |
| 1111 | """ |
Antoine Pitrou | 4a60d42 | 2013-12-02 21:25:18 +0100 | [diff] [blame] | 1112 | return self._accessor.open(self, flags, mode) |
| 1113 | |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1114 | # Public API |
| 1115 | |
| 1116 | @classmethod |
| 1117 | def cwd(cls): |
| 1118 | """Return a new path pointing to the current working directory |
| 1119 | (as returned by os.getcwd()). |
| 1120 | """ |
| 1121 | return cls(os.getcwd()) |
| 1122 | |
Antoine Pitrou | 17cba7d | 2015-01-12 21:03:41 +0100 | [diff] [blame] | 1123 | @classmethod |
| 1124 | def home(cls): |
| 1125 | """Return a new path pointing to the user's home directory (as |
| 1126 | returned by os.path.expanduser('~')). |
| 1127 | """ |
| 1128 | return cls(cls()._flavour.gethomedir(None)) |
| 1129 | |
Antoine Pitrou | 43e3d94 | 2014-05-13 10:50:15 +0200 | [diff] [blame] | 1130 | def samefile(self, other_path): |
Berker Peksag | 05492b8 | 2015-10-22 03:34:16 +0300 | [diff] [blame] | 1131 | """Return whether other_path is the same or not as this file |
Berker Peksag | 267597f | 2015-10-21 20:10:24 +0300 | [diff] [blame] | 1132 | (as returned by os.path.samefile()). |
Antoine Pitrou | 43e3d94 | 2014-05-13 10:50:15 +0200 | [diff] [blame] | 1133 | """ |
| 1134 | st = self.stat() |
| 1135 | try: |
| 1136 | other_st = other_path.stat() |
| 1137 | except AttributeError: |
Barney Gale | 5b1d918 | 2020-04-17 18:47:27 +0100 | [diff] [blame] | 1138 | other_st = self._accessor.stat(other_path) |
Antoine Pitrou | 43e3d94 | 2014-05-13 10:50:15 +0200 | [diff] [blame] | 1139 | return os.path.samestat(st, other_st) |
| 1140 | |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1141 | def iterdir(self): |
| 1142 | """Iterate over the files in this directory. Does not yield any |
| 1143 | result for the special paths '.' and '..'. |
| 1144 | """ |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1145 | for name in self._accessor.listdir(self): |
| 1146 | if name in {'.', '..'}: |
| 1147 | # Yielding a path object for these makes little sense |
| 1148 | continue |
| 1149 | yield self._make_child_relpath(name) |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1150 | |
| 1151 | def glob(self, pattern): |
| 1152 | """Iterate over this subtree and yield all existing files (of any |
Eivind Teig | 537b6ca | 2019-02-11 11:47:09 +0100 | [diff] [blame] | 1153 | kind, including directories) matching the given relative pattern. |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1154 | """ |
Serhiy Storchaka | f4f445b | 2020-02-12 12:11:34 +0200 | [diff] [blame] | 1155 | sys.audit("pathlib.Path.glob", self, pattern) |
Berker Peksag | 4a208e4 | 2016-01-30 17:50:48 +0200 | [diff] [blame] | 1156 | if not pattern: |
| 1157 | raise ValueError("Unacceptable pattern: {!r}".format(pattern)) |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1158 | drv, root, pattern_parts = self._flavour.parse_parts((pattern,)) |
| 1159 | if drv or root: |
| 1160 | raise NotImplementedError("Non-relative patterns are unsupported") |
Serhiy Storchaka | 10ecbad | 2019-10-21 20:37:15 +0300 | [diff] [blame] | 1161 | selector = _make_selector(tuple(pattern_parts), self._flavour) |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1162 | for p in selector.select_from(self): |
| 1163 | yield p |
| 1164 | |
| 1165 | def rglob(self, pattern): |
| 1166 | """Recursively yield all existing files (of any kind, including |
Eivind Teig | 537b6ca | 2019-02-11 11:47:09 +0100 | [diff] [blame] | 1167 | directories) matching the given relative pattern, anywhere in |
| 1168 | this subtree. |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1169 | """ |
Serhiy Storchaka | f4f445b | 2020-02-12 12:11:34 +0200 | [diff] [blame] | 1170 | sys.audit("pathlib.Path.rglob", self, pattern) |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1171 | drv, root, pattern_parts = self._flavour.parse_parts((pattern,)) |
| 1172 | if drv or root: |
| 1173 | raise NotImplementedError("Non-relative patterns are unsupported") |
Serhiy Storchaka | 10ecbad | 2019-10-21 20:37:15 +0300 | [diff] [blame] | 1174 | selector = _make_selector(("**",) + tuple(pattern_parts), self._flavour) |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1175 | for p in selector.select_from(self): |
| 1176 | yield p |
| 1177 | |
| 1178 | def absolute(self): |
| 1179 | """Return an absolute version of this path. This function works |
| 1180 | even if the path doesn't point to anything. |
| 1181 | |
| 1182 | No normalization is done, i.e. all '.' and '..' will be kept along. |
| 1183 | Use resolve() to get the canonical path to a file. |
| 1184 | """ |
| 1185 | # XXX untested yet! |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1186 | if self.is_absolute(): |
| 1187 | return self |
| 1188 | # FIXME this must defer to the specific flavour (and, under Windows, |
| 1189 | # use nt._getfullpathname()) |
| 1190 | obj = self._from_parts([os.getcwd()] + self._parts, init=False) |
| 1191 | obj._init(template=self) |
| 1192 | return obj |
| 1193 | |
Steve Dower | 98eb360 | 2016-11-09 12:58:17 -0800 | [diff] [blame] | 1194 | def resolve(self, strict=False): |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1195 | """ |
| 1196 | Make the path absolute, resolving all symlinks on the way and also |
| 1197 | normalizing it (for example turning slashes into backslashes under |
| 1198 | Windows). |
| 1199 | """ |
Steve Dower | 98eb360 | 2016-11-09 12:58:17 -0800 | [diff] [blame] | 1200 | s = self._flavour.resolve(self, strict=strict) |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1201 | if s is None: |
| 1202 | # No symlink resolution => for consistency, raise an error if |
| 1203 | # the path doesn't exist or is forbidden |
| 1204 | self.stat() |
| 1205 | s = str(self.absolute()) |
| 1206 | # Now we have no symlinks in the path, it's safe to normalize it. |
| 1207 | normed = self._flavour.pathmod.normpath(s) |
| 1208 | obj = self._from_parts((normed,), init=False) |
| 1209 | obj._init(template=self) |
| 1210 | return obj |
| 1211 | |
| 1212 | def stat(self): |
| 1213 | """ |
| 1214 | Return the result of the stat() system call on this path, like |
| 1215 | os.stat() does. |
| 1216 | """ |
| 1217 | return self._accessor.stat(self) |
| 1218 | |
| 1219 | def owner(self): |
| 1220 | """ |
| 1221 | Return the login name of the file owner. |
| 1222 | """ |
Barney Gale | 22386bb | 2020-04-17 17:41:07 +0100 | [diff] [blame] | 1223 | return self._accessor.owner(self) |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1224 | |
| 1225 | def group(self): |
| 1226 | """ |
| 1227 | Return the group name of the file gid. |
| 1228 | """ |
Barney Gale | 22386bb | 2020-04-17 17:41:07 +0100 | [diff] [blame] | 1229 | return self._accessor.group(self) |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1230 | |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1231 | def open(self, mode='r', buffering=-1, encoding=None, |
| 1232 | errors=None, newline=None): |
| 1233 | """ |
| 1234 | Open the file pointed by this path and return a file object, as |
| 1235 | the built-in open() function does. |
| 1236 | """ |
Serhiy Storchaka | 62a9951 | 2017-03-25 13:42:11 +0200 | [diff] [blame] | 1237 | return io.open(self, mode, buffering, encoding, errors, newline, |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1238 | opener=self._opener) |
| 1239 | |
Georg Brandl | ea68398 | 2014-10-01 19:12:33 +0200 | [diff] [blame] | 1240 | def read_bytes(self): |
| 1241 | """ |
| 1242 | Open the file in bytes mode, read it, and close the file. |
| 1243 | """ |
| 1244 | with self.open(mode='rb') as f: |
| 1245 | return f.read() |
| 1246 | |
| 1247 | def read_text(self, encoding=None, errors=None): |
| 1248 | """ |
| 1249 | Open the file in text mode, read it, and close the file. |
| 1250 | """ |
| 1251 | with self.open(mode='r', encoding=encoding, errors=errors) as f: |
| 1252 | return f.read() |
| 1253 | |
| 1254 | def write_bytes(self, data): |
| 1255 | """ |
| 1256 | Open the file in bytes mode, write to it, and close the file. |
| 1257 | """ |
| 1258 | # type-check for the buffer interface before truncating the file |
| 1259 | view = memoryview(data) |
| 1260 | with self.open(mode='wb') as f: |
| 1261 | return f.write(view) |
| 1262 | |
| 1263 | def write_text(self, data, encoding=None, errors=None): |
| 1264 | """ |
| 1265 | Open the file in text mode, write to it, and close the file. |
| 1266 | """ |
| 1267 | if not isinstance(data, str): |
| 1268 | raise TypeError('data must be str, not %s' % |
| 1269 | data.__class__.__name__) |
| 1270 | with self.open(mode='w', encoding=encoding, errors=errors) as f: |
| 1271 | return f.write(data) |
| 1272 | |
Girts | a01ba33 | 2019-10-23 14:18:40 -0700 | [diff] [blame] | 1273 | def readlink(self): |
| 1274 | """ |
| 1275 | Return the path to which the symbolic link points. |
| 1276 | """ |
| 1277 | path = self._accessor.readlink(self) |
| 1278 | obj = self._from_parts((path,), init=False) |
| 1279 | obj._init(template=self) |
| 1280 | return obj |
| 1281 | |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1282 | def touch(self, mode=0o666, exist_ok=True): |
| 1283 | """ |
| 1284 | Create this file with the given access mode, if it doesn't exist. |
| 1285 | """ |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1286 | if exist_ok: |
| 1287 | # First try to bump modification time |
| 1288 | # Implementation note: GNU touch uses the UTIME_NOW option of |
| 1289 | # the utimensat() / futimens() functions. |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1290 | try: |
Antoine Pitrou | 2cf3917 | 2013-11-23 15:25:59 +0100 | [diff] [blame] | 1291 | self._accessor.utime(self, None) |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1292 | except OSError: |
| 1293 | # Avoid exception chaining |
| 1294 | pass |
| 1295 | else: |
| 1296 | return |
| 1297 | flags = os.O_CREAT | os.O_WRONLY |
| 1298 | if not exist_ok: |
| 1299 | flags |= os.O_EXCL |
| 1300 | fd = self._raw_open(flags, mode) |
| 1301 | os.close(fd) |
| 1302 | |
Barry Warsaw | 7c549c4 | 2014-08-05 11:28:12 -0400 | [diff] [blame] | 1303 | def mkdir(self, mode=0o777, parents=False, exist_ok=False): |
Serhiy Storchaka | af7b9ec | 2017-03-24 20:51:53 +0200 | [diff] [blame] | 1304 | """ |
| 1305 | Create a new directory at this given path. |
| 1306 | """ |
Serhiy Storchaka | af7b9ec | 2017-03-24 20:51:53 +0200 | [diff] [blame] | 1307 | try: |
| 1308 | self._accessor.mkdir(self, mode) |
| 1309 | except FileNotFoundError: |
| 1310 | if not parents or self.parent == self: |
| 1311 | raise |
Armin Rigo | 22a594a | 2017-04-13 20:08:15 +0200 | [diff] [blame] | 1312 | self.parent.mkdir(parents=True, exist_ok=True) |
| 1313 | self.mkdir(mode, parents=False, exist_ok=exist_ok) |
Serhiy Storchaka | af7b9ec | 2017-03-24 20:51:53 +0200 | [diff] [blame] | 1314 | except OSError: |
| 1315 | # Cannot rely on checking for EEXIST, since the operating system |
| 1316 | # could give priority to other errors like EACCES or EROFS |
| 1317 | if not exist_ok or not self.is_dir(): |
| 1318 | raise |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1319 | |
| 1320 | def chmod(self, mode): |
| 1321 | """ |
| 1322 | Change the permissions of the path, like os.chmod(). |
| 1323 | """ |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1324 | self._accessor.chmod(self, mode) |
| 1325 | |
| 1326 | def lchmod(self, mode): |
| 1327 | """ |
| 1328 | Like chmod(), except if the path points to a symlink, the symlink's |
| 1329 | permissions are changed, rather than its target's. |
| 1330 | """ |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1331 | self._accessor.lchmod(self, mode) |
| 1332 | |
zlohhcuB treboR | d9e006b | 2019-05-16 00:02:11 +0200 | [diff] [blame] | 1333 | def unlink(self, missing_ok=False): |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1334 | """ |
| 1335 | Remove this file or link. |
| 1336 | If the path is a directory, use rmdir() instead. |
| 1337 | """ |
zlohhcuB treboR | d9e006b | 2019-05-16 00:02:11 +0200 | [diff] [blame] | 1338 | try: |
| 1339 | self._accessor.unlink(self) |
| 1340 | except FileNotFoundError: |
| 1341 | if not missing_ok: |
| 1342 | raise |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1343 | |
| 1344 | def rmdir(self): |
| 1345 | """ |
| 1346 | Remove this directory. The directory must be empty. |
| 1347 | """ |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1348 | self._accessor.rmdir(self) |
| 1349 | |
| 1350 | def lstat(self): |
| 1351 | """ |
| 1352 | Like stat(), except if the path points to a symlink, the symlink's |
| 1353 | status information is returned, rather than its target's. |
| 1354 | """ |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1355 | return self._accessor.lstat(self) |
| 1356 | |
Joannah Nanjekye | 6b5b013 | 2019-05-04 11:27:10 -0400 | [diff] [blame] | 1357 | def link_to(self, target): |
| 1358 | """ |
| 1359 | Create a hard link pointing to a path named target. |
| 1360 | """ |
Joannah Nanjekye | 6b5b013 | 2019-05-04 11:27:10 -0400 | [diff] [blame] | 1361 | self._accessor.link_to(self, target) |
| 1362 | |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1363 | def rename(self, target): |
| 1364 | """ |
hui shang | 088a09a | 2019-09-11 21:26:49 +0800 | [diff] [blame] | 1365 | Rename this path to the given path, |
| 1366 | and return a new Path instance pointing to the given path. |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1367 | """ |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1368 | self._accessor.rename(self, target) |
hui shang | 088a09a | 2019-09-11 21:26:49 +0800 | [diff] [blame] | 1369 | return self.__class__(target) |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1370 | |
| 1371 | def replace(self, target): |
| 1372 | """ |
| 1373 | Rename this path to the given path, clobbering the existing |
hui shang | 088a09a | 2019-09-11 21:26:49 +0800 | [diff] [blame] | 1374 | destination if it exists, and return a new Path instance |
| 1375 | pointing to the given path. |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1376 | """ |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1377 | self._accessor.replace(self, target) |
hui shang | 088a09a | 2019-09-11 21:26:49 +0800 | [diff] [blame] | 1378 | return self.__class__(target) |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1379 | |
| 1380 | def symlink_to(self, target, target_is_directory=False): |
| 1381 | """ |
| 1382 | Make this path a symlink pointing to the given path. |
| 1383 | Note the order of arguments (self, target) is the reverse of os.symlink's. |
| 1384 | """ |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1385 | self._accessor.symlink(target, self, target_is_directory) |
| 1386 | |
| 1387 | # Convenience functions for querying the stat results |
| 1388 | |
| 1389 | def exists(self): |
| 1390 | """ |
| 1391 | Whether this path exists. |
| 1392 | """ |
| 1393 | try: |
| 1394 | self.stat() |
| 1395 | except OSError as e: |
Steve Dower | 2f6fae6 | 2019-02-03 23:08:18 -0800 | [diff] [blame] | 1396 | if not _ignore_error(e): |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1397 | raise |
| 1398 | return False |
Serhiy Storchaka | 0185f34 | 2018-09-18 11:28:51 +0300 | [diff] [blame] | 1399 | except ValueError: |
| 1400 | # Non-encodable path |
| 1401 | return False |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1402 | return True |
| 1403 | |
| 1404 | def is_dir(self): |
| 1405 | """ |
| 1406 | Whether this path is a directory. |
| 1407 | """ |
| 1408 | try: |
| 1409 | return S_ISDIR(self.stat().st_mode) |
| 1410 | except OSError as e: |
Steve Dower | 2f6fae6 | 2019-02-03 23:08:18 -0800 | [diff] [blame] | 1411 | if not _ignore_error(e): |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1412 | raise |
| 1413 | # Path doesn't exist or is a broken symlink |
| 1414 | # (see https://bitbucket.org/pitrou/pathlib/issue/12/) |
| 1415 | return False |
Serhiy Storchaka | 0185f34 | 2018-09-18 11:28:51 +0300 | [diff] [blame] | 1416 | except ValueError: |
| 1417 | # Non-encodable path |
| 1418 | return False |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1419 | |
| 1420 | def is_file(self): |
| 1421 | """ |
| 1422 | Whether this path is a regular file (also True for symlinks pointing |
| 1423 | to regular files). |
| 1424 | """ |
| 1425 | try: |
| 1426 | return S_ISREG(self.stat().st_mode) |
| 1427 | except OSError as e: |
Steve Dower | 2f6fae6 | 2019-02-03 23:08:18 -0800 | [diff] [blame] | 1428 | if not _ignore_error(e): |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1429 | raise |
| 1430 | # Path doesn't exist or is a broken symlink |
| 1431 | # (see https://bitbucket.org/pitrou/pathlib/issue/12/) |
| 1432 | return False |
Serhiy Storchaka | 0185f34 | 2018-09-18 11:28:51 +0300 | [diff] [blame] | 1433 | except ValueError: |
| 1434 | # Non-encodable path |
| 1435 | return False |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1436 | |
Cooper Lees | 173ff4a | 2017-08-01 15:35:45 -0700 | [diff] [blame] | 1437 | def is_mount(self): |
| 1438 | """ |
| 1439 | Check if this path is a POSIX mount point |
| 1440 | """ |
| 1441 | # Need to exist and be a dir |
| 1442 | if not self.exists() or not self.is_dir(): |
| 1443 | return False |
| 1444 | |
Cooper Lees | 173ff4a | 2017-08-01 15:35:45 -0700 | [diff] [blame] | 1445 | try: |
Barney Gale | c746c4f | 2020-04-17 18:42:06 +0100 | [diff] [blame] | 1446 | parent_dev = self.parent.stat().st_dev |
Cooper Lees | 173ff4a | 2017-08-01 15:35:45 -0700 | [diff] [blame] | 1447 | except OSError: |
| 1448 | return False |
| 1449 | |
| 1450 | dev = self.stat().st_dev |
| 1451 | if dev != parent_dev: |
| 1452 | return True |
| 1453 | ino = self.stat().st_ino |
Barney Gale | c746c4f | 2020-04-17 18:42:06 +0100 | [diff] [blame] | 1454 | parent_ino = self.parent.stat().st_ino |
Cooper Lees | 173ff4a | 2017-08-01 15:35:45 -0700 | [diff] [blame] | 1455 | return ino == parent_ino |
| 1456 | |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1457 | def is_symlink(self): |
| 1458 | """ |
| 1459 | Whether this path is a symbolic link. |
| 1460 | """ |
| 1461 | try: |
| 1462 | return S_ISLNK(self.lstat().st_mode) |
| 1463 | except OSError as e: |
Steve Dower | 2f6fae6 | 2019-02-03 23:08:18 -0800 | [diff] [blame] | 1464 | if not _ignore_error(e): |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1465 | raise |
| 1466 | # Path doesn't exist |
| 1467 | return False |
Serhiy Storchaka | 0185f34 | 2018-09-18 11:28:51 +0300 | [diff] [blame] | 1468 | except ValueError: |
| 1469 | # Non-encodable path |
| 1470 | return False |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1471 | |
| 1472 | def is_block_device(self): |
| 1473 | """ |
| 1474 | Whether this path is a block device. |
| 1475 | """ |
| 1476 | try: |
| 1477 | return S_ISBLK(self.stat().st_mode) |
| 1478 | except OSError as e: |
Steve Dower | 2f6fae6 | 2019-02-03 23:08:18 -0800 | [diff] [blame] | 1479 | if not _ignore_error(e): |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1480 | raise |
| 1481 | # Path doesn't exist or is a broken symlink |
| 1482 | # (see https://bitbucket.org/pitrou/pathlib/issue/12/) |
| 1483 | return False |
Serhiy Storchaka | 0185f34 | 2018-09-18 11:28:51 +0300 | [diff] [blame] | 1484 | except ValueError: |
| 1485 | # Non-encodable path |
| 1486 | return False |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1487 | |
| 1488 | def is_char_device(self): |
| 1489 | """ |
| 1490 | Whether this path is a character device. |
| 1491 | """ |
| 1492 | try: |
| 1493 | return S_ISCHR(self.stat().st_mode) |
| 1494 | except OSError as e: |
Steve Dower | 2f6fae6 | 2019-02-03 23:08:18 -0800 | [diff] [blame] | 1495 | if not _ignore_error(e): |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1496 | raise |
| 1497 | # Path doesn't exist or is a broken symlink |
| 1498 | # (see https://bitbucket.org/pitrou/pathlib/issue/12/) |
| 1499 | return False |
Serhiy Storchaka | 0185f34 | 2018-09-18 11:28:51 +0300 | [diff] [blame] | 1500 | except ValueError: |
| 1501 | # Non-encodable path |
| 1502 | return False |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1503 | |
| 1504 | def is_fifo(self): |
| 1505 | """ |
| 1506 | Whether this path is a FIFO. |
| 1507 | """ |
| 1508 | try: |
| 1509 | return S_ISFIFO(self.stat().st_mode) |
| 1510 | except OSError as e: |
Steve Dower | 2f6fae6 | 2019-02-03 23:08:18 -0800 | [diff] [blame] | 1511 | if not _ignore_error(e): |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1512 | raise |
| 1513 | # Path doesn't exist or is a broken symlink |
| 1514 | # (see https://bitbucket.org/pitrou/pathlib/issue/12/) |
| 1515 | return False |
Serhiy Storchaka | 0185f34 | 2018-09-18 11:28:51 +0300 | [diff] [blame] | 1516 | except ValueError: |
| 1517 | # Non-encodable path |
| 1518 | return False |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1519 | |
| 1520 | def is_socket(self): |
| 1521 | """ |
| 1522 | Whether this path is a socket. |
| 1523 | """ |
| 1524 | try: |
| 1525 | return S_ISSOCK(self.stat().st_mode) |
| 1526 | except OSError as e: |
Steve Dower | 2f6fae6 | 2019-02-03 23:08:18 -0800 | [diff] [blame] | 1527 | if not _ignore_error(e): |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1528 | raise |
| 1529 | # Path doesn't exist or is a broken symlink |
| 1530 | # (see https://bitbucket.org/pitrou/pathlib/issue/12/) |
| 1531 | return False |
Serhiy Storchaka | 0185f34 | 2018-09-18 11:28:51 +0300 | [diff] [blame] | 1532 | except ValueError: |
| 1533 | # Non-encodable path |
| 1534 | return False |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1535 | |
Antoine Pitrou | 8477ed6 | 2014-12-30 20:54:45 +0100 | [diff] [blame] | 1536 | def expanduser(self): |
| 1537 | """ Return a new path with expanded ~ and ~user constructs |
| 1538 | (as returned by os.path.expanduser) |
| 1539 | """ |
| 1540 | if (not (self._drv or self._root) and |
| 1541 | self._parts and self._parts[0][:1] == '~'): |
| 1542 | homedir = self._flavour.gethomedir(self._parts[0][1:]) |
| 1543 | return self._from_parts([homedir] + self._parts[1:]) |
| 1544 | |
| 1545 | return self |
| 1546 | |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1547 | |
| 1548 | class PosixPath(Path, PurePosixPath): |
chason | dfa015c | 2018-02-19 08:36:32 +0900 | [diff] [blame] | 1549 | """Path subclass for non-Windows systems. |
| 1550 | |
| 1551 | On a POSIX system, instantiating a Path should return this object. |
| 1552 | """ |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1553 | __slots__ = () |
| 1554 | |
| 1555 | class WindowsPath(Path, PureWindowsPath): |
chason | dfa015c | 2018-02-19 08:36:32 +0900 | [diff] [blame] | 1556 | """Path subclass for Windows systems. |
| 1557 | |
| 1558 | On a Windows system, instantiating a Path should return this object. |
| 1559 | """ |
Antoine Pitrou | 31119e4 | 2013-11-22 17:38:12 +0100 | [diff] [blame] | 1560 | __slots__ = () |
Berker Peksag | 04d4229 | 2016-03-11 23:07:27 +0200 | [diff] [blame] | 1561 | |
Cooper Lees | 173ff4a | 2017-08-01 15:35:45 -0700 | [diff] [blame] | 1562 | def is_mount(self): |
| 1563 | raise NotImplementedError("Path.is_mount() is unsupported on this system") |