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