Skip to content

Commit b363c9a

Browse files
committed
fix: clean up CdCommand logic and remove redundant code
1 parent d6912e1 commit b363c9a

File tree

1 file changed

+9
-14
lines changed

1 file changed

+9
-14
lines changed

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

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -7,36 +7,31 @@
77
public class CdCommand implements Command {
88
@Override
99
public void execute(String[] args, ShellContext context) {
10-
// No argument -> print current directory
10+
// If no argument, print current directory
1111
if (args.length == 0) {
1212
System.out.println(context.getCurrentDir().getAbsolutePath());
1313
return;
1414
}
1515

1616
String dir = args[0];
17+
File newDir;
1718

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
26-
if (!newDir.isAbsolute()) {
27-
newDir = new File(context.getCurrentDir(), dir);
28-
}
29-
30-
// Handle "cd .." when already at root
19+
// Handle "cd .." (go to parent directory)
3120
if (dir.equals("..")) {
3221
File parent = context.getCurrentDir().getParentFile();
3322
if (parent == null) {
3423
System.out.println("Already at the root directory.");
3524
return;
3625
}
3726
newDir = parent;
27+
} else {
28+
newDir = new File(dir);
29+
if (!newDir.isAbsolute()) {
30+
newDir = new File(context.getCurrentDir(), dir);
31+
}
3832
}
3933

34+
// Change directory if valid
4035
if (newDir.exists() && newDir.isDirectory()) {
4136
context.setCurrentDir(newDir);
4237
} else {

0 commit comments

Comments
 (0)