001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2017 the original author or authors.
004//
005// This library is free software; you can redistribute it and/or
006// modify it under the terms of the GNU Lesser General Public
007// License as published by the Free Software Foundation; either
008// version 2.1 of the License, or (at your option) any later version.
009//
010// This library is distributed in the hope that it will be useful,
011// but WITHOUT ANY WARRANTY; without even the implied warranty of
012// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
013// Lesser General Public License for more details.
014//
015// You should have received a copy of the GNU Lesser General Public
016// License along with this library; if not, write to the Free Software
017// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
018////////////////////////////////////////////////////////////////////////////////
019
020package com.puppycrawl.tools.checkstyle.checks;
021
022import java.io.File;
023import java.io.IOException;
024import java.io.RandomAccessFile;
025import java.util.List;
026import java.util.Locale;
027
028import com.google.common.io.Closeables;
029import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck;
030
031/**
032 * <p>
033 * Checks that there is a newline at the end of each file.
034 * </p>
035 * <p>
036 * An example of how to configure the check is:
037 * </p>
038 * <pre>
039 * &lt;module name="NewlineAtEndOfFile"/&gt;</pre>
040 * <p>
041 * This will check against the platform-specific default line separator.
042 * </p>
043 * <p>
044 * It is also possible to enforce the use of a specific line-separator across
045 * platforms, with the 'lineSeparator' property:
046 * </p>
047 * <pre>
048 * &lt;module name="NewlineAtEndOfFile"&gt;
049 *   &lt;property name="lineSeparator" value="lf"/&gt;
050 * &lt;/module&gt;</pre>
051 * <p>
052 * Valid values for the 'lineSeparator' property are 'system' (system default),
053 * 'crlf' (windows), 'cr' (mac), 'lf' (unix) and 'lf_cr_crlf' (lf, cr or crlf).
054 * </p>
055 *
056 * @author Christopher Lenz
057 * @author lkuehne
058 */
059public class NewlineAtEndOfFileCheck
060    extends AbstractFileSetCheck {
061
062    /**
063     * A key is pointing to the warning message text in "messages.properties"
064     * file.
065     */
066    public static final String MSG_KEY_UNABLE_OPEN = "unable.open";
067
068    /**
069     * A key is pointing to the warning message text in "messages.properties"
070     * file.
071     */
072    public static final String MSG_KEY_NO_NEWLINE_EOF = "noNewlineAtEOF";
073
074    /** The line separator to check against. */
075    private LineSeparatorOption lineSeparator = LineSeparatorOption.SYSTEM;
076
077    @Override
078    protected void processFiltered(File file, List<String> lines) {
079        // Cannot use lines as the line separators have been removed!
080        try {
081            final RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
082            boolean threw = true;
083            try {
084                if (!endsWithNewline(randomAccessFile)) {
085                    log(0, MSG_KEY_NO_NEWLINE_EOF, file.getPath());
086                }
087                threw = false;
088            }
089            finally {
090                Closeables.close(randomAccessFile, threw);
091            }
092        }
093        catch (final IOException ignored) {
094            log(0, MSG_KEY_UNABLE_OPEN, file.getPath());
095        }
096    }
097
098    /**
099     * Sets the line separator to one of 'crlf', 'lf','cr', 'lf_cr_crlf' or 'system'.
100     *
101     * @param lineSeparatorParam The line separator to set
102     * @throws IllegalArgumentException If the specified line separator is not
103     *         one of 'crlf', 'lf', 'cr', 'lf_cr_crlf' or 'system'
104     */
105    public void setLineSeparator(String lineSeparatorParam) {
106        try {
107            lineSeparator =
108                Enum.valueOf(LineSeparatorOption.class, lineSeparatorParam.trim()
109                    .toUpperCase(Locale.ENGLISH));
110        }
111        catch (IllegalArgumentException iae) {
112            throw new IllegalArgumentException("unable to parse " + lineSeparatorParam, iae);
113        }
114    }
115
116    /**
117     * Checks whether the content provided by the Reader ends with the platform
118     * specific line separator.
119     * @param randomAccessFile The reader for the content to check
120     * @return boolean Whether the content ends with a line separator
121     * @throws IOException When an IO error occurred while reading from the
122     *         provided reader
123     */
124    private boolean endsWithNewline(RandomAccessFile randomAccessFile)
125            throws IOException {
126        final boolean result;
127        final int len = lineSeparator.length();
128        if (randomAccessFile.length() < len) {
129            result = false;
130        }
131        else {
132            randomAccessFile.seek(randomAccessFile.length() - len);
133            final byte[] lastBytes = new byte[len];
134            final int readBytes = randomAccessFile.read(lastBytes);
135            if (readBytes != len) {
136                throw new IOException("Unable to read " + len + " bytes, got "
137                        + readBytes);
138            }
139            result = lineSeparator.matches(lastBytes);
140        }
141        return result;
142    }
143}