Skip to content

Commit f2c917a

Browse files
committed
Add TreeCommand to display directory structure
Closes #13
1 parent ea53bc9 commit f2c917a

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

src/main/java/com/mycmd/App.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ private static void registerCommands(Map<String, Command> commands) {
5656
commands.put("whoami", new WhoamiCommand());
5757
commands.put("touch", new TouchCommand());
5858
commands.put("time", new TimeCommand());
59+
commands.put("tree", new TreeCommand());
5960
commands.put("date", new DateCommand());
6061
}
6162
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.mycmd.commands;
2+
3+
import com.mycmd.Command;
4+
import com.mycmd.ShellContext;
5+
import java.io.File;
6+
7+
public class TreeCommand implements Command{
8+
public void execute(String[] args, ShellContext context){
9+
File[] files = context.getCurrentDir().listFiles();
10+
11+
if (files == null || files.length == 0) {
12+
System.out.println("No files found.");
13+
return;
14+
}
15+
16+
System.out.println(context.getCurrentDir().getAbsolutePath());
17+
printDirectory(files, "", true);
18+
System.out.println();
19+
}
20+
21+
private void printDirectory(File[] files, String prefix, boolean isLast) {
22+
if (files == null || files.length == 0) return;
23+
24+
for (int i = 0; i < files.length; i++) {
25+
File f = files[i];
26+
if (f.isHidden()) continue;
27+
28+
boolean last = (i == files.length - 1);
29+
System.out.println(prefix + (last ? "└───" : "├───") + f.getName());
30+
31+
if (f.isDirectory()) {
32+
String newPrefix = prefix + (last ? " " : "│ ");
33+
printDirectory(f.listFiles(), newPrefix, last);
34+
}
35+
}
36+
}
37+
}

0 commit comments

Comments
 (0)