pathlib2.py 53 KB

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