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" file.
055     */
056    public static final String MSG_KEY_UNABLE_OPEN = "unable.open";
057
058    /**
059     * A key is pointing to the warning message text in "message.properties" file.
060     */
061    public static final String MSG_KEY_WRONG_ENDING = "wrong.line.ending";
062
063    /**
064     * Default line ending LF.
065     */
066    private LineEndingOption lineEnding = LineEndingOption.LF;
067
068    /**
069     * Creates a new {@code LineEndingCheck} instance.
070     */
071    public LineEndingCheck() {
072        // no code by default
073    }
074
075    /**
076     * Setter to set lineEnding.
077     *
078     * @param ending string of value LF or CRLF
079     * @since 13.3.0
080     */
081    public void setLineEnding(String ending) {
082        lineEnding = Enum.valueOf(LineEndingOption.class,
083                ending.trim().toUpperCase(Locale.ENGLISH));
084    }
085
086    @Override
087    protected void processFiltered(File file, FileText fileText) {
088        try {
089            final byte[] content = Files.readAllBytes(file.toPath());
090            checkLineEndings(lineEnding, content);
091        }
092        catch (final IOException ignore) {
093            log(0, MSG_KEY_UNABLE_OPEN, file.getPath());
094        }
095    }
096
097    /**
098     * Checks that the file content uses the configured line ending
099     * and logs a violation for each line that does not match.
100     *
101     * @param expected the expected line ending
102     * @param content the file content as bytes
103     */
104    private void checkLineEndings(LineEndingOption expected, byte... content) {
105        int line = 1;
106
107        for (int index = 0; index < content.length; index++) {
108            final byte current = content[index];
109            if (LineEndingOption.CR.matches(current)) {
110                final boolean nextIsLf = index + 1 < content.length
111                        && LineEndingOption.LF.matches(content[index + 1]);
112                final LineEndingOption actual;
113                if (nextIsLf) {
114                    actual = LineEndingOption.CRLF;
115                }
116                else {
117                    actual = LineEndingOption.CR;
118                }
119                if (actual != expected) {
120                    logIncorrectLineEnding(line, actual);
121                }
122                line++;
123            }
124            else if (LineEndingOption.LF.matches(current)) {
125                final boolean prevIsCr = index > 0
126                        && LineEndingOption.CR.matches(content[index - 1]);
127                if (!prevIsCr) {
128                    final LineEndingOption actual = LineEndingOption.LF;
129                    if (actual != expected) {
130                        logIncorrectLineEnding(line, actual);
131                    }
132                    line++;
133                }
134            }
135        }
136    }
137
138    /**
139     * Logs an incorrect line ending detected at the given line.
140     *
141     * @param line the line number where the issue was found
142     * @param wrongLineEnding the detected incorrect line ending
143     */
144    private void logIncorrectLineEnding(int line,
145                                        LineEndingOption wrongLineEnding) {
146        log(line, MSG_KEY_WRONG_ENDING, lineEnding, wrongLineEnding);
147    }
148
149}