path.py 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475
  1. # mypy: allow-untyped-defs
  2. """local path implementation."""
  3. from __future__ import annotations
  4. import atexit
  5. from collections.abc import Callable
  6. from contextlib import contextmanager
  7. import fnmatch
  8. import importlib.util
  9. import io
  10. import os
  11. from os.path import abspath
  12. from os.path import dirname
  13. from os.path import exists
  14. from os.path import isabs
  15. from os.path import isdir
  16. from os.path import isfile
  17. from os.path import islink
  18. from os.path import normpath
  19. import posixpath
  20. from stat import S_ISDIR
  21. from stat import S_ISLNK
  22. from stat import S_ISREG
  23. import sys
  24. from typing import Any
  25. from typing import cast
  26. from typing import Literal
  27. from typing import overload
  28. from typing import TYPE_CHECKING
  29. import uuid
  30. import warnings
  31. from . import error
  32. # Moved from local.py.
  33. iswin32 = sys.platform == "win32" or (getattr(os, "_name", False) == "nt")
  34. class Checkers:
  35. _depend_on_existence = "exists", "link", "dir", "file"
  36. def __init__(self, path):
  37. self.path = path
  38. def dotfile(self):
  39. return self.path.basename.startswith(".")
  40. def ext(self, arg):
  41. if not arg.startswith("."):
  42. arg = "." + arg
  43. return self.path.ext == arg
  44. def basename(self, arg):
  45. return self.path.basename == arg
  46. def basestarts(self, arg):
  47. return self.path.basename.startswith(arg)
  48. def relto(self, arg):
  49. return self.path.relto(arg)
  50. def fnmatch(self, arg):
  51. return self.path.fnmatch(arg)
  52. def endswith(self, arg):
  53. return str(self.path).endswith(arg)
  54. def _evaluate(self, kw):
  55. from .._code.source import getrawcode
  56. for name, value in kw.items():
  57. invert = False
  58. meth = None
  59. try:
  60. meth = getattr(self, name)
  61. except AttributeError:
  62. if name[:3] == "not":
  63. invert = True
  64. try:
  65. meth = getattr(self, name[3:])
  66. except AttributeError:
  67. pass
  68. if meth is None:
  69. raise TypeError(f"no {name!r} checker available for {self.path!r}")
  70. try:
  71. if getrawcode(meth).co_argcount > 1:
  72. if (not meth(value)) ^ invert:
  73. return False
  74. else:
  75. if bool(value) ^ bool(meth()) ^ invert:
  76. return False
  77. except (error.ENOENT, error.ENOTDIR, error.EBUSY):
  78. # EBUSY feels not entirely correct,
  79. # but its kind of necessary since ENOMEDIUM
  80. # is not accessible in python
  81. for name in self._depend_on_existence:
  82. if name in kw:
  83. if kw.get(name):
  84. return False
  85. name = "not" + name
  86. if name in kw:
  87. if not kw.get(name):
  88. return False
  89. return True
  90. _statcache: Stat
  91. def _stat(self) -> Stat:
  92. try:
  93. return self._statcache
  94. except AttributeError:
  95. try:
  96. self._statcache = self.path.stat()
  97. except error.ELOOP:
  98. self._statcache = self.path.lstat()
  99. return self._statcache
  100. def dir(self):
  101. return S_ISDIR(self._stat().mode)
  102. def file(self):
  103. return S_ISREG(self._stat().mode)
  104. def exists(self):
  105. return self._stat()
  106. def link(self):
  107. st = self.path.lstat()
  108. return S_ISLNK(st.mode)
  109. class NeverRaised(Exception):
  110. pass
  111. class Visitor:
  112. def __init__(self, fil, rec, ignore, bf, sort):
  113. if isinstance(fil, str):
  114. fil = FNMatcher(fil)
  115. if isinstance(rec, str):
  116. self.rec: Callable[[LocalPath], bool] = FNMatcher(rec)
  117. elif not hasattr(rec, "__call__") and rec:
  118. self.rec = lambda path: True
  119. else:
  120. self.rec = rec
  121. self.fil = fil
  122. self.ignore = ignore
  123. self.breadthfirst = bf
  124. self.optsort = cast(Callable[[Any], Any], sorted) if sort else (lambda x: x)
  125. def gen(self, path):
  126. try:
  127. entries = path.listdir()
  128. except self.ignore:
  129. return
  130. rec = self.rec
  131. dirs = self.optsort(
  132. [p for p in entries if p.check(dir=1) and (rec is None or rec(p))]
  133. )
  134. if not self.breadthfirst:
  135. for subdir in dirs:
  136. yield from self.gen(subdir)
  137. for p in self.optsort(entries):
  138. if self.fil is None or self.fil(p):
  139. yield p
  140. if self.breadthfirst:
  141. for subdir in dirs:
  142. yield from self.gen(subdir)
  143. class FNMatcher:
  144. def __init__(self, pattern):
  145. self.pattern = pattern
  146. def __call__(self, path):
  147. pattern = self.pattern
  148. if (
  149. pattern.find(path.sep) == -1
  150. and iswin32
  151. and pattern.find(posixpath.sep) != -1
  152. ):
  153. # Running on Windows, the pattern has no Windows path separators,
  154. # and the pattern has one or more Posix path separators. Replace
  155. # the Posix path separators with the Windows path separator.
  156. pattern = pattern.replace(posixpath.sep, path.sep)
  157. if pattern.find(path.sep) == -1:
  158. name = path.basename
  159. else:
  160. name = str(path) # path.strpath # XXX svn?
  161. if not os.path.isabs(pattern):
  162. pattern = "*" + path.sep + pattern
  163. return fnmatch.fnmatch(name, pattern)
  164. def map_as_list(func, iter):
  165. return list(map(func, iter))
  166. class Stat:
  167. if TYPE_CHECKING:
  168. @property
  169. def size(self) -> int: ...
  170. @property
  171. def mtime(self) -> float: ...
  172. def __getattr__(self, name: str) -> Any:
  173. return getattr(self._osstatresult, "st_" + name)
  174. def __init__(self, path, osstatresult):
  175. self.path = path
  176. self._osstatresult = osstatresult
  177. @property
  178. def owner(self):
  179. if iswin32:
  180. raise NotImplementedError("XXX win32")
  181. import pwd
  182. entry = error.checked_call(pwd.getpwuid, self.uid) # type:ignore[attr-defined,unused-ignore]
  183. return entry[0]
  184. @property
  185. def group(self):
  186. """Return group name of file."""
  187. if iswin32:
  188. raise NotImplementedError("XXX win32")
  189. import grp
  190. entry = error.checked_call(grp.getgrgid, self.gid) # type:ignore[attr-defined,unused-ignore]
  191. return entry[0]
  192. def isdir(self):
  193. return S_ISDIR(self._osstatresult.st_mode)
  194. def isfile(self):
  195. return S_ISREG(self._osstatresult.st_mode)
  196. def islink(self):
  197. self.path.lstat()
  198. return S_ISLNK(self._osstatresult.st_mode)
  199. def getuserid(user):
  200. import pwd
  201. if not isinstance(user, int):
  202. user = pwd.getpwnam(user)[2] # type:ignore[attr-defined,unused-ignore]
  203. return user
  204. def getgroupid(group):
  205. import grp
  206. if not isinstance(group, int):
  207. group = grp.getgrnam(group)[2] # type:ignore[attr-defined,unused-ignore]
  208. return group
  209. class LocalPath:
  210. """Object oriented interface to os.path and other local filesystem
  211. related information.
  212. """
  213. class ImportMismatchError(ImportError):
  214. """raised on pyimport() if there is a mismatch of __file__'s"""
  215. sep = os.sep
  216. def __init__(self, path=None, expanduser=False):
  217. """Initialize and return a local Path instance.
  218. Path can be relative to the current directory.
  219. If path is None it defaults to the current working directory.
  220. If expanduser is True, tilde-expansion is performed.
  221. Note that Path instances always carry an absolute path.
  222. Note also that passing in a local path object will simply return
  223. the exact same path object. Use new() to get a new copy.
  224. """
  225. if path is None:
  226. self.strpath = error.checked_call(os.getcwd)
  227. else:
  228. try:
  229. path = os.fspath(path)
  230. except TypeError:
  231. raise ValueError(
  232. "can only pass None, Path instances "
  233. "or non-empty strings to LocalPath"
  234. )
  235. if expanduser:
  236. path = os.path.expanduser(path)
  237. self.strpath = abspath(path)
  238. if sys.platform != "win32":
  239. def chown(self, user, group, rec=0):
  240. """Change ownership to the given user and group.
  241. user and group may be specified by a number or
  242. by a name. if rec is True change ownership
  243. recursively.
  244. """
  245. uid = getuserid(user)
  246. gid = getgroupid(group)
  247. if rec:
  248. for x in self.visit(rec=lambda x: x.check(link=0)):
  249. if x.check(link=0):
  250. error.checked_call(os.chown, str(x), uid, gid)
  251. error.checked_call(os.chown, str(self), uid, gid)
  252. def readlink(self) -> str:
  253. """Return value of a symbolic link."""
  254. # https://github.com/python/mypy/issues/12278
  255. return error.checked_call(os.readlink, self.strpath) # type: ignore[arg-type,return-value,unused-ignore]
  256. def mklinkto(self, oldname):
  257. """Posix style hard link to another name."""
  258. error.checked_call(os.link, str(oldname), str(self))
  259. def mksymlinkto(self, value, absolute=1):
  260. """Create a symbolic link with the given value (pointing to another name)."""
  261. if absolute:
  262. error.checked_call(os.symlink, str(value), self.strpath)
  263. else:
  264. base = self.common(value)
  265. # with posix local paths '/' is always a common base
  266. relsource = self.__class__(value).relto(base)
  267. reldest = self.relto(base)
  268. n = reldest.count(self.sep)
  269. target = self.sep.join(("..",) * n + (relsource,))
  270. error.checked_call(os.symlink, target, self.strpath)
  271. def __div__(self, other):
  272. return self.join(os.fspath(other))
  273. __truediv__ = __div__ # py3k
  274. @property
  275. def basename(self):
  276. """Basename part of path."""
  277. return self._getbyspec("basename")[0]
  278. @property
  279. def dirname(self):
  280. """Dirname part of path."""
  281. return self._getbyspec("dirname")[0]
  282. @property
  283. def purebasename(self):
  284. """Pure base name of the path."""
  285. return self._getbyspec("purebasename")[0]
  286. @property
  287. def ext(self):
  288. """Extension of the path (including the '.')."""
  289. return self._getbyspec("ext")[0]
  290. def read_binary(self):
  291. """Read and return a bytestring from reading the path."""
  292. with self.open("rb") as f:
  293. return f.read()
  294. def read_text(self, encoding):
  295. """Read and return a Unicode string from reading the path."""
  296. with self.open("r", encoding=encoding) as f:
  297. return f.read()
  298. def read(self, mode="r"):
  299. """Read and return a bytestring from reading the path."""
  300. with self.open(mode) as f:
  301. return f.read()
  302. def readlines(self, cr=1):
  303. """Read and return a list of lines from the path. if cr is False, the
  304. newline will be removed from the end of each line."""
  305. mode = "r"
  306. if not cr:
  307. content = self.read(mode)
  308. return content.split("\n")
  309. else:
  310. f = self.open(mode)
  311. try:
  312. return f.readlines()
  313. finally:
  314. f.close()
  315. def load(self):
  316. """(deprecated) return object unpickled from self.read()"""
  317. f = self.open("rb")
  318. try:
  319. import pickle
  320. return error.checked_call(pickle.load, f)
  321. finally:
  322. f.close()
  323. def move(self, target):
  324. """Move this path to target."""
  325. if target.relto(self):
  326. raise error.EINVAL(target, "cannot move path into a subdirectory of itself")
  327. try:
  328. self.rename(target)
  329. except error.EXDEV: # invalid cross-device link
  330. self.copy(target)
  331. self.remove()
  332. def fnmatch(self, pattern):
  333. """Return true if the basename/fullname matches the glob-'pattern'.
  334. valid pattern characters::
  335. * matches everything
  336. ? matches any single character
  337. [seq] matches any character in seq
  338. [!seq] matches any char not in seq
  339. If the pattern contains a path-separator then the full path
  340. is used for pattern matching and a '*' is prepended to the
  341. pattern.
  342. if the pattern doesn't contain a path-separator the pattern
  343. is only matched against the basename.
  344. """
  345. return FNMatcher(pattern)(self)
  346. def relto(self, relpath):
  347. """Return a string which is the relative part of the path
  348. to the given 'relpath'.
  349. """
  350. if not isinstance(relpath, (str, LocalPath)):
  351. raise TypeError(f"{relpath!r}: not a string or path object")
  352. strrelpath = str(relpath)
  353. if strrelpath and strrelpath[-1] != self.sep:
  354. strrelpath += self.sep
  355. # assert strrelpath[-1] == self.sep
  356. # assert strrelpath[-2] != self.sep
  357. strself = self.strpath
  358. if sys.platform == "win32" or getattr(os, "_name", None) == "nt":
  359. if os.path.normcase(strself).startswith(os.path.normcase(strrelpath)):
  360. return strself[len(strrelpath) :]
  361. elif strself.startswith(strrelpath):
  362. return strself[len(strrelpath) :]
  363. return ""
  364. def ensure_dir(self, *args):
  365. """Ensure the path joined with args is a directory."""
  366. return self.ensure(*args, dir=True)
  367. def bestrelpath(self, dest):
  368. """Return a string which is a relative path from self
  369. (assumed to be a directory) to dest such that
  370. self.join(bestrelpath) == dest and if not such
  371. path can be determined return dest.
  372. """
  373. try:
  374. if self == dest:
  375. return os.curdir
  376. base = self.common(dest)
  377. if not base: # can be the case on windows
  378. return str(dest)
  379. self2base = self.relto(base)
  380. reldest = dest.relto(base)
  381. if self2base:
  382. n = self2base.count(self.sep) + 1
  383. else:
  384. n = 0
  385. lst = [os.pardir] * n
  386. if reldest:
  387. lst.append(reldest)
  388. target = dest.sep.join(lst)
  389. return target
  390. except AttributeError:
  391. return str(dest)
  392. def exists(self):
  393. return self.check()
  394. def isdir(self):
  395. return self.check(dir=1)
  396. def isfile(self):
  397. return self.check(file=1)
  398. def parts(self, reverse=False):
  399. """Return a root-first list of all ancestor directories
  400. plus the path itself.
  401. """
  402. current = self
  403. lst = [self]
  404. while 1:
  405. last = current
  406. current = current.dirpath()
  407. if last == current:
  408. break
  409. lst.append(current)
  410. if not reverse:
  411. lst.reverse()
  412. return lst
  413. def common(self, other):
  414. """Return the common part shared with the other path
  415. or None if there is no common part.
  416. """
  417. last = None
  418. for x, y in zip(self.parts(), other.parts()):
  419. if x != y:
  420. return last
  421. last = x
  422. return last
  423. def __add__(self, other):
  424. """Return new path object with 'other' added to the basename"""
  425. return self.new(basename=self.basename + str(other))
  426. def visit(self, fil=None, rec=None, ignore=NeverRaised, bf=False, sort=False):
  427. """Yields all paths below the current one
  428. fil is a filter (glob pattern or callable), if not matching the
  429. path will not be yielded, defaulting to None (everything is
  430. returned)
  431. rec is a filter (glob pattern or callable) that controls whether
  432. a node is descended, defaulting to None
  433. ignore is an Exception class that is ignoredwhen calling dirlist()
  434. on any of the paths (by default, all exceptions are reported)
  435. bf if True will cause a breadthfirst search instead of the
  436. default depthfirst. Default: False
  437. sort if True will sort entries within each directory level.
  438. """
  439. yield from Visitor(fil, rec, ignore, bf, sort).gen(self)
  440. def _sortlist(self, res, sort):
  441. if sort:
  442. if hasattr(sort, "__call__"):
  443. warnings.warn(
  444. DeprecationWarning(
  445. "listdir(sort=callable) is deprecated and breaks on python3"
  446. ),
  447. stacklevel=3,
  448. )
  449. res.sort(sort)
  450. else:
  451. res.sort()
  452. def __fspath__(self):
  453. return self.strpath
  454. def __hash__(self):
  455. s = self.strpath
  456. if iswin32:
  457. s = s.lower()
  458. return hash(s)
  459. def __eq__(self, other):
  460. s1 = os.fspath(self)
  461. try:
  462. s2 = os.fspath(other)
  463. except TypeError:
  464. return False
  465. if iswin32:
  466. s1 = s1.lower()
  467. try:
  468. s2 = s2.lower()
  469. except AttributeError:
  470. return False
  471. return s1 == s2
  472. def __ne__(self, other):
  473. return not (self == other)
  474. def __lt__(self, other):
  475. return os.fspath(self) < os.fspath(other)
  476. def __gt__(self, other):
  477. return os.fspath(self) > os.fspath(other)
  478. def samefile(self, other):
  479. """Return True if 'other' references the same file as 'self'."""
  480. other = os.fspath(other)
  481. if not isabs(other):
  482. other = abspath(other)
  483. if self == other:
  484. return True
  485. if not hasattr(os.path, "samefile"):
  486. return False
  487. return error.checked_call(os.path.samefile, self.strpath, other)
  488. def remove(self, rec=1, ignore_errors=False):
  489. """Remove a file or directory (or a directory tree if rec=1).
  490. if ignore_errors is True, errors while removing directories will
  491. be ignored.
  492. """
  493. if self.check(dir=1, link=0):
  494. if rec:
  495. # force remove of readonly files on windows
  496. if iswin32:
  497. self.chmod(0o700, rec=1)
  498. import shutil
  499. error.checked_call(
  500. shutil.rmtree, self.strpath, ignore_errors=ignore_errors
  501. )
  502. else:
  503. error.checked_call(os.rmdir, self.strpath)
  504. else:
  505. if iswin32:
  506. self.chmod(0o700)
  507. error.checked_call(os.remove, self.strpath)
  508. def computehash(self, hashtype="md5", chunksize=524288):
  509. """Return hexdigest of hashvalue for this file."""
  510. try:
  511. try:
  512. import hashlib as mod
  513. except ImportError:
  514. if hashtype == "sha1":
  515. hashtype = "sha"
  516. mod = __import__(hashtype)
  517. hash = getattr(mod, hashtype)()
  518. except (AttributeError, ImportError):
  519. raise ValueError(f"Don't know how to compute {hashtype!r} hash")
  520. f = self.open("rb")
  521. try:
  522. while 1:
  523. buf = f.read(chunksize)
  524. if not buf:
  525. return hash.hexdigest()
  526. hash.update(buf)
  527. finally:
  528. f.close()
  529. def new(self, **kw):
  530. """Create a modified version of this path.
  531. the following keyword arguments modify various path parts::
  532. a:/some/path/to/a/file.ext
  533. xx drive
  534. xxxxxxxxxxxxxxxxx dirname
  535. xxxxxxxx basename
  536. xxxx purebasename
  537. xxx ext
  538. """
  539. obj = object.__new__(self.__class__)
  540. if not kw:
  541. obj.strpath = self.strpath
  542. return obj
  543. drive, dirname, basename, purebasename, ext = self._getbyspec(
  544. "drive,dirname,basename,purebasename,ext"
  545. )
  546. if "basename" in kw:
  547. if "purebasename" in kw or "ext" in kw:
  548. raise ValueError(f"invalid specification {kw!r}")
  549. else:
  550. pb = kw.setdefault("purebasename", purebasename)
  551. try:
  552. ext = kw["ext"]
  553. except KeyError:
  554. pass
  555. else:
  556. if ext and not ext.startswith("."):
  557. ext = "." + ext
  558. kw["basename"] = pb + ext
  559. if "dirname" in kw and not kw["dirname"]:
  560. kw["dirname"] = drive
  561. else:
  562. kw.setdefault("dirname", dirname)
  563. kw.setdefault("sep", self.sep)
  564. obj.strpath = normpath("{dirname}{sep}{basename}".format(**kw))
  565. return obj
  566. def _getbyspec(self, spec: str) -> list[str]:
  567. """See new for what 'spec' can be."""
  568. res = []
  569. parts = self.strpath.split(self.sep)
  570. args = filter(None, spec.split(","))
  571. for name in args:
  572. if name == "drive":
  573. res.append(parts[0])
  574. elif name == "dirname":
  575. res.append(self.sep.join(parts[:-1]))
  576. else:
  577. basename = parts[-1]
  578. if name == "basename":
  579. res.append(basename)
  580. else:
  581. i = basename.rfind(".")
  582. if i == -1:
  583. purebasename, ext = basename, ""
  584. else:
  585. purebasename, ext = basename[:i], basename[i:]
  586. if name == "purebasename":
  587. res.append(purebasename)
  588. elif name == "ext":
  589. res.append(ext)
  590. else:
  591. raise ValueError(f"invalid part specification {name!r}")
  592. return res
  593. def dirpath(self, *args, **kwargs):
  594. """Return the directory path joined with any given path arguments."""
  595. if not kwargs:
  596. path = object.__new__(self.__class__)
  597. path.strpath = dirname(self.strpath)
  598. if args:
  599. path = path.join(*args)
  600. return path
  601. return self.new(basename="").join(*args, **kwargs)
  602. def join(self, *args: os.PathLike[str], abs: bool = False) -> LocalPath:
  603. """Return a new path by appending all 'args' as path
  604. components. if abs=1 is used restart from root if any
  605. of the args is an absolute path.
  606. """
  607. sep = self.sep
  608. strargs = [os.fspath(arg) for arg in args]
  609. strpath = self.strpath
  610. if abs:
  611. newargs: list[str] = []
  612. for arg in reversed(strargs):
  613. if isabs(arg):
  614. strpath = arg
  615. strargs = newargs
  616. break
  617. newargs.insert(0, arg)
  618. # special case for when we have e.g. strpath == "/"
  619. actual_sep = "" if strpath.endswith(sep) else sep
  620. for arg in strargs:
  621. arg = arg.strip(sep)
  622. if iswin32:
  623. # allow unix style paths even on windows.
  624. arg = arg.strip("/")
  625. arg = arg.replace("/", sep)
  626. strpath = strpath + actual_sep + arg
  627. actual_sep = sep
  628. obj = object.__new__(self.__class__)
  629. obj.strpath = normpath(strpath)
  630. return obj
  631. def open(self, mode="r", ensure=False, encoding=None):
  632. """Return an opened file with the given mode.
  633. If ensure is True, create parent directories if needed.
  634. """
  635. if ensure:
  636. self.dirpath().ensure(dir=1)
  637. if encoding:
  638. return error.checked_call(
  639. io.open,
  640. self.strpath,
  641. mode,
  642. encoding=encoding,
  643. )
  644. return error.checked_call(open, self.strpath, mode)
  645. def _fastjoin(self, name):
  646. child = object.__new__(self.__class__)
  647. child.strpath = self.strpath + self.sep + name
  648. return child
  649. def islink(self):
  650. return islink(self.strpath)
  651. def check(self, **kw):
  652. """Check a path for existence and properties.
  653. Without arguments, return True if the path exists, otherwise False.
  654. valid checkers::
  655. file = 1 # is a file
  656. file = 0 # is not a file (may not even exist)
  657. dir = 1 # is a dir
  658. link = 1 # is a link
  659. exists = 1 # exists
  660. You can specify multiple checker definitions, for example::
  661. path.check(file=1, link=1) # a link pointing to a file
  662. """
  663. if not kw:
  664. return exists(self.strpath)
  665. if len(kw) == 1:
  666. if "dir" in kw:
  667. return not kw["dir"] ^ isdir(self.strpath)
  668. if "file" in kw:
  669. return not kw["file"] ^ isfile(self.strpath)
  670. if not kw:
  671. kw = {"exists": 1}
  672. return Checkers(self)._evaluate(kw)
  673. _patternchars = set("*?[" + os.sep)
  674. def listdir(self, fil=None, sort=None):
  675. """List directory contents, possibly filter by the given fil func
  676. and possibly sorted.
  677. """
  678. if fil is None and sort is None:
  679. names = error.checked_call(os.listdir, self.strpath)
  680. return map_as_list(self._fastjoin, names)
  681. if isinstance(fil, str):
  682. if not self._patternchars.intersection(fil):
  683. child = self._fastjoin(fil)
  684. if exists(child.strpath):
  685. return [child]
  686. return []
  687. fil = FNMatcher(fil)
  688. names = error.checked_call(os.listdir, self.strpath)
  689. res = []
  690. for name in names:
  691. child = self._fastjoin(name)
  692. if fil is None or fil(child):
  693. res.append(child)
  694. self._sortlist(res, sort)
  695. return res
  696. def size(self) -> int:
  697. """Return size of the underlying file object"""
  698. return self.stat().size
  699. def mtime(self) -> float:
  700. """Return last modification time of the path."""
  701. return self.stat().mtime
  702. def copy(self, target, mode=False, stat=False):
  703. """Copy path to target.
  704. If mode is True, will copy permission from path to target.
  705. If stat is True, copy permission, last modification
  706. time, last access time, and flags from path to target.
  707. """
  708. if self.check(file=1):
  709. if target.check(dir=1):
  710. target = target.join(self.basename)
  711. assert self != target
  712. copychunked(self, target)
  713. if mode:
  714. copymode(self.strpath, target.strpath)
  715. if stat:
  716. copystat(self, target)
  717. else:
  718. def rec(p):
  719. return p.check(link=0)
  720. for x in self.visit(rec=rec):
  721. relpath = x.relto(self)
  722. newx = target.join(relpath)
  723. newx.dirpath().ensure(dir=1)
  724. if x.check(link=1):
  725. newx.mksymlinkto(x.readlink())
  726. continue
  727. elif x.check(file=1):
  728. copychunked(x, newx)
  729. elif x.check(dir=1):
  730. newx.ensure(dir=1)
  731. if mode:
  732. copymode(x.strpath, newx.strpath)
  733. if stat:
  734. copystat(x, newx)
  735. def rename(self, target):
  736. """Rename this path to target."""
  737. target = os.fspath(target)
  738. return error.checked_call(os.rename, self.strpath, target)
  739. def dump(self, obj, bin=1):
  740. """Pickle object into path location"""
  741. f = self.open("wb")
  742. import pickle
  743. try:
  744. error.checked_call(pickle.dump, obj, f, bin)
  745. finally:
  746. f.close()
  747. def mkdir(self, *args):
  748. """Create & return the directory joined with args."""
  749. p = self.join(*args)
  750. error.checked_call(os.mkdir, os.fspath(p))
  751. return p
  752. def write_binary(self, data, ensure=False):
  753. """Write binary data into path. If ensure is True create
  754. missing parent directories.
  755. """
  756. if ensure:
  757. self.dirpath().ensure(dir=1)
  758. with self.open("wb") as f:
  759. f.write(data)
  760. def write_text(self, data, encoding, ensure=False):
  761. """Write text data into path using the specified encoding.
  762. If ensure is True create missing parent directories.
  763. """
  764. if ensure:
  765. self.dirpath().ensure(dir=1)
  766. with self.open("w", encoding=encoding) as f:
  767. f.write(data)
  768. def write(self, data, mode="w", ensure=False):
  769. """Write data into path. If ensure is True create
  770. missing parent directories.
  771. """
  772. if ensure:
  773. self.dirpath().ensure(dir=1)
  774. if "b" in mode:
  775. if not isinstance(data, bytes):
  776. raise ValueError("can only process bytes")
  777. else:
  778. if not isinstance(data, str):
  779. if not isinstance(data, bytes):
  780. data = str(data)
  781. else:
  782. data = data.decode(sys.getdefaultencoding())
  783. f = self.open(mode)
  784. try:
  785. f.write(data)
  786. finally:
  787. f.close()
  788. def _ensuredirs(self):
  789. parent = self.dirpath()
  790. if parent == self:
  791. return self
  792. if parent.check(dir=0):
  793. parent._ensuredirs()
  794. if self.check(dir=0):
  795. try:
  796. self.mkdir()
  797. except error.EEXIST:
  798. # race condition: file/dir created by another thread/process.
  799. # complain if it is not a dir
  800. if self.check(dir=0):
  801. raise
  802. return self
  803. def ensure(self, *args, **kwargs):
  804. """Ensure that an args-joined path exists (by default as
  805. a file). if you specify a keyword argument 'dir=True'
  806. then the path is forced to be a directory path.
  807. """
  808. p = self.join(*args)
  809. if kwargs.get("dir", 0):
  810. return p._ensuredirs()
  811. else:
  812. p.dirpath()._ensuredirs()
  813. if not p.check(file=1):
  814. p.open("wb").close()
  815. return p
  816. @overload
  817. def stat(self, raising: Literal[True] = ...) -> Stat: ...
  818. @overload
  819. def stat(self, raising: Literal[False]) -> Stat | None: ...
  820. def stat(self, raising: bool = True) -> Stat | None:
  821. """Return an os.stat() tuple."""
  822. if raising:
  823. return Stat(self, error.checked_call(os.stat, self.strpath))
  824. try:
  825. return Stat(self, os.stat(self.strpath))
  826. except KeyboardInterrupt:
  827. raise
  828. except Exception:
  829. return None
  830. def lstat(self) -> Stat:
  831. """Return an os.lstat() tuple."""
  832. return Stat(self, error.checked_call(os.lstat, self.strpath))
  833. def setmtime(self, mtime=None):
  834. """Set modification time for the given path. if 'mtime' is None
  835. (the default) then the file's mtime is set to current time.
  836. Note that the resolution for 'mtime' is platform dependent.
  837. """
  838. if mtime is None:
  839. return error.checked_call(os.utime, self.strpath, mtime)
  840. try:
  841. return error.checked_call(os.utime, self.strpath, (-1, mtime))
  842. except error.EINVAL:
  843. return error.checked_call(os.utime, self.strpath, (self.atime(), mtime))
  844. def chdir(self):
  845. """Change directory to self and return old current directory"""
  846. try:
  847. old = self.__class__()
  848. except error.ENOENT:
  849. old = None
  850. error.checked_call(os.chdir, self.strpath)
  851. return old
  852. @contextmanager
  853. def as_cwd(self):
  854. """
  855. Return a context manager, which changes to the path's dir during the
  856. managed "with" context.
  857. On __enter__ it returns the old dir, which might be ``None``.
  858. """
  859. old = self.chdir()
  860. try:
  861. yield old
  862. finally:
  863. if old is not None:
  864. old.chdir()
  865. def realpath(self):
  866. """Return a new path which contains no symbolic links."""
  867. return self.__class__(os.path.realpath(self.strpath))
  868. def atime(self):
  869. """Return last access time of the path."""
  870. return self.stat().atime
  871. def __repr__(self):
  872. return f"local({self.strpath!r})"
  873. def __str__(self):
  874. """Return string representation of the Path."""
  875. return self.strpath
  876. def chmod(self, mode, rec=0):
  877. """Change permissions to the given mode. If mode is an
  878. integer it directly encodes the os-specific modes.
  879. if rec is True perform recursively.
  880. """
  881. if not isinstance(mode, int):
  882. raise TypeError(f"mode {mode!r} must be an integer")
  883. if rec:
  884. for x in self.visit(rec=rec):
  885. error.checked_call(os.chmod, str(x), mode)
  886. error.checked_call(os.chmod, self.strpath, mode)
  887. def pypkgpath(self):
  888. """Return the Python package path by looking for the last
  889. directory upwards which still contains an __init__.py.
  890. Return None if a pkgpath cannot be determined.
  891. """
  892. pkgpath = None
  893. for parent in self.parts(reverse=True):
  894. if parent.isdir():
  895. if not parent.join("__init__.py").exists():
  896. break
  897. if not isimportable(parent.basename):
  898. break
  899. pkgpath = parent
  900. return pkgpath
  901. def _ensuresyspath(self, ensuremode, path):
  902. if ensuremode:
  903. s = str(path)
  904. if ensuremode == "append":
  905. if s not in sys.path:
  906. sys.path.append(s)
  907. else:
  908. if s != sys.path[0]:
  909. sys.path.insert(0, s)
  910. def pyimport(self, modname=None, ensuresyspath=True):
  911. """Return path as an imported python module.
  912. If modname is None, look for the containing package
  913. and construct an according module name.
  914. The module will be put/looked up in sys.modules.
  915. if ensuresyspath is True then the root dir for importing
  916. the file (taking __init__.py files into account) will
  917. be prepended to sys.path if it isn't there already.
  918. If ensuresyspath=="append" the root dir will be appended
  919. if it isn't already contained in sys.path.
  920. if ensuresyspath is False no modification of syspath happens.
  921. Special value of ensuresyspath=="importlib" is intended
  922. purely for using in pytest, it is capable only of importing
  923. separate .py files outside packages, e.g. for test suite
  924. without any __init__.py file. It effectively allows having
  925. same-named test modules in different places and offers
  926. mild opt-in via this option. Note that it works only in
  927. recent versions of python.
  928. """
  929. if not self.check():
  930. raise error.ENOENT(self)
  931. if ensuresyspath == "importlib":
  932. if modname is None:
  933. modname = self.purebasename
  934. spec = importlib.util.spec_from_file_location(modname, str(self))
  935. if spec is None or spec.loader is None:
  936. raise ImportError(f"Can't find module {modname} at location {self!s}")
  937. mod = importlib.util.module_from_spec(spec)
  938. spec.loader.exec_module(mod)
  939. return mod
  940. pkgpath = None
  941. if modname is None:
  942. pkgpath = self.pypkgpath()
  943. if pkgpath is not None:
  944. pkgroot = pkgpath.dirpath()
  945. names = self.new(ext="").relto(pkgroot).split(self.sep)
  946. if names[-1] == "__init__":
  947. names.pop()
  948. modname = ".".join(names)
  949. else:
  950. pkgroot = self.dirpath()
  951. modname = self.purebasename
  952. self._ensuresyspath(ensuresyspath, pkgroot)
  953. __import__(modname)
  954. mod = sys.modules[modname]
  955. if self.basename == "__init__.py":
  956. return mod # we don't check anything as we might
  957. # be in a namespace package ... too icky to check
  958. modfile = mod.__file__
  959. assert modfile is not None
  960. if modfile[-4:] in (".pyc", ".pyo"):
  961. modfile = modfile[:-1]
  962. elif modfile.endswith("$py.class"):
  963. modfile = modfile[:-9] + ".py"
  964. if modfile.endswith(os.sep + "__init__.py"):
  965. if self.basename != "__init__.py":
  966. modfile = modfile[:-12]
  967. try:
  968. issame = self.samefile(modfile)
  969. except error.ENOENT:
  970. issame = False
  971. if not issame:
  972. ignore = os.getenv("PY_IGNORE_IMPORTMISMATCH")
  973. if ignore != "1":
  974. raise self.ImportMismatchError(modname, modfile, self)
  975. return mod
  976. else:
  977. try:
  978. return sys.modules[modname]
  979. except KeyError:
  980. # we have a custom modname, do a pseudo-import
  981. import types
  982. mod = types.ModuleType(modname)
  983. mod.__file__ = str(self)
  984. sys.modules[modname] = mod
  985. try:
  986. with open(str(self), "rb") as f:
  987. exec(f.read(), mod.__dict__)
  988. except BaseException:
  989. del sys.modules[modname]
  990. raise
  991. return mod
  992. def sysexec(self, *argv: os.PathLike[str], **popen_opts: Any) -> str:
  993. """Return stdout text from executing a system child process,
  994. where the 'self' path points to executable.
  995. The process is directly invoked and not through a system shell.
  996. """
  997. from subprocess import PIPE
  998. from subprocess import Popen
  999. popen_opts.pop("stdout", None)
  1000. popen_opts.pop("stderr", None)
  1001. proc = Popen(
  1002. [str(self)] + [str(arg) for arg in argv],
  1003. **popen_opts,
  1004. stdout=PIPE,
  1005. stderr=PIPE,
  1006. )
  1007. stdout: str | bytes
  1008. stdout, stderr = proc.communicate()
  1009. ret = proc.wait()
  1010. if isinstance(stdout, bytes):
  1011. stdout = stdout.decode(sys.getdefaultencoding())
  1012. if ret != 0:
  1013. if isinstance(stderr, bytes):
  1014. stderr = stderr.decode(sys.getdefaultencoding())
  1015. raise RuntimeError(
  1016. ret,
  1017. ret,
  1018. str(self),
  1019. stdout,
  1020. stderr,
  1021. )
  1022. return stdout
  1023. @classmethod
  1024. def sysfind(cls, name, checker=None, paths=None):
  1025. """Return a path object found by looking at the systems
  1026. underlying PATH specification. If the checker is not None
  1027. it will be invoked to filter matching paths. If a binary
  1028. cannot be found, None is returned
  1029. Note: This is probably not working on plain win32 systems
  1030. but may work on cygwin.
  1031. """
  1032. if isabs(name):
  1033. p = local(name)
  1034. if p.check(file=1):
  1035. return p
  1036. else:
  1037. if paths is None:
  1038. if iswin32:
  1039. paths = os.environ["Path"].split(";")
  1040. if "" not in paths and "." not in paths:
  1041. paths.append(".")
  1042. try:
  1043. systemroot = os.environ["SYSTEMROOT"]
  1044. except KeyError:
  1045. pass
  1046. else:
  1047. paths = [
  1048. path.replace("%SystemRoot%", systemroot) for path in paths
  1049. ]
  1050. else:
  1051. paths = os.environ["PATH"].split(":")
  1052. tryadd = []
  1053. if iswin32:
  1054. tryadd += os.environ["PATHEXT"].split(os.pathsep)
  1055. tryadd.append("")
  1056. for x in paths:
  1057. for addext in tryadd:
  1058. p = local(x).join(name, abs=True) + addext
  1059. try:
  1060. if p.check(file=1):
  1061. if checker:
  1062. if not checker(p):
  1063. continue
  1064. return p
  1065. except error.EACCES:
  1066. pass
  1067. return None
  1068. @classmethod
  1069. def _gethomedir(cls):
  1070. try:
  1071. x = os.environ["HOME"]
  1072. except KeyError:
  1073. try:
  1074. x = os.environ["HOMEDRIVE"] + os.environ["HOMEPATH"]
  1075. except KeyError:
  1076. return None
  1077. return cls(x)
  1078. # """
  1079. # special class constructors for local filesystem paths
  1080. # """
  1081. @classmethod
  1082. def get_temproot(cls):
  1083. """Return the system's temporary directory
  1084. (where tempfiles are usually created in)
  1085. """
  1086. import tempfile
  1087. return local(tempfile.gettempdir())
  1088. @classmethod
  1089. def mkdtemp(cls, rootdir=None):
  1090. """Return a Path object pointing to a fresh new temporary directory
  1091. (which we created ourselves).
  1092. """
  1093. import tempfile
  1094. if rootdir is None:
  1095. rootdir = cls.get_temproot()
  1096. path = error.checked_call(tempfile.mkdtemp, dir=str(rootdir))
  1097. return cls(path)
  1098. @classmethod
  1099. def make_numbered_dir(
  1100. cls, prefix="session-", rootdir=None, keep=3, lock_timeout=172800
  1101. ): # two days
  1102. """Return unique directory with a number greater than the current
  1103. maximum one. The number is assumed to start directly after prefix.
  1104. if keep is true directories with a number less than (maxnum-keep)
  1105. will be removed. If .lock files are used (lock_timeout non-zero),
  1106. algorithm is multi-process safe.
  1107. """
  1108. if rootdir is None:
  1109. rootdir = cls.get_temproot()
  1110. nprefix = prefix.lower()
  1111. def parse_num(path):
  1112. """Parse the number out of a path (if it matches the prefix)"""
  1113. nbasename = path.basename.lower()
  1114. if nbasename.startswith(nprefix):
  1115. try:
  1116. return int(nbasename[len(nprefix) :])
  1117. except ValueError:
  1118. pass
  1119. def create_lockfile(path):
  1120. """Exclusively create lockfile. Throws when failed"""
  1121. mypid = os.getpid()
  1122. lockfile = path.join(".lock")
  1123. if hasattr(lockfile, "mksymlinkto"):
  1124. lockfile.mksymlinkto(str(mypid))
  1125. else:
  1126. fd = error.checked_call(
  1127. os.open, str(lockfile), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644
  1128. )
  1129. with os.fdopen(fd, "w") as f:
  1130. f.write(str(mypid))
  1131. return lockfile
  1132. def atexit_remove_lockfile(lockfile):
  1133. """Ensure lockfile is removed at process exit"""
  1134. mypid = os.getpid()
  1135. def try_remove_lockfile():
  1136. # in a fork() situation, only the last process should
  1137. # remove the .lock, otherwise the other processes run the
  1138. # risk of seeing their temporary dir disappear. For now
  1139. # we remove the .lock in the parent only (i.e. we assume
  1140. # that the children finish before the parent).
  1141. if os.getpid() != mypid:
  1142. return
  1143. try:
  1144. lockfile.remove()
  1145. except error.Error:
  1146. pass
  1147. atexit.register(try_remove_lockfile)
  1148. # compute the maximum number currently in use with the prefix
  1149. lastmax = None
  1150. while True:
  1151. maxnum = -1
  1152. for path in rootdir.listdir():
  1153. num = parse_num(path)
  1154. if num is not None:
  1155. maxnum = max(maxnum, num)
  1156. # make the new directory
  1157. try:
  1158. udir = rootdir.mkdir(prefix + str(maxnum + 1))
  1159. if lock_timeout:
  1160. lockfile = create_lockfile(udir)
  1161. atexit_remove_lockfile(lockfile)
  1162. except (error.EEXIST, error.ENOENT, error.EBUSY):
  1163. # race condition (1): another thread/process created the dir
  1164. # in the meantime - try again
  1165. # race condition (2): another thread/process spuriously acquired
  1166. # lock treating empty directory as candidate
  1167. # for removal - try again
  1168. # race condition (3): another thread/process tried to create the lock at
  1169. # the same time (happened in Python 3.3 on Windows)
  1170. # https://ci.appveyor.com/project/pytestbot/py/build/1.0.21/job/ffi85j4c0lqwsfwa
  1171. if lastmax == maxnum:
  1172. raise
  1173. lastmax = maxnum
  1174. continue
  1175. break
  1176. def get_mtime(path):
  1177. """Read file modification time"""
  1178. try:
  1179. return path.lstat().mtime
  1180. except error.Error:
  1181. pass
  1182. garbage_prefix = prefix + "garbage-"
  1183. def is_garbage(path):
  1184. """Check if path denotes directory scheduled for removal"""
  1185. bn = path.basename
  1186. return bn.startswith(garbage_prefix)
  1187. # prune old directories
  1188. udir_time = get_mtime(udir)
  1189. if keep and udir_time:
  1190. for path in rootdir.listdir():
  1191. num = parse_num(path)
  1192. if num is not None and num <= (maxnum - keep):
  1193. try:
  1194. # try acquiring lock to remove directory as exclusive user
  1195. if lock_timeout:
  1196. create_lockfile(path)
  1197. except (error.EEXIST, error.ENOENT, error.EBUSY):
  1198. path_time = get_mtime(path)
  1199. if not path_time:
  1200. # assume directory doesn't exist now
  1201. continue
  1202. if abs(udir_time - path_time) < lock_timeout:
  1203. # assume directory with lockfile exists
  1204. # and lock timeout hasn't expired yet
  1205. continue
  1206. # path dir locked for exclusive use
  1207. # and scheduled for removal to avoid another thread/process
  1208. # treating it as a new directory or removal candidate
  1209. garbage_path = rootdir.join(garbage_prefix + str(uuid.uuid4()))
  1210. try:
  1211. path.rename(garbage_path)
  1212. garbage_path.remove(rec=1)
  1213. except KeyboardInterrupt:
  1214. raise
  1215. except Exception: # this might be error.Error, WindowsError ...
  1216. pass
  1217. if is_garbage(path):
  1218. try:
  1219. path.remove(rec=1)
  1220. except KeyboardInterrupt:
  1221. raise
  1222. except Exception: # this might be error.Error, WindowsError ...
  1223. pass
  1224. # make link...
  1225. try:
  1226. username = os.environ["USER"] # linux, et al
  1227. except KeyError:
  1228. try:
  1229. username = os.environ["USERNAME"] # windows
  1230. except KeyError:
  1231. username = "current"
  1232. src = str(udir)
  1233. dest = src[: src.rfind("-")] + "-" + username
  1234. try:
  1235. os.unlink(dest)
  1236. except OSError:
  1237. pass
  1238. try:
  1239. os.symlink(src, dest)
  1240. except (OSError, AttributeError, NotImplementedError):
  1241. pass
  1242. return udir
  1243. def copymode(src, dest):
  1244. """Copy permission from src to dst."""
  1245. import shutil
  1246. shutil.copymode(src, dest)
  1247. def copystat(src, dest):
  1248. """Copy permission, last modification time,
  1249. last access time, and flags from src to dst."""
  1250. import shutil
  1251. shutil.copystat(str(src), str(dest))
  1252. def copychunked(src, dest):
  1253. chunksize = 524288 # half a meg of bytes
  1254. fsrc = src.open("rb")
  1255. try:
  1256. fdest = dest.open("wb")
  1257. try:
  1258. while 1:
  1259. buf = fsrc.read(chunksize)
  1260. if not buf:
  1261. break
  1262. fdest.write(buf)
  1263. finally:
  1264. fdest.close()
  1265. finally:
  1266. fsrc.close()
  1267. def isimportable(name):
  1268. if name and (name[0].isalpha() or name[0] == "_"):
  1269. name = name.replace("_", "")
  1270. return not name or name.isalnum()
  1271. local = LocalPath