Skip to content

Commit 5aa7385

Browse files
authored
Merge pull request #672 from diffplug/feat/foreign
Make it easy to integrate native formatters
2 parents 6f1177f + 55d45e8 commit 5aa7385

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

42 files changed

+1259
-48
lines changed

CHANGES.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,12 @@ This document is intended for Spotless developers.
1010
We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format (starting after version `1.27.0`).
1111

1212
## [Unreleased]
13+
### Added
14+
* The ability to shell out to formatters with their own executables. ([#672](https://github.com/diffplug/spotless/pull/672))
15+
* `ProcessRunner` makes it easy to efficiently and debuggably call foreign executables, and pipe their stdout and stderr to strings.
16+
* `ForeignExe` finds executables on the path (or other strategies), and confirms that they have the correct version (to facilitate Spotless' caching). If the executable is not present or the wrong version, it points the user towards how to fix the problem.
17+
* These classes were used to add support for [python black](https://github.com/psf/black) and [clang-format](https://clang.llvm.org/docs/ClangFormat.html).
18+
* Incidental to this effort, `FormatterFunc.Closeable` now has new methods which make resource-handling safer. The old method is still available as `ofDangerous`, but it should not be used outside of a testing situation. There are some legacy usages of `ofDangerous` in the codebase, and it would be nice to fix them, but the existing usages are using it safely.
1319

1420
## [2.2.2] - 2020-08-21
1521
### Fixed

CONTRIBUTING.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,15 @@ Here's a checklist for creating a new step for Spotless:
104104

105105
In order for Spotless' model to work, each step needs to look only at the `String` input, otherwise they cannot compose. However, there are some cases where the source `File` is useful, such as to look at the file extension. In this case, you can pass a `FormatterFunc.NeedsFile` instead of a `FormatterFunc`. This should only be used in [rare circumstances](https://github.com/diffplug/spotless/pull/637), be careful that you don't accidentally depend on the bytes inside of the `File`!
106106

107+
### Integrating outside the JVM
108+
109+
There are many great formatters (prettier, clang-format, black, etc.) which live entirely outside the JVM. We have two main strategies for these:
110+
111+
- shell out to an external command for every file (used by clang-format and black) // TODO: link
112+
- open a headless server and make http calls to it from Spotless (used by prettier) // TODO: link
113+
114+
Because of Spotless' up-to-date checking and [git ratcheting](https://github.com/diffplug/spotless/tree/main/plugin-gradle#ratchet), Spotless actually doesn't have to call formatters very often, so even an expensive shell call for every single invocation isn't that bad. Anything that works is better than nothing, and we can always speed things up later if it feels too slow (but it probably won't).
115+
107116
## How to enable the _ext projects
108117

109118
The `_ext` projects are disabled per default, since:

README.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ output = [
1212
[![License Apache](https://img.shields.io/badge/license-apache-brightgreen.svg)](https://tldrlegal.com/license/apache-license-2.0-(apache-2.0))
1313
<!---freshmark /shields -->
1414

15-
Spotless can format &lt;java | kotlin | scala | sql | groovy | javascript | flow | typeScript | css | scss | less | jsx | vue | graphql | json | yaml | markdown | license headers | anything> using &lt;gradle | maven | anything>.
15+
Spotless can format &lt;antlr | c | c# | c++ | css | flow | graphql | groovy | html | java | javascript | json | jsx | kotlin | less | license headers | markdown | objective-c | protobuf | python | scala | scss | sql | typeScript | vue | yaml | anything> using &lt;gradle | maven | anything>.
1616

1717
- [Spotless for Gradle](plugin-gradle)
1818
- [VS Code extension](https://marketplace.visualstudio.com/items?itemName=richardwillis.vscode-spotless-gradle)
@@ -46,6 +46,7 @@ lib('generic.ReplaceRegexStep') +'{{yes}} | {{yes}}
4646
lib('generic.ReplaceStep') +'{{yes}} | {{yes}} | {{no}} |',
4747
lib('generic.TrimTrailingWhitespaceStep') +'{{yes}} | {{yes}} | {{no}} |',
4848
lib('antlr4.Antlr4FormatterStep') +'{{yes}} | {{yes}} | {{no}} |',
49+
lib('cpp.ClangFormatStep') +'{{yes}} | {{no}} | {{no}} |',
4950
extra('cpp.EclipseFormatterStep') +'{{yes}} | {{yes}} | {{no}} |',
5051
extra('groovy.GrEclipseFormatterStep') +'{{yes}} | {{no}} | {{no}} |',
5152
lib('java.GoogleJavaFormatStep') +'{{yes}} | {{yes}} | {{no}} |',
@@ -57,6 +58,7 @@ lib('kotlin.KtfmtStep') +'{{yes}} | {{yes}}
5758
lib('markdown.FreshMarkStep') +'{{yes}} | {{no}} | {{no}} |',
5859
lib('npm.PrettierFormatterStep') +'{{yes}} | {{yes}} | {{no}} |',
5960
lib('npm.TsFmtFormatterStep') +'{{yes}} | {{yes}} | {{no}} |',
61+
lib('python.BlackStep') +'{{yes}} | {{no}} | {{no}} |',
6062
lib('scala.ScalaFmtStep') +'{{yes}} | {{yes}} | {{no}} |',
6163
lib('sql.DBeaverSQLFormatterStep') +'{{yes}} | {{no}} | {{no}} |',
6264
extra('wtp.EclipseWtpFormatterStep') +'{{yes}} | {{yes}} | {{no}} |',
@@ -78,6 +80,7 @@ extra('wtp.EclipseWtpFormatterStep') +'{{yes}} | {{yes}}
7880
| [`generic.ReplaceStep`](lib/src/main/java/com/diffplug/spotless/generic/ReplaceStep.java) | :+1: | :+1: | :white_large_square: |
7981
| [`generic.TrimTrailingWhitespaceStep`](lib/src/main/java/com/diffplug/spotless/generic/TrimTrailingWhitespaceStep.java) | :+1: | :+1: | :white_large_square: |
8082
| [`antlr4.Antlr4FormatterStep`](lib/src/main/java/com/diffplug/spotless/antlr4/Antlr4FormatterStep.java) | :+1: | :+1: | :white_large_square: |
83+
| [`cpp.ClangFormatStep`](lib/src/main/java/com/diffplug/spotless/cpp/ClangFormatStep.java) | :+1: | :white_large_square: | :white_large_square: |
8184
| [`cpp.EclipseFormatterStep`](lib-extra/src/main/java/com/diffplug/spotless/extra/cpp/EclipseFormatterStep.java) | :+1: | :+1: | :white_large_square: |
8285
| [`groovy.GrEclipseFormatterStep`](lib-extra/src/main/java/com/diffplug/spotless/extra/groovy/GrEclipseFormatterStep.java) | :+1: | :white_large_square: | :white_large_square: |
8386
| [`java.GoogleJavaFormatStep`](lib/src/main/java/com/diffplug/spotless/java/GoogleJavaFormatStep.java) | :+1: | :+1: | :white_large_square: |
@@ -89,6 +92,7 @@ extra('wtp.EclipseWtpFormatterStep') +'{{yes}} | {{yes}}
8992
| [`markdown.FreshMarkStep`](lib/src/main/java/com/diffplug/spotless/markdown/FreshMarkStep.java) | :+1: | :white_large_square: | :white_large_square: |
9093
| [`npm.PrettierFormatterStep`](lib/src/main/java/com/diffplug/spotless/npm/PrettierFormatterStep.java) | :+1: | :+1: | :white_large_square: |
9194
| [`npm.TsFmtFormatterStep`](lib/src/main/java/com/diffplug/spotless/npm/TsFmtFormatterStep.java) | :+1: | :+1: | :white_large_square: |
95+
| [`python.BlackStep`](lib/src/main/java/com/diffplug/spotless/python/BlackStep.java) | :+1: | :white_large_square: | :white_large_square: |
9296
| [`scala.ScalaFmtStep`](lib/src/main/java/com/diffplug/spotless/scala/ScalaFmtStep.java) | :+1: | :+1: | :white_large_square: |
9397
| [`sql.DBeaverSQLFormatterStep`](lib/src/main/java/com/diffplug/spotless/sql/DBeaverSQLFormatterStep.java) | :+1: | :white_large_square: | :white_large_square: |
9498
| [`wtp.EclipseWtpFormatterStep`](lib-extra/src/main/java/com/diffplug/spotless/extra/wtp/EclipseWtpFormatterStep.java) | :+1: | :+1: | :white_large_square: |

gradle/special-tests.gradle

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
def special = [
2+
'Npm',
3+
'Black',
4+
'Clang'
5+
]
6+
7+
tasks.named('test') {
8+
useJUnit { excludeCategories special.collect { "com.diffplug.spotless.category.${it}Test" } as String[] }
9+
}
10+
11+
special.forEach {
12+
def category = "com.diffplug.spotless.category.${it}Test"
13+
tasks.register("${it}Test", Test) {
14+
useJUnit { includeCategories category }
15+
}
16+
}
Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
/*
2+
* Copyright 2020 DiffPlug
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package com.diffplug.spotless;
17+
18+
import java.io.IOException;
19+
import java.nio.charset.Charset;
20+
import java.util.Objects;
21+
import java.util.regex.Matcher;
22+
import java.util.regex.Pattern;
23+
24+
import javax.annotation.Nullable;
25+
26+
/**
27+
* Finds a foreign executable and checks its version.
28+
* If either part of that fails, it shows you why
29+
* and helps you fix it.
30+
*
31+
* Usage: `ForeignExe.nameAndVersion("grep", "2.5.7").confirmVersionAndGetAbsolutePath()`
32+
* will find grep, confirm that it is version 2.5.7, and then return.
33+
*/
34+
public class ForeignExe {
35+
private @Nullable String pathToExe;
36+
private String versionFlag = "--version";
37+
private Pattern versionRegex = Pattern.compile("version (\\S*)");
38+
private @Nullable String fixCantFind, fixWrongVersion;
39+
40+
// MANDATORY
41+
private String name;
42+
private String version;
43+
44+
/** The name of the executable, used by "where" (win) and "which" (unix). */
45+
public static ForeignExe nameAndVersion(String exeName, String version) {
46+
ForeignExe foreign = new ForeignExe();
47+
foreign.name = Objects.requireNonNull(exeName);
48+
foreign.version = Objects.requireNonNull(version);
49+
return foreign;
50+
}
51+
52+
/** The flag which causes the exe to print its version (defaults to --version). */
53+
public ForeignExe versionFlag(String versionFlag) {
54+
this.versionFlag = Objects.requireNonNull(versionFlag);
55+
return this;
56+
}
57+
58+
/** A regex which can parse the version out of the output of the {@link #versionFlag(String)} command (defaults to `version (\\S*)`) */
59+
public ForeignExe versionRegex(Pattern versionRegex) {
60+
this.versionRegex = Objects.requireNonNull(versionRegex);
61+
return this;
62+
}
63+
64+
/** Use {version} anywhere you would like to inject the actual version string. */
65+
public ForeignExe fixCantFind(String msg) {
66+
this.fixCantFind = msg;
67+
return this;
68+
}
69+
70+
/** Use {version} or {versionFound} anywhere you would like to inject the actual version strings. */
71+
public ForeignExe fixWrongVersion(String msg) {
72+
this.fixWrongVersion = msg;
73+
return this;
74+
}
75+
76+
/** Path to the executable. If null, will search for the executable on the system path. */
77+
public ForeignExe pathToExe(@Nullable String pathToExe) {
78+
this.pathToExe = pathToExe;
79+
return this;
80+
}
81+
82+
/**
83+
* Searches for the executable and confirms that it has the expected version.
84+
* If it can't find the executable, or if it doesn't have the correct version,
85+
* throws an exception with a message describing how to fix.
86+
*/
87+
public String confirmVersionAndGetAbsolutePath() throws IOException, InterruptedException {
88+
try (ProcessRunner runner = new ProcessRunner()) {
89+
String exeAbsPath;
90+
if (pathToExe != null) {
91+
exeAbsPath = pathToExe;
92+
} else {
93+
ProcessRunner.Result cmdWhich = runner.shellWinUnix("where " + name, "which " + name);
94+
if (cmdWhich.exitNotZero()) {
95+
throw cantFind("Unable to find " + name + " on path", cmdWhich);
96+
} else {
97+
exeAbsPath = cmdWhich.assertExitZero(Charset.defaultCharset()).trim();
98+
}
99+
}
100+
ProcessRunner.Result cmdVersion = runner.exec(exeAbsPath, versionFlag);
101+
if (cmdVersion.exitNotZero()) {
102+
throw cantFind("Unable to run " + exeAbsPath, cmdVersion);
103+
}
104+
Matcher versionMatcher = versionRegex.matcher(cmdVersion.assertExitZero(Charset.defaultCharset()));
105+
if (!versionMatcher.find()) {
106+
throw cantFind("Unable to parse version with /" + versionRegex + "/", cmdVersion);
107+
}
108+
String versionFound = versionMatcher.group(1);
109+
if (!versionFound.equals(version)) {
110+
throw wrongVersion("You specified version " + version + ", but Spotless found " + versionFound, cmdVersion, versionFound);
111+
}
112+
return exeAbsPath;
113+
}
114+
}
115+
116+
private RuntimeException cantFind(String message, ProcessRunner.Result cmd) {
117+
return exceptionFmt(message, cmd, fixCantFind == null ? null : fixCantFind.replace("{version}", version));
118+
}
119+
120+
private RuntimeException wrongVersion(String message, ProcessRunner.Result cmd, String versionFound) {
121+
return exceptionFmt(message, cmd, fixWrongVersion == null ? null : fixWrongVersion.replace("{version}", version).replace("{versionFound}", versionFound));
122+
}
123+
124+
private RuntimeException exceptionFmt(String msgPrimary, ProcessRunner.Result cmd, @Nullable String msgFix) {
125+
StringBuilder errorMsg = new StringBuilder();
126+
errorMsg.append(msgPrimary);
127+
errorMsg.append('\n');
128+
if (msgFix != null) {
129+
errorMsg.append(msgFix);
130+
errorMsg.append('\n');
131+
}
132+
errorMsg.append(cmd.toString());
133+
return new RuntimeException(errorMsg.toString());
134+
}
135+
}

lib/src/main/java/com/diffplug/spotless/FormatterFunc.java

Lines changed: 75 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,17 @@ interface Closeable extends FormatterFunc, AutoCloseable {
4040
@Override
4141
void close();
4242

43-
/** Creates a {@link Closeable} from an AutoCloseable and a function. */
44-
public static Closeable of(AutoCloseable closeable, FormatterFunc function) {
43+
/**
44+
* Dangerous way to create a {@link Closeable} from an AutoCloseable and a function.
45+
*
46+
* It's important for FormatterStep's to allocate their resources as lazily as possible.
47+
* It's easy to create a resource inside the state, and not realize that it may not be
48+
* released. It's far better to use one of the non-deprecated `of()` methods below.
49+
*
50+
* The bug (and its fix) which is easy to write using this method: https://github.com/diffplug/spotless/commit/7f16ecca031810b5e6e6f647e1f10a6d2152d9f4
51+
* How the `of()` methods below make the correct thing easier to write and safer: https://github.com/diffplug/spotless/commit/18c10f9c93d6f18f753233d0b5f028d5f0961916
52+
*/
53+
public static Closeable ofDangerous(AutoCloseable closeable, FormatterFunc function) {
4554
Objects.requireNonNull(closeable, "closeable");
4655
Objects.requireNonNull(function, "function");
4756
return new Closeable() {
@@ -52,12 +61,73 @@ public void close() {
5261

5362
@Override
5463
public String apply(String unix, File file) throws Exception {
55-
return function.apply(Objects.requireNonNull(unix), Objects.requireNonNull(file));
64+
return function.apply(unix, file);
65+
}
66+
67+
@Override
68+
public String apply(String unix) throws Exception {
69+
return function.apply(unix);
70+
}
71+
};
72+
}
73+
74+
/** @deprecated synonym for {@link #ofDangerous(AutoCloseable, FormatterFunc)} */
75+
@Deprecated
76+
public static Closeable of(AutoCloseable closeable, FormatterFunc function) {
77+
return ofDangerous(closeable, function);
78+
}
79+
80+
@FunctionalInterface
81+
interface ResourceFunc<T extends AutoCloseable> {
82+
String apply(T resource, String unix) throws Exception;
83+
}
84+
85+
/** Creates a {@link FormatterFunc.Closeable} which uses the given resource to execute the format function. */
86+
public static <T extends AutoCloseable> Closeable of(T resource, ResourceFunc<T> function) {
87+
Objects.requireNonNull(resource, "resource");
88+
Objects.requireNonNull(function, "function");
89+
return new Closeable() {
90+
@Override
91+
public void close() {
92+
ThrowingEx.run(resource::close);
93+
}
94+
95+
@Override
96+
public String apply(String unix, File file) throws Exception {
97+
return function.apply(resource, unix);
98+
}
99+
100+
@Override
101+
public String apply(String unix) throws Exception {
102+
return function.apply(resource, unix);
103+
}
104+
};
105+
}
106+
107+
@FunctionalInterface
108+
interface ResourceFuncNeedsFile<T extends AutoCloseable> {
109+
String apply(T resource, String unix, File file) throws Exception;
110+
}
111+
112+
/** Creates a {@link FormatterFunc.Closeable} which uses the given resource to execute the file-dependent format function. */
113+
public static <T extends AutoCloseable> Closeable of(T resource, ResourceFuncNeedsFile<T> function) {
114+
Objects.requireNonNull(resource, "resource");
115+
Objects.requireNonNull(function, "function");
116+
return new Closeable() {
117+
@Override
118+
public void close() {
119+
ThrowingEx.run(resource::close);
120+
}
121+
122+
@Override
123+
public String apply(String unix, File file) throws Exception {
124+
FormatterStepImpl.checkNotSentinel(file);
125+
return function.apply(resource, unix, file);
56126
}
57127

58128
@Override
59129
public String apply(String unix) throws Exception {
60-
return function.apply(Objects.requireNonNull(unix));
130+
return apply(unix, FormatterStepImpl.SENTINEL);
61131
}
62132
};
63133
}
@@ -80,9 +150,7 @@ interface NeedsFile extends FormatterFunc {
80150

81151
@Override
82152
default String apply(String unix, File file) throws Exception {
83-
if (file == FormatterStepImpl.SENTINEL) {
84-
throw new IllegalArgumentException("This step requires the underlying file. If this is a test, use StepHarnessWithFile");
85-
}
153+
FormatterStepImpl.checkNotSentinel(file);
86154
return applyWithFile(unix, file);
87155
}
88156

lib/src/main/java/com/diffplug/spotless/FormatterStepImpl.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,4 +114,10 @@ protected String format(Integer state, String rawUnix, File file) throws Excepti
114114

115115
/** A dummy SENTINEL file. */
116116
static final File SENTINEL = new File("");
117+
118+
static void checkNotSentinel(File file) {
119+
if (file == SENTINEL) {
120+
throw new IllegalArgumentException("This step requires the underlying file. If this is a test, use StepHarnessWithFile");
121+
}
122+
}
117123
}

0 commit comments

Comments
 (0)