Skip to content

Commit

Permalink
Merge branch 'main' into petertrr/add-gofmt#861
Browse files Browse the repository at this point in the history
  • Loading branch information
nedtwigg authored Jan 22, 2024
2 parents 9d71e6d + 13d9627 commit a145ac0
Show file tree
Hide file tree
Showing 15 changed files with 237 additions and 30 deletions.
2 changes: 1 addition & 1 deletion CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format (

## [Unreleased]
### Added
* Maven - Support for formatting shell scripts via [shfmt](https://github.com/mvdan/sh). ([#1998](https://github.com/diffplug/spotless/pull/1998))
* Support for `gofmt` ([#2001](https://github.com/diffplug/spotless/pull/2001))
* Support for formatting Java Docs for the Palantir formatter ([#2009](https://github.com/diffplug/spotless/pull/2009))

## [2.44.0] - 2024-01-15
### Added
Expand Down
11 changes: 11 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,17 @@ gradlew :plugin-maven:test --tests com.diffplug.spotless.maven.pom.SortPomMavenT
gradlew :plugin-gradle:test --tests com.diffplug.gradle.spotless.FreshMarkExtensionTest
```

## Check and format code

Before creating a pull request, you might want to format (yes, spotless is formatted by spotless)
the code and check for possible bugs

* `./gradlew spotlessApply`
* `./gradlew spotbugsMain`

These checks are also run by the automated pipeline when you submit a pull request, if
the pipeline fails, first check if the code is formatted and no bugs were found.

## Integration testing

### Gradle - locally
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ public class PalantirJavaFormatStep {
// prevent direct instantiation
private PalantirJavaFormatStep() {}

private static final boolean DEFAULT_FORMAT_JAVADOC = false;
private static final String DEFAULT_STYLE = "PALANTIR";
private static final String NAME = "palantir-java-format";
public static final String MAVEN_COORDINATE = "com.palantir.javaformat:palantir-java-format:";
Expand All @@ -42,14 +43,25 @@ public static FormatterStep create(String version, Provisioner provisioner) {
return create(version, defaultStyle(), provisioner);
}

/** Creates a step which formats everything - code, import order, and unused imports. And with the style input. */
/**
* Creates a step which formats code, import order, and unused imports, but not Java docs. And with the given format
* style.
*/
public static FormatterStep create(String version, String style, Provisioner provisioner) {
return create(version, style, DEFAULT_FORMAT_JAVADOC, provisioner);
}

/**
* Creates a step which formats everything - code, import order, unused imports, and Java docs. And with the given
* format style.
*/
public static FormatterStep create(String version, String style, boolean formatJavadoc, Provisioner provisioner) {
Objects.requireNonNull(version, "version");
Objects.requireNonNull(style, "style");
Objects.requireNonNull(provisioner, "provisioner");

return FormatterStep.createLazy(NAME,
() -> new State(JarState.from(MAVEN_COORDINATE + version, provisioner), version, style),
() -> new State(JarState.from(MAVEN_COORDINATE + version, provisioner), version, style, formatJavadoc),
State::createFormat);
}

Expand All @@ -63,6 +75,11 @@ public static String defaultStyle() {
return DEFAULT_STYLE;
}

/** Get default for whether Java docs should be formatted */
public static boolean defaultFormatJavadoc() {
return DEFAULT_FORMAT_JAVADOC;
}

private static final class State implements Serializable {
private static final long serialVersionUID = 1L;

Expand All @@ -71,23 +88,23 @@ private static final class State implements Serializable {
/** Version of the formatter jar. */
private final String formatterVersion;
private final String style;
/** Whether to format Java docs. */
private final boolean formatJavadoc;

State(JarState jarState, String formatterVersion) {
this(jarState, formatterVersion, DEFAULT_STYLE);
}

State(JarState jarState, String formatterVersion, String style) {
State(JarState jarState, String formatterVersion, String style, boolean formatJavadoc) {
ModuleHelper.doOpenInternalPackagesIfRequired();
this.jarState = jarState;
this.formatterVersion = formatterVersion;
this.style = style;
this.formatJavadoc = formatJavadoc;
}

FormatterFunc createFormat() throws Exception {
final ClassLoader classLoader = jarState.getClassLoader();
final Class<?> formatterFunc = classLoader.loadClass("com.diffplug.spotless.glue.pjf.PalantirJavaFormatFormatterFunc");
final Constructor<?> constructor = formatterFunc.getConstructor(String.class); // style
return JVM_SUPPORT.suggestLaterVersionOnError(formatterVersion, (FormatterFunc) constructor.newInstance(style));
// 1st arg is "style", 2nd arg is "formatJavadoc"
final Constructor<?> constructor = formatterFunc.getConstructor(String.class, boolean.class);
return JVM_SUPPORT.suggestLaterVersionOnError(formatterVersion, (FormatterFunc) constructor.newInstance(style, formatJavadoc));
}
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2022-2023 DiffPlug
* Copyright 2022-2024 DiffPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -15,6 +15,9 @@
*/
package com.diffplug.spotless.glue.pjf;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.palantir.javaformat.java.Formatter;
import com.palantir.javaformat.java.ImportOrderer;
import com.palantir.javaformat.java.JavaFormatterOptions;
Expand All @@ -28,11 +31,20 @@ public class PalantirJavaFormatFormatterFunc implements FormatterFunc {

private final JavaFormatterOptions.Style formatterStyle;

public PalantirJavaFormatFormatterFunc(String style) {
/**
* Creates a new formatter func that formats code via Palantir.
* @param style The style to use for formatting.
* @param formatJavadoc Whether to format Java docs. Requires at least Palantir 2.36.0 or later, otherwise the
* constructor will throw.
*/
public PalantirJavaFormatFormatterFunc(String style, boolean formatJavadoc) {
this.formatterStyle = JavaFormatterOptions.Style.valueOf(style);
formatter = Formatter.createFormatter(JavaFormatterOptions.builder()
.style(formatterStyle)
.build());
JavaFormatterOptions.Builder builder = JavaFormatterOptions.builder();
builder.style(formatterStyle);
if (formatJavadoc) {
applyFormatJavadoc(builder);
}
formatter = Formatter.createFormatter(builder.build());
}

@Override
Expand All @@ -47,4 +59,15 @@ public String apply(String input) throws Exception {
public String toString() {
return "PalantirJavaFormatFormatterFunc{formatter=" + formatter + '}';
}

private static void applyFormatJavadoc(JavaFormatterOptions.Builder builder) {
// The formatJavadoc option is available since Palantir 2.36.0
// To support older versions for now, attempt to invoke the builder method via reflection.
try {
Method formatJavadoc = JavaFormatterOptions.Builder.class.getMethod("formatJavadoc", boolean.class);
formatJavadoc.invoke(builder, true);
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
throw new IllegalStateException("Cannot enable formatJavadoc option, make sure you are using Palantir with version 2.36.0 or later", e);
}
}
}
3 changes: 3 additions & 0 deletions plugin-gradle/CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format (
## [Unreleased]
* Support for `gofmt` ([#2001](https://github.com/diffplug/spotless/pull/2001))

### Added
* Maven / Gradle - Support for formatting Java Docs for the Palantir formatter ([#2009](https://github.com/diffplug/spotless/pull/2009))

## [6.24.0] - 2024-01-15
### Added
* Support for shell formatting via [shfmt](https://github.com/mvdan/sh). ([#1994](https://github.com/diffplug/spotless/pull/1994))
Expand Down
24 changes: 22 additions & 2 deletions plugin-gradle/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,8 @@ spotless {
palantirJavaFormat()
// optional: you can specify a specific version and/or switch to AOSP/GOOGLE style
palantirJavaFormat('2.9.0').style("GOOGLE")
// optional: you can also format Javadocs, requires at least Palantir 2.39.0
palantirJavaFormat('2.39.0').formatJavadoc(true)
```

### eclipse jdt
Expand Down Expand Up @@ -1086,16 +1088,34 @@ To apply prettier to more kinds of files, just add more formats
Since spotless uses the actual npm prettier package behind the scenes, it is possible to use prettier with
[plugins](https://prettier.io/docs/en/plugins.html#official-plugins) or [community-plugins](https://www.npmjs.com/search?q=prettier-plugin) in order to support even more file types.
#### prettier version below 3
```gradle
spotless {
java {
prettier(['prettier': '2.8.8', 'prettier-plugin-java': '2.2.0']).config(['parser': 'java', 'tabWidth': 4])
// prettier(['prettier': '3.0.3', 'prettier-plugin-java': '2.3.0']).config(['parser': 'java', 'tabWidth': 4, 'plugins': ['prettier-plugin-java']]) // Prettier v3 requires additional 'plugins' config
}
format 'php', {
target 'src/**/*.php'
prettier(['prettier': '2.8.8', '@prettier/plugin-php': '0.19.6']).config(['parser': 'php', 'tabWidth': 3])
// prettier(['prettier': '3.0.3', '@prettier/plugin-php': '0.20.1']).config(['parser': 'php', 'tabWidth': 3, 'plugins': ['@prettier/plugin-php']]) // Prettier v3 requires additional 'plugins' config
}
}
```
#### prettier version 3+
With version 3 prettier it is required to pass in an additional 'plugins' parameter to the config block with a list of plugins you want to use.
```gradle
spotless {
java {
prettier(['prettier': '3.0.3', 'prettier-plugin-java': '2.3.0'])
.config(['parser': 'java', 'tabWidth': 4, 'plugins': ['prettier-plugin-java']])
}
format 'php', {
target 'src/**/*.php'
prettier(['prettier': '3.0.3', '@prettier/plugin-php': '0.20.1'])
.config(['parser': 'php', 'tabWidth': 3, 'plugins': ['@prettier/plugin-php']])
}
}
```
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2016-2023 DiffPlug
* Copyright 2016-2024 DiffPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -256,6 +256,7 @@ public PalantirJavaFormatConfig palantirJavaFormat(String version) {
public class PalantirJavaFormatConfig {
final String version;
String style;
boolean formatJavadoc;

PalantirJavaFormatConfig(String version) {
this.version = Objects.requireNonNull(version);
Expand All @@ -269,8 +270,14 @@ public PalantirJavaFormatConfig style(String style) {
return this;
}

public PalantirJavaFormatConfig formatJavadoc(boolean formatJavadoc) {
this.formatJavadoc = formatJavadoc;
replaceStep(createStep());
return this;
}

private FormatterStep createStep() {
return PalantirJavaFormatStep.create(version, style, provisioner());
return PalantirJavaFormatStep.create(version, style, formatJavadoc, provisioner());
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2022 DiffPlug
* Copyright 2022-2024 DiffPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -45,4 +45,26 @@ void integration() throws IOException {
"palantirJavaFormat('1.0.1')");
checkRunsThenUpToDate();
}

@Test
void formatJavaDoc() throws IOException {
setFile("build.gradle").toLines(
"plugins {",
" id 'com.diffplug.spotless'",
"}",
"repositories { mavenCentral() }",
"",
"spotless {",
" java {",
" target file('test.java')",
" palantirJavaFormat('2.39.0').formatJavadoc(true)",
" }",
"}");

setFile("test.java").toResource("java/palantirjavaformat/JavaCodeWithJavaDocUnformatted.test");
gradleRunner().withArguments("spotlessApply").build();
assertFile("test.java").sameAsResource("java/palantirjavaformat/JavaCodeWithJavaDocFormatted.test");

checkRunsThenUpToDate();
}
}
1 change: 1 addition & 0 deletions plugin-maven/CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format (
### Added
* Support for formatting shell scripts via [shfmt](https://github.com/mvdan/sh). ([#1998](https://github.com/diffplug/spotless/issues/1998))
* Support for `gofmt` ([#2001](https://github.com/diffplug/spotless/pull/2001))
* Support for formatting Java Docs for the Palantir formatter ([#2009](https://github.com/diffplug/spotless/pull/2009))

## [2.42.0] - 2024-01-15
### Added
Expand Down
3 changes: 2 additions & 1 deletion plugin-maven/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -247,8 +247,9 @@ any other maven phase (i.e. compile) then it can be configured as below;

```xml
<palantirJavaFormat>
<version>2.10.0</version> <!-- optional -->
<version>2.39.0</version> <!-- optional -->
<style>PALANTIR</style> <!-- or AOSP/GOOGLE (optional) -->
<formatJavadoc>false</formatJavadoc> <!-- defaults to false (optional, requires at least Palantir 2.39.0) -->
</palantirJavaFormat>
```

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2016-2023 DiffPlug
* Copyright 2016-2024 DiffPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -30,10 +30,14 @@ public class PalantirJavaFormat implements FormatterStepFactory {
@Parameter
private String style;

@Parameter
private Boolean formatJavadoc;

@Override
public FormatterStep newFormatterStep(FormatterStepConfig config) {
String version = this.version != null ? this.version : PalantirJavaFormatStep.defaultVersion();
String style = this.style != null ? this.style : PalantirJavaFormatStep.defaultStyle();
return PalantirJavaFormatStep.create(version, style, config.getProvisioner());
boolean formatJavadoc = this.formatJavadoc != null ? this.formatJavadoc : PalantirJavaFormatStep.defaultFormatJavadoc();
return PalantirJavaFormatStep.create(version, style, formatJavadoc, config.getProvisioner());
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2022-2023 DiffPlug
* Copyright 2022-2024 DiffPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -27,7 +27,7 @@ void specificVersionDefaultStyle() throws Exception {
" <version>1.1.0</version>",
"</palantirJavaFormat>");

runTest("java/palantirjavaformat/JavaCodeFormatted.test");
runTest("java/palantirjavaformat/JavaCodeFormatted.test", "java/palantirjavaformat/JavaCodeUnformatted.test");
}

@Test
Expand All @@ -37,12 +37,23 @@ void specificJava11Version2() throws Exception {
" <version>2.39.0</version>",
"</palantirJavaFormat>");

runTest("java/palantirjavaformat/JavaCodeFormatted.test");
runTest("java/palantirjavaformat/JavaCodeFormatted.test", "java/palantirjavaformat/JavaCodeUnformatted.test");
}

private void runTest(String targetResource) throws Exception {
@Test
void formatJavaDoc() throws Exception {
writePomWithJavaSteps(
"<palantirJavaFormat>",
" <version>2.39.0</version>",
" <formatJavadoc>true</formatJavadoc>",
"</palantirJavaFormat>");

runTest("java/palantirjavaformat/JavaCodeWithJavaDocFormatted.test", "java/palantirjavaformat/JavaCodeWithJavaDocUnformatted.test");
}

private void runTest(String targetResource, String sourceResource) throws Exception {
String path = "src/main/java/test.java";
setFile(path).toResource("java/palantirjavaformat/JavaCodeUnformatted.test");
setFile(path).toResource(sourceResource);
mavenRunner().withArguments("spotless:apply").runNoError();
assertFile(path).sameAsResource(targetResource);
}
Expand Down
Loading

0 comments on commit a145ac0

Please sign in to comment.