com.diffplug.spotless.maven.FormattersHolder Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of spotless-maven-plugin Show documentation
Show all versions of spotless-maven-plugin Show documentation
Spotless - keep your code spotless with Gradle
/*
* Copyright 2021-2023 DiffPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.diffplug.spotless.maven;
import java.io.File;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.function.Supplier;
import com.diffplug.spotless.Formatter;
class FormattersHolder implements AutoCloseable {
private final Map>> formatterToFiles;
FormattersHolder(Map>> formatterToFiles) {
this.formatterToFiles = formatterToFiles;
}
static FormattersHolder create(Map>> formatterFactoryToFiles, FormatterConfig config) {
Map>> formatterToFiles = new LinkedHashMap<>();
try {
for (Entry>> entry : formatterFactoryToFiles.entrySet()) {
FormatterFactory formatterFactory = entry.getKey();
Supplier> files = entry.getValue();
Formatter formatter = formatterFactory.newFormatter(files, config);
formatterToFiles.put(formatter, files);
}
} catch (RuntimeException openError) {
try {
close(formatterToFiles.keySet());
} catch (Exception closeError) {
openError.addSuppressed(closeError);
}
throw openError;
}
return new FormattersHolder(formatterToFiles);
}
Iterable getFormatters() {
return formatterToFiles.keySet();
}
Map>> getFormattersWithFiles() {
return formatterToFiles;
}
@Override
public void close() {
try {
close(formatterToFiles.keySet());
} catch (Exception e) {
throw new RuntimeException("Unable to close formatters", e);
}
}
private static void close(Set formatters) throws Exception {
Exception error = null;
for (Formatter formatter : formatters) {
try {
formatter.close();
} catch (Exception e) {
if (error == null) {
error = e;
} else {
error.addSuppressed(e);
}
}
}
if (error != null) {
throw error;
}
}
}