-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathx-tree.py
More file actions
941 lines (810 loc) · 35.5 KB
/
x-tree.py
File metadata and controls
941 lines (810 loc) · 35.5 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
#!/usr/bin/env python3
#[x-cmds]: UPDATE
"""A really advanced directory tree generator
with a lost of options and customization."""
from functools import lru_cache
from pathlib import Path
from typing import NamedTuple, TypedDict, Optional
from xulbux.base.consts import COLOR
from xulbux import FormatCodes, Console, File
import fnmatch
import time
import os
import re
ARGS = Console.get_args({
"base_dir": "before",
"ignore_dirs": {"-i", "--ignore", "--ignore-dirs"},
"no_progress": {"-n", "-np", "--no-progress"},
"use_all_defaults": {"-d", "--default"},
"help": {"-h", "--help"},
})
DEFAULT: ScriptDefaults = {
"ignore_dirs": [],
"auto_ignore": True,
"include_file_contents": False,
"tree_style": 2,
"indent": 2,
"into_file": False,
}
def print_help():
help_text = """
[b|in|bg:black]( Tree Generator — Quickly generate advanced and good looking directory trees )
[b](Usage:) [br:green](x-tree) [br:cyan](<base_dir>) [br:blue]([options])
[b](Arguments:)
[br:cyan](base_dir) Base directory to generate tree from [dim]((default: CWD))
[b](Options:)
[br:blue](-i), [br:blue](--ignore-dirs[dim](=)S) Directories to ignore [dim]((abs paths / rel paths / dir names, separated by [br:cyan](|)))
[br:blue](-n), [br:blue](--no-progress) Disable progress display during tree generation
[br:blue](-d), [br:blue](--default) Use all default settings without prompts
[b](Examples:)
[br:green](x-tree) [br:blue](-i="/abs/to/dir1 | rel/to/dir2 | dir3") [dim](# [i](Ignore specified directories))
[br:green](x-tree) [br:blue](--no-progress) [dim](# [i](Disable progress display))
[br:green](x-tree) [br:blue](-d) [dim](# [i](Use all default settings without prompts))
"""
FormatCodes.print(help_text)
class ScriptDefaults(TypedDict):
ignore_dirs: list[str]
auto_ignore: bool
include_file_contents: bool
tree_style: int
indent: int
into_file: bool
class TreeStylePreset(TypedDict):
line_ver: str
line_hor: str
branch_new: str
corners: tuple[str, str, str]
error: str
ignored: str
dirname_end: str
class DirScanResult(NamedTuple):
should_ignore: bool
total_count: int
hash_count: int
show_partial: bool
entries: tuple[os.DirEntry[str], ...]
class IgnoreDirectory(Exception):
"""Raised when a directory should be ignored."""
...
class GenerationStats:
"""Tracks statistics for displaying during tree generation."""
processed_dirs: int = 0
processed_files: int = 0
current_depth: int = 0
max_depth: int = 0
class IGNORE:
"""Contains patterns and logic for determining which
directories/files to auto-ignore during tree generation."""
paths: set[str] = {
"__pycache__",
"__tests__",
"_locales",
"_site",
".adobe",
".angular",
".archive-unpack",
".codeium",
".coverage",
".docker",
".ds_store",
".env",
".git",
".gitlab",
".gradle",
".hg",
".idea",
".ipynb_checkpoints",
".kube",
".minecraft/assets/objects",
".minecraft/assets/skins",
".mvn",
".next",
".npm",
".nuxt",
".nvm",
".nx",
".output",
".scannerwork",
".sonar",
".svn",
".terraform",
".tox",
".venv",
".vs",
".webpack",
".yarn",
"*.noindex",
"*[-_.@]cache",
"*[-_.@]indexed",
"*[-_.@]temp",
"$recycle.bin",
"addons-l10n",
"adobe/typeQuest",
"aggregatedCache",
"artifacts",
"autofillStates",
"backstageInAppNavCache",
"bin",
"blob_storage",
"bower_components",
"build",
"cache",
"cache[-_.@]*",
"cache[0-9]*",
"cacheStorage",
"celeryBeat-schedule",
"code cache",
"code_tracker",
"composer/files",
"coreSync/cloudNative",
"coreSync/plugins",
"coverage-reports",
"coverage",
"crlCache",
"cvs",
"D3DSCache",
"data/emojis",
"dawnCache",
"dawnGraphiteCache",
"dawnWebGPUCache",
"debug",
"debugbar",
"dist-newstyle",
"dist",
"docker",
"docs/_build",
"env",
"GPUCache",
"graphicsCache",
"graphiteDawnCache",
"grShaderCache",
"htmlCache",
"htmlCov",
"hyphen-data",
"identityCache",
"indexed[-_.@]*",
"indexedDB",
"indexes",
"jspm_packages",
"junit",
"lib/encodings",
"local storage",
"locales",
"log",
"logs",
"media cache files",
"meta/assets/indexes",
"meta/assets/objects",
"metadataIndexer",
"migrations",
"node_modules",
"node",
"npm",
"null",
"nvm",
"obj",
"office/*/aggMru",
"office/*/dts",
"office/*/usageMetricsStore",
"office/*/wef",
"officeFileCache",
"out",
"packages",
"patch64",
"pods",
"program64",
"pythonLocator",
"recent/automaticDestinations",
"recent/customDestinations",
"release",
"reports",
"rsa",
"scriptCache",
"session storage",
"shaderCache",
"site-packages",
"slCache",
"spotify/data",
"spotify/users",
"ssr/assets",
"steamLink/avatars",
"storage/framework",
"tapCache",
"target",
"temp",
"temp[-_.@]*",
"test-results",
"tmp",
"user/history",
"user/webStorage",
"uxp/plugins/external",
"vendor",
"venv",
"virtualBkgnd_*",
"vscode.git/askPass",
"webCache2",
"wheels",
"x64",
"x86",
"xcuserdata",
}
sep: str = r"[-_~x@\s]+"
ext: str = r"(?:\.[-_a-zA-Z0-9]+)*?$"
pre: str = rf"^(?![a-zA-Z]+\.[a-zA-Z])(?:[a-zA-Z0-9]+{sep})*?"
date = r"[12][0-9]{3}(?:0[1-9]|1[0-2])(?:0[1-9]|[12][0-9]|3[01])"
reoccurring: dict[str, str] = {
"number": r"-?[a-fA-F0-9]{4,}",
"delimited_number": r"_[0-9]{1,2}",
"hex": r"(?:[a-fA-F0-9]{16}[a-fA-F0-9]{20}|[a-fA-F0-9]{32}|[a-fA-F0-9]{38}|[a-fA-F0-9]{40}|[a-fA-F0-9]{64})",
"min_hex32": r"\.min_[a-fA-F0-9]{32}",
"id3hex4": rf"\w{{3}}[a-fA-F0-9]{{4}}(?:{sep}|{ext})",
"rand4": rf"(?![A-Z][a-z]{{3}})(?:(?=.*[A-Z])(?=.*[a-z])|(?=.*[0-9]))[a-zA-Z0-9]{{4}}{ext}",
"rand5": rf"(?![A-Z][a-z]{{4}})(?:(?=.*[A-Z])(?=.*[a-z])|(?=.*[0-9]))[a-zA-Z0-9]{{5}}{ext}",
"rand11": rf"(?![A-Z][a-zA-Z]{{10}})(?:(?=.*[A-Z])(?=.*[a-z])|(?=.*[0-9]))[a-zA-Z0-9]{{11}}(?:{sep}|{ext})",
"rand25": rf"(?![A-Z][a-zA-Z]{{24}})(?:(?=.*[A-Z])(?=.*[a-z])|(?=.*[0-9]))[a-zA-Z0-9]{{25}}(?:{sep}|{ext})",
"rand32": rf"(?![A-Z][a-zA-Z]{{31}})(?:(?=.*[A-Z])(?=.*[a-z])|(?=.*[0-9]))[a-zA-Z0-9]{{32}}(?:{sep}|{ext})",
"rand59": rf"(?![A-Z][a-zA-Z]{{58}})(?:(?=.*[A-Z])(?=.*[a-z])|(?=.*[0-9]))[a-zA-Z0-9]{{59}}(?:{sep}|{ext})",
"e_rand32": rf"e_[a-zA-Z0-9]{{32}}(?:{sep}|{ext})",
"num5-rand12": r"[0-9]{5}-[a-zA-Z0-9]{12}",
"lower32_num1,2.hex64": r"[a-z]{32}_[0-9]{1,2}\.[a-fA-F0-9]{64}",
"date": date,
"delimited_date": r"(?:[0-9]{2}|[0-9]{4})[-.](?:[0-9]{2}|[0-9]{4})[-.](?:[0-9]{2}|[0-9]{4})",
"domain": r"[-a-z]+(?:\.[-a-z]+){2,}",
"version.date": r"(?:[0-9]\.){3}" + date,
"base64": r"[+/0-9A-Za-z]{8,}={1,2}",
"uuid": rf"\{{?[a-zA-Z0-9]{{8}}-[a-zA-Z0-9]{{4}}-[a-zA-Z0-9]{{4}}-[a-zA-Z0-9]{{4}}-[a-zA-Z0-9]{{12}}\}}?(?:[-_a-zA-Z0-9]+(?:{sep}|{ext}))?",
"sid": r"S-[0-9]+-[0-9]+(?:-[0-9]+){2,}",
}
standalones: dict[str, str] = {
"hex2": r"[a-fA-F0-9]{2}",
"upper2": r"[A-Z]{2}" + ext,
"alt-lower2": r"alt-[a-z]{2}" + ext,
"rand_num": r"[A-Z0-9]{2,6}_[a-z][0-9]" + ext,
"id_num": r"(?:[a-zA-Z0-9]{6}-){2}[a-zA-Z0-9]{6}\s(?:[0-9]{2}|[a-z][0-9]{2})",
"domain_hex": rf"{reoccurring['domain']}_{reoccurring['hex']}",
"camelCase_version-hex64": r"[a-z]+(?:[A-Z][a-z]+)*?_[0-9]{1,2}(?:\.[0-9]{1,2})+-[a-fA-F0-9]{64}",
}
pattern: re.Pattern[str] = re.compile(
rf"(?:^(?:{'|'.join(standalones.values())})$|{pre}(?:(?:{sep})?(?:{'|'.join(reoccurring.values())}))+{ext})"
)
class Tree:
_NEWLINE = b"\n"
_SPACE = b" "
BINARY_EXTENSIONS: frozenset[str] = frozenset({
".exe", ".dll", ".so", ".dylib", ".bin", ".dat", ".db", ".sqlite", ".jpg", ".jpeg", ".png", ".gif", ".ico", ".cur",
".pdf", ".doc", ".docx", ".xls", ".xlsx", ".zip", ".tar", ".gz", ".7z", ".rar", ".mp3", ".mp4", ".avi", ".mov"
})
IGNORE_DIRS: list[str] = [d.lower() for d in IGNORE.paths]
def __init__(
self,
base_dir: Path,
ignore_dirs: Optional[list[str]] = [],
auto_ignore: Optional[bool] = True,
include_file_contents: Optional[bool] = False,
style: int = 1,
indent: int = 2,
display_progress: Optional[bool] = True,
):
self.base_dir: Path = base_dir.resolve()
self.ignore_dirs: list[str] = (ignore_dirs or []) + (self.IGNORE_DIRS if auto_ignore else [])
self.auto_ignore: Optional[bool] = auto_ignore
self.include_file_contents: Optional[bool] = include_file_contents
self.style: int = style
self.indent: int = indent
self.display_progress: Optional[bool] = display_progress
self.ignore_set: frozenset[str] = frozenset()
self.style_presets: dict[int, TreeStylePreset] = {
1: {
"line_ver": "│",
"line_hor": "─",
"branch_new": "├",
"corners": ("└", "┘", "┐"),
"error": "⚠",
"ignored": "...",
"dirname_end": "/",
},
2: {
"line_ver": "│",
"line_hor": "─",
"branch_new": "├",
"corners": ("╰", "╯", "╮"),
"error": "⚠",
"ignored": "...",
"dirname_end": "/",
},
3: {
"line_ver": "┃",
"line_hor": "━",
"branch_new": "┣",
"corners": ("┗", "┛", "┓"),
"error": "⚠",
"ignored": "...",
"dirname_end": "/",
},
4: {
"line_ver": "║",
"line_hor": "═",
"branch_new": "╠",
"corners": ("╚", "╝", "╗"),
"error": "⚠",
"ignored": "...",
"dirname_end": "/",
},
}
self._reset_style_attrs()
self.gen_stats = GenerationStats()
self._progress_update_interval = 0.05 # SECONDS BETWEEN UPDATES
self._last_progress_update = 0
def generate(
self,
ignore_dirs: list[str] = [],
auto_ignore: Optional[bool] = None,
include_file_contents: Optional[bool] = None,
style: Optional[int] = None,
indent: Optional[int] = None,
display_progress: Optional[bool] = None,
) -> str:
self.display_progress = self.display_progress if display_progress is None else display_progress
if self.display_progress:
Console.info("starting tree generation...", start="\n")
else:
Console.info("generating tree...", start="\n")
self.gen_stats = GenerationStats()
self.ignore_dirs += ignore_dirs
if not auto_ignore:
self.ignore_dirs = []
self.auto_ignore = self.auto_ignore if auto_ignore is None else auto_ignore
self.include_file_contents = include_file_contents or self.include_file_contents
self.style = style if style is not None and style >= 1 else self.style
self.indent = (indent if indent is not None and indent >= 0 else self.indent) + 1
if not self.base_dir.is_dir():
raise ValueError(f"Invalid base directory: {self.base_dir}")
self.ignore_set = (
frozenset() if len(norm_ignore_dirs := set( \
# NORMALIZE PATHS AND CONVERT ABSOLUTE PATHS TO START WITH /
(
d.lower().replace("\\", "/") if not Path(d).is_absolute()
else "/" + d.lower().replace("\\", "/").lstrip("/")
) for d in self.ignore_dirs
)) == 0 else frozenset(norm_ignore_dirs)
)
self._reset_style_attrs()
result = self._gen_tree(self.base_dir)
Console.done(
f"[b](Generated tree:) max depth [br:cyan]({self.gen_stats.max_depth}) [dim](|) "
f"[br:cyan]({self.gen_stats.processed_dirs:,}) dirs [dim](|) [br:cyan]({self.gen_stats.processed_files:,}) files",
start="\033[F\033[K",
end="\n\n",
)
return result
def _reset_style_attrs(self) -> None:
styles = self.style_presets.get(self.style, self.style_presets[1])
self.line_ver = styles["line_ver"]
self.line_hor = styles["line_hor"]
self.branch_new = styles["branch_new"]
self.corners = styles["corners"]
self.error = styles["error"]
self.ignored = styles["ignored"]
self.dirname_end = styles["dirname_end"]
self._tab = self._SPACE * self.indent
self._line_ver_b = self.line_ver.encode()
self._line_hor_b = self.line_hor.encode() * max(0, self.indent - (2 if self.indent > 2 else 1))
self._branch_new_b = self.branch_new.encode()
self._corners_b = tuple(c.encode() for c in self.corners)
self._dirname_end_b = self.dirname_end.encode()
self._ignored_suffix_b = f"{self.line_hor}{self.ignored}\n".encode()
def show_styles(self) -> None:
for style, details in self.style_presets.items():
FormatCodes.print(
f" [b|i]({style}) {details["corners"][0]}{details["line_hor"]}{details["ignored"]}{details["dirname_end"]}",
flush=True,
)
@staticmethod
@lru_cache(maxsize=4096)
def _encode_str(s: str) -> bytes:
return s.encode()
_HASH_NAME_CHARS: frozenset[str] = frozenset(
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"0123456789"
"-_~@. \t{}+/="
)
_HEX_SEGMENT: re.Pattern[str] = re.compile(r"^[a-fA-F0-9]{8,}$")
_UUID_ANYWHERE: re.Pattern[str] = re.compile(r"[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}")
_SEP_SPLITTER: re.Pattern[str] = re.compile(r"[-_~@\s]+")
@staticmethod
@lru_cache(maxsize=4096)
def _is_likely_hash_name(name: str) -> bool:
if not Tree._HASH_NAME_CHARS.issuperset(name):
return False
if len(name) < 2:
return bool(IGNORE.pattern.match(name))
if Tree._UUID_ANYWHERE.search(name):
return True
base = name.rsplit(".", 1)[0] if "." in name else name
for seg in Tree._SEP_SPLITTER.split(base):
if len(seg) >= 8 and Tree._HEX_SEGMENT.match(seg):
return True
return False
@staticmethod
def _find_filename_patterns(names: list[str], min_pattern_length: int = 4) -> tuple[bool, float]:
"""Analyze filenames to detect patterns indicating localization, versioning etc."""
if len(names) < 5:
return False, 0.0
prefixes: dict[str, int] = {}
suffixes: dict[str, int] = {}
for name in names:
base = Path(name).stem
for i in range(1, len(base) + 1):
if len(prefix := base[:i]) >= min_pattern_length:
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if len(suffix := base[-i:]) >= min_pattern_length:
suffixes[suffix] = suffixes.get(suffix, 0) + 1
best_prefix_count = max(prefixes.values()) if prefixes else 0
best_suffix_count = max(suffixes.values()) if suffixes else 0
pattern_ratio = max(best_prefix_count, best_suffix_count) / len(names)
return (max(best_prefix_count, best_suffix_count) >= 5 and pattern_ratio >= 0.7), pattern_ratio
@lru_cache(maxsize=1024)
def _scan_directory(self, dir_path: Path) -> DirScanResult:
"""Cached directory scanning with analysis."""
if not self.auto_ignore:
with os.scandir(dir_path) as it:
return DirScanResult(False, 0, 0, False, tuple(it))
try:
entries: tuple[os.DirEntry[str], ...] = ()
with os.scandir(dir_path) as it:
entries = tuple(it)
if not entries:
return DirScanResult(False, 0, 0, False, entries)
dir_name = Path(dir_path).name
total_count = len(entries)
if total_count < 3:
return DirScanResult(False, total_count, 0, False, entries)
hash_count = normal_count = 0
filenames: list[str] = []
for entry in entries:
name = entry.name
if name.startswith("."):
total_count -= 1
continue
filenames.append(name)
if self._is_likely_hash_name(name):
hash_count += 1
else:
normal_count += 1
has_pattern, _ = self._find_filename_patterns(filenames)
if normal_count >= 3 and hash_count >= 5:
return DirScanResult(False, total_count, hash_count, True, entries)
if has_pattern and total_count > 5:
return DirScanResult(True, total_count, hash_count, False, entries)
if total_count > 5 and (hash_count / total_count) > 0.8:
return DirScanResult(True, total_count, hash_count, False, entries)
if self._is_likely_hash_name(dir_name):
return DirScanResult((hash_count / total_count > 0.7), total_count, hash_count, False, entries)
return DirScanResult(False, total_count, hash_count, False, entries)
except Exception:
return DirScanResult(False, 0, 0, False, ())
def _should_ignore_path(self, path: str) -> bool:
"""Check if a path matches any ignore pattern (supports `*` wildcards and `[…]` character classes)."""
if not path:
return False
path_lower = path.lower().replace("\\", "/")
path_parts = None
for pattern in self.ignore_set:
has_wildcard = "*" in pattern or "[" in pattern
if not has_wildcard:
# EXACT MATCHING
if "/" in pattern:
if pattern.startswith("/") and path_lower == pattern[1:]:
return True
elif pattern in path_lower:
return True
else:
# SINGLE COMPONENT EXACT MATCH
if path_parts is None:
path_parts = path_lower.split("/")
if pattern in path_parts:
return True
else:
# WILDCARD MATCHING
if "/" in pattern:
if pattern.startswith("/"):
if fnmatch.fnmatch(path_lower, pattern[1:]):
return True
else:
# MULTI-COMPONENT WILDCARD PATTERN - MATCH AT ANY DEPTH
if path_parts is None:
path_parts = path_lower.split("/")
pattern_parts = pattern.split("/")
plen = len(pattern_parts)
for i in range(len(path_parts) - plen + 1):
if all(fnmatch.fnmatch(path_parts[i + j], pattern_parts[j]) for j in range(plen)):
return True
else:
# SINGLE COMPONENT WILDCARD - CHECK EACH PATH COMPONENT
if path_parts is None:
path_parts = path_lower.split("/")
if any(fnmatch.fnmatch(part, pattern) for part in path_parts):
return True
return False
@staticmethod
@lru_cache(maxsize=1024)
def _is_text_file(filepath: str) -> bool:
if Path(filepath).suffix.lower() in Tree.BINARY_EXTENSIONS:
return False
try:
with open(filepath, "rb") as f:
chunk = f.read(1024)
text_characters = bytes(range(32, 127)) + b"\n\r\t\f\b"
return bool(chunk) and all(byte in text_characters for byte in chunk)
except Exception:
return False
def _update_progress(self, current_dir: Path, is_dir: bool = True) -> None:
"""Update the generation progress display."""
if is_dir:
self.gen_stats.processed_dirs += 1
else:
self.gen_stats.processed_files += 1
self.gen_stats.current_depth = len(Path(current_dir).parts) - len(Path(self.base_dir).parts)
self.gen_stats.max_depth = max(self.gen_stats.max_depth, self.gen_stats.current_depth)
if not self.display_progress:
return
elif (current_time := time.time()) - self._last_progress_update < self._progress_update_interval:
return
self._last_progress_update = current_time
try:
rel_path = str(Path(current_dir).relative_to(self.base_dir)).replace("\\", "/")
except ValueError:
rel_path = Path(current_dir).name
formatted_dirs, formatted_files = format(self.gen_stats.processed_dirs, ","), format(self.gen_stats.processed_files, ",")
max_rel_path_len = Console.w - (
30 + len(f"depth {self.gen_stats.current_depth}/{self.gen_stats.max_depth} | {formatted_dirs} dirs | {formatted_files} files | ")
)
if len(rel_path) > max_rel_path_len:
rel_path = ("..." + rel_path[-max_rel_path_len:])
Console.log(
"GENERATING TREE",
f"depth [br:cyan]({self.gen_stats.current_depth}/{self.gen_stats.max_depth}) [dim](|) [br:cyan]({formatted_dirs}) dirs [dim](|) [br:cyan]({formatted_files}) files [dim](|) [white]{rel_path}[_]",
title_bg_color=COLOR.BLUE,
start="\033[F\033[K",
)
def _gen_tree(self, _dir: Path, _prefix: str = "", _level: int = 0, _parent_path: str = "") -> str:
"""Generate tree for directory.
_dir: Current directory path
_prefix: Line prefix for visual tree structure
_level: Current recursion depth
_parent_path: Relative path from base_dir to current dir"""
self._update_progress(_dir)
result: bytearray = bytearray()
try:
if (_level == 0):
dir_path = Path(_dir)
base_name = dir_path.name or dir_path.drive.rstrip(":\\")
result.extend(base_name.encode())
result.extend(self._dirname_end_b)
result.extend(self._NEWLINE)
_parent_path = ""
scan_result = self._scan_directory(str(_dir))
# DISPLAY DIRECTORIES FIRST AND EVERYTHING ELSE AFTER, BOTH GROUPS SORTED ALPHABETICALLY
entries = tuple(sorted(scan_result.entries, key=lambda e: (not e.is_dir(), e.name.lower())))
if not entries:
return bytes(result).decode() if result else ""
prefix_bytes = self._encode_str(_prefix)
if scan_result.should_ignore:
result.extend(prefix_bytes)
result.extend(self._corners_b[0])
result.extend(self._ignored_suffix_b)
return bytes(result).decode() if result else ""
entries_count = len(entries)
prefix_ver = prefix_bytes + self._line_ver_b + self._tab[:-1]
prefix_tab = prefix_bytes + self._tab
if scan_result.show_partial:
visible_entries: list[Optional[os.DirEntry[str]]] = []
last_was_ignored = False
for entry in entries:
if not self._is_likely_hash_name(entry.name):
if last_was_ignored:
visible_entries.append(None)
visible_entries.append(entry)
last_was_ignored = False
else:
last_was_ignored = True
if visible_entries and visible_entries[-1] is None:
visible_entries.pop()
for idx, entry in enumerate(visible_entries):
is_last = idx == len(visible_entries) - 1
if entry is None:
result.extend(prefix_bytes)
result.extend((self._corners_b[0] if is_last else self._branch_new_b))
result.extend(self._ignored_suffix_b)
continue
branch = self._corners_b[0] if is_last else self._branch_new_b
current_prefix = prefix_bytes + branch + self._line_hor_b
if entry.is_dir():
result.extend(current_prefix)
result.extend(entry.name.encode())
result.extend(self._dirname_end_b)
result.extend(self._NEWLINE)
new_prefix = _prefix + (" " * self.indent if is_last else self.line_ver + " " * (self.indent - 1))
result.extend(self._gen_tree(Path(entry.path), new_prefix, _level + 1).encode())
else:
self._update_progress(Path(entry.path), is_dir=False)
result.extend(current_prefix)
result.extend(entry.name.encode())
result.extend(self._NEWLINE)
if self.include_file_contents and self._is_text_file(entry.path):
content_prefix = _prefix + (" " * self.indent if is_last else self.line_ver + " " * (self.indent - 1))
try:
with open(entry.path, "r", encoding="utf-8", errors="replace") as f:
if (lines := f.readlines()):
lines = [
l.replace("\t", " ").translate({
0x2000: " ", 0x2001: " ", 0x2002: " ", 0x2003: " ", 0x2004: " ", 0x2005: " ",
0x2006: " ", 0x2007: " ", 0x2008: " ", 0x2009: " ", 0x200A: " "
}) for l in lines
]
content_width = max(len(line.rstrip()) for line in lines)
hor_border = self.line_hor * (content_width + 2)
result.extend(f"{content_prefix}{self.branch_new}{hor_border}{self.corners[2]}\n".encode())
for l in lines:
stripped = l.rstrip()
padding = " " * (content_width - len(stripped))
result.extend(
f"{content_prefix}{self.line_ver} {stripped}{padding} {self.line_ver}\n"
.encode()
)
result.extend(f"{content_prefix}{self.corners[0]}{hor_border}{self.corners[1]}\n".encode())
except:
result.extend(
f"{content_prefix}{self.corners[0]}{self.line_hor}[b|in|red] {self.error} Error reading file contents. [_b|_in|white]\n"
.encode()
)
else:
for idx, entry in enumerate(entries):
is_dir, is_last = entry.is_dir(), idx == entries_count - 1
branch = self._corners_b[0] if is_last else self._branch_new_b
current_prefix = prefix_bytes + branch + self._line_hor_b
current_rel_path = str(Path(_parent_path) / entry.name)
if self._should_ignore_path(current_rel_path) or (is_dir and self._scan_directory(entry.path).should_ignore):
result.extend(current_prefix)
result.extend(entry.name.encode())
if is_dir:
result.extend(self._dirname_end_b)
result.extend(self._NEWLINE)
result.extend(prefix_tab if is_last else prefix_ver)
result.extend(self._corners_b[0])
result.extend(self._ignored_suffix_b)
else:
result.extend(self._NEWLINE)
continue
if is_dir:
result.extend(current_prefix)
result.extend(entry.name.encode())
result.extend(self._dirname_end_b)
result.extend(self._NEWLINE)
new_prefix = _prefix + (" " * self.indent if is_last else self.line_ver + " " * (self.indent - 1))
result.extend(self._gen_tree(Path(entry.path), new_prefix, _level + 1, current_rel_path).encode())
else:
self._update_progress(Path(entry.path), is_dir=False)
result.extend(current_prefix)
result.extend(entry.name.encode())
result.extend(self._NEWLINE)
if self.include_file_contents and self._is_text_file(entry.path):
content_prefix = _prefix + (" " * self.indent if is_last else self.line_ver + " " * (self.indent - 1))
try:
with open(entry.path, "r", encoding="utf-8", errors="replace") as f:
if (lines := f.readlines()):
lines = [
l.replace("\t", " ").translate({
0x2000: " ", 0x2001: " ", 0x2002: " ", 0x2003: " ", 0x2004: " ", 0x2005: " ",
0x2006: " ", 0x2007: " ", 0x2008: " ", 0x2009: " ", 0x200A: " "
}) for l in lines
]
content_width = max(len(l.rstrip()) for l in lines)
hor_border = self.line_hor * (content_width + 2)
result.extend(f"{content_prefix}{self.branch_new}{hor_border}{self.corners[2]}\n".encode())
for l in lines:
result.extend(
f"{content_prefix}{self.line_ver} {(stripped := l.rstrip())}{" " * (content_width - len(stripped))} {self.line_ver}\n"
.encode()
)
result.extend(f"{content_prefix}{self.corners[0]}{hor_border}{self.corners[1]}\n".encode())
except:
result.extend(
f"{content_prefix}{self.corners[0]}{self.line_hor}[b|in|red] {self.error} Error reading file contents. [_b|_in|white]\n"
.encode()
)
except Exception as e:
error_prefix = (_prefix + self.corners[0] + (self.line_hor * (self.indent - 1)))
result.extend(f"{error_prefix}[b|in|red] {self.error} {str(e)} [_b|_in|white]\n".encode())
return bytes(result).decode() if result else ""
def main():
if ARGS.help.exists:
print_help()
return
tree = Tree(
Path(ARGS.base_dir.values[0]) \
if ARGS.base_dir.values
else Path.cwd()
)
ignore_dirs = DEFAULT["ignore_dirs"]
auto_ignore = DEFAULT["auto_ignore"]
include_file_contents = DEFAULT["include_file_contents"]
style = DEFAULT["tree_style"]
indent = DEFAULT["indent"]
into_file = DEFAULT["into_file"]
if not ARGS.use_all_defaults.exists:
if ARGS.ignore_dirs.exists:
ignore_dirs = ARGS.ignore_dirs.values[0].split("|") if ARGS.ignore_dirs.values else []
else:
ignore_dirs = Console.input(
"[b](Enter directory names/paths which's content should be ignored) ([cyan](|) separated) [b](>) "
).split("|")
ignore_dirs = [d.strip() for d in ignore_dirs]
auto_ignore = Console.input(
f"[b](Enable auto-ignore unimportant directories) {"(Y)" if auto_ignore else "(N)"} [b](>) ",
max_len=1,
allowed_chars="yYnN",
default_val="Y" if auto_ignore else "N",
).upper() == "Y"
include_file_contents = Console.input(
f"[b](Display the file contents in the tree) {"(Y)" if include_file_contents else "(N)"} [b](>) ",
max_len=1,
allowed_chars="yYnN",
default_val="Y" if include_file_contents else "N",
).upper() == "Y"
FormatCodes.print("[b](Enter the tree style) (1-4)")
tree.show_styles()
style = Console.input(
f"({style}) [b](>) ",
max_len=1,
allowed_chars="1234",
default_val=style,
output_type=int,
)
indent = Console.input(
f"[b](Enter the indent) ({indent}) [b](>) ",
max_len=2,
allowed_chars="0123456789",
default_val=indent,
output_type=int,
)
into_file = Console.input(
f"[b](Output tree into file) {"(Y)" if into_file else "(N)"} [b](>) ",
max_len=1,
allowed_chars="yYnN",
default_val="Y" if into_file else "N",
).upper() == "Y"
result = tree.generate(
ignore_dirs=ignore_dirs,
auto_ignore=auto_ignore,
include_file_contents=include_file_contents,
style=style,
indent=indent,
display_progress=(not ARGS.no_progress.exists),
)
if into_file:
file, cls_line = None, ""
try:
file = File.create("tree.txt", result)
except FileExistsError:
cls_line = "\033[F\033[K"
if Console.confirm(f"{' ' * 17}[white]tree.txt[_] already exists. Overwrite?", end=""):
file = File.create("tree.txt", result, force=True)
else:
Console.exit()
if file:
Console.done(f"[white]file:///{str(file).replace('\\', '/')}[_] successfully created.", start=cls_line, end="\n\n")
else:
Console.fail("[br:red]File is empty or failed to create file.[_]", start=cls_line, end="\n\n")
else:
FormatCodes.print(f"[white]{result}[_]", flush=True)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print()
except PermissionError:
Console.fail("Permission to create file was denied.", start="\n", end="\n\n")
except Exception as e:
Console.fail(e, start="\n", end="\n\n")