2020import java .net .URISyntaxException ;
2121import java .net .URL ;
2222import java .util .ArrayList ;
23+ import java .util .Collection ;
2324import java .util .HashMap ;
2425import java .util .List ;
2526import java .util .Map ;
3233import org .sonar .iac .common .api .checks .CheckContext ;
3334import org .sonar .iac .common .api .checks .IacCheck ;
3435import org .sonar .iac .common .api .checks .InitContext ;
36+ import org .sonar .iac .common .api .tree .HasComments ;
3537import org .sonar .iac .common .api .tree .Tree ;
3638import org .sonar .iac .common .api .tree .impl .TextRanges ;
3739import org .sonar .iac .common .extension .visitors .TreeContext ;
3840import org .sonar .iac .common .extension .visitors .TreeVisitor ;
41+ import org .sonar .iac .docker .tree .TreeUtils ;
3942import org .sonar .iac .docker .tree .api .Argument ;
4043import org .sonar .iac .docker .tree .api .ArgumentList ;
4144import org .sonar .iac .docker .tree .api .ExpandableStringCharacters ;
@@ -114,6 +117,7 @@ private void processShellCode(ShellCode shellCode, RunInstruction runInstruction
114117 if (originalSourceCode == null ) {
115118 return ;
116119 }
120+ var commentsByLine = getCommentLengthsByLine (shellCode );
117121 var codeLines = originalSourceCode .lines ().toList ();
118122 for (int i = 0 ; i < codeLines .size (); i ++) {
119123 var line = codeLines .get (i );
@@ -132,12 +136,22 @@ private void processShellCode(ShellCode shellCode, RunInstruction runInstruction
132136 // lineLength is only the part belonging to ShellCode; add the length of preceding parts of the Run instruction
133137 lineLength += shellCode .textRange ().start ().lineOffset ();
134138 }
139+ lineLength -= commentsByLine .getOrDefault (lineNumber , 0 );
135140 if (lineLength > maxLength ) {
141+
136142 runInstructionData .tooLongLinesWithLastOffset .put (lineNumber , lineLength );
137143 }
138144 }
139145 }
140146
147+ private static Map <Integer , Integer > getCommentLengthsByLine (Tree from ) {
148+ return TreeUtils .descendants (from ).filter (HasComments .class ::isInstance )
149+ .map (HasComments .class ::cast )
150+ .map (HasComments ::comments )
151+ .flatMap (Collection ::stream )
152+ .collect (Collectors .toMap (comment -> comment .textRange ().start ().line (), comment -> comment .contentText ().length (), (c1 , c2 ) -> c1 ));
153+ }
154+
141155 private void processSyntaxToken (SyntaxToken token , RunInstructionData runInstructionData ) {
142156 if (token .parent () instanceof SyntaxTokenShellCode ) {
143157 // Skip tokens that are part of ShellCode, as they are already handled by processShellCode
0 commit comments