-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
1224 lines (1048 loc) · 38.2 KB
/
main.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
"""
Copyright (c) 2023 Gou Haoming
doFolder is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
import os
import re
from typing import (
Any,
Union,
Callable,
Literal,
List,
Tuple,
Iterable,
TypeVar,
Generic,
IO,
Dict,
overload,
Set,
)
import shutil
import copy
from watchdog.observers import Observer
from watchdog.events import (
FileSystemEventHandler,
FileSystemEvent,
FileSystemMovedEvent,
EVENT_TYPE_CREATED,
EVENT_TYPE_DELETED,
EVENT_TYPE_MODIFIED,
)
import hashlib
import logging
from concurrent.futures import ThreadPoolExecutor
from specialStr import Path
import base64
import json
from concurrent.futures import ThreadPoolExecutor, _base
import time
__all__ = ["File", "Folder", "Path"]
EVENT_TYPES = Literal["created", "deleted", "modified"]
SearchCondition = Union[str, re.Pattern, Callable[[Union["File", "Folder"]], bool]]
FormatedMatching = Tuple[
Callable[[Union["File", "Folder"]], bool], int, Union[int, None]
]
UnformattedMatching = Union[
SearchCondition, Tuple[SearchCondition, int, Union[int, None]]
]
_T = TypeVar("_T", bound="_HasName")
_U = TypeVar("_U")
class RuntimeError(Exception):
def __init__(self, error: BaseException) -> None:
super().__init__(str(error))
self.error = error
class DisabledError(Exception):
pass
class UnknownError(Exception):
def __init__(self) -> None:
super().__init__(
"Sorry, an unknown error has occurred. This could have been due to an oversight by the author. If you feel the same way, open an issue on Gitee(https://gitee.com/kuankuan2007/do-folder) or Github(https://github.com/kuankuan2007/do-folder)"
)
def tryRun(fn: Callable[..., _U]) -> Union[_U, RuntimeError]:
try:
return fn()
except BaseException as e:
return RuntimeError(e)
class _HasName(Generic[_T]):
name: str
class _FolderUpdateHeader(FileSystemEventHandler):
def __init__(self, target: "Folder"):
self.target = target
def on_moved(self, event: FileSystemMovedEvent):
self.target._update(
Path(event.src_path).findRest(self.target.path),
EVENT_TYPE_DELETED,
Path(event.src_path),
event.is_directory,
)
self.target._update(
Path(event.dest_path).findRest(self.target.path),
EVENT_TYPE_CREATED,
Path(event.dest_path),
event.is_directory,
)
def on_deleted(self, event: FileSystemEvent):
self.target._update(
Path(event.src_path).findRest(self.target.path),
event.event_type,
Path(event.src_path),
event.is_directory,
)
def on_created(self, event: FileSystemEvent):
self.target._update(
Path(event.src_path).findRest(self.target.path),
event.event_type,
Path(event.src_path),
event.is_directory,
)
def on_modified(self, event: FileSystemEvent):
if event.is_directory:
return
self.target._update(
Path(event.src_path).findRest(self.target.path),
event.event_type,
Path(event.src_path),
event.is_directory,
)
class FolderOrFileNotFoundError(Exception):
def __init__(self, reason):
self.reason = reason
def __str__(self) -> str:
return str(self.reason)
def __repr__(self) -> str:
return str(self.reason)
class FileOrFolderAlreadyExists(Exception):
def __init__(self, reason):
self.reason = reason
def __str__(self) -> str:
return str(self.reason)
def __repr__(self) -> str:
return str(self.reason)
def _formatMatching(condition: UnformattedMatching) -> FormatedMatching:
limit = (1, 1)
if isinstance(condition, tuple) and not callable(condition):
limit = (condition[1], condition[2])
condition = condition[0]
if isinstance(condition, str) and not callable(condition):
match: Callable[[Union["File", "Folder"]], bool] = (
lambda item: item.name == condition
)
elif isinstance(condition, re.Pattern) and not callable(condition):
match: Callable[[Union["File", "Folder"]], bool] = lambda item: bool(
condition.search(item.name)
)
elif callable(condition):
match = condition
else:
raise ValueError(f'Unknown condition "{condition}" type is "{type(condition)}"')
return (match, limit[0], limit[1])
class _ObjectListIndexedByName(Generic[_T]):
def __init__(self, var: Iterable[_T] = []):
self.values: List[_T] = list(var)
def remove(self, var: _T) -> None:
self.values.remove(var)
def removeByName(self, name: str) -> None:
for i in self.values:
if i.name == name:
self.values.remove(i)
return
raise ValueError(f'No Object named "{name}"')
def __str__(self) -> str:
return f"<{self.__class__.__name__} len={len(self.values)}>"
def __repr__(self) -> str:
return f"<{self.__class__.__name__} {self.values}>"
def append(self, var: _T):
self.values.append(var)
def __len__(self):
return len(self.values)
def __add__(self, var: "_ObjectListIndexedByName"):
return _ObjectListIndexedByName(self.values + var.values)
def __contains__(self, var: Union[_T, str]) -> bool:
if var in self.values:
return True
for i in range(len(self.values)):
if self.values[i].name == var:
return True
return False
def __getitem__(self, key: Union[int, str]) -> Union[_T, None]:
if isinstance(key, str):
for i in self.values:
if i.name == key:
return i
return None
elif isinstance(key, int):
return self.values[key]
return None
def __getattribute__(self, key: str) -> Any:
try:
return super().__getattribute__(key)
except AttributeError:
for i in self.values:
if i.name == key:
return i
raise AttributeError(f"name {key} is neither attribute or name of values")
def __iter__(self):
return self.values.__iter__()
def getSubAttribute(self, key: str) -> List:
retsult = []
for i in self:
if isinstance(tryRun(lambda: i.__getattribute__(key)), RuntimeError):
raise AttributeError(
f'Not all attributes named "{key}" of the list are existent'
)
retsult.append(i.__getattribute__(key))
return retsult
def callSubAttribute(self, fn: str, *args, **kw) -> Any:
li = self.getSubAttribute(fn)
for i in li:
if not callable(i):
raise AttributeError(
f'Not all attributes named "{fn}" of the list are callable'
)
return [tryRun(lambda: i(*args, **kw)) for i in li]
class SearchResult(_ObjectListIndexedByName[Union["File", "Folder"]]):
def __init__(
self,
var: Iterable[Union["File", "Folder"]] = [],
match: Union[FormatedMatching, None] = None,
):
super().__init__(var)
self.match = match
def __add__(self, var: "SearchResult"):
return SearchResult(self.values + var.values, match=self.match)
def remove(self) -> None:
self.callSubAttribute("remove")
def copy(self, path: Union[str, Path]) -> None:
self.callSubAttribute("copy", path)
def move(self, path: Union[str, Path]) -> None:
self.callSubAttribute("move", path)
def rename(self, newName: str) -> None:
li = self.getSubAttribute("rename")
for index, i in enumerate(li):
i(newName.format(index, i=index, index=index))
class FileList(_ObjectListIndexedByName["File"]):
def __init__(self, var: Iterable["File"] = []):
super().__init__(var)
def __add__(self, var: "FileList"):
return FileList(self.values + var.values)
class FolderList(_ObjectListIndexedByName["Folder"]):
def __init__(self, var: Iterable["Folder"] = []):
super().__init__(var)
def __add__(self, var: "FolderList"):
return FolderList(self.values + var.values)
class FileSystemNode(_HasName):
path: Path
copy: Callable[[], None]
remove: Callable[[], None]
move: Callable[[str], None]
rename: Callable[[str], None]
class File(FileSystemNode):
def __init__(self, path: Union[str, Path], parent: Union["Folder", None] = None):
self._active = True
if not isinstance(path, Path):
path = Path(path)
self.path = path
self.parent = parent
self.refresh()
def deactivate(self):
"""
Deactivates the object.
"""
self._active = False
def refresh(self):
"""Rebuild all of this file object"""
state = os.stat(self.path)
self.mode = state.st_mode
self.ino = state.st_ino
self.dev = state.st_dev
self.uid = state.st_uid
self.gid = state.st_gid
self.size = state.st_size
self.mtime = state.st_mtime
self.ctime = state.st_ctime
self.atime = state.st_atime
self._md5: Union[None, str] = None
self._sha1: Union[None, str] = None
self._sha256: Union[None, str] = None
self._sha512: Union[None, str] = None
@property
def name(self) -> str:
return self.path.name
def open(self, *args, **kw) -> IO:
"""
Open the file at the given path with the specified arguments and keyword arguments.
Parameters:
*args: Variable length argument list.
**kw: Arbitrary keyword arguments.
Returns:
IO: The opened file object.
"""
return open(self.path, *args, **kw)
def __str__(self) -> str:
return f'<File "{self.name}">'
def __repr__(self) -> str:
return f'<File "{self.name}">'
@property
def content(self) -> bytes:
"""
Return the content of the file as bytes.
:return: A bytes object containing the content of the file.
:rtype: bytes
"""
with self.open("rb") as f:
return f.read()
@content.setter
def _setContent(self, content: bytes):
"""
Sets the content of the object.
Parameters:
content (bytes): The content to be set.
Returns:
None
"""
with self.open("wb") as f:
f.write(content)
f.flush()
@property
def md5(self) -> str:
"""
Returns the MD5 hash of the content.
:return: The MD5 hash as a string.
:rtype: str
"""
if self._md5:
return self._md5
self._md5 = hashlib.md5(self.content).hexdigest()
return self._md5
@property
def sha1(self) -> str:
"""
Returns the SHA-1 hash value of the content.
:return: A string representing the SHA-1 hash value.
:rtype: str
"""
if self._sha1:
return self._sha1
self._sha1 = hashlib.sha1(self.content).hexdigest()
return self._sha1
@property
def sha256(self) -> str:
"""
Returns the SHA-256 hash of the content.
:return: A string representing the SHA-256 hash.
:rtype: str
"""
if self._sha256:
return self._sha256
self._sha256 = hashlib.sha256(self.content).hexdigest()
return self._sha256
@property
def sha512(self) -> str:
"""
Returns the SHA512 hash of the content.
Returns:
str: The SHA512 hash of the content.
"""
if self._sha512:
return self._sha512
self._sha512 = hashlib.sha512(self.content).hexdigest()
return self._sha512
@property
def hash(self) -> str:
"""
Returns the hash value of the object.
:return: A string representing the hash value.
:rtype: str
"""
return self.md5
def remove(self):
"""
Removes the file at the specified path.
This method deletes the file located at the `self.path` location. If the file has a parent directory, it also updates the parent directory by calling `self.parent._updateRemoveSubItem(self.name)`.
"""
os.remove(self.path)
if self.parent:
self.parent._updateRemoveSubItem(self.name)
def copy(self, path: str):
"""
Copy the file or directory at `self.path` to the specified `path`.
Parameters:
path (str): The destination path where the file or directory will be copied to.
Returns:
None
"""
shutil.copy(self.path, path)
def move(self, path: str):
"""
Move the file or directory represented by this item to the specified path.
Args:
path (str): The destination path to move the item to.
Returns:
None
"""
shutil.move(self.path, path)
if self.parent:
self.parent._updateRemoveSubItem(self.name)
def rename(self, newName: str) -> None:
"""
Renames the object with a new name.
Parameters:
newName (str): The new name for the object.
Returns:
None
"""
splitPath = self.path.spitPath(False)
while len(splitPath) and splitPath[-1] == "":
splitPath = splitPath[:-1]
if not len(splitPath):
raise ValueError("The path has no location to rename")
splitPath[-1] = newName
newPath: Path = Path(self.path.driver + "/".join(splitPath))
os.rename(self.path, newPath)
if self.parent:
self.parent._updateRenameSubItem(self.name, newName)
def __getattribute__(self, __name: str) -> Any:
if not super().__getattribute__("_active") and __name not in [
"_active",
"path",
"parent",
"name",
]:
raise DisabledError(
"Can not get item from disabled file. You abandoned me, and then you flirt with me like this"
)
return super().__getattribute__(__name)
class Folder(FileSystemNode):
def __init__(
self,
path: Union[str, Path],
onlisten: bool = False,
parent: Union["Folder", None] = None,
scan: bool = False,
ignores: Iterable[Union[str, Path]] = [],
gitignore: bool = False,
):
"""
Args:
path (Union[str, Path]): The path to the file or directory.
onlisten (bool, optional): Indicates whether to enable listening for changes. Defaults to False.
parent (Union["Folder", None], optional): The parent folder. Defaults to None.
scan (bool, optional): Indicates whether to scan the directory contents. Defaults to False.
ignores (Iterable[Union[str, Path]], optional): A list of paths to ignore. Defaults to [].
gitignore (bool, optional): Indicates whether to use the .gitignore file. Defaults to False.
"""
self._active = True
if not isinstance(path, Path):
path = Path(path)
self.onlisten = onlisten
self.path = path
self.parent = parent
self.scaned = scan
self.gitignore = gitignore
self.ignores: List[Path] = []
self.scan = scan
self.logger = logging.getLogger(self.name)
if self.onlisten:
self.event_handler = _FolderUpdateHeader(self)
self.observer = Observer()
self.observer.schedule(self.event_handler, path=path, recursive=True)
self.observer.start()
gitignores = []
if gitignore:
try:
with open(path.add(".gitignore"), encoding="utf-8") as f:
gitignores = [i[:-1] for i in set(f.readlines())]
except:
gitignores = []
for i in set(gitignores + list(ignores)):
if not isinstance(i, Path):
i = Path(path.getAbsolutePath(i))
self.ignores.append(i)
if scan:
self.refresh()
def deactivate(self):
"""
Deactivates the object.
"""
self._active = False
def refresh(self):
self.logger.debug("refresh folder contents")
"""Rebuild all of this folder object"""
self.scaned = True
self.dir: List[str] = os.listdir(self.path)
self.files: FileList = FileList([])
self.subfolder: FolderList = FolderList([])
for i in self.dir:
newPath = self.path.add(i)
if newPath in self.ignores:
continue
if os.path.isfile(newPath):
self.files.append(self._newFile(newPath))
elif os.path.isdir(newPath):
self.subfolder.append(self._newSubFolder(newPath))
def _newFile(self, path: Path) -> File:
"""
Creates a new File object with the given path and adds it to the current directory.
Args:
path (Path): The path of the file to be created.
Returns:
File: The newly created File object.
"""
return File(path, parent=self)
def _newSubFolder(self, path: Path) -> "Folder":
"""
Create a new subfolder within the current folder.
Args:
path (Path): The path of the new subfolder.
Returns:
Folder: The newly created subfolder.
"""
return Folder(
path,
parent=self,
scan=self.scan,
ignores=self.ignores,
gitignore=self.gitignore,
)
@property
def name(self) -> str:
"""
Returns the name of the object.
:return: A string representing the name of the object.
:rtype: str
"""
return self.path.name
def __str__(self) -> str:
return f'<Folder "{self.name}">'
def __repr__(self) -> str:
return self.__str__()
def __contains__(self, item: Union[str, "Folder", "File"]) -> bool:
if isinstance(item, str):
return item in self.dir
elif isinstance(item, Folder):
return item in self.subfolder
elif isinstance(item, File):
return item in self.files
return False
def __getitem__(self, key) -> Union["File", "Folder", None]:
if not self._active and key not in ["path", "name"]:
raise DisabledError(
"Can not get item from disabled folder. You abandoned me, and then you flirt with me like this"
)
for item in self.subfolder:
if item.name == key:
return item
for item in self.files:
if item.name == key:
return item
return None
def __travel(self):
for i in self.files:
yield i
for i in self.subfolder:
yield i
def __iter__(self):
return self.__travel()
def _update(
self, path: List[str], eventType: str, eventTarget: Path, isDirectory: bool
):
"""Update when something changes"""
if not self.scaned:
return
if len(path) > 1:
nextFolder = self[path[0]]
if isinstance(nextFolder, Folder):
nextFolder._update(path[1:], eventType, eventTarget, isDirectory)
return
self.logger.debug(f"file content update.{eventType}")
name = path[0]
if eventType == EVENT_TYPE_CREATED:
if name in self:
return
if name in self.ignores:
return
if isDirectory:
self.subfolder.append(self._newSubFolder(eventTarget))
else:
self.files.append(self._newFile(eventTarget))
if eventType == EVENT_TYPE_DELETED:
target = self[name]
if isinstance(target, Folder):
self.subfolder.remove(target)
elif isinstance(target, File):
self.files.remove(target)
if eventType == EVENT_TYPE_MODIFIED:
target = self[name]
if isinstance(target, Folder):
target.refresh()
def __getattribute__(self, name: str) -> Any:
if not super().__getattribute__("_active") and name not in [
"path",
"name",
"parent",
"_active",
]:
raise DisabledError(
"Can not get attributes from disabled folder. You abandoned me, and then you flirt with me like this"
)
if not super().__getattribute__("scaned") and name not in [
"path",
"name",
"parent",
"_active",
"scaned",
"refresh",
"logger",
"ignores",
]:
self.refresh()
try:
return super().__getattribute__(name)
except AttributeError:
target = self[name]
if target:
return target
raise AttributeError(f'"{name}" is not a attribute ,a subfolder or a file')
def forEach(
self,
callback: Callable[[Union["File", "Folder"]], Any],
rootPosition: Literal["first", "last"] = "first",
) -> None:
"""
Go through each of these elements
:param callback:The function to call
:rootPosition:Is the root before or after the child element
"""
if rootPosition == "first":
callback(self)
for item in self.files:
callback(item)
for item in self.subfolder:
item.forEach(callback, rootPosition)
if rootPosition == "last":
callback(self)
def forEachFile(self, callback: Callable[[File], Any]) -> None:
"""
Go through each of these file
:param callback:The function to call
"""
for item in self.files:
callback(item)
for item in self.subfolder:
item.forEachFile(callback)
def forEachFolder(
self,
callback: Callable[["Folder"], Any],
rootPosition: Literal["first", "last"] = "first",
) -> None:
"""
Go through each of these folder
:param callback:The function to call
:param rootPosition:Is the root before or after the child element
"""
if rootPosition == "first":
callback(self)
for item in self.subfolder:
item.forEachFolder(callback, rootPosition)
if rootPosition == "last":
callback(self)
def remove(self) -> None:
"""
Remove the folder.
This function removes the folder along with all its contents. It uses the `shutil.rmtree` function to delete the folder recursively. If the folder has a parent, it also calls the `_updateRemoveSubItem` function on the parent to update its internal state.
Parameters:
None
Returns:
None
"""
self.logger.info("Removing folder")
shutil.rmtree(self.path)
if self.parent:
self.parent._updateRemoveSubItem(self.name)
def _updateRemoveSubItem(self, name: str):
"""
Updates and removes a sub-item from the directory.
Parameters:
name (str): The name of the sub-item to be updated and removed.
Returns:
None
"""
item = self[name]
if item == None:
return
elif isinstance(item, File):
self.files.remove(item)
elif isinstance(item, Folder):
self.subfolder.remove(item)
item.deactivate()
def move(self, path: str) -> None:
"""
Move a folder to the specified path.
Args:
path (str): The path where the folder will be moved to.
Returns:
None: This function does not return anything.
"""
self.logger.info(f"Moving folder to {path}")
shutil.move(self.path, path)
def copy(self, path: str) -> None:
"""
Copies the entire folder at `self.path` to the specified destination `path`.
Args:
path (str): The destination path where the folder will be copied.
Returns:
None: This function does not return anything.
"""
self.logger.info(f"Copying folder to {path}")
shutil.copytree(self.path, path)
def rename(self, newName: str) -> None:
"""
Renames the file or directory to the specified new name.
Parameters:
newName (str): The new name to assign to the file or directory.
Returns:
None
Raises:
ValueError: If the path has no location to rename.
Notes:
- The function modifies the existing file or directory name.
- If the function is called on a directory, all its sub-items will also be renamed.
"""
splitPath = self.path.spitPath(False)
while len(splitPath) and splitPath[-1] == "":
splitPath = splitPath[:-1]
if not len(splitPath):
raise ValueError("The path has no location to rename")
splitPath[-1] = newName
newPath: Path = Path(self.path.driver + "/".join(splitPath))
os.rename(self.path, newPath)
if self.parent:
self.parent._updateRenameSubItem(self.name, newName)
def _updateRenameSubItem(self, name: str, newName: str):
"""
Updates the name of a sub-item in the current directory.
Parameters:
name (str): The name of the sub-item to be updated.
newName (str): The new name to assign to the sub-item.
Returns:
None
"""
item = self[name]
if item == None:
return
elif isinstance(item, File):
self.files.remove(item)
self.files.append(self._newFile(self.path.add(newName)))
elif isinstance(item, Folder):
self.subfolder.remove(item)
self.subfolder.append(self._newSubFolder(self.path.add(newName)))
item.deactivate()
def hasSubfolder(self, name: str, recursive: bool = False) -> bool:
"""
Whether to include a subfolder
:param name:folder name
"""
for i in self.subfolder:
if i.name == name:
return True
if recursive:
for i in self.subfolder:
if i.hasSubfolder(name, recursive=recursive):
return True
return False
def hasFile(self, name: str, recursive: bool = False) -> bool:
"""
Whether to include a file
:param name:file name
"""
for i in self.files:
if i.name == name:
return True
if recursive:
for i in self.subfolder:
if i.hasFile(name, recursive=recursive):
return True
return False
def search(
self,
condition: List[UnformattedMatching],
aim: Literal["file", "folder", "both"] = "both",
threaded: bool = False,
threads: Union[None, int] = None,
) -> SearchResult:
"""
Search item in the Folder
:param condition: search conditions which is unformatted
str: match the files whose name == condition\n
re.Pattern[str]: match the files whose name matches the regular expression\n
Callable[[Union["File","Folder"]],bool]: Returns a match based on the folder or file object\n
Tuple[str | re.Pattern[str]| Callable ,int,int|None] the condition , the Minimum repetition , Maximum repetition("None" indicates that there is no limit)
:param aim: search type
"""
self.logger.debug(f"Searching objects in folder.{condition}")
threadPool = ThreadPoolExecutor(max_workers=threads) if threaded else None
waitlist: List[_base.Future] = []
retsult: SearchResult = SearchResult()
self._match(
[_formatMatching(i) for i in condition],
retsult,
aim=aim,
pool=threadPool,
waitlist=waitlist,
)
for i in waitlist:
while not i.done():
time.sleep(0.1)
return retsult
def _match(
self,
condition: List[FormatedMatching],
retsult: SearchResult,
aim: Literal["file", "folder", "both"] = "both",
pool: Union[ThreadPoolExecutor, None] = None,
waitlist: List[_base.Future] = [],
) -> None:
"""
This is the ultimate implementation of the search behavior, but if your criteria are not formatted, consider starting with the "search" function, which will format the criteria and complete the search for you
:param condition: search conditions which is formatted
:param aim: search type
"""
for i in range(len(condition)):
if aim != "folder":
for j in self.files:
if not condition[i][0](j):
continue
restCondition = copy.deepcopy(condition[i:])
restCondition[0] = (
restCondition[0][0],
max(restCondition[0][1] - 1, 0),
None
if restCondition[0][2] == None
else max(restCondition[0][2] - 1, 0),
)
k = i
while k < len(restCondition):
if restCondition[k][1] != 0:
break
k += 1
if k == len(restCondition):
retsult.append(j)
for j in self.subfolder:
if not condition[i][0](j):
continue
restCondition = copy.deepcopy(condition)
restCondition[0] = (
restCondition[0][0],
max(restCondition[0][1] - 1, 0),
None
if restCondition[0][2] == None
else max(restCondition[0][2] - 1, 0),
)
if restCondition[0][2] != None and restCondition[0][2] <= 0:
del restCondition[0]
if pool: