001package org.unix4j.unix.wc;
002
003import org.unix4j.command.AbstractCommand;
004import org.unix4j.context.ExecutionContext;
005import org.unix4j.io.FileInput;
006import org.unix4j.io.Input;
007import org.unix4j.processor.InputLineProcessor;
008import org.unix4j.processor.LineProcessor;
009import org.unix4j.unix.Wc;
010import org.unix4j.util.FileUtil;
011
012import java.io.File;
013import java.util.Arrays;
014import java.util.List;
015
016/**
017 * Implementation of the {@link Wc wc} command.
018 */
019class WcCommand extends AbstractCommand<WcArguments> {
020        public WcCommand(WcArguments arguments) {
021                super(Wc.NAME, arguments);
022        }
023
024        @Override
025        public LineProcessor execute(ExecutionContext context, final LineProcessor output) {
026                final WcArguments args = getArguments(context);
027                
028                //input from files?
029                final List<? extends Input> inputs;
030                if (args.isFilesSet()) {
031                        inputs = FileInput.multiple(args.getFiles());
032                } else if (args.isPathsSet()) {
033                        final List<File> files = FileUtil.expandFiles(context.getCurrentDirectory(), args.getPaths());
034                        inputs = FileInput.multiple(files);
035                } else if (args.isInputsSet()) {
036                        inputs = Arrays.asList(args.getInputs());
037                } else {
038                        //standard input
039                        return getStandardInputProcessor(context, output);
040                }
041                
042        if(inputs.size() == 1){
043                        return new InputLineProcessor(inputs.get(0), new WcFileProcessor(context, args), output);
044
045        } else if(inputs.size() > 1){
046            return new WcMultipleFilesProcessor(context, inputs, output, args);
047
048                } else {
049                        throw new IllegalStateException("No inputs specified");
050                }
051        }
052        
053        private WcProcessor getStandardInputProcessor(ExecutionContext context, final LineProcessor output) {
054                return new WcProcessor(this, context, output);
055        }
056}