@@ -649,9 +649,11 @@ def insert(
649
649
def _print (
650
650
self ,
651
651
node : Node ,
652
+ depth : int = 0 ,
652
653
prefix : str = "" ,
653
654
connector : str = "" ,
654
655
fancy : bool = True ,
656
+ levels : int = None ,
655
657
):
656
658
"""
657
659
Recursive helper function to print all nodes in a FileTree.
@@ -669,7 +671,14 @@ def _print(
669
671
670
672
fancy: bool, default: True
671
673
Whether to use fancy formatting (including colors).
674
+
675
+ levels: int, optional
676
+ The maximum number of levels to print.
672
677
"""
678
+ # Skip this node and its children if we have hit the maximum depth.
679
+ if levels and depth > levels :
680
+ return []
681
+
673
682
if fancy :
674
683
dash = "\u2500 "
675
684
cont = "\u251C "
@@ -722,23 +731,29 @@ def _print(
722
731
next_connector = cont
723
732
lines += self ._print (
724
733
node .children [name ],
734
+ depth + 1 ,
725
735
next_prefix ,
726
736
next_connector ,
727
737
fancy ,
738
+ levels ,
728
739
)
729
740
730
741
return lines
731
742
732
- def write_to (self , stream : TextIO ):
743
+ def write_to (self , stream : TextIO , levels : int = None ):
733
744
"""
734
745
Write the FileTree to the specified stream.
735
746
736
747
Parameters
737
748
----------
738
749
stream: TextIO
739
750
The text stream to write to.
751
+
752
+ levels: int, optional
753
+ The maximum number of levels to print.
754
+ If 0, print only the top-level summary.
740
755
"""
741
- lines = self ._print (self .root , fancy = stream .isatty ())
756
+ lines = self ._print (self .root , fancy = stream .isatty (), levels = levels )
742
757
output = "\n " .join (lines )
743
758
if not stream .isatty ():
744
759
output = _strip_colors (output )
@@ -751,6 +766,7 @@ def files(
751
766
* ,
752
767
stream : TextIO = sys .stdout ,
753
768
prune : bool = False ,
769
+ levels : int = None ,
754
770
):
755
771
"""
756
772
Produce a file tree representing the code base.
@@ -815,4 +831,4 @@ def files(
815
831
print (legend , file = stream )
816
832
817
833
# Print the tree.
818
- tree .write_to (stream )
834
+ tree .write_to (stream , levels = levels )
0 commit comments