Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Java cleanups #1619

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2016-2021 DiffPlug
* Copyright 2016-2023 DiffPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -60,7 +60,7 @@ public class EclipseBasedStepBuilder {
*/
private static final String ECLIPSE_FORMATTER_RESOURCES = EclipseBasedStepBuilder.class.getPackage().getName().replace('.', '/');

private List<String> dependencies = new ArrayList<>();
private final List<String> dependencies = new ArrayList<>();
private Iterable<File> settingsFiles = new ArrayList<>();

/** Initialize valid default configuration, taking latest version */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public boolean isClean(Project project, ObjectId treeSha, File file) throws IOEx
return isClean(project, treeSha, relativePath);
}

private Map<Repository, DirCache> dirCaches = new HashMap<>();
private final Map<Repository, DirCache> dirCaches = new HashMap<>();

/**
* This is the highest-level method, which all the others serve. Given the sha
Expand Down Expand Up @@ -136,9 +136,9 @@ private static boolean worktreeIsCleanCheckout(TreeWalk treeWalk) {
private final static int INDEX = 1;
private final static int WORKDIR = 2;

Map<File, Repository> gitRoots = new HashMap<>();
Table<Repository, String, ObjectId> rootTreeShaCache = HashBasedTable.create();
Map<Project, ObjectId> subtreeShaCache = new HashMap<>();
final Map<File, Repository> gitRoots = new HashMap<>();
final Table<Repository, String, ObjectId> rootTreeShaCache = HashBasedTable.create();
final Map<Project, ObjectId> subtreeShaCache = new HashMap<>();

/**
* The first part of making this fast is finding the appropriate git repository quickly. Because of composite
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2020-2022 DiffPlug
* Copyright 2020-2023 DiffPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -107,7 +107,7 @@ static class RepositorySpecificResolver extends FileRepositoryBuilder {

private File commonDirectory;

private Config baseConfig;
private final Config baseConfig;

public RepositorySpecificResolver() {
this(null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ private static String diffWhitespaceLineEndings(String dirty, String clean, bool
try (DiffFormatter formatter = new DiffFormatter(out)) {
formatter.format(edits, a, b);
}
String formatted = out.toString(StandardCharsets.UTF_8.name());
String formatted = out.toString(StandardCharsets.UTF_8);

// we don't need the diff to show this, since we display newlines ourselves
formatted = formatted.replace("\\ No newline at end of file\n", "");
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2016-2021 DiffPlug
* Copyright 2016-2023 DiffPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -15,7 +15,6 @@
*/
package com.diffplug.spotless.extra.wtp;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;
Expand Down Expand Up @@ -50,7 +49,7 @@ public enum EclipseWtpFormatterStep {
}

public EclipseBasedStepBuilder createBuilder(Provisioner provisioner) {
return new EclipseBasedStepBuilder(NAME, " - " + toString(), provisioner, state -> formatterCall.apply(implementationClassName, state));
return new EclipseBasedStepBuilder(NAME, " - " + this, provisioner, state -> formatterCall.apply(implementationClassName, state));
}

public static String defaultVersion() {
Expand Down Expand Up @@ -78,16 +77,13 @@ private static FormatterFunc applyWithFile(String className, EclipseBasedStepBui
Class<?> formatterClazz = state.loadClass(FORMATTER_PACKAGE + className);
Object formatter = formatterClazz.getConstructor(Properties.class).newInstance(state.getPreferences());
Method method = formatterClazz.getMethod(FORMATTER_METHOD, String.class, String.class);
return JVM_SUPPORT.suggestLaterVersionOnError(state.getSemanticVersion(), new FormatterFunc.NeedsFile() {
@Override
public String applyWithFile(String unix, File file) throws Exception {
try {
return (String) method.invoke(formatter, unix, file.getAbsolutePath());
} catch (InvocationTargetException exceptionWrapper) {
Throwable throwable = exceptionWrapper.getTargetException();
Exception exception = (throwable instanceof Exception) ? (Exception) throwable : null;
throw (null == exception) ? exceptionWrapper : exception;
}
return JVM_SUPPORT.suggestLaterVersionOnError(state.getSemanticVersion(), (FormatterFunc.NeedsFile) (unix, file) -> {
try {
return (String) method.invoke(formatter, unix, file.getAbsolutePath());
} catch (InvocationTargetException exceptionWrapper) {
Throwable throwable = exceptionWrapper.getTargetException();
Exception exception = (throwable instanceof Exception) ? (Exception) throwable : null;
throw (null == exception) ? exceptionWrapper : exception;
}
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ void policyTest() {
setFile(".gitattributes").toContent(StringPrinter.buildStringFromLines(
"* eol=lf",
"*.MF eol=crlf"));
LineEnding.Policy policy = LineEnding.GIT_ATTRIBUTES.createPolicy(rootFolder(), () -> testFiles());
LineEnding.Policy policy = LineEnding.GIT_ATTRIBUTES.createPolicy(rootFolder(), this::testFiles);
Assertions.assertThat(policy.getEndingFor(newFile("someFile"))).isEqualTo("\n");
Assertions.assertThat(policy.getEndingFor(newFile("subfolder/someFile"))).isEqualTo("\n");
Assertions.assertThat(policy.getEndingFor(newFile("MANIFEST.MF"))).isEqualTo("\r\n");
Expand All @@ -98,7 +98,7 @@ void policyDefaultLineEndingTest() throws GitAPIException {
"[core]",
"autocrlf=true",
"eol=lf"));
LineEnding.Policy policy = LineEnding.GIT_ATTRIBUTES.createPolicy(rootFolder(), () -> testFiles());
LineEnding.Policy policy = LineEnding.GIT_ATTRIBUTES.createPolicy(rootFolder(), this::testFiles);
Assertions.assertThat(policy.getEndingFor(newFile("someFile"))).isEqualTo("\r\n");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
package com.diffplug.spotless.glue.java;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

Expand All @@ -39,10 +38,10 @@
public class JavaCleanthatRefactorerFunc implements FormatterFunc {
private static final Logger LOGGER = LoggerFactory.getLogger(JavaCleanthatRefactorerFunc.class);

private String jdkVersion;
private List<String> included;
private List<String> excluded;
private boolean includeDraft;
private final String jdkVersion;
private final List<String> included;
private final List<String> excluded;
private final boolean includeDraft;

public JavaCleanthatRefactorerFunc(String jdkVersion, List<String> included, List<String> excluded, boolean includeDraft) {
this.jdkVersion = jdkVersion == null ? IJdkVersionConstants.JDK_8 : jdkVersion;
Expand All @@ -52,7 +51,7 @@ public JavaCleanthatRefactorerFunc(String jdkVersion, List<String> included, Lis
}

public JavaCleanthatRefactorerFunc() {
this(IJdkVersionConstants.JDK_8, Arrays.asList("SafeAndConsensual"), Arrays.asList(), false);
this(IJdkVersionConstants.JDK_8, List.of("SafeAndConsensual"), List.of(), false);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
*/
// https://github.com/FasterXML/jackson-dataformats-text/issues/372
public abstract class AJacksonFormatterFunc implements FormatterFunc {
private JacksonConfig jacksonConfig;
private final JacksonConfig jacksonConfig;

public AJacksonFormatterFunc(JacksonConfig jacksonConfig) {
this.jacksonConfig = jacksonConfig;
Expand All @@ -49,9 +49,8 @@ protected String format(ObjectMapper objectMapper, String input) throws IllegalA
try {
// ObjectNode is not compatible with SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS
Object objectNode = objectMapper.readValue(input, inferType(input));
String output = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(objectNode);

return output;
return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(objectNode);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException("Unable to format. input='" + input + "'", e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
*/
// https://github.com/FasterXML/jackson-dataformats-text/issues/372
public class JacksonJsonFormatterFunc extends AJacksonFormatterFunc {
private JacksonJsonConfig jacksonConfig;
private final JacksonJsonConfig jacksonConfig;

public JacksonJsonFormatterFunc(JacksonJsonConfig jacksonConfig) {
super(jacksonConfig);
Expand Down
6 changes: 3 additions & 3 deletions lib/src/main/java/com/diffplug/spotless/EncodingErrorMsg.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@

class EncodingErrorMsg {
static final char UNREPRESENTABLE = '�';
private static int CONTEXT = 3;
private static final int CONTEXT = 3;

static @Nullable String msg(String chars, byte[] bytes, Charset charset) {
int unrepresentable = chars.indexOf(UNREPRESENTABLE);
Expand Down Expand Up @@ -70,7 +70,7 @@ private EncodingErrorMsg(String chars, ByteBuffer byteBuf, Charset charset, int
if (charset.equals(StandardCharsets.UTF_8)) {
message.append("Spotless uses UTF-8 by default.");
} else {
message.append("You configured Spotless to use " + charset.name() + ".");
message.append("You configured Spotless to use ").append(charset.name()).append(".");
}

int line = 1;
Expand All @@ -84,7 +84,7 @@ private EncodingErrorMsg(String chars, ByteBuffer byteBuf, Charset charset, int
++col;
}
}
message.append(" At line " + line + " col " + col + ":");
message.append(" At line ").append(line).append(" col ").append(col).append(":");

// https://docs.oracle.com/javase/8/docs/technotes/guides/intl/encoding.doc.html
LinkedHashSet<Charset> encodings = new LinkedHashSet<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,8 @@ protected Class<?> findClass(String name) throws ClassNotFoundException {
private static boolean useBuildToolClassLoader(String name) {
if (name.startsWith("org.slf4j.")) {
return true;
} else if (!name.startsWith("com.diffplug.spotless.extra") && name.startsWith("com.diffplug.spotless.")) {
return true;
} else {
return false;
}
} else
return !name.startsWith("com.diffplug.spotless.extra") && name.startsWith("com.diffplug.spotless.");
}

@Override
Expand Down
10 changes: 5 additions & 5 deletions lib/src/main/java/com/diffplug/spotless/FileSignature.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2016-2021 DiffPlug
* Copyright 2016-2023 DiffPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -71,7 +71,7 @@ public static FileSignature signAsSet(Iterable<File> files) throws IOException {
StringBuilder builder = new StringBuilder();
builder.append("For these files:\n");
for (File file : files) {
builder.append(" " + file.getAbsolutePath() + "\n");
builder.append(" ").append(file.getAbsolutePath()).append("\n");
}
builder.append("a caching signature is being generated, which will be based only on their\n");
builder.append("names, not their full path (foo.txt, not C:\folder\foo.txt). Unexpectedly,\n");
Expand Down Expand Up @@ -107,7 +107,7 @@ public File getOnlyFile() {
}
}

private static boolean machineIsWin = System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("win");
private static final boolean machineIsWin = System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("win");

/** Returns true if this JVM is running on a windows machine. */
public static boolean machineIsWin() {
Expand Down Expand Up @@ -143,11 +143,11 @@ private static List<File> validateInputFiles(List<File> files) {
static final Cache cache = new Cache();

private static final class Cache {
Map<String, Sig> cache = new HashMap<>();
final Map<String, Sig> cache = new HashMap<>();

synchronized Sig sign(File fileInput) throws IOException {
String canonicalPath = fileInput.getCanonicalPath();
Sig sig = cache.computeIfAbsent(canonicalPath, ThrowingEx.<String, Sig> wrap(p -> {
Sig sig = cache.computeIfAbsent(canonicalPath, ThrowingEx.wrap(p -> {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
File file = new File(p);
// calculate the size and content hash of the file
Expand Down
4 changes: 2 additions & 2 deletions lib/src/main/java/com/diffplug/spotless/ForeignExe.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2020-2021 DiffPlug
* Copyright 2020-2023 DiffPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -129,7 +129,7 @@ private RuntimeException exceptionFmt(String msgPrimary, ProcessRunner.Result cm
errorMsg.append(msgFix);
errorMsg.append('\n');
}
errorMsg.append(cmd.toString());
errorMsg.append(cmd);
return new RuntimeException(errorMsg.toString());
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2016-2021 DiffPlug
* Copyright 2016-2023 DiffPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -20,20 +20,20 @@
/** A policy for handling exceptions in the format. */
public interface FormatExceptionPolicy extends Serializable, NoLambda {
/** Called for every error in the formatter. */
public void handleError(Throwable e, FormatterStep step, String relativePath);
void handleError(Throwable e, FormatterStep step, String relativePath);

/**
* Returns a byte array representation of everything inside this {@code FormatExceptionPolicy}.
*
* The main purpose of this method is to ensure one can't instantiate this class with lambda
* expressions, which are notoriously difficult to serialize and deserialize properly.
*/
public byte[] toBytes();
byte[] toBytes();

/**
* A policy which rethrows subclasses of {@code Error} and logs other kinds of Exception.
*/
public static FormatExceptionPolicy failOnlyOnError() {
static FormatExceptionPolicy failOnlyOnError() {
return new FormatExceptionPolicyLegacy();
}
}
8 changes: 4 additions & 4 deletions lib/src/main/java/com/diffplug/spotless/FormatterFunc.java
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ interface Closeable extends FormatterFunc, AutoCloseable {
* The bug (and its fix) which is easy to write using this method: https://github.com/diffplug/spotless/commit/7f16ecca031810b5e6e6f647e1f10a6d2152d9f4
* How the {@code of()} methods below make the correct thing easier to write and safer: https://github.com/diffplug/spotless/commit/18c10f9c93d6f18f753233d0b5f028d5f0961916
*/
public static Closeable ofDangerous(AutoCloseable closeable, FormatterFunc function) {
static Closeable ofDangerous(AutoCloseable closeable, FormatterFunc function) {
Objects.requireNonNull(closeable, "closeable");
Objects.requireNonNull(function, "function");
return new Closeable() {
Expand All @@ -73,7 +73,7 @@ public String apply(String unix) throws Exception {

/** @deprecated synonym for {@link #ofDangerous(AutoCloseable, FormatterFunc)} */
@Deprecated
public static Closeable of(AutoCloseable closeable, FormatterFunc function) {
static Closeable of(AutoCloseable closeable, FormatterFunc function) {
return ofDangerous(closeable, function);
}

Expand All @@ -83,7 +83,7 @@ interface ResourceFunc<T extends AutoCloseable> {
}

/** Creates a {@link FormatterFunc.Closeable} which uses the given resource to execute the format function. */
public static <T extends AutoCloseable> Closeable of(T resource, ResourceFunc<T> function) {
static <T extends AutoCloseable> Closeable of(T resource, ResourceFunc<T> function) {
Objects.requireNonNull(resource, "resource");
Objects.requireNonNull(function, "function");
return new Closeable() {
Expand All @@ -110,7 +110,7 @@ interface ResourceFuncNeedsFile<T extends AutoCloseable> {
}

/** Creates a {@link FormatterFunc.Closeable} which uses the given resource to execute the file-dependent format function. */
public static <T extends AutoCloseable> Closeable of(T resource, ResourceFuncNeedsFile<T> function) {
static <T extends AutoCloseable> Closeable of(T resource, ResourceFuncNeedsFile<T> function) {
Objects.requireNonNull(resource, "resource");
Objects.requireNonNull(function, "function");
return new Closeable() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2016-2021 DiffPlug
* Copyright 2016-2023 DiffPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -205,9 +205,8 @@ protected Properties execute(final File xmlFile, final Node rootNode)
protected Properties execute(File file, Node rootNode) throws IOException, IllegalArgumentException {
final Properties properties = new Properties();
Node firstProfile = getSingleProfile(rootNode);
for (Object settingObj : getChildren(firstProfile, "setting")) {
Node setting = (Node) settingObj;
NamedNodeMap attributes = setting.getAttributes();
for (Node settingObj : getChildren(firstProfile, "setting")) {
NamedNodeMap attributes = settingObj.getAttributes();
Node id = attributes.getNamedItem("id");
Node value = attributes.getNamedItem("value");
if (null == id) {
Expand Down
Loading