001/////////////////////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code and other text files for adherence to a set of rules. 003// Copyright (C) 2001-2024 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.Locale; 026 027import com.puppycrawl.tools.checkstyle.StatelessCheck; 028import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck; 029import com.puppycrawl.tools.checkstyle.api.FileText; 030 031/** 032 * <p> 033 * Checks whether files end with a line separator. 034 * </p> 035 * <p> 036 * Rationale: Any source files and text files in general should end with a line 037 * separator to let other easily add new content at the end of file and "diff" 038 * command does not show previous lines as changed. 039 * </p> 040 * <p> 041 * Example (the line with 'No newline at end of file' should not be in the diff): 042 * </p> 043 * <pre> 044 * @@ -32,4 +32,5 @@ ForbidWildcardAsReturnTypeCheck.returnTypeClassNamesIgnoreRegex 045 * PublicReferenceToPrivateTypeCheck.name = Public Reference To Private Type 046 * 047 * StaticMethodCandidateCheck.name = Static Method Candidate 048 * -StaticMethodCandidateCheck.desc = Checks whether private methods should be declared as static. 049 * \ No newline at end of file 050 * +StaticMethodCandidateCheck.desc = Checks whether private methods should be declared as static. 051 * +StaticMethodCandidateCheck.skippedMethods = Method names to skip during the check. 052 * </pre> 053 * <p> 054 * It can also trick the VCS to report the wrong owner for such lines. 055 * An engineer who has added nothing but a newline character becomes the last 056 * known author for the entire line. As a result, a mate can ask him a question 057 * to which he will not give the correct answer. 058 * </p> 059 * <p> 060 * Old Rationale: CVS source control management systems will even print 061 * a warning when it encounters a file that doesn't end with a line separator. 062 * </p> 063 * <p> 064 * Attention: property fileExtensions works with files that are passed by similar 065 * property for at <a href="https://checkstyle.org/config.html#Checker">Checker</a>. 066 * Please make sure required file extensions are mentioned at Checker's fileExtensions property. 067 * </p> 068 * <p> 069 * This will check against the platform-specific default line separator. 070 * </p> 071 * <p> 072 * It is also possible to enforce the use of a specific line-separator across 073 * platforms, with the {@code lineSeparator} property. 074 * </p> 075 * <ul> 076 * <li> 077 * Property {@code fileExtensions} - Specify the file extensions of the files to process. 078 * Type is {@code java.lang.String[]}. 079 * Default value is {@code ""}. 080 * </li> 081 * <li> 082 * Property {@code lineSeparator} - Specify the type of line separator. 083 * Type is {@code com.puppycrawl.tools.checkstyle.checks.LineSeparatorOption}. 084 * Default value is {@code lf_cr_crlf}. 085 * </li> 086 * </ul> 087 * <p> 088 * Parent is {@code com.puppycrawl.tools.checkstyle.Checker} 089 * </p> 090 * <p> 091 * Violation Message Keys: 092 * </p> 093 * <ul> 094 * <li> 095 * {@code noNewlineAtEOF} 096 * </li> 097 * <li> 098 * {@code unable.open} 099 * </li> 100 * <li> 101 * {@code wrong.line.end} 102 * </li> 103 * </ul> 104 * 105 * @since 3.1 106 */ 107@StatelessCheck 108public class NewlineAtEndOfFileCheck 109 extends AbstractFileSetCheck { 110 111 /** 112 * A key is pointing to the warning message text in "messages.properties" 113 * file. 114 */ 115 public static final String MSG_KEY_UNABLE_OPEN = "unable.open"; 116 117 /** 118 * A key is pointing to the warning message text in "messages.properties" 119 * file. 120 */ 121 public static final String MSG_KEY_NO_NEWLINE_EOF = "noNewlineAtEOF"; 122 123 /** 124 * A key is pointing to the warning message text in "messages.properties" 125 * file. 126 */ 127 public static final String MSG_KEY_WRONG_ENDING = "wrong.line.end"; 128 129 /** Specify the type of line separator. */ 130 private LineSeparatorOption lineSeparator = LineSeparatorOption.LF_CR_CRLF; 131 132 @Override 133 protected void processFiltered(File file, FileText fileText) { 134 try { 135 readAndCheckFile(file); 136 } 137 catch (final IOException ignored) { 138 log(1, MSG_KEY_UNABLE_OPEN, file.getPath()); 139 } 140 } 141 142 /** 143 * Setter to specify the type of line separator. 144 * 145 * @param lineSeparatorParam The line separator to set 146 * @throws IllegalArgumentException If the specified line separator is not 147 * one of 'crlf', 'lf', 'cr', 'lf_cr_crlf' or 'system' 148 * @since 3.1 149 */ 150 public void setLineSeparator(String lineSeparatorParam) { 151 lineSeparator = 152 Enum.valueOf(LineSeparatorOption.class, lineSeparatorParam.trim() 153 .toUpperCase(Locale.ENGLISH)); 154 } 155 156 /** 157 * Reads the file provided and checks line separators. 158 * 159 * @param file the file to be processed 160 * @throws IOException When an IO error occurred while reading from the 161 * file provided 162 */ 163 private void readAndCheckFile(File file) throws IOException { 164 // Cannot use lines as the line separators have been removed! 165 try (RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r")) { 166 if (lineSeparator == LineSeparatorOption.LF 167 && endsWithNewline(randomAccessFile, LineSeparatorOption.CRLF)) { 168 log(1, MSG_KEY_WRONG_ENDING); 169 } 170 else if (!endsWithNewline(randomAccessFile, lineSeparator)) { 171 log(1, MSG_KEY_NO_NEWLINE_EOF); 172 } 173 } 174 } 175 176 /** 177 * Checks whether the content provided by the Reader ends with the platform 178 * specific line separator. 179 * 180 * @param file The reader for the content to check 181 * @param separator The line separator 182 * @return boolean Whether the content ends with a line separator 183 * @throws IOException When an IO error occurred while reading from the 184 * provided reader 185 */ 186 private static boolean endsWithNewline(RandomAccessFile file, LineSeparatorOption separator) 187 throws IOException { 188 final boolean result; 189 final int len = separator.length(); 190 if (file.length() < len) { 191 result = false; 192 } 193 else { 194 file.seek(file.length() - len); 195 final byte[] lastBytes = new byte[len]; 196 final int readBytes = file.read(lastBytes); 197 if (readBytes != len) { 198 throw new IOException("Unable to read " + len + " bytes, got " 199 + readBytes); 200 } 201 result = separator.matches(lastBytes); 202 } 203 return result; 204 } 205 206}