001package org.unix4j.unix.cd; 002 003import java.io.File; 004import java.util.List; 005 006import org.unix4j.command.AbstractCommand; 007import org.unix4j.command.Command; 008import org.unix4j.command.JoinedCommand; 009import org.unix4j.context.DerivedExecutionContext; 010import org.unix4j.context.ExecutionContext; 011import org.unix4j.processor.LineProcessor; 012import org.unix4j.unix.Cd; 013import org.unix4j.unix.Echo; 014import org.unix4j.util.FileUtil; 015 016/** 017 * Implementation of the {@link Cd cd} command. 018 */ 019class CdCommand extends AbstractCommand<CdArguments> { 020 public CdCommand(CdArguments arguments) { 021 super(Echo.NAME, arguments); 022 } 023 024 @Override 025 public Command<CdArguments> join(Command<?> next) { 026 return new JoinedCommand<CdArguments>(this, next) { 027 @Override 028 public LineProcessor execute(ExecutionContext context, LineProcessor output) { 029 final CdArguments args = getArguments(context); 030 final File file; 031 if (args.isPathSet()) { 032 final String path = args.getPath(context); 033 final List<File> files = FileUtil.expandFiles(context.getCurrentDirectory(), path); 034 if (files.isEmpty()) { 035 throw new IllegalArgumentException("no file found for path argument: " + path); 036 } 037 file = files.get(0); 038 } else if (args.isFileSet()) { 039 file = args.getFile(); 040 } else { 041 file = context.getUserHome(); 042 } 043 if (!file.isDirectory()) { 044 throw new IllegalArgumentException("not a valid directory: " + file.getAbsolutePath()); 045 } 046 final DerivedExecutionContext currentDirContext = new DerivedExecutionContext(context); 047 currentDirContext.setCurrentDirectory(file); 048 return super.execute(currentDirContext, output); 049 } 050 }; 051 } 052 053 @Override 054 public LineProcessor execute(ExecutionContext context, final LineProcessor output) { 055 return output;// pipe through, we don't do anything with the input or 056 // output 057 } 058}