001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
003// Copyright (C) 2001-2026 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.nio.file.Files;
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 * <div>
033 * Checks whether file uses a specific line-ending sequence
034 * ({@code LF}, {@code CRLF}, or {@code CR}).
035 * </div>
036 *
037 * <p>
038 * A violation is reported for each line whose actual line ending does not match
039 * the configured one.
040 * </p>
041 *
042 * <p>
043 * Notes:
044 * Files containing mixed line endings may produce multiple violations,
045 * one for each non-matching line.
046 * </p>
047 *
048 * @since 13.3.0
049 */
050@StatelessCheck
051public class LineEndingCheck extends AbstractFileSetCheck {
052
053    /**
054     * A key is pointing to the warning message text in "message.properties"
055     * file.
056     */
057    public static final String MSG_KEY_UNABLE_OPEN = "unable.open";
058
059    /**
060     * A key is pointing to the warning message text in "message.properties"
061     * file.
062     */
063    public static final String MSG_KEY_WRONG_ENDING = "wrong.line.ending";
064
065    /**
066     * Default line ending LF.
067     */
068    private LineEndingOption lineEnding = LineEndingOption.LF;
069
070    /**
071     * Creates a new {@code LineEndingCheck} instance.
072     */
073    public LineEndingCheck() {
074        // no code by default
075    }
076
077    /**
078     * Setter to set lineEnding.
079     *
080     * @param ending string of value LF or CRLF
081     * @since 13.3.0
082     */
083    public void setLineEnding(String ending) {
084        lineEnding = Enum.valueOf(LineEndingOption.class,
085                ending.trim().toUpperCase(Locale.ENGLISH));
086    }
087
088    @Override
089    protected void processFiltered(File file, FileText fileText) {
090        try {
091            final byte[] content = Files.readAllBytes(file.toPath());
092            checkLineEndings(lineEnding, content);
093        }
094        catch (final IOException ignore) {
095            log(0, MSG_KEY_UNABLE_OPEN, file.getPath());
096        }
097    }
098
099    /**
100     * Checks that the file content uses the configured line ending
101     * and logs a violation for each line that does not match.
102     *
103     * @param expected the expected line ending
104     * @param content the file content as bytes
105     */
106    private void checkLineEndings(LineEndingOption expected, byte... content) {
107        int line = 1;
108
109        for (int index = 0; index < content.length; index++) {
110            final byte current = content[index];
111            if (LineEndingOption.CR.matches(current)) {
112                final boolean nextIsLf = index + 1 < content.length
113                        && LineEndingOption.LF.matches(content[index + 1]);
114                final LineEndingOption actual;
115                if (nextIsLf) {
116                    actual = LineEndingOption.CRLF;
117                }
118                else {
119                    actual = LineEndingOption.CR;
120                }
121                if (actual != expected) {
122                    logIncorrectLineEnding(line, actual);
123                }
124                line++;
125            }
126            else if (LineEndingOption.LF.matches(current)) {
127                final boolean prevIsCr = index > 0
128                        && LineEndingOption.CR.matches(content[index - 1]);
129                if (!prevIsCr) {
130                    final LineEndingOption actual = LineEndingOption.LF;
131                    if (actual != expected) {
132                        logIncorrectLineEnding(line, actual);
133                    }
134                    line++;
135                }
136            }
137        }
138    }
139
140    /**
141     * Logs an incorrect line ending detected at the given line.
142     *
143     * @param line the line number where the issue was found
144     * @param wrongLineEnding the detected incorrect line ending
145     */
146    private void logIncorrectLineEnding(int line,
147                                        LineEndingOption wrongLineEnding) {
148        log(line, MSG_KEY_WRONG_ENDING, lineEnding, wrongLineEnding);
149    }
150
151}