2525func main () {
2626 app := & cli.Command {
2727 Name : "xtree" ,
28- Usage : "This CLI uses {JSON|YAML|TOML} to generate directory tree" ,
28+ Usage : "This CLI uses {JSON|YAML|TOML} to generate ASCII tree" ,
2929 Version : fmt .Sprintf ("%s / revision %s" , Version , Revision ),
3030 Commands : []* cli.Command {
3131 {
@@ -44,6 +44,12 @@ func main() {
4444 Aliases : []string {"a" },
4545 Usage : "set this option when you want to allow duplicate node names at the same level." ,
4646 },
47+ & cli.IntFlag {
48+ Name : "level" ,
49+ Aliases : []string {"l" },
50+ Usage : "set this option when you want to specify the depth of the tree." ,
51+ HideDefault : true ,
52+ },
4753 },
4854 Before : notExistArgs ,
4955 Action : actionOutput ,
@@ -72,11 +78,15 @@ func actionOutput(ctx context.Context, c *cli.Command) error {
7278 root = gtree .NewRoot ("." , gtree .WithDuplicationAllowed ())
7379 }
7480 omitIndex := c .Bool ("omit-index" )
81+ level := c .Int ("level" )
82+ if c .IsSet ("level" ) && level <= 0 {
83+ return errors .New ("invalid level, must be greater than 0." )
84+ }
7585
76- return output (os .Stdout , os .Stdin , root , omitIndex )
86+ return output (os .Stdout , os .Stdin , root , omitIndex , level )
7787}
7888
79- func output (w io.Writer , r io.Reader , root * gtree.Node , omitIndex bool ) error {
89+ func output (w io.Writer , r io.Reader , root * gtree.Node , omitIndex bool , level int ) error {
8090 input , err := io .ReadAll (r )
8191 if err != nil {
8292 return err
@@ -87,12 +97,20 @@ func output(w io.Writer, r io.Reader, root *gtree.Node, omitIndex bool) error {
8797 }
8898 walk (root , "" , data , omitIndex )
8999
100+ limit := level + 1
90101 for wn , err := range gtree .WalkIterFromRoot (root ) {
91102 if err != nil {
92103 return err
93104 }
94105
95- fmt .Fprintln (w , wn .Row ())
106+ if level == 0 {
107+ fmt .Fprintln (w , wn .Row ())
108+ continue
109+ }
110+ if wn .Level () <= uint (limit ) {
111+ fmt .Fprintln (w , wn .Row ())
112+ continue
113+ }
96114 }
97115
98116 return nil
0 commit comments