package commands; import java.io.File; import java.io.IOException; import kernel.AppException; import kernel.AbstractProcess; /** * implentation of the CD command * * @author Vaclav Podlena * */ public class cd extends AbstractProcess { /** * Realizes the CD command. * * @throws AppException * Exception caused by an error in the virtual machines manager. */ public void realization() throws AppException { File actualDir = new File(getParentCurrentPath()), newDir; if (getArgs().size() == 0) newDir = new File(System.getProperty("user.home")); else { // If there is an argument ".", stay in the same directory if (getArgs().get(0).equals(".")) { newDir = actualDir; } // If there is an argument "..", go to the parent directory else if (getArgs().get(0).equals("..")) { newDir = actualDir.getParentFile(); } else if (getArgs().get(0).equals("...")) { try { this.getErrOut().write(("cd: ... invalid command\n").getBytes()); this.getErrOut().flush(); } catch (IOException e) { e.printStackTrace(); } return; } // Else change the directory to the given (absolute or relative) path else { File paramDir = new File(getArgs().get(0)); if (paramDir.isAbsolute()) newDir = new File(paramDir.getAbsolutePath()); else newDir = new File(actualDir.getAbsolutePath() + System.getProperty("file.separator") + getArgs().get(0)); } } if (newDir == null || !newDir.exists()) { try { this.getErrOut().write( ("cd: " + (newDir == null ? "Can't find parent directory for " + getParentCurrentPath() : newDir.getAbsolutePath() + " doesn't exist") + "\n").getBytes()); this.getErrOut().flush(); } catch (IOException e) { e.printStackTrace(); } } else setParentCurrentPath(newDir.getAbsolutePath()); ((shell) this.getParent()).notifyDirChange(); } /** * Provides help for users. */ public String getHelp() { return "\n\nDescription: implentation of the CD command\n\nUsage:\n" + "cd [dir]\n\n" + "dir\tDestination directory ('.', '..', relative path, absolute path). " + "If this argument isn't used, the home directory is set."; } }