You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1442 lines
47 KiB

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