Debian Codegraph @

Lib/pathlib/_local.py

raw ◀ ▶
1 Debian patch touch this file
1 import io
2 import operator
3 import os
4 import posixpath
5 import sys
6 import warnings
7 from glob import _StringGlobber
8 from itertools import chain
9 from _collections_abc import Sequence
10
11 try:
12 import pwd
13 except ImportError:
14 pwd = None
15 try:
16 import grp
17 except ImportError:
18 grp = None
19
20 from ._abc import UnsupportedOperation, PurePathBase, PathBase
21
22
23 __all__ = [
24 "PurePath", "PurePosixPath", "PureWindowsPath",
25 "Path", "PosixPath", "WindowsPath",
26 ]
27
28
29 class _PathParents(Sequence):
30 """This object provides sequence-like access to the logical ancestors
31 of a path. Don't try to construct it yourself."""
32 __slots__ = ('_path', '_drv', '_root', '_tail')
33
34 def __init__(self, path):
35 self._path = path
36 self._drv = path.drive
37 self._root = path.root
38 self._tail = path._tail
39
40 def __len__(self):
41 return len(self._tail)
42
43 def __getitem__(self, idx):
44 if isinstance(idx, slice):
45 return tuple(self[i] for i in range(*idx.indices(len(self))))
46
47 if idx >= len(self) or idx < -len(self):
48 raise IndexError(idx)
49 if idx < 0:
50 idx += len(self)
51 return self._path._from_parsed_parts(self._drv, self._root,
52 self._tail[:-idx - 1])
53
54 def __repr__(self):
55 return "<{}.parents>".format(type(self._path).__name__)
56
57
58 class PurePath(PurePathBase):
59 """Base class for manipulating paths without I/O.
60
61 PurePath represents a filesystem path and offers operations which
62 don't imply any actual filesystem I/O. Depending on your system,
63 instantiating a PurePath will return either a PurePosixPath or a
64 PureWindowsPath object. You can also instantiate either of these classes
65 directly, regardless of your system.
66 """
67
68 __slots__ = (
69 # The `_raw_paths` slot stores unnormalized string paths. This is set
70 # in the `__init__()` method.
71 '_raw_paths',
72
73 # The `_drv`, `_root` and `_tail_cached` slots store parsed and
74 # normalized parts of the path. They are set when any of the `drive`,
75 # `root` or `_tail` properties are accessed for the first time. The
76 # three-part division corresponds to the result of
77 # `os.path.splitroot()`, except that the tail is further split on path
78 # separators (i.e. it is a list of strings), and that the root and
79 # tail are normalized.
80 '_drv', '_root', '_tail_cached',
81
82 # The `_str` slot stores the string representation of the path,
83 # computed from the drive, root and tail when `__str__()` is called
84 # for the first time. It's used to implement `_str_normcase`
85 '_str',
86
87 # The `_str_normcase_cached` slot stores the string path with
88 # normalized case. It is set when the `_str_normcase` property is
89 # accessed for the first time. It's used to implement `__eq__()`
90 # `__hash__()`, and `_parts_normcase`
91 '_str_normcase_cached',
92
93 # The `_parts_normcase_cached` slot stores the case-normalized
94 # string path after splitting on path separators. It's set when the
95 # `_parts_normcase` property is accessed for the first time. It's used
96 # to implement comparison methods like `__lt__()`.
97 '_parts_normcase_cached',
98
99 # The `_hash` slot stores the hash of the case-normalized string
100 # path. It's set when `__hash__()` is called for the first time.
101 '_hash',
102 )
103 parser = os.path
104 _globber = _StringGlobber
105
106 def __new__(cls, *args, **kwargs):
107 """Construct a PurePath from one or several strings and or existing
108 PurePath objects. The strings and path objects are combined so as
109 to yield a canonicalized path, which is incorporated into the
110 new PurePath object.
111 """
112 if cls is PurePath:
113 cls = PureWindowsPath if os.name == 'nt' else PurePosixPath
114 return object.__new__(cls)
115
116 def __init__(self, *args):
•117 import ntpath
118 paths = []
119 for arg in args:
120 if isinstance(arg, PurePath):
121 if arg.parser is not self.parser:
122 # GH-103631: Convert separators for backwards compatibility.
123 paths.append(arg.as_posix())
124 else:
125 paths.extend(arg._raw_paths)
126 else:
127 try:
128 path = os.fspath(arg)
129 except TypeError:
130 path = arg
131 if not isinstance(path, str):
132 raise TypeError(
133 "argument should be a str or an os.PathLike "
134 "object where __fspath__ returns a str, "
135 f"not {type(path).__name__!r}")
136 paths.append(path)
137 # Avoid calling super().__init__, as an optimisation
138 self._raw_paths = paths
139
140 def joinpath(self, *pathsegments):
141 """Combine this path with one or several arguments, and return a
142 new path representing either a subpath (if all arguments are relative
143 paths) or a totally different path (if one of the arguments is
144 anchored).
145 """
146 return self.with_segments(self, *pathsegments)
147
148 def __truediv__(self, key):
149 try:
150 return self.with_segments(self, key)
151 except TypeError:
152 return NotImplemented
153
154 def __rtruediv__(self, key):
155 try:
156 return self.with_segments(key, self)
157 except TypeError:
158 return NotImplemented
159
160 def __reduce__(self):
161 return self.__class__, tuple(self._raw_paths)
162
163 def __repr__(self):
164 return "{}({!r})".format(self.__class__.__name__, self.as_posix())
165
166 def __fspath__(self):
167 return str(self)
168
169 def __bytes__(self):
170 """Return the bytes representation of the path. This is only
171 recommended to use under Unix."""
172 return os.fsencode(self)
173
174 @property
175 def _str_normcase(self):
176 # String with normalized case, for hashing and equality checks
177 try:
178 return self._str_normcase_cached
179 except AttributeError:
180 if self.parser is posixpath:
181 self._str_normcase_cached = str(self)
182 else:
183 self._str_normcase_cached = str(self).lower()
184 return self._str_normcase_cached
185
186 def __hash__(self):
187 try:
188 return self._hash
189 except AttributeError:
190 self._hash = hash(self._str_normcase)
191 return self._hash
192
193 def __eq__(self, other):
194 if not isinstance(other, PurePath):
195 return NotImplemented
196 return self._str_normcase == other._str_normcase and self.parser is other.parser
197
198 @property
199 def _parts_normcase(self):
200 # Cached parts with normalized case, for comparisons.
201 try:
202 return self._parts_normcase_cached
203 except AttributeError:
204 self._parts_normcase_cached = self._str_normcase.split(self.parser.sep)
205 return self._parts_normcase_cached
206
207 def __lt__(self, other):
208 if not isinstance(other, PurePath) or self.parser is not other.parser:
209 return NotImplemented
210 return self._parts_normcase < other._parts_normcase
211
212 def __le__(self, other):
213 if not isinstance(other, PurePath) or self.parser is not other.parser:
214 return NotImplemented
215 return self._parts_normcase <= other._parts_normcase
216
217 def __gt__(self, other):
218 if not isinstance(other, PurePath) or self.parser is not other.parser:
219 return NotImplemented
220 return self._parts_normcase > other._parts_normcase
221
222 def __ge__(self, other):
223 if not isinstance(other, PurePath) or self.parser is not other.parser:
224 return NotImplemented
225 return self._parts_normcase >= other._parts_normcase
226
227 def __str__(self):
228 """Return the string representation of the path, suitable for
229 passing to system calls."""
230 try:
231 return self._str
232 except AttributeError:
233 self._str = self._format_parsed_parts(self.drive, self.root,
234 self._tail) or '.'
235 return self._str
236
237 @classmethod
238 def _format_parsed_parts(cls, drv, root, tail):
239 if drv or root:
240 return drv + root + cls.parser.sep.join(tail)
241 elif tail and cls.parser.splitdrive(tail[0])[0]:
242 tail = ['.'] + tail
243 return cls.parser.sep.join(tail)
244
245 def _from_parsed_parts(self, drv, root, tail):
246 path = self._from_parsed_string(self._format_parsed_parts(drv, root, tail))
247 path._drv = drv
248 path._root = root
249 path._tail_cached = tail
250 return path
251
252 def _from_parsed_string(self, path_str):
253 path = self.with_segments(path_str)
254 path._str = path_str or '.'
255 return path
256
257 @classmethod
258 def _parse_path(cls, path):
259 if not path:
260 return '', '', []
261 sep = cls.parser.sep
262 altsep = cls.parser.altsep
263 if altsep:
264 path = path.replace(altsep, sep)
265 drv, root, rel = cls.parser.splitroot(path)
266 if not root and drv.startswith(sep) and not drv.endswith(sep):
267 drv_parts = drv.split(sep)
268 if len(drv_parts) == 4 and drv_parts[2] not in '?.':
269 # e.g. //server/share
270 root = sep
271 elif len(drv_parts) == 6:
272 # e.g. //?/unc/server/share
273 root = sep
274 parsed = [sys.intern(str(x)) for x in rel.split(sep) if x and x != '.']
275 return drv, root, parsed
276
277 @property
278 def _raw_path(self):
279 """The joined but unnormalized path."""
280 paths = self._raw_paths
281 if len(paths) == 0:
282 path = ''
283 elif len(paths) == 1:
284 path = paths[0]
285 else:
286 path = self.parser.join(*paths)
287 return path
288
289 @property
290 def drive(self):
291 """The drive prefix (letter or UNC path), if any."""
292 try:
293 return self._drv
294 except AttributeError:
295 self._drv, self._root, self._tail_cached = self._parse_path(self._raw_path)
296 return self._drv
297
298 @property
299 def root(self):
300 """The root of the path, if any."""
301 try:
302 return self._root
303 except AttributeError:
304 self._drv, self._root, self._tail_cached = self._parse_path(self._raw_path)
305 return self._root
306
307 @property
308 def _tail(self):
309 try:
310 return self._tail_cached
311 except AttributeError:
312 self._drv, self._root, self._tail_cached = self._parse_path(self._raw_path)
313 return self._tail_cached
314
315 @property
316 def anchor(self):
317 """The concatenation of the drive and root, or ''."""
318 return self.drive + self.root
319
320 @property
321 def parts(self):
322 """An object providing sequence-like access to the
323 components in the filesystem path."""
324 if self.drive or self.root:
325 return (self.drive + self.root,) + tuple(self._tail)
326 else:
327 return tuple(self._tail)
328
329 @property
330 def parent(self):
331 """The logical parent of the path."""
332 drv = self.drive
333 root = self.root
334 tail = self._tail
335 if not tail:
336 return self
337 return self._from_parsed_parts(drv, root, tail[:-1])
338
339 @property
340 def parents(self):
341 """A sequence of this path's logical parents."""
342 # The value of this property should not be cached on the path object,
343 # as doing so would introduce a reference cycle.
344 return _PathParents(self)
345
346 @property
347 def name(self):
348 """The final path component, if any."""
349 tail = self._tail
350 if not tail:
351 return ''
352 return tail[-1]
353
354 def with_name(self, name):
355 """Return a new path with the file name changed."""
356 p = self.parser
357 if not name or p.sep in name or (p.altsep and p.altsep in name) or name == '.':
358 raise ValueError(f"Invalid name {name!r}")
359 tail = self._tail.copy()
360 if not tail:
361 raise ValueError(f"{self!r} has an empty name")
362 tail[-1] = name
363 return self._from_parsed_parts(self.drive, self.root, tail)
364
365 def relative_to(self, other, /, *_deprecated, walk_up=False):
366 """Return the relative path to another path identified by the passed
367 arguments. If the operation is not possible (because this is not
368 related to the other path), raise ValueError.
369
370 The *walk_up* parameter controls whether `..` may be used to resolve
371 the path.
372 """
373 if _deprecated:
374 msg = ("support for supplying more than one positional argument "
375 "to pathlib.PurePath.relative_to() is deprecated and "
376 "scheduled for removal in Python 3.14")
377 warnings.warn(msg, DeprecationWarning, stacklevel=2)
378 other = self.with_segments(other, *_deprecated)
379 elif not isinstance(other, PurePath):
380 other = self.with_segments(other)
381 for step, path in enumerate(chain([other], other.parents)):
382 if path == self or path in self.parents:
383 break
384 elif not walk_up:
385 raise ValueError(f"{str(self)!r} is not in the subpath of {str(other)!r}")
386 elif path.name == '..':
387 raise ValueError(f"'..' segment in {str(other)!r} cannot be walked")
388 else:
389 raise ValueError(f"{str(self)!r} and {str(other)!r} have different anchors")
390 parts = ['..'] * step + self._tail[len(path._tail):]
391 return self._from_parsed_parts('', '', parts)
392
393 def is_relative_to(self, other, /, *_deprecated):
394 """Return True if the path is relative to another path or False.
395 """
396 if _deprecated:
397 msg = ("support for supplying more than one argument to "
398 "pathlib.PurePath.is_relative_to() is deprecated and "
399 "scheduled for removal in Python 3.14")
400 warnings.warn(msg, DeprecationWarning, stacklevel=2)
401 other = self.with_segments(other, *_deprecated)
402 elif not isinstance(other, PurePath):
403 other = self.with_segments(other)
404 return other == self or other in self.parents
405
406 def is_absolute(self):
407 """True if the path is absolute (has both a root and, if applicable,
408 a drive)."""
409 if self.parser is posixpath:
410 # Optimization: work with raw paths on POSIX.
411 for path in self._raw_paths:
412 if path.startswith('/'):
413 return True
414 return False
415 return self.parser.isabs(self)
416
417 def is_reserved(self):
418 """Return True if the path contains one of the special names reserved
419 by the system, if any."""
•420 import ntpath
421 msg = ("pathlib.PurePath.is_reserved() is deprecated and scheduled "
422 "for removal in Python 3.15. Use os.path.isreserved() to "
423 "detect reserved paths on Windows.")
424 warnings.warn(msg, DeprecationWarning, stacklevel=2)
425 if self.parser is ntpath:
426 return self.parser.isreserved(self)
427 return False
428
429 def as_uri(self):
430 """Return the path as a URI."""
431 if not self.is_absolute():
432 raise ValueError("relative path can't be expressed as a file URI")
433
434 drive = self.drive
435 if len(drive) == 2 and drive[1] == ':':
436 # It's a path on a local drive => 'file:///c:/a/b'
437 prefix = 'file:///' + drive
438 path = self.as_posix()[2:]
439 elif drive:
440 # It's a path on a network drive => 'file://host/share/a/b'
441 prefix = 'file:'
442 path = self.as_posix()
443 else:
444 # It's a posix path => 'file:///etc/hosts'
445 prefix = 'file://'
446 path = str(self)
447 from urllib.parse import quote_from_bytes
448 return prefix + quote_from_bytes(os.fsencode(path))
449
450 @property
451 def _pattern_str(self):
452 """The path expressed as a string, for use in pattern-matching."""
453 # The string representation of an empty path is a single dot ('.'). Empty
454 # paths shouldn't match wildcards, so we change it to the empty string.
455 path_str = str(self)
456 return '' if path_str == '.' else path_str
457
458 # Subclassing os.PathLike makes isinstance() checks slower,
459 # which in turn makes Path construction slower. Register instead!
460 os.PathLike.register(PurePath)
461
462
463 class PurePosixPath(PurePath):
464 """PurePath subclass for non-Windows systems.
465
466 On a POSIX system, instantiating a PurePath should return this object.
467 However, you can also instantiate it directly on any system.
468 """
469 parser = posixpath
470 __slots__ = ()
471
472
473 class PureWindowsPath(PurePath):
474 """PurePath subclass for Windows systems.
475
476 On a Windows system, instantiating a PurePath should return this object.
477 However, you can also instantiate it directly on any system.
478 """
•479 import ntpath
480 parser = ntpath
481 __slots__ = ()
482
483
484 class Path(PathBase, PurePath):
485 """PurePath subclass that can make system calls.
486
487 Path represents a filesystem path but unlike PurePath, also offers
488 methods to do system calls on path objects. Depending on your system,
489 instantiating a Path will return either a PosixPath or a WindowsPath
490 object. You can also instantiate a PosixPath or WindowsPath directly,
491 but cannot instantiate a WindowsPath on a POSIX system or vice versa.
492 """
493 __slots__ = ()
494 as_uri = PurePath.as_uri
495
496 @classmethod
497 def _unsupported_msg(cls, attribute):
498 return f"{cls.__name__}.{attribute} is unsupported on this system"
499
500 def __init__(self, *args, **kwargs):
501 if kwargs:
502 msg = ("support for supplying keyword arguments to pathlib.PurePath "
503 "is deprecated and scheduled for removal in Python {remove}")
504 warnings._deprecated("pathlib.PurePath(**kwargs)", msg, remove=(3, 14))
505 super().__init__(*args)
506
507 def __new__(cls, *args, **kwargs):
508 if cls is Path:
509 cls = WindowsPath if os.name == 'nt' else PosixPath
510 return object.__new__(cls)
511
512 def stat(self, *, follow_symlinks=True):
513 """
514 Return the result of the stat() system call on this path, like
515 os.stat() does.
516 """
517 return os.stat(self, follow_symlinks=follow_symlinks)
518
519 def is_mount(self):
520 """
521 Check if this path is a mount point
522 """
523 return os.path.ismount(self)
524
525 def is_junction(self):
526 """
527 Whether this path is a junction.
528 """
529 return os.path.isjunction(self)
530
531 def open(self, mode='r', buffering=-1, encoding=None,
532 errors=None, newline=None):
533 """
534 Open the file pointed to by this path and return a file object, as
535 the built-in open() function does.
536 """
537 if "b" not in mode:
538 encoding = io.text_encoding(encoding)
539 return io.open(self, mode, buffering, encoding, errors, newline)
540
541 def read_text(self, encoding=None, errors=None, newline=None):
542 """
543 Open the file in text mode, read it, and close the file.
544 """
545 # Call io.text_encoding() here to ensure any warning is raised at an
546 # appropriate stack level.
547 encoding = io.text_encoding(encoding)
548 return PathBase.read_text(self, encoding, errors, newline)
549
550 def write_text(self, data, encoding=None, errors=None, newline=None):
551 """
552 Open the file in text mode, write to it, and close the file.
553 """
554 # Call io.text_encoding() here to ensure any warning is raised at an
555 # appropriate stack level.
556 encoding = io.text_encoding(encoding)
557 return PathBase.write_text(self, data, encoding, errors, newline)
558
559 _remove_leading_dot = operator.itemgetter(slice(2, None))
560 _remove_trailing_slash = operator.itemgetter(slice(-1))
561
562 def _filter_trailing_slash(self, paths):
563 sep = self.parser.sep
564 anchor_len = len(self.anchor)
565 for path_str in paths:
566 if len(path_str) > anchor_len and path_str[-1] == sep:
567 path_str = path_str[:-1]
568 yield path_str
569
570 def iterdir(self):
571 """Yield path objects of the directory contents.
572
573 The children are yielded in arbitrary order, and the
574 special entries '.' and '..' are not included.
575 """
576 root_dir = str(self)
577 with os.scandir(root_dir) as scandir_it:
578 paths = [entry.path for entry in scandir_it]
579 if root_dir == '.':
580 paths = map(self._remove_leading_dot, paths)
581 return map(self._from_parsed_string, paths)
582
583 def glob(self, pattern, *, case_sensitive=None, recurse_symlinks=False):
584 """Iterate over this subtree and yield all existing files (of any
585 kind, including directories) matching the given relative pattern.
586 """
587 sys.audit("pathlib.Path.glob", self, pattern)
588 if not isinstance(pattern, PurePath):
589 pattern = self.with_segments(pattern)
590 if pattern.anchor:
591 raise NotImplementedError("Non-relative patterns are unsupported")
592 parts = pattern._tail.copy()
593 if not parts:
594 raise ValueError("Unacceptable pattern: {!r}".format(pattern))
595 raw = pattern._raw_path
596 if raw[-1] in (self.parser.sep, self.parser.altsep):
597 # GH-65238: pathlib doesn't preserve trailing slash. Add it back.
598 parts.append('')
599 select = self._glob_selector(parts[::-1], case_sensitive, recurse_symlinks)
600 root = str(self)
601 paths = select(root)
602
603 # Normalize results
604 if root == '.':
605 paths = map(self._remove_leading_dot, paths)
606 if parts[-1] == '':
607 paths = map(self._remove_trailing_slash, paths)
608 elif parts[-1] == '**':
609 paths = self._filter_trailing_slash(paths)
610 paths = map(self._from_parsed_string, paths)
611 return paths
612
613 def rglob(self, pattern, *, case_sensitive=None, recurse_symlinks=False):
614 """Recursively yield all existing files (of any kind, including
615 directories) matching the given relative pattern, anywhere in
616 this subtree.
617 """
618 sys.audit("pathlib.Path.rglob", self, pattern)
619 if not isinstance(pattern, PurePath):
620 pattern = self.with_segments(pattern)
621 pattern = '**' / pattern
622 return self.glob(pattern, case_sensitive=case_sensitive, recurse_symlinks=recurse_symlinks)
623
624 def walk(self, top_down=True, on_error=None, follow_symlinks=False):
625 """Walk the directory tree from this directory, similar to os.walk()."""
626 sys.audit("pathlib.Path.walk", self, on_error, follow_symlinks)
627 root_dir = str(self)
628 if not follow_symlinks:
629 follow_symlinks = os._walk_symlinks_as_files
630 results = os.walk(root_dir, top_down, on_error, follow_symlinks)
631 for path_str, dirnames, filenames in results:
632 if root_dir == '.':
633 path_str = path_str[2:]
634 yield self._from_parsed_string(path_str), dirnames, filenames
635
636 def absolute(self):
637 """Return an absolute version of this path
638 No normalization or symlink resolution is performed.
639
640 Use resolve() to resolve symlinks and remove '..' segments.
641 """
642 if self.is_absolute():
643 return self
644 if self.root:
645 drive = os.path.splitroot(os.getcwd())[0]
646 return self._from_parsed_parts(drive, self.root, self._tail)
647 if self.drive:
648 # There is a CWD on each drive-letter drive.
649 cwd = os.path.abspath(self.drive)
650 else:
651 cwd = os.getcwd()
652 if not self._tail:
653 # Fast path for "empty" paths, e.g. Path("."), Path("") or Path().
654 # We pass only one argument to with_segments() to avoid the cost
655 # of joining, and we exploit the fact that getcwd() returns a
656 # fully-normalized string by storing it in _str. This is used to
657 # implement Path.cwd().
658 return self._from_parsed_string(cwd)
659 drive, root, rel = os.path.splitroot(cwd)
660 if not rel:
661 return self._from_parsed_parts(drive, root, self._tail)
662 tail = rel.split(self.parser.sep)
663 tail.extend(self._tail)
664 return self._from_parsed_parts(drive, root, tail)
665
666 def resolve(self, strict=False):
667 """
668 Make the path absolute, resolving all symlinks on the way and also
669 normalizing it.
670 """
671
672 return self.with_segments(os.path.realpath(self, strict=strict))
673
674 if pwd:
675 def owner(self, *, follow_symlinks=True):
676 """
677 Return the login name of the file owner.
678 """
679 uid = self.stat(follow_symlinks=follow_symlinks).st_uid
680 return pwd.getpwuid(uid).pw_name
681
682 if grp:
683 def group(self, *, follow_symlinks=True):
684 """
685 Return the group name of the file gid.
686 """
687 gid = self.stat(follow_symlinks=follow_symlinks).st_gid
688 return grp.getgrgid(gid).gr_name
689
690 if hasattr(os, "readlink"):
691 def readlink(self):
692 """
693 Return the path to which the symbolic link points.
694 """
695 return self.with_segments(os.readlink(self))
696
697 def touch(self, mode=0o666, exist_ok=True):
698 """
699 Create this file with the given access mode, if it doesn't exist.
700 """
701
702 if exist_ok:
703 # First try to bump modification time
704 # Implementation note: GNU touch uses the UTIME_NOW option of
705 # the utimensat() / futimens() functions.
706 try:
707 os.utime(self, None)
708 except OSError:
709 # Avoid exception chaining
710 pass
711 else:
712 return
713 flags = os.O_CREAT | os.O_WRONLY
714 if not exist_ok:
715 flags |= os.O_EXCL
716 fd = os.open(self, flags, mode)
717 os.close(fd)
718
719 def mkdir(self, mode=0o777, parents=False, exist_ok=False):
720 """
721 Create a new directory at this given path.
722 """
723 try:
724 os.mkdir(self, mode)
725 except FileNotFoundError:
726 if not parents or self.parent == self:
727 raise
728 self.parent.mkdir(parents=True, exist_ok=True)
729 self.mkdir(mode, parents=False, exist_ok=exist_ok)
730 except OSError:
731 # Cannot rely on checking for EEXIST, since the operating system
732 # could give priority to other errors like EACCES or EROFS
733 if not exist_ok or not self.is_dir():
734 raise
735
736 def chmod(self, mode, *, follow_symlinks=True):
737 """
738 Change the permissions of the path, like os.chmod().
739 """
740 os.chmod(self, mode, follow_symlinks=follow_symlinks)
741
742 def unlink(self, missing_ok=False):
743 """
744 Remove this file or link.
745 If the path is a directory, use rmdir() instead.
746 """
747 try:
748 os.unlink(self)
749 except FileNotFoundError:
750 if not missing_ok:
751 raise
752
753 def rmdir(self):
754 """
755 Remove this directory. The directory must be empty.
756 """
757 os.rmdir(self)
758
759 def rename(self, target):
760 """
761 Rename this path to the target path.
762
763 The target path may be absolute or relative. Relative paths are
764 interpreted relative to the current working directory, *not* the
765 directory of the Path object.
766
767 Returns the new Path instance pointing to the target path.
768 """
769 os.rename(self, target)
770 return self.with_segments(target)
771
772 def replace(self, target):
773 """
774 Rename this path to the target path, overwriting if that path exists.
775
776 The target path may be absolute or relative. Relative paths are
777 interpreted relative to the current working directory, *not* the
778 directory of the Path object.
779
780 Returns the new Path instance pointing to the target path.
781 """
782 os.replace(self, target)
783 return self.with_segments(target)
784
785 if hasattr(os, "symlink"):
786 def symlink_to(self, target, target_is_directory=False):
787 """
788 Make this path a symlink pointing to the target path.
789 Note the order of arguments (link, target) is the reverse of os.symlink.
790 """
791 os.symlink(target, self, target_is_directory)
792
793 if hasattr(os, "link"):
794 def hardlink_to(self, target):
795 """
796 Make this path a hard link pointing to the same file as *target*.
797
798 Note the order of arguments (self, target) is the reverse of os.link's.
799 """
800 os.link(target, self)
801
802 def expanduser(self):
803 """ Return a new path with expanded ~ and ~user constructs
804 (as returned by os.path.expanduser)
805 """
806 if (not (self.drive or self.root) and
807 self._tail and self._tail[0][:1] == '~'):
808 homedir = os.path.expanduser(self._tail[0])
809 if homedir[:1] == "~":
810 raise RuntimeError("Could not determine home directory.")
811 drv, root, tail = self._parse_path(homedir)
812 return self._from_parsed_parts(drv, root, tail + self._tail[1:])
813
814 return self
815
816 @classmethod
817 def from_uri(cls, uri):
818 """Return a new path from the given 'file' URI."""
819 if not uri.startswith('file:'):
820 raise ValueError(f"URI does not start with 'file:': {uri!r}")
821 path = uri[5:]
822 if path[:3] == '///':
823 # Remove empty authority
824 path = path[2:]
825 elif path[:12] == '//localhost/':
826 # Remove 'localhost' authority
827 path = path[11:]
828 if path[:3] == '///' or (path[:1] == '/' and path[2:3] in ':|'):
829 # Remove slash before DOS device/UNC path
830 path = path[1:]
831 if path[1:2] == '|':
832 # Replace bar with colon in DOS drive
833 path = path[:1] + ':' + path[2:]
834 from urllib.parse import unquote_to_bytes
835 path = cls(os.fsdecode(unquote_to_bytes(path)))
836 if not path.is_absolute():
837 raise ValueError(f"URI is not absolute: {uri!r}")
838 return path
839
840
841 class PosixPath(Path, PurePosixPath):
842 """Path subclass for non-Windows systems.
843
844 On a POSIX system, instantiating a Path should return this object.
845 """
846 __slots__ = ()
847
848 if os.name == 'nt':
849 def __new__(cls, *args, **kwargs):
850 raise UnsupportedOperation(
851 f"cannot instantiate {cls.__name__!r} on your system")
852
853 class WindowsPath(Path, PureWindowsPath):
854 """Path subclass for Windows systems.
855
856 On a Windows system, instantiating a Path should return this object.
857 """
858 __slots__ = ()
859
860 if os.name != 'nt':
861 def __new__(cls, *args, **kwargs):
862 raise UnsupportedOperation(
863 f"cannot instantiate {cls.__name__!r} on your system")