Skip to content

Commit d6912e1

Browse files
committed
fix: prevent 'cd ..' from moving above root directory
1 parent 1efb555 commit d6912e1

File tree

1 file changed

+24
-2
lines changed

1 file changed

+24
-2
lines changed

src/main/java/com/mycmd/commands/CdCommand.java

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,36 @@
77
public class CdCommand implements Command {
88
@Override
99
public void execute(String[] args, ShellContext context) {
10+
// No argument -> print current directory
1011
if (args.length == 0) {
1112
System.out.println(context.getCurrentDir().getAbsolutePath());
1213
return;
1314
}
14-
File newDir = new File(args[0]);
15+
16+
String dir = args[0];
17+
18+
// Normalize "cd.." without space to ".."
19+
if (dir.equals("cd..")) {
20+
dir = "..";
21+
}
22+
23+
File newDir = new File(dir);
24+
25+
// If relative path, resolve from current directory
1526
if (!newDir.isAbsolute()) {
16-
newDir = new File(context.getCurrentDir(), args[0]);
27+
newDir = new File(context.getCurrentDir(), dir);
28+
}
29+
30+
// Handle "cd .." when already at root
31+
if (dir.equals("..")) {
32+
File parent = context.getCurrentDir().getParentFile();
33+
if (parent == null) {
34+
System.out.println("Already at the root directory.");
35+
return;
36+
}
37+
newDir = parent;
1738
}
39+
1840
if (newDir.exists() && newDir.isDirectory()) {
1941
context.setCurrentDir(newDir);
2042
} else {

0 commit comments

Comments
 (0)