001package org.unix4j.unix.ls;
002
003import java.io.File;
004import java.util.List;
005
006import org.unix4j.line.Line;
007import org.unix4j.line.SimpleLine;
008import org.unix4j.processor.LineProcessor;
009import org.unix4j.util.FileUtil;
010
011class LsFormatterDirectoryHeader implements LsFormatter {
012
013        static Factory FACTORY = new Factory() {
014                @Override
015                public LsFormatter create(File relativeTo, File directory, List<File> directoryFiles, LsArguments args) {
016                        return new LsFormatterDirectoryHeader(directoryFiles, args);
017                }
018        };
019
020        private final long totalBytes;
021
022        LsFormatterDirectoryHeader(List<File> directoryFiles, LsArguments args) {
023                long totalBytes = 0L;
024                for (final File f : directoryFiles) {
025                        if (f.isFile()) {
026                                totalBytes += f.length();
027                        }
028                }
029                this.totalBytes = totalBytes;
030        }
031
032        @Override
033        public boolean writeFormatted(File relativeTo, File file, LsArguments args, LineProcessor output) {
034                String relativePath = FileUtil.getRelativePath(relativeTo, file);
035                if (!relativePath.startsWith(".") && !relativePath.startsWith("/")) {
036                        relativePath = "./" + relativePath;
037                }
038                if (!".".equals(relativePath)) {
039                        if (!output.processLine(Line.EMPTY_LINE)) {
040                                return false;
041                        }
042                        if (!output.processLine(new SimpleLine(relativePath + ":"))) {
043                                return false;
044                        }
045                }
046                if (args.isLongFormat()) {
047                        return output.processLine(new SimpleLine("total: " + LsCommand.getSizeString(args, totalBytes)));
048                }
049                return true;
050        }
051
052}