From 225d992fcf8fee26b7a3ca820f3fc82bc2bf064d Mon Sep 17 00:00:00 2001 From: "benjamin.gentner" Date: Fri, 2 Sep 2022 16:34:35 +0200 Subject: [PATCH 01/59] Fix Freshmark compatibility with JDK 15+ (fixes #803) --- .../spotless/markdown/FreshMarkStep.java | 16 +++++++++++++++- .../spotless/markdown/FreshMarkStepTest.java | 6 +----- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/lib/src/main/java/com/diffplug/spotless/markdown/FreshMarkStep.java b/lib/src/main/java/com/diffplug/spotless/markdown/FreshMarkStep.java index 2591cac7a5..fd03e95046 100644 --- a/lib/src/main/java/com/diffplug/spotless/markdown/FreshMarkStep.java +++ b/lib/src/main/java/com/diffplug/spotless/markdown/FreshMarkStep.java @@ -19,6 +19,8 @@ import java.io.Serializable; import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; import java.util.Map; import java.util.NavigableMap; import java.util.Objects; @@ -31,6 +33,7 @@ import com.diffplug.spotless.FormatterFunc; import com.diffplug.spotless.FormatterStep; import com.diffplug.spotless.JarState; +import com.diffplug.spotless.Jvm; import com.diffplug.spotless.Provisioner; import com.diffplug.spotless.ThrowingEx.Supplier; @@ -42,6 +45,10 @@ private FreshMarkStep() {} private static final String DEFAULT_VERSION = "1.3.1"; private static final String NAME = "freshmark"; private static final String MAVEN_COORDINATE = "com.diffplug.freshmark:freshmark:"; + + private static final String NASHORN_MAVEN_COORDINATE = "org.openjdk.nashorn:nashorn-core:"; + + private static final String NASHORN_VERSION = "15.4"; private static final String FORMATTER_CLASS = "com.diffplug.freshmark.FreshMark"; private static final String FORMATTER_METHOD = "compile"; @@ -55,8 +62,15 @@ public static FormatterStep create(String version, Supplier> prop Objects.requireNonNull(version, "version"); Objects.requireNonNull(properties, "properties"); Objects.requireNonNull(provisioner, "provisioner"); + + List mavenCoordinates = new ArrayList<>(); + mavenCoordinates.add(MAVEN_COORDINATE + version); + if (Jvm.version() >= 15) { + mavenCoordinates.add(NASHORN_MAVEN_COORDINATE + NASHORN_VERSION); + } + return FormatterStep.createLazy(NAME, - () -> new State(JarState.from(MAVEN_COORDINATE + version, provisioner), properties.get()), + () -> new State(JarState.from(mavenCoordinates, provisioner), properties.get()), State::createFormat); } diff --git a/testlib/src/test/java/com/diffplug/spotless/markdown/FreshMarkStepTest.java b/testlib/src/test/java/com/diffplug/spotless/markdown/FreshMarkStepTest.java index 477642e247..a5fede28bc 100644 --- a/testlib/src/test/java/com/diffplug/spotless/markdown/FreshMarkStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/markdown/FreshMarkStepTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 DiffPlug + * Copyright 2016-2022 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,20 +15,16 @@ */ package com.diffplug.spotless.markdown; -import static org.junit.jupiter.api.condition.JRE.JAVA_14; - import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.condition.EnabledForJreRange; import com.diffplug.spotless.FormatterStep; import com.diffplug.spotless.SerializableEqualityTester; import com.diffplug.spotless.StepHarness; import com.diffplug.spotless.TestProvisioner; -@EnabledForJreRange(max = JAVA_14) class FreshMarkStepTest { @Test void behavior() throws Exception { From fed3ffc811da37a30921aa9835627e8ca377c2e2 Mon Sep 17 00:00:00 2001 From: Benoit Lacelle Date: Thu, 19 Jan 2023 19:42:01 +0400 Subject: [PATCH 02/59] First commit to discuss the idea --- .../spotless/maven/ImpactedFilesTracker.java | 24 +++++++++++++++++++ .../spotless/maven/SpotlessApplyMojo.java | 8 +++++++ 2 files changed, 32 insertions(+) create mode 100644 plugin-maven/src/main/java/com/diffplug/spotless/maven/ImpactedFilesTracker.java diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/ImpactedFilesTracker.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/ImpactedFilesTracker.java new file mode 100644 index 0000000000..6019591e09 --- /dev/null +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/ImpactedFilesTracker.java @@ -0,0 +1,24 @@ +package com.diffplug.spotless.maven; + +import java.util.concurrent.atomic.AtomicInteger; + +public class ImpactedFilesTracker { + protected final AtomicInteger nbChecked = new AtomicInteger(); + protected final AtomicInteger nbCleaned = new AtomicInteger(); + + public void checked() { + nbChecked.incrementAndGet(); + } + + public int getChecked() { + return nbChecked.get(); + } + + public void cleaned() { + nbCleaned.incrementAndGet(); + } + + public int getCleaned() { + return nbCleaned.get(); + } +} diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java index 7a15d01b17..b617505826 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java @@ -33,6 +33,8 @@ public class SpotlessApplyMojo extends AbstractSpotlessMojo { @Override protected void process(Iterable files, Formatter formatter, UpToDateChecker upToDateChecker) throws MojoExecutionException { + ImpactedFilesTracker impactedFilesTracker = new ImpactedFilesTracker(); + for (File file : files) { if (upToDateChecker.isUpToDate(file.toPath())) { if (getLog().isDebugEnabled()) { @@ -42,10 +44,13 @@ protected void process(Iterable files, Formatter formatter, UpToDateChecke } try { + impactedFilesTracker.checked(); PaddedCell.DirtyState dirtyState = PaddedCell.calculateDirtyState(formatter, file); if (!dirtyState.isClean() && !dirtyState.didNotConverge()) { + getLog().info(String.format("Writing clean file: %s", file)); dirtyState.writeCanonicalTo(file); buildContext.refresh(file); + impactedFilesTracker.cleaned(); } } catch (IOException e) { throw new MojoExecutionException("Unable to format file " + file, e); @@ -53,5 +58,8 @@ protected void process(Iterable files, Formatter formatter, UpToDateChecke upToDateChecker.setUpToDate(file.toPath()); } + + // We print the number of considered files which is useful when ratchetFrom is setup + getLog().info(String.format("A formatter with %s steps cleaned: %s files (for %s considered)", formatter.getSteps().size(), impactedFilesTracker.getCleaned(), impactedFilesTracker.getChecked())); } } From 8e1865052fb0300123a2bed4ca271a945bde0574 Mon Sep 17 00:00:00 2001 From: Ned Twigg Date: Thu, 26 Jan 2023 13:49:53 -0800 Subject: [PATCH 03/59] spotlessApply for 2023 --- .../main/java/com/diffplug/spotless/markdown/FreshMarkStep.java | 2 +- .../java/com/diffplug/spotless/markdown/FreshMarkStepTest.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/src/main/java/com/diffplug/spotless/markdown/FreshMarkStep.java b/lib/src/main/java/com/diffplug/spotless/markdown/FreshMarkStep.java index fd03e95046..fca5ac39a4 100644 --- a/lib/src/main/java/com/diffplug/spotless/markdown/FreshMarkStep.java +++ b/lib/src/main/java/com/diffplug/spotless/markdown/FreshMarkStep.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 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. diff --git a/testlib/src/test/java/com/diffplug/spotless/markdown/FreshMarkStepTest.java b/testlib/src/test/java/com/diffplug/spotless/markdown/FreshMarkStepTest.java index a5fede28bc..586212383d 100644 --- a/testlib/src/test/java/com/diffplug/spotless/markdown/FreshMarkStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/markdown/FreshMarkStepTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 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. From b0d16195d45c04a06965217b2bc14bd69d3fe2aa Mon Sep 17 00:00:00 2001 From: Benoit Lacelle Date: Sat, 28 Jan 2023 18:39:41 +0400 Subject: [PATCH 04/59] Introduce Formatter.name, Improve synthesis log --- .../java/com/diffplug/spotless/Formatter.java | 26 +++++++++++++--- .../gradle/spotless/SpotlessTask.java | 3 +- .../spotless/maven/FormatterFactory.java | 4 ++- .../spotless/maven/ImpactedFilesTracker.java | 31 +++++++++++++++++++ .../spotless/maven/SpotlessApplyMojo.java | 10 ++++-- .../spotless/StepHarnessWithFile.java | 1 + 6 files changed, 67 insertions(+), 8 deletions(-) diff --git a/lib/src/main/java/com/diffplug/spotless/Formatter.java b/lib/src/main/java/com/diffplug/spotless/Formatter.java index 038e77fa64..bdfe008a61 100644 --- a/lib/src/main/java/com/diffplug/spotless/Formatter.java +++ b/lib/src/main/java/com/diffplug/spotless/Formatter.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 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. @@ -39,13 +39,16 @@ public final class Formatter implements Serializable, AutoCloseable { private static final long serialVersionUID = 1L; + // The name is used for logging purpose. It does not convey any applicative purpose + private String name; private LineEnding.Policy lineEndingsPolicy; private Charset encoding; private Path rootDir; private List steps; private FormatExceptionPolicy exceptionPolicy; - private Formatter(LineEnding.Policy lineEndingsPolicy, Charset encoding, Path rootDirectory, List steps, FormatExceptionPolicy exceptionPolicy) { + private Formatter(String name, LineEnding.Policy lineEndingsPolicy, Charset encoding, Path rootDirectory, List steps, FormatExceptionPolicy exceptionPolicy) { + this.name = name; this.lineEndingsPolicy = Objects.requireNonNull(lineEndingsPolicy, "lineEndingsPolicy"); this.encoding = Objects.requireNonNull(encoding, "encoding"); this.rootDir = Objects.requireNonNull(rootDirectory, "rootDir"); @@ -55,6 +58,7 @@ private Formatter(LineEnding.Policy lineEndingsPolicy, Charset encoding, Path ro // override serialize output private void writeObject(ObjectOutputStream out) throws IOException { + out.writeObject(name); out.writeObject(lineEndingsPolicy); out.writeObject(encoding.name()); out.writeObject(rootDir.toString()); @@ -65,6 +69,7 @@ private void writeObject(ObjectOutputStream out) throws IOException { // override serialize input @SuppressWarnings("unchecked") private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + name = (String) in.readObject(); lineEndingsPolicy = (LineEnding.Policy) in.readObject(); encoding = Charset.forName((String) in.readObject()); rootDir = Paths.get((String) in.readObject()); @@ -78,6 +83,10 @@ private void readObjectNoData() throws ObjectStreamException { throw new UnsupportedOperationException(); } + public String getName() { + return name; + } + public LineEnding.Policy getLineEndingsPolicy() { return lineEndingsPolicy; } @@ -103,6 +112,8 @@ public static Formatter.Builder builder() { } public static class Builder { + // optional parameters + private String name = "misc"; // required parameters private LineEnding.Policy lineEndingsPolicy; private Charset encoding; @@ -112,6 +123,11 @@ public static class Builder { private Builder() {} + public Builder name(String name) { + this.name = name; + return this; + } + public Builder lineEndingsPolicy(LineEnding.Policy lineEndingsPolicy) { this.lineEndingsPolicy = lineEndingsPolicy; return this; @@ -138,7 +154,7 @@ public Builder exceptionPolicy(FormatExceptionPolicy exceptionPolicy) { } public Formatter build() { - return new Formatter(lineEndingsPolicy, encoding, rootDir, steps, + return new Formatter(name, lineEndingsPolicy, encoding, rootDir, steps, exceptionPolicy == null ? FormatExceptionPolicy.failOnlyOnError() : exceptionPolicy); } } @@ -248,6 +264,7 @@ public String compute(String unix, File file) { public int hashCode() { final int prime = 31; int result = 1; + result = prime * result + name.hashCode(); result = prime * result + encoding.hashCode(); result = prime * result + lineEndingsPolicy.hashCode(); result = prime * result + rootDir.hashCode(); @@ -268,7 +285,8 @@ public boolean equals(Object obj) { return false; } Formatter other = (Formatter) obj; - return encoding.equals(other.encoding) && + return name.equals(other.name) && + encoding.equals(other.encoding) && lineEndingsPolicy.equals(other.lineEndingsPolicy) && rootDir.equals(other.rootDir) && steps.equals(other.steps) && diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTask.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTask.java index 6f2279b2e0..c23cea0845 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTask.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTask.java @@ -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. @@ -184,6 +184,7 @@ String formatName() { Formatter buildFormatter() { return Formatter.builder() + .name(formatName()) .lineEndingsPolicy(lineEndingsPolicy.get()) .encoding(Charset.forName(encoding)) .rootDir(getProjectDir().get().getAsFile().toPath()) diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/FormatterFactory.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/FormatterFactory.java index d5fbe60370..b78e987d34 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/FormatterFactory.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/FormatterFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 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. @@ -101,7 +101,9 @@ public final Formatter newFormatter(Supplier> filesToFormat, Form formatterSteps.add(pair.out()); } + String formatterName = this.getClass().getSimpleName(); return Formatter.builder() + .name(formatterName) .encoding(formatterEncoding) .lineEndingsPolicy(formatterLineEndingPolicy) .exceptionPolicy(new FormatExceptionPolicyStrict()) diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/ImpactedFilesTracker.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/ImpactedFilesTracker.java index 6019591e09..7474c109bc 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/ImpactedFilesTracker.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/ImpactedFilesTracker.java @@ -1,11 +1,41 @@ +/* + * Copyright 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.util.concurrent.atomic.AtomicInteger; +/** + * Tracks the number of processed files, typically by a single Formatter for a whole repository + */ public class ImpactedFilesTracker { + protected final AtomicInteger nbSkipped = new AtomicInteger(); protected final AtomicInteger nbChecked = new AtomicInteger(); protected final AtomicInteger nbCleaned = new AtomicInteger(); + /** + * Some cache mechanism may indicate some content is clean, without having to execute the cleaning process + */ + public void skippedAsCleanCache() { + nbSkipped.incrementAndGet(); + } + + public int getSkipped() { + return nbSkipped.get(); + } + public void checked() { nbChecked.incrementAndGet(); } @@ -21,4 +51,5 @@ public void cleaned() { public int getCleaned() { return nbCleaned.get(); } + } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java index b617505826..0f712ecd12 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 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. @@ -37,6 +37,7 @@ protected void process(Iterable files, Formatter formatter, UpToDateChecke for (File file : files) { if (upToDateChecker.isUpToDate(file.toPath())) { + impactedFilesTracker.skippedAsCleanCache(); if (getLog().isDebugEnabled()) { getLog().debug("Spotless will not format an up-to-date file: " + file); } @@ -60,6 +61,11 @@ protected void process(Iterable files, Formatter formatter, UpToDateChecke } // We print the number of considered files which is useful when ratchetFrom is setup - getLog().info(String.format("A formatter with %s steps cleaned: %s files (for %s considered)", formatter.getSteps().size(), impactedFilesTracker.getCleaned(), impactedFilesTracker.getChecked())); + int nbSkipped = impactedFilesTracker.getSkipped(); + int nbChecked = impactedFilesTracker.getChecked(); + int nbCleaned = impactedFilesTracker.getCleaned(); + int totalProcessed = nbSkipped + nbChecked + nbCleaned; + getLog().info(String.format("Spotless.%s is keeping %s files clean - %s were changed to be clean, %s were already clean, %s were skipped because caching determined they were already clean", + formatter.getName(), totalProcessed, nbCleaned, nbChecked, nbSkipped)); } } diff --git a/testlib/src/main/java/com/diffplug/spotless/StepHarnessWithFile.java b/testlib/src/main/java/com/diffplug/spotless/StepHarnessWithFile.java index 98a709c59f..9a9eb4042b 100644 --- a/testlib/src/main/java/com/diffplug/spotless/StepHarnessWithFile.java +++ b/testlib/src/main/java/com/diffplug/spotless/StepHarnessWithFile.java @@ -38,6 +38,7 @@ private StepHarnessWithFile(ResourceHarness harness, Formatter formatter) { /** Creates a harness for testing steps which do depend on the file. */ public static StepHarnessWithFile forStep(ResourceHarness harness, FormatterStep step) { return new StepHarnessWithFile(harness, Formatter.builder() + .name(step.getName()) .encoding(StandardCharsets.UTF_8) .lineEndingsPolicy(LineEnding.UNIX.createPolicy()) .steps(Collections.singletonList(step)) From 0bb25119d7f96220f4aa5b4072053849a9b06662 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sun, 29 Jan 2023 13:17:02 +0000 Subject: [PATCH 05/59] Update dependency org.mockito:mockito-core to v5.1.0 --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index dc4f24a36b..6256e51203 100644 --- a/gradle.properties +++ b/gradle.properties @@ -28,4 +28,4 @@ VER_DURIAN=1.2.0 VER_JGIT=6.4.0.202211300538-r VER_JUNIT=5.9.2 VER_ASSERTJ=3.24.2 -VER_MOCKITO=5.0.0 +VER_MOCKITO=5.1.0 From cc03d541e9e2a8b645e54e535ad0259c959c1ff7 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 30 Jan 2023 09:08:11 +0000 Subject: [PATCH 06/59] Update plugin com.diffplug.spotless-changelog to v3 --- settings.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/settings.gradle b/settings.gradle index 0ee51448dd..379daca7bb 100644 --- a/settings.gradle +++ b/settings.gradle @@ -14,7 +14,7 @@ plugins { // https://github.com/spotbugs/spotbugs-gradle-plugin/releases id 'com.github.spotbugs' version '5.0.13' apply false // https://github.com/diffplug/spotless-changelog/blob/main/CHANGELOG.md - id 'com.diffplug.spotless-changelog' version '2.4.1' apply false + id 'com.diffplug.spotless-changelog' version '3.0.1' apply false // https://github.com/diffplug/goomph/blob/main/CHANGES.md // DO NOT UPDATE, see https://github.com/diffplug/spotless/pull/874 id 'com.diffplug.p2.asmaven' version '3.27.0' apply false From cf2a4eb08d002db8b4c51fa4c43ad022361a6013 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 30 Jan 2023 16:37:03 +0000 Subject: [PATCH 07/59] Update plugin com.gradle.enterprise to v3.12.3 --- settings.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/settings.gradle b/settings.gradle index 0ee51448dd..e476425c96 100644 --- a/settings.gradle +++ b/settings.gradle @@ -23,7 +23,7 @@ plugins { // https://github.com/davidburstrom/version-compatibility-gradle-plugin/tags id 'io.github.davidburstrom.version-compatibility' version '0.4.0' apply false // https://plugins.gradle.org/plugin/com.gradle.enterprise - id 'com.gradle.enterprise' version '3.12.2' + id 'com.gradle.enterprise' version '3.12.3' } dependencyResolutionManagement { From cf434f2eecf9a9369f22c1c95f56adbb792df30f Mon Sep 17 00:00:00 2001 From: Benoit Lacelle Date: Mon, 30 Jan 2023 23:19:53 +0400 Subject: [PATCH 08/59] Start with Cleanthat Java refactorer --- .../java/JavaCleanthatRefactorerFunc.java | 56 +++++++ .../spotless/java/CleanthatStepFactory.java | 140 ++++++++++++++++++ 2 files changed, 196 insertions(+) create mode 100644 lib/src/cleanthat/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFunc.java create mode 100644 lib/src/main/java/com/diffplug/spotless/java/CleanthatStepFactory.java diff --git a/lib/src/cleanthat/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFunc.java b/lib/src/cleanthat/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFunc.java new file mode 100644 index 0000000000..bc96f0019b --- /dev/null +++ b/lib/src/cleanthat/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFunc.java @@ -0,0 +1,56 @@ +/* + * Copyright 2021-2023 Solven + * + * 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.glue.java; + +import com.diffplug.spotless.FormatterFunc; +import eu.solven.cleanthat.config.pojo.CleanthatEngineProperties; +import eu.solven.cleanthat.engine.java.refactorer.JavaRefactorer; +import eu.solven.cleanthat.engine.java.refactorer.JavaRefactorerProperties; +import eu.solven.cleanthat.formatter.LineEnding; +import eu.solven.cleanthat.formatter.PathAndContent; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class JavaCleanthatRefactorerFunc implements FormatterFunc { + private List included; + private List excluded; + + public JavaCleanthatRefactorerFunc(List included, List excluded) { + this.included = included == null ? Collections.emptyList() : included; + this.excluded = excluded == null ? Collections.emptyList() : excluded; + } + + public JavaCleanthatRefactorerFunc() { + this(Arrays.asList(JavaRefactorerProperties.WILDCARD), Arrays.asList()); + } + + @Override + public String apply(String input) throws Exception { + JavaRefactorerProperties refactorerProperties = new JavaRefactorerProperties(); + + refactorerProperties.setIncluded(included); + refactorerProperties.setExcluded(excluded); + + JavaRefactorer refactorer = + new JavaRefactorer(CleanthatEngineProperties.builder().build(), refactorerProperties); + + // Spotless calls steps always with LF eol. + return refactorer.doFormat(new PathAndContent(Paths.get("fake"), input), LineEnding.LF); + } + +} diff --git a/lib/src/main/java/com/diffplug/spotless/java/CleanthatStepFactory.java b/lib/src/main/java/com/diffplug/spotless/java/CleanthatStepFactory.java new file mode 100644 index 0000000000..fa9936fb1e --- /dev/null +++ b/lib/src/main/java/com/diffplug/spotless/java/CleanthatStepFactory.java @@ -0,0 +1,140 @@ +/* + * Copyright 2016-2023 Solven + * + * 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.java; + +import com.diffplug.spotless.FormatterFunc; +import com.diffplug.spotless.FormatterStep; +import com.diffplug.spotless.JarState; +import com.diffplug.spotless.Jvm; +import com.diffplug.spotless.Provisioner; +import java.io.IOException; +import java.io.Serializable; +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.util.List; +import java.util.Objects; + +/** + * Enables CleanThat as a SpotLess step. This may be moved to Spotless own repo + * (https://github.com/diffplug/spotless/tree/main/lib) + * + * @author Benoit Lacelle + */ +// https://github.com/diffplug/spotless/blob/main/CONTRIBUTING.md#how-to-add-a-new-formatterstep +public final class CleanthatStepFactory { + + private static final String NAME = "cleanthat"; + private static final String MAVEN_COORDINATE = "io.github.solven-eu.cleanthat:java:"; + + private static final Jvm.Support JVM_SUPPORT = Jvm.support(NAME).add(8, "2.0"); + + // prevent direct instantiation + private CleanthatStepFactory() { + } + + /** Creates a step which formats everything - code, import order, and unused imports. */ + public static FormatterStep create(Provisioner provisioner) { + return create(defaultVersion(), provisioner); + } + + /** Creates a step which formats everything - code, import order, and unused imports. */ + public static FormatterStep create(String version, Provisioner provisioner) { + return create(MAVEN_COORDINATE, version, defaultExcluded(), defaultIncluded(), provisioner); + } + + private static List defaultExcluded() { + return List.of(); + } + + private static List defaultIncluded() { + return List.of("*"); + } + + /** Creates a step which formats everything - groupArtifact, code, import order, and unused imports. */ + public static FormatterStep create(String groupArtifact, + String version, + List excluded, + List included, + Provisioner provisioner) { + Objects.requireNonNull(groupArtifact, "groupArtifact"); + if (groupArtifact.chars().filter(ch -> ch == ':').count() != 1) { + throw new IllegalArgumentException("groupArtifact must be in the form 'groupId:artifactId'"); + } + Objects.requireNonNull(version, "version"); + Objects.requireNonNull(provisioner, "provisioner"); + return FormatterStep.createLazy(NAME, + () -> new JavaRulesState(NAME, groupArtifact, version, excluded, included, provisioner), + JavaRulesState::createFormat); + } + + /** Get default formatter version */ + public static String defaultVersion() { + return JVM_SUPPORT.getRecommendedFormatterVersion(); + } + + static final class JavaRulesState implements Serializable { + private static final long serialVersionUID = 1L; + + final JarState jarState; + final String stepName; + final String version; + + final List included; + final List excluded; + + JavaRulesState(String stepName, String version, Provisioner provisioner) throws IOException { + this(stepName, MAVEN_COORDINATE, version, defaultExcluded(), defaultIncluded(), provisioner); + } + + JavaRulesState(String stepName, + String groupArtifact, + String version, + List included, + List excluded, + Provisioner provisioner) throws IOException { + JVM_SUPPORT.assertFormatterSupported(version); + // ModuleHelper.doOpenInternalPackagesIfRequired(); + this.jarState = JarState.from(groupArtifact + ":" + version, provisioner); + this.stepName = stepName; + this.version = version; + + this.included = included; + this.excluded = excluded; + } + + @SuppressWarnings("PMD.UseProperClassLoader") + FormatterFunc createFormat() { + ClassLoader classLoader = jarState.getClassLoader(); + + Object formatter; + Method formatterMethod; + try { + Class formatterClazz = + classLoader.loadClass("com.diffplug.spotless.glue.java.JavaCleanthatRefactoringFunc"); + Constructor formatterConstructor = formatterClazz.getConstructor(List.class, List.class); + + formatter = formatterConstructor.newInstance(included, excluded); + formatterMethod = formatterClazz.getMethod("apply", String.class); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException("Issue executing the formatter", e); + } + return JVM_SUPPORT.suggestLaterVersionOnError(version, input -> { + return (String) formatterMethod.invoke(formatter, input); + }); + } + + } +} From 8fcce07eee63e064ad1c8e3583dd6c89c32899fa Mon Sep 17 00:00:00 2001 From: Benoit Lacelle Date: Tue, 31 Jan 2023 00:10:27 +0400 Subject: [PATCH 09/59] Apply suggestions --- .../java/com/diffplug/spotless/Formatter.java | 2 +- .../spotless/maven/ImpactedFilesTracker.java | 28 +++++++++---------- .../spotless/maven/SpotlessApplyMojo.java | 13 +++++---- 3 files changed, 21 insertions(+), 22 deletions(-) diff --git a/lib/src/main/java/com/diffplug/spotless/Formatter.java b/lib/src/main/java/com/diffplug/spotless/Formatter.java index bdfe008a61..dede79c1b3 100644 --- a/lib/src/main/java/com/diffplug/spotless/Formatter.java +++ b/lib/src/main/java/com/diffplug/spotless/Formatter.java @@ -113,7 +113,7 @@ public static Formatter.Builder builder() { public static class Builder { // optional parameters - private String name = "misc"; + private String name = "unnamed"; // required parameters private LineEnding.Policy lineEndingsPolicy; private Charset encoding; diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/ImpactedFilesTracker.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/ImpactedFilesTracker.java index 7474c109bc..f66802475e 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/ImpactedFilesTracker.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/ImpactedFilesTracker.java @@ -15,41 +15,39 @@ */ package com.diffplug.spotless.maven; -import java.util.concurrent.atomic.AtomicInteger; - /** * Tracks the number of processed files, typically by a single Formatter for a whole repository */ -public class ImpactedFilesTracker { - protected final AtomicInteger nbSkipped = new AtomicInteger(); - protected final AtomicInteger nbChecked = new AtomicInteger(); - protected final AtomicInteger nbCleaned = new AtomicInteger(); +class ImpactedFilesTracker { + protected int nbskippedAsCleanCache = 0; + protected int nbCheckedButAlreadyClean = 0; + protected int nbCleaned = 0; /** * Some cache mechanism may indicate some content is clean, without having to execute the cleaning process */ public void skippedAsCleanCache() { - nbSkipped.incrementAndGet(); + nbskippedAsCleanCache++; } - public int getSkipped() { - return nbSkipped.get(); + public int getSkippedAsCleanCache() { + return nbskippedAsCleanCache; } - public void checked() { - nbChecked.incrementAndGet(); + public void checkedButAlreadyClean() { + nbCheckedButAlreadyClean++; } - public int getChecked() { - return nbChecked.get(); + public int getCheckedButAlreadyClean() { + return nbCheckedButAlreadyClean; } public void cleaned() { - nbCleaned.incrementAndGet(); + nbCleaned++; } public int getCleaned() { - return nbCleaned.get(); + return nbCleaned; } } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java index 0f712ecd12..0c1cbf8785 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java @@ -45,13 +45,14 @@ protected void process(Iterable files, Formatter formatter, UpToDateChecke } try { - impactedFilesTracker.checked(); PaddedCell.DirtyState dirtyState = PaddedCell.calculateDirtyState(formatter, file); if (!dirtyState.isClean() && !dirtyState.didNotConverge()) { getLog().info(String.format("Writing clean file: %s", file)); dirtyState.writeCanonicalTo(file); buildContext.refresh(file); impactedFilesTracker.cleaned(); + } else { + impactedFilesTracker.checkedButAlreadyClean(); } } catch (IOException e) { throw new MojoExecutionException("Unable to format file " + file, e); @@ -61,11 +62,11 @@ protected void process(Iterable files, Formatter formatter, UpToDateChecke } // We print the number of considered files which is useful when ratchetFrom is setup - int nbSkipped = impactedFilesTracker.getSkipped(); - int nbChecked = impactedFilesTracker.getChecked(); - int nbCleaned = impactedFilesTracker.getCleaned(); - int totalProcessed = nbSkipped + nbChecked + nbCleaned; + int skippedAsCleanCache = impactedFilesTracker.getSkippedAsCleanCache(); + int checkedButAlreadyClean = impactedFilesTracker.getCheckedButAlreadyClean(); + int cleaned = impactedFilesTracker.getCleaned(); + int totalProcessed = skippedAsCleanCache + checkedButAlreadyClean + cleaned; getLog().info(String.format("Spotless.%s is keeping %s files clean - %s were changed to be clean, %s were already clean, %s were skipped because caching determined they were already clean", - formatter.getName(), totalProcessed, nbCleaned, nbChecked, nbSkipped)); + formatter.getName(), totalProcessed, cleaned, checkedButAlreadyClean, skippedAsCleanCache)); } } From ed45e5b57bdd4b62874d8d55aa7f5d93a0d7e138 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 30 Jan 2023 23:12:28 +0000 Subject: [PATCH 10/59] Update dependency org.mockito:mockito-core to v5.1.1 --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 6256e51203..c72fa0429d 100644 --- a/gradle.properties +++ b/gradle.properties @@ -28,4 +28,4 @@ VER_DURIAN=1.2.0 VER_JGIT=6.4.0.202211300538-r VER_JUNIT=5.9.2 VER_ASSERTJ=3.24.2 -VER_MOCKITO=5.1.0 +VER_MOCKITO=5.1.1 From c890b89c7fb4430858bac8277bc5cfffad87ebac Mon Sep 17 00:00:00 2001 From: Benoit Lacelle Date: Tue, 31 Jan 2023 08:39:13 +0400 Subject: [PATCH 11/59] Add a CHANGES entry. Log only if totalProcessed>0 --- plugin-maven/CHANGES.md | 1 + .../java/com/diffplug/spotless/maven/SpotlessApplyMojo.java | 6 ++++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/plugin-maven/CHANGES.md b/plugin-maven/CHANGES.md index 1bb49898f1..2ecb7735ff 100644 --- a/plugin-maven/CHANGES.md +++ b/plugin-maven/CHANGES.md @@ -4,6 +4,7 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format ( ## [Unreleased] ### Added +* A synthesis log with the number of considered files is added after each formatter execution [#1507](https://github.com/diffplug/spotless/pull/1507) ### Fixed * The default list of type annotations used by `formatAnnotations` has had 8 more annotations from the Checker Framework added [#1494](https://github.com/diffplug/spotless/pull/1494) ### Changes diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java index 0c1cbf8785..8dd758e84b 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java @@ -66,7 +66,9 @@ protected void process(Iterable files, Formatter formatter, UpToDateChecke int checkedButAlreadyClean = impactedFilesTracker.getCheckedButAlreadyClean(); int cleaned = impactedFilesTracker.getCleaned(); int totalProcessed = skippedAsCleanCache + checkedButAlreadyClean + cleaned; - getLog().info(String.format("Spotless.%s is keeping %s files clean - %s were changed to be clean, %s were already clean, %s were skipped because caching determined they were already clean", - formatter.getName(), totalProcessed, cleaned, checkedButAlreadyClean, skippedAsCleanCache)); + if (totalProcessed > 0) { + getLog().info(String.format("Spotless.%s is keeping %s files clean - %s were changed to be clean, %s were already clean, %s were skipped because caching determined they were already clean", + formatter.getName(), totalProcessed, cleaned, checkedButAlreadyClean, skippedAsCleanCache)); + } } } From 6f6b34fe35753064fdd35e5fcce8b42ec62660fb Mon Sep 17 00:00:00 2001 From: Benoit Lacelle Date: Tue, 31 Jan 2023 08:45:30 +0400 Subject: [PATCH 12/59] Add debug log if no concerned filers --- .../java/com/diffplug/spotless/maven/SpotlessApplyMojo.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java index 8dd758e84b..5f99f6a126 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java @@ -69,6 +69,9 @@ protected void process(Iterable files, Formatter formatter, UpToDateChecke if (totalProcessed > 0) { getLog().info(String.format("Spotless.%s is keeping %s files clean - %s were changed to be clean, %s were already clean, %s were skipped because caching determined they were already clean", formatter.getName(), totalProcessed, cleaned, checkedButAlreadyClean, skippedAsCleanCache)); + } else { + getLog().debug(String.format("Spotless.%s is not considering a single file", + formatter.getName())); } } } From d7ff074095b4bbcbe1acb6a7e4ad1edf6fccb78f Mon Sep 17 00:00:00 2001 From: Ned Twigg Date: Mon, 30 Jan 2023 22:46:21 -0800 Subject: [PATCH 13/59] Treat empty target as a warning (likely a mistake, e.g. #437). --- .../java/com/diffplug/spotless/maven/SpotlessApplyMojo.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java index 5f99f6a126..440b72c21e 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java @@ -70,8 +70,7 @@ protected void process(Iterable files, Formatter formatter, UpToDateChecke getLog().info(String.format("Spotless.%s is keeping %s files clean - %s were changed to be clean, %s were already clean, %s were skipped because caching determined they were already clean", formatter.getName(), totalProcessed, cleaned, checkedButAlreadyClean, skippedAsCleanCache)); } else { - getLog().debug(String.format("Spotless.%s is not considering a single file", - formatter.getName())); + getLog().warn(String.format("Spotless.%s has no target files. Examine your ``: https://github.com/diffplug/spotless/tree/main/plugin-maven#quickstart", formatter.getName())); } } } From eeee68aaa9e605d23b0622af7ff2650237c96fa5 Mon Sep 17 00:00:00 2001 From: Ned Twigg Date: Mon, 30 Jan 2023 22:48:52 -0800 Subject: [PATCH 14/59] Minor renaming to condense SpotlessApplyMojo. --- .../spotless/maven/ImpactedFilesTracker.java | 3 +++ .../spotless/maven/SpotlessApplyMojo.java | 16 ++++++---------- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/ImpactedFilesTracker.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/ImpactedFilesTracker.java index f66802475e..60eb8af762 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/ImpactedFilesTracker.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/ImpactedFilesTracker.java @@ -50,4 +50,7 @@ public int getCleaned() { return nbCleaned; } + public int getTotal() { + return nbskippedAsCleanCache + nbCheckedButAlreadyClean + nbCleaned; + } } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java index 440b72c21e..f7f23d6d75 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java @@ -33,11 +33,11 @@ public class SpotlessApplyMojo extends AbstractSpotlessMojo { @Override protected void process(Iterable files, Formatter formatter, UpToDateChecker upToDateChecker) throws MojoExecutionException { - ImpactedFilesTracker impactedFilesTracker = new ImpactedFilesTracker(); + ImpactedFilesTracker counter = new ImpactedFilesTracker(); for (File file : files) { if (upToDateChecker.isUpToDate(file.toPath())) { - impactedFilesTracker.skippedAsCleanCache(); + counter.skippedAsCleanCache(); if (getLog().isDebugEnabled()) { getLog().debug("Spotless will not format an up-to-date file: " + file); } @@ -50,9 +50,9 @@ protected void process(Iterable files, Formatter formatter, UpToDateChecke getLog().info(String.format("Writing clean file: %s", file)); dirtyState.writeCanonicalTo(file); buildContext.refresh(file); - impactedFilesTracker.cleaned(); + counter.cleaned(); } else { - impactedFilesTracker.checkedButAlreadyClean(); + counter.checkedButAlreadyClean(); } } catch (IOException e) { throw new MojoExecutionException("Unable to format file " + file, e); @@ -62,13 +62,9 @@ protected void process(Iterable files, Formatter formatter, UpToDateChecke } // We print the number of considered files which is useful when ratchetFrom is setup - int skippedAsCleanCache = impactedFilesTracker.getSkippedAsCleanCache(); - int checkedButAlreadyClean = impactedFilesTracker.getCheckedButAlreadyClean(); - int cleaned = impactedFilesTracker.getCleaned(); - int totalProcessed = skippedAsCleanCache + checkedButAlreadyClean + cleaned; - if (totalProcessed > 0) { + if (counter.getTotal() > 0) { getLog().info(String.format("Spotless.%s is keeping %s files clean - %s were changed to be clean, %s were already clean, %s were skipped because caching determined they were already clean", - formatter.getName(), totalProcessed, cleaned, checkedButAlreadyClean, skippedAsCleanCache)); + formatter.getName(), counter.getTotal(), counter.getCleaned(), counter.getCheckedButAlreadyClean(), counter.getSkippedAsCleanCache())); } else { getLog().warn(String.format("Spotless.%s has no target files. Examine your ``: https://github.com/diffplug/spotless/tree/main/plugin-maven#quickstart", formatter.getName())); } From 1981d4b2c8f521264e1d3ece408daf4bebf97e49 Mon Sep 17 00:00:00 2001 From: Aleksey Genus Date: Tue, 31 Jan 2023 16:31:50 +0600 Subject: [PATCH 15/59] Sort by keys inside json arrays --- .../spotless/glue/gson/GsonFormatterFunc.java | 32 +++++++++++++++---- 1 file changed, 25 insertions(+), 7 deletions(-) diff --git a/lib/src/gson/java/com/diffplug/spotless/glue/gson/GsonFormatterFunc.java b/lib/src/gson/java/com/diffplug/spotless/glue/gson/GsonFormatterFunc.java index b19476a1a8..0ff5037cba 100644 --- a/lib/src/gson/java/com/diffplug/spotless/glue/gson/GsonFormatterFunc.java +++ b/lib/src/gson/java/com/diffplug/spotless/glue/gson/GsonFormatterFunc.java @@ -21,6 +21,7 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.stream.JsonWriter; @@ -57,8 +58,8 @@ public String apply(String inputString) { if (jsonElement == null) { throw new AssertionError(FAILED_TO_PARSE_ERROR_MESSAGE); } - if (gsonConfig.isSortByKeys() && jsonElement.isJsonObject()) { - jsonElement = sortByKeys(jsonElement.getAsJsonObject()); + if (gsonConfig.isSortByKeys()) { + jsonElement = sortByKeys(jsonElement); } try (StringWriter stringWriter = new StringWriter()) { JsonWriter jsonWriter = new JsonWriter(stringWriter); @@ -72,19 +73,36 @@ public String apply(String inputString) { return result; } + private JsonElement sortByKeys(JsonElement jsonElement) { + if (jsonElement.isJsonArray()) { + return sortByKeys(jsonElement.getAsJsonArray()); + } else if (jsonElement.isJsonObject()) { + return sortByKeys(jsonElement.getAsJsonObject()); + } else { + return jsonElement; + } + } + private JsonElement sortByKeys(JsonObject jsonObject) { JsonObject result = new JsonObject(); jsonObject.keySet().stream().sorted() .forEach(key -> { - JsonElement element = jsonObject.get(key); - if (element.isJsonObject()) { - element = sortByKeys(element.getAsJsonObject()); - } - result.add(key, element); + JsonElement sorted = sortByKeys(jsonObject.get(key)); + result.add(key, sorted); }); return result; } + private JsonElement sortByKeys(JsonArray jsonArray) { + var result = new JsonArray(); + for (JsonElement element : jsonArray) { + JsonElement sorted = sortByKeys(element); + result.add(sorted); + } + + return result; + } + private String generateIndent(int indentSpaces) { return String.join("", Collections.nCopies(indentSpaces, " ")); } From d77a3390fd4a378467f2c5b5a790aed2febaa48f Mon Sep 17 00:00:00 2001 From: Aleksey Genus Date: Tue, 31 Jan 2023 17:24:14 +0600 Subject: [PATCH 16/59] Add changes --- CHANGES.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGES.md b/CHANGES.md index 401998b233..72a4b99e93 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -12,6 +12,7 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format ( ## [Unreleased] ### Changes * **POTENTIALLY BREAKING** Bump bytecode from Java 8 to 11 ([#1530](https://github.com/diffplug/spotless/pull/1530) part 2 of [#1337](https://github.com/diffplug/spotless/issues/1337)) +* **POTENTIALLY BREAKING** `sortByKeys` for JSON formatting now takes into account objects inside arrays ([#1546](https://github.com/diffplug/spotless/pull/1546)) ## [2.34.0] - 2023-01-26 ### Added From 6a9dcfd99ccdf5bec5f7330bd4bae9b404d78fc5 Mon Sep 17 00:00:00 2001 From: Ned Twigg Date: Tue, 31 Jan 2023 09:31:49 -0800 Subject: [PATCH 17/59] Stop disabling plugin-maven on JITPACK. --- settings.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/settings.gradle b/settings.gradle index ac0e81a61b..9573775884 100644 --- a/settings.gradle +++ b/settings.gradle @@ -91,7 +91,7 @@ def getStartProperty(java.lang.String name) { } -if (System.getenv('SPOTLESS_EXCLUDE_MAVEN') != 'true' && getStartProperty('SPOTLESS_EXCLUDE_MAVEN') != 'true' && System.getenv('JITPACK') != 'true') { +if (System.getenv('SPOTLESS_EXCLUDE_MAVEN') != 'true' && getStartProperty('SPOTLESS_EXCLUDE_MAVEN') != 'true') { include 'plugin-maven' // maven-specific glue code } From 4c7b616e510bd83167ff329361ad819fac28ae6e Mon Sep 17 00:00:00 2001 From: Ned Twigg Date: Tue, 31 Jan 2023 09:36:09 -0800 Subject: [PATCH 18/59] Set JitPack build JDK to 11. --- jitpack.yml | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 jitpack.yml diff --git a/jitpack.yml b/jitpack.yml new file mode 100644 index 0000000000..adb3fe10c8 --- /dev/null +++ b/jitpack.yml @@ -0,0 +1,2 @@ +jdk: + - openjdk11 From c77a4a609afa04b4f5969b7eabecd468cf88664e Mon Sep 17 00:00:00 2001 From: Ned Twigg Date: Tue, 31 Jan 2023 09:49:13 -0800 Subject: [PATCH 19/59] Disable signing on JitPack. --- gradle/java-publish.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/java-publish.gradle b/gradle/java-publish.gradle index 7d2055d78d..4f77a43ac2 100644 --- a/gradle/java-publish.gradle +++ b/gradle/java-publish.gradle @@ -170,7 +170,7 @@ model { } } -if (!version.endsWith('-SNAPSHOT')) { +if (!version.endsWith('-SNAPSHOT') && System.getenv('JITPACK') != 'true') { signing { String gpg_key = decode64('ORG_GRADLE_PROJECT_gpg_key64') useInMemoryPgpKeys(gpg_key, System.env['ORG_GRADLE_PROJECT_gpg_passphrase']) From 1c060830640b39f04b2e16b6ac49da52d7d0d276 Mon Sep 17 00:00:00 2001 From: Ned Twigg Date: Tue, 31 Jan 2023 09:58:13 -0800 Subject: [PATCH 20/59] Another attempt to disable signing on JitPack. --- gradle/java-publish.gradle | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/gradle/java-publish.gradle b/gradle/java-publish.gradle index 4f77a43ac2..3839391d3a 100644 --- a/gradle/java-publish.gradle +++ b/gradle/java-publish.gradle @@ -170,7 +170,11 @@ model { } } -if (!version.endsWith('-SNAPSHOT') && System.getenv('JITPACK') != 'true') { +if (System.getenv('JITPACK') == 'true') { + signing { + setRequired(false) + } +} else if (!version.endsWith('-SNAPSHOT')) { signing { String gpg_key = decode64('ORG_GRADLE_PROJECT_gpg_key64') useInMemoryPgpKeys(gpg_key, System.env['ORG_GRADLE_PROJECT_gpg_passphrase']) From cc43cf1becc90cf964234fa00bd542c0b873d279 Mon Sep 17 00:00:00 2001 From: Ned Twigg Date: Tue, 31 Jan 2023 13:47:59 -0800 Subject: [PATCH 21/59] Another attempt at fixing JitPack. --- gradle/java-publish.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/java-publish.gradle b/gradle/java-publish.gradle index 3839391d3a..7583bbe344 100644 --- a/gradle/java-publish.gradle +++ b/gradle/java-publish.gradle @@ -170,7 +170,7 @@ model { } } -if (System.getenv('JITPACK') == 'true') { +if (System.env['JITPACK'] == 'true') { signing { setRequired(false) } From e3f1ca4c9cd37356c8940c28814e441e78fe02c5 Mon Sep 17 00:00:00 2001 From: Ned Twigg Date: Tue, 31 Jan 2023 13:59:54 -0800 Subject: [PATCH 22/59] Update contributing guide and changelog. --- CONTRIBUTING.md | 2 +- plugin-maven/CHANGES.md | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 782e377d58..783f58b9af 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -207,7 +207,7 @@ If it doesn't work, you can check the JitPack log at `https://jitpack.io/com/git ### Maven -Run `./gradlew publishToMavenLocal` to publish this to your local repository. The maven plugin is not published to JitPack due to [jitpack/jitpack.io#4112](https://github.com/jitpack/jitpack.io/issues/4112). +Run `./gradlew publishToMavenLocal` to publish this to your local repository. You can also use the JitPack artifacts, using the same principles as Gradle above. ## License diff --git a/plugin-maven/CHANGES.md b/plugin-maven/CHANGES.md index c9e0f420a5..0029814ae9 100644 --- a/plugin-maven/CHANGES.md +++ b/plugin-maven/CHANGES.md @@ -5,6 +5,7 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format ( ## [Unreleased] ### Added * A synthesis log with the number of considered files is added after each formatter execution ([#1507](https://github.com/diffplug/spotless/pull/1507)) +* Any commit of the Spotless maven plugin now available via JitPack ([#1547](https://github.com/diffplug/spotless/pull/1547)) ## [2.31.0] - 2023-01-26 ### Added From a413524f4fc09814c51522897453e6dae453e0d7 Mon Sep 17 00:00:00 2001 From: Aleksey Genus Date: Wed, 1 Feb 2023 11:47:14 +0600 Subject: [PATCH 23/59] Add changes to maven and gradle changelogs Add tests --- plugin-gradle/CHANGES.md | 2 ++ plugin-maven/CHANGES.md | 2 ++ testlib/src/main/resources/json/sortByKeysAfter.json | 6 ++++++ .../src/main/resources/json/sortByKeysAfterDisabled.json | 6 ++++++ testlib/src/main/resources/json/sortByKeysBefore.json | 6 ++++++ 5 files changed, 22 insertions(+) diff --git a/plugin-gradle/CHANGES.md b/plugin-gradle/CHANGES.md index 49ef0adbbe..a81ee7bd93 100644 --- a/plugin-gradle/CHANGES.md +++ b/plugin-gradle/CHANGES.md @@ -3,6 +3,8 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format (starting after version `3.27.0`). ## [Unreleased] +### Changes +* **POTENTIALLY BREAKING** `sortByKeys` for JSON formatting now takes into account objects inside arrays ([#1546](https://github.com/diffplug/spotless/pull/1546)) ## [6.14.0] - 2023-01-26 ### Added diff --git a/plugin-maven/CHANGES.md b/plugin-maven/CHANGES.md index c9e0f420a5..1ffea0faa7 100644 --- a/plugin-maven/CHANGES.md +++ b/plugin-maven/CHANGES.md @@ -5,6 +5,8 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format ( ## [Unreleased] ### Added * A synthesis log with the number of considered files is added after each formatter execution ([#1507](https://github.com/diffplug/spotless/pull/1507)) +### Changes +* **POTENTIALLY BREAKING** `sortByKeys` for JSON formatting now takes into account objects inside arrays ([#1546](https://github.com/diffplug/spotless/pull/1546)) ## [2.31.0] - 2023-01-26 ### Added diff --git a/testlib/src/main/resources/json/sortByKeysAfter.json b/testlib/src/main/resources/json/sortByKeysAfter.json index c4a48de2f2..7a83087f1d 100644 --- a/testlib/src/main/resources/json/sortByKeysAfter.json +++ b/testlib/src/main/resources/json/sortByKeysAfter.json @@ -6,6 +6,12 @@ 2, 1 ], + "_objectsInArraysAreSorted": [ + { + "a": "1", + "b": 2 + } + ], "a": 3, "c": 4, "x": 5, diff --git a/testlib/src/main/resources/json/sortByKeysAfterDisabled.json b/testlib/src/main/resources/json/sortByKeysAfterDisabled.json index de7462bb98..81d81e6891 100644 --- a/testlib/src/main/resources/json/sortByKeysAfterDisabled.json +++ b/testlib/src/main/resources/json/sortByKeysAfterDisabled.json @@ -15,5 +15,11 @@ 3, 2, 1 + ], + "_objectsInArraysAreSorted": [ + { + "b": 2, + "a": "1" + } ] } diff --git a/testlib/src/main/resources/json/sortByKeysBefore.json b/testlib/src/main/resources/json/sortByKeysBefore.json index de7462bb98..81d81e6891 100644 --- a/testlib/src/main/resources/json/sortByKeysBefore.json +++ b/testlib/src/main/resources/json/sortByKeysBefore.json @@ -15,5 +15,11 @@ 3, 2, 1 + ], + "_objectsInArraysAreSorted": [ + { + "b": 2, + "a": "1" + } ] } From c060599aa9c8cb2ee9ad8660cf891ec3e4765f31 Mon Sep 17 00:00:00 2001 From: Aleksey Genus Date: Wed, 1 Feb 2023 11:48:14 +0600 Subject: [PATCH 24/59] Make values consistent --- testlib/src/main/resources/json/sortByKeysAfter.json | 2 +- testlib/src/main/resources/json/sortByKeysAfterDisabled.json | 2 +- testlib/src/main/resources/json/sortByKeysBefore.json | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/testlib/src/main/resources/json/sortByKeysAfter.json b/testlib/src/main/resources/json/sortByKeysAfter.json index 7a83087f1d..070904e872 100644 --- a/testlib/src/main/resources/json/sortByKeysAfter.json +++ b/testlib/src/main/resources/json/sortByKeysAfter.json @@ -8,7 +8,7 @@ ], "_objectsInArraysAreSorted": [ { - "a": "1", + "a": 1, "b": 2 } ], diff --git a/testlib/src/main/resources/json/sortByKeysAfterDisabled.json b/testlib/src/main/resources/json/sortByKeysAfterDisabled.json index 81d81e6891..eb9e38241f 100644 --- a/testlib/src/main/resources/json/sortByKeysAfterDisabled.json +++ b/testlib/src/main/resources/json/sortByKeysAfterDisabled.json @@ -19,7 +19,7 @@ "_objectsInArraysAreSorted": [ { "b": 2, - "a": "1" + "a": 1 } ] } diff --git a/testlib/src/main/resources/json/sortByKeysBefore.json b/testlib/src/main/resources/json/sortByKeysBefore.json index 81d81e6891..eb9e38241f 100644 --- a/testlib/src/main/resources/json/sortByKeysBefore.json +++ b/testlib/src/main/resources/json/sortByKeysBefore.json @@ -19,7 +19,7 @@ "_objectsInArraysAreSorted": [ { "b": 2, - "a": "1" + "a": 1 } ] } From 62ddd9eb084721f963fadd03ef235f0e1f00fa84 Mon Sep 17 00:00:00 2001 From: Benoit Lacelle Date: Wed, 1 Feb 2023 12:30:32 +0400 Subject: [PATCH 25/59] Switch from WARN to DEBUG --- .../java/com/diffplug/spotless/maven/SpotlessApplyMojo.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java index f7f23d6d75..028cc3fb9c 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java @@ -66,7 +66,7 @@ protected void process(Iterable files, Formatter formatter, UpToDateChecke getLog().info(String.format("Spotless.%s is keeping %s files clean - %s were changed to be clean, %s were already clean, %s were skipped because caching determined they were already clean", formatter.getName(), counter.getTotal(), counter.getCleaned(), counter.getCheckedButAlreadyClean(), counter.getSkippedAsCleanCache())); } else { - getLog().warn(String.format("Spotless.%s has no target files. Examine your ``: https://github.com/diffplug/spotless/tree/main/plugin-maven#quickstart", formatter.getName())); + getLog().debug(String.format("Spotless.%s has no target files. Examine your ``: https://github.com/diffplug/spotless/tree/main/plugin-maven#quickstart", formatter.getName())); } } } From df8fbf22848a61dd0fff91c19eaff19ca080630a Mon Sep 17 00:00:00 2001 From: Aleksey Genus Date: Wed, 1 Feb 2023 14:36:20 +0600 Subject: [PATCH 26/59] Fix jackson tests --- .../main/resources/json/sortByKeysAfterDisabled_Simple.json | 4 ++++ testlib/src/main/resources/json/sortByKeysAfter_Jackson.json | 4 ++++ .../json/sortByKeysAfter_Jackson_spaceAfterKeySeparator.json | 4 ++++ 3 files changed, 12 insertions(+) diff --git a/testlib/src/main/resources/json/sortByKeysAfterDisabled_Simple.json b/testlib/src/main/resources/json/sortByKeysAfterDisabled_Simple.json index d2d3612fbd..cd7ebc2be1 100644 --- a/testlib/src/main/resources/json/sortByKeysAfterDisabled_Simple.json +++ b/testlib/src/main/resources/json/sortByKeysAfterDisabled_Simple.json @@ -11,6 +11,10 @@ "x": 5, "X": 2 }, + "_objectsInArraysAreSorted": [{ + "a": 1, + "b": 2 + }], "_arraysNotSorted": [ 3, 2, diff --git a/testlib/src/main/resources/json/sortByKeysAfter_Jackson.json b/testlib/src/main/resources/json/sortByKeysAfter_Jackson.json index 3af39fd0fb..003b2ba66f 100644 --- a/testlib/src/main/resources/json/sortByKeysAfter_Jackson.json +++ b/testlib/src/main/resources/json/sortByKeysAfter_Jackson.json @@ -2,6 +2,10 @@ "A": 1, "X": 2, "_arraysNotSorted": [ 3, 2, 1 ], + "_objectsInArraysAreSorted": [ { + "a": 1, + "b": 2 + } ], "a": 3, "c": 4, "x": 5, diff --git a/testlib/src/main/resources/json/sortByKeysAfter_Jackson_spaceAfterKeySeparator.json b/testlib/src/main/resources/json/sortByKeysAfter_Jackson_spaceAfterKeySeparator.json index 3af39fd0fb..003b2ba66f 100644 --- a/testlib/src/main/resources/json/sortByKeysAfter_Jackson_spaceAfterKeySeparator.json +++ b/testlib/src/main/resources/json/sortByKeysAfter_Jackson_spaceAfterKeySeparator.json @@ -2,6 +2,10 @@ "A": 1, "X": 2, "_arraysNotSorted": [ 3, 2, 1 ], + "_objectsInArraysAreSorted": [ { + "a": 1, + "b": 2 + } ], "a": 3, "c": 4, "x": 5, From dc9878b949b7e00058ef69d341e3824135f76640 Mon Sep 17 00:00:00 2001 From: Kostiantyn Liutovych Date: Sat, 4 Feb 2023 14:24:18 +0100 Subject: [PATCH 27/59] Respect sourceDirectory/testSourceDirectory configs for Java formatters --- plugin-maven/CHANGES.md | 2 + .../spotless/maven/AbstractSpotlessMojo.java | 2 +- .../spotless/maven/FormatterFactory.java | 3 +- .../spotless/maven/antlr4/Antlr4.java | 6 +- .../com/diffplug/spotless/maven/cpp/Cpp.java | 6 +- .../spotless/maven/generic/Format.java | 6 +- .../spotless/maven/groovy/Groovy.java | 6 +- .../diffplug/spotless/maven/java/Java.java | 31 +++- .../spotless/maven/javascript/Javascript.java | 4 +- .../diffplug/spotless/maven/json/Json.java | 4 +- .../spotless/maven/kotlin/Kotlin.java | 6 +- .../spotless/maven/markdown/Markdown.java | 6 +- .../com/diffplug/spotless/maven/pom/Pom.java | 6 +- .../spotless/maven/python/Python.java | 6 +- .../diffplug/spotless/maven/scala/Scala.java | 6 +- .../com/diffplug/spotless/maven/sql/Sql.java | 6 +- .../spotless/maven/typescript/Typescript.java | 4 +- .../diffplug/spotless/maven/yaml/Yaml.java | 4 +- .../maven/MavenIntegrationHarness.java | 17 +- .../maven/MultiModuleProjectTest.java | 2 +- .../maven/java/JavaDefaultIncludesTest.java | 151 ++++++++++++++++++ .../src/test/resources/pom-test.xml.mustache | 1 + 22 files changed, 250 insertions(+), 35 deletions(-) create mode 100644 plugin-maven/src/test/java/com/diffplug/spotless/maven/java/JavaDefaultIncludesTest.java diff --git a/plugin-maven/CHANGES.md b/plugin-maven/CHANGES.md index 9c0b237ea3..b924c07fd6 100644 --- a/plugin-maven/CHANGES.md +++ b/plugin-maven/CHANGES.md @@ -5,6 +5,8 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format ( ## [Unreleased] ### Added * A synthesis log with the number of considered files is added after each formatter execution ([#1507](https://github.com/diffplug/spotless/pull/1507)) +### Fixed +* Respect `sourceDirectory` and `testSourceDirectory` POM configurations for Java formatters ([#1553](https://github.com/diffplug/spotless/pull/1553)) ### Changes * **POTENTIALLY BREAKING** `sortByKeys` for JSON formatting now takes into account objects inside arrays ([#1546](https://github.com/diffplug/spotless/pull/1546)) * Any commit of the Spotless maven plugin now available via JitPack ([#1547](https://github.com/diffplug/spotless/pull/1547)) diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/AbstractSpotlessMojo.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/AbstractSpotlessMojo.java index c4082f52e0..f6aab0eabb 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/AbstractSpotlessMojo.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/AbstractSpotlessMojo.java @@ -320,7 +320,7 @@ private static String withTrailingSeparator(String path) { private Set getIncludes(FormatterFactory formatterFactory) { Set configuredIncludes = formatterFactory.includes(); - Set includes = configuredIncludes.isEmpty() ? formatterFactory.defaultIncludes() : configuredIncludes; + Set includes = configuredIncludes.isEmpty() ? formatterFactory.defaultIncludes(project) : configuredIncludes; if (includes.isEmpty()) { throw new PluginException("You must specify some files to include, such as 'src/**/*.blah'"); } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/FormatterFactory.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/FormatterFactory.java index b78e987d34..c4a6663087 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/FormatterFactory.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/FormatterFactory.java @@ -29,6 +29,7 @@ import java.util.stream.Collectors; import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.project.MavenProject; import com.diffplug.common.collect.Sets; import com.diffplug.spotless.FormatExceptionPolicyStrict; @@ -71,7 +72,7 @@ public abstract class FormatterFactory { private ToggleOffOn toggle; - public abstract Set defaultIncludes(); + public abstract Set defaultIncludes(MavenProject project); public abstract String licenseHeaderDelimiter(); diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/antlr4/Antlr4.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/antlr4/Antlr4.java index bc24ebcf16..a43416fb4e 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/antlr4/Antlr4.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/antlr4/Antlr4.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2020 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. @@ -17,6 +17,8 @@ import java.util.Set; +import org.apache.maven.project.MavenProject; + import com.diffplug.common.collect.ImmutableSet; import com.diffplug.spotless.antlr4.Antlr4Defaults; import com.diffplug.spotless.maven.FormatterFactory; @@ -30,7 +32,7 @@ */ public class Antlr4 extends FormatterFactory { @Override - public Set defaultIncludes() { + public Set defaultIncludes(MavenProject project) { return ImmutableSet.of(Antlr4Defaults.includes()); } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/cpp/Cpp.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/cpp/Cpp.java index f1d07d8552..44940ae4d8 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/cpp/Cpp.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/cpp/Cpp.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2020 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. @@ -18,6 +18,8 @@ import java.util.Collections; import java.util.Set; +import org.apache.maven.project.MavenProject; + import com.diffplug.spotless.cpp.CppDefaults; import com.diffplug.spotless.maven.FormatterFactory; import com.diffplug.spotless.maven.generic.LicenseHeader; @@ -30,7 +32,7 @@ */ public class Cpp extends FormatterFactory { @Override - public Set defaultIncludes() { + public Set defaultIncludes(MavenProject project) { return Collections.emptySet(); } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/generic/Format.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/generic/Format.java index 465381fb52..a696e13ffb 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/generic/Format.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/generic/Format.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 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. @@ -18,6 +18,8 @@ import java.util.Collections; import java.util.Set; +import org.apache.maven.project.MavenProject; + import com.diffplug.spotless.maven.FormatterFactory; /** @@ -29,7 +31,7 @@ public class Format extends FormatterFactory { @Override - public Set defaultIncludes() { + public Set defaultIncludes(MavenProject project) { return Collections.emptySet(); } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/groovy/Groovy.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/groovy/Groovy.java index e9b3c6c412..8041b812f9 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/groovy/Groovy.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/groovy/Groovy.java @@ -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. @@ -17,6 +17,8 @@ import java.util.Set; +import org.apache.maven.project.MavenProject; + import com.diffplug.common.collect.ImmutableSet; import com.diffplug.spotless.maven.FormatterFactory; import com.diffplug.spotless.maven.generic.LicenseHeader; @@ -33,7 +35,7 @@ public class Groovy extends FormatterFactory { private static final String LICENSE_HEADER_DELIMITER = "package "; @Override - public Set defaultIncludes() { + public Set defaultIncludes(MavenProject project) { return DEFAULT_INCLUDES; } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/Java.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/Java.java index 4bd018d53c..0921a838b3 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/Java.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/Java.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 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. @@ -15,9 +15,17 @@ */ package com.diffplug.spotless.maven.java; +import static java.util.stream.Collectors.toSet; + +import java.io.File; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.Set; +import java.util.stream.Stream; + +import org.apache.maven.model.Build; +import org.apache.maven.project.MavenProject; -import com.diffplug.common.collect.ImmutableSet; import com.diffplug.spotless.maven.FormatterFactory; import com.diffplug.spotless.maven.generic.LicenseHeader; @@ -29,12 +37,17 @@ */ public class Java extends FormatterFactory { - private static final Set DEFAULT_INCLUDES = ImmutableSet.of("src/main/java/**/*.java", "src/test/java/**/*.java"); private static final String LICENSE_HEADER_DELIMITER = "package "; @Override - public Set defaultIncludes() { - return DEFAULT_INCLUDES; + public Set defaultIncludes(MavenProject project) { + Path projectDir = project.getBasedir().toPath(); + Build build = project.getBuild(); + return Stream.of(build.getSourceDirectory(), build.getTestSourceDirectory()) + .map(Paths::get) + .map(projectDir::relativize) + .map(Java::fileMask) + .collect(toSet()); } @Override @@ -65,4 +78,12 @@ public void addRemoveUnusedImports(RemoveUnusedImports removeUnusedImports) { public void addFormatAnnotations(FormatAnnotations formatAnnotations) { addStepFactory(formatAnnotations); } + + private static String fileMask(Path path) { + String dir = path.toString(); + if (!dir.endsWith(File.separator)) { + dir += File.separator; + } + return dir + "**" + File.separator + "*.java"; + } } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/javascript/Javascript.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/javascript/Javascript.java index 7ca35dd258..31a5917e06 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/javascript/Javascript.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/javascript/Javascript.java @@ -18,6 +18,8 @@ import java.util.Collections; import java.util.Set; +import org.apache.maven.project.MavenProject; + import com.diffplug.spotless.maven.FormatterFactory; /** @@ -27,7 +29,7 @@ */ public class Javascript extends FormatterFactory { @Override - public Set defaultIncludes() { + public Set defaultIncludes(MavenProject project) { return Collections.emptySet(); } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/json/Json.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/json/Json.java index 852088278a..5bb7c17b3a 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/json/Json.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/json/Json.java @@ -18,6 +18,8 @@ import java.util.Collections; import java.util.Set; +import org.apache.maven.project.MavenProject; + import com.diffplug.spotless.maven.FormatterFactory; /** @@ -27,7 +29,7 @@ public class Json extends FormatterFactory { public static final int DEFAULT_INDENTATION = 4; @Override - public Set defaultIncludes() { + public Set defaultIncludes(MavenProject project) { return Collections.emptySet(); } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/kotlin/Kotlin.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/kotlin/Kotlin.java index cfb0aad39e..18eb13773d 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/kotlin/Kotlin.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/kotlin/Kotlin.java @@ -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. @@ -19,6 +19,8 @@ import java.util.Set; +import org.apache.maven.project.MavenProject; + import com.diffplug.common.collect.ImmutableSet; import com.diffplug.spotless.maven.FormatterFactory; @@ -27,7 +29,7 @@ public class Kotlin extends FormatterFactory { private static final Set DEFAULT_INCLUDES = ImmutableSet.of("src/main/kotlin/**/*.kt", "src/test/kotlin/**/*.kt"); @Override - public Set defaultIncludes() { + public Set defaultIncludes(MavenProject project) { return DEFAULT_INCLUDES; } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/markdown/Markdown.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/markdown/Markdown.java index 2ba9b1f58f..0941beb76a 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/markdown/Markdown.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/markdown/Markdown.java @@ -1,5 +1,5 @@ /* - * Copyright 2021 DiffPlug + * 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. @@ -18,6 +18,8 @@ import java.util.Collections; import java.util.Set; +import org.apache.maven.project.MavenProject; + import com.diffplug.spotless.maven.FormatterFactory; import com.diffplug.spotless.maven.generic.LicenseHeader; @@ -29,7 +31,7 @@ */ public class Markdown extends FormatterFactory { @Override - public Set defaultIncludes() { + public Set defaultIncludes(MavenProject project) { return Collections.emptySet(); } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/pom/Pom.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/pom/Pom.java index f083a17c89..9a4d3eea06 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/pom/Pom.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/pom/Pom.java @@ -1,5 +1,5 @@ /* - * Copyright 2021 DiffPlug + * 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. @@ -17,6 +17,8 @@ import java.util.Set; +import org.apache.maven.project.MavenProject; + import com.diffplug.common.collect.ImmutableSet; import com.diffplug.spotless.maven.FormatterFactory; import com.diffplug.spotless.maven.generic.LicenseHeader; @@ -29,7 +31,7 @@ */ public class Pom extends FormatterFactory { @Override - public Set defaultIncludes() { + public Set defaultIncludes(MavenProject project) { return ImmutableSet.of("pom.xml"); } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/python/Python.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/python/Python.java index 09443f070b..df7348c16c 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/python/Python.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/python/Python.java @@ -1,5 +1,5 @@ /* - * Copyright 2021 DiffPlug + * 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. @@ -18,6 +18,8 @@ import java.util.Collections; import java.util.Set; +import org.apache.maven.project.MavenProject; + import com.diffplug.spotless.maven.FormatterFactory; import com.diffplug.spotless.maven.generic.LicenseHeader; @@ -30,7 +32,7 @@ public class Python extends FormatterFactory { @Override - public Set defaultIncludes() { + public Set defaultIncludes(MavenProject project) { return Collections.emptySet(); } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/scala/Scala.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/scala/Scala.java index 423ca71930..7a9e455f5f 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/scala/Scala.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/scala/Scala.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 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. @@ -17,6 +17,8 @@ import java.util.Set; +import org.apache.maven.project.MavenProject; + import com.diffplug.common.collect.ImmutableSet; import com.diffplug.spotless.maven.FormatterFactory; import com.diffplug.spotless.maven.generic.LicenseHeader; @@ -34,7 +36,7 @@ public class Scala extends FormatterFactory { private static final String LICENSE_HEADER_DELIMITER = "package "; @Override - public Set defaultIncludes() { + public Set defaultIncludes(MavenProject project) { return DEFAULT_INCLUDES; } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/sql/Sql.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/sql/Sql.java index c49ac074d9..64ebcb55d7 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/sql/Sql.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/sql/Sql.java @@ -1,5 +1,5 @@ /* - * Copyright 2020 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. @@ -18,6 +18,8 @@ import java.util.Collections; import java.util.Set; +import org.apache.maven.project.MavenProject; + import com.diffplug.spotless.maven.FormatterFactory; /** @@ -27,7 +29,7 @@ */ public class Sql extends FormatterFactory { @Override - public Set defaultIncludes() { + public Set defaultIncludes(MavenProject project) { return Collections.emptySet(); } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/typescript/Typescript.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/typescript/Typescript.java index 6f0d7f91b2..6ba45ab719 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/typescript/Typescript.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/typescript/Typescript.java @@ -18,6 +18,8 @@ import java.util.Collections; import java.util.Set; +import org.apache.maven.project.MavenProject; + import com.diffplug.spotless.maven.FormatterFactory; /** @@ -27,7 +29,7 @@ */ public class Typescript extends FormatterFactory { @Override - public Set defaultIncludes() { + public Set defaultIncludes(MavenProject project) { return Collections.emptySet(); } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/yaml/Yaml.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/yaml/Yaml.java index a6ceaaa592..e22f6d40ce 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/yaml/Yaml.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/yaml/Yaml.java @@ -18,6 +18,8 @@ import java.util.Collections; import java.util.Set; +import org.apache.maven.project.MavenProject; + import com.diffplug.spotless.maven.FormatterFactory; /** @@ -25,7 +27,7 @@ */ public class Yaml extends FormatterFactory { @Override - public Set defaultIncludes() { + public Set defaultIncludes(MavenProject project) { return Collections.emptySet(); } diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenIntegrationHarness.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenIntegrationHarness.java index f4e94e573c..fdc4a745a1 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenIntegrationHarness.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenIntegrationHarness.java @@ -54,7 +54,9 @@ public class MavenIntegrationHarness extends ResourceHarness { */ private static final String SPOTLESS_MAVEN_VERSION_IDE = null; + private static final String POM_TEMPLATE = "/pom-test.xml.mustache"; private static final String SPOTLESS_MAVEN_PLUGIN_VERSION = "spotlessMavenPluginVersion"; + private static final String BUILD = "build"; private static final String CONFIGURATION = "configuration"; private static final String EXECUTIONS = "executions"; private static final String MODULES = "modules"; @@ -209,11 +211,11 @@ protected MavenRunner mavenRunnerWithRemoteDebug() throws IOException { } protected String createPomXmlContent(String pluginVersion, String[] executions, String[] configuration, String[] dependencies, String[] plugins) throws IOException { - return createPomXmlContent("/pom-test.xml.mustache", pluginVersion, executions, configuration, dependencies, plugins); + return createPomXmlContent(POM_TEMPLATE, pluginVersion, executions, configuration, dependencies, plugins); } protected String createPomXmlContent(String pomTemplate, String pluginVersion, String[] executions, String[] configuration, String[] dependencies, String[] plugins) throws IOException { - Map params = buildPomXmlParams(pluginVersion, executions, configuration, null, dependencies, plugins); + Map params = buildPomXmlParams(pluginVersion, null, executions, configuration, null, dependencies, plugins); return createPomXmlContent(pomTemplate, params); } @@ -221,6 +223,11 @@ protected String createPomXmlContent(String pluginVersion, String[] executions, return createPomXmlContent(pluginVersion, executions, configuration, null, null); } + protected String createPomXmlContent(String[] build, String[] configuration) throws IOException { + Map params = buildPomXmlParams(null, build, null, configuration, null, null, null); + return createPomXmlContent(POM_TEMPLATE, params); + } + protected String createPomXmlContent(String pomTemplate, Map params) throws IOException { URL url = MavenIntegrationHarness.class.getResource(pomTemplate); try (BufferedReader reader = Resources.asCharSource(url, StandardCharsets.UTF_8).openBufferedStream()) { @@ -231,10 +238,14 @@ protected String createPomXmlContent(String pomTemplate, Map par } } - protected static Map buildPomXmlParams(String pluginVersion, String[] executions, String[] configuration, String[] modules, String[] dependencies, String[] plugins) { + protected static Map buildPomXmlParams(String pluginVersion, String[] build, String[] executions, String[] configuration, String[] modules, String[] dependencies, String[] plugins) { Map params = new HashMap<>(); params.put(SPOTLESS_MAVEN_PLUGIN_VERSION, pluginVersion == null ? getSystemProperty(SPOTLESS_MAVEN_PLUGIN_VERSION) : pluginVersion); + if (build != null) { + params.put(BUILD, String.join("\n", build)); + } + if (configuration != null) { params.put(CONFIGURATION, String.join("\n", configuration)); } diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/MultiModuleProjectTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/MultiModuleProjectTest.java index 6206affc04..1c9521c402 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/MultiModuleProjectTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/MultiModuleProjectTest.java @@ -145,7 +145,7 @@ private void createRootPom() throws IOException { modulesList.addAll(subProjects.keySet()); String[] modules = modulesList.toArray(new String[0]); - Map rootPomParams = buildPomXmlParams(null, null, configuration, modules, null, null); + Map rootPomParams = buildPomXmlParams(null, null, null, configuration, modules, null, null); setFile("pom.xml").toContent(createPomXmlContent("/multi-module/pom-parent.xml.mustache", rootPomParams)); } diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/JavaDefaultIncludesTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/JavaDefaultIncludesTest.java new file mode 100644 index 0000000000..57f717ad07 --- /dev/null +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/JavaDefaultIncludesTest.java @@ -0,0 +1,151 @@ +/* + * Copyright 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.java; + +import java.io.IOException; +import java.util.Arrays; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.diffplug.spotless.maven.MavenIntegrationHarness; + +public class JavaDefaultIncludesTest extends MavenIntegrationHarness { + + private static final String UNFORMATTED = "java/removeunusedimports/JavaCodeWithPackageUnformatted.test"; + private static final String FORMATTED = "java/removeunusedimports/JavaCodeWithPackageFormatted.test"; + + private static final String FILE_1 = "src/main/java/com/diffplug/spotless/One.java"; + private static final String FILE_2 = "src/test/java/com/diffplug/spotless/Two.java"; + private static final String FILE_3 = "src/com/diffplug/spotless/Three.java"; + private static final String FILE_4 = "test/com/diffplug/spotless/Four.java"; + private static final String FILE_5 = "foo/bar/Five.java"; + + @BeforeEach + void beforeEach() { + for (String file : Arrays.asList(FILE_1, FILE_2, FILE_3, FILE_4, FILE_5)) { + setFile(file).toResource(UNFORMATTED); + } + } + + @Test + void noCustomConfiguration() throws Exception { + writePomWithBuildConfiguration(); + + mavenRunner().withArguments("spotless:apply").runNoError(); + + // Files 1, 2 are formatted because they live under default Maven source & test source dirs + assertFile(FILE_1).sameAsResource(FORMATTED); + assertFile(FILE_2).sameAsResource(FORMATTED); + + // Files 3, 4, 5 are not formatted because they live outside default Maven source & test source dirs + assertFile(FILE_3).sameAsResource(UNFORMATTED); + assertFile(FILE_4).sameAsResource(UNFORMATTED); + assertFile(FILE_5).sameAsResource(UNFORMATTED); + } + + @Test + void customSourceDirConfiguration() throws Exception { + writePomWithBuildConfiguration("src"); + + mavenRunner().withArguments("spotless:apply").runNoError(); + + // Files 1, 2, 3 are formatted because they live under the custom-configured source dir + assertFile(FILE_1).sameAsResource(FORMATTED); + assertFile(FILE_2).sameAsResource(FORMATTED); + assertFile(FILE_3).sameAsResource(FORMATTED); + + // File 4, 5 are not formatted because they live outside the custom-configured source dir and default test source dir + assertFile(FILE_4).sameAsResource(UNFORMATTED); + assertFile(FILE_5).sameAsResource(UNFORMATTED); + } + + @Test + void customTestSourceDirConfiguration() throws Exception { + writePomWithBuildConfiguration("test"); + + mavenRunner().withArguments("spotless:apply").runNoError(); + + // File 1 is formatted because it lives under the default source dir + assertFile(FILE_1).sameAsResource(FORMATTED); + // File 4 is formatted because it lives under the custom-configured test source dir + assertFile(FILE_4).sameAsResource(FORMATTED); + + // Files 2, 3, 5 are not formatted because they live outside the default source dir and custom-configured test source dir + assertFile(FILE_2).sameAsResource(UNFORMATTED); + assertFile(FILE_3).sameAsResource(UNFORMATTED); + assertFile(FILE_5).sameAsResource(UNFORMATTED); + } + + @Test + void customSourceDirAndTestSourceDirConfiguration() throws Exception { + writePomWithBuildConfiguration( + "src", + "test"); + + mavenRunner().withArguments("spotless:apply").runNoError(); + + // Files 1, 2, 3, 4 are formatted because they live under custom-configured source and test source dirs + assertFile(FILE_1).sameAsResource(FORMATTED); + assertFile(FILE_2).sameAsResource(FORMATTED); + assertFile(FILE_3).sameAsResource(FORMATTED); + assertFile(FILE_4).sameAsResource(FORMATTED); + + // File 5 is not formatted because it lives outside custom-configured source and test source dirs + assertFile(FILE_5).sameAsResource(UNFORMATTED); + } + + @Test + void sameCustomSourceDirAndTestSourceDirConfiguration() throws Exception { + writePomWithBuildConfiguration( + "foo/bar", + "foo/bar"); + + mavenRunner().withArguments("spotless:apply").runNoError(); + + // Files 1, 2, 3, 4 are not formatted because they live outside custom-configured source and test source dirs + assertFile(FILE_1).sameAsResource(UNFORMATTED); + assertFile(FILE_2).sameAsResource(UNFORMATTED); + assertFile(FILE_3).sameAsResource(UNFORMATTED); + assertFile(FILE_4).sameAsResource(UNFORMATTED); + + // File 5 is formatted because it lives under the custom-configured source/test source dir + assertFile(FILE_5).sameAsResource(FORMATTED); + } + + @Test + void nestedCustomSourceDirAndTestSourceDirConfiguration() throws Exception { + writePomWithBuildConfiguration( + "foo", + "foo/bar"); + + mavenRunner().withArguments("spotless:apply").runNoError(); + + // Files 1, 2, 3, 4 are not formatted because they live outside custom-configured source and test source dirs + assertFile(FILE_1).sameAsResource(UNFORMATTED); + assertFile(FILE_2).sameAsResource(UNFORMATTED); + assertFile(FILE_3).sameAsResource(UNFORMATTED); + assertFile(FILE_4).sameAsResource(UNFORMATTED); + + // File 5 is formatted because it lives under the custom-configured source/test source dir + assertFile(FILE_5).sameAsResource(FORMATTED); + } + + private void writePomWithBuildConfiguration(String... build) throws IOException { + String xml = createPomXmlContent(build, new String[]{"", "", ""}); + setFile("pom.xml").toContent(xml); + } +} diff --git a/plugin-maven/src/test/resources/pom-test.xml.mustache b/plugin-maven/src/test/resources/pom-test.xml.mustache index 6db3cb0c15..f87e8c1a3e 100644 --- a/plugin-maven/src/test/resources/pom-test.xml.mustache +++ b/plugin-maven/src/test/resources/pom-test.xml.mustache @@ -20,6 +20,7 @@ + {{{build}}} {{{plugins}}} From 6d3862c702dd522fbb5f989a670b03720f8a49d9 Mon Sep 17 00:00:00 2001 From: Ned Twigg Date: Sun, 5 Feb 2023 01:07:51 -0800 Subject: [PATCH 28/59] Use the latest JScriptBox on Java 15+ --- .../main/java/com/diffplug/spotless/markdown/FreshMarkStep.java | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/src/main/java/com/diffplug/spotless/markdown/FreshMarkStep.java b/lib/src/main/java/com/diffplug/spotless/markdown/FreshMarkStep.java index fca5ac39a4..4477c640c7 100644 --- a/lib/src/main/java/com/diffplug/spotless/markdown/FreshMarkStep.java +++ b/lib/src/main/java/com/diffplug/spotless/markdown/FreshMarkStep.java @@ -66,6 +66,7 @@ public static FormatterStep create(String version, Supplier> prop List mavenCoordinates = new ArrayList<>(); mavenCoordinates.add(MAVEN_COORDINATE + version); if (Jvm.version() >= 15) { + mavenCoordinates.add("com.diffplug.jscriptbox:jscriptbox:3.0.1"); mavenCoordinates.add(NASHORN_MAVEN_COORDINATE + NASHORN_VERSION); } From e9d72aa093a70a8ed66d71aa8625394fa4d0f147 Mon Sep 17 00:00:00 2001 From: Ned Twigg Date: Sun, 5 Feb 2023 01:13:31 -0800 Subject: [PATCH 29/59] Update changelogs. --- CHANGES.md | 2 ++ plugin-gradle/CHANGES.md | 3 ++- plugin-maven/CHANGES.md | 1 - 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 72a4b99e93..c8add05b6a 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -12,7 +12,9 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format ( ## [Unreleased] ### Changes * **POTENTIALLY BREAKING** Bump bytecode from Java 8 to 11 ([#1530](https://github.com/diffplug/spotless/pull/1530) part 2 of [#1337](https://github.com/diffplug/spotless/issues/1337)) +### Fixed * **POTENTIALLY BREAKING** `sortByKeys` for JSON formatting now takes into account objects inside arrays ([#1546](https://github.com/diffplug/spotless/pull/1546)) +* `freshmark` fixed on java 15+ ([#1304](https://github.com/diffplug/spotless/pull/1304) fixes [#803](https://github.com/diffplug/spotless/issues/803)) ## [2.34.0] - 2023-01-26 ### Added diff --git a/plugin-gradle/CHANGES.md b/plugin-gradle/CHANGES.md index a81ee7bd93..fef2c71346 100644 --- a/plugin-gradle/CHANGES.md +++ b/plugin-gradle/CHANGES.md @@ -3,7 +3,8 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format (starting after version `3.27.0`). ## [Unreleased] -### Changes +### Fixed +* `freshmark` fixed on java 15+ ([#1304](https://github.com/diffplug/spotless/pull/1304) fixes [#803](https://github.com/diffplug/spotless/issues/803)) * **POTENTIALLY BREAKING** `sortByKeys` for JSON formatting now takes into account objects inside arrays ([#1546](https://github.com/diffplug/spotless/pull/1546)) ## [6.14.0] - 2023-01-26 diff --git a/plugin-maven/CHANGES.md b/plugin-maven/CHANGES.md index b924c07fd6..d498b868c7 100644 --- a/plugin-maven/CHANGES.md +++ b/plugin-maven/CHANGES.md @@ -7,7 +7,6 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format ( * A synthesis log with the number of considered files is added after each formatter execution ([#1507](https://github.com/diffplug/spotless/pull/1507)) ### Fixed * Respect `sourceDirectory` and `testSourceDirectory` POM configurations for Java formatters ([#1553](https://github.com/diffplug/spotless/pull/1553)) -### Changes * **POTENTIALLY BREAKING** `sortByKeys` for JSON formatting now takes into account objects inside arrays ([#1546](https://github.com/diffplug/spotless/pull/1546)) * Any commit of the Spotless maven plugin now available via JitPack ([#1547](https://github.com/diffplug/spotless/pull/1547)) From 0252904844cbd3a182f9668c49073b809aee97ab Mon Sep 17 00:00:00 2001 From: runner Date: Sun, 5 Feb 2023 16:46:18 +0000 Subject: [PATCH 30/59] Published lib/2.34.1 --- CHANGES.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index c8add05b6a..5f1a1ffa9f 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -10,6 +10,8 @@ This document is intended for Spotless developers. We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format (starting after version `1.27.0`). ## [Unreleased] + +## [2.34.1] - 2023-02-05 ### Changes * **POTENTIALLY BREAKING** Bump bytecode from Java 8 to 11 ([#1530](https://github.com/diffplug/spotless/pull/1530) part 2 of [#1337](https://github.com/diffplug/spotless/issues/1337)) ### Fixed From 2fece0442035a72fc3be978d47dca483e8d02b2c Mon Sep 17 00:00:00 2001 From: runner Date: Sun, 5 Feb 2023 16:48:11 +0000 Subject: [PATCH 31/59] Published gradle/6.14.1 --- plugin-gradle/CHANGES.md | 2 ++ plugin-gradle/README.md | 50 ++++++++++++++++++++-------------------- 2 files changed, 27 insertions(+), 25 deletions(-) diff --git a/plugin-gradle/CHANGES.md b/plugin-gradle/CHANGES.md index fef2c71346..e3234584b8 100644 --- a/plugin-gradle/CHANGES.md +++ b/plugin-gradle/CHANGES.md @@ -3,6 +3,8 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format (starting after version `3.27.0`). ## [Unreleased] + +## [6.14.1] - 2023-02-05 ### Fixed * `freshmark` fixed on java 15+ ([#1304](https://github.com/diffplug/spotless/pull/1304) fixes [#803](https://github.com/diffplug/spotless/issues/803)) * **POTENTIALLY BREAKING** `sortByKeys` for JSON formatting now takes into account objects inside arrays ([#1546](https://github.com/diffplug/spotless/pull/1546)) diff --git a/plugin-gradle/README.md b/plugin-gradle/README.md index 6a56d26e20..f61280bc7e 100644 --- a/plugin-gradle/README.md +++ b/plugin-gradle/README.md @@ -14,9 +14,9 @@ output = [ ].join('\n'); --> [![Gradle plugin](https://img.shields.io/badge/plugins.gradle.org-com.diffplug.spotless-blue.svg)](https://plugins.gradle.org/plugin/com.diffplug.spotless) -[![Changelog](https://img.shields.io/badge/changelog-6.14.0-blue.svg)](CHANGES.md) +[![Changelog](https://img.shields.io/badge/changelog-6.14.1-blue.svg)](CHANGES.md) [![Maven central](https://img.shields.io/badge/mavencentral-here-blue.svg)](https://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22com.diffplug.spotless%22%20AND%20a%3A%22spotless-plugin-gradle%22) -[![Javadoc](https://img.shields.io/badge/javadoc-here-blue.svg)](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.0/index.html) +[![Javadoc](https://img.shields.io/badge/javadoc-here-blue.svg)](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.1/index.html) [![VS Code plugin](https://img.shields.io/badge/IDE-VS_Code-blueviolet.svg)](https://marketplace.visualstudio.com/items?itemName=richardwillis.vscode-spotless-gradle) [![IntelliJ plugin](https://img.shields.io/badge/IDE-IntelliJ-blueviolet.svg)](https://plugins.jetbrains.com/plugin/18321-spotless-gradle) @@ -123,10 +123,10 @@ spotless { ``` Spotless consists of a list of formats (in the example above, `misc` and `java`), and each format has: -- a `target` (the files to format), which you set with [`target`](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.0/com/diffplug/gradle/spotless/FormatExtension.html#target-java.lang.Object...-) and [`targetExclude`](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.0/com/diffplug/gradle/spotless/FormatExtension.html#targetExclude-java.lang.Object...-) -- a list of `FormatterStep`, which are just `String -> String` functions, such as [`replace`](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.0/com/diffplug/gradle/spotless/FormatExtension.html#replace-java.lang.String-java.lang.CharSequence-java.lang.CharSequence-), [`replaceRegex`](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.0/com/diffplug/gradle/spotless/FormatExtension.html#replaceRegex-java.lang.String-java.lang.String-java.lang.String-), [`trimTrailingWhitespace`](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.0/com/diffplug/gradle/spotless/FormatExtension.html#replace-java.lang.String-java.lang.CharSequence-java.lang.CharSequence-), [`custom`](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.0/com/diffplug/gradle/spotless/FormatExtension.html#custom-java.lang.String-groovy.lang.Closure-), [`prettier`](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.0/com/diffplug/gradle/spotless/FormatExtension.html#prettier--), [`eclipseWtp`](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.0/com/diffplug/gradle/spotless/FormatExtension.html#eclipseWtp-com.diffplug.spotless.extra.wtp.EclipseWtpFormatterStep-), [`licenseHeader`](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.0/com/diffplug/gradle/spotless/FormatExtension.html#licenseHeader-java.lang.String-java.lang.String-) etc. +- a `target` (the files to format), which you set with [`target`](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.1/com/diffplug/gradle/spotless/FormatExtension.html#target-java.lang.Object...-) and [`targetExclude`](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.1/com/diffplug/gradle/spotless/FormatExtension.html#targetExclude-java.lang.Object...-) +- a list of `FormatterStep`, which are just `String -> String` functions, such as [`replace`](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.1/com/diffplug/gradle/spotless/FormatExtension.html#replace-java.lang.String-java.lang.CharSequence-java.lang.CharSequence-), [`replaceRegex`](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.1/com/diffplug/gradle/spotless/FormatExtension.html#replaceRegex-java.lang.String-java.lang.String-java.lang.String-), [`trimTrailingWhitespace`](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.1/com/diffplug/gradle/spotless/FormatExtension.html#replace-java.lang.String-java.lang.CharSequence-java.lang.CharSequence-), [`custom`](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.1/com/diffplug/gradle/spotless/FormatExtension.html#custom-java.lang.String-groovy.lang.Closure-), [`prettier`](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.1/com/diffplug/gradle/spotless/FormatExtension.html#prettier--), [`eclipseWtp`](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.1/com/diffplug/gradle/spotless/FormatExtension.html#eclipseWtp-com.diffplug.spotless.extra.wtp.EclipseWtpFormatterStep-), [`licenseHeader`](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.1/com/diffplug/gradle/spotless/FormatExtension.html#licenseHeader-java.lang.String-java.lang.String-) etc. -All the generic steps live in [`FormatExtension`](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.0/com/diffplug/gradle/spotless/FormatExtension.html), and there are many language-specific steps which live in its language-specific subclasses, which are described below. +All the generic steps live in [`FormatExtension`](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.1/com/diffplug/gradle/spotless/FormatExtension.html), and there are many language-specific steps which live in its language-specific subclasses, which are described below. ### Requirements @@ -138,7 +138,7 @@ If you're stuck on an older version of Gradle, `id 'com.diffplug.gradle.spotless ## Java -`com.diffplug.gradle.spotless.JavaExtension` [javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.0/com/diffplug/gradle/spotless/JavaExtension.html), [code](https://github.com/diffplug/spotless/blob/main/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavaExtension.java) +`com.diffplug.gradle.spotless.JavaExtension` [javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.1/com/diffplug/gradle/spotless/JavaExtension.html), [code](https://github.com/diffplug/spotless/blob/main/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavaExtension.java) ```gradle spotless { @@ -262,8 +262,8 @@ You can make a pull request to add new annotations to Spotless's default list. ## Groovy -- `com.diffplug.gradle.spotless.GroovyExtension` [javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.0/com/diffplug/gradle/spotless/GroovyExtension.html), [code](https://github.com/diffplug/spotless/blob/main/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/GroovyExtension.java) -- `com.diffplug.gradle.spotless.GroovyGradleExtension` [javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.0/com/diffplug/gradle/spotless/GroovyGradleExtension.html), [code](https://github.com/diffplug/spotless/blob/main/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/GroovyGradleExtension.java) +- `com.diffplug.gradle.spotless.GroovyExtension` [javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.1/com/diffplug/gradle/spotless/GroovyExtension.html), [code](https://github.com/diffplug/spotless/blob/main/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/GroovyExtension.java) +- `com.diffplug.gradle.spotless.GroovyGradleExtension` [javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.1/com/diffplug/gradle/spotless/GroovyGradleExtension.html), [code](https://github.com/diffplug/spotless/blob/main/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/GroovyGradleExtension.java) Configuration for Groovy is similar to [Java](#java), in that it also supports `licenseHeader` and `importOrder`. @@ -314,8 +314,8 @@ Groovy-Eclipse formatting errors/warnings lead per default to a build failure. T ## Kotlin -- `com.diffplug.gradle.spotless.KotlinExtension` [javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.0/com/diffplug/gradle/spotless/KotlinExtension.html), [code](https://github.com/diffplug/spotless/blob/main/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/KotlinExtension.java) -- `com.diffplug.gradle.spotless.KotlinGradleExtension` [javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.0/com/diffplug/gradle/spotless/KotlinGradleExtension.html), [code](https://github.com/diffplug/spotless/blob/main/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/KotlinGradleExtension.java) +- `com.diffplug.gradle.spotless.KotlinExtension` [javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.1/com/diffplug/gradle/spotless/KotlinExtension.html), [code](https://github.com/diffplug/spotless/blob/main/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/KotlinExtension.java) +- `com.diffplug.gradle.spotless.KotlinGradleExtension` [javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.1/com/diffplug/gradle/spotless/KotlinGradleExtension.html), [code](https://github.com/diffplug/spotless/blob/main/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/KotlinGradleExtension.java) ```gradle spotless { // if you are using build.gradle.kts, instead of 'spotless {' use: @@ -386,7 +386,7 @@ spotless { ## Scala -`com.diffplug.gradle.spotless.ScalaExtension` [javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.0/com/diffplug/gradle/spotless/ScalaExtension.html), [code](https://github.com/diffplug/spotless/blob/main/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/ScalaExtension.java) +`com.diffplug.gradle.spotless.ScalaExtension` [javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.1/com/diffplug/gradle/spotless/ScalaExtension.html), [code](https://github.com/diffplug/spotless/blob/main/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/ScalaExtension.java) ```gradle spotless { @@ -418,7 +418,7 @@ spotless { ## C/C++ -`com.diffplug.gradle.spotless.CppExtension` [javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.0/com/diffplug/gradle/spotless/CppExtension.html), [code](https://github.com/diffplug/spotless/blob/main/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/CppExtension.java) +`com.diffplug.gradle.spotless.CppExtension` [javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.1/com/diffplug/gradle/spotless/CppExtension.html), [code](https://github.com/diffplug/spotless/blob/main/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/CppExtension.java) ```gradle spotless { @@ -450,7 +450,7 @@ spotles { ## Python -`com.diffplug.gradle.spotless.PythonExtension` [javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.0/com/diffplug/gradle/spotless/PythonExtension.html), [code](https://github.com/diffplug/spotless/blob/main/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/PythonExtension.java) +`com.diffplug.gradle.spotless.PythonExtension` [javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.1/com/diffplug/gradle/spotless/PythonExtension.html), [code](https://github.com/diffplug/spotless/blob/main/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/PythonExtension.java) ```gradle spotless { @@ -484,7 +484,7 @@ black().pathToExe('C:/myuser/.pyenv/versions/3.8.0/scripts/black.exe') ## FreshMark -`com.diffplug.gradle.spotless.FreshMarkExtension` [javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.0/com/diffplug/gradle/spotless/FreshMarkExtension.html), [code](https://github.com/diffplug/spotless/blob/main/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/FreshMarkExtension.java) +`com.diffplug.gradle.spotless.FreshMarkExtension` [javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.1/com/diffplug/gradle/spotless/FreshMarkExtension.html), [code](https://github.com/diffplug/spotless/blob/main/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/FreshMarkExtension.java) [homepage](https://github.com/diffplug/freshmark). [changelog](https://github.com/diffplug/freshmark/blob/master/CHANGES.md). FreshMark lets you generate markdown in the comments of your markdown. This helps to keep badges and links up-to-date (see the source for this file), and can also be helpful for generating complex tables (see the source for [the parent readme](../README.md)). @@ -505,7 +505,7 @@ spotless { ## Antlr4 -`com.diffplug.gradle.spotless.Antlr4Extension` [javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.0/com/diffplug/gradle/spotless/Antlr4Extension.html), [code](https://github.com/diffplug/spotless/blob/main/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/Antlr4Extension.java) +`com.diffplug.gradle.spotless.Antlr4Extension` [javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.1/com/diffplug/gradle/spotless/Antlr4Extension.html), [code](https://github.com/diffplug/spotless/blob/main/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/Antlr4Extension.java) ```gradle spotless { @@ -530,7 +530,7 @@ antlr4formatter('1.2.1') // version is optional ## SQL -`com.diffplug.gradle.spotless.SqlExtension` [javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.0/com/diffplug/gradle/spotless/SqlExtension.html), [code](https://github.com/diffplug/spotless/blob/main/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SqlExtension.java) +`com.diffplug.gradle.spotless.SqlExtension` [javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.1/com/diffplug/gradle/spotless/SqlExtension.html), [code](https://github.com/diffplug/spotless/blob/main/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SqlExtension.java) ```gradle spotless { @@ -570,7 +570,7 @@ sql.formatter.indent.size=4 ## Typescript -- `com.diffplug.gradle.spotless.TypescriptExtension` [javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.0/com/diffplug/gradle/spotless/TypescriptExtension.html), [code](https://github.com/diffplug/spotless/blob/main/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/TypescriptExtension.java) +- `com.diffplug.gradle.spotless.TypescriptExtension` [javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.1/com/diffplug/gradle/spotless/TypescriptExtension.html), [code](https://github.com/diffplug/spotless/blob/main/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/TypescriptExtension.java) ```gradle spotless { @@ -662,7 +662,7 @@ For details, see the [npm detection](#npm-detection) and [`.npmrc` detection](#n ## Javascript -- `com.diffplug.gradle.spotless.JavascriptExtension` [javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.0/com/diffplug/gradle/spotless/JavascriptExtension.html), [code](https://github.com/diffplug/spotless/blob/main/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavascriptExtension.java) +- `com.diffplug.gradle.spotless.JavascriptExtension` [javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.1/com/diffplug/gradle/spotless/JavascriptExtension.html), [code](https://github.com/diffplug/spotless/blob/main/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavascriptExtension.java) ```gradle spotless { @@ -726,7 +726,7 @@ For details, see the [npm detection](#npm-detection) and [`.npmrc` detection](#n ## JSON -- `com.diffplug.gradle.spotless.JsonExtension` [javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.0/com/diffplug/gradle/spotless/JsonExtension.html), [code](https://github.com/diffplug/spotless/blob/main/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JsonExtension.java) +- `com.diffplug.gradle.spotless.JsonExtension` [javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.1/com/diffplug/gradle/spotless/JsonExtension.html), [code](https://github.com/diffplug/spotless/blob/main/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JsonExtension.java) ```gradle spotless { @@ -801,7 +801,7 @@ spotless { ## YAML -- `com.diffplug.gradle.spotless.YamlExtension` [javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.0/com/diffplug/gradle/spotless/JsonExtension.html), [code](https://github.com/diffplug/spotless/blob/main/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/YamlExtension.java) +- `com.diffplug.gradle.spotless.YamlExtension` [javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.1/com/diffplug/gradle/spotless/JsonExtension.html), [code](https://github.com/diffplug/spotless/blob/main/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/YamlExtension.java) ```gradle spotless { @@ -1014,7 +1014,7 @@ Once a file's license header has a valid year, whether it is a year (`2020`) or * `2017` -> `2017-2020` * `2017-2019` -> `2017-2020` -See the [javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.0/com/diffplug/gradle/spotless/FormatExtension.LicenseHeaderConfig.html) for a complete listing of options. +See the [javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.1/com/diffplug/gradle/spotless/FormatExtension.LicenseHeaderConfig.html) for a complete listing of options. @@ -1087,9 +1087,9 @@ spotless { custom 'lowercase', { str -> str.toLowerCase() } ``` -However, custom rules will disable up-to-date checking and caching, unless you read [this javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.0/com/diffplug/gradle/spotless/FormatExtension.html#bumpThisNumberIfACustomStepChanges-int-) and follow its instructions carefully. +However, custom rules will disable up-to-date checking and caching, unless you read [this javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.1/com/diffplug/gradle/spotless/FormatExtension.html#bumpThisNumberIfACustomStepChanges-int-) and follow its instructions carefully. -Another option is to create proper `FormatterStep` in your `buildSrc`, and then call [`addStep`](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.0/com/diffplug/gradle/spotless/FormatExtension.html#addStep-com.diffplug.spotless.FormatterStep-). The contributing guide describes [how to do this](https://github.com/diffplug/spotless/blob/main/CONTRIBUTING.md#how-to-add-a-new-formatterstep). If the step is generally-useful, we hope you'll open a PR to share it! +Another option is to create proper `FormatterStep` in your `buildSrc`, and then call [`addStep`](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.1/com/diffplug/gradle/spotless/FormatExtension.html#addStep-com.diffplug.spotless.FormatterStep-). The contributing guide describes [how to do this](https://github.com/diffplug/spotless/blob/main/CONTRIBUTING.md#how-to-add-a-new-formatterstep). If the step is generally-useful, we hope you'll open a PR to share it! ```gradle @@ -1122,11 +1122,11 @@ spotless { format 'foo', com.acme.FooLanguageExtension, { ``` -If you'd like to create a one-off Spotless task outside of the `check`/`apply` framework, see [`FormatExtension.createIndependentApplyTask`](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.0/com/diffplug/gradle/spotless/FormatExtension.html#createIndependentApplyTask-java.lang.String-). +If you'd like to create a one-off Spotless task outside of the `check`/`apply` framework, see [`FormatExtension.createIndependentApplyTask`](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.1/com/diffplug/gradle/spotless/FormatExtension.html#createIndependentApplyTask-java.lang.String-). ## Inception (languages within languages within...) -In very rare cases, you might want to format e.g. javascript which is written inside JSP templates, or maybe java within a markdown file, or something wacky like that. You can specify hunks within a file using either open/close tags or a regex with a single capturing group, and then specify rules within it, like so. See [javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.0/com/diffplug/gradle/spotless/FormatExtension.html#withinBlocks-java.lang.String-java.lang.String-java.lang.String-org.gradle.api.Action-) for more details. +In very rare cases, you might want to format e.g. javascript which is written inside JSP templates, or maybe java within a markdown file, or something wacky like that. You can specify hunks within a file using either open/close tags or a regex with a single capturing group, and then specify rules within it, like so. See [javadoc](https://javadoc.io/doc/com.diffplug.spotless/spotless-plugin-gradle/6.14.1/com/diffplug/gradle/spotless/FormatExtension.html#withinBlocks-java.lang.String-java.lang.String-java.lang.String-org.gradle.api.Action-) for more details. ```gradle import com.diffplug.gradle.spotless.JavaExtension From 8d99d7dc44b75fbfbcd25a2550332a11f40219cc Mon Sep 17 00:00:00 2001 From: runner Date: Sun, 5 Feb 2023 16:50:20 +0000 Subject: [PATCH 32/59] Published maven/2.32.0 --- plugin-maven/CHANGES.md | 2 ++ plugin-maven/README.md | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/plugin-maven/CHANGES.md b/plugin-maven/CHANGES.md index d498b868c7..567d880f4f 100644 --- a/plugin-maven/CHANGES.md +++ b/plugin-maven/CHANGES.md @@ -3,6 +3,8 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format (starting after version `1.27.0`). ## [Unreleased] + +## [2.32.0] - 2023-02-05 ### Added * A synthesis log with the number of considered files is added after each formatter execution ([#1507](https://github.com/diffplug/spotless/pull/1507)) ### Fixed diff --git a/plugin-maven/README.md b/plugin-maven/README.md index 73402cd929..0787150ee1 100644 --- a/plugin-maven/README.md +++ b/plugin-maven/README.md @@ -8,8 +8,8 @@ output = [ ].join('\n'); --> [![Maven central](https://img.shields.io/badge/mavencentral-com.diffplug.spotless%3Aspotless--maven--plugin-blue.svg)](https://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22com.diffplug.spotless%22%20AND%20a%3A%22spotless-maven-plugin%22) -[![Changelog](https://img.shields.io/badge/changelog-2.31.0-blue.svg)](CHANGES.md) -[![Javadoc](https://img.shields.io/badge/javadoc-here-blue.svg)](https://javadoc.io/doc/com.diffplug.spotless/spotless-maven-plugin/2.31.0/index.html) +[![Changelog](https://img.shields.io/badge/changelog-2.32.0-blue.svg)](CHANGES.md) +[![Javadoc](https://img.shields.io/badge/javadoc-here-blue.svg)](https://javadoc.io/doc/com.diffplug.spotless/spotless-maven-plugin/2.32.0/index.html) + @@ -274,6 +276,25 @@ list of well-known type annotations. You can make a pull request to add new one In the future there will be mechanisms to add/remove annotations from the list. These mechanisms already exist for the Gradle plugin. +### Cleanthat + +[homepage](https://github.com/solven-eu/cleanthat). CleanThat enables automatic refactoring of Java code + +```xml + + 2.0 + ${maven.compiler.source} + + * + + + LiteralsFirstInComparisons + + + OptionalNotEmpty + + +``` ## Groovy diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/CleanthatJava.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/CleanthatJava.java index 76c130bcdd..7460ab67b9 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/CleanthatJava.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/CleanthatJava.java @@ -20,7 +20,7 @@ import org.apache.maven.plugins.annotations.Parameter; import com.diffplug.spotless.FormatterStep; -import com.diffplug.spotless.java.CleanthatStepFactory; +import com.diffplug.spotless.java.CleanthatJavaStep; import com.diffplug.spotless.maven.FormatterStepConfig; import com.diffplug.spotless.maven.FormatterStepFactory; @@ -33,19 +33,19 @@ public class CleanthatJava implements FormatterStepFactory { // https://maven.apache.org/plugins/maven-compiler-plugin/compile-mojo.html#source @Parameter(property = "maven.compiler.source") - private String sourceJdk = CleanthatStepFactory.defaultJdkVersion(); + private String sourceJdk = CleanthatJavaStep.defaultJdkVersion(); @Parameter - private List mutators = CleanthatStepFactory.defaultMutators(); + private List mutators = CleanthatJavaStep.defaultMutators(); @Parameter - private List excludedMutators = CleanthatStepFactory.defaultExcludedMutators(); + private List excludedMutators = CleanthatJavaStep.defaultExcludedMutators(); @Override public FormatterStep newFormatterStep(FormatterStepConfig config) { - String groupArtifact = this.groupArtifact != null ? this.groupArtifact : CleanthatStepFactory.defaultGroupArtifact(); - String version = this.version != null ? this.version : CleanthatStepFactory.defaultVersion(); + String groupArtifact = this.groupArtifact != null ? this.groupArtifact : CleanthatJavaStep.defaultGroupArtifact(); + String version = this.version != null ? this.version : CleanthatJavaStep.defaultVersion(); - return CleanthatStepFactory.create(groupArtifact, version, sourceJdk, mutators, excludedMutators, config.getProvisioner()); + return CleanthatJavaStep.create(groupArtifact, version, sourceJdk, mutators, excludedMutators, config.getProvisioner()); } } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/Java.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/Java.java index 0921a838b3..efdf0827db 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/Java.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/Java.java @@ -79,6 +79,10 @@ public void addFormatAnnotations(FormatAnnotations formatAnnotations) { addStepFactory(formatAnnotations); } + public void addCleanthat(CleanthatJava cleanthat) { + addStepFactory(cleanthat); + } + private static String fileMask(Path path) { String dir = path.toString(); if (!dir.endsWith(File.separator)) { diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/CleanthatJavaRefactorerTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/CleanthatJavaRefactorerTest.java new file mode 100644 index 0000000000..c72aeb15b2 --- /dev/null +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/CleanthatJavaRefactorerTest.java @@ -0,0 +1,76 @@ +/* + * Copyright 2022-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.java; + +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.diffplug.spotless.maven.MavenIntegrationHarness; + +class CleanthatJavaRefactorerTest extends MavenIntegrationHarness { + private static final Logger LOGGER = LoggerFactory.getLogger(CleanthatJavaRefactorerTest.class); + + @Test + void testLiteralsFirstInComparisons() throws Exception { + writePomWithJavaSteps( + "", + ""); + + runTest("LiteralsFirstInComparisons.dirty.java", "LiteralsFirstInComparisons.clean.java"); + } + + @Test + void testMultipleMutators() throws Exception { + writePomWithJavaSteps( + "", + ""); + + runTest("MultipleMutators.dirty.java", "MultipleMutators.clean.java"); + } + + @Test + void testExcludeOptionalNotEmpty() throws Exception { + writePomWithJavaSteps( + "", + " ", + " OptionalNotEmpty", + " ", + ""); + + runTest("MultipleMutators.dirty.java", "MultipleMutators.clean.onlyLiteralsFirst.java"); + } + + @Test + void testIncludeOnlyLiteralsFirstInComparisons() throws Exception { + writePomWithJavaSteps( + "", + " ", + " LiteralsFirstInComparisons", + " ", + ""); + + runTest("MultipleMutators.dirty.java", "MultipleMutators.clean.onlyLiteralsFirst.java"); + } + + private void runTest(String dirtyPath, String cleanPath) throws Exception { + String path = "src/main/java/test.java"; + setFile(path).toResource("java/cleanthat/" + dirtyPath); + Assertions.assertThat(mavenRunner().withArguments("spotless:apply -X").runNoError().stdOutUtf8()).isEmpty(); + assertFile(path).sameAsResource("java/cleanthat/" + cleanPath); + } +} diff --git a/testlib/src/main/resources/java/cleanthat/LiteralsFirstInComparisons.clean.java b/testlib/src/main/resources/java/cleanthat/LiteralsFirstInComparisons.clean.java new file mode 100644 index 0000000000..8bacfa58db --- /dev/null +++ b/testlib/src/main/resources/java/cleanthat/LiteralsFirstInComparisons.clean.java @@ -0,0 +1,8 @@ +package eu.solven.cleanthat.engine.java.refactorer.cases.do_not_format_me; + +public class LiteralsFirstInComparisonsCases { + + public boolean isHardcoded(String input) { + return "hardcoded".equals(input); + } +} diff --git a/testlib/src/main/resources/java/cleanthat/LiteralsFirstInComparisons.dirty.java b/testlib/src/main/resources/java/cleanthat/LiteralsFirstInComparisons.dirty.java new file mode 100644 index 0000000000..3a1e074c91 --- /dev/null +++ b/testlib/src/main/resources/java/cleanthat/LiteralsFirstInComparisons.dirty.java @@ -0,0 +1,8 @@ +package eu.solven.cleanthat.engine.java.refactorer.cases.do_not_format_me; + +public class LiteralsFirstInComparisonsCases { + + public boolean isHardcoded(String input) { + return input.equals("hardcoded"); + } +} diff --git a/testlib/src/main/resources/java/cleanthat/MultipleMutators.clean.java b/testlib/src/main/resources/java/cleanthat/MultipleMutators.clean.java new file mode 100644 index 0000000000..0829602dc1 --- /dev/null +++ b/testlib/src/main/resources/java/cleanthat/MultipleMutators.clean.java @@ -0,0 +1,14 @@ +package eu.solven.cleanthat.engine.java.refactorer.cases.do_not_format_me; + +import java.util.Optional; + +public class LiteralsFirstInComparisonsCases { + + public boolean isHardcoded(String input) { + return input.equals("hardcoded"); + } + + public boolean isPresent(Optional optional) { + return optional.isPresent(); + } +} diff --git a/testlib/src/main/resources/java/cleanthat/MultipleMutators.clean.onlyLiteralsFirst.java b/testlib/src/main/resources/java/cleanthat/MultipleMutators.clean.onlyLiteralsFirst.java new file mode 100644 index 0000000000..629d24504b --- /dev/null +++ b/testlib/src/main/resources/java/cleanthat/MultipleMutators.clean.onlyLiteralsFirst.java @@ -0,0 +1,14 @@ +package eu.solven.cleanthat.engine.java.refactorer.cases.do_not_format_me; + +import java.util.Optional; + +public class LiteralsFirstInComparisonsCases { + + public boolean isHardcoded(String input) { + return "hardcoded".equals(input); + } + + public boolean isPresent(Optional optional) { + return !optional.isEmpty(); + } +} diff --git a/testlib/src/main/resources/java/cleanthat/MultipleMutators.dirty.java b/testlib/src/main/resources/java/cleanthat/MultipleMutators.dirty.java new file mode 100644 index 0000000000..8ac230cabc --- /dev/null +++ b/testlib/src/main/resources/java/cleanthat/MultipleMutators.dirty.java @@ -0,0 +1,14 @@ +package eu.solven.cleanthat.engine.java.refactorer.cases.do_not_format_me; + +import java.util.Optional; + +public class LiteralsFirstInComparisonsCases { + + public boolean isHardcoded(String input) { + return input.equals("hardcoded"); + } + + public boolean isPresent(Optional optional) { + return !optional.isEmpty(); + } +} From 4f62769da7ba656ee47e9596d7f5b0f9c531c650 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lars=20L=C3=B8nne?= Date: Wed, 8 Feb 2023 14:06:17 +0100 Subject: [PATCH 41/59] fixes continuation indent in ktfmt default formatter --- .../spotless/glue/ktfmt/KtfmtFormatterFunc.java | 2 +- .../com/diffplug/spotless/maven/kotlin/KtfmtTest.java | 11 +++++++++++ .../main/resources/kotlin/ktfmt/continuation.clean | 6 ++++++ .../main/resources/kotlin/ktfmt/continuation.dirty | 4 ++++ 4 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 testlib/src/main/resources/kotlin/ktfmt/continuation.clean create mode 100644 testlib/src/main/resources/kotlin/ktfmt/continuation.dirty diff --git a/lib/src/ktfmt/java/com/diffplug/spotless/glue/ktfmt/KtfmtFormatterFunc.java b/lib/src/ktfmt/java/com/diffplug/spotless/glue/ktfmt/KtfmtFormatterFunc.java index 72e0e50e3c..e34f7b4755 100644 --- a/lib/src/ktfmt/java/com/diffplug/spotless/glue/ktfmt/KtfmtFormatterFunc.java +++ b/lib/src/ktfmt/java/com/diffplug/spotless/glue/ktfmt/KtfmtFormatterFunc.java @@ -78,7 +78,7 @@ private FormattingOptions createFormattingOptions() { formattingOptions.getStyle(), ktfmtFormattingOptions.getMaxWidth().orElse(formattingOptions.getMaxWidth()), ktfmtFormattingOptions.getBlockIndent().orElse(formattingOptions.getBlockIndent()), - ktfmtFormattingOptions.getContinuationIndent().orElse(formattingOptions.getBlockIndent()), + ktfmtFormattingOptions.getContinuationIndent().orElse(formattingOptions.getContinuationIndent()), ktfmtFormattingOptions.getRemoveUnusedImport().orElse(formattingOptions.getRemoveUnusedImports()), formattingOptions.getDebuggingPrintOpsAfterFormatting()); } diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/kotlin/KtfmtTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/kotlin/KtfmtTest.java index 4ae266cc23..25ecbc598d 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/kotlin/KtfmtTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/kotlin/KtfmtTest.java @@ -19,6 +19,8 @@ import com.diffplug.spotless.maven.MavenIntegrationHarness; +import java.io.IOException; + class KtfmtTest extends MavenIntegrationHarness { @Test void testKtfmt() throws Exception { @@ -36,6 +38,15 @@ void testKtfmt() throws Exception { assertFile(path2).sameAsResource("kotlin/ktfmt/basic.clean"); } + @Test + void testContinuation() throws Exception { + writePomWithKotlinSteps(""); + + setFile("src/main/kotlin/main.kt").toResource("kotlin/ktfmt/continuation.dirty"); + mavenRunner().withArguments("spotless:apply").runNoError(); + assertFile("src/main/kotlin/main.kt").sameAsResource("kotlin/ktfmt/continuation.clean"); + } + @Test void testKtfmtStyle() throws Exception { writePomWithKotlinSteps(""); diff --git a/testlib/src/main/resources/kotlin/ktfmt/continuation.clean b/testlib/src/main/resources/kotlin/ktfmt/continuation.clean new file mode 100644 index 0000000000..11677928fc --- /dev/null +++ b/testlib/src/main/resources/kotlin/ktfmt/continuation.clean @@ -0,0 +1,6 @@ +fun myFunction() { + val location = + restTemplate.postForLocation( + "/v1/my-api", mapOf("name" to "some-name", "url" to "https://www.google.com")) + return location +} diff --git a/testlib/src/main/resources/kotlin/ktfmt/continuation.dirty b/testlib/src/main/resources/kotlin/ktfmt/continuation.dirty new file mode 100644 index 0000000000..3652274d12 --- /dev/null +++ b/testlib/src/main/resources/kotlin/ktfmt/continuation.dirty @@ -0,0 +1,4 @@ +fun myFunction() { + val location = restTemplate.postForLocation("/v1/my-api", mapOf("name" to "some-name", "url" to "https://www.google.com")) + return location +} From 8c74020fd505ecbc46db645b7fa330cbf5fd9514 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lars=20L=C3=B8nne?= Date: Wed, 8 Feb 2023 14:16:52 +0100 Subject: [PATCH 42/59] adds a summary of the change to plugin-maven/CHANGES.md --- plugin-maven/CHANGES.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/plugin-maven/CHANGES.md b/plugin-maven/CHANGES.md index 567d880f4f..0e656e24ec 100644 --- a/plugin-maven/CHANGES.md +++ b/plugin-maven/CHANGES.md @@ -3,6 +3,8 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format (starting after version `1.27.0`). ## [Unreleased] +### Fixed +* Maven plugin with `ktfmt` default style uses correct continuation indent ([#1562](https://github.com/diffplug/spotless/pull/1562)) ## [2.32.0] - 2023-02-05 ### Added From 69e8524c650a53eaae67df350a56bb389b0a8903 Mon Sep 17 00:00:00 2001 From: Benoit Lacelle Date: Wed, 8 Feb 2023 22:28:15 +0400 Subject: [PATCH 43/59] Move to 2.1 to fix issue with class detection --- lib/build.gradle | 5 +- .../spotless/java/CleanthatJavaStep.java | 2 +- .../java/JavaCleanthatRefactorerFuncTest.java | 28 ++++++++ .../java/JavaCleanthatRefactorerFuncTest.java | 72 +++++++++++++++++++ .../java/CleanthatJavaRefactorerTest.java | 2 +- 5 files changed, 106 insertions(+), 3 deletions(-) create mode 100644 lib/src/test/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFuncTest.java create mode 100644 lib/src/testCleanthat/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFuncTest.java diff --git a/lib/build.gradle b/lib/build.gradle index 0e1c2086ea..cd6996a979 100644 --- a/lib/build.gradle +++ b/lib/build.gradle @@ -55,6 +55,7 @@ dependencies { testCommonImplementation "org.junit.jupiter:junit-jupiter:$VER_JUNIT" testCommonImplementation "org.assertj:assertj-core:$VER_ASSERTJ" testCommonImplementation "com.diffplug.durian:durian-testlib:$VER_DURIAN" + testCommonImplementation 'io.github.solven-eu.cleanthat:java:2.1' // used for pom sorting sortPomCompileOnly 'com.github.ekryd.sortpom:sortpom-sorter:3.0.0' @@ -102,7 +103,9 @@ dependencies { gsonCompileOnly 'com.google.code.gson:gson:2.10.1' - cleanthatCompileOnly 'io.github.solven-eu.cleanthat:java:2.0' + // TODO How can one add a test module like 'compatKtLint0Dot48Dot0'? + // cleanthatCompileAndTestOnly 'io.github.solven-eu.cleanthat:java:2.1' + cleanthatCompileOnly 'io.github.solven-eu.cleanthat:java:2.1' } // we'll hold the core lib to a high standard diff --git a/lib/src/main/java/com/diffplug/spotless/java/CleanthatJavaStep.java b/lib/src/main/java/com/diffplug/spotless/java/CleanthatJavaStep.java index 79434cba56..fe4966d873 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/CleanthatJavaStep.java +++ b/lib/src/main/java/com/diffplug/spotless/java/CleanthatJavaStep.java @@ -39,7 +39,7 @@ public final class CleanthatJavaStep { private static final String NAME = "cleanthat"; private static final String MAVEN_COORDINATE = "io.github.solven-eu.cleanthat:java"; - private static final Jvm.Support JVM_SUPPORT = Jvm. support(NAME).add(11, "2.0"); + private static final Jvm.Support JVM_SUPPORT = Jvm. support(NAME).add(11, "2.1"); // prevent direct instantiation private CleanthatJavaStep() {} diff --git a/lib/src/test/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFuncTest.java b/lib/src/test/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFuncTest.java new file mode 100644 index 0000000000..2f3cdc9646 --- /dev/null +++ b/lib/src/test/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFuncTest.java @@ -0,0 +1,28 @@ +/* + * Copyright 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.glue.java; + +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.Test; + +import eu.solven.cleanthat.engine.java.refactorer.JavaRefactorer; + +public class JavaCleanthatRefactorerFuncTest { + @Test + public void testMutatorsDetection() { + Assertions.assertThat(JavaRefactorer.getAllIncluded()).isNotEmpty(); + } +} diff --git a/lib/src/testCleanthat/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFuncTest.java b/lib/src/testCleanthat/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFuncTest.java new file mode 100644 index 0000000000..c811b51233 --- /dev/null +++ b/lib/src/testCleanthat/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFuncTest.java @@ -0,0 +1,72 @@ +/* + * Copyright 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.glue.ktlint.compat; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.Map; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +public class KtLintCompat0Dot48Dot0AdapterTest { + @Test + public void testDefaults(@TempDir Path path) throws IOException { + KtLintCompat0Dot48Dot0Adapter ktLintCompat0Dot48Dot0Adapter = new KtLintCompat0Dot48Dot0Adapter(); + String text = loadAndWriteText(path, "empty_class_body.kt"); + final Path filePath = Paths.get(path.toString(), "empty_class_body.kt"); + + Map userData = new HashMap<>(); + + Map editorConfigOverrideMap = new HashMap<>(); + + String formatted = ktLintCompat0Dot48Dot0Adapter.format(text, filePath, false, false, null, userData, editorConfigOverrideMap); + assertEquals("class empty_class_body\n", formatted); + } + + @Test + public void testEditorConfigCanDisable(@TempDir Path path) throws IOException { + KtLintCompat0Dot48Dot0Adapter ktLintCompat0Dot48Dot0Adapter = new KtLintCompat0Dot48Dot0Adapter(); + String text = loadAndWriteText(path, "fails_no_semicolons.kt"); + final Path filePath = Paths.get(path.toString(), "fails_no_semicolons.kt"); + + Map userData = new HashMap<>(); + + Map editorConfigOverrideMap = new HashMap<>(); + editorConfigOverrideMap.put("indent_style", "tab"); + editorConfigOverrideMap.put("ktlint_standard_no-semi", "disabled"); + // ktlint_filename is an invalid rule in ktlint 0.48.0 + editorConfigOverrideMap.put("ktlint_filename", "disabled"); + + String formatted = ktLintCompat0Dot48Dot0Adapter.format(text, filePath, false, false, null, userData, editorConfigOverrideMap); + assertEquals("class fails_no_semicolons {\n\tval i = 0;\n}\n", formatted); + } + + private static String loadAndWriteText(Path path, String name) throws IOException { + try (InputStream is = KtLintCompat0Dot48Dot0AdapterTest.class.getResourceAsStream("/" + name)) { + Files.copy(is, path.resolve(name)); + } + return new String(Files.readAllBytes(path.resolve(name)), StandardCharsets.UTF_8); + } + +} diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/CleanthatJavaRefactorerTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/CleanthatJavaRefactorerTest.java index c72aeb15b2..833b19dda8 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/CleanthatJavaRefactorerTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/CleanthatJavaRefactorerTest.java @@ -70,7 +70,7 @@ void testIncludeOnlyLiteralsFirstInComparisons() throws Exception { private void runTest(String dirtyPath, String cleanPath) throws Exception { String path = "src/main/java/test.java"; setFile(path).toResource("java/cleanthat/" + dirtyPath); - Assertions.assertThat(mavenRunner().withArguments("spotless:apply -X").runNoError().stdOutUtf8()).isEmpty(); + Assertions.assertThat(mavenRunner().withArguments("spotless:apply").withRemoteDebug(21654).runNoError().stdOutUtf8()).doesNotContain("[ERROR]"); assertFile(path).sameAsResource("java/cleanthat/" + cleanPath); } } From bcab5b4abb044d6ba9b730b56b99c74cd4408453 Mon Sep 17 00:00:00 2001 From: Benoit Lacelle Date: Wed, 8 Feb 2023 22:32:23 +0400 Subject: [PATCH 44/59] Improve documentation and changelog ref --- .../spotless/glue/java/JavaCleanthatRefactorerFunc.java | 4 ++++ .../java/com/diffplug/spotless/java/CleanthatJavaStep.java | 1 + plugin-maven/README.md | 2 +- 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/lib/src/cleanthat/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFunc.java b/lib/src/cleanthat/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFunc.java index 5ec54e69be..7432ebf3f9 100644 --- a/lib/src/cleanthat/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFunc.java +++ b/lib/src/cleanthat/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFunc.java @@ -30,6 +30,10 @@ import eu.solven.cleanthat.engine.java.refactorer.JavaRefactorerProperties; import eu.solven.cleanthat.formatter.LineEnding; +/** + * The glue for CleanThat: it is build over the version in build.gradle, but at runtime it will be executed over + * the version loaded in JarState, which is by default defined in com.diffplug.spotless.java.CleanthatJavaStep#JVM_SUPPORT + */ public class JavaCleanthatRefactorerFunc implements FormatterFunc { private static final Logger LOGGER = LoggerFactory.getLogger(JavaCleanthatRefactorerFunc.class); diff --git a/lib/src/main/java/com/diffplug/spotless/java/CleanthatJavaStep.java b/lib/src/main/java/com/diffplug/spotless/java/CleanthatJavaStep.java index fe4966d873..1cd032a304 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/CleanthatJavaStep.java +++ b/lib/src/main/java/com/diffplug/spotless/java/CleanthatJavaStep.java @@ -39,6 +39,7 @@ public final class CleanthatJavaStep { private static final String NAME = "cleanthat"; private static final String MAVEN_COORDINATE = "io.github.solven-eu.cleanthat:java"; + // CleanThat changelog is available at https://github.com/solven-eu/cleanthat/blob/master/CHANGES.MD private static final Jvm.Support JVM_SUPPORT = Jvm. support(NAME).add(11, "2.1"); // prevent direct instantiation diff --git a/plugin-maven/README.md b/plugin-maven/README.md index 36d46b2386..b1b9098bfe 100644 --- a/plugin-maven/README.md +++ b/plugin-maven/README.md @@ -278,7 +278,7 @@ These mechanisms already exist for the Gradle plugin. ### Cleanthat -[homepage](https://github.com/solven-eu/cleanthat). CleanThat enables automatic refactoring of Java code +[homepage](https://github.com/solven-eu/cleanthat). CleanThat enables automatic refactoring of Java code. [ChangeLog](https://github.com/solven-eu/cleanthat/blob/master/CHANGES.MD) ```xml From a5c8b4da6975b69e5d62ea29246a422a269610e1 Mon Sep 17 00:00:00 2001 From: Benoit Lacelle Date: Wed, 8 Feb 2023 23:06:46 +0400 Subject: [PATCH 45/59] Fix classLoader issue --- .../java/JavaCleanthatRefactorerFunc.java | 19 +++++++++++++++++++ .../java/CleanthatJavaRefactorerTest.java | 15 +++++++++++++-- .../cleanthat/MultipleMutators.clean.java | 2 +- 3 files changed, 33 insertions(+), 3 deletions(-) diff --git a/lib/src/cleanthat/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFunc.java b/lib/src/cleanthat/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFunc.java index 7432ebf3f9..c94fd3c7c4 100644 --- a/lib/src/cleanthat/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFunc.java +++ b/lib/src/cleanthat/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFunc.java @@ -15,6 +15,7 @@ */ package com.diffplug.spotless.glue.java; +import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -25,6 +26,7 @@ import com.diffplug.spotless.FormatterFunc; import eu.solven.cleanthat.config.pojo.CleanthatEngineProperties; +import eu.solven.cleanthat.config.pojo.SourceCodeProperties; import eu.solven.cleanthat.engine.java.IJdkVersionConstants; import eu.solven.cleanthat.engine.java.refactorer.JavaRefactorer; import eu.solven.cleanthat.engine.java.refactorer.JavaRefactorerProperties; @@ -53,8 +55,25 @@ public JavaCleanthatRefactorerFunc() { @Override public String apply(String input) throws Exception { + // https://stackoverflow.com/questions/1771679/difference-between-threads-context-class-loader-and-normal-classloader + ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); + try { + // Ensure CleanThat main Thread has its custom classLoader while executing its refactoring + Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); + return doApply(input); + } finally { + // Restore the originalClassLoader + Thread.currentThread().setContextClassLoader(originalClassLoader); + } + } + + private String doApply(String input) throws InterruptedException, IOException { + // call some API that uses reflection without taking ClassLoader param CleanthatEngineProperties engineProperties = CleanthatEngineProperties.builder().engineVersion(jdkVersion).build(); + // Spotless will push us LF content + engineProperties.setSourceCode(SourceCodeProperties.builder().lineEnding(LineEnding.LF).build()); + JavaRefactorerProperties refactorerProperties = new JavaRefactorerProperties(); refactorerProperties.setIncluded(included); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/CleanthatJavaRefactorerTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/CleanthatJavaRefactorerTest.java index 833b19dda8..edb7a69cd5 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/CleanthatJavaRefactorerTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/CleanthatJavaRefactorerTest.java @@ -35,11 +35,21 @@ void testLiteralsFirstInComparisons() throws Exception { } @Test - void testMultipleMutators() throws Exception { + void testMultipleMutators_defaultIsJdk7() throws Exception { writePomWithJavaSteps( "", ""); + runTest("MultipleMutators.dirty.java", "MultipleMutators.clean.onlyLiteralsFirst.java"); + } + + @Test + void testMultipleMutators_Jdk11IntroducedOptionalisPresent() throws Exception { + writePomWithJavaSteps( + "", + "11", + ""); + runTest("MultipleMutators.dirty.java", "MultipleMutators.clean.java"); } @@ -70,7 +80,8 @@ void testIncludeOnlyLiteralsFirstInComparisons() throws Exception { private void runTest(String dirtyPath, String cleanPath) throws Exception { String path = "src/main/java/test.java"; setFile(path).toResource("java/cleanthat/" + dirtyPath); - Assertions.assertThat(mavenRunner().withArguments("spotless:apply").withRemoteDebug(21654).runNoError().stdOutUtf8()).doesNotContain("[ERROR]"); + // .withRemoteDebug(21654) + Assertions.assertThat(mavenRunner().withArguments("spotless:apply").runNoError().stdOutUtf8()).doesNotContain("[ERROR]"); assertFile(path).sameAsResource("java/cleanthat/" + cleanPath); } } diff --git a/testlib/src/main/resources/java/cleanthat/MultipleMutators.clean.java b/testlib/src/main/resources/java/cleanthat/MultipleMutators.clean.java index 0829602dc1..318e1efa15 100644 --- a/testlib/src/main/resources/java/cleanthat/MultipleMutators.clean.java +++ b/testlib/src/main/resources/java/cleanthat/MultipleMutators.clean.java @@ -5,7 +5,7 @@ public class LiteralsFirstInComparisonsCases { public boolean isHardcoded(String input) { - return input.equals("hardcoded"); + return "hardcoded".equals(input); } public boolean isPresent(Optional optional) { From 14122d0f9254c570c4fb894560db91d6b681a528 Mon Sep 17 00:00:00 2001 From: Benoit Lacelle Date: Wed, 8 Feb 2023 23:35:47 +0400 Subject: [PATCH 46/59] Add Gradle compatibility --- .../gradle/spotless/JavaExtension.java | 74 ++++++++++++++++++- .../CleanthatJavaIntegrationTest.java | 42 +++++++++++ 2 files changed, 115 insertions(+), 1 deletion(-) create mode 100644 plugin-gradle/src/test/java/com/diffplug/gradle/spotless/CleanthatJavaIntegrationTest.java diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavaExtension.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavaExtension.java index 0f5926ec66..e65d0601e7 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavaExtension.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavaExtension.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2022 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. @@ -34,6 +34,7 @@ import com.diffplug.spotless.extra.EclipseBasedStepBuilder; import com.diffplug.spotless.extra.java.EclipseJdtFormatterStep; import com.diffplug.spotless.generic.LicenseHeaderStep; +import com.diffplug.spotless.java.CleanthatJavaStep; import com.diffplug.spotless.java.FormatAnnotationsStep; import com.diffplug.spotless.java.GoogleJavaFormatStep; import com.diffplug.spotless.java.ImportOrderStep; @@ -270,6 +271,77 @@ private FormatterStep createStep() { } } + /** Apply CleanThat refactoring rules. */ + public CleanthatJavaConfig cleanthat() { + return new CleanthatJavaConfig(); + } + + public class CleanthatJavaConfig { + private String groupArtifact = CleanthatJavaStep.defaultGroupArtifact(); + + private String version = CleanthatJavaStep.defaultVersion(); + + private String sourceJdk = CleanthatJavaStep.defaultJdkVersion(); + + private List mutators = CleanthatJavaStep.defaultMutators(); + + private List excludedMutators = CleanthatJavaStep.defaultExcludedMutators(); + + CleanthatJavaConfig() { + addStep(createStep()); + } + + public CleanthatJavaConfig groupArtifact(String groupArtifact) { + Objects.requireNonNull(groupArtifact); + this.groupArtifact = groupArtifact; + replaceStep(createStep()); + return this; + } + + public CleanthatJavaConfig version(String version) { + Objects.requireNonNull(version); + this.version = version; + replaceStep(createStep()); + return this; + } + + public CleanthatJavaConfig sourceJdk(String sourceJdk) { + Objects.requireNonNull(sourceJdk); + this.sourceJdk = sourceJdk; + replaceStep(createStep()); + return this; + } + + // Especially useful to clear default mutators + public CleanthatJavaConfig clearMutators() { + this.mutators.clear(); + replaceStep(createStep()); + return this; + } + + // The fully qualified name of a class implementing eu.solven.cleanthat.engine.java.refactorer.meta.IMutator + // or '*' to include all default mutators + public CleanthatJavaConfig addMutator(String mutator) { + this.mutators.add(mutator); + replaceStep(createStep()); + return this; + } + + // useful to exclude a mutator amongst the default list of mutators + public CleanthatJavaConfig excludeMutator(String mutator) { + this.excludedMutators.add(mutator); + replaceStep(createStep()); + return this; + } + + private FormatterStep createStep() { + return CleanthatJavaStep.create( + groupArtifact, + version, + sourceJdk, mutators, excludedMutators, provisioner()); + } + } + /** If the user hasn't specified the files yet, we'll assume he/she means all of the java files. */ @Override protected void setupTask(SpotlessTask task) { diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/CleanthatJavaIntegrationTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/CleanthatJavaIntegrationTest.java new file mode 100644 index 0000000000..2b3ede1472 --- /dev/null +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/CleanthatJavaIntegrationTest.java @@ -0,0 +1,42 @@ +/* + * Copyright 2022-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.gradle.spotless; + +import java.io.IOException; + +import org.junit.jupiter.api.Test; + +class CleanthatJavaIntegrationTest extends GradleIntegrationHarness { + @Test + void integration() throws IOException { + setFile("build.gradle").toLines( + "plugins {", + " id 'com.diffplug.spotless'", + "}", + "repositories { mavenCentral() }", + "", + "spotless {", + " java {", + " target file('test.java')", + " cleanthat().sourceJdk('11')", + " }", + "}"); + + setFile("test.java").toResource("java/cleanthat/MultipleMutators.dirty.java"); + gradleRunner().withArguments("spotlessApply").build(); + assertFile("test.java").sameAsResource("java/cleanthat/MultipleMutators.clean.java"); + } +} From cfd07b06952840df641eea1c59d6f495e86544e6 Mon Sep 17 00:00:00 2001 From: Benoit Lacelle Date: Wed, 8 Feb 2023 23:44:50 +0400 Subject: [PATCH 47/59] Improve Gradle integration --- .../spotless/java/CleanthatJavaStep.java | 6 ++--- plugin-gradle/CHANGES.md | 2 ++ plugin-gradle/README.md | 22 ++++++++++++++++++- .../gradle/spotless/JavaExtension.java | 8 +++---- plugin-maven/CHANGES.md | 2 +- .../spotless/maven/java/CleanthatJava.java | 2 +- 6 files changed, 32 insertions(+), 10 deletions(-) diff --git a/lib/src/main/java/com/diffplug/spotless/java/CleanthatJavaStep.java b/lib/src/main/java/com/diffplug/spotless/java/CleanthatJavaStep.java index 1cd032a304..b5cc5452d1 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/CleanthatJavaStep.java +++ b/lib/src/main/java/com/diffplug/spotless/java/CleanthatJavaStep.java @@ -52,10 +52,10 @@ public static FormatterStep create(Provisioner provisioner) { /** Creates a step which apply default CleanThat mutators. */ public static FormatterStep create(String version, Provisioner provisioner) { - return create(MAVEN_COORDINATE, version, defaultJdkVersion(), defaultExcludedMutators(), defaultMutators(), provisioner); + return create(MAVEN_COORDINATE, version, defaultSourceJdk(), defaultExcludedMutators(), defaultMutators(), provisioner); } - public static String defaultJdkVersion() { + public static String defaultSourceJdk() { // see IJdkVersionConstants.JDK_7 // https://maven.apache.org/plugins/maven-compiler-plugin/compile-mojo.html#source // 1.7 is the default for 'maven-compiler-plugin' since 3.9.0 @@ -114,7 +114,7 @@ static final class JavaRefactorerState implements Serializable { final List excluded; JavaRefactorerState(String stepName, String version, Provisioner provisioner) throws IOException { - this(stepName, MAVEN_COORDINATE, version, defaultJdkVersion(), defaultExcludedMutators(), defaultMutators(), provisioner); + this(stepName, MAVEN_COORDINATE, version, defaultSourceJdk(), defaultExcludedMutators(), defaultMutators(), provisioner); } JavaRefactorerState(String stepName, diff --git a/plugin-gradle/CHANGES.md b/plugin-gradle/CHANGES.md index e3234584b8..1a5458c436 100644 --- a/plugin-gradle/CHANGES.md +++ b/plugin-gradle/CHANGES.md @@ -3,6 +3,8 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format (starting after version `3.27.0`). ## [Unreleased] +### Added +* CleanThat Java Refactorer ([#1560](https://github.com/diffplug/spotless/pull/1560)) ## [6.14.1] - 2023-02-05 ### Fixed diff --git a/plugin-gradle/README.md b/plugin-gradle/README.md index f61280bc7e..c0f8adebfb 100644 --- a/plugin-gradle/README.md +++ b/plugin-gradle/README.md @@ -54,7 +54,7 @@ Spotless supports all of Gradle's built-in performance features (incremental bui - [**Quickstart**](#quickstart) - [Requirements](#requirements) - **Languages** - - [Java](#java) ([google-java-format](#google-java-format), [eclipse jdt](#eclipse-jdt), [clang-format](#clang-format), [prettier](#prettier), [palantir-java-format](#palantir-java-format), [formatAnnotations](#formatAnnotations)) + - [Java](#java) ([google-java-format](#google-java-format), [eclipse jdt](#eclipse-jdt), [clang-format](#clang-format), [prettier](#prettier), [palantir-java-format](#palantir-java-format), [formatAnnotations](#formatAnnotations), [cleanthat](#cleanthat)) - [Groovy](#groovy) ([eclipse groovy](#eclipse-groovy)) - [Kotlin](#kotlin) ([ktfmt](#ktfmt), [ktlint](#ktlint), [diktat](#diktat), [prettier](#prettier)) - [Scala](#scala) ([scalafmt](#scalafmt)) @@ -154,6 +154,9 @@ spotless { removeUnusedImports() + // Cleanthat will refactor your code, but it may break your style: apply it before your formatter + cleanthat() // has its own section below + // Choose one of these formatters. googleJavaFormat() // has its own section below eclipse() // has its own section below @@ -257,6 +260,23 @@ You can use `addTypeAnnotation()` and `removeTypeAnnotation()` to override its d You can make a pull request to add new annotations to Spotless's default list. +### cleanthat + +[homepage](https://github.com/solven-eu/cleanthat). CleanThat enables automatic refactoring of Java code. [ChangeLog](https://github.com/solven-eu/cleanthat/blob/master/CHANGES.MD) + +```gradle +spotless { + java { + cleanthat() + // optional: you can specify a specific version and/or config file + cleanthat() + .groupArtifact('1.7') // default is 'io.github.solven-eu.cleanthat:java' + .version('2.1') // You may force a past of -SNAPSHOT + .sourceCompatibility('1.7') // default is '1.7' + .addMutator('your.custom.MagicMutator') + .excludeMutator('UseCollectionIsEmpty') +``` + diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavaExtension.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavaExtension.java index e65d0601e7..6e9f6de005 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavaExtension.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavaExtension.java @@ -281,7 +281,7 @@ public class CleanthatJavaConfig { private String version = CleanthatJavaStep.defaultVersion(); - private String sourceJdk = CleanthatJavaStep.defaultJdkVersion(); + private String sourceJdk = CleanthatJavaStep.defaultSourceJdk(); private List mutators = CleanthatJavaStep.defaultMutators(); @@ -305,9 +305,9 @@ public CleanthatJavaConfig version(String version) { return this; } - public CleanthatJavaConfig sourceJdk(String sourceJdk) { - Objects.requireNonNull(sourceJdk); - this.sourceJdk = sourceJdk; + public CleanthatJavaConfig sourceCompatibility(String jdkVersion) { + Objects.requireNonNull(jdkVersion); + this.sourceJdk = jdkVersion; replaceStep(createStep()); return this; } diff --git a/plugin-maven/CHANGES.md b/plugin-maven/CHANGES.md index fc276f7c8d..a13353e68e 100644 --- a/plugin-maven/CHANGES.md +++ b/plugin-maven/CHANGES.md @@ -4,7 +4,7 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format ( ## [Unreleased] ### Added -* CleanThat Java Refactorer ([#???](https://github.com/diffplug/spotless/pull/???)) +* CleanThat Java Refactorer ([#1560](https://github.com/diffplug/spotless/pull/1560)) ## [2.32.0] - 2023-02-05 ### Added diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/CleanthatJava.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/CleanthatJava.java index 7460ab67b9..d7dd1f2530 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/CleanthatJava.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/CleanthatJava.java @@ -33,7 +33,7 @@ public class CleanthatJava implements FormatterStepFactory { // https://maven.apache.org/plugins/maven-compiler-plugin/compile-mojo.html#source @Parameter(property = "maven.compiler.source") - private String sourceJdk = CleanthatJavaStep.defaultJdkVersion(); + private String sourceJdk = CleanthatJavaStep.defaultSourceJdk(); @Parameter private List mutators = CleanthatJavaStep.defaultMutators(); From 374acb6fec5484f92a1119e05e3a80e9f92a1bc0 Mon Sep 17 00:00:00 2001 From: Benoit Lacelle Date: Thu, 9 Feb 2023 00:01:28 +0400 Subject: [PATCH 48/59] Fix unitTests --- README.md | 2 +- lib/build.gradle | 9 ++- .../java/JavaCleanthatRefactorerFuncTest.java | 72 ------------------- .../glue/java/JavaCleanthatRefactorerFuncTest | 28 ++++++++ .../CleanthatJavaIntegrationTest.java | 2 +- 5 files changed, 37 insertions(+), 76 deletions(-) delete mode 100644 lib/src/testCleanthat/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFuncTest.java create mode 100644 lib/src/testCompatCleanthat2Dot1/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFuncTest diff --git a/README.md b/README.md index 5f59368677..420c13ab53 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,7 @@ lib('java.PalantirJavaFormatStep') +'{{yes}} | {{yes}} lib('java.RemoveUnusedImportsStep') +'{{yes}} | {{yes}} | {{yes}} | {{no}} |', extra('java.EclipseJdtFormatterStep') +'{{yes}} | {{yes}} | {{yes}} | {{no}} |', lib('java.FormatAnnotationsStep') +'{{yes}} | {{yes}} | {{no}} | {{no}} |', -lib('java.CleanthatJavaStep') +'{{no}} | {{yes}} | {{no}} | {{no}} |', +lib('java.CleanthatJavaStep') +'{{yes}} | {{yes}} | {{no}} | {{no}} |', lib('json.gson.GsonStep') +'{{yes}} | {{yes}} | {{no}} | {{no}} |', lib('json.JacksonJsonStep') +'{{yes}} | {{yes}} | {{no}} | {{no}} |', lib('json.JsonSimpleStep') +'{{yes}} | {{yes}} | {{no}} | {{no}} |', diff --git a/lib/build.gradle b/lib/build.gradle index cd6996a979..154b2acd6a 100644 --- a/lib/build.gradle +++ b/lib/build.gradle @@ -40,6 +40,12 @@ versionCompatibility { ] targetSourceSetName = 'ktlint' } + namespaces.register('Cleanthat') { + versions = [ + '2.1', + ] + targetSourceSetName = 'cleanthat' + } } } @@ -103,9 +109,8 @@ dependencies { gsonCompileOnly 'com.google.code.gson:gson:2.10.1' - // TODO How can one add a test module like 'compatKtLint0Dot48Dot0'? - // cleanthatCompileAndTestOnly 'io.github.solven-eu.cleanthat:java:2.1' cleanthatCompileOnly 'io.github.solven-eu.cleanthat:java:2.1' + compatCleanthat2Dot1CompileAndTestOnly 'io.github.solven-eu.cleanthat:java:2.1' } // we'll hold the core lib to a high standard diff --git a/lib/src/testCleanthat/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFuncTest.java b/lib/src/testCleanthat/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFuncTest.java deleted file mode 100644 index c811b51233..0000000000 --- a/lib/src/testCleanthat/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFuncTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 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.glue.ktlint.compat; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.HashMap; -import java.util.Map; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -public class KtLintCompat0Dot48Dot0AdapterTest { - @Test - public void testDefaults(@TempDir Path path) throws IOException { - KtLintCompat0Dot48Dot0Adapter ktLintCompat0Dot48Dot0Adapter = new KtLintCompat0Dot48Dot0Adapter(); - String text = loadAndWriteText(path, "empty_class_body.kt"); - final Path filePath = Paths.get(path.toString(), "empty_class_body.kt"); - - Map userData = new HashMap<>(); - - Map editorConfigOverrideMap = new HashMap<>(); - - String formatted = ktLintCompat0Dot48Dot0Adapter.format(text, filePath, false, false, null, userData, editorConfigOverrideMap); - assertEquals("class empty_class_body\n", formatted); - } - - @Test - public void testEditorConfigCanDisable(@TempDir Path path) throws IOException { - KtLintCompat0Dot48Dot0Adapter ktLintCompat0Dot48Dot0Adapter = new KtLintCompat0Dot48Dot0Adapter(); - String text = loadAndWriteText(path, "fails_no_semicolons.kt"); - final Path filePath = Paths.get(path.toString(), "fails_no_semicolons.kt"); - - Map userData = new HashMap<>(); - - Map editorConfigOverrideMap = new HashMap<>(); - editorConfigOverrideMap.put("indent_style", "tab"); - editorConfigOverrideMap.put("ktlint_standard_no-semi", "disabled"); - // ktlint_filename is an invalid rule in ktlint 0.48.0 - editorConfigOverrideMap.put("ktlint_filename", "disabled"); - - String formatted = ktLintCompat0Dot48Dot0Adapter.format(text, filePath, false, false, null, userData, editorConfigOverrideMap); - assertEquals("class fails_no_semicolons {\n\tval i = 0;\n}\n", formatted); - } - - private static String loadAndWriteText(Path path, String name) throws IOException { - try (InputStream is = KtLintCompat0Dot48Dot0AdapterTest.class.getResourceAsStream("/" + name)) { - Files.copy(is, path.resolve(name)); - } - return new String(Files.readAllBytes(path.resolve(name)), StandardCharsets.UTF_8); - } - -} diff --git a/lib/src/testCompatCleanthat2Dot1/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFuncTest b/lib/src/testCompatCleanthat2Dot1/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFuncTest new file mode 100644 index 0000000000..2f3cdc9646 --- /dev/null +++ b/lib/src/testCompatCleanthat2Dot1/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFuncTest @@ -0,0 +1,28 @@ +/* + * Copyright 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.glue.java; + +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.Test; + +import eu.solven.cleanthat.engine.java.refactorer.JavaRefactorer; + +public class JavaCleanthatRefactorerFuncTest { + @Test + public void testMutatorsDetection() { + Assertions.assertThat(JavaRefactorer.getAllIncluded()).isNotEmpty(); + } +} diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/CleanthatJavaIntegrationTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/CleanthatJavaIntegrationTest.java index 2b3ede1472..a754b963f2 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/CleanthatJavaIntegrationTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/CleanthatJavaIntegrationTest.java @@ -31,7 +31,7 @@ void integration() throws IOException { "spotless {", " java {", " target file('test.java')", - " cleanthat().sourceJdk('11')", + " cleanthat().sourceCompatibility('11')", " }", "}"); From 8fbbb7165a840fb8d5435266617a342e8fd21846 Mon Sep 17 00:00:00 2001 From: Benoit Lacelle Date: Thu, 9 Feb 2023 00:02:25 +0400 Subject: [PATCH 49/59] Remove useless dependency --- lib/build.gradle | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/build.gradle b/lib/build.gradle index 154b2acd6a..21181cd54b 100644 --- a/lib/build.gradle +++ b/lib/build.gradle @@ -61,7 +61,6 @@ dependencies { testCommonImplementation "org.junit.jupiter:junit-jupiter:$VER_JUNIT" testCommonImplementation "org.assertj:assertj-core:$VER_ASSERTJ" testCommonImplementation "com.diffplug.durian:durian-testlib:$VER_DURIAN" - testCommonImplementation 'io.github.solven-eu.cleanthat:java:2.1' // used for pom sorting sortPomCompileOnly 'com.github.ekryd.sortpom:sortpom-sorter:3.0.0' From 640a1c20426f1f5ef114a8b15176bf618d6b4d0d Mon Sep 17 00:00:00 2001 From: Benoit Lacelle Date: Thu, 9 Feb 2023 00:08:01 +0400 Subject: [PATCH 50/59] Remove irrelevant test file --- README.md | 2 +- .../java/JavaCleanthatRefactorerFuncTest.java | 28 ------------------- 2 files changed, 1 insertion(+), 29 deletions(-) delete mode 100644 lib/src/test/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFuncTest.java diff --git a/README.md b/README.md index 420c13ab53..662c624bdf 100644 --- a/README.md +++ b/README.md @@ -132,7 +132,7 @@ lib('yaml.JacksonYamlStep') +'{{yes}} | {{yes}} | [`java.RemoveUnusedImportsStep`](lib/src/main/java/com/diffplug/spotless/java/RemoveUnusedImportsStep.java) | :+1: | :+1: | :+1: | :white_large_square: | | [`java.EclipseJdtFormatterStep`](lib-extra/src/main/java/com/diffplug/spotless/extra/java/EclipseJdtFormatterStep.java) | :+1: | :+1: | :+1: | :white_large_square: | | [`java.FormatAnnotationsStep`](lib/src/main/java/com/diffplug/spotless/java/FormatAnnotationsStep.java) | :+1: | :+1: | :white_large_square: | :white_large_square: | -| [`java.CleanthatJavaStep`](lib/src/main/java/com/diffplug/spotless/java/CleanthatJavaStep.java) | :white_large_square: | :+1: | :white_large_square: | :white_large_square: | +| [`java.CleanthatJavaStep`](lib/src/main/java/com/diffplug/spotless/java/CleanthatJavaStep.java) | :+1: | :+1: | :white_large_square: | :white_large_square: | | [`json.gson.GsonStep`](lib/src/main/java/com/diffplug/spotless/json/gson/GsonStep.java) | :+1: | :+1: | :white_large_square: | :white_large_square: | | [`json.JacksonJsonStep`](lib/src/main/java/com/diffplug/spotless/json/JacksonJsonStep.java) | :+1: | :+1: | :white_large_square: | :white_large_square: | | [`json.JsonSimpleStep`](lib/src/main/java/com/diffplug/spotless/json/JsonSimpleStep.java) | :+1: | :+1: | :white_large_square: | :white_large_square: | diff --git a/lib/src/test/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFuncTest.java b/lib/src/test/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFuncTest.java deleted file mode 100644 index 2f3cdc9646..0000000000 --- a/lib/src/test/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFuncTest.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright 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.glue.java; - -import org.assertj.core.api.Assertions; -import org.junit.jupiter.api.Test; - -import eu.solven.cleanthat.engine.java.refactorer.JavaRefactorer; - -public class JavaCleanthatRefactorerFuncTest { - @Test - public void testMutatorsDetection() { - Assertions.assertThat(JavaRefactorer.getAllIncluded()).isNotEmpty(); - } -} From fdee03ce774ceff7ef92b3d4db680b0e361ed0fd Mon Sep 17 00:00:00 2001 From: Benoit Lacelle Date: Thu, 9 Feb 2023 00:25:00 +0400 Subject: [PATCH 51/59] Fix extention of unitTest --- ...RefactorerFuncTest => JavaCleanthatRefactorerFuncTest.java} | 0 plugin-maven/README.md | 3 ++- 2 files changed, 2 insertions(+), 1 deletion(-) rename lib/src/testCompatCleanthat2Dot1/java/com/diffplug/spotless/glue/java/{JavaCleanthatRefactorerFuncTest => JavaCleanthatRefactorerFuncTest.java} (100%) diff --git a/lib/src/testCompatCleanthat2Dot1/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFuncTest b/lib/src/testCompatCleanthat2Dot1/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFuncTest.java similarity index 100% rename from lib/src/testCompatCleanthat2Dot1/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFuncTest rename to lib/src/testCompatCleanthat2Dot1/java/com/diffplug/spotless/glue/java/JavaCleanthatRefactorerFuncTest.java diff --git a/plugin-maven/README.md b/plugin-maven/README.md index b1b9098bfe..f59a1d9004 100644 --- a/plugin-maven/README.md +++ b/plugin-maven/README.md @@ -182,6 +182,7 @@ any other maven phase (i.e. compile) then it can be configured as below; src/test/java/**/*.java + @@ -285,7 +286,7 @@ These mechanisms already exist for the Gradle plugin. 2.0 ${maven.compiler.source} - * + * LiteralsFirstInComparisons From ce086ba1382f618a2cb0b93c9f2fac02f19cfdb1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lars=20L=C3=B8nne?= Date: Wed, 8 Feb 2023 21:34:29 +0100 Subject: [PATCH 52/59] adds entry about continuation indent to the other changelogs --- CHANGES.md | 2 ++ plugin-gradle/CHANGES.md | 2 ++ 2 files changed, 4 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 5f1a1ffa9f..86a9eeabf2 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -10,6 +10,8 @@ This document is intended for Spotless developers. We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format (starting after version `1.27.0`). ## [Unreleased] +### Fixed +* Maven plugin with `ktfmt` default style uses correct continuation indent ([#1562](https://github.com/diffplug/spotless/pull/1562)) ## [2.34.1] - 2023-02-05 ### Changes diff --git a/plugin-gradle/CHANGES.md b/plugin-gradle/CHANGES.md index e3234584b8..9927b56f07 100644 --- a/plugin-gradle/CHANGES.md +++ b/plugin-gradle/CHANGES.md @@ -3,6 +3,8 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format (starting after version `3.27.0`). ## [Unreleased] +### Fixed +* Maven plugin with `ktfmt` default style uses correct continuation indent ([#1562](https://github.com/diffplug/spotless/pull/1562)) ## [6.14.1] - 2023-02-05 ### Fixed From 3e1ea286ca1d203e32f80b557e3fde54c91fa79a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lars=20L=C3=B8nne?= Date: Thu, 9 Feb 2023 12:33:03 +0100 Subject: [PATCH 53/59] updates copyright --- .../com/diffplug/spotless/glue/ktfmt/KtfmtFormatterFunc.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/src/ktfmt/java/com/diffplug/spotless/glue/ktfmt/KtfmtFormatterFunc.java b/lib/src/ktfmt/java/com/diffplug/spotless/glue/ktfmt/KtfmtFormatterFunc.java index e34f7b4755..80f4a42fcd 100644 --- a/lib/src/ktfmt/java/com/diffplug/spotless/glue/ktfmt/KtfmtFormatterFunc.java +++ b/lib/src/ktfmt/java/com/diffplug/spotless/glue/ktfmt/KtfmtFormatterFunc.java @@ -1,5 +1,5 @@ /* - * Copyright 2022 DiffPlug + * Copyright 2022-2023 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. From 1b990ab98d23561c4433bcab4175356903b2e5c2 Mon Sep 17 00:00:00 2001 From: Simon Gamma Date: Thu, 26 Jan 2023 16:35:21 +0100 Subject: [PATCH 54/59] 1162: adding tests verifying issue results in 'Couldn't resolve parser "php"' on gradle side and 'Couldn't resolve parser "java"' on maven side --- .../spotless/PrettierIntegrationTest.java | 42 +++++++++++++++ .../maven/MavenIntegrationHarness.java | 15 ++++-- .../prettier/PrettierFormatStepTest.java | 52 +++++++++++++++++++ 3 files changed, 105 insertions(+), 4 deletions(-) diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/PrettierIntegrationTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/PrettierIntegrationTest.java index 4c458e3ca7..8819d5bc07 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/PrettierIntegrationTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/PrettierIntegrationTest.java @@ -183,6 +183,48 @@ void usePhpCommunityPlugin() throws IOException { assertFile("php-example.php").sameAsResource("npm/prettier/plugins/php.clean"); } + /** + * This test is to ensure that we can have multiple prettier instances in one spotless config. + * + * @see Issue #1162 on github + */ + @Test + void usePhpAndJavaCommunityPlugin() throws IOException { + setFile("build.gradle").toLines( + "plugins {", + " id 'com.diffplug.spotless'", + "}", + "repositories { mavenCentral() }", + "def prettierConfigPhp = [:]", + "prettierConfigPhp['tabWidth'] = 3", + "prettierConfigPhp['parser'] = 'php'", + "def prettierPackagesPhp = [:]", + "prettierPackagesPhp['prettier'] = '2.0.5'", + "prettierPackagesPhp['@prettier/plugin-php'] = '0.14.2'", + "def prettierConfigJava = [:]", + "prettierConfigJava['tabWidth'] = 4", + "prettierConfigJava['parser'] = 'java'", + "def prettierPackagesJava = [:]", + "prettierPackagesJava['prettier'] = '2.0.5'", + "prettierPackagesJava['prettier-plugin-java'] = '0.8.0'", + "spotless {", + " format 'php', {", + " target 'php-example.php'", + " prettier(prettierPackagesPhp).config(prettierConfigPhp)", + " }", + " java {", + " target 'JavaTest.java'", + " prettier(prettierPackagesJava).config(prettierConfigJava)", + " }", + "}"); + setFile("php-example.php").toResource("npm/prettier/plugins/php.dirty"); + setFile("JavaTest.java").toResource("npm/prettier/plugins/java-test.dirty"); + final BuildResult spotlessApply = gradleRunner().withArguments("--stacktrace", "spotlessApply").build(); + Assertions.assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); + assertFile("php-example.php").sameAsResource("npm/prettier/plugins/php.clean"); + assertFile("JavaTest.java").sameAsResource("npm/prettier/plugins/java-test.clean"); + } + @Test void autodetectNpmrcFileConfig() throws IOException { setFile(".npmrc").toLines( diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenIntegrationHarness.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenIntegrationHarness.java index fdc4a745a1..2891ee3b2c 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenIntegrationHarness.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenIntegrationHarness.java @@ -285,7 +285,7 @@ private static String getSystemProperty(String name) { return value; } - private static String[] groupWithSteps(String group, String[] includes, String... steps) { + protected static String[] groupWithSteps(String group, String[] includes, String... steps) { String[] result = new String[steps.length + includes.length + 2]; result[0] = "<" + group + ">"; System.arraycopy(includes, 0, result, 1, includes.length); @@ -294,15 +294,22 @@ private static String[] groupWithSteps(String group, String[] includes, String.. return result; } - private static String[] groupWithSteps(String group, String... steps) { + protected static String[] groupWithSteps(String group, String... steps) { return groupWithSteps(group, new String[]{}, steps); } - private static String[] including(String... includes) { + protected static String[] including(String... includes) { return groupWithSteps("includes", groupWithSteps("include", includes)); } - private static String[] formats(String... formats) { + protected static String[] formats(String... formats) { return groupWithSteps("formats", formats); } + + protected static String[] formats(String[]... formats) { + String[] formatsArray = Arrays.stream(formats) + .flatMap(Arrays::stream) + .toArray(String[]::new); + return formats(formatsArray); + } } diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/prettier/PrettierFormatStepTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/prettier/PrettierFormatStepTest.java index 47dab5d152..78a0fc30ff 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/prettier/PrettierFormatStepTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/prettier/PrettierFormatStepTest.java @@ -106,6 +106,58 @@ void unique_dependency_config() throws Exception { assertThat(result.stdOutUtf8()).contains(Prettier.ERROR_MESSAGE_ONLY_ONE_CONFIG); } + /** + * This test is to ensure that we can have multiple prettier instances in one spotless config. + * + * @see Issue #1162 on github + */ + @Test + void multiple_prettier_configs() throws Exception { + writePom( + formats( + groupWithSteps("format", including("php-example.php"), + "", + " ", + " ", + " prettier", + " 2.0.5", + " ", + " ", + " @prettier/plugin-php", + " 0.14.2", + " ", + " ", + " ", + " 3", + " php", + " ", + ""), + groupWithSteps("java", including("JavaTest.java"), + "", + " ", + " ", + " prettier", + " 2.0.5", + " ", + " ", + " prettier-plugin-java", + " 0.8.0", + " ", + " ", + " ", + " 4", + " java", + " ", + ""))); + + setFile("php-example.php").toResource("npm/prettier/plugins/php.dirty"); + setFile("JavaTest.java").toResource("npm/prettier/plugins/java-test.dirty"); + mavenRunner().withArguments("spotless:apply").runNoError(); + assertFile("php-example.php").sameAsResource("npm/prettier/plugins/php.clean"); + assertFile("JavaTest.java").sameAsResource("npm/prettier/plugins/java-test.clean"); + + } + @Test void custom_plugin() throws Exception { writePomWithFormatSteps( From fdbbd024158911d65cb567b04340f875d45dd46b Mon Sep 17 00:00:00 2001 From: Simon Gamma Date: Fri, 27 Jan 2023 20:21:18 +0100 Subject: [PATCH 55/59] 1162: add unique suffix reflecting package.json content --- .../diffplug/spotless/npm/NodeServerLayout.java | 4 ++-- .../spotless/npm/NpmFormatterStepStateBase.java | 9 ++++++++- .../spotless/npm/NpmResourceHelper.java | 17 +++++++++++++++++ 3 files changed, 27 insertions(+), 3 deletions(-) diff --git a/lib/src/main/java/com/diffplug/spotless/npm/NodeServerLayout.java b/lib/src/main/java/com/diffplug/spotless/npm/NodeServerLayout.java index 63a6a923da..60c34bcc8c 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NodeServerLayout.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NodeServerLayout.java @@ -29,8 +29,8 @@ class NodeServerLayout { private final File serveJsFile; private final File npmrcFile; - NodeServerLayout(File buildDir, String stepName) { - this.nodeModulesDir = new File(buildDir, "spotless-node-modules-" + stepName); + NodeServerLayout(File buildDir, String stepName, String stepSuffix) { + this.nodeModulesDir = new File(buildDir, String.format("spotless-node-modules-%s-%s", stepName, stepSuffix)); this.packageJsonFile = new File(nodeModulesDir, "package.json"); this.serveJsFile = new File(nodeModulesDir, "serve.js"); this.npmrcFile = new File(nodeModulesDir, ".npmrc"); diff --git a/lib/src/main/java/com/diffplug/spotless/npm/NpmFormatterStepStateBase.java b/lib/src/main/java/com/diffplug/spotless/npm/NpmFormatterStepStateBase.java index 92ac7df6f2..412a827d9e 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NpmFormatterStepStateBase.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NpmFormatterStepStateBase.java @@ -56,7 +56,14 @@ protected NpmFormatterStepStateBase(String stepName, NpmConfig npmConfig, NpmFor this.stepName = requireNonNull(stepName); this.npmConfig = requireNonNull(npmConfig); this.locations = locations; - this.nodeServerLayout = new NodeServerLayout(locations.buildDir(), stepName); + String stateSuffix = stateSuffix(); + logger.info("Creating {} with name {} and state suffix {}", this.getClass().getSimpleName(), stepName, stateSuffix); + this.nodeServerLayout = new NodeServerLayout(locations.buildDir(), stepName, stateSuffix); + } + + protected String stateSuffix() { + String packageJsonContent = npmConfig.getPackageJsonContent(); + return NpmResourceHelper.md5(packageJsonContent); } protected void prepareNodeServerLayout() throws IOException { diff --git a/lib/src/main/java/com/diffplug/spotless/npm/NpmResourceHelper.java b/lib/src/main/java/com/diffplug/spotless/npm/NpmResourceHelper.java index 2acf3a180d..aa66c54fcf 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NpmResourceHelper.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NpmResourceHelper.java @@ -21,6 +21,7 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; +import java.security.MessageDigest; import java.time.Duration; import java.util.Arrays; import java.util.Objects; @@ -122,4 +123,20 @@ static File copyFileToDirAtSubpath(File file, File targetDir, String relativePat throw ThrowingEx.asRuntime(e); } } + + static String md5(File file) { + return md5(readUtf8StringFromFile(file)); + } + + static String md5(String fileContent) { + MessageDigest md = ThrowingEx.get(() -> MessageDigest.getInstance("MD5")); + md.update(fileContent.getBytes(StandardCharsets.UTF_8)); + byte[] digest = md.digest(); + // convert byte array digest to hex string + StringBuilder sb = new StringBuilder(); + for (byte b : digest) { + sb.append(String.format("%02x", b & 0xff)); + } + return sb.toString(); + } } From e0a290a2b784b073eb13bac62f77dff57b9cee11 Mon Sep 17 00:00:00 2001 From: Simon Gamma Date: Wed, 8 Feb 2023 21:09:13 +0100 Subject: [PATCH 56/59] 1162: separate node dirs per package.json --- .../spotless/npm/NodeServerLayout.java | 40 ++++++++++++++++--- .../npm/NpmFormatterStepStateBase.java | 18 ++++----- .../diffplug/spotless/npm/eslint-package.json | 2 +- .../spotless/npm/prettier-package.json | 2 +- .../diffplug/spotless/npm/tsfmt-package.json | 2 +- 5 files changed, 45 insertions(+), 19 deletions(-) diff --git a/lib/src/main/java/com/diffplug/spotless/npm/NodeServerLayout.java b/lib/src/main/java/com/diffplug/spotless/npm/NodeServerLayout.java index 60c34bcc8c..8b39c5e4ab 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NodeServerLayout.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NodeServerLayout.java @@ -18,25 +18,44 @@ import java.io.File; import java.nio.file.Files; import java.nio.file.Path; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import java.util.stream.Stream; import com.diffplug.spotless.ThrowingEx; class NodeServerLayout { + private static final Pattern PACKAGE_JSON_NAME_PATTERN = Pattern.compile("\"name\"\\s*:\\s*\"([^\"]+)\""); + private final File nodeModulesDir; private final File packageJsonFile; + + private final File packageLockJsonFile; + private final File serveJsFile; private final File npmrcFile; - NodeServerLayout(File buildDir, String stepName, String stepSuffix) { - this.nodeModulesDir = new File(buildDir, String.format("spotless-node-modules-%s-%s", stepName, stepSuffix)); + NodeServerLayout(File buildDir, String packageJsonContent) { + this.nodeModulesDir = new File(buildDir, nodeModulesDirName(packageJsonContent)); this.packageJsonFile = new File(nodeModulesDir, "package.json"); + this.packageLockJsonFile = new File(nodeModulesDir, "package-lock.json"); this.serveJsFile = new File(nodeModulesDir, "serve.js"); this.npmrcFile = new File(nodeModulesDir, ".npmrc"); } + private static String nodeModulesDirName(String packageJsonContent) { + String md5Hash = NpmResourceHelper.md5(packageJsonContent); + Matcher matcher = PACKAGE_JSON_NAME_PATTERN.matcher(packageJsonContent); + if (!matcher.find()) { + throw new IllegalArgumentException("package.json must contain a name property"); + } + String packageName = matcher.group(1); + return String.format("%s-node-modules-%s", packageName, md5Hash); + } + File nodeModulesDir() { + return nodeModulesDir; } @@ -52,10 +71,6 @@ public File npmrcFile() { return npmrcFile; } - static File getBuildDirFromNodeModulesDir(File nodeModulesDir) { - return nodeModulesDir.getParentFile(); - } - public boolean isLayoutPrepared() { if (!nodeModulesDir().isDirectory()) { return false; @@ -63,6 +78,9 @@ public boolean isLayoutPrepared() { if (!packageJsonFile().isFile()) { return false; } + if (!packageLockJsonFile.isFile()) { + return false; + } if (!serveJsFile().isFile()) { return false; } @@ -82,4 +100,14 @@ public boolean isNodeModulesPrepared() { } }); } + + @Override + public String toString() { + return String.format( + "NodeServerLayout[nodeModulesDir=%s, packageJsonFile=%s, serveJsFile=%s, npmrcFile=%s]", + this.nodeModulesDir, + this.packageJsonFile, + this.serveJsFile, + this.npmrcFile); + } } diff --git a/lib/src/main/java/com/diffplug/spotless/npm/NpmFormatterStepStateBase.java b/lib/src/main/java/com/diffplug/spotless/npm/NpmFormatterStepStateBase.java index 412a827d9e..f3f8a80fe8 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/NpmFormatterStepStateBase.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/NpmFormatterStepStateBase.java @@ -56,17 +56,13 @@ protected NpmFormatterStepStateBase(String stepName, NpmConfig npmConfig, NpmFor this.stepName = requireNonNull(stepName); this.npmConfig = requireNonNull(npmConfig); this.locations = locations; - String stateSuffix = stateSuffix(); - logger.info("Creating {} with name {} and state suffix {}", this.getClass().getSimpleName(), stepName, stateSuffix); - this.nodeServerLayout = new NodeServerLayout(locations.buildDir(), stepName, stateSuffix); - } - - protected String stateSuffix() { - String packageJsonContent = npmConfig.getPackageJsonContent(); - return NpmResourceHelper.md5(packageJsonContent); + this.nodeServerLayout = new NodeServerLayout(locations.buildDir(), npmConfig.getPackageJsonContent()); } protected void prepareNodeServerLayout() throws IOException { + final long started = System.currentTimeMillis(); + // maybe introduce trace logger? + logger.info("Preparing {} for npm step {}.", this.nodeServerLayout, getClass().getName()); NpmResourceHelper.assertDirectoryExists(nodeServerLayout.nodeModulesDir()); NpmResourceHelper.writeUtf8StringToFile(nodeServerLayout.packageJsonFile(), this.npmConfig.getPackageJsonContent()); @@ -77,12 +73,14 @@ protected void prepareNodeServerLayout() throws IOException { } else { NpmResourceHelper.deleteFileIfExists(nodeServerLayout.npmrcFile()); } + logger.info("Prepared {} for npm step {} in {} ms.", this.nodeServerLayout, getClass().getName(), System.currentTimeMillis() - started); } protected void prepareNodeServer() throws IOException { - FormattedPrinter.SYSOUT.print("running npm install"); + final long started = System.currentTimeMillis(); + logger.info("running npm install in {} for npm step {}", this.nodeServerLayout.nodeModulesDir(), getClass().getName()); runNpmInstall(nodeServerLayout.nodeModulesDir()); - FormattedPrinter.SYSOUT.print("npm install finished"); + logger.info("npm install finished in {} ms in {} for npm step {}", System.currentTimeMillis() - started, this.nodeServerLayout.nodeModulesDir(), getClass().getName()); } private void runNpmInstall(File npmProjectDir) throws IOException { diff --git a/lib/src/main/resources/com/diffplug/spotless/npm/eslint-package.json b/lib/src/main/resources/com/diffplug/spotless/npm/eslint-package.json index dcd91e729d..0d7ce930f7 100644 --- a/lib/src/main/resources/com/diffplug/spotless/npm/eslint-package.json +++ b/lib/src/main/resources/com/diffplug/spotless/npm/eslint-package.json @@ -1,5 +1,5 @@ { - "name": "spotless-eslint-formatter-step", + "name": "spotless-eslint", "version": "2.0.0", "description": "Spotless formatter step for running eslint as a rest service.", "repository": "https://github.com/diffplug/spotless", diff --git a/lib/src/main/resources/com/diffplug/spotless/npm/prettier-package.json b/lib/src/main/resources/com/diffplug/spotless/npm/prettier-package.json index 7bda08db8a..395a05da67 100644 --- a/lib/src/main/resources/com/diffplug/spotless/npm/prettier-package.json +++ b/lib/src/main/resources/com/diffplug/spotless/npm/prettier-package.json @@ -1,5 +1,5 @@ { - "name": "spotless-prettier-formatter-step", + "name": "spotless-prettier", "version": "2.0.0", "description": "Spotless formatter step for running prettier as a rest service.", "repository": "https://github.com/diffplug/spotless", diff --git a/lib/src/main/resources/com/diffplug/spotless/npm/tsfmt-package.json b/lib/src/main/resources/com/diffplug/spotless/npm/tsfmt-package.json index 7037bd2ec1..483dd0753d 100644 --- a/lib/src/main/resources/com/diffplug/spotless/npm/tsfmt-package.json +++ b/lib/src/main/resources/com/diffplug/spotless/npm/tsfmt-package.json @@ -1,5 +1,5 @@ { - "name": "spotless-tsfmt-formatter-step", + "name": "spotless-tsfmt", "version": "2.0.0", "description": "Spotless formatter step for running tsfmt as a rest service.", "repository": "https://github.com/diffplug/spotless", From 080f2378af86d3fa8e8db5be207a03415dc47fe8 Mon Sep 17 00:00:00 2001 From: Simon Gamma Date: Thu, 9 Feb 2023 20:44:38 +0100 Subject: [PATCH 57/59] 1162: use slf4j for logging --- .../com/diffplug/spotless/LazyArgLogger.java | 40 ++++++++++++++++++ .../spotless/npm/EslintFormatterStep.java | 9 ++-- .../spotless/npm/FormattedPrinter.java | 42 ------------------- .../spotless/npm/PrettierFormatterStep.java | 7 ++-- .../spotless/PrettierIntegrationTest.java | 4 +- 5 files changed, 52 insertions(+), 50 deletions(-) create mode 100644 lib/src/main/java/com/diffplug/spotless/LazyArgLogger.java delete mode 100644 lib/src/main/java/com/diffplug/spotless/npm/FormattedPrinter.java diff --git a/lib/src/main/java/com/diffplug/spotless/LazyArgLogger.java b/lib/src/main/java/com/diffplug/spotless/LazyArgLogger.java new file mode 100644 index 0000000000..e3456a2317 --- /dev/null +++ b/lib/src/main/java/com/diffplug/spotless/LazyArgLogger.java @@ -0,0 +1,40 @@ +/* + * Copyright 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; + +import java.util.function.Supplier; + +/** + * This is a utility class to allow for lazy evaluation of arguments to be passed to a logger + * and thus avoid unnecessary computation of the arguments if the log level is not enabled. + */ +public final class LazyArgLogger { + + private final Supplier argSupplier; + + private LazyArgLogger(Supplier argSupplier) { + this.argSupplier = argSupplier; + } + + public static LazyArgLogger lazy(Supplier argSupplier) { + return new LazyArgLogger(argSupplier); + } + + @Override + public String toString() { + return String.valueOf(argSupplier.get()); + } +} diff --git a/lib/src/main/java/com/diffplug/spotless/npm/EslintFormatterStep.java b/lib/src/main/java/com/diffplug/spotless/npm/EslintFormatterStep.java index 221a745ad7..b262bb4b98 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/EslintFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/EslintFormatterStep.java @@ -15,6 +15,7 @@ */ package com.diffplug.spotless.npm; +import static com.diffplug.spotless.LazyArgLogger.lazy; import static java.util.Objects.requireNonNull; import java.io.File; @@ -115,7 +116,7 @@ protected void prepareNodeServerLayout() throws IOException { // If any config files are provided, we need to make sure they are at the same location as the node modules // as eslint will try to resolve plugin/config names relatively to the config file location and some // eslint configs contain relative paths to additional config files (such as tsconfig.json e.g.) - FormattedPrinter.SYSOUT.print("Copying config file <%s> to <%s> and using the copy", origEslintConfig.getEslintConfigPath(), nodeServerLayout.nodeModulesDir()); + logger.info("Copying config file <{}> to <{}> and using the copy", origEslintConfig.getEslintConfigPath(), nodeServerLayout.nodeModulesDir()); File configFileCopy = NpmResourceHelper.copyFileToDir(origEslintConfig.getEslintConfigPath(), nodeServerLayout.nodeModulesDir()); this.eslintConfigInUse = this.origEslintConfig.withEslintConfigPath(configFileCopy).verify(); } @@ -125,7 +126,7 @@ protected void prepareNodeServerLayout() throws IOException { @Nonnull public FormatterFunc createFormatterFunc() { try { - FormattedPrinter.SYSOUT.print("creating formatter function (starting server)"); + logger.info("Creating formatter function (starting server)"); ServerProcessInfo eslintRestServer = npmRunServer(); EslintRestService restService = new EslintRestService(eslintRestServer.getBaseUrl()); return Closeable.ofDangerous(() -> endServer(restService, eslintRestServer), new EslintFilePathPassingFormatterFunc(locations.projectDir(), nodeServerLayout.nodeModulesDir(), eslintConfigInUse, restService)); @@ -135,7 +136,7 @@ public FormatterFunc createFormatterFunc() { } private void endServer(BaseNpmRestService restService, ServerProcessInfo restServer) throws Exception { - FormattedPrinter.SYSOUT.print("Closing formatting function (ending server)."); + logger.info("Closing formatting function (ending server)."); try { restService.shutdown(); } catch (Throwable t) { @@ -161,7 +162,7 @@ public EslintFilePathPassingFormatterFunc(File projectDir, File nodeModulesDir, @Override public String applyWithFile(String unix, File file) throws Exception { - FormattedPrinter.SYSOUT.print("formatting String '" + unix.substring(0, Math.min(50, unix.length())) + "[...]' in file '" + file + "'"); + logger.info("formatting String '{}[...]' in file '{}'", lazy(() -> unix.substring(0, Math.min(50, unix.length()))), file); Map eslintCallOptions = new HashMap<>(); setConfigToCallOptions(eslintCallOptions); diff --git a/lib/src/main/java/com/diffplug/spotless/npm/FormattedPrinter.java b/lib/src/main/java/com/diffplug/spotless/npm/FormattedPrinter.java deleted file mode 100644 index 97d5cdb4c6..0000000000 --- a/lib/src/main/java/com/diffplug/spotless/npm/FormattedPrinter.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2020 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.npm; - -import static java.util.Objects.requireNonNull; - -import java.io.PrintStream; -import java.time.LocalDateTime; - -enum FormattedPrinter { - SYSOUT(System.out); - - private static final boolean enabled = false; - - private final PrintStream printStream; - - FormattedPrinter(PrintStream printStream) { - this.printStream = requireNonNull(printStream); - } - - public void print(String msg, Object... paramsForStringFormat) { - if (!enabled) { - return; - } - String formatted = String.format(msg, paramsForStringFormat); - String prefixed = String.format("[%s] %s", LocalDateTime.now().toString(), formatted); - this.printStream.println(prefixed); - } -} diff --git a/lib/src/main/java/com/diffplug/spotless/npm/PrettierFormatterStep.java b/lib/src/main/java/com/diffplug/spotless/npm/PrettierFormatterStep.java index 22f1a69e7c..05c61f9bdf 100644 --- a/lib/src/main/java/com/diffplug/spotless/npm/PrettierFormatterStep.java +++ b/lib/src/main/java/com/diffplug/spotless/npm/PrettierFormatterStep.java @@ -15,6 +15,7 @@ */ package com.diffplug.spotless.npm; +import static com.diffplug.spotless.LazyArgLogger.lazy; import static java.util.Objects.requireNonNull; import java.io.File; @@ -86,7 +87,7 @@ private static class State extends NpmFormatterStepStateBase implements Serializ @Nonnull public FormatterFunc createFormatterFunc() { try { - FormattedPrinter.SYSOUT.print("creating formatter function (starting server)"); + logger.info("creating formatter function (starting server)"); ServerProcessInfo prettierRestServer = npmRunServer(); PrettierRestService restService = new PrettierRestService(prettierRestServer.getBaseUrl()); String prettierConfigOptions = restService.resolveConfig(this.prettierConfig.getPrettierConfigPath(), this.prettierConfig.getOptions()); @@ -97,7 +98,7 @@ public FormatterFunc createFormatterFunc() { } private void endServer(PrettierRestService restService, ServerProcessInfo restServer) throws Exception { - FormattedPrinter.SYSOUT.print("Closing formatting function (ending server)."); + logger.info("Closing formatting function (ending server)."); try { restService.shutdown(); } catch (Throwable t) { @@ -119,7 +120,7 @@ public PrettierFilePathPassingFormatterFunc(String prettierConfigOptions, Pretti @Override public String applyWithFile(String unix, File file) throws Exception { - FormattedPrinter.SYSOUT.print("formatting String '" + unix.substring(0, Math.min(50, unix.length())) + "[...]' in file '" + file + "'"); + logger.info("formatting String '{}[...]' in file '{}'", lazy(() -> unix.substring(0, Math.min(50, unix.length()))), file); final String prettierConfigOptionsWithFilepath = assertFilepathInConfigOptions(file); try { diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/PrettierIntegrationTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/PrettierIntegrationTest.java index 8819d5bc07..a6b2ea9dc8 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/PrettierIntegrationTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/PrettierIntegrationTest.java @@ -219,8 +219,10 @@ void usePhpAndJavaCommunityPlugin() throws IOException { "}"); setFile("php-example.php").toResource("npm/prettier/plugins/php.dirty"); setFile("JavaTest.java").toResource("npm/prettier/plugins/java-test.dirty"); - final BuildResult spotlessApply = gradleRunner().withArguments("--stacktrace", "spotlessApply").build(); + final BuildResult spotlessApply = gradleRunner().forwardOutput().withArguments("--stacktrace", "--info", "spotlessApply").build(); Assertions.assertThat(spotlessApply.getOutput()).contains("BUILD SUCCESSFUL"); + final BuildResult spotlessApply2 = gradleRunner().forwardOutput().withArguments("--stacktrace", "--info", "spotlessApply").build(); + Assertions.assertThat(spotlessApply2.getOutput()).contains("BUILD SUCCESSFUL"); assertFile("php-example.php").sameAsResource("npm/prettier/plugins/php.clean"); assertFile("JavaTest.java").sameAsResource("npm/prettier/plugins/java-test.clean"); } From 92eb869d8a50a86dacc416b0d49052ccd4137ec5 Mon Sep 17 00:00:00 2001 From: Simon Gamma Date: Thu, 9 Feb 2023 20:54:10 +0100 Subject: [PATCH 58/59] 1162: prepare changelog --- CHANGES.md | 5 ++++- plugin-gradle/CHANGES.md | 3 +++ plugin-maven/CHANGES.md | 3 +++ 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/CHANGES.md b/CHANGES.md index 5f1a1ffa9f..0e2e994a22 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -10,7 +10,10 @@ This document is intended for Spotless developers. We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format (starting after version `1.27.0`). ## [Unreleased] - +### Added +* Introduce `LazyArgLogger` to allow for lazy evaluation of log messages in slf4j logging. ([#1565](https://github.com/diffplug/spotless/pull/1565)) +### Fixed +* Allow multiple instances of the same npm-based formatter to be used by separating their `node_modules` directories. ([#1565](https://github.com/diffplug/spotless/pull/1565)) ## [2.34.1] - 2023-02-05 ### Changes * **POTENTIALLY BREAKING** Bump bytecode from Java 8 to 11 ([#1530](https://github.com/diffplug/spotless/pull/1530) part 2 of [#1337](https://github.com/diffplug/spotless/issues/1337)) diff --git a/plugin-gradle/CHANGES.md b/plugin-gradle/CHANGES.md index e3234584b8..ec5ae54c27 100644 --- a/plugin-gradle/CHANGES.md +++ b/plugin-gradle/CHANGES.md @@ -3,6 +3,9 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format (starting after version `3.27.0`). ## [Unreleased] +### Fixed +* Allow multiple instances of the same npm-based formatter to be used simultaneously. E.g. use prettier for typescript + *and* Java (using the community prettier-plugin-java) without messing up their respective `node_module` dependencies. ([#1565](https://github.com/diffplug/spotless/pull/1565)) ## [6.14.1] - 2023-02-05 ### Fixed diff --git a/plugin-maven/CHANGES.md b/plugin-maven/CHANGES.md index 567d880f4f..cce049488a 100644 --- a/plugin-maven/CHANGES.md +++ b/plugin-maven/CHANGES.md @@ -3,6 +3,9 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format (starting after version `1.27.0`). ## [Unreleased] +### Fixed +* Allow multiple instances of the same npm-based formatter to be used simultaneously. E.g. use prettier for typescript + *and* Java (using the community prettier-plugin-java) without messing up their respective `node_module` dependencies. ([#1565](https://github.com/diffplug/spotless/pull/1565)) ## [2.32.0] - 2023-02-05 ### Added From 4cb02f30d815992dc23ef9dc8f4e20bd9b9c3147 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lars=20L=C3=B8nne?= Date: Fri, 10 Feb 2023 12:59:00 +0100 Subject: [PATCH 59/59] runs spotlessApply and removes an unused import --- .../test/java/com/diffplug/spotless/maven/kotlin/KtfmtTest.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/kotlin/KtfmtTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/kotlin/KtfmtTest.java index 25ecbc598d..e452c5d56b 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/kotlin/KtfmtTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/kotlin/KtfmtTest.java @@ -19,8 +19,6 @@ import com.diffplug.spotless.maven.MavenIntegrationHarness; -import java.io.IOException; - class KtfmtTest extends MavenIntegrationHarness { @Test void testKtfmt() throws Exception {