google-java-format icon indicating copy to clipboard operation
google-java-format copied to clipboard

Formatter leaves extra blank line when removing imports

Open toweroy opened this issue 3 years ago • 1 comments

What happens

When running the formatter against a class that will remove unused import(s) and would remove all imports of that type, the formatter leaves the surrounding empty lines. So for example:

package com.test;

import java.util.HashSet;
import java.util.Set;

public class ClassA {
  
}

The resulting formatted code leaves an empty line:

package com.test;


public class ClassA {}

Which will cause errors when checking the formatting.

What we expected

Formatter would leave a single empty line instead of two. Like so:

package com.test;

public class ClassA {}

Extra info

The line will be removed if the formatter is executed again.

toweroy avatar May 19 '22 12:05 toweroy

It looks like calling the formatter once again on that resulting file will remove the extra line.

Looks like an ordering issue between the formatter itself (which will remove the extra line) and the "remove unused imports" phase: "remove unused imports" will remove whole lines, but then when removing the whole imports block it leaves the blank lines before and after alone, and this phase is run after the formatter which would collapse the consecutive blank lines. Reversing the two phases would likely fix this issue, but maybe there's a reason to remove unused imports after formatting the file (formatting shouldn't remove code, so unused imports shouldn't change before and after, and it should be safe to reverse the phases IMO)

tbroyer avatar May 19 '22 13:05 tbroyer

#598

cushon avatar Dec 11 '23 02:12 cushon