From aa570125a74c8175ab2103d1c34c28e366f49efc Mon Sep 17 00:00:00 2001 From: Tim te Beek Date: Wed, 15 Nov 2023 11:39:16 +0100 Subject: [PATCH] Remove duplicated semicolons, without removing newline (#216) * Remove duplicated semicolons, without removing newline * Review suggestions * No need for StringBuilder --- .../staticanalysis/RemoveExtraSemicolons.java | 22 ++++++------- .../RemoveExtraSemicolonsTest.java | 33 +++++++++++++++++++ 2 files changed, 43 insertions(+), 12 deletions(-) diff --git a/src/main/java/org/openrewrite/staticanalysis/RemoveExtraSemicolons.java b/src/main/java/org/openrewrite/staticanalysis/RemoveExtraSemicolons.java index 74b4b3a87..313d3a84c 100644 --- a/src/main/java/org/openrewrite/staticanalysis/RemoveExtraSemicolons.java +++ b/src/main/java/org/openrewrite/staticanalysis/RemoveExtraSemicolons.java @@ -15,15 +15,6 @@ */ package org.openrewrite.staticanalysis; -import java.time.Duration; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Optional; -import java.util.Set; - import org.openrewrite.ExecutionContext; import org.openrewrite.Recipe; import org.openrewrite.TreeVisitor; @@ -33,6 +24,9 @@ import org.openrewrite.java.tree.Space; import org.openrewrite.java.tree.Statement; +import java.time.Duration; +import java.util.*; + public class RemoveExtraSemicolons extends Recipe { @Override @@ -69,9 +63,13 @@ public J.Block visitBlock(final J.Block block, final ExecutionContext executionC if (statement instanceof J.Empty) { nextNonEmptyAggregatedWithComments(statement, iterator) .ifPresent(nextLine -> { - Space updatedPrefix = nextLine.getPrefix() - .withWhitespace(statement.getPrefix().getWhitespace()); - result.add(nextLine.withPrefix(updatedPrefix)); + String whitespace = statement.getPrefix().getWhitespace(); + if (!whitespace.contains("\n") && nextLine.getComments().isEmpty()) { + result.add(nextLine); + } else { + Space updatedPrefix = nextLine.getPrefix().withWhitespace(whitespace); + result.add(nextLine.withPrefix(updatedPrefix)); + } }); } else { result.add(statement); diff --git a/src/test/java/org/openrewrite/staticanalysis/RemoveExtraSemicolonsTest.java b/src/test/java/org/openrewrite/staticanalysis/RemoveExtraSemicolonsTest.java index 079350f59..e92110296 100644 --- a/src/test/java/org/openrewrite/staticanalysis/RemoveExtraSemicolonsTest.java +++ b/src/test/java/org/openrewrite/staticanalysis/RemoveExtraSemicolonsTest.java @@ -213,4 +213,37 @@ int test() { ) ); } + + @Test + void repeatedSemicolon() { + rewriteRun( + //language=java + java( + """ + class Test { + void test() { + int a = 1;; + int b = 2; + int c = 3;;; + int d = 4; + int e = 5; ; + int f = 6; + } + } + """, + """ + class Test { + void test() { + int a = 1; + int b = 2; + int c = 3; + int d = 4; + int e = 5; + int f = 6; + } + } + """ + ) + ); + } }