Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions src/main/java/com/mycmd/commands/CdCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,31 @@
public class CdCommand implements Command {
@Override
public void execute(String[] args, ShellContext context) {
// If no argument, print current directory
if (args.length == 0) {
System.out.println(context.getCurrentDir().getAbsolutePath());
return;
}
File newDir = new File(args[0]);
if (!newDir.isAbsolute()) {
newDir = new File(context.getCurrentDir(), args[0]);

String dir = args[0];
File newDir;

// Handle "cd .." (go to parent directory)
if (dir.equals("..")) {
File parent = context.getCurrentDir().getParentFile();
if (parent == null) {
System.out.println("Already at the root directory.");
return;
}
newDir = parent;
} else {
newDir = new File(dir);
if (!newDir.isAbsolute()) {
newDir = new File(context.getCurrentDir(), dir);
}
}

// Change directory if valid
if (newDir.exists() && newDir.isDirectory()) {
context.setCurrentDir(newDir);
} else {
Expand Down