001package org.unix4j.unix.grep;
002
003import org.unix4j.context.ExecutionContext;
004import org.unix4j.io.FileInput;
005import org.unix4j.io.Input;
006import org.unix4j.line.Line;
007import org.unix4j.line.SimpleLine;
008import org.unix4j.processor.DefaultInputProcessor;
009import org.unix4j.processor.LineProcessor;
010
011/**
012 * Counts the matching lines and writes the count and the file name to the
013 * output. The matching operation is delegated to the {@link LineMatcher} passed
014 * to the constructor.
015 */
016final class WriteFilesWithMatchingLinesProcessor extends DefaultInputProcessor implements LineProcessor {
017        
018        private final ExecutionContext context;
019        private final LineMatcher matcher;
020        private boolean matches = false;
021        private final LineProcessor output;
022
023        public WriteFilesWithMatchingLinesProcessor(GrepCommand command, ExecutionContext context, LineProcessor output, LineMatcher matcher) {
024                this.context = context;
025                this.matcher = matcher;
026                this.output = output;
027        }
028
029        @Override
030        public void begin(Input input, LineProcessor output) {
031                matches = false;
032        }
033        
034        @Override
035        public boolean processLine(Line line) {
036                if (matcher.matches(line)) {
037                        matches = true;
038                        return false;//the first match is good enough
039                }
040                return true;// we want more lines, maybe another one matches
041        }
042        @Override
043        public boolean processLine(Input input, Line line, LineProcessor output) {
044                return processLine(line);
045        }
046
047        @Override
048        public void finish(Input input, LineProcessor output) {
049                if (matches) {
050                        final String fileInfo = input instanceof FileInput ? ((FileInput)input).getFileInfo(context.getCurrentDirectory()) : input.toString();
051                        output.processLine(new SimpleLine(fileInfo));
052                }
053        }
054        
055        @Override
056        public void finish() {
057                if (matches) {
058                        output.processLine(new SimpleLine("(standard input)"));
059                }
060        }
061}