|
| 1 | +/* |
| 2 | + * Copyright 2020-2024 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.generic; |
| 17 | + |
| 18 | +import java.io.File; |
| 19 | +import java.io.Serializable; |
| 20 | +import java.nio.charset.StandardCharsets; |
| 21 | +import java.nio.file.Path; |
| 22 | +import java.util.ArrayList; |
| 23 | +import java.util.List; |
| 24 | +import java.util.Objects; |
| 25 | +import java.util.regex.Matcher; |
| 26 | +import java.util.regex.Pattern; |
| 27 | + |
| 28 | +import com.diffplug.spotless.Formatter; |
| 29 | +import com.diffplug.spotless.FormatterFunc; |
| 30 | +import com.diffplug.spotless.FormatterStep; |
| 31 | +import com.diffplug.spotless.LineEnding; |
| 32 | +import com.diffplug.spotless.SerializedFunction; |
| 33 | + |
| 34 | +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; |
| 35 | + |
| 36 | +public class FenceStep { |
| 37 | + /** Declares the name of the step. */ |
| 38 | + public static FenceStep named(String name) { |
| 39 | + return new FenceStep(name); |
| 40 | + } |
| 41 | + |
| 42 | + public static String defaultToggleName() { |
| 43 | + return "toggle"; |
| 44 | + } |
| 45 | + |
| 46 | + public static String defaultToggleOff() { |
| 47 | + return "spotless:off"; |
| 48 | + } |
| 49 | + |
| 50 | + public static String defaultToggleOn() { |
| 51 | + return "spotless:on"; |
| 52 | + } |
| 53 | + |
| 54 | + String name; |
| 55 | + Pattern regex; |
| 56 | + |
| 57 | + private FenceStep(String name) { |
| 58 | + this.name = Objects.requireNonNull(name); |
| 59 | + } |
| 60 | + |
| 61 | + /** Defines the opening and closing markers. */ |
| 62 | + public FenceStep openClose(String open, String close) { |
| 63 | + return regex(Pattern.quote(open) + "([\\s\\S]*?)" + Pattern.quote(close)); |
| 64 | + } |
| 65 | + |
| 66 | + /** Defines the pipe via regex. Must have *exactly one* capturing group. */ |
| 67 | + public FenceStep regex(String regex) { |
| 68 | + return regex(Pattern.compile(regex)); |
| 69 | + } |
| 70 | + |
| 71 | + /** Defines the pipe via regex. Must have *exactly one* capturing group. */ |
| 72 | + public FenceStep regex(Pattern regex) { |
| 73 | + this.regex = Objects.requireNonNull(regex); |
| 74 | + return this; |
| 75 | + } |
| 76 | + |
| 77 | + private void assertRegexSet() { |
| 78 | + Objects.requireNonNull(regex, "must call regex() or openClose()"); |
| 79 | + } |
| 80 | + |
| 81 | + /** Returns a step which will apply the given steps but preserve the content selected by the regex / openClose pair. */ |
| 82 | + public FormatterStep preserveWithin(List<FormatterStep> steps) { |
| 83 | + assertRegexSet(); |
| 84 | + return FormatterStep.createLazy(name, |
| 85 | + () -> new PreserveWithin(regex, steps), |
| 86 | + SerializedFunction.identity(), |
| 87 | + state -> FormatterFunc.Closeable.of(state.buildFormatter(), state)); |
| 88 | + } |
| 89 | + |
| 90 | + /** |
| 91 | + * Returns a step which will apply the given steps only within the blocks selected by the regex / openClose pair. |
| 92 | + * Linting within the substeps is not supported. |
| 93 | + */ |
| 94 | + public FormatterStep applyWithin(List<FormatterStep> steps) { |
| 95 | + assertRegexSet(); |
| 96 | + return FormatterStep.createLazy(name, |
| 97 | + () -> new ApplyWithin(regex, steps), |
| 98 | + SerializedFunction.identity(), |
| 99 | + state -> FormatterFunc.Closeable.of(state.buildFormatter(), state)); |
| 100 | + } |
| 101 | + |
| 102 | + static class ApplyWithin extends Apply implements FormatterFunc.Closeable.ResourceFuncNeedsFile<Formatter> { |
| 103 | + private static final long serialVersionUID = 17061466531957339L; |
| 104 | + |
| 105 | + ApplyWithin(Pattern regex, List<FormatterStep> steps) { |
| 106 | + super(regex, steps); |
| 107 | + } |
| 108 | + |
| 109 | + @Override |
| 110 | + public String apply(Formatter formatter, String unix, File file) throws Exception { |
| 111 | + List<String> groups = groupsZeroed(); |
| 112 | + Matcher matcher = regex.matcher(unix); |
| 113 | + while (matcher.find()) { |
| 114 | + // apply the formatter to each group |
| 115 | + groups.add(formatter.compute(matcher.group(1), file)); |
| 116 | + } |
| 117 | + // and then assemble the result right away |
| 118 | + return assembleGroups(unix); |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + static class PreserveWithin extends Apply implements FormatterFunc.Closeable.ResourceFuncNeedsFile<Formatter> { |
| 123 | + private static final long serialVersionUID = -8676786492305178343L; |
| 124 | + |
| 125 | + PreserveWithin(Pattern regex, List<FormatterStep> steps) { |
| 126 | + super(regex, steps); |
| 127 | + } |
| 128 | + |
| 129 | + private void storeGroups(String unix) { |
| 130 | + List<String> groups = groupsZeroed(); |
| 131 | + Matcher matcher = regex.matcher(unix); |
| 132 | + while (matcher.find()) { |
| 133 | + // store whatever is within the open/close tags |
| 134 | + groups.add(matcher.group(1)); |
| 135 | + } |
| 136 | + } |
| 137 | + |
| 138 | + @Override |
| 139 | + public String apply(Formatter formatter, String unix, File file) throws Exception { |
| 140 | + storeGroups(unix); |
| 141 | + String formatted = formatter.compute(unix, file); |
| 142 | + return assembleGroups(formatted); |
| 143 | + } |
| 144 | + } |
| 145 | + |
| 146 | + @SuppressFBWarnings("SE_TRANSIENT_FIELD_NOT_RESTORED") |
| 147 | + static class Apply implements Serializable { |
| 148 | + private static final long serialVersionUID = -2301848328356559915L; |
| 149 | + final Pattern regex; |
| 150 | + final List<FormatterStep> steps; |
| 151 | + |
| 152 | + transient ArrayList<String> groups = new ArrayList<>(); |
| 153 | + transient StringBuilder builderInternal; |
| 154 | + |
| 155 | + public Apply(Pattern regex, List<FormatterStep> steps) { |
| 156 | + this.regex = regex; |
| 157 | + this.steps = steps; |
| 158 | + } |
| 159 | + |
| 160 | + protected ArrayList<String> groupsZeroed() { |
| 161 | + if (groups == null) { |
| 162 | + groups = new ArrayList<>(); |
| 163 | + } else { |
| 164 | + groups.clear(); |
| 165 | + } |
| 166 | + return groups; |
| 167 | + } |
| 168 | + |
| 169 | + private StringBuilder builderZeroed() { |
| 170 | + if (builderInternal == null) { |
| 171 | + builderInternal = new StringBuilder(); |
| 172 | + } else { |
| 173 | + builderInternal.setLength(0); |
| 174 | + } |
| 175 | + return builderInternal; |
| 176 | + } |
| 177 | + |
| 178 | + protected Formatter buildFormatter() { |
| 179 | + return Formatter.builder() |
| 180 | + .encoding(StandardCharsets.UTF_8) // can be any UTF, doesn't matter |
| 181 | + .lineEndingsPolicy(LineEnding.UNIX.createPolicy()) // just internal, won't conflict with user |
| 182 | + .steps(steps) |
| 183 | + .rootDir(Path.of("")) // TODO: error messages will be suboptimal for now, but it will get fixed when we ship linting |
| 184 | + .build(); |
| 185 | + } |
| 186 | + |
| 187 | + protected String assembleGroups(String unix) { |
| 188 | + if (groups.isEmpty()) { |
| 189 | + return unix; |
| 190 | + } |
| 191 | + StringBuilder builder = builderZeroed(); |
| 192 | + Matcher matcher = regex.matcher(unix); |
| 193 | + int lastEnd = 0; |
| 194 | + int groupIdx = 0; |
| 195 | + while (matcher.find()) { |
| 196 | + builder.append(unix, lastEnd, matcher.start(1)); |
| 197 | + builder.append(groups.get(groupIdx)); |
| 198 | + lastEnd = matcher.end(1); |
| 199 | + ++groupIdx; |
| 200 | + } |
| 201 | + if (groupIdx == groups.size()) { |
| 202 | + builder.append(unix, lastEnd, unix.length()); |
| 203 | + return builder.toString(); |
| 204 | + } else { |
| 205 | + // these will be needed to generate Lints later on |
| 206 | + // int startLine = 1 + (int) builder.toString().codePoints().filter(c -> c == '\n').count(); |
| 207 | + // int endLine = 1 + (int) unix.codePoints().filter(c -> c == '\n').count(); |
| 208 | + |
| 209 | + // throw an error with either the full regex, or the nicer open/close pair |
| 210 | + Matcher openClose = Pattern.compile("\\\\Q([\\s\\S]*?)\\\\E" + "\\Q([\\s\\S]*?)\\E" + "\\\\Q([\\s\\S]*?)\\\\E") |
| 211 | + .matcher(regex.pattern()); |
| 212 | + String pattern; |
| 213 | + if (openClose.matches()) { |
| 214 | + pattern = openClose.group(1) + " " + openClose.group(2); |
| 215 | + } else { |
| 216 | + pattern = regex.pattern(); |
| 217 | + } |
| 218 | + throw new Error("An intermediate step removed a match of " + pattern); |
| 219 | + } |
| 220 | + } |
| 221 | + } |
| 222 | +} |
0 commit comments