path.py 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969
  1. #
  2. # Copyright (c) 2010 Mikhail Gusarov
  3. #
  4. # Permission is hereby granted, free of charge, to any person obtaining a copy
  5. # of this software and associated documentation files (the "Software"), to deal
  6. # in the Software without restriction, including without limitation the rights
  7. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. # copies of the Software, and to permit persons to whom the Software is
  9. # furnished to do so, subject to the following conditions:
  10. #
  11. # The above copyright notice and this permission notice shall be included in
  12. # all copies or substantial portions of the Software.
  13. #
  14. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. # SOFTWARE.
  21. #
  22. """
  23. path.py - An object representing a path to a file or directory.
  24. https://github.com/jaraco/path.py
  25. Example::
  26. from path import Path
  27. d = Path('/home/guido/bin')
  28. # Globbing
  29. for f in d.files('*.py'):
  30. f.chmod(0o755)
  31. # Changing the working directory:
  32. with Path("somewhere"):
  33. # cwd in now `somewhere`
  34. ...
  35. # Concatenate paths with /
  36. foo_txt = Path("bar") / "foo.txt"
  37. """
  38. from __future__ import unicode_literals
  39. import sys
  40. import warnings
  41. import os
  42. import fnmatch
  43. import glob
  44. import shutil
  45. import hashlib
  46. import errno
  47. import tempfile
  48. import functools
  49. import operator
  50. import re
  51. import contextlib
  52. import io
  53. import distutils.dir_util
  54. import importlib
  55. import itertools
  56. try:
  57. import win32security
  58. except ImportError:
  59. pass
  60. try:
  61. import pwd
  62. except ImportError:
  63. pass
  64. try:
  65. import grp
  66. except ImportError:
  67. pass
  68. ##############################################################################
  69. # Python 2/3 support
  70. PY3 = sys.version_info >= (3,)
  71. PY2 = not PY3
  72. string_types = str,
  73. text_type = str
  74. getcwdu = os.getcwd
  75. if PY2:
  76. import __builtin__
  77. string_types = __builtin__.basestring,
  78. text_type = __builtin__.unicode
  79. getcwdu = os.getcwdu
  80. map = itertools.imap
  81. @contextlib.contextmanager
  82. def io_error_compat():
  83. try:
  84. yield
  85. except IOError as io_err:
  86. # On Python 2, io.open raises IOError; transform to OSError for
  87. # future compatibility.
  88. os_err = OSError(*io_err.args)
  89. os_err.filename = getattr(io_err, 'filename', None)
  90. raise os_err
  91. ##############################################################################
  92. __all__ = ['Path', 'TempDir', 'CaseInsensitivePattern']
  93. LINESEPS = ['\r\n', '\r', '\n']
  94. U_LINESEPS = LINESEPS + ['\u0085', '\u2028', '\u2029']
  95. NEWLINE = re.compile('|'.join(LINESEPS))
  96. U_NEWLINE = re.compile('|'.join(U_LINESEPS))
  97. NL_END = re.compile(r'(?:{0})$'.format(NEWLINE.pattern))
  98. U_NL_END = re.compile(r'(?:{0})$'.format(U_NEWLINE.pattern))
  99. try:
  100. import pkg_resources
  101. __version__ = pkg_resources.require('path.py')[0].version
  102. except Exception:
  103. __version__ = 'unknown'
  104. class TreeWalkWarning(Warning):
  105. pass
  106. # from jaraco.functools
  107. def compose(*funcs):
  108. compose_two = lambda f1, f2: lambda *args, **kwargs: f1(f2(*args, **kwargs)) # noqa
  109. return functools.reduce(compose_two, funcs)
  110. def simple_cache(func):
  111. """
  112. Save results for the :meth:'path.using_module' classmethod.
  113. When Python 3.2 is available, use functools.lru_cache instead.
  114. """
  115. saved_results = {}
  116. def wrapper(cls, module):
  117. if module in saved_results:
  118. return saved_results[module]
  119. saved_results[module] = func(cls, module)
  120. return saved_results[module]
  121. return wrapper
  122. class ClassProperty(property):
  123. def __get__(self, cls, owner):
  124. return self.fget.__get__(None, owner)()
  125. class multimethod(object):
  126. """
  127. Acts like a classmethod when invoked from the class and like an
  128. instancemethod when invoked from the instance.
  129. """
  130. def __init__(self, func):
  131. self.func = func
  132. def __get__(self, instance, owner):
  133. return (
  134. functools.partial(self.func, owner) if instance is None
  135. else functools.partial(self.func, owner, instance)
  136. )
  137. class Path(text_type):
  138. """
  139. Represents a filesystem path.
  140. For documentation on individual methods, consult their
  141. counterparts in :mod:`os.path`.
  142. Some methods are additionally included from :mod:`shutil`.
  143. The functions are linked directly into the class namespace
  144. such that they will be bound to the Path instance. For example,
  145. ``Path(src).copy(target)`` is equivalent to
  146. ``shutil.copy(src, target)``. Therefore, when referencing
  147. the docs for these methods, assume `src` references `self`,
  148. the Path instance.
  149. """
  150. module = os.path
  151. """ The path module to use for path operations.
  152. .. seealso:: :mod:`os.path`
  153. """
  154. def __init__(self, other=''):
  155. if other is None:
  156. raise TypeError("Invalid initial value for path: None")
  157. @classmethod
  158. @simple_cache
  159. def using_module(cls, module):
  160. subclass_name = cls.__name__ + '_' + module.__name__
  161. if PY2:
  162. subclass_name = str(subclass_name)
  163. bases = (cls,)
  164. ns = {'module': module}
  165. return type(subclass_name, bases, ns)
  166. @ClassProperty
  167. @classmethod
  168. def _next_class(cls):
  169. """
  170. What class should be used to construct new instances from this class
  171. """
  172. return cls
  173. # --- Special Python methods.
  174. def __repr__(self):
  175. return '%s(%s)' % (type(self).__name__, super(Path, self).__repr__())
  176. # Adding a Path and a string yields a Path.
  177. def __add__(self, more):
  178. try:
  179. return self._next_class(super(Path, self).__add__(more))
  180. except TypeError: # Python bug
  181. return NotImplemented
  182. def __radd__(self, other):
  183. if not isinstance(other, string_types):
  184. return NotImplemented
  185. return self._next_class(other.__add__(self))
  186. # The / operator joins Paths.
  187. def __div__(self, rel):
  188. """ fp.__div__(rel) == fp / rel == fp.joinpath(rel)
  189. Join two path components, adding a separator character if
  190. needed.
  191. .. seealso:: :func:`os.path.join`
  192. """
  193. return self._next_class(self.module.join(self, rel))
  194. # Make the / operator work even when true division is enabled.
  195. __truediv__ = __div__
  196. # The / operator joins Paths the other way around
  197. def __rdiv__(self, rel):
  198. """ fp.__rdiv__(rel) == rel / fp
  199. Join two path components, adding a separator character if
  200. needed.
  201. .. seealso:: :func:`os.path.join`
  202. """
  203. return self._next_class(self.module.join(rel, self))
  204. # Make the / operator work even when true division is enabled.
  205. __rtruediv__ = __rdiv__
  206. def __enter__(self):
  207. self._old_dir = self.getcwd()
  208. os.chdir(self)
  209. return self
  210. def __exit__(self, *_):
  211. os.chdir(self._old_dir)
  212. def __fspath__(self):
  213. return self
  214. @classmethod
  215. def getcwd(cls):
  216. """ Return the current working directory as a path object.
  217. .. seealso:: :func:`os.getcwdu`
  218. """
  219. return cls(getcwdu())
  220. #
  221. # --- Operations on Path strings.
  222. def abspath(self):
  223. """ .. seealso:: :func:`os.path.abspath` """
  224. return self._next_class(self.module.abspath(self))
  225. def normcase(self):
  226. """ .. seealso:: :func:`os.path.normcase` """
  227. return self._next_class(self.module.normcase(self))
  228. def normpath(self):
  229. """ .. seealso:: :func:`os.path.normpath` """
  230. return self._next_class(self.module.normpath(self))
  231. def realpath(self):
  232. """ .. seealso:: :func:`os.path.realpath` """
  233. return self._next_class(self.module.realpath(self))
  234. def expanduser(self):
  235. """ .. seealso:: :func:`os.path.expanduser` """
  236. return self._next_class(self.module.expanduser(self))
  237. def expandvars(self):
  238. """ .. seealso:: :func:`os.path.expandvars` """
  239. return self._next_class(self.module.expandvars(self))
  240. def dirname(self):
  241. """ .. seealso:: :attr:`parent`, :func:`os.path.dirname` """
  242. return self._next_class(self.module.dirname(self))
  243. def basename(self):
  244. """ .. seealso:: :attr:`name`, :func:`os.path.basename` """
  245. return self._next_class(self.module.basename(self))
  246. def expand(self):
  247. """ Clean up a filename by calling :meth:`expandvars()`,
  248. :meth:`expanduser()`, and :meth:`normpath()` on it.
  249. This is commonly everything needed to clean up a filename
  250. read from a configuration file, for example.
  251. """
  252. return self.expandvars().expanduser().normpath()
  253. @property
  254. def stem(self):
  255. """ The same as :meth:`name`, but with one file extension stripped off.
  256. >>> Path('/home/guido/python.tar.gz').stem
  257. 'python.tar'
  258. """
  259. base, ext = self.module.splitext(self.name)
  260. return base
  261. @property
  262. def namebase(self):
  263. warnings.warn("Use .stem instead of .namebase", DeprecationWarning)
  264. return self.stem
  265. @property
  266. def ext(self):
  267. """ The file extension, for example ``'.py'``. """
  268. f, ext = self.module.splitext(self)
  269. return ext
  270. def with_suffix(self, suffix):
  271. """ Return a new path with the file suffix changed (or added, if none)
  272. >>> Path('/home/guido/python.tar.gz').with_suffix(".foo")
  273. Path('/home/guido/python.tar.foo')
  274. >>> Path('python').with_suffix('.zip')
  275. Path('python.zip')
  276. >>> Path('filename.ext').with_suffix('zip')
  277. Traceback (most recent call last):
  278. ...
  279. ValueError: Invalid suffix 'zip'
  280. """
  281. if not suffix.startswith('.'):
  282. raise ValueError("Invalid suffix {suffix!r}".format(**locals()))
  283. return self.stripext() + suffix
  284. @property
  285. def drive(self):
  286. """ The drive specifier, for example ``'C:'``.
  287. This is always empty on systems that don't use drive specifiers.
  288. """
  289. drive, r = self.module.splitdrive(self)
  290. return self._next_class(drive)
  291. parent = property(
  292. dirname, None, None,
  293. """ This path's parent directory, as a new Path object.
  294. For example,
  295. ``Path('/usr/local/lib/libpython.so').parent ==
  296. Path('/usr/local/lib')``
  297. .. seealso:: :meth:`dirname`, :func:`os.path.dirname`
  298. """)
  299. name = property(
  300. basename, None, None,
  301. """ The name of this file or directory without the full path.
  302. For example,
  303. ``Path('/usr/local/lib/libpython.so').name == 'libpython.so'``
  304. .. seealso:: :meth:`basename`, :func:`os.path.basename`
  305. """)
  306. def splitpath(self):
  307. """ p.splitpath() -> Return ``(p.parent, p.name)``.
  308. .. seealso:: :attr:`parent`, :attr:`name`, :func:`os.path.split`
  309. """
  310. parent, child = self.module.split(self)
  311. return self._next_class(parent), child
  312. def splitdrive(self):
  313. """ p.splitdrive() -> Return ``(p.drive, <the rest of p>)``.
  314. Split the drive specifier from this path. If there is
  315. no drive specifier, :samp:`{p.drive}` is empty, so the return value
  316. is simply ``(Path(''), p)``. This is always the case on Unix.
  317. .. seealso:: :func:`os.path.splitdrive`
  318. """
  319. drive, rel = self.module.splitdrive(self)
  320. return self._next_class(drive), rel
  321. def splitext(self):
  322. """ p.splitext() -> Return ``(p.stripext(), p.ext)``.
  323. Split the filename extension from this path and return
  324. the two parts. Either part may be empty.
  325. The extension is everything from ``'.'`` to the end of the
  326. last path segment. This has the property that if
  327. ``(a, b) == p.splitext()``, then ``a + b == p``.
  328. .. seealso:: :func:`os.path.splitext`
  329. """
  330. filename, ext = self.module.splitext(self)
  331. return self._next_class(filename), ext
  332. def stripext(self):
  333. """ p.stripext() -> Remove one file extension from the path.
  334. For example, ``Path('/home/guido/python.tar.gz').stripext()``
  335. returns ``Path('/home/guido/python.tar')``.
  336. """
  337. return self.splitext()[0]
  338. def splitunc(self):
  339. """ .. seealso:: :func:`os.path.splitunc` """
  340. unc, rest = self.module.splitunc(self)
  341. return self._next_class(unc), rest
  342. @property
  343. def uncshare(self):
  344. """
  345. The UNC mount point for this path.
  346. This is empty for paths on local drives.
  347. """
  348. unc, r = self.module.splitunc(self)
  349. return self._next_class(unc)
  350. @multimethod
  351. def joinpath(cls, first, *others):
  352. """
  353. Join first to zero or more :class:`Path` components,
  354. adding a separator character (:samp:`{first}.module.sep`)
  355. if needed. Returns a new instance of
  356. :samp:`{first}._next_class`.
  357. .. seealso:: :func:`os.path.join`
  358. """
  359. if not isinstance(first, cls):
  360. first = cls(first)
  361. return first._next_class(first.module.join(first, *others))
  362. def splitall(self):
  363. r""" Return a list of the path components in this path.
  364. The first item in the list will be a Path. Its value will be
  365. either :data:`os.curdir`, :data:`os.pardir`, empty, or the root
  366. directory of this path (for example, ``'/'`` or ``'C:\\'``). The
  367. other items in the list will be strings.
  368. ``path.Path.joinpath(*result)`` will yield the original path.
  369. """
  370. parts = []
  371. loc = self
  372. while loc != os.curdir and loc != os.pardir:
  373. prev = loc
  374. loc, child = prev.splitpath()
  375. if loc == prev:
  376. break
  377. parts.append(child)
  378. parts.append(loc)
  379. parts.reverse()
  380. return parts
  381. def relpath(self, start='.'):
  382. """ Return this path as a relative path,
  383. based from `start`, which defaults to the current working directory.
  384. """
  385. cwd = self._next_class(start)
  386. return cwd.relpathto(self)
  387. def relpathto(self, dest):
  388. """ Return a relative path from `self` to `dest`.
  389. If there is no relative path from `self` to `dest`, for example if
  390. they reside on different drives in Windows, then this returns
  391. ``dest.abspath()``.
  392. """
  393. origin = self.abspath()
  394. dest = self._next_class(dest).abspath()
  395. orig_list = origin.normcase().splitall()
  396. # Don't normcase dest! We want to preserve the case.
  397. dest_list = dest.splitall()
  398. if orig_list[0] != self.module.normcase(dest_list[0]):
  399. # Can't get here from there.
  400. return dest
  401. # Find the location where the two paths start to differ.
  402. i = 0
  403. for start_seg, dest_seg in zip(orig_list, dest_list):
  404. if start_seg != self.module.normcase(dest_seg):
  405. break
  406. i += 1
  407. # Now i is the point where the two paths diverge.
  408. # Need a certain number of "os.pardir"s to work up
  409. # from the origin to the point of divergence.
  410. segments = [os.pardir] * (len(orig_list) - i)
  411. # Need to add the diverging part of dest_list.
  412. segments += dest_list[i:]
  413. if len(segments) == 0:
  414. # If they happen to be identical, use os.curdir.
  415. relpath = os.curdir
  416. else:
  417. relpath = self.module.join(*segments)
  418. return self._next_class(relpath)
  419. # --- Listing, searching, walking, and matching
  420. def listdir(self, pattern=None):
  421. """ D.listdir() -> List of items in this directory.
  422. Use :meth:`files` or :meth:`dirs` instead if you want a listing
  423. of just files or just subdirectories.
  424. The elements of the list are Path objects.
  425. With the optional `pattern` argument, this only lists
  426. items whose names match the given pattern.
  427. .. seealso:: :meth:`files`, :meth:`dirs`
  428. """
  429. if pattern is None:
  430. pattern = '*'
  431. return [
  432. self / child
  433. for child in os.listdir(self)
  434. if self._next_class(child).fnmatch(pattern)
  435. ]
  436. def dirs(self, pattern=None):
  437. """ D.dirs() -> List of this directory's subdirectories.
  438. The elements of the list are Path objects.
  439. This does not walk recursively into subdirectories
  440. (but see :meth:`walkdirs`).
  441. With the optional `pattern` argument, this only lists
  442. directories whose names match the given pattern. For
  443. example, ``d.dirs('build-*')``.
  444. """
  445. return [p for p in self.listdir(pattern) if p.isdir()]
  446. def files(self, pattern=None):
  447. """ D.files() -> List of the files in this directory.
  448. The elements of the list are Path objects.
  449. This does not walk into subdirectories (see :meth:`walkfiles`).
  450. With the optional `pattern` argument, this only lists files
  451. whose names match the given pattern. For example,
  452. ``d.files('*.pyc')``.
  453. """
  454. return [p for p in self.listdir(pattern) if p.isfile()]
  455. def walk(self, pattern=None, errors='strict'):
  456. """ D.walk() -> iterator over files and subdirs, recursively.
  457. The iterator yields Path objects naming each child item of
  458. this directory and its descendants. This requires that
  459. ``D.isdir()``.
  460. This performs a depth-first traversal of the directory tree.
  461. Each directory is returned just before all its children.
  462. The `errors=` keyword argument controls behavior when an
  463. error occurs. The default is ``'strict'``, which causes an
  464. exception. Other allowed values are ``'warn'`` (which
  465. reports the error via :func:`warnings.warn()`), and ``'ignore'``.
  466. `errors` may also be an arbitrary callable taking a msg parameter.
  467. """
  468. class Handlers:
  469. def strict(msg):
  470. raise
  471. def warn(msg):
  472. warnings.warn(msg, TreeWalkWarning)
  473. def ignore(msg):
  474. pass
  475. if not callable(errors) and errors not in vars(Handlers):
  476. raise ValueError("invalid errors parameter")
  477. errors = vars(Handlers).get(errors, errors)
  478. try:
  479. childList = self.listdir()
  480. except Exception:
  481. exc = sys.exc_info()[1]
  482. tmpl = "Unable to list directory '%(self)s': %(exc)s"
  483. msg = tmpl % locals()
  484. errors(msg)
  485. return
  486. for child in childList:
  487. if pattern is None or child.fnmatch(pattern):
  488. yield child
  489. try:
  490. isdir = child.isdir()
  491. except Exception:
  492. exc = sys.exc_info()[1]
  493. tmpl = "Unable to access '%(child)s': %(exc)s"
  494. msg = tmpl % locals()
  495. errors(msg)
  496. isdir = False
  497. if isdir:
  498. for item in child.walk(pattern, errors):
  499. yield item
  500. def walkdirs(self, pattern=None, errors='strict'):
  501. """ D.walkdirs() -> iterator over subdirs, recursively.
  502. With the optional `pattern` argument, this yields only
  503. directories whose names match the given pattern. For
  504. example, ``mydir.walkdirs('*test')`` yields only directories
  505. with names ending in ``'test'``.
  506. The `errors=` keyword argument controls behavior when an
  507. error occurs. The default is ``'strict'``, which causes an
  508. exception. The other allowed values are ``'warn'`` (which
  509. reports the error via :func:`warnings.warn()`), and ``'ignore'``.
  510. """
  511. if errors not in ('strict', 'warn', 'ignore'):
  512. raise ValueError("invalid errors parameter")
  513. try:
  514. dirs = self.dirs()
  515. except Exception:
  516. if errors == 'ignore':
  517. return
  518. elif errors == 'warn':
  519. warnings.warn(
  520. "Unable to list directory '%s': %s"
  521. % (self, sys.exc_info()[1]),
  522. TreeWalkWarning)
  523. return
  524. else:
  525. raise
  526. for child in dirs:
  527. if pattern is None or child.fnmatch(pattern):
  528. yield child
  529. for subsubdir in child.walkdirs(pattern, errors):
  530. yield subsubdir
  531. def walkfiles(self, pattern=None, errors='strict'):
  532. """ D.walkfiles() -> iterator over files in D, recursively.
  533. The optional argument `pattern` limits the results to files
  534. with names that match the pattern. For example,
  535. ``mydir.walkfiles('*.tmp')`` yields only files with the ``.tmp``
  536. extension.
  537. """
  538. if errors not in ('strict', 'warn', 'ignore'):
  539. raise ValueError("invalid errors parameter")
  540. try:
  541. childList = self.listdir()
  542. except Exception:
  543. if errors == 'ignore':
  544. return
  545. elif errors == 'warn':
  546. warnings.warn(
  547. "Unable to list directory '%s': %s"
  548. % (self, sys.exc_info()[1]),
  549. TreeWalkWarning)
  550. return
  551. else:
  552. raise
  553. for child in childList:
  554. try:
  555. isfile = child.isfile()
  556. isdir = not isfile and child.isdir()
  557. except Exception:
  558. if errors == 'ignore':
  559. continue
  560. elif errors == 'warn':
  561. warnings.warn(
  562. "Unable to access '%s': %s"
  563. % (self, sys.exc_info()[1]),
  564. TreeWalkWarning)
  565. continue
  566. else:
  567. raise
  568. if isfile:
  569. if pattern is None or child.fnmatch(pattern):
  570. yield child
  571. elif isdir:
  572. for f in child.walkfiles(pattern, errors):
  573. yield f
  574. def fnmatch(self, pattern, normcase=None):
  575. """ Return ``True`` if `self.name` matches the given `pattern`.
  576. `pattern` - A filename pattern with wildcards,
  577. for example ``'*.py'``. If the pattern contains a `normcase`
  578. attribute, it is applied to the name and path prior to comparison.
  579. `normcase` - (optional) A function used to normalize the pattern and
  580. filename before matching. Defaults to :meth:`self.module`, which
  581. defaults to :meth:`os.path.normcase`.
  582. .. seealso:: :func:`fnmatch.fnmatch`
  583. """
  584. default_normcase = getattr(pattern, 'normcase', self.module.normcase)
  585. normcase = normcase or default_normcase
  586. name = normcase(self.name)
  587. pattern = normcase(pattern)
  588. return fnmatch.fnmatchcase(name, pattern)
  589. def glob(self, pattern):
  590. """ Return a list of Path objects that match the pattern.
  591. `pattern` - a path relative to this directory, with wildcards.
  592. For example, ``Path('/users').glob('*/bin/*')`` returns a list
  593. of all the files users have in their :file:`bin` directories.
  594. .. seealso:: :func:`glob.glob`
  595. .. note:: Glob is **not** recursive, even when using ``**``.
  596. To do recursive globbing see :func:`walk`,
  597. :func:`walkdirs` or :func:`walkfiles`.
  598. """
  599. cls = self._next_class
  600. return [cls(s) for s in glob.glob(self / pattern)]
  601. def iglob(self, pattern):
  602. """ Return an iterator of Path objects that match the pattern.
  603. `pattern` - a path relative to this directory, with wildcards.
  604. For example, ``Path('/users').iglob('*/bin/*')`` returns an
  605. iterator of all the files users have in their :file:`bin`
  606. directories.
  607. .. seealso:: :func:`glob.iglob`
  608. .. note:: Glob is **not** recursive, even when using ``**``.
  609. To do recursive globbing see :func:`walk`,
  610. :func:`walkdirs` or :func:`walkfiles`.
  611. """
  612. cls = self._next_class
  613. return (cls(s) for s in glob.iglob(self / pattern))
  614. #
  615. # --- Reading or writing an entire file at once.
  616. def open(self, *args, **kwargs):
  617. """ Open this file and return a corresponding :class:`file` object.
  618. Keyword arguments work as in :func:`io.open`. If the file cannot be
  619. opened, an :class:`~exceptions.OSError` is raised.
  620. """
  621. with io_error_compat():
  622. return io.open(self, *args, **kwargs)
  623. def bytes(self):
  624. """ Open this file, read all bytes, return them as a string. """
  625. with self.open('rb') as f:
  626. return f.read()
  627. def chunks(self, size, *args, **kwargs):
  628. """ Returns a generator yielding chunks of the file, so it can
  629. be read piece by piece with a simple for loop.
  630. Any argument you pass after `size` will be passed to :meth:`open`.
  631. :example:
  632. >>> hash = hashlib.md5()
  633. >>> for chunk in Path("path.py").chunks(8192, mode='rb'):
  634. ... hash.update(chunk)
  635. This will read the file by chunks of 8192 bytes.
  636. """
  637. with self.open(*args, **kwargs) as f:
  638. for chunk in iter(lambda: f.read(size) or None, None):
  639. yield chunk
  640. def write_bytes(self, bytes, append=False):
  641. """ Open this file and write the given bytes to it.
  642. Default behavior is to overwrite any existing file.
  643. Call ``p.write_bytes(bytes, append=True)`` to append instead.
  644. """
  645. if append:
  646. mode = 'ab'
  647. else:
  648. mode = 'wb'
  649. with self.open(mode) as f:
  650. f.write(bytes)
  651. def text(self, encoding=None, errors='strict'):
  652. r""" Open this file, read it in, return the content as a string.
  653. All newline sequences are converted to ``'\n'``. Keyword arguments
  654. will be passed to :meth:`open`.
  655. .. seealso:: :meth:`lines`
  656. """
  657. with self.open(mode='r', encoding=encoding, errors=errors) as f:
  658. return U_NEWLINE.sub('\n', f.read())
  659. def write_text(self, text, encoding=None, errors='strict',
  660. linesep=os.linesep, append=False):
  661. r""" Write the given text to this file.
  662. The default behavior is to overwrite any existing file;
  663. to append instead, use the `append=True` keyword argument.
  664. There are two differences between :meth:`write_text` and
  665. :meth:`write_bytes`: newline handling and Unicode handling.
  666. See below.
  667. Parameters:
  668. `text` - str/unicode - The text to be written.
  669. `encoding` - str - The Unicode encoding that will be used.
  670. This is ignored if `text` isn't a Unicode string.
  671. `errors` - str - How to handle Unicode encoding errors.
  672. Default is ``'strict'``. See ``help(unicode.encode)`` for the
  673. options. This is ignored if `text` isn't a Unicode
  674. string.
  675. `linesep` - keyword argument - str/unicode - The sequence of
  676. characters to be used to mark end-of-line. The default is
  677. :data:`os.linesep`. You can also specify ``None`` to
  678. leave all newlines as they are in `text`.
  679. `append` - keyword argument - bool - Specifies what to do if
  680. the file already exists (``True``: append to the end of it;
  681. ``False``: overwrite it.) The default is ``False``.
  682. --- Newline handling.
  683. ``write_text()`` converts all standard end-of-line sequences
  684. (``'\n'``, ``'\r'``, and ``'\r\n'``) to your platform's default
  685. end-of-line sequence (see :data:`os.linesep`; on Windows, for example,
  686. the end-of-line marker is ``'\r\n'``).
  687. If you don't like your platform's default, you can override it
  688. using the `linesep=` keyword argument. If you specifically want
  689. ``write_text()`` to preserve the newlines as-is, use ``linesep=None``.
  690. This applies to Unicode text the same as to 8-bit text, except
  691. there are three additional standard Unicode end-of-line sequences:
  692. ``u'\x85'``, ``u'\r\x85'``, and ``u'\u2028'``.
  693. (This is slightly different from when you open a file for
  694. writing with ``fopen(filename, "w")`` in C or ``open(filename, 'w')``
  695. in Python.)
  696. --- Unicode
  697. If `text` isn't Unicode, then apart from newline handling, the
  698. bytes are written verbatim to the file. The `encoding` and
  699. `errors` arguments are not used and must be omitted.
  700. If `text` is Unicode, it is first converted to :func:`bytes` using the
  701. specified `encoding` (or the default encoding if `encoding`
  702. isn't specified). The `errors` argument applies only to this
  703. conversion.
  704. """
  705. if isinstance(text, text_type):
  706. if linesep is not None:
  707. text = U_NEWLINE.sub(linesep, text)
  708. text = text.encode(encoding or sys.getdefaultencoding(), errors)
  709. else:
  710. assert encoding is None
  711. text = NEWLINE.sub(linesep, text)
  712. self.write_bytes(text, append=append)
  713. def lines(self, encoding=None, errors='strict', retain=True):
  714. r""" Open this file, read all lines, return them in a list.
  715. Optional arguments:
  716. `encoding` - The Unicode encoding (or character set) of
  717. the file. The default is ``None``, meaning the content
  718. of the file is read as 8-bit characters and returned
  719. as a list of (non-Unicode) str objects.
  720. `errors` - How to handle Unicode errors; see help(str.decode)
  721. for the options. Default is ``'strict'``.
  722. `retain` - If ``True``, retain newline characters; but all newline
  723. character combinations (``'\r'``, ``'\n'``, ``'\r\n'``) are
  724. translated to ``'\n'``. If ``False``, newline characters are
  725. stripped off. Default is ``True``.
  726. This uses ``'U'`` mode.
  727. .. seealso:: :meth:`text`
  728. """
  729. if encoding is None and retain:
  730. with self.open('U') as f:
  731. return f.readlines()
  732. else:
  733. return self.text(encoding, errors).splitlines(retain)
  734. def write_lines(self, lines, encoding=None, errors='strict',
  735. linesep=os.linesep, append=False):
  736. r""" Write the given lines of text to this file.
  737. By default this overwrites any existing file at this path.
  738. This puts a platform-specific newline sequence on every line.
  739. See `linesep` below.
  740. `lines` - A list of strings.
  741. `encoding` - A Unicode encoding to use. This applies only if
  742. `lines` contains any Unicode strings.
  743. `errors` - How to handle errors in Unicode encoding. This
  744. also applies only to Unicode strings.
  745. linesep - The desired line-ending. This line-ending is
  746. applied to every line. If a line already has any
  747. standard line ending (``'\r'``, ``'\n'``, ``'\r\n'``,
  748. ``u'\x85'``, ``u'\r\x85'``, ``u'\u2028'``), that will
  749. be stripped off and this will be used instead. The
  750. default is os.linesep, which is platform-dependent
  751. (``'\r\n'`` on Windows, ``'\n'`` on Unix, etc.).
  752. Specify ``None`` to write the lines as-is, like
  753. :meth:`file.writelines`.
  754. Use the keyword argument ``append=True`` to append lines to the
  755. file. The default is to overwrite the file.
  756. .. warning ::
  757. When you use this with Unicode data, if the encoding of the
  758. existing data in the file is different from the encoding
  759. you specify with the `encoding=` parameter, the result is
  760. mixed-encoding data, which can really confuse someone trying
  761. to read the file later.
  762. """
  763. with self.open('ab' if append else 'wb') as f:
  764. for line in lines:
  765. isUnicode = isinstance(line, text_type)
  766. if linesep is not None:
  767. pattern = U_NL_END if isUnicode else NL_END
  768. line = pattern.sub('', line) + linesep
  769. if isUnicode:
  770. line = line.encode(
  771. encoding or sys.getdefaultencoding(), errors)
  772. f.write(line)
  773. def read_md5(self):
  774. """ Calculate the md5 hash for this file.
  775. This reads through the entire file.
  776. .. seealso:: :meth:`read_hash`
  777. """
  778. return self.read_hash('md5')
  779. def _hash(self, hash_name):
  780. """ Returns a hash object for the file at the current path.
  781. `hash_name` should be a hash algo name (such as ``'md5'``
  782. or ``'sha1'``) that's available in the :mod:`hashlib` module.
  783. """
  784. m = hashlib.new(hash_name)
  785. for chunk in self.chunks(8192, mode="rb"):
  786. m.update(chunk)
  787. return m
  788. def read_hash(self, hash_name):
  789. """ Calculate given hash for this file.
  790. List of supported hashes can be obtained from :mod:`hashlib` package.
  791. This reads the entire file.
  792. .. seealso:: :meth:`hashlib.hash.digest`
  793. """
  794. return self._hash(hash_name).digest()
  795. def read_hexhash(self, hash_name):
  796. """ Calculate given hash for this file, returning hexdigest.
  797. List of supported hashes can be obtained from :mod:`hashlib` package.
  798. This reads the entire file.
  799. .. seealso:: :meth:`hashlib.hash.hexdigest`
  800. """
  801. return self._hash(hash_name).hexdigest()
  802. # --- Methods for querying the filesystem.
  803. # N.B. On some platforms, the os.path functions may be implemented in C
  804. # (e.g. isdir on Windows, Python 3.2.2), and compiled functions don't get
  805. # bound. Playing it safe and wrapping them all in method calls.
  806. def isabs(self):
  807. """ .. seealso:: :func:`os.path.isabs` """
  808. return self.module.isabs(self)
  809. def exists(self):
  810. """ .. seealso:: :func:`os.path.exists` """
  811. return self.module.exists(self)
  812. def isdir(self):
  813. """ .. seealso:: :func:`os.path.isdir` """
  814. return self.module.isdir(self)
  815. def isfile(self):
  816. """ .. seealso:: :func:`os.path.isfile` """
  817. return self.module.isfile(self)
  818. def islink(self):
  819. """ .. seealso:: :func:`os.path.islink` """
  820. return self.module.islink(self)
  821. def ismount(self):
  822. """ .. seealso:: :func:`os.path.ismount` """
  823. return self.module.ismount(self)
  824. def samefile(self, other):
  825. """ .. seealso:: :func:`os.path.samefile` """
  826. if not hasattr(self.module, 'samefile'):
  827. other = Path(other).realpath().normpath().normcase()
  828. return self.realpath().normpath().normcase() == other
  829. return self.module.samefile(self, other)
  830. def getatime(self):
  831. """ .. seealso:: :attr:`atime`, :func:`os.path.getatime` """
  832. return self.module.getatime(self)
  833. atime = property(
  834. getatime, None, None,
  835. """ Last access time of the file.
  836. .. seealso:: :meth:`getatime`, :func:`os.path.getatime`
  837. """)
  838. def getmtime(self):
  839. """ .. seealso:: :attr:`mtime`, :func:`os.path.getmtime` """
  840. return self.module.getmtime(self)
  841. mtime = property(
  842. getmtime, None, None,
  843. """ Last-modified time of the file.
  844. .. seealso:: :meth:`getmtime`, :func:`os.path.getmtime`
  845. """)
  846. def getctime(self):
  847. """ .. seealso:: :attr:`ctime`, :func:`os.path.getctime` """
  848. return self.module.getctime(self)
  849. ctime = property(
  850. getctime, None, None,
  851. """ Creation time of the file.
  852. .. seealso:: :meth:`getctime`, :func:`os.path.getctime`
  853. """)
  854. def getsize(self):
  855. """ .. seealso:: :attr:`size`, :func:`os.path.getsize` """
  856. return self.module.getsize(self)
  857. size = property(
  858. getsize, None, None,
  859. """ Size of the file, in bytes.
  860. .. seealso:: :meth:`getsize`, :func:`os.path.getsize`
  861. """)
  862. if hasattr(os, 'access'):
  863. def access(self, mode):
  864. """ Return ``True`` if current user has access to this path.
  865. mode - One of the constants :data:`os.F_OK`, :data:`os.R_OK`,
  866. :data:`os.W_OK`, :data:`os.X_OK`
  867. .. seealso:: :func:`os.access`
  868. """
  869. return os.access(self, mode)
  870. def stat(self):
  871. """ Perform a ``stat()`` system call on this path.
  872. .. seealso:: :meth:`lstat`, :func:`os.stat`
  873. """
  874. return os.stat(self)
  875. def lstat(self):
  876. """ Like :meth:`stat`, but do not follow symbolic links.
  877. .. seealso:: :meth:`stat`, :func:`os.lstat`
  878. """
  879. return os.lstat(self)
  880. def __get_owner_windows(self):
  881. """
  882. Return the name of the owner of this file or directory. Follow
  883. symbolic links.
  884. Return a name of the form ``r'DOMAIN\\User Name'``; may be a group.
  885. .. seealso:: :attr:`owner`
  886. """
  887. desc = win32security.GetFileSecurity(
  888. self, win32security.OWNER_SECURITY_INFORMATION)
  889. sid = desc.GetSecurityDescriptorOwner()
  890. account, domain, typecode = win32security.LookupAccountSid(None, sid)
  891. return domain + '\\' + account
  892. def __get_owner_unix(self):
  893. """
  894. Return the name of the owner of this file or directory. Follow
  895. symbolic links.
  896. .. seealso:: :attr:`owner`
  897. """
  898. st = self.stat()
  899. return pwd.getpwuid(st.st_uid).pw_name
  900. def __get_owner_not_implemented(self):
  901. raise NotImplementedError("Ownership not available on this platform.")
  902. if 'win32security' in globals():
  903. get_owner = __get_owner_windows
  904. elif 'pwd' in globals():
  905. get_owner = __get_owner_unix
  906. else:
  907. get_owner = __get_owner_not_implemented
  908. owner = property(
  909. get_owner, None, None,
  910. """ Name of the owner of this file or directory.
  911. .. seealso:: :meth:`get_owner`""")
  912. if hasattr(os, 'statvfs'):
  913. def statvfs(self):
  914. """ Perform a ``statvfs()`` system call on this path.
  915. .. seealso:: :func:`os.statvfs`
  916. """
  917. return os.statvfs(self)
  918. if hasattr(os, 'pathconf'):
  919. def pathconf(self, name):
  920. """ .. seealso:: :func:`os.pathconf` """
  921. return os.pathconf(self, name)
  922. #
  923. # --- Modifying operations on files and directories
  924. def utime(self, times):
  925. """ Set the access and modified times of this file.
  926. .. seealso:: :func:`os.utime`
  927. """
  928. os.utime(self, times)
  929. return self
  930. def chmod(self, mode):
  931. """
  932. Set the mode. May be the new mode (os.chmod behavior) or a `symbolic
  933. mode <http://en.wikipedia.org/wiki/Chmod#Symbolic_modes>`_.
  934. .. seealso:: :func:`os.chmod`
  935. """
  936. if isinstance(mode, string_types):
  937. mask = _multi_permission_mask(mode)
  938. mode = mask(self.stat().st_mode)
  939. os.chmod(self, mode)
  940. return self
  941. def chown(self, uid=-1, gid=-1):
  942. """
  943. Change the owner and group by names rather than the uid or gid numbers.
  944. .. seealso:: :func:`os.chown`
  945. """
  946. if hasattr(os, 'chown'):
  947. if 'pwd' in globals() and isinstance(uid, string_types):
  948. uid = pwd.getpwnam(uid).pw_uid
  949. if 'grp' in globals() and isinstance(gid, string_types):
  950. gid = grp.getgrnam(gid).gr_gid
  951. os.chown(self, uid, gid)
  952. else:
  953. msg = "Ownership not available on this platform."
  954. raise NotImplementedError(msg)
  955. return self
  956. def rename(self, new):
  957. """ .. seealso:: :func:`os.rename` """
  958. os.rename(self, new)
  959. return self._next_class(new)
  960. def renames(self, new):
  961. """ .. seealso:: :func:`os.renames` """
  962. os.renames(self, new)
  963. return self._next_class(new)
  964. #
  965. # --- Create/delete operations on directories
  966. def mkdir(self, mode=0o777):
  967. """ .. seealso:: :func:`os.mkdir` """
  968. os.mkdir(self, mode)
  969. return self
  970. def mkdir_p(self, mode=0o777):
  971. """ Like :meth:`mkdir`, but does not raise an exception if the
  972. directory already exists. """
  973. try:
  974. self.mkdir(mode)
  975. except OSError:
  976. _, e, _ = sys.exc_info()
  977. if e.errno != errno.EEXIST:
  978. raise
  979. return self
  980. def makedirs(self, mode=0o777):
  981. """ .. seealso:: :func:`os.makedirs` """
  982. os.makedirs(self, mode)
  983. return self
  984. def makedirs_p(self, mode=0o777):
  985. """ Like :meth:`makedirs`, but does not raise an exception if the
  986. directory already exists. """
  987. try:
  988. self.makedirs(mode)
  989. except OSError:
  990. _, e, _ = sys.exc_info()
  991. if e.errno != errno.EEXIST:
  992. raise
  993. return self
  994. def rmdir(self):
  995. """ .. seealso:: :func:`os.rmdir` """
  996. os.rmdir(self)
  997. return self
  998. def rmdir_p(self):
  999. """ Like :meth:`rmdir`, but does not raise an exception if the
  1000. directory is not empty or does not exist. """
  1001. try:
  1002. self.rmdir()
  1003. except OSError:
  1004. _, e, _ = sys.exc_info()
  1005. bypass_codes = errno.ENOTEMPTY, errno.EEXIST, errno.ENOENT
  1006. if e.errno not in bypass_codes:
  1007. raise
  1008. return self
  1009. def removedirs(self):
  1010. """ .. seealso:: :func:`os.removedirs` """
  1011. os.removedirs(self)
  1012. return self
  1013. def removedirs_p(self):
  1014. """ Like :meth:`removedirs`, but does not raise an exception if the
  1015. directory is not empty or does not exist. """
  1016. try:
  1017. self.removedirs()
  1018. except OSError:
  1019. _, e, _ = sys.exc_info()
  1020. if e.errno != errno.ENOTEMPTY and e.errno != errno.EEXIST:
  1021. raise
  1022. return self
  1023. # --- Modifying operations on files
  1024. def touch(self):
  1025. """ Set the access/modified times of this file to the current time.
  1026. Create the file if it does not exist.
  1027. """
  1028. fd = os.open(self, os.O_WRONLY | os.O_CREAT, 0o666)
  1029. os.close(fd)
  1030. os.utime(self, None)
  1031. return self
  1032. def remove(self):
  1033. """ .. seealso:: :func:`os.remove` """
  1034. os.remove(self)
  1035. return self
  1036. def remove_p(self):
  1037. """ Like :meth:`remove`, but does not raise an exception if the
  1038. file does not exist. """
  1039. try:
  1040. self.unlink()
  1041. except OSError:
  1042. _, e, _ = sys.exc_info()
  1043. if e.errno != errno.ENOENT:
  1044. raise
  1045. return self
  1046. def unlink(self):
  1047. """ .. seealso:: :func:`os.unlink` """
  1048. os.unlink(self)
  1049. return self
  1050. def unlink_p(self):
  1051. """ Like :meth:`unlink`, but does not raise an exception if the
  1052. file does not exist. """
  1053. self.remove_p()
  1054. return self
  1055. # --- Links
  1056. if hasattr(os, 'link'):
  1057. def link(self, newpath):
  1058. """ Create a hard link at `newpath`, pointing to this file.
  1059. .. seealso:: :func:`os.link`
  1060. """
  1061. os.link(self, newpath)
  1062. return self._next_class(newpath)
  1063. if hasattr(os, 'symlink'):
  1064. def symlink(self, newlink=None):
  1065. """ Create a symbolic link at `newlink`, pointing here.
  1066. If newlink is not supplied, the symbolic link will assume
  1067. the name self.basename(), creating the link in the cwd.
  1068. .. seealso:: :func:`os.symlink`
  1069. """
  1070. if newlink is None:
  1071. newlink = self.basename()
  1072. os.symlink(self, newlink)
  1073. return self._next_class(newlink)
  1074. if hasattr(os, 'readlink'):
  1075. def readlink(self):
  1076. """ Return the path to which this symbolic link points.
  1077. The result may be an absolute or a relative path.
  1078. .. seealso:: :meth:`readlinkabs`, :func:`os.readlink`
  1079. """
  1080. return self._next_class(os.readlink(self))
  1081. def readlinkabs(self):
  1082. """ Return the path to which this symbolic link points.
  1083. The result is always an absolute path.
  1084. .. seealso:: :meth:`readlink`, :func:`os.readlink`
  1085. """
  1086. p = self.readlink()
  1087. if p.isabs():
  1088. return p
  1089. else:
  1090. return (self.parent / p).abspath()
  1091. # High-level functions from shutil
  1092. # These functions will be bound to the instance such that
  1093. # Path(name).copy(target) will invoke shutil.copy(name, target)
  1094. copyfile = shutil.copyfile
  1095. copymode = shutil.copymode
  1096. copystat = shutil.copystat
  1097. copy = shutil.copy
  1098. copy2 = shutil.copy2
  1099. copytree = shutil.copytree
  1100. if hasattr(shutil, 'move'):
  1101. move = shutil.move
  1102. rmtree = shutil.rmtree
  1103. def rmtree_p(self):
  1104. """ Like :meth:`rmtree`, but does not raise an exception if the
  1105. directory does not exist. """
  1106. try:
  1107. self.rmtree()
  1108. except OSError:
  1109. _, e, _ = sys.exc_info()
  1110. if e.errno != errno.ENOENT:
  1111. raise
  1112. return self
  1113. def chdir(self):
  1114. """ .. seealso:: :func:`os.chdir` """
  1115. os.chdir(self)
  1116. cd = chdir
  1117. def merge_tree(self, dst, symlinks=False, *args, **kwargs):
  1118. """
  1119. Copy entire contents of self to dst, overwriting existing
  1120. contents in dst with those in self.
  1121. If the additional keyword `update` is True, each
  1122. `src` will only be copied if `dst` does not exist,
  1123. or `src` is newer than `dst`.
  1124. Note that the technique employed stages the files in a temporary
  1125. directory first, so this function is not suitable for merging
  1126. trees with large files, especially if the temporary directory
  1127. is not capable of storing a copy of the entire source tree.
  1128. """
  1129. update = kwargs.pop('update', False)
  1130. with TempDir() as _temp_dir:
  1131. # first copy the tree to a stage directory to support
  1132. # the parameters and behavior of copytree.
  1133. stage = _temp_dir / str(hash(self))
  1134. self.copytree(stage, symlinks, *args, **kwargs)
  1135. # now copy everything from the stage directory using
  1136. # the semantics of dir_util.copy_tree
  1137. distutils.dir_util.copy_tree(
  1138. stage,
  1139. dst,
  1140. preserve_symlinks=symlinks,
  1141. update=update,
  1142. )
  1143. #
  1144. # --- Special stuff from os
  1145. if hasattr(os, 'chroot'):
  1146. def chroot(self):
  1147. """ .. seealso:: :func:`os.chroot` """
  1148. os.chroot(self)
  1149. if hasattr(os, 'startfile'):
  1150. def startfile(self):
  1151. """ .. seealso:: :func:`os.startfile` """
  1152. os.startfile(self)
  1153. return self
  1154. # in-place re-writing, courtesy of Martijn Pieters
  1155. # http://www.zopatista.com/python/2013/11/26/inplace-file-rewriting/
  1156. @contextlib.contextmanager
  1157. def in_place(
  1158. self, mode='r', buffering=-1, encoding=None, errors=None,
  1159. newline=None, backup_extension=None,
  1160. ):
  1161. """
  1162. A context in which a file may be re-written in-place with
  1163. new content.
  1164. Yields a tuple of :samp:`({readable}, {writable})` file
  1165. objects, where `writable` replaces `readable`.
  1166. If an exception occurs, the old file is restored, removing the
  1167. written data.
  1168. Mode *must not* use ``'w'``, ``'a'``, or ``'+'``; only
  1169. read-only-modes are allowed. A :exc:`ValueError` is raised
  1170. on invalid modes.
  1171. For example, to add line numbers to a file::
  1172. p = Path(filename)
  1173. assert p.isfile()
  1174. with p.in_place() as (reader, writer):
  1175. for number, line in enumerate(reader, 1):
  1176. writer.write('{0:3}: '.format(number)))
  1177. writer.write(line)
  1178. Thereafter, the file at `filename` will have line numbers in it.
  1179. """
  1180. import io
  1181. if set(mode).intersection('wa+'):
  1182. raise ValueError('Only read-only file modes can be used')
  1183. # move existing file to backup, create new file with same permissions
  1184. # borrowed extensively from the fileinput module
  1185. backup_fn = self + (backup_extension or os.extsep + 'bak')
  1186. try:
  1187. os.unlink(backup_fn)
  1188. except os.error:
  1189. pass
  1190. os.rename(self, backup_fn)
  1191. readable = io.open(
  1192. backup_fn, mode, buffering=buffering,
  1193. encoding=encoding, errors=errors, newline=newline,
  1194. )
  1195. try:
  1196. perm = os.fstat(readable.fileno()).st_mode
  1197. except OSError:
  1198. writable = open(
  1199. self, 'w' + mode.replace('r', ''),
  1200. buffering=buffering, encoding=encoding, errors=errors,
  1201. newline=newline,
  1202. )
  1203. else:
  1204. os_mode = os.O_CREAT | os.O_WRONLY | os.O_TRUNC
  1205. if hasattr(os, 'O_BINARY'):
  1206. os_mode |= os.O_BINARY
  1207. fd = os.open(self, os_mode, perm)
  1208. writable = io.open(
  1209. fd, "w" + mode.replace('r', ''),
  1210. buffering=buffering, encoding=encoding, errors=errors,
  1211. newline=newline,
  1212. )
  1213. try:
  1214. if hasattr(os, 'chmod'):
  1215. os.chmod(self, perm)
  1216. except OSError:
  1217. pass
  1218. try:
  1219. yield readable, writable
  1220. except Exception:
  1221. # move backup back
  1222. readable.close()
  1223. writable.close()
  1224. try:
  1225. os.unlink(self)
  1226. except os.error:
  1227. pass
  1228. os.rename(backup_fn, self)
  1229. raise
  1230. else:
  1231. readable.close()
  1232. writable.close()
  1233. finally:
  1234. try:
  1235. os.unlink(backup_fn)
  1236. except os.error:
  1237. pass
  1238. @ClassProperty
  1239. @classmethod
  1240. def special(cls):
  1241. """
  1242. Return a SpecialResolver object suitable referencing a suitable
  1243. directory for the relevant platform for the given
  1244. type of content.
  1245. For example, to get a user config directory, invoke:
  1246. dir = Path.special().user.config
  1247. Uses the `appdirs
  1248. <https://pypi.python.org/pypi/appdirs/1.4.0>`_ to resolve
  1249. the paths in a platform-friendly way.
  1250. To create a config directory for 'My App', consider:
  1251. dir = Path.special("My App").user.config.makedirs_p()
  1252. If the ``appdirs`` module is not installed, invocation
  1253. of special will raise an ImportError.
  1254. """
  1255. return functools.partial(SpecialResolver, cls)
  1256. class SpecialResolver(object):
  1257. class ResolverScope:
  1258. def __init__(self, paths, scope):
  1259. self.paths = paths
  1260. self.scope = scope
  1261. def __getattr__(self, class_):
  1262. return self.paths.get_dir(self.scope, class_)
  1263. def __init__(self, path_class, *args, **kwargs):
  1264. appdirs = importlib.import_module('appdirs')
  1265. # let appname default to None until
  1266. # https://github.com/ActiveState/appdirs/issues/55 is solved.
  1267. not args and kwargs.setdefault('appname', None)
  1268. vars(self).update(
  1269. path_class=path_class,
  1270. wrapper=appdirs.AppDirs(*args, **kwargs),
  1271. )
  1272. def __getattr__(self, scope):
  1273. return self.ResolverScope(self, scope)
  1274. def get_dir(self, scope, class_):
  1275. """
  1276. Return the callable function from appdirs, but with the
  1277. result wrapped in self.path_class
  1278. """
  1279. prop_name = '{scope}_{class_}_dir'.format(**locals())
  1280. value = getattr(self.wrapper, prop_name)
  1281. MultiPath = Multi.for_class(self.path_class)
  1282. return MultiPath.detect(value)
  1283. class Multi:
  1284. """
  1285. A mix-in for a Path which may contain multiple Path separated by pathsep.
  1286. """
  1287. @classmethod
  1288. def for_class(cls, path_cls):
  1289. name = 'Multi' + path_cls.__name__
  1290. if PY2:
  1291. name = str(name)
  1292. return type(name, (cls, path_cls), {})
  1293. @classmethod
  1294. def detect(cls, input):
  1295. if os.pathsep not in input:
  1296. cls = cls._next_class
  1297. return cls(input)
  1298. def __iter__(self):
  1299. return iter(map(self._next_class, self.split(os.pathsep)))
  1300. @ClassProperty
  1301. @classmethod
  1302. def _next_class(cls):
  1303. """
  1304. Multi-subclasses should use the parent class
  1305. """
  1306. return next(
  1307. class_
  1308. for class_ in cls.__mro__
  1309. if not issubclass(class_, Multi)
  1310. )
  1311. class TempDir(Path):
  1312. """
  1313. A temporary directory via :func:`tempfile.mkdtemp`, and
  1314. constructed with the same parameters that you can use
  1315. as a context manager.
  1316. Example::
  1317. with TempDir() as d:
  1318. # do stuff with the Path object "d"
  1319. # here the directory is deleted automatically
  1320. .. seealso:: :func:`tempfile.mkdtemp`
  1321. """
  1322. @ClassProperty
  1323. @classmethod
  1324. def _next_class(cls):
  1325. return Path
  1326. def __new__(cls, *args, **kwargs):
  1327. dirname = tempfile.mkdtemp(*args, **kwargs)
  1328. return super(TempDir, cls).__new__(cls, dirname)
  1329. def __init__(self, *args, **kwargs):
  1330. pass
  1331. def __enter__(self):
  1332. # TempDir should return a Path version of itself and not itself
  1333. # so that a second context manager does not create a second
  1334. # temporary directory, but rather changes CWD to the location
  1335. # of the temporary directory.
  1336. return self._next_class(self)
  1337. def __exit__(self, exc_type, exc_value, traceback):
  1338. if not exc_value:
  1339. self.rmtree()
  1340. # For backwards compatibility.
  1341. tempdir = TempDir
  1342. def _multi_permission_mask(mode):
  1343. """
  1344. Support multiple, comma-separated Unix chmod symbolic modes.
  1345. >>> _multi_permission_mask('a=r,u+w')(0) == 0o644
  1346. True
  1347. """
  1348. def compose(f, g):
  1349. return lambda *args, **kwargs: g(f(*args, **kwargs))
  1350. return functools.reduce(compose, map(_permission_mask, mode.split(',')))
  1351. def _permission_mask(mode):
  1352. """
  1353. Convert a Unix chmod symbolic mode like ``'ugo+rwx'`` to a function
  1354. suitable for applying to a mask to affect that change.
  1355. >>> mask = _permission_mask('ugo+rwx')
  1356. >>> mask(0o554) == 0o777
  1357. True
  1358. >>> _permission_mask('go-x')(0o777) == 0o766
  1359. True
  1360. >>> _permission_mask('o-x')(0o445) == 0o444
  1361. True
  1362. >>> _permission_mask('a+x')(0) == 0o111
  1363. True
  1364. >>> _permission_mask('a=rw')(0o057) == 0o666
  1365. True
  1366. >>> _permission_mask('u=x')(0o666) == 0o166
  1367. True
  1368. >>> _permission_mask('g=')(0o157) == 0o107
  1369. True
  1370. """
  1371. # parse the symbolic mode
  1372. parsed = re.match('(?P<who>[ugoa]+)(?P<op>[-+=])(?P<what>[rwx]*)$', mode)
  1373. if not parsed:
  1374. raise ValueError("Unrecognized symbolic mode", mode)
  1375. # generate a mask representing the specified permission
  1376. spec_map = dict(r=4, w=2, x=1)
  1377. specs = (spec_map[perm] for perm in parsed.group('what'))
  1378. spec = functools.reduce(operator.or_, specs, 0)
  1379. # now apply spec to each subject in who
  1380. shift_map = dict(u=6, g=3, o=0)
  1381. who = parsed.group('who').replace('a', 'ugo')
  1382. masks = (spec << shift_map[subj] for subj in who)
  1383. mask = functools.reduce(operator.or_, masks)
  1384. op = parsed.group('op')
  1385. # if op is -, invert the mask
  1386. if op == '-':
  1387. mask ^= 0o777
  1388. # if op is =, retain extant values for unreferenced subjects
  1389. if op == '=':
  1390. masks = (0o7 << shift_map[subj] for subj in who)
  1391. retain = functools.reduce(operator.or_, masks) ^ 0o777
  1392. op_map = {
  1393. '+': operator.or_,
  1394. '-': operator.and_,
  1395. '=': lambda mask, target: target & retain ^ mask,
  1396. }
  1397. return functools.partial(op_map[op], mask)
  1398. class CaseInsensitivePattern(text_type):
  1399. """
  1400. A string with a ``'normcase'`` property, suitable for passing to
  1401. :meth:`listdir`, :meth:`dirs`, :meth:`files`, :meth:`walk`,
  1402. :meth:`walkdirs`, or :meth:`walkfiles` to match case-insensitive.
  1403. For example, to get all files ending in .py, .Py, .pY, or .PY in the
  1404. current directory::
  1405. from path import Path, CaseInsensitivePattern as ci
  1406. Path('.').files(ci('*.py'))
  1407. """
  1408. @property
  1409. def normcase(self):
  1410. return __import__('ntpath').normcase
  1411. class FastPath(Path):
  1412. """
  1413. Performance optimized version of Path for use
  1414. on embedded platforms and other systems with limited
  1415. CPU. See #115 and #116 for background.
  1416. """
  1417. def listdir(self, pattern=None):
  1418. children = os.listdir(self)
  1419. if pattern is None:
  1420. return [self / child for child in children]
  1421. pattern, normcase = self.__prepare(pattern)
  1422. return [
  1423. self / child
  1424. for child in children
  1425. if self._next_class(child).__fnmatch(pattern, normcase)
  1426. ]
  1427. def walk(self, pattern=None, errors='strict'):
  1428. class Handlers:
  1429. def strict(msg):
  1430. raise
  1431. def warn(msg):
  1432. warnings.warn(msg, TreeWalkWarning)
  1433. def ignore(msg):
  1434. pass
  1435. if not callable(errors) and errors not in vars(Handlers):
  1436. raise ValueError("invalid errors parameter")
  1437. errors = vars(Handlers).get(errors, errors)
  1438. if pattern:
  1439. pattern, normcase = self.__prepare(pattern)
  1440. else:
  1441. normcase = None
  1442. return self.__walk(pattern, normcase, errors)
  1443. def __walk(self, pattern, normcase, errors):
  1444. """ Prepared version of walk """
  1445. try:
  1446. childList = self.listdir()
  1447. except Exception:
  1448. exc = sys.exc_info()[1]
  1449. tmpl = "Unable to list directory '%(self)s': %(exc)s"
  1450. msg = tmpl % locals()
  1451. errors(msg)
  1452. return
  1453. for child in childList:
  1454. if pattern is None or child.__fnmatch(pattern, normcase):
  1455. yield child
  1456. try:
  1457. isdir = child.isdir()
  1458. except Exception:
  1459. exc = sys.exc_info()[1]
  1460. tmpl = "Unable to access '%(child)s': %(exc)s"
  1461. msg = tmpl % locals()
  1462. errors(msg)
  1463. isdir = False
  1464. if isdir:
  1465. for item in child.__walk(pattern, normcase, errors):
  1466. yield item
  1467. def walkdirs(self, pattern=None, errors='strict'):
  1468. if errors not in ('strict', 'warn', 'ignore'):
  1469. raise ValueError("invalid errors parameter")
  1470. if pattern:
  1471. pattern, normcase = self.__prepare(pattern)
  1472. else:
  1473. normcase = None
  1474. return self.__walkdirs(pattern, normcase, errors)
  1475. def __walkdirs(self, pattern, normcase, errors):
  1476. """ Prepared version of walkdirs """
  1477. try:
  1478. dirs = self.dirs()
  1479. except Exception:
  1480. if errors == 'ignore':
  1481. return
  1482. elif errors == 'warn':
  1483. warnings.warn(
  1484. "Unable to list directory '%s': %s"
  1485. % (self, sys.exc_info()[1]),
  1486. TreeWalkWarning)
  1487. return
  1488. else:
  1489. raise
  1490. for child in dirs:
  1491. if pattern is None or child.__fnmatch(pattern, normcase):
  1492. yield child
  1493. for subsubdir in child.__walkdirs(pattern, normcase, errors):
  1494. yield subsubdir
  1495. def walkfiles(self, pattern=None, errors='strict'):
  1496. if errors not in ('strict', 'warn', 'ignore'):
  1497. raise ValueError("invalid errors parameter")
  1498. if pattern:
  1499. pattern, normcase = self.__prepare(pattern)
  1500. else:
  1501. normcase = None
  1502. return self.__walkfiles(pattern, normcase, errors)
  1503. def __walkfiles(self, pattern, normcase, errors):
  1504. """ Prepared version of walkfiles """
  1505. try:
  1506. childList = self.listdir()
  1507. except Exception:
  1508. if errors == 'ignore':
  1509. return
  1510. elif errors == 'warn':
  1511. warnings.warn(
  1512. "Unable to list directory '%s': %s"
  1513. % (self, sys.exc_info()[1]),
  1514. TreeWalkWarning)
  1515. return
  1516. else:
  1517. raise
  1518. for child in childList:
  1519. try:
  1520. isfile = child.isfile()
  1521. isdir = not isfile and child.isdir()
  1522. except Exception:
  1523. if errors == 'ignore':
  1524. continue
  1525. elif errors == 'warn':
  1526. warnings.warn(
  1527. "Unable to access '%s': %s"
  1528. % (self, sys.exc_info()[1]),
  1529. TreeWalkWarning)
  1530. continue
  1531. else:
  1532. raise
  1533. if isfile:
  1534. if pattern is None or child.__fnmatch(pattern, normcase):
  1535. yield child
  1536. elif isdir:
  1537. for f in child.__walkfiles(pattern, normcase, errors):
  1538. yield f
  1539. def __fnmatch(self, pattern, normcase):
  1540. """ Return ``True`` if `self.name` matches the given `pattern`,
  1541. prepared version.
  1542. `pattern` - A filename pattern with wildcards,
  1543. for example ``'*.py'``. The pattern is expected to be normcase'd
  1544. already.
  1545. `normcase` - A function used to normalize the pattern and
  1546. filename before matching.
  1547. .. seealso:: :func:`Path.fnmatch`
  1548. """
  1549. return fnmatch.fnmatchcase(normcase(self.name), pattern)
  1550. def __prepare(self, pattern, normcase=None):
  1551. """ Prepares a fmatch_pattern for use with ``FastPath.__fnmatch`.
  1552. `pattern` - A filename pattern with wildcards,
  1553. for example ``'*.py'``. If the pattern contains a `normcase`
  1554. attribute, it is applied to the name and path prior to comparison.
  1555. `normcase` - (optional) A function used to normalize the pattern and
  1556. filename before matching. Defaults to :meth:`self.module`,
  1557. which defaults to :meth:`os.path.normcase`.
  1558. .. seealso:: :func:`FastPath.__fnmatch`
  1559. """
  1560. if not normcase:
  1561. normcase = getattr(pattern, 'normcase', self.module.normcase)
  1562. pattern = normcase(pattern)
  1563. return pattern, normcase
  1564. def fnmatch(self, pattern, normcase=None):
  1565. if not pattern:
  1566. raise ValueError("No pattern provided")
  1567. pattern, normcase = self.__prepare(pattern, normcase)
  1568. return self.__fnmatch(pattern, normcase)