-
Notifications
You must be signed in to change notification settings - Fork 459
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Implement buf format
Gradle step
#1208
Merged
Merged
Changes from all commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
7da4090
implement buf format gradle step
andrewparmet ef357fc
update changelogs
andrewparmet 4e56621
fix bad comment
andrewparmet 5b16ed1
allow specification of path to exe
andrewparmet 85759c8
fix table
andrewparmet 2ec3dce
typo
andrewparmet 8d25fd8
add tag to disable buf tests in CI
andrewparmet 78712ba
lint
andrewparmet 6ee9378
Merge branch 'main' into add-buf-format
nedtwigg 5c44a8e
add doc to pathToExe noting executable path trick
andrewparmet 580037d
add to readme as well
andrewparmet 3f7b1e8
tidy up diction
andrewparmet 24a913c
tabs
andrewparmet 0e3be7d
update link
andrewparmet 3c1bb4c
update link
andrewparmet 3d2d2b8
update default version
andrewparmet 57fc5c8
Merge branch 'main' into add-buf-format
nedtwigg 6e7556f
spotlessApply
nedtwigg 0943a81
Fix BufStepTest for the changes we've had in test infrastructure.
nedtwigg 0fc9036
Add warnings that buf must be the first step.
nedtwigg File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
99 changes: 99 additions & 0 deletions
99
lib/src/main/java/com/diffplug/spotless/protobuf/BufStep.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,99 @@ | ||
/* | ||
* 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.protobuf; | ||
|
||
import java.io.File; | ||
import java.io.IOException; | ||
import java.io.Serializable; | ||
import java.nio.charset.StandardCharsets; | ||
import java.util.Arrays; | ||
import java.util.List; | ||
import java.util.regex.Pattern; | ||
|
||
import javax.annotation.Nullable; | ||
|
||
import com.diffplug.spotless.ForeignExe; | ||
import com.diffplug.spotless.FormatterFunc; | ||
import com.diffplug.spotless.FormatterStep; | ||
import com.diffplug.spotless.ProcessRunner; | ||
|
||
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; | ||
|
||
public class BufStep { | ||
public static String name() { | ||
return "buf"; | ||
} | ||
|
||
public static String defaultVersion() { | ||
return "1.24.0"; | ||
} | ||
|
||
private final String version; | ||
private final @Nullable String pathToExe; | ||
|
||
private BufStep(String version, @Nullable String pathToExe) { | ||
this.version = version; | ||
this.pathToExe = pathToExe; | ||
} | ||
|
||
public static BufStep withVersion(String version) { | ||
return new BufStep(version, null); | ||
} | ||
|
||
public BufStep withPathToExe(String pathToExe) { | ||
return new BufStep(version, pathToExe); | ||
} | ||
|
||
public FormatterStep create() { | ||
return FormatterStep.createLazy(name(), this::createState, State::toFunc); | ||
} | ||
|
||
private State createState() throws IOException, InterruptedException { | ||
String instructions = "https://docs.buf.build/installation"; | ||
String exeAbsPath = ForeignExe.nameAndVersion("buf", version) | ||
.pathToExe(pathToExe) | ||
.versionRegex(Pattern.compile("(\\S*)")) | ||
.fixCantFind("Try following the instructions at " + instructions + ", or else tell Spotless where it is with {@code buf().pathToExe('path/to/executable')}") | ||
.confirmVersionAndGetAbsolutePath(); | ||
return new State(this, exeAbsPath); | ||
} | ||
|
||
@SuppressFBWarnings("SE_TRANSIENT_FIELD_NOT_RESTORED") | ||
static class State implements Serializable { | ||
private static final long serialVersionUID = -1825662356883926318L; | ||
// used for up-to-date checks and caching | ||
final String version; | ||
// used for executing | ||
final transient List<String> args; | ||
|
||
State(BufStep step, String exeAbsPath) { | ||
this.version = step.version; | ||
this.args = Arrays.asList(exeAbsPath, "format"); | ||
} | ||
|
||
String format(ProcessRunner runner, String input, File file) throws IOException, InterruptedException { | ||
String[] processArgs = args.toArray(new String[args.size() + 1]); | ||
// add an argument to the end | ||
processArgs[args.size()] = file.getAbsolutePath(); | ||
return runner.exec(input.getBytes(StandardCharsets.UTF_8), processArgs).assertExitZero(StandardCharsets.UTF_8); | ||
} | ||
|
||
FormatterFunc.Closeable toFunc() { | ||
ProcessRunner runner = new ProcessRunner(); | ||
return FormatterFunc.Closeable.of(runner, this::format); | ||
} | ||
} | ||
} |
20 changes: 20 additions & 0 deletions
20
lib/src/main/java/com/diffplug/spotless/protobuf/ProtobufConstants.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
/* | ||
* 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.protobuf; | ||
|
||
public class ProtobufConstants { | ||
public static final String LICENSE_HEADER_DELIMITER = "syntax"; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
109 changes: 109 additions & 0 deletions
109
plugin-gradle/src/main/java/com/diffplug/gradle/spotless/ProtobufExtension.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,109 @@ | ||
/* | ||
* 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 static com.diffplug.spotless.protobuf.ProtobufConstants.LICENSE_HEADER_DELIMITER; | ||
|
||
import java.util.Objects; | ||
|
||
import javax.inject.Inject; | ||
|
||
import com.diffplug.spotless.FormatterStep; | ||
import com.diffplug.spotless.protobuf.BufStep; | ||
|
||
public class ProtobufExtension extends FormatExtension implements HasBuiltinDelimiterForLicense { | ||
static final String NAME = "protobuf"; | ||
|
||
@Inject | ||
public ProtobufExtension(SpotlessExtension spotless) { | ||
super(spotless); | ||
} | ||
|
||
@Override | ||
public LicenseHeaderConfig licenseHeader(String licenseHeader) { | ||
return licenseHeader(licenseHeader, LICENSE_HEADER_DELIMITER); | ||
} | ||
|
||
@Override | ||
public LicenseHeaderConfig licenseHeaderFile(Object licenseHeaderFile) { | ||
return licenseHeaderFile(licenseHeaderFile, LICENSE_HEADER_DELIMITER); | ||
} | ||
|
||
/** If the user hasn't specified files, assume all protobuf files should be checked. */ | ||
@Override | ||
protected void setupTask(SpotlessTask task) { | ||
if (target == null) { | ||
target = parseTarget("**/*.proto"); | ||
} | ||
super.setupTask(task); | ||
} | ||
|
||
/** Adds the specified version of <a href="https://buf.build/">buf</a>. */ | ||
public BufFormatExtension buf(String version) { | ||
Objects.requireNonNull(version); | ||
return new BufFormatExtension(version); | ||
} | ||
|
||
public BufFormatExtension buf() { | ||
return buf(BufStep.defaultVersion()); | ||
} | ||
|
||
public class BufFormatExtension { | ||
BufStep step; | ||
|
||
BufFormatExtension(String version) { | ||
this.step = BufStep.withVersion(version); | ||
if (!steps.isEmpty()) { | ||
throw new IllegalArgumentException("buf() must be the first step, move other steps after it. Thumbs up [this issue](https://github.com/bufbuild/buf/issues/1035) for a resolution, see [here](https://github.com/diffplug/spotless/pull/1208#discussion_r1264439669) for more details on the problem."); | ||
} | ||
addStep(createStep()); | ||
} | ||
|
||
/** | ||
* When used in conjunction with the <a href=https://github.com/bufbuild/buf-gradle-plugin>{@code buf-gradle-plugin}</a>, | ||
* the {@code buf} executable can be resolved from its {@code bufTool} configuration: | ||
* | ||
* <pre> | ||
* {@code | ||
* spotless { | ||
* protobuf { | ||
* buf().pathToExe(configurations.getByName(BUF_BINARY_CONFIGURATION_NAME).getSingleFile().getAbsolutePath()) | ||
* } | ||
* } | ||
* } | ||
* </pre> | ||
* | ||
* Be sure to disable the {@code buf-gradle-plugin}'s execution of {@code buf format}: | ||
* | ||
* <pre> | ||
* {@code | ||
* buf { | ||
* enforceFormat = false | ||
* } | ||
* } | ||
* </pre> | ||
*/ | ||
public BufFormatExtension pathToExe(String pathToExe) { | ||
step = step.withPathToExe(pathToExe); | ||
replaceStep(createStep()); | ||
return this; | ||
} | ||
|
||
private FormatterStep createStep() { | ||
return step.create(); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
58 changes: 58 additions & 0 deletions
58
plugin-gradle/src/test/java/com/diffplug/gradle/spotless/BufIntegrationTest.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
/* | ||
* 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; | ||
|
||
import com.diffplug.spotless.tag.BufTest; | ||
|
||
@BufTest | ||
class BufIntegrationTest extends GradleIntegrationHarness { | ||
@Test | ||
void buf() throws IOException { | ||
setFile("build.gradle").toLines( | ||
"plugins {", | ||
" id 'com.diffplug.spotless'", | ||
"}", | ||
"spotless {", | ||
" protobuf {", | ||
" buf()", | ||
" }", | ||
"}"); | ||
setFile("buf.proto").toResource("protobuf/buf/buf.proto"); | ||
gradleRunner().withArguments("spotlessApply").build(); | ||
assertFile("buf.proto").sameAsResource("protobuf/buf/buf.proto.clean"); | ||
} | ||
|
||
@Test | ||
void bufWithLicense() throws IOException { | ||
setFile("build.gradle").toLines( | ||
"plugins {", | ||
" id 'com.diffplug.spotless'", | ||
"}", | ||
"spotless {", | ||
" protobuf {", | ||
" buf()", | ||
" licenseHeader '/* (C) 2022 */'", | ||
" }", | ||
"}"); | ||
setFile("license.proto").toResource("protobuf/buf/license.proto"); | ||
gradleRunner().withArguments("spotlessApply").build(); | ||
assertFile("license.proto").sameAsResource("protobuf/buf/license.proto.clean"); | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Bummer, we've got a problem. Your answer about the test needing the file to exist made me suspicious, so I did a little digging.
On this line you are passing the file's content on
stdin
asinput.getBytes(...)
but the buf command is ignoring that and just reading the file content from disk. That breaks Spotless' model - for example, any steps that get applied beforebuf()
will get wiped out, and our IDE integrations will also not work as expected.Looks like this is a known issue, and they plan to add the ability to read
buf
from stdin: bufbuild/buf#1035I'd like to delay merging this until
buf
adds this feature. If this delay would be a big hassle to your workflow, I'm okay merging this semi-broken feature in, with the promise that we'll stop supporting this version ofbuf
once they release a version which supportsstdin
.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Either is fine. I can use the buf-gradle-plugin in the meantime. Bummer to not be able to use
spotlessApply
for everything!There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Since the buf-gradle-plugin is already available and the buf team has accepted the feature request, I'll wait until it gets resolved rather than merge something half-broken.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It doesn't seem like the Buf team is going to be taking on stdin support anytime soon. What are your thoughts on merging this semi-broken feature? Would it cause problems for any common formatting use cases besides license headers?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Oh, and since I opened this PR the Buf team has begun publishing a Buf binary to Maven Central. Is there an existing pattern for locating a binary that way? The
buf-gradle-plugin
references it under the hood now, so it's also possible to let it be a transparent improvement here and leave the instructions here as they are.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm okay merging this as-is.
Main thing it breaks is idempotence. Most formatters have idempotency bugs, which Spotless quietly fixes, and that won't work here. It also means that things like
replace
,license
,tabsToSpaces
etc will only work if you put them after the buf step, they can't come before. Not great, but we can document it and point them to the buf issue to thumbs-up it.I assume the binary has to be extracted from the jar? We don't have any formatters like that currently. I'd be happy to merge that in, but even happier to leave that up to some other plugin and document that in our docs. Let me know when you're ready to merge and we'll let it rip :)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ok - letting
buf-gradle-plugin
handle that is probably best. I corrected the docs pointing to it (Buf in-housed it earlier this year) but the instructions are the same otherwise. Extracting from the jar would mean writing code to support specifying a Maven artifact as a source for a binary and I don't think I want to tackle that at the moment given that it can be added later and we're going to put this behind common configuration code anyways.I'm happy as this is! Should I take care of those doc notes? I checked the box to let you do it if you want to just do it quickly yourself.