View Javadoc
1   ///////////////////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3   // Copyright (C) 2001-2025 the original author or authors.
4   //
5   // This library is free software; you can redistribute it and/or
6   // modify it under the terms of the GNU Lesser General Public
7   // License as published by the Free Software Foundation; either
8   // version 2.1 of the License, or (at your option) any later version.
9   //
10  // This library is distributed in the hope that it will be useful,
11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  // Lesser General Public License for more details.
14  //
15  // You should have received a copy of the GNU Lesser General Public
16  // License along with this library; if not, write to the Free Software
17  // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  ///////////////////////////////////////////////////////////////////////////////////////////////
19  
20  package com.puppycrawl.tools.checkstyle;
21  
22  import static com.google.common.truth.Truth.assertWithMessage;
23  
24  import java.io.IOException;
25  import java.nio.file.Files;
26  import java.nio.file.Path;
27  import java.util.List;
28  import java.util.Set;
29  import java.util.stream.Stream;
30  
31  import org.junit.jupiter.api.Assumptions;
32  import org.junit.jupiter.params.ParameterizedTest;
33  import org.junit.jupiter.params.provider.MethodSource;
34  
35  import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
36  
37  class IndentationTrailingCommentsVerticalAlignmentTest {
38  
39      private static final String INDENTATION_TEST_FILES_PATH =
40          "com/puppycrawl/tools/checkstyle/checks/indentation/indentation";
41  
42      private static final int TAB_WIDTH = 4;
43  
44      private static final Set<String> ALLOWED_VIOLATION_FILES = Set.of(
45          // reason: checkstyle check: Line gets longer than 100 characters
46          "InputIndentationInvalidLabelIndent.java",
47          "InputIndentationInvalidMethodIndent2.java",
48          "InputIndentationMethodPrecededByAnnotationWithParameterOnSeparateLine.java",
49          "InputIndentationNewChildren.java",
50          "InputIndentationNewWithForceStrictCondition.java",
51          "InputIndentationStrictCondition.java",
52          "InputIndentationTryResourcesNotStrict.java",
53          "InputIndentationTryResourcesNotStrict1.java",
54          "InputIndentationTryWithResourcesStrict.java",
55          "InputIndentationTryWithResourcesStrict1.java",
56          "InputIndentationValidClassDefIndent.java",
57          "InputIndentationValidClassDefIndent1.java",
58          "InputIndentationCorrectIfAndParameter1.java",
59          "InputIndentationPackageDeclaration3.java"
60      );
61  
62      @MethodSource("indentationTestFiles")
63      @ParameterizedTest
64      public void testTrailingCommentsAlignment(Path testFile) throws IOException {
65          final String fileName = testFile.getFileName().toString();
66          if (ALLOWED_VIOLATION_FILES.contains(fileName)) {
67              Assumptions.assumeTrue(false, "Skipping file: " + fileName);
68          }
69  
70          final List<String> lines = Files.readAllLines(testFile);
71          int expectedStartIndex = -1;
72  
73          for (int idx = 0; idx < lines.size(); idx++) {
74              final String line = lines.get(idx);
75              if (line.trim().startsWith("import ") || line.trim().startsWith("package ")) {
76                  continue;
77              }
78              final int commentStartIndex = line.indexOf("//indent:");
79              if (commentStartIndex > 0) {
80                  final String codePart = line.substring(0, commentStartIndex);
81                  if (!codePart.isBlank()) {
82                      int actualStartIndex =
83                          CommonUtil.lengthExpandedTabs(line, commentStartIndex, TAB_WIDTH);
84  
85                      // for unicode characters having supplementary code points
86                      final long extraWidth = codePart.codePoints().filter(
87                          Character::isSupplementaryCodePoint).count();
88                      actualStartIndex -= Math.toIntExact(extraWidth);
89  
90                      if (expectedStartIndex == -1) {
91                          expectedStartIndex = actualStartIndex;
92                      }
93                      else {
94                          assertWithMessage("Trailing comment alignment mismatch in file: "
95                                  + testFile + " on line " + (idx + 1))
96                                  .that(actualStartIndex)
97                                  .isEqualTo(expectedStartIndex);
98                      }
99                  }
100             }
101         }
102     }
103 
104     private static Stream<Path> indentationTestFiles() {
105         final Path resourcesDir = Path.of("src", "test", "resources");
106         final Path indentationDir = resourcesDir.resolve(INDENTATION_TEST_FILES_PATH);
107         Stream<Path> result;
108         try (Stream<Path> testFiles = Files.walk(indentationDir)) {
109             final List<Path> collected = testFiles
110                 .filter(path -> {
111                     final String fileName = path.getFileName().toString();
112                     return fileName.startsWith("InputIndentation")
113                             && fileName.endsWith(".java");
114                 }).toList();
115             result = collected.stream();
116         }
117         catch (IOException exception) {
118             assertWithMessage("Failed to find indentation test files")
119                     .that(exception)
120                     .isNull();
121             result = Stream.empty();
122         }
123         return result;
124     }
125 }