|
| 1 | +/* |
| 2 | + * Copyright 2023 DiffPlug |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package com.diffplug.spotless.groovy; |
| 17 | + |
| 18 | +import java.io.BufferedReader; |
| 19 | +import java.io.Serializable; |
| 20 | +import java.io.StringReader; |
| 21 | + |
| 22 | +import com.diffplug.spotless.FormatterFunc; |
| 23 | +import com.diffplug.spotless.FormatterStep; |
| 24 | + |
| 25 | +/** |
| 26 | + * Removes all semicolons from the end of lines. |
| 27 | + * |
| 28 | + * @author Jose Luis Badano |
| 29 | + */ |
| 30 | +public final class RemoveSemicolonsStep { |
| 31 | + private static final String NAME = "Remove unnecessary semicolons"; |
| 32 | + |
| 33 | + private RemoveSemicolonsStep() { |
| 34 | + // do not instantiate |
| 35 | + } |
| 36 | + |
| 37 | + public static FormatterStep create() { |
| 38 | + return FormatterStep.createLazy(NAME, |
| 39 | + State::new, |
| 40 | + RemoveSemicolonsStep.State::toFormatter); |
| 41 | + } |
| 42 | + |
| 43 | + private static final class State implements Serializable { |
| 44 | + private static final long serialVersionUID = 1L; |
| 45 | + |
| 46 | + FormatterFunc toFormatter() { |
| 47 | + return raw -> { |
| 48 | + try (BufferedReader reader = new BufferedReader(new StringReader(raw))) { |
| 49 | + StringBuilder result = new StringBuilder(); |
| 50 | + String line; |
| 51 | + while ((line = reader.readLine()) != null) { |
| 52 | + result.append(removeSemicolon(line)); |
| 53 | + result.append(System.lineSeparator()); |
| 54 | + } |
| 55 | + return result.toString(); |
| 56 | + } |
| 57 | + }; |
| 58 | + } |
| 59 | + |
| 60 | + /** |
| 61 | + * Removes the last semicolon in a line if it exists. |
| 62 | + * |
| 63 | + * @param line the line to remove the semicolon from |
| 64 | + * @return the line without the last semicolon |
| 65 | + */ |
| 66 | + private String removeSemicolon(String line) { |
| 67 | + // find last semicolon in a string a remove it |
| 68 | + int lastSemicolon = line.lastIndexOf(";"); |
| 69 | + if (lastSemicolon != -1 && lastSemicolon == line.length() - 1) { |
| 70 | + return line.substring(0, lastSemicolon); |
| 71 | + } else { |
| 72 | + return line; |
| 73 | + } |
| 74 | + } |
| 75 | + } |
| 76 | +} |
0 commit comments