Debian Codegraph @

src/_pytest/_py/path.py

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