logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

pathlib.py (49526B)


  1. import fnmatch
  2. import functools
  3. import io
  4. import ntpath
  5. import os
  6. import posixpath
  7. import re
  8. import sys
  9. import warnings
  10. from _collections_abc import Sequence
  11. from errno import EINVAL, ENOENT, ENOTDIR, EBADF, ELOOP
  12. from operator import attrgetter
  13. from stat import S_ISDIR, S_ISLNK, S_ISREG, S_ISSOCK, S_ISBLK, S_ISCHR, S_ISFIFO
  14. from urllib.parse import quote_from_bytes as urlquote_from_bytes
  15. __all__ = [
  16. "PurePath", "PurePosixPath", "PureWindowsPath",
  17. "Path", "PosixPath", "WindowsPath",
  18. ]
  19. #
  20. # Internals
  21. #
  22. _WINERROR_NOT_READY = 21 # drive exists but is not accessible
  23. _WINERROR_INVALID_NAME = 123 # fix for bpo-35306
  24. _WINERROR_CANT_RESOLVE_FILENAME = 1921 # broken symlink pointing to itself
  25. # EBADF - guard against macOS `stat` throwing EBADF
  26. _IGNORED_ERROS = (ENOENT, ENOTDIR, EBADF, ELOOP)
  27. _IGNORED_WINERRORS = (
  28. _WINERROR_NOT_READY,
  29. _WINERROR_INVALID_NAME,
  30. _WINERROR_CANT_RESOLVE_FILENAME)
  31. def _ignore_error(exception):
  32. return (getattr(exception, 'errno', None) in _IGNORED_ERROS or
  33. getattr(exception, 'winerror', None) in _IGNORED_WINERRORS)
  34. def _is_wildcard_pattern(pat):
  35. # Whether this pattern needs actual matching using fnmatch, or can
  36. # be looked up directly as a file.
  37. return "*" in pat or "?" in pat or "[" in pat
  38. class _Flavour(object):
  39. """A flavour implements a particular (platform-specific) set of path
  40. semantics."""
  41. def __init__(self):
  42. self.join = self.sep.join
  43. def parse_parts(self, parts):
  44. parsed = []
  45. sep = self.sep
  46. altsep = self.altsep
  47. drv = root = ''
  48. it = reversed(parts)
  49. for part in it:
  50. if not part:
  51. continue
  52. if altsep:
  53. part = part.replace(altsep, sep)
  54. drv, root, rel = self.splitroot(part)
  55. if sep in rel:
  56. for x in reversed(rel.split(sep)):
  57. if x and x != '.':
  58. parsed.append(sys.intern(x))
  59. else:
  60. if rel and rel != '.':
  61. parsed.append(sys.intern(rel))
  62. if drv or root:
  63. if not drv:
  64. # If no drive is present, try to find one in the previous
  65. # parts. This makes the result of parsing e.g.
  66. # ("C:", "/", "a") reasonably intuitive.
  67. for part in it:
  68. if not part:
  69. continue
  70. if altsep:
  71. part = part.replace(altsep, sep)
  72. drv = self.splitroot(part)[0]
  73. if drv:
  74. break
  75. break
  76. if drv or root:
  77. parsed.append(drv + root)
  78. parsed.reverse()
  79. return drv, root, parsed
  80. def join_parsed_parts(self, drv, root, parts, drv2, root2, parts2):
  81. """
  82. Join the two paths represented by the respective
  83. (drive, root, parts) tuples. Return a new (drive, root, parts) tuple.
  84. """
  85. if root2:
  86. if not drv2 and drv:
  87. return drv, root2, [drv + root2] + parts2[1:]
  88. elif drv2:
  89. if drv2 == drv or self.casefold(drv2) == self.casefold(drv):
  90. # Same drive => second path is relative to the first
  91. return drv, root, parts + parts2[1:]
  92. else:
  93. # Second path is non-anchored (common case)
  94. return drv, root, parts + parts2
  95. return drv2, root2, parts2
  96. class _WindowsFlavour(_Flavour):
  97. # Reference for Windows paths can be found at
  98. # http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
  99. sep = '\\'
  100. altsep = '/'
  101. has_drv = True
  102. pathmod = ntpath
  103. is_supported = (os.name == 'nt')
  104. drive_letters = set('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
  105. ext_namespace_prefix = '\\\\?\\'
  106. reserved_names = (
  107. {'CON', 'PRN', 'AUX', 'NUL', 'CONIN$', 'CONOUT$'} |
  108. {'COM%s' % c for c in '123456789\xb9\xb2\xb3'} |
  109. {'LPT%s' % c for c in '123456789\xb9\xb2\xb3'}
  110. )
  111. # Interesting findings about extended paths:
  112. # * '\\?\c:\a' is an extended path, which bypasses normal Windows API
  113. # path processing. Thus relative paths are not resolved and slash is not
  114. # translated to backslash. It has the native NT path limit of 32767
  115. # characters, but a bit less after resolving device symbolic links,
  116. # such as '\??\C:' => '\Device\HarddiskVolume2'.
  117. # * '\\?\c:/a' looks for a device named 'C:/a' because slash is a
  118. # regular name character in the object namespace.
  119. # * '\\?\c:\foo/bar' is invalid because '/' is illegal in NT filesystems.
  120. # The only path separator at the filesystem level is backslash.
  121. # * '//?/c:\a' and '//?/c:/a' are effectively equivalent to '\\.\c:\a' and
  122. # thus limited to MAX_PATH.
  123. # * Prior to Windows 8, ANSI API bytes paths are limited to MAX_PATH,
  124. # even with the '\\?\' prefix.
  125. def splitroot(self, part, sep=sep):
  126. first = part[0:1]
  127. second = part[1:2]
  128. if (second == sep and first == sep):
  129. # XXX extended paths should also disable the collapsing of "."
  130. # components (according to MSDN docs).
  131. prefix, part = self._split_extended_path(part)
  132. first = part[0:1]
  133. second = part[1:2]
  134. else:
  135. prefix = ''
  136. third = part[2:3]
  137. if (second == sep and first == sep and third != sep):
  138. # is a UNC path:
  139. # vvvvvvvvvvvvvvvvvvvvv root
  140. # \\machine\mountpoint\directory\etc\...
  141. # directory ^^^^^^^^^^^^^^
  142. index = part.find(sep, 2)
  143. if index != -1:
  144. index2 = part.find(sep, index + 1)
  145. # a UNC path can't have two slashes in a row
  146. # (after the initial two)
  147. if index2 != index + 1:
  148. if index2 == -1:
  149. index2 = len(part)
  150. if prefix:
  151. return prefix + part[1:index2], sep, part[index2+1:]
  152. else:
  153. return part[:index2], sep, part[index2+1:]
  154. drv = root = ''
  155. if second == ':' and first in self.drive_letters:
  156. drv = part[:2]
  157. part = part[2:]
  158. first = third
  159. if first == sep:
  160. root = first
  161. part = part.lstrip(sep)
  162. return prefix + drv, root, part
  163. def casefold(self, s):
  164. return s.lower()
  165. def casefold_parts(self, parts):
  166. return [p.lower() for p in parts]
  167. def compile_pattern(self, pattern):
  168. return re.compile(fnmatch.translate(pattern), re.IGNORECASE).fullmatch
  169. def _split_extended_path(self, s, ext_prefix=ext_namespace_prefix):
  170. prefix = ''
  171. if s.startswith(ext_prefix):
  172. prefix = s[:4]
  173. s = s[4:]
  174. if s.startswith('UNC\\'):
  175. prefix += s[:3]
  176. s = '\\' + s[3:]
  177. return prefix, s
  178. def is_reserved(self, parts):
  179. # NOTE: the rules for reserved names seem somewhat complicated
  180. # (e.g. r"..\NUL" is reserved but not r"foo\NUL" if "foo" does not
  181. # exist). We err on the side of caution and return True for paths
  182. # which are not considered reserved by Windows.
  183. if not parts:
  184. return False
  185. if parts[0].startswith('\\\\'):
  186. # UNC paths are never reserved
  187. return False
  188. name = parts[-1].partition('.')[0].partition(':')[0].rstrip(' ')
  189. return name.upper() in self.reserved_names
  190. def make_uri(self, path):
  191. # Under Windows, file URIs use the UTF-8 encoding.
  192. drive = path.drive
  193. if len(drive) == 2 and drive[1] == ':':
  194. # It's a path on a local drive => 'file:///c:/a/b'
  195. rest = path.as_posix()[2:].lstrip('/')
  196. return 'file:///%s/%s' % (
  197. drive, urlquote_from_bytes(rest.encode('utf-8')))
  198. else:
  199. # It's a path on a network drive => 'file://host/share/a/b'
  200. return 'file:' + urlquote_from_bytes(path.as_posix().encode('utf-8'))
  201. class _PosixFlavour(_Flavour):
  202. sep = '/'
  203. altsep = ''
  204. has_drv = False
  205. pathmod = posixpath
  206. is_supported = (os.name != 'nt')
  207. def splitroot(self, part, sep=sep):
  208. if part and part[0] == sep:
  209. stripped_part = part.lstrip(sep)
  210. # According to POSIX path resolution:
  211. # http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap04.html#tag_04_11
  212. # "A pathname that begins with two successive slashes may be
  213. # interpreted in an implementation-defined manner, although more
  214. # than two leading slashes shall be treated as a single slash".
  215. if len(part) - len(stripped_part) == 2:
  216. return '', sep * 2, stripped_part
  217. else:
  218. return '', sep, stripped_part
  219. else:
  220. return '', '', part
  221. def casefold(self, s):
  222. return s
  223. def casefold_parts(self, parts):
  224. return parts
  225. def compile_pattern(self, pattern):
  226. return re.compile(fnmatch.translate(pattern)).fullmatch
  227. def is_reserved(self, parts):
  228. return False
  229. def make_uri(self, path):
  230. # We represent the path using the local filesystem encoding,
  231. # for portability to other applications.
  232. bpath = bytes(path)
  233. return 'file://' + urlquote_from_bytes(bpath)
  234. _windows_flavour = _WindowsFlavour()
  235. _posix_flavour = _PosixFlavour()
  236. class _Accessor:
  237. """An accessor implements a particular (system-specific or not) way of
  238. accessing paths on the filesystem."""
  239. class _NormalAccessor(_Accessor):
  240. stat = os.stat
  241. open = io.open
  242. listdir = os.listdir
  243. scandir = os.scandir
  244. chmod = os.chmod
  245. mkdir = os.mkdir
  246. unlink = os.unlink
  247. if hasattr(os, "link"):
  248. link = os.link
  249. else:
  250. def link(self, src, dst):
  251. raise NotImplementedError("os.link() not available on this system")
  252. rmdir = os.rmdir
  253. rename = os.rename
  254. replace = os.replace
  255. if hasattr(os, "symlink"):
  256. symlink = os.symlink
  257. else:
  258. def symlink(self, src, dst, target_is_directory=False):
  259. raise NotImplementedError("os.symlink() not available on this system")
  260. def touch(self, path, mode=0o666, exist_ok=True):
  261. if exist_ok:
  262. # First try to bump modification time
  263. # Implementation note: GNU touch uses the UTIME_NOW option of
  264. # the utimensat() / futimens() functions.
  265. try:
  266. os.utime(path, None)
  267. except OSError:
  268. # Avoid exception chaining
  269. pass
  270. else:
  271. return
  272. flags = os.O_CREAT | os.O_WRONLY
  273. if not exist_ok:
  274. flags |= os.O_EXCL
  275. fd = os.open(path, flags, mode)
  276. os.close(fd)
  277. if hasattr(os, "readlink"):
  278. readlink = os.readlink
  279. else:
  280. def readlink(self, path):
  281. raise NotImplementedError("os.readlink() not available on this system")
  282. def owner(self, path):
  283. try:
  284. import pwd
  285. return pwd.getpwuid(self.stat(path).st_uid).pw_name
  286. except ImportError:
  287. raise NotImplementedError("Path.owner() is unsupported on this system")
  288. def group(self, path):
  289. try:
  290. import grp
  291. return grp.getgrgid(self.stat(path).st_gid).gr_name
  292. except ImportError:
  293. raise NotImplementedError("Path.group() is unsupported on this system")
  294. getcwd = os.getcwd
  295. expanduser = staticmethod(os.path.expanduser)
  296. realpath = staticmethod(os.path.realpath)
  297. _normal_accessor = _NormalAccessor()
  298. #
  299. # Globbing helpers
  300. #
  301. def _make_selector(pattern_parts, flavour):
  302. pat = pattern_parts[0]
  303. child_parts = pattern_parts[1:]
  304. if pat == '**':
  305. cls = _RecursiveWildcardSelector
  306. elif '**' in pat:
  307. raise ValueError("Invalid pattern: '**' can only be an entire path component")
  308. elif _is_wildcard_pattern(pat):
  309. cls = _WildcardSelector
  310. else:
  311. cls = _PreciseSelector
  312. return cls(pat, child_parts, flavour)
  313. if hasattr(functools, "lru_cache"):
  314. _make_selector = functools.lru_cache()(_make_selector)
  315. class _Selector:
  316. """A selector matches a specific glob pattern part against the children
  317. of a given path."""
  318. def __init__(self, child_parts, flavour):
  319. self.child_parts = child_parts
  320. if child_parts:
  321. self.successor = _make_selector(child_parts, flavour)
  322. self.dironly = True
  323. else:
  324. self.successor = _TerminatingSelector()
  325. self.dironly = False
  326. def select_from(self, parent_path):
  327. """Iterate over all child paths of `parent_path` matched by this
  328. selector. This can contain parent_path itself."""
  329. path_cls = type(parent_path)
  330. is_dir = path_cls.is_dir
  331. exists = path_cls.exists
  332. scandir = parent_path._accessor.scandir
  333. if not is_dir(parent_path):
  334. return iter([])
  335. return self._select_from(parent_path, is_dir, exists, scandir)
  336. class _TerminatingSelector:
  337. def _select_from(self, parent_path, is_dir, exists, scandir):
  338. yield parent_path
  339. class _PreciseSelector(_Selector):
  340. def __init__(self, name, child_parts, flavour):
  341. self.name = name
  342. _Selector.__init__(self, child_parts, flavour)
  343. def _select_from(self, parent_path, is_dir, exists, scandir):
  344. try:
  345. path = parent_path._make_child_relpath(self.name)
  346. if (is_dir if self.dironly else exists)(path):
  347. for p in self.successor._select_from(path, is_dir, exists, scandir):
  348. yield p
  349. except PermissionError:
  350. return
  351. class _WildcardSelector(_Selector):
  352. def __init__(self, pat, child_parts, flavour):
  353. self.match = flavour.compile_pattern(pat)
  354. _Selector.__init__(self, child_parts, flavour)
  355. def _select_from(self, parent_path, is_dir, exists, scandir):
  356. try:
  357. with scandir(parent_path) as scandir_it:
  358. entries = list(scandir_it)
  359. for entry in entries:
  360. if self.dironly:
  361. try:
  362. # "entry.is_dir()" can raise PermissionError
  363. # in some cases (see bpo-38894), which is not
  364. # among the errors ignored by _ignore_error()
  365. if not entry.is_dir():
  366. continue
  367. except OSError as e:
  368. if not _ignore_error(e):
  369. raise
  370. continue
  371. name = entry.name
  372. if self.match(name):
  373. path = parent_path._make_child_relpath(name)
  374. for p in self.successor._select_from(path, is_dir, exists, scandir):
  375. yield p
  376. except PermissionError:
  377. return
  378. class _RecursiveWildcardSelector(_Selector):
  379. def __init__(self, pat, child_parts, flavour):
  380. _Selector.__init__(self, child_parts, flavour)
  381. def _iterate_directories(self, parent_path, is_dir, scandir):
  382. yield parent_path
  383. try:
  384. with scandir(parent_path) as scandir_it:
  385. entries = list(scandir_it)
  386. for entry in entries:
  387. entry_is_dir = False
  388. try:
  389. entry_is_dir = entry.is_dir()
  390. except OSError as e:
  391. if not _ignore_error(e):
  392. raise
  393. if entry_is_dir and not entry.is_symlink():
  394. path = parent_path._make_child_relpath(entry.name)
  395. for p in self._iterate_directories(path, is_dir, scandir):
  396. yield p
  397. except PermissionError:
  398. return
  399. def _select_from(self, parent_path, is_dir, exists, scandir):
  400. try:
  401. yielded = set()
  402. try:
  403. successor_select = self.successor._select_from
  404. for starting_point in self._iterate_directories(parent_path, is_dir, scandir):
  405. for p in successor_select(starting_point, is_dir, exists, scandir):
  406. if p not in yielded:
  407. yield p
  408. yielded.add(p)
  409. finally:
  410. yielded.clear()
  411. except PermissionError:
  412. return
  413. #
  414. # Public API
  415. #
  416. class _PathParents(Sequence):
  417. """This object provides sequence-like access to the logical ancestors
  418. of a path. Don't try to construct it yourself."""
  419. __slots__ = ('_pathcls', '_drv', '_root', '_parts')
  420. def __init__(self, path):
  421. # We don't store the instance to avoid reference cycles
  422. self._pathcls = type(path)
  423. self._drv = path._drv
  424. self._root = path._root
  425. self._parts = path._parts
  426. def __len__(self):
  427. if self._drv or self._root:
  428. return len(self._parts) - 1
  429. else:
  430. return len(self._parts)
  431. def __getitem__(self, idx):
  432. if isinstance(idx, slice):
  433. return tuple(self[i] for i in range(*idx.indices(len(self))))
  434. if idx >= len(self) or idx < -len(self):
  435. raise IndexError(idx)
  436. return self._pathcls._from_parsed_parts(self._drv, self._root,
  437. self._parts[:-idx - 1])
  438. def __repr__(self):
  439. return "<{}.parents>".format(self._pathcls.__name__)
  440. class PurePath(object):
  441. """Base class for manipulating paths without I/O.
  442. PurePath represents a filesystem path and offers operations which
  443. don't imply any actual filesystem I/O. Depending on your system,
  444. instantiating a PurePath will return either a PurePosixPath or a
  445. PureWindowsPath object. You can also instantiate either of these classes
  446. directly, regardless of your system.
  447. """
  448. __slots__ = (
  449. '_drv', '_root', '_parts',
  450. '_str', '_hash', '_pparts', '_cached_cparts',
  451. )
  452. def __new__(cls, *args):
  453. """Construct a PurePath from one or several strings and or existing
  454. PurePath objects. The strings and path objects are combined so as
  455. to yield a canonicalized path, which is incorporated into the
  456. new PurePath object.
  457. """
  458. if cls is PurePath:
  459. cls = PureWindowsPath if os.name == 'nt' else PurePosixPath
  460. return cls._from_parts(args)
  461. def __reduce__(self):
  462. # Using the parts tuple helps share interned path parts
  463. # when pickling related paths.
  464. return (self.__class__, tuple(self._parts))
  465. @classmethod
  466. def _parse_args(cls, args):
  467. # This is useful when you don't want to create an instance, just
  468. # canonicalize some constructor arguments.
  469. parts = []
  470. for a in args:
  471. if isinstance(a, PurePath):
  472. parts += a._parts
  473. else:
  474. a = os.fspath(a)
  475. if isinstance(a, str):
  476. # Force-cast str subclasses to str (issue #21127)
  477. parts.append(str(a))
  478. else:
  479. raise TypeError(
  480. "argument should be a str object or an os.PathLike "
  481. "object returning str, not %r"
  482. % type(a))
  483. return cls._flavour.parse_parts(parts)
  484. @classmethod
  485. def _from_parts(cls, args):
  486. # We need to call _parse_args on the instance, so as to get the
  487. # right flavour.
  488. self = object.__new__(cls)
  489. drv, root, parts = self._parse_args(args)
  490. self._drv = drv
  491. self._root = root
  492. self._parts = parts
  493. return self
  494. @classmethod
  495. def _from_parsed_parts(cls, drv, root, parts):
  496. self = object.__new__(cls)
  497. self._drv = drv
  498. self._root = root
  499. self._parts = parts
  500. return self
  501. @classmethod
  502. def _format_parsed_parts(cls, drv, root, parts):
  503. if drv or root:
  504. return drv + root + cls._flavour.join(parts[1:])
  505. else:
  506. return cls._flavour.join(parts)
  507. def _make_child(self, args):
  508. drv, root, parts = self._parse_args(args)
  509. drv, root, parts = self._flavour.join_parsed_parts(
  510. self._drv, self._root, self._parts, drv, root, parts)
  511. return self._from_parsed_parts(drv, root, parts)
  512. def __str__(self):
  513. """Return the string representation of the path, suitable for
  514. passing to system calls."""
  515. try:
  516. return self._str
  517. except AttributeError:
  518. self._str = self._format_parsed_parts(self._drv, self._root,
  519. self._parts) or '.'
  520. return self._str
  521. def __fspath__(self):
  522. return str(self)
  523. def as_posix(self):
  524. """Return the string representation of the path with forward (/)
  525. slashes."""
  526. f = self._flavour
  527. return str(self).replace(f.sep, '/')
  528. def __bytes__(self):
  529. """Return the bytes representation of the path. This is only
  530. recommended to use under Unix."""
  531. return os.fsencode(self)
  532. def __repr__(self):
  533. return "{}({!r})".format(self.__class__.__name__, self.as_posix())
  534. def as_uri(self):
  535. """Return the path as a 'file' URI."""
  536. if not self.is_absolute():
  537. raise ValueError("relative path can't be expressed as a file URI")
  538. return self._flavour.make_uri(self)
  539. @property
  540. def _cparts(self):
  541. # Cached casefolded parts, for hashing and comparison
  542. try:
  543. return self._cached_cparts
  544. except AttributeError:
  545. self._cached_cparts = self._flavour.casefold_parts(self._parts)
  546. return self._cached_cparts
  547. def __eq__(self, other):
  548. if not isinstance(other, PurePath):
  549. return NotImplemented
  550. return self._cparts == other._cparts and self._flavour is other._flavour
  551. def __hash__(self):
  552. try:
  553. return self._hash
  554. except AttributeError:
  555. self._hash = hash(tuple(self._cparts))
  556. return self._hash
  557. def __lt__(self, other):
  558. if not isinstance(other, PurePath) or self._flavour is not other._flavour:
  559. return NotImplemented
  560. return self._cparts < other._cparts
  561. def __le__(self, other):
  562. if not isinstance(other, PurePath) or self._flavour is not other._flavour:
  563. return NotImplemented
  564. return self._cparts <= other._cparts
  565. def __gt__(self, other):
  566. if not isinstance(other, PurePath) or self._flavour is not other._flavour:
  567. return NotImplemented
  568. return self._cparts > other._cparts
  569. def __ge__(self, other):
  570. if not isinstance(other, PurePath) or self._flavour is not other._flavour:
  571. return NotImplemented
  572. return self._cparts >= other._cparts
  573. def __class_getitem__(cls, type):
  574. return cls
  575. drive = property(attrgetter('_drv'),
  576. doc="""The drive prefix (letter or UNC path), if any.""")
  577. root = property(attrgetter('_root'),
  578. doc="""The root of the path, if any.""")
  579. @property
  580. def anchor(self):
  581. """The concatenation of the drive and root, or ''."""
  582. anchor = self._drv + self._root
  583. return anchor
  584. @property
  585. def name(self):
  586. """The final path component, if any."""
  587. parts = self._parts
  588. if len(parts) == (1 if (self._drv or self._root) else 0):
  589. return ''
  590. return parts[-1]
  591. @property
  592. def suffix(self):
  593. """
  594. The final component's last suffix, if any.
  595. This includes the leading period. For example: '.txt'
  596. """
  597. name = self.name
  598. i = name.rfind('.')
  599. if 0 < i < len(name) - 1:
  600. return name[i:]
  601. else:
  602. return ''
  603. @property
  604. def suffixes(self):
  605. """
  606. A list of the final component's suffixes, if any.
  607. These include the leading periods. For example: ['.tar', '.gz']
  608. """
  609. name = self.name
  610. if name.endswith('.'):
  611. return []
  612. name = name.lstrip('.')
  613. return ['.' + suffix for suffix in name.split('.')[1:]]
  614. @property
  615. def stem(self):
  616. """The final path component, minus its last suffix."""
  617. name = self.name
  618. i = name.rfind('.')
  619. if 0 < i < len(name) - 1:
  620. return name[:i]
  621. else:
  622. return name
  623. def with_name(self, name):
  624. """Return a new path with the file name changed."""
  625. if not self.name:
  626. raise ValueError("%r has an empty name" % (self,))
  627. drv, root, parts = self._flavour.parse_parts((name,))
  628. if (not name or name[-1] in [self._flavour.sep, self._flavour.altsep]
  629. or drv or root or len(parts) != 1):
  630. raise ValueError("Invalid name %r" % (name))
  631. return self._from_parsed_parts(self._drv, self._root,
  632. self._parts[:-1] + [name])
  633. def with_stem(self, stem):
  634. """Return a new path with the stem changed."""
  635. return self.with_name(stem + self.suffix)
  636. def with_suffix(self, suffix):
  637. """Return a new path with the file suffix changed. If the path
  638. has no suffix, add given suffix. If the given suffix is an empty
  639. string, remove the suffix from the path.
  640. """
  641. f = self._flavour
  642. if f.sep in suffix or f.altsep and f.altsep in suffix:
  643. raise ValueError("Invalid suffix %r" % (suffix,))
  644. if suffix and not suffix.startswith('.') or suffix == '.':
  645. raise ValueError("Invalid suffix %r" % (suffix))
  646. name = self.name
  647. if not name:
  648. raise ValueError("%r has an empty name" % (self,))
  649. old_suffix = self.suffix
  650. if not old_suffix:
  651. name = name + suffix
  652. else:
  653. name = name[:-len(old_suffix)] + suffix
  654. return self._from_parsed_parts(self._drv, self._root,
  655. self._parts[:-1] + [name])
  656. def relative_to(self, *other):
  657. """Return the relative path to another path identified by the passed
  658. arguments. If the operation is not possible (because this is not
  659. a subpath of the other path), raise ValueError.
  660. """
  661. # For the purpose of this method, drive and root are considered
  662. # separate parts, i.e.:
  663. # Path('c:/').relative_to('c:') gives Path('/')
  664. # Path('c:/').relative_to('/') raise ValueError
  665. if not other:
  666. raise TypeError("need at least one argument")
  667. parts = self._parts
  668. drv = self._drv
  669. root = self._root
  670. if root:
  671. abs_parts = [drv, root] + parts[1:]
  672. else:
  673. abs_parts = parts
  674. to_drv, to_root, to_parts = self._parse_args(other)
  675. if to_root:
  676. to_abs_parts = [to_drv, to_root] + to_parts[1:]
  677. else:
  678. to_abs_parts = to_parts
  679. n = len(to_abs_parts)
  680. cf = self._flavour.casefold_parts
  681. if (root or drv) if n == 0 else cf(abs_parts[:n]) != cf(to_abs_parts):
  682. formatted = self._format_parsed_parts(to_drv, to_root, to_parts)
  683. raise ValueError("{!r} is not in the subpath of {!r}"
  684. " OR one path is relative and the other is absolute."
  685. .format(str(self), str(formatted)))
  686. return self._from_parsed_parts('', root if n == 1 else '',
  687. abs_parts[n:])
  688. def is_relative_to(self, *other):
  689. """Return True if the path is relative to another path or False.
  690. """
  691. try:
  692. self.relative_to(*other)
  693. return True
  694. except ValueError:
  695. return False
  696. @property
  697. def parts(self):
  698. """An object providing sequence-like access to the
  699. components in the filesystem path."""
  700. # We cache the tuple to avoid building a new one each time .parts
  701. # is accessed. XXX is this necessary?
  702. try:
  703. return self._pparts
  704. except AttributeError:
  705. self._pparts = tuple(self._parts)
  706. return self._pparts
  707. def joinpath(self, *args):
  708. """Combine this path with one or several arguments, and return a
  709. new path representing either a subpath (if all arguments are relative
  710. paths) or a totally different path (if one of the arguments is
  711. anchored).
  712. """
  713. return self._make_child(args)
  714. def __truediv__(self, key):
  715. try:
  716. return self._make_child((key,))
  717. except TypeError:
  718. return NotImplemented
  719. def __rtruediv__(self, key):
  720. try:
  721. return self._from_parts([key] + self._parts)
  722. except TypeError:
  723. return NotImplemented
  724. @property
  725. def parent(self):
  726. """The logical parent of the path."""
  727. drv = self._drv
  728. root = self._root
  729. parts = self._parts
  730. if len(parts) == 1 and (drv or root):
  731. return self
  732. return self._from_parsed_parts(drv, root, parts[:-1])
  733. @property
  734. def parents(self):
  735. """A sequence of this path's logical parents."""
  736. return _PathParents(self)
  737. def is_absolute(self):
  738. """True if the path is absolute (has both a root and, if applicable,
  739. a drive)."""
  740. if not self._root:
  741. return False
  742. return not self._flavour.has_drv or bool(self._drv)
  743. def is_reserved(self):
  744. """Return True if the path contains one of the special names reserved
  745. by the system, if any."""
  746. return self._flavour.is_reserved(self._parts)
  747. def match(self, path_pattern):
  748. """
  749. Return True if this path matches the given pattern.
  750. """
  751. cf = self._flavour.casefold
  752. path_pattern = cf(path_pattern)
  753. drv, root, pat_parts = self._flavour.parse_parts((path_pattern,))
  754. if not pat_parts:
  755. raise ValueError("empty pattern")
  756. if drv and drv != cf(self._drv):
  757. return False
  758. if root and root != cf(self._root):
  759. return False
  760. parts = self._cparts
  761. if drv or root:
  762. if len(pat_parts) != len(parts):
  763. return False
  764. pat_parts = pat_parts[1:]
  765. elif len(pat_parts) > len(parts):
  766. return False
  767. for part, pat in zip(reversed(parts), reversed(pat_parts)):
  768. if not fnmatch.fnmatchcase(part, pat):
  769. return False
  770. return True
  771. # Can't subclass os.PathLike from PurePath and keep the constructor
  772. # optimizations in PurePath._parse_args().
  773. os.PathLike.register(PurePath)
  774. class PurePosixPath(PurePath):
  775. """PurePath subclass for non-Windows systems.
  776. On a POSIX system, instantiating a PurePath should return this object.
  777. However, you can also instantiate it directly on any system.
  778. """
  779. _flavour = _posix_flavour
  780. __slots__ = ()
  781. class PureWindowsPath(PurePath):
  782. """PurePath subclass for Windows systems.
  783. On a Windows system, instantiating a PurePath should return this object.
  784. However, you can also instantiate it directly on any system.
  785. """
  786. _flavour = _windows_flavour
  787. __slots__ = ()
  788. # Filesystem-accessing classes
  789. class Path(PurePath):
  790. """PurePath subclass that can make system calls.
  791. Path represents a filesystem path but unlike PurePath, also offers
  792. methods to do system calls on path objects. Depending on your system,
  793. instantiating a Path will return either a PosixPath or a WindowsPath
  794. object. You can also instantiate a PosixPath or WindowsPath directly,
  795. but cannot instantiate a WindowsPath on a POSIX system or vice versa.
  796. """
  797. _accessor = _normal_accessor
  798. __slots__ = ()
  799. def __new__(cls, *args, **kwargs):
  800. if cls is Path:
  801. cls = WindowsPath if os.name == 'nt' else PosixPath
  802. self = cls._from_parts(args)
  803. if not self._flavour.is_supported:
  804. raise NotImplementedError("cannot instantiate %r on your system"
  805. % (cls.__name__,))
  806. return self
  807. def _make_child_relpath(self, part):
  808. # This is an optimization used for dir walking. `part` must be
  809. # a single part relative to this path.
  810. parts = self._parts + [part]
  811. return self._from_parsed_parts(self._drv, self._root, parts)
  812. def __enter__(self):
  813. return self
  814. def __exit__(self, t, v, tb):
  815. # https://bugs.python.org/issue39682
  816. # In previous versions of pathlib, this method marked this path as
  817. # closed; subsequent attempts to perform I/O would raise an IOError.
  818. # This functionality was never documented, and had the effect of
  819. # making Path objects mutable, contrary to PEP 428. In Python 3.9 the
  820. # _closed attribute was removed, and this method made a no-op.
  821. # This method and __enter__()/__exit__() should be deprecated and
  822. # removed in the future.
  823. pass
  824. # Public API
  825. @classmethod
  826. def cwd(cls):
  827. """Return a new path pointing to the current working directory
  828. (as returned by os.getcwd()).
  829. """
  830. return cls(cls._accessor.getcwd())
  831. @classmethod
  832. def home(cls):
  833. """Return a new path pointing to the user's home directory (as
  834. returned by os.path.expanduser('~')).
  835. """
  836. return cls("~").expanduser()
  837. def samefile(self, other_path):
  838. """Return whether other_path is the same or not as this file
  839. (as returned by os.path.samefile()).
  840. """
  841. st = self.stat()
  842. try:
  843. other_st = other_path.stat()
  844. except AttributeError:
  845. other_st = self._accessor.stat(other_path)
  846. return os.path.samestat(st, other_st)
  847. def iterdir(self):
  848. """Iterate over the files in this directory. Does not yield any
  849. result for the special paths '.' and '..'.
  850. """
  851. for name in self._accessor.listdir(self):
  852. if name in {'.', '..'}:
  853. # Yielding a path object for these makes little sense
  854. continue
  855. yield self._make_child_relpath(name)
  856. def glob(self, pattern):
  857. """Iterate over this subtree and yield all existing files (of any
  858. kind, including directories) matching the given relative pattern.
  859. """
  860. sys.audit("pathlib.Path.glob", self, pattern)
  861. if not pattern:
  862. raise ValueError("Unacceptable pattern: {!r}".format(pattern))
  863. drv, root, pattern_parts = self._flavour.parse_parts((pattern,))
  864. if drv or root:
  865. raise NotImplementedError("Non-relative patterns are unsupported")
  866. selector = _make_selector(tuple(pattern_parts), self._flavour)
  867. for p in selector.select_from(self):
  868. yield p
  869. def rglob(self, pattern):
  870. """Recursively yield all existing files (of any kind, including
  871. directories) matching the given relative pattern, anywhere in
  872. this subtree.
  873. """
  874. sys.audit("pathlib.Path.rglob", self, pattern)
  875. drv, root, pattern_parts = self._flavour.parse_parts((pattern,))
  876. if drv or root:
  877. raise NotImplementedError("Non-relative patterns are unsupported")
  878. selector = _make_selector(("**",) + tuple(pattern_parts), self._flavour)
  879. for p in selector.select_from(self):
  880. yield p
  881. def absolute(self):
  882. """Return an absolute version of this path. This function works
  883. even if the path doesn't point to anything.
  884. No normalization is done, i.e. all '.' and '..' will be kept along.
  885. Use resolve() to get the canonical path to a file.
  886. """
  887. # XXX untested yet!
  888. if self.is_absolute():
  889. return self
  890. # FIXME this must defer to the specific flavour (and, under Windows,
  891. # use nt._getfullpathname())
  892. return self._from_parts([self._accessor.getcwd()] + self._parts)
  893. def resolve(self, strict=False):
  894. """
  895. Make the path absolute, resolving all symlinks on the way and also
  896. normalizing it (for example turning slashes into backslashes under
  897. Windows).
  898. """
  899. def check_eloop(e):
  900. winerror = getattr(e, 'winerror', 0)
  901. if e.errno == ELOOP or winerror == _WINERROR_CANT_RESOLVE_FILENAME:
  902. raise RuntimeError("Symlink loop from %r" % e.filename)
  903. try:
  904. s = self._accessor.realpath(self, strict=strict)
  905. except OSError as e:
  906. check_eloop(e)
  907. raise
  908. p = self._from_parts((s,))
  909. # In non-strict mode, realpath() doesn't raise on symlink loops.
  910. # Ensure we get an exception by calling stat()
  911. if not strict:
  912. try:
  913. p.stat()
  914. except OSError as e:
  915. check_eloop(e)
  916. return p
  917. def stat(self, *, follow_symlinks=True):
  918. """
  919. Return the result of the stat() system call on this path, like
  920. os.stat() does.
  921. """
  922. return self._accessor.stat(self, follow_symlinks=follow_symlinks)
  923. def owner(self):
  924. """
  925. Return the login name of the file owner.
  926. """
  927. return self._accessor.owner(self)
  928. def group(self):
  929. """
  930. Return the group name of the file gid.
  931. """
  932. return self._accessor.group(self)
  933. def open(self, mode='r', buffering=-1, encoding=None,
  934. errors=None, newline=None):
  935. """
  936. Open the file pointed by this path and return a file object, as
  937. the built-in open() function does.
  938. """
  939. if "b" not in mode:
  940. encoding = io.text_encoding(encoding)
  941. return self._accessor.open(self, mode, buffering, encoding, errors,
  942. newline)
  943. def read_bytes(self):
  944. """
  945. Open the file in bytes mode, read it, and close the file.
  946. """
  947. with self.open(mode='rb') as f:
  948. return f.read()
  949. def read_text(self, encoding=None, errors=None):
  950. """
  951. Open the file in text mode, read it, and close the file.
  952. """
  953. encoding = io.text_encoding(encoding)
  954. with self.open(mode='r', encoding=encoding, errors=errors) as f:
  955. return f.read()
  956. def write_bytes(self, data):
  957. """
  958. Open the file in bytes mode, write to it, and close the file.
  959. """
  960. # type-check for the buffer interface before truncating the file
  961. view = memoryview(data)
  962. with self.open(mode='wb') as f:
  963. return f.write(view)
  964. def write_text(self, data, encoding=None, errors=None, newline=None):
  965. """
  966. Open the file in text mode, write to it, and close the file.
  967. """
  968. if not isinstance(data, str):
  969. raise TypeError('data must be str, not %s' %
  970. data.__class__.__name__)
  971. encoding = io.text_encoding(encoding)
  972. with self.open(mode='w', encoding=encoding, errors=errors, newline=newline) as f:
  973. return f.write(data)
  974. def readlink(self):
  975. """
  976. Return the path to which the symbolic link points.
  977. """
  978. path = self._accessor.readlink(self)
  979. return self._from_parts((path,))
  980. def touch(self, mode=0o666, exist_ok=True):
  981. """
  982. Create this file with the given access mode, if it doesn't exist.
  983. """
  984. self._accessor.touch(self, mode, exist_ok)
  985. def mkdir(self, mode=0o777, parents=False, exist_ok=False):
  986. """
  987. Create a new directory at this given path.
  988. """
  989. try:
  990. self._accessor.mkdir(self, mode)
  991. except FileNotFoundError:
  992. if not parents or self.parent == self:
  993. raise
  994. self.parent.mkdir(parents=True, exist_ok=True)
  995. self.mkdir(mode, parents=False, exist_ok=exist_ok)
  996. except OSError:
  997. # Cannot rely on checking for EEXIST, since the operating system
  998. # could give priority to other errors like EACCES or EROFS
  999. if not exist_ok or not self.is_dir():
  1000. raise
  1001. def chmod(self, mode, *, follow_symlinks=True):
  1002. """
  1003. Change the permissions of the path, like os.chmod().
  1004. """
  1005. self._accessor.chmod(self, mode, follow_symlinks=follow_symlinks)
  1006. def lchmod(self, mode):
  1007. """
  1008. Like chmod(), except if the path points to a symlink, the symlink's
  1009. permissions are changed, rather than its target's.
  1010. """
  1011. self.chmod(mode, follow_symlinks=False)
  1012. def unlink(self, missing_ok=False):
  1013. """
  1014. Remove this file or link.
  1015. If the path is a directory, use rmdir() instead.
  1016. """
  1017. try:
  1018. self._accessor.unlink(self)
  1019. except FileNotFoundError:
  1020. if not missing_ok:
  1021. raise
  1022. def rmdir(self):
  1023. """
  1024. Remove this directory. The directory must be empty.
  1025. """
  1026. self._accessor.rmdir(self)
  1027. def lstat(self):
  1028. """
  1029. Like stat(), except if the path points to a symlink, the symlink's
  1030. status information is returned, rather than its target's.
  1031. """
  1032. return self.stat(follow_symlinks=False)
  1033. def rename(self, target):
  1034. """
  1035. Rename this path to the target path.
  1036. The target path may be absolute or relative. Relative paths are
  1037. interpreted relative to the current working directory, *not* the
  1038. directory of the Path object.
  1039. Returns the new Path instance pointing to the target path.
  1040. """
  1041. self._accessor.rename(self, target)
  1042. return self.__class__(target)
  1043. def replace(self, target):
  1044. """
  1045. Rename this path to the target path, overwriting if that path exists.
  1046. The target path may be absolute or relative. Relative paths are
  1047. interpreted relative to the current working directory, *not* the
  1048. directory of the Path object.
  1049. Returns the new Path instance pointing to the target path.
  1050. """
  1051. self._accessor.replace(self, target)
  1052. return self.__class__(target)
  1053. def symlink_to(self, target, target_is_directory=False):
  1054. """
  1055. Make this path a symlink pointing to the target path.
  1056. Note the order of arguments (link, target) is the reverse of os.symlink.
  1057. """
  1058. self._accessor.symlink(target, self, target_is_directory)
  1059. def hardlink_to(self, target):
  1060. """
  1061. Make this path a hard link pointing to the same file as *target*.
  1062. Note the order of arguments (self, target) is the reverse of os.link's.
  1063. """
  1064. self._accessor.link(target, self)
  1065. def link_to(self, target):
  1066. """
  1067. Make the target path a hard link pointing to this path.
  1068. Note this function does not make this path a hard link to *target*,
  1069. despite the implication of the function and argument names. The order
  1070. of arguments (target, link) is the reverse of Path.symlink_to, but
  1071. matches that of os.link.
  1072. Deprecated since Python 3.10 and scheduled for removal in Python 3.12.
  1073. Use `hardlink_to()` instead.
  1074. """
  1075. warnings.warn("pathlib.Path.link_to() is deprecated and is scheduled "
  1076. "for removal in Python 3.12. "
  1077. "Use pathlib.Path.hardlink_to() instead.",
  1078. DeprecationWarning, stacklevel=2)
  1079. self._accessor.link(self, target)
  1080. # Convenience functions for querying the stat results
  1081. def exists(self):
  1082. """
  1083. Whether this path exists.
  1084. """
  1085. try:
  1086. self.stat()
  1087. except OSError as e:
  1088. if not _ignore_error(e):
  1089. raise
  1090. return False
  1091. except ValueError:
  1092. # Non-encodable path
  1093. return False
  1094. return True
  1095. def is_dir(self):
  1096. """
  1097. Whether this path is a directory.
  1098. """
  1099. try:
  1100. return S_ISDIR(self.stat().st_mode)
  1101. except OSError as e:
  1102. if not _ignore_error(e):
  1103. raise
  1104. # Path doesn't exist or is a broken symlink
  1105. # (see http://web.archive.org/web/20200623061726/https://bitbucket.org/pitrou/pathlib/issues/12/ )
  1106. return False
  1107. except ValueError:
  1108. # Non-encodable path
  1109. return False
  1110. def is_file(self):
  1111. """
  1112. Whether this path is a regular file (also True for symlinks pointing
  1113. to regular files).
  1114. """
  1115. try:
  1116. return S_ISREG(self.stat().st_mode)
  1117. except OSError as e:
  1118. if not _ignore_error(e):
  1119. raise
  1120. # Path doesn't exist or is a broken symlink
  1121. # (see http://web.archive.org/web/20200623061726/https://bitbucket.org/pitrou/pathlib/issues/12/ )
  1122. return False
  1123. except ValueError:
  1124. # Non-encodable path
  1125. return False
  1126. def is_mount(self):
  1127. """
  1128. Check if this path is a POSIX mount point
  1129. """
  1130. # Need to exist and be a dir
  1131. if not self.exists() or not self.is_dir():
  1132. return False
  1133. try:
  1134. parent_dev = self.parent.stat().st_dev
  1135. except OSError:
  1136. return False
  1137. dev = self.stat().st_dev
  1138. if dev != parent_dev:
  1139. return True
  1140. ino = self.stat().st_ino
  1141. parent_ino = self.parent.stat().st_ino
  1142. return ino == parent_ino
  1143. def is_symlink(self):
  1144. """
  1145. Whether this path is a symbolic link.
  1146. """
  1147. try:
  1148. return S_ISLNK(self.lstat().st_mode)
  1149. except OSError as e:
  1150. if not _ignore_error(e):
  1151. raise
  1152. # Path doesn't exist
  1153. return False
  1154. except ValueError:
  1155. # Non-encodable path
  1156. return False
  1157. def is_block_device(self):
  1158. """
  1159. Whether this path is a block device.
  1160. """
  1161. try:
  1162. return S_ISBLK(self.stat().st_mode)
  1163. except OSError as e:
  1164. if not _ignore_error(e):
  1165. raise
  1166. # Path doesn't exist or is a broken symlink
  1167. # (see http://web.archive.org/web/20200623061726/https://bitbucket.org/pitrou/pathlib/issues/12/ )
  1168. return False
  1169. except ValueError:
  1170. # Non-encodable path
  1171. return False
  1172. def is_char_device(self):
  1173. """
  1174. Whether this path is a character device.
  1175. """
  1176. try:
  1177. return S_ISCHR(self.stat().st_mode)
  1178. except OSError as e:
  1179. if not _ignore_error(e):
  1180. raise
  1181. # Path doesn't exist or is a broken symlink
  1182. # (see http://web.archive.org/web/20200623061726/https://bitbucket.org/pitrou/pathlib/issues/12/ )
  1183. return False
  1184. except ValueError:
  1185. # Non-encodable path
  1186. return False
  1187. def is_fifo(self):
  1188. """
  1189. Whether this path is a FIFO.
  1190. """
  1191. try:
  1192. return S_ISFIFO(self.stat().st_mode)
  1193. except OSError as e:
  1194. if not _ignore_error(e):
  1195. raise
  1196. # Path doesn't exist or is a broken symlink
  1197. # (see http://web.archive.org/web/20200623061726/https://bitbucket.org/pitrou/pathlib/issues/12/ )
  1198. return False
  1199. except ValueError:
  1200. # Non-encodable path
  1201. return False
  1202. def is_socket(self):
  1203. """
  1204. Whether this path is a socket.
  1205. """
  1206. try:
  1207. return S_ISSOCK(self.stat().st_mode)
  1208. except OSError as e:
  1209. if not _ignore_error(e):
  1210. raise
  1211. # Path doesn't exist or is a broken symlink
  1212. # (see http://web.archive.org/web/20200623061726/https://bitbucket.org/pitrou/pathlib/issues/12/ )
  1213. return False
  1214. except ValueError:
  1215. # Non-encodable path
  1216. return False
  1217. def expanduser(self):
  1218. """ Return a new path with expanded ~ and ~user constructs
  1219. (as returned by os.path.expanduser)
  1220. """
  1221. if (not (self._drv or self._root) and
  1222. self._parts and self._parts[0][:1] == '~'):
  1223. homedir = self._accessor.expanduser(self._parts[0])
  1224. if homedir[:1] == "~":
  1225. raise RuntimeError("Could not determine home directory.")
  1226. return self._from_parts([homedir] + self._parts[1:])
  1227. return self
  1228. class PosixPath(Path, PurePosixPath):
  1229. """Path subclass for non-Windows systems.
  1230. On a POSIX system, instantiating a Path should return this object.
  1231. """
  1232. __slots__ = ()
  1233. class WindowsPath(Path, PureWindowsPath):
  1234. """Path subclass for Windows systems.
  1235. On a Windows system, instantiating a Path should return this object.
  1236. """
  1237. __slots__ = ()
  1238. def is_mount(self):
  1239. raise NotImplementedError("Path.is_mount() is unsupported on this system")