-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathpaths.py
More file actions
1286 lines (964 loc) · 34 KB
/
paths.py
File metadata and controls
1286 lines (964 loc) · 34 KB
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
#!/usr/bin/env python
#
# paths.py
"""
Functions for paths and files.
.. versionchanged:: 1.0.0
Removed ``relpath2``.
Use :func:`domdf_python_tools.paths.relpath` instead.
"""
#
# Copyright © 2018-2020 Dominic Davis-Foster <dominic@davis-foster.co.uk>
#
# Parts of the docstrings, the PathPlus class and the DirComparator class
# based on Python and its Documentation
# Licensed under the Python Software Foundation License Version 2.
# Copyright © 2001-2021 Python Software Foundation. All rights reserved.
# Copyright © 2000 BeOpen.com. All rights reserved.
# Copyright © 1995-2000 Corporation for National Research Initiatives. All rights reserved.
# Copyright © 1991-1995 Stichting Mathematisch Centrum. All rights reserved.
#
# copytree based on https://stackoverflow.com/a/12514470/3092681
# Copyright © 2012 atzz
# Licensed under CC-BY-SA
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
# OR OTHER DEALINGS IN THE SOFTWARE.
#
# stdlib
import contextlib
import filecmp
import fnmatch
import gzip
import json
import os
import pathlib
import shutil
import stat
import sys
import tempfile
import urllib.parse
from collections import defaultdict, deque
from operator import methodcaller
from typing import (
IO,
Any,
Callable,
ContextManager,
Dict,
Iterable,
Iterator,
List,
Optional,
Sequence,
Type,
TypeVar,
Union
)
# this package
from domdf_python_tools.compat import nullcontext
from domdf_python_tools.typing import JsonLibrary, PathLike
__all__ = [
"append",
"copytree",
"delete",
"maybe_make",
"parent_path",
"read",
"relpath",
"write",
"clean_writer",
"make_executable",
"PathPlus",
"PosixPathPlus",
"WindowsPathPlus",
"in_directory",
"_P",
"_PP",
"traverse_to_file",
"matchglob",
"unwanted_dirs",
"TemporaryPathPlus",
"sort_paths",
"DirComparator",
"compare_dirs",
]
NEWLINE_DEFAULT = type("NEWLINE_DEFAULT", (object, ), {"__repr__": lambda self: "NEWLINE_DEFAULT"})()
_P = TypeVar("_P", bound=pathlib.Path)
"""
.. versionadded:: 0.11.0
.. versionchanged:: 1.7.0 Now bound to :class:`pathlib.Path`.
"""
_PP = TypeVar("_PP", bound="PathPlus")
"""
.. versionadded:: 2.3.0
"""
unwanted_dirs = (
".git",
".hg",
"venv",
".venv",
".mypy_cache",
"__pycache__",
".pytest_cache",
".tox",
".tox4",
".nox",
"__pypackages__",
)
"""
A list of directories which will likely be unwanted when searching directory trees for files.
.. versionadded:: 2.3.0
.. versionchanged:: 2.9.0 Added ``.hg`` (`mercurial <https://www.mercurial-scm.org>`_)
.. versionchanged:: 3.0.0 Added ``__pypackages__`` (:pep:`582`)
.. versionchanged:: 3.2.0 Added ``.nox`` (https://nox.thea.codes/)
"""
def append(var: str, filename: PathLike, **kwargs) -> int:
"""
Append ``var`` to the file ``filename`` in the current directory.
.. TODO:: make this the file in the given directory, by default the current directory
:param var: The value to append to the file
:param filename: The file to append to
"""
kwargs.setdefault("encoding", "UTF-8")
with open(os.path.join(os.getcwd(), filename), 'a', **kwargs) as f: # noqa: ENC001
return f.write(var)
def copytree(
src: PathLike,
dst: PathLike,
symlinks: bool = False,
ignore: Optional[Callable] = None,
) -> PathLike:
"""
Alternative to :func:`shutil.copytree` to support copying to a directory that already exists.
Based on https://stackoverflow.com/a/12514470 by https://stackoverflow.com/users/23252/atzz
In Python 3.8 and above :func:`shutil.copytree` takes a ``dirs_exist_ok`` argument,
which has the same result.
:param src: Source file to copy
:param dst: Destination to copy file to
:param symlinks: Whether to represent symbolic links in the source as symbolic
links in the destination. If false or omitted, the contents and metadata
of the linked files are copied to the new tree. When symlinks is false,
if the file pointed by the symlink doesn't exist, an exception will be
added in the list of errors raised in an Error exception at the end of
the copy process. You can set the optional ignore_dangling_symlinks
flag to true if you want to silence this exception. Notice that this
option has no effect on platforms that don’t support :func:`os.symlink`.
:param ignore: A callable that will receive as its arguments the source
directory, and a list of its contents. The ignore callable will be
called once for each directory that is copied. The callable must return
a sequence of directory and file names relative to the current
directory (i.e. a subset of the items in its second argument); these
names will then be ignored in the copy process.
:func:`shutil.ignore_patterns` can be used to create such a callable
that ignores names based on
glob-style patterns.
"""
for item in os.listdir(src):
s = os.path.join(src, item)
d = os.path.join(dst, item)
if os.path.isdir(s):
shutil.copytree(s, d, symlinks, ignore)
else:
shutil.copy2(s, d)
return dst
def delete(filename: PathLike, **kwargs):
"""
Delete the file in the current directory.
.. TODO:: make this the file in the given directory, by default the current directory
:param filename: The file to delete
"""
os.remove(os.path.join(os.getcwd(), filename), **kwargs)
def maybe_make(directory: PathLike, mode: int = 0o777, parents: bool = False):
"""
Create a directory at the given path, but only if the directory does not already exist.
.. attention::
This will fail silently if a file with the same name already exists.
This appears to be due to the behaviour of :func:`os.mkdir`.
:param directory: Directory to create
:param mode: Combined with the process's umask value to determine the file mode and access flags
:param parents: If :py:obj:`False` (the default), a missing parent raises a :class:`FileNotFoundError`.
If :py:obj:`True`, any missing parents of this path are created as needed; they are created with the
default permissions without taking mode into account (mimicking the POSIX ``mkdir -p`` command).
:no-default parents:
.. versionchanged:: 1.6.0 Removed the ``'exist_ok'`` option, since it made no sense in this context.
"""
if not isinstance(directory, pathlib.Path):
directory = pathlib.Path(directory)
try:
directory.mkdir(mode, parents, exist_ok=True)
except FileExistsError:
pass
def parent_path(path: PathLike) -> pathlib.Path:
"""
Returns the path of the parent directory for the given file or directory.
:param path: Path to find the parent for
:return: The parent directory
"""
if not isinstance(path, pathlib.Path):
path = pathlib.Path(path)
return path.parent
def read(filename: PathLike, **kwargs) -> str:
"""
Read a file in the current directory (in text mode).
.. TODO:: make this the file in the given directory, by default the current directory
:param filename: The file to read from.
:return: The contents of the file.
"""
kwargs.setdefault("encoding", "UTF-8")
with open(os.path.join(os.getcwd(), filename), **kwargs) as f: # noqa: ENC001
return f.read()
def relpath(path: PathLike, relative_to: Optional[PathLike] = None) -> pathlib.Path:
"""
Returns the path for the given file or directory relative to the given
directory or, if that would require path traversal, returns the absolute path.
:param path: Path to find the relative path for
:param relative_to: The directory to find the path relative to.
Defaults to the current directory.
:no-default relative_to:
""" # noqa: D400
if not isinstance(path, pathlib.Path):
path = pathlib.Path(path)
abs_path = path.absolute()
if relative_to is None:
relative_to = pathlib.Path().absolute()
if not isinstance(relative_to, pathlib.Path):
relative_to = pathlib.Path(relative_to)
relative_to = relative_to.absolute()
try:
return abs_path.relative_to(relative_to)
except ValueError:
return abs_path
def write(var: str, filename: PathLike, **kwargs) -> None:
"""
Write a variable to file in the current directory.
.. TODO:: make this the file in the given directory, by default the current directory
:param var: The value to write to the file.
:param filename: The file to write to.
"""
kwargs.setdefault("encoding", "UTF-8")
with open(os.path.join(os.getcwd(), filename), 'w', **kwargs) as f: # noqa: ENC001
f.write(var)
def clean_writer(string: str, fp: IO) -> None:
"""
Write string to ``fp`` without trailing spaces.
:param string:
:param fp:
"""
# this package
from domdf_python_tools.stringlist import StringList
buffer = StringList(string)
buffer.blankline(ensure_single=True)
fp.write(str(buffer))
def make_executable(filename: PathLike) -> None:
"""
Make the given file executable.
:param filename:
"""
if not isinstance(filename, pathlib.Path):
filename = pathlib.Path(filename)
st = os.stat(str(filename))
os.chmod(str(filename), st.st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
@contextlib.contextmanager
def in_directory(directory: PathLike):
"""
Context manager to change into the given directory for the
duration of the ``with`` block.
:param directory:
""" # noqa: D400
oldwd = os.getcwd()
try:
os.chdir(str(directory))
yield
finally:
os.chdir(oldwd)
class PathPlus(pathlib.Path):
"""
Subclass of :class:`pathlib.Path` with additional methods and a default encoding of UTF-8.
Path represents a filesystem path but, unlike :class:`pathlib.PurePath`, also offers
methods to do system calls on path objects.
Depending on your system, instantiating a :class:`~.PathPlus` will return
either a :class:`~.PosixPathPlus` or a :class:`~.WindowsPathPlus`. object.
You can also instantiate a :class:`~.PosixPathPlus` or :class:`WindowsPath` directly,
but cannot instantiate a :class:`~.WindowsPathPlus` on a POSIX system or vice versa.
.. versionadded:: 0.3.8
.. versionchanged:: 0.5.1 Defaults to Unix line endings (``LF``) on all platforms.
"""
__slots__ = ()
if sys.version_info < (3, 11):
_accessor = pathlib._normal_accessor # type: ignore
_closed = False
def _init(self, *args, **kwargs):
pass
@classmethod
def _from_parts(cls, args, init=True):
return super()._from_parts(args) # type: ignore
def __new__(cls: Type[_PP], *args, **kwargs) -> _PP: # noqa: D102
if cls is PathPlus:
cls = WindowsPathPlus if os.name == "nt" else PosixPathPlus # type: ignore
self = cls._from_parts(args, init=False)
if not self._flavour.is_supported:
raise NotImplementedError(f"cannot instantiate {cls.__name__!r} on your system")
self._init()
return self
def make_executable(self) -> None:
"""
Make the file executable.
.. versionadded:: 0.3.8
"""
make_executable(self)
def write_clean(
self,
string: str,
encoding: Optional[str] = "UTF-8",
errors: Optional[str] = None,
):
"""
Write to the file without trailing whitespace, and with a newline at the end of the file.
.. versionadded:: 0.3.8
:param string:
:param encoding: The encoding to write to the file in.
:param errors:
"""
with self.open('w', encoding=encoding, errors=errors) as fp:
clean_writer(string, fp)
def maybe_make(
self,
mode: int = 0o777,
parents: bool = False,
):
"""
Create a directory at this path, but only if the directory does not already exist.
.. versionadded:: 0.3.8
:param mode: Combined with the process’ umask value to determine the file mode and access flags
:param parents: If :py:obj:`False` (the default), a missing parent raises a :class:`FileNotFoundError`.
If :py:obj:`True`, any missing parents of this path are created as needed; they are created with the
default permissions without taking mode into account (mimicking the POSIX mkdir -p command).
:no-default parents:
.. versionchanged:: 1.6.0 Removed the ``'exist_ok'`` option, since it made no sense in this context.
.. attention::
This will fail silently if a file with the same name already exists.
This appears to be due to the behaviour of :func:`os.mkdir`.
"""
try:
self.mkdir(mode, parents, exist_ok=True)
except FileExistsError:
pass
def append_text(
self,
string: str,
encoding: Optional[str] = "UTF-8",
errors: Optional[str] = None,
):
"""
Open the file in text mode, append the given string to it, and close the file.
.. versionadded:: 0.3.8
:param string:
:param encoding: The encoding to write to the file in.
:param errors:
"""
with self.open('a', encoding=encoding, errors=errors) as fp:
fp.write(string)
def write_text(
self,
data: str,
encoding: Optional[str] = "UTF-8",
errors: Optional[str] = None,
newline: Optional[str] = NEWLINE_DEFAULT,
) -> int:
"""
Open the file in text mode, write to it, and close the file.
.. versionadded:: 0.3.8
:param data:
:param encoding: The encoding to write to the file in.
:param errors:
:param newline:
:default newline: `universal newlines <https://docs.python.org/3/glossary.html#term-universal-newlines>`__ for reading, Unix line endings (``LF``) for writing.
.. versionchanged:: 3.1.0
Added the ``newline`` argument to match Python 3.10.
(see :github:pull:`22420 <python/cpython>`)
"""
if not isinstance(data, str):
raise TypeError(f'data must be str, not {data.__class__.__name__}')
with self.open(mode='w', encoding=encoding, errors=errors, newline=newline) as f:
return f.write(data)
def write_lines(
self,
data: Iterable[str],
encoding: Optional[str] = "UTF-8",
errors: Optional[str] = None,
*,
trailing_whitespace: bool = False
) -> None:
"""
Write the given list of lines to the file without trailing whitespace.
.. versionadded:: 0.5.0
:param data:
:param encoding: The encoding to write to the file in.
:param errors:
:param trailing_whitespace: If :py:obj:`True` trailing whitespace is preserved.
.. versionchanged:: 2.4.0 Added the ``trailing_whitespace`` option.
"""
if trailing_whitespace:
data = list(data)
if data[-1].strip():
data.append('')
self.write_text('\n'.join(data), encoding=encoding, errors=errors)
else:
self.write_clean('\n'.join(data), encoding=encoding, errors=errors)
def read_text(
self,
encoding: Optional[str] = "UTF-8",
errors: Optional[str] = None,
) -> str:
"""
Open the file in text mode, read it, and close the file.
.. versionadded:: 0.3.8
:param encoding: The encoding to write to the file in.
:param errors:
:return: The content of the file.
"""
return super().read_text(encoding=encoding, errors=errors)
def read_lines(
self,
encoding: Optional[str] = "UTF-8",
errors: Optional[str] = None,
) -> List[str]:
"""
Open the file in text mode, return a list containing the lines in the file,
and close the file.
.. versionadded:: 0.5.0
:param encoding: The encoding to write to the file in.
:param errors:
:return: The content of the file.
""" # noqa: D400
return self.read_text(encoding=encoding, errors=errors).split('\n')
def open( # type: ignore # noqa: A003 # pylint: disable=redefined-builtin
self,
mode: str = 'r',
buffering: int = -1,
encoding: Optional[str] = "UTF-8",
errors: Optional[str] = None,
newline: Optional[str] = NEWLINE_DEFAULT,
) -> IO[Any]:
"""
Open the file pointed by this path and return a file object, as
the built-in :func:`open` function does.
.. versionadded:: 0.3.8
:param mode: The mode to open the file in.
:default mode: ``'r'`` (read only)
:param buffering:
:param encoding:
:param errors:
:param newline:
:default newline: `universal newlines <https://docs.python.org/3/glossary.html#term-universal-newlines>`__ for reading, Unix line endings (``LF``) for writing.
:rtype:
.. versionchanged:: 0.5.1
Defaults to Unix line endings (``LF``) on all platforms.
""" # noqa: D400
if 'b' in mode:
encoding = None
newline = None
if newline is NEWLINE_DEFAULT:
if 'r' in mode:
newline = None
else:
newline = '\n'
return super().open(
mode,
buffering=buffering,
encoding=encoding,
errors=errors,
newline=newline,
)
def dump_json(
self,
data: Any,
encoding: Optional[str] = "UTF-8",
errors: Optional[str] = None,
json_library: JsonLibrary = json, # type: ignore
*,
compress: bool = False,
**kwargs,
) -> None:
r"""
Dump ``data`` to the file as JSON.
.. versionadded:: 0.5.0
:param data: The object to serialise to JSON.
:param encoding: The encoding to write to the file in.
:param errors:
:param json_library: The JSON serialisation library to use.
:default json_library: :mod:`json`
:param compress: Whether to compress the JSON file using gzip.
:param \*\*kwargs: Keyword arguments to pass to the JSON serialisation function.
:rtype:
.. versionchanged:: 1.0.0
Now uses :meth:`PathPlus.write_clean <domdf_python_tools.paths.PathPlus.write_clean>`
rather than :meth:`PathPlus.write_text <domdf_python_tools.paths.PathPlus.write_text>`,
and as a result returns :py:obj:`None` rather than :class:`int`.
.. versionchanged:: 1.9.0 Added the ``compress`` keyword-only argument.
"""
if compress:
with gzip.open(self, mode="wt", encoding=encoding, errors=errors) as fp:
fp.write(json_library.dumps(data, **kwargs))
else:
self.write_clean(
json_library.dumps(data, **kwargs),
encoding=encoding,
errors=errors,
)
def load_json(
self,
encoding: Optional[str] = "UTF-8",
errors: Optional[str] = None,
json_library: JsonLibrary = json, # type: ignore
*,
decompress: bool = False,
**kwargs,
) -> Any:
r"""
Load JSON data from the file.
.. versionadded:: 0.5.0
:param encoding: The encoding to write to the file in.
:param errors:
:param json_library: The JSON serialisation library to use.
:default json_library: :mod:`json`
:param decompress: Whether to decompress the JSON file using gzip.
Will raise an exception if the file is not compressed.
:param \*\*kwargs: Keyword arguments to pass to the JSON deserialisation function.
:return: The deserialised JSON data.
.. versionchanged:: 1.9.0 Added the ``compress`` keyword-only argument.
"""
if decompress:
with gzip.open(self, mode="rt", encoding=encoding, errors=errors) as fp:
content = fp.read()
else:
content = self.read_text(encoding=encoding, errors=errors)
return json_library.loads(
content,
**kwargs,
)
if sys.version_info < (3, 10): # pragma: no cover (py310+)
def is_mount(self) -> bool:
"""
Check if this path is a POSIX mount point.
.. versionadded:: 0.3.8 for Python 3.7 and above
.. versionadded:: 0.11.0 for Python 3.6
"""
# Need to exist and be a dir
if not self.exists() or not self.is_dir():
return False
# https://github.com/python/cpython/pull/18839/files
try:
parent_dev = self.parent.stat().st_dev
except OSError:
return False
dev = self.stat().st_dev
if dev != parent_dev:
return True
ino = self.stat().st_ino
parent_ino = self.parent.stat().st_ino
return ino == parent_ino
if sys.version_info < (3, 8): # pragma: no cover (py38+)
def rename(self: _P, target: Union[str, pathlib.PurePath]) -> _P: # type: ignore
"""
Rename this path to the target path.
The target path may be absolute or relative. Relative paths are
interpreted relative to the current working directory, *not* the
directory of the Path object.
.. versionadded:: 0.3.8 for Python 3.8 and above
.. versionadded:: 0.11.0 for Python 3.6 and Python 3.7
:param target:
:returns: The new Path instance pointing to the target path.
"""
os.rename(self, target)
return self.__class__(target)
def replace(self: _P, target: Union[str, pathlib.PurePath]) -> _P: # type: ignore
"""
Rename this path to the target path, overwriting if that path exists.
The target path may be absolute or relative. Relative paths are
interpreted relative to the current working directory, *not* the
directory of the Path object.
Returns the new Path instance pointing to the target path.
.. versionadded:: 0.3.8 for Python 3.8 and above
.. versionadded:: 0.11.0 for Python 3.6 and Python 3.7
:param target:
:returns: The new Path instance pointing to the target path.
"""
os.replace(self, target)
return self.__class__(target)
def unlink(self, missing_ok: bool = False) -> None:
"""
Remove this file or link.
If the path is a directory, use :meth:`~domdf_python_tools.paths.PathPlus.rmdir()` instead.
.. versionadded:: 0.3.8 for Python 3.8 and above
.. versionadded:: 0.11.0 for Python 3.6 and Python 3.7
"""
try:
os.unlink(self)
except FileNotFoundError:
if not missing_ok:
raise
def __enter__(self):
return self
def __exit__(self, t, v, tb):
# https://bugs.python.org/issue39682
# In previous versions of pathlib, this method marked this path as
# closed; subsequent attempts to perform I/O would raise an IOError.
# This functionality was never documented, and had the effect of
# making Path objects mutable, contrary to PEP 428. In Python 3.9 the
# _closed attribute was removed, and this method made a no-op.
# This method and __enter__()/__exit__() should be deprecated and
# removed in the future.
pass
if sys.version_info < (3, 9): # pragma: no cover (py39+)
def is_relative_to(self, *other: Union[str, os.PathLike]) -> bool:
r"""
Returns whether the path is relative to another path.
.. versionadded:: 0.3.8 for Python 3.9 and above.
.. latex:vspace:: -10px
.. versionadded:: 1.4.0 for Python 3.6 and Python 3.7.
.. latex:vspace:: -10px
:param \*other:
.. latex:vspace:: -20px
:rtype:
.. latex:vspace:: -20px
"""
try:
self.relative_to(*other)
return True
except ValueError:
return False
def abspath(self) -> "PathPlus":
"""
Return the absolute version of the path.
.. versionadded:: 1.3.0
"""
return self.__class__(os.path.abspath(self))
def iterchildren(
self: _PP,
exclude_dirs: Optional[Iterable[str]] = unwanted_dirs,
match: Optional[str] = None,
matchcase: bool = True,
) -> Iterator[_PP]:
"""
Returns an iterator over all children (files and directories) of the current path object.
.. versionadded:: 2.3.0
:param exclude_dirs: A list of directory names which should be excluded from the output,
together with their children.
:param match: A pattern to match filenames against.
The pattern should be in the format taken by :func:`~.matchglob`.
:param matchcase: Whether the filename's case should match the pattern.
:rtype:
.. versionchanged:: 2.5.0 Added the ``matchcase`` option.
"""
if not self.abspath().is_dir():
return
if exclude_dirs is None:
exclude_dirs = ()
if match and not os.path.isabs(match) and self.is_absolute():
match = (self / match).as_posix()
file: _PP
for file in self.iterdir():
parts = file.parts
if any(d in parts for d in exclude_dirs):
continue
if match is None or (match is not None and matchglob(file, match, matchcase)):
yield file
if file.is_dir():
yield from file.iterchildren(exclude_dirs, match)
@classmethod
def from_uri(cls: Type[_PP], uri: str) -> _PP:
"""
Construct a :class:`~.PathPlus` from a ``file`` URI returned by :meth:`pathlib.PurePath.as_uri`.
.. versionadded:: 2.9.0
:param uri:
:rtype: :class:`~.PathPlus`
"""
parseresult = urllib.parse.urlparse(uri)
if parseresult.scheme != "file":
raise ValueError(f"Unsupported URI scheme {parseresult.scheme!r}")
if parseresult.params or parseresult.query or parseresult.fragment:
raise ValueError("Malformed file URI")
if sys.platform == "win32": # pragma: no cover (!Windows)
if parseresult.netloc:
path = ''.join([
"//",
urllib.parse.unquote_to_bytes(parseresult.netloc).decode("UTF-8"),
urllib.parse.unquote_to_bytes(parseresult.path).decode("UTF-8"),
])
else:
path = urllib.parse.unquote_to_bytes(parseresult.path).decode("UTF-8").lstrip('/')
else: # pragma: no cover (Windows)
if parseresult.netloc:
raise ValueError("Malformed file URI")
path = urllib.parse.unquote_to_bytes(parseresult.path).decode("UTF-8")
return cls(path)
def move(self: _PP, dst: PathLike) -> _PP:
"""
Recursively move ``self`` to ``dst``.
``self`` may be a file or a directory.
See :func:`shutil.move` for more details.
.. versionadded:: 3.2.0
:param dst:
:returns: The new location of ``self``.
:rtype: :class:`~.PathPlus`
"""
new_path = shutil.move(os.fspath(self), dst)
return self.__class__(new_path)
def stream(self, chunk_size: int = 1024) -> Iterator[bytes]:
"""
Stream the file in ``chunk_size`` sized chunks.
:param chunk_size: The chunk size, in bytes
.. versionadded:: 3.2.0
"""
with self.open("rb") as fp:
while True:
chunk = fp.read(chunk_size)
if not chunk:
break
yield chunk
class PosixPathPlus(PathPlus, pathlib.PurePosixPath):
"""
:class:`~.PathPlus` subclass for non-Windows systems.
On a POSIX system, instantiating a :class:`~.PathPlus` object should return an instance of this class.
.. versionadded:: 0.3.8
"""
__slots__ = ()
class WindowsPathPlus(PathPlus, pathlib.PureWindowsPath):
"""
:class:`~.PathPlus` subclass for Windows systems.
On a Windows system, instantiating a :class:`~.PathPlus` object should return an instance of this class.
.. versionadded:: 0.3.8
.. autoclasssumm:: WindowsPathPlus
:autosummary-sections: ;;
The following methods are unsupported on Windows:
* :meth:`~pathlib.Path.group`
* :meth:`~pathlib.Path.is_mount`
* :meth:`~pathlib.Path.owner`
"""
__slots__ = ()
def owner(self): # pragma: no cover
"""
Unsupported on Windows.