-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathpath.py
1475 lines (1271 loc) · 48.1 KB
/
path.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# mypy: allow-untyped-defs
"""local path implementation."""
from __future__ import annotations
import atexit
from collections.abc import Callable
from contextlib import contextmanager
import fnmatch
import importlib.util
import io
import os
from os.path import abspath
from os.path import dirname
from os.path import exists
from os.path import isabs
from os.path import isdir
from os.path import isfile
from os.path import islink
from os.path import normpath
import posixpath
from stat import S_ISDIR
from stat import S_ISLNK
from stat import S_ISREG
import sys
from typing import Any
from typing import cast
from typing import Literal
from typing import overload
from typing import TYPE_CHECKING
import uuid
import warnings
from . import error
# Moved from local.py.
iswin32 = sys.platform == "win32" or (getattr(os, "_name", False) == "nt")
class Checkers:
_depend_on_existence = "exists", "link", "dir", "file"
def __init__(self, path):
self.path = path
def dotfile(self):
return self.path.basename.startswith(".")
def ext(self, arg):
if not arg.startswith("."):
arg = "." + arg
return self.path.ext == arg
def basename(self, arg):
return self.path.basename == arg
def basestarts(self, arg):
return self.path.basename.startswith(arg)
def relto(self, arg):
return self.path.relto(arg)
def fnmatch(self, arg):
return self.path.fnmatch(arg)
def endswith(self, arg):
return str(self.path).endswith(arg)
def _evaluate(self, kw):
from .._code.source import getrawcode
for name, value in kw.items():
invert = False
meth = None
try:
meth = getattr(self, name)
except AttributeError:
if name[:3] == "not":
invert = True
try:
meth = getattr(self, name[3:])
except AttributeError:
pass
if meth is None:
raise TypeError(f"no {name!r} checker available for {self.path!r}")
try:
if getrawcode(meth).co_argcount > 1:
if (not meth(value)) ^ invert:
return False
else:
if bool(value) ^ bool(meth()) ^ invert:
return False
except (error.ENOENT, error.ENOTDIR, error.EBUSY):
# EBUSY feels not entirely correct,
# but its kind of necessary since ENOMEDIUM
# is not accessible in python
for name in self._depend_on_existence:
if name in kw:
if kw.get(name):
return False
name = "not" + name
if name in kw:
if not kw.get(name):
return False
return True
_statcache: Stat
def _stat(self) -> Stat:
try:
return self._statcache
except AttributeError:
try:
self._statcache = self.path.stat()
except error.ELOOP:
self._statcache = self.path.lstat()
return self._statcache
def dir(self):
return S_ISDIR(self._stat().mode)
def file(self):
return S_ISREG(self._stat().mode)
def exists(self):
return self._stat()
def link(self):
st = self.path.lstat()
return S_ISLNK(st.mode)
class NeverRaised(Exception):
pass
class Visitor:
def __init__(self, fil, rec, ignore, bf, sort):
if isinstance(fil, str):
fil = FNMatcher(fil)
if isinstance(rec, str):
self.rec: Callable[[LocalPath], bool] = FNMatcher(rec)
elif not hasattr(rec, "__call__") and rec:
self.rec = lambda path: True
else:
self.rec = rec
self.fil = fil
self.ignore = ignore
self.breadthfirst = bf
self.optsort = cast(Callable[[Any], Any], sorted) if sort else (lambda x: x)
def gen(self, path):
try:
entries = path.listdir()
except self.ignore:
return
rec = self.rec
dirs = self.optsort(
[p for p in entries if p.check(dir=1) and (rec is None or rec(p))]
)
if not self.breadthfirst:
for subdir in dirs:
yield from self.gen(subdir)
for p in self.optsort(entries):
if self.fil is None or self.fil(p):
yield p
if self.breadthfirst:
for subdir in dirs:
yield from self.gen(subdir)
class FNMatcher:
def __init__(self, pattern):
self.pattern = pattern
def __call__(self, path):
pattern = self.pattern
if (
pattern.find(path.sep) == -1
and iswin32
and pattern.find(posixpath.sep) != -1
):
# Running on Windows, the pattern has no Windows path separators,
# and the pattern has one or more Posix path separators. Replace
# the Posix path separators with the Windows path separator.
pattern = pattern.replace(posixpath.sep, path.sep)
if pattern.find(path.sep) == -1:
name = path.basename
else:
name = str(path) # path.strpath # XXX svn?
if not os.path.isabs(pattern):
pattern = "*" + path.sep + pattern
return fnmatch.fnmatch(name, pattern)
def map_as_list(func, iter):
return list(map(func, iter))
class Stat:
if TYPE_CHECKING:
@property
def size(self) -> int: ...
@property
def mtime(self) -> float: ...
def __getattr__(self, name: str) -> Any:
return getattr(self._osstatresult, "st_" + name)
def __init__(self, path, osstatresult):
self.path = path
self._osstatresult = osstatresult
@property
def owner(self):
if iswin32:
raise NotImplementedError("XXX win32")
import pwd
entry = error.checked_call(pwd.getpwuid, self.uid) # type:ignore[attr-defined,unused-ignore]
return entry[0]
@property
def group(self):
"""Return group name of file."""
if iswin32:
raise NotImplementedError("XXX win32")
import grp
entry = error.checked_call(grp.getgrgid, self.gid) # type:ignore[attr-defined,unused-ignore]
return entry[0]
def isdir(self):
return S_ISDIR(self._osstatresult.st_mode)
def isfile(self):
return S_ISREG(self._osstatresult.st_mode)
def islink(self):
self.path.lstat()
return S_ISLNK(self._osstatresult.st_mode)
def getuserid(user):
import pwd
if not isinstance(user, int):
user = pwd.getpwnam(user)[2] # type:ignore[attr-defined,unused-ignore]
return user
def getgroupid(group):
import grp
if not isinstance(group, int):
group = grp.getgrnam(group)[2] # type:ignore[attr-defined,unused-ignore]
return group
class LocalPath:
"""Object oriented interface to os.path and other local filesystem
related information.
"""
class ImportMismatchError(ImportError):
"""raised on pyimport() if there is a mismatch of __file__'s"""
sep = os.sep
def __init__(self, path=None, expanduser=False):
"""Initialize and return a local Path instance.
Path can be relative to the current directory.
If path is None it defaults to the current working directory.
If expanduser is True, tilde-expansion is performed.
Note that Path instances always carry an absolute path.
Note also that passing in a local path object will simply return
the exact same path object. Use new() to get a new copy.
"""
if path is None:
self.strpath = error.checked_call(os.getcwd)
else:
try:
path = os.fspath(path)
except TypeError:
raise ValueError(
"can only pass None, Path instances "
"or non-empty strings to LocalPath"
)
if expanduser:
path = os.path.expanduser(path)
self.strpath = abspath(path)
if sys.platform != "win32":
def chown(self, user, group, rec=0):
"""Change ownership to the given user and group.
user and group may be specified by a number or
by a name. if rec is True change ownership
recursively.
"""
uid = getuserid(user)
gid = getgroupid(group)
if rec:
for x in self.visit(rec=lambda x: x.check(link=0)):
if x.check(link=0):
error.checked_call(os.chown, str(x), uid, gid)
error.checked_call(os.chown, str(self), uid, gid)
def readlink(self) -> str:
"""Return value of a symbolic link."""
# https://github.com/python/mypy/issues/12278
return error.checked_call(os.readlink, self.strpath) # type: ignore[arg-type,return-value,unused-ignore]
def mklinkto(self, oldname):
"""Posix style hard link to another name."""
error.checked_call(os.link, str(oldname), str(self))
def mksymlinkto(self, value, absolute=1):
"""Create a symbolic link with the given value (pointing to another name)."""
if absolute:
error.checked_call(os.symlink, str(value), self.strpath)
else:
base = self.common(value)
# with posix local paths '/' is always a common base
relsource = self.__class__(value).relto(base)
reldest = self.relto(base)
n = reldest.count(self.sep)
target = self.sep.join(("..",) * n + (relsource,))
error.checked_call(os.symlink, target, self.strpath)
def __div__(self, other):
return self.join(os.fspath(other))
__truediv__ = __div__ # py3k
@property
def basename(self):
"""Basename part of path."""
return self._getbyspec("basename")[0]
@property
def dirname(self):
"""Dirname part of path."""
return self._getbyspec("dirname")[0]
@property
def purebasename(self):
"""Pure base name of the path."""
return self._getbyspec("purebasename")[0]
@property
def ext(self):
"""Extension of the path (including the '.')."""
return self._getbyspec("ext")[0]
def read_binary(self):
"""Read and return a bytestring from reading the path."""
with self.open("rb") as f:
return f.read()
def read_text(self, encoding):
"""Read and return a Unicode string from reading the path."""
with self.open("r", encoding=encoding) as f:
return f.read()
def read(self, mode="r"):
"""Read and return a bytestring from reading the path."""
with self.open(mode) as f:
return f.read()
def readlines(self, cr=1):
"""Read and return a list of lines from the path. if cr is False, the
newline will be removed from the end of each line."""
mode = "r"
if not cr:
content = self.read(mode)
return content.split("\n")
else:
f = self.open(mode)
try:
return f.readlines()
finally:
f.close()
def load(self):
"""(deprecated) return object unpickled from self.read()"""
f = self.open("rb")
try:
import pickle
return error.checked_call(pickle.load, f)
finally:
f.close()
def move(self, target):
"""Move this path to target."""
if target.relto(self):
raise error.EINVAL(target, "cannot move path into a subdirectory of itself")
try:
self.rename(target)
except error.EXDEV: # invalid cross-device link
self.copy(target)
self.remove()
def fnmatch(self, pattern):
"""Return true if the basename/fullname matches the glob-'pattern'.
valid pattern characters::
* matches everything
? matches any single character
[seq] matches any character in seq
[!seq] matches any char not in seq
If the pattern contains a path-separator then the full path
is used for pattern matching and a '*' is prepended to the
pattern.
if the pattern doesn't contain a path-separator the pattern
is only matched against the basename.
"""
return FNMatcher(pattern)(self)
def relto(self, relpath):
"""Return a string which is the relative part of the path
to the given 'relpath'.
"""
if not isinstance(relpath, (str, LocalPath)):
raise TypeError(f"{relpath!r}: not a string or path object")
strrelpath = str(relpath)
if strrelpath and strrelpath[-1] != self.sep:
strrelpath += self.sep
# assert strrelpath[-1] == self.sep
# assert strrelpath[-2] != self.sep
strself = self.strpath
if sys.platform == "win32" or getattr(os, "_name", None) == "nt":
if os.path.normcase(strself).startswith(os.path.normcase(strrelpath)):
return strself[len(strrelpath) :]
elif strself.startswith(strrelpath):
return strself[len(strrelpath) :]
return ""
def ensure_dir(self, *args):
"""Ensure the path joined with args is a directory."""
return self.ensure(*args, dir=True)
def bestrelpath(self, dest):
"""Return a string which is a relative path from self
(assumed to be a directory) to dest such that
self.join(bestrelpath) == dest and if not such
path can be determined return dest.
"""
try:
if self == dest:
return os.curdir
base = self.common(dest)
if not base: # can be the case on windows
return str(dest)
self2base = self.relto(base)
reldest = dest.relto(base)
if self2base:
n = self2base.count(self.sep) + 1
else:
n = 0
lst = [os.pardir] * n
if reldest:
lst.append(reldest)
target = dest.sep.join(lst)
return target
except AttributeError:
return str(dest)
def exists(self):
return self.check()
def isdir(self):
return self.check(dir=1)
def isfile(self):
return self.check(file=1)
def parts(self, reverse=False):
"""Return a root-first list of all ancestor directories
plus the path itself.
"""
current = self
lst = [self]
while 1:
last = current
current = current.dirpath()
if last == current:
break
lst.append(current)
if not reverse:
lst.reverse()
return lst
def common(self, other):
"""Return the common part shared with the other path
or None if there is no common part.
"""
last = None
for x, y in zip(self.parts(), other.parts()):
if x != y:
return last
last = x
return last
def __add__(self, other):
"""Return new path object with 'other' added to the basename"""
return self.new(basename=self.basename + str(other))
def visit(self, fil=None, rec=None, ignore=NeverRaised, bf=False, sort=False):
"""Yields all paths below the current one
fil is a filter (glob pattern or callable), if not matching the
path will not be yielded, defaulting to None (everything is
returned)
rec is a filter (glob pattern or callable) that controls whether
a node is descended, defaulting to None
ignore is an Exception class that is ignoredwhen calling dirlist()
on any of the paths (by default, all exceptions are reported)
bf if True will cause a breadthfirst search instead of the
default depthfirst. Default: False
sort if True will sort entries within each directory level.
"""
yield from Visitor(fil, rec, ignore, bf, sort).gen(self)
def _sortlist(self, res, sort):
if sort:
if hasattr(sort, "__call__"):
warnings.warn(
DeprecationWarning(
"listdir(sort=callable) is deprecated and breaks on python3"
),
stacklevel=3,
)
res.sort(sort)
else:
res.sort()
def __fspath__(self):
return self.strpath
def __hash__(self):
s = self.strpath
if iswin32:
s = s.lower()
return hash(s)
def __eq__(self, other):
s1 = os.fspath(self)
try:
s2 = os.fspath(other)
except TypeError:
return False
if iswin32:
s1 = s1.lower()
try:
s2 = s2.lower()
except AttributeError:
return False
return s1 == s2
def __ne__(self, other):
return not (self == other)
def __lt__(self, other):
return os.fspath(self) < os.fspath(other)
def __gt__(self, other):
return os.fspath(self) > os.fspath(other)
def samefile(self, other):
"""Return True if 'other' references the same file as 'self'."""
other = os.fspath(other)
if not isabs(other):
other = abspath(other)
if self == other:
return True
if not hasattr(os.path, "samefile"):
return False
return error.checked_call(os.path.samefile, self.strpath, other)
def remove(self, rec=1, ignore_errors=False):
"""Remove a file or directory (or a directory tree if rec=1).
if ignore_errors is True, errors while removing directories will
be ignored.
"""
if self.check(dir=1, link=0):
if rec:
# force remove of readonly files on windows
if iswin32:
self.chmod(0o700, rec=1)
import shutil
error.checked_call(
shutil.rmtree, self.strpath, ignore_errors=ignore_errors
)
else:
error.checked_call(os.rmdir, self.strpath)
else:
if iswin32:
self.chmod(0o700)
error.checked_call(os.remove, self.strpath)
def computehash(self, hashtype="md5", chunksize=524288):
"""Return hexdigest of hashvalue for this file."""
try:
try:
import hashlib as mod
except ImportError:
if hashtype == "sha1":
hashtype = "sha"
mod = __import__(hashtype)
hash = getattr(mod, hashtype)()
except (AttributeError, ImportError):
raise ValueError(f"Don't know how to compute {hashtype!r} hash")
f = self.open("rb")
try:
while 1:
buf = f.read(chunksize)
if not buf:
return hash.hexdigest()
hash.update(buf)
finally:
f.close()
def new(self, **kw):
"""Create a modified version of this path.
the following keyword arguments modify various path parts::
a:/some/path/to/a/file.ext
xx drive
xxxxxxxxxxxxxxxxx dirname
xxxxxxxx basename
xxxx purebasename
xxx ext
"""
obj = object.__new__(self.__class__)
if not kw:
obj.strpath = self.strpath
return obj
drive, dirname, basename, purebasename, ext = self._getbyspec(
"drive,dirname,basename,purebasename,ext"
)
if "basename" in kw:
if "purebasename" in kw or "ext" in kw:
raise ValueError(f"invalid specification {kw!r}")
else:
pb = kw.setdefault("purebasename", purebasename)
try:
ext = kw["ext"]
except KeyError:
pass
else:
if ext and not ext.startswith("."):
ext = "." + ext
kw["basename"] = pb + ext
if "dirname" in kw and not kw["dirname"]:
kw["dirname"] = drive
else:
kw.setdefault("dirname", dirname)
kw.setdefault("sep", self.sep)
obj.strpath = normpath("{dirname}{sep}{basename}".format(**kw))
return obj
def _getbyspec(self, spec: str) -> list[str]:
"""See new for what 'spec' can be."""
res = []
parts = self.strpath.split(self.sep)
args = filter(None, spec.split(","))
for name in args:
if name == "drive":
res.append(parts[0])
elif name == "dirname":
res.append(self.sep.join(parts[:-1]))
else:
basename = parts[-1]
if name == "basename":
res.append(basename)
else:
i = basename.rfind(".")
if i == -1:
purebasename, ext = basename, ""
else:
purebasename, ext = basename[:i], basename[i:]
if name == "purebasename":
res.append(purebasename)
elif name == "ext":
res.append(ext)
else:
raise ValueError(f"invalid part specification {name!r}")
return res
def dirpath(self, *args, **kwargs):
"""Return the directory path joined with any given path arguments."""
if not kwargs:
path = object.__new__(self.__class__)
path.strpath = dirname(self.strpath)
if args:
path = path.join(*args)
return path
return self.new(basename="").join(*args, **kwargs)
def join(self, *args: os.PathLike[str], abs: bool = False) -> LocalPath:
"""Return a new path by appending all 'args' as path
components. if abs=1 is used restart from root if any
of the args is an absolute path.
"""
sep = self.sep
strargs = [os.fspath(arg) for arg in args]
strpath = self.strpath
if abs:
newargs: list[str] = []
for arg in reversed(strargs):
if isabs(arg):
strpath = arg
strargs = newargs
break
newargs.insert(0, arg)
# special case for when we have e.g. strpath == "/"
actual_sep = "" if strpath.endswith(sep) else sep
for arg in strargs:
arg = arg.strip(sep)
if iswin32:
# allow unix style paths even on windows.
arg = arg.strip("/")
arg = arg.replace("/", sep)
strpath = strpath + actual_sep + arg
actual_sep = sep
obj = object.__new__(self.__class__)
obj.strpath = normpath(strpath)
return obj
def open(self, mode="r", ensure=False, encoding=None):
"""Return an opened file with the given mode.
If ensure is True, create parent directories if needed.
"""
if ensure:
self.dirpath().ensure(dir=1)
if encoding:
return error.checked_call(
io.open,
self.strpath,
mode,
encoding=encoding,
)
return error.checked_call(open, self.strpath, mode)
def _fastjoin(self, name):
child = object.__new__(self.__class__)
child.strpath = self.strpath + self.sep + name
return child
def islink(self):
return islink(self.strpath)
def check(self, **kw):
"""Check a path for existence and properties.
Without arguments, return True if the path exists, otherwise False.
valid checkers::
file = 1 # is a file
file = 0 # is not a file (may not even exist)
dir = 1 # is a dir
link = 1 # is a link
exists = 1 # exists
You can specify multiple checker definitions, for example::
path.check(file=1, link=1) # a link pointing to a file
"""
if not kw:
return exists(self.strpath)
if len(kw) == 1:
if "dir" in kw:
return not kw["dir"] ^ isdir(self.strpath)
if "file" in kw:
return not kw["file"] ^ isfile(self.strpath)
if not kw:
kw = {"exists": 1}
return Checkers(self)._evaluate(kw)
_patternchars = set("*?[" + os.sep)
def listdir(self, fil=None, sort=None):
"""List directory contents, possibly filter by the given fil func
and possibly sorted.
"""
if fil is None and sort is None:
names = error.checked_call(os.listdir, self.strpath)
return map_as_list(self._fastjoin, names)
if isinstance(fil, str):
if not self._patternchars.intersection(fil):
child = self._fastjoin(fil)
if exists(child.strpath):
return [child]
return []
fil = FNMatcher(fil)
names = error.checked_call(os.listdir, self.strpath)
res = []
for name in names:
child = self._fastjoin(name)
if fil is None or fil(child):
res.append(child)
self._sortlist(res, sort)
return res
def size(self) -> int:
"""Return size of the underlying file object"""
return self.stat().size
def mtime(self) -> float:
"""Return last modification time of the path."""
return self.stat().mtime
def copy(self, target, mode=False, stat=False):
"""Copy path to target.
If mode is True, will copy permission from path to target.
If stat is True, copy permission, last modification
time, last access time, and flags from path to target.
"""
if self.check(file=1):
if target.check(dir=1):
target = target.join(self.basename)
assert self != target
copychunked(self, target)
if mode:
copymode(self.strpath, target.strpath)
if stat:
copystat(self, target)
else:
def rec(p):
return p.check(link=0)
for x in self.visit(rec=rec):
relpath = x.relto(self)
newx = target.join(relpath)
newx.dirpath().ensure(dir=1)
if x.check(link=1):
newx.mksymlinkto(x.readlink())
continue
elif x.check(file=1):
copychunked(x, newx)
elif x.check(dir=1):
newx.ensure(dir=1)
if mode:
copymode(x.strpath, newx.strpath)
if stat:
copystat(x, newx)
def rename(self, target):
"""Rename this path to target."""
target = os.fspath(target)
return error.checked_call(os.rename, self.strpath, target)
def dump(self, obj, bin=1):
"""Pickle object into path location"""
f = self.open("wb")
import pickle
try:
error.checked_call(pickle.dump, obj, f, bin)
finally:
f.close()
def mkdir(self, *args):
"""Create & return the directory joined with args."""
p = self.join(*args)
error.checked_call(os.mkdir, os.fspath(p))
return p
def write_binary(self, data, ensure=False):
"""Write binary data into path. If ensure is True create
missing parent directories.
"""
if ensure:
self.dirpath().ensure(dir=1)
with self.open("wb") as f:
f.write(data)
def write_text(self, data, encoding, ensure=False):
"""Write text data into path using the specified encoding.
If ensure is True create missing parent directories.
"""
if ensure:
self.dirpath().ensure(dir=1)
with self.open("w", encoding=encoding) as f:
f.write(data)
def write(self, data, mode="w", ensure=False):
"""Write data into path. If ensure is True create
missing parent directories.
"""
if ensure:
self.dirpath().ensure(dir=1)
if "b" in mode:
if not isinstance(data, bytes):
raise ValueError("can only process bytes")
else:
if not isinstance(data, str):
if not isinstance(data, bytes):
data = str(data)
else:
data = data.decode(sys.getdefaultencoding())
f = self.open(mode)
try:
f.write(data)
finally:
f.close()
def _ensuredirs(self):
parent = self.dirpath()
if parent == self:
return self
if parent.check(dir=0):
parent._ensuredirs()
if self.check(dir=0):
try:
self.mkdir()
except error.EEXIST:
# race condition: file/dir created by another thread/process.
# complain if it is not a dir
if self.check(dir=0):
raise
return self
def ensure(self, *args, **kwargs):
"""Ensure that an args-joined path exists (by default as
a file). if you specify a keyword argument 'dir=True'
then the path is forced to be a directory path.
"""
p = self.join(*args)
if kwargs.get("dir", 0):
return p._ensuredirs()
else:
p.dirpath()._ensuredirs()
if not p.check(file=1):
p.open("wb").close()
return p
@overload
def stat(self, raising: Literal[True] = ...) -> Stat: ...
@overload
def stat(self, raising: Literal[False]) -> Stat | None: ...
def stat(self, raising: bool = True) -> Stat | None:
"""Return an os.stat() tuple."""
if raising:
return Stat(self, error.checked_call(os.stat, self.strpath))
try:
return Stat(self, os.stat(self.strpath))
except KeyboardInterrupt:
raise
except Exception:
return None
def lstat(self) -> Stat:
"""Return an os.lstat() tuple."""
return Stat(self, error.checked_call(os.lstat, self.strpath))
def setmtime(self, mtime=None):
"""Set modification time for the given path. if 'mtime' is None
(the default) then the file's mtime is set to current time.
Note that the resolution for 'mtime' is platform dependent.
"""
if mtime is None:
return error.checked_call(os.utime, self.strpath, mtime)
try:
return error.checked_call(os.utime, self.strpath, (-1, mtime))
except error.EINVAL:
return error.checked_call(os.utime, self.strpath, (self.atime(), mtime))
def chdir(self):
"""Change directory to self and return old current directory"""
try:
old = self.__class__()
except error.ENOENT:
old = None