Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

YAML implementation with Jackson #1478

Merged
merged 12 commits into from
Jan 12, 2023
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -121,3 +121,6 @@ nbdist/
nbactions.xml
nb-configuration.xml
.nb-gradle/

# MacOS jenv
.java-version
1 change: 1 addition & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format (
* Add option `editorConfigFile` for `ktLint` [#142](https://github.com/diffplug/spotless/issues/142)
* **POTENTIALLY BREAKING** `ktlint` step now modifies license headers. Make sure to put `licenseHeader` *after* `ktlint`.
* Added `skipLinesMatching` option to `licenseHeader` to support formats where license header cannot be immediately added to the top of the file (e.g. xml, sh). ([#1441](https://github.com/diffplug/spotless/pull/1441)).
* Add YAML support through Jackson ([#1478](https://github.com/diffplug/spotless/pull/1478))
### Fixed
* Support `ktlint` 0.48+ new rule disabling syntax ([#1456](https://github.com/diffplug/spotless/pull/1456)) fixes ([#1444](https://github.com/diffplug/spotless/issues/1444))
* Added support for npm-based [ESLint](https://eslint.org/)-formatter for javascript and typescript ([#1453](https://github.com/diffplug/spotless/pull/1453))
Expand Down
6 changes: 5 additions & 1 deletion lib/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ def NEEDS_GLUE = [
'ktlint',
'flexmark',
'diktat',
'scalafmt'
'scalafmt',
'jackson'
]
for (glue in NEEDS_GLUE) {
sourceSets.register(glue) {
Expand Down Expand Up @@ -55,6 +56,9 @@ dependencies {

palantirJavaFormatCompileOnly 'com.palantir.javaformat:palantir-java-format:1.1.0' // this version needs to stay compilable against Java 8 for CI Job testNpm

// used jackson-based formatters
jacksonCompileOnly 'com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.14.1'

String VER_KTFMT = '0.42'
ktfmtCompileOnly "com.facebook:ktfmt:$VER_KTFMT"
String VER_KTLINT_GOOGLE_JAVA_FORMAT = '1.7' // for JDK 8 compatibility
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
/*
* 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.
* 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.yaml;

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

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;

import com.diffplug.spotless.FormatterFunc;

public class YamlJacksonFormatterFunc implements FormatterFunc {
private List<String> enabledFeatures;
private List<String> disabledFeatures;

public YamlJacksonFormatterFunc(List<String> enabledFeatures, List<String> disabledFeatures) {
this.enabledFeatures = enabledFeatures;
this.disabledFeatures = disabledFeatures;
}

@Override
public String apply(String input) throws Exception {
ObjectMapper objectMapper = makeObjectMapper();

return format(objectMapper, input);
}

protected ObjectMapper makeObjectMapper() {
YAMLFactory yamlFactory = new YAMLFactory();
ObjectMapper objectMapper = new ObjectMapper(yamlFactory);

// Configure the ObjectMapper
// https://github.com/FasterXML/jackson-databind#commonly-used-features
for (String rawFeature : enabledFeatures) {
// https://stackoverflow.com/questions/3735927/java-instantiating-an-enum-using-reflection
SerializationFeature feature = SerializationFeature.valueOf(rawFeature);

objectMapper.enable(feature);
}

for (String rawFeature : disabledFeatures) {
// https://stackoverflow.com/questions/3735927/java-instantiating-an-enum-using-reflection
SerializationFeature feature = SerializationFeature.valueOf(rawFeature);

objectMapper.disable(feature);
}
return objectMapper;
}

protected String format(ObjectMapper objectMapper, String input) throws IllegalArgumentException, IOException {
// We may consider adding manually an initial '---' prefix to help management of multiple documents
nedtwigg marked this conversation as resolved.
Show resolved Hide resolved
// if (!input.trim().startsWith("---")) {
// input = "---" + "\n" + input;
// }

try {
// https://stackoverflow.com/questions/25222327/deserialize-pojos-from-multiple-yaml-documents-in-a-single-file-in-jackson
// https://github.com/FasterXML/jackson-dataformats-text/issues/66#issuecomment-375328648
// 2023-01: For now, we get 'Cannot deserialize value of type `com.fasterxml.jackson.databind.node.ObjectNode` from Array value'
// JsonParser yamlParser = objectMapper.getFactory().createParser(input);
// List<ObjectNode> docs = objectMapper.readValues(yamlParser, ObjectNode.class).readAll();
// return objectMapper.writeValueAsString(docs);

// 2023-01: This returns JSON instead of YAML
// This will transit with a JsonNode
// A JsonNode may keep the comments from the input node
// JsonNode jsonNode = objectMapper.readTree(input);
//Not 'toPrettyString' as one could require no INDENT_OUTPUT
// return jsonNode.toPrettyString();
ObjectNode objectNode = objectMapper.readValue(input, ObjectNode.class);
return objectMapper.writeValueAsString(objectNode);
} catch (JsonProcessingException e) {
throw new AssertionError("Unable to format YAML. input='" + input + "'", e);
}
}

// Spotbugs
private static class ObjectNodeTypeReference extends TypeReference<ObjectNode> {}
}
85 changes: 85 additions & 0 deletions lib/src/main/java/com/diffplug/spotless/yaml/YamlJacksonStep.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/*
* 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.
* 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.yaml;

import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import com.diffplug.spotless.FormatterFunc;
import com.diffplug.spotless.FormatterStep;
import com.diffplug.spotless.JarState;
import com.diffplug.spotless.Provisioner;

/**
* Simple YAML formatter which reformats the file according to Jackson YAMLFactory.
*/
// https://stackoverflow.com/questions/14515994/convert-json-string-to-pretty-print-json-output-using-jackson
public class YamlJacksonStep {
static final String MAVEN_COORDINATE = "com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:";
// https://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-yaml
static final String DEFAULT_VERSION = "2.14.1";

private YamlJacksonStep() {}

public static String defaultVersion() {
return DEFAULT_VERSION;
}

public static FormatterStep create(List<String> enabledFeatures,
List<String> disabledFeatures,
String jacksonVersion,
Provisioner provisioner) {
Objects.requireNonNull(provisioner, "provisioner cannot be null");
return FormatterStep.createLazy("yaml",
() -> new State(enabledFeatures, disabledFeatures, jacksonVersion, provisioner),
State::toFormatter);
}

public static FormatterStep create(Provisioner provisioner) {
return create(Arrays.asList("INDENT_OUTPUT"), Arrays.asList(), defaultVersion(), provisioner);
}

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

private final List<String> enabledFeatures;
private final List<String> disabledFeatures;

private final JarState jarState;

private State(List<String> enabledFeatures,
List<String> disabledFeatures,
String jacksonVersion,
Provisioner provisioner) throws IOException {
this.enabledFeatures = enabledFeatures;
this.disabledFeatures = disabledFeatures;

this.jarState = JarState.from(YamlJacksonStep.MAVEN_COORDINATE + jacksonVersion, provisioner);
}

FormatterFunc toFormatter() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException,
InstantiationException, IllegalAccessException {
Class<?> formatterFunc = jarState.getClassLoader().loadClass("com.diffplug.spotless.glue.yaml.YamlJacksonFormatterFunc");
Constructor<?> constructor = formatterFunc.getConstructor(List.class, List.class);
return (FormatterFunc) constructor.newInstance(enabledFeatures, disabledFeatures);
}
}
}
nedtwigg marked this conversation as resolved.
Show resolved Hide resolved
3 changes: 2 additions & 1 deletion plugin-maven/CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format (
## [Unreleased]
### Added
* Add option `editorConfigFile` for `ktLint` [#142](https://github.com/diffplug/spotless/issues/142)
* **POTENTIALLY BREAKING** `ktlint` step now modifies license headers. Make sure to put `licenseHeader` *after* `ktlint`.
* **POTENTIALLY BREAKING** `ktlint` step now modifies license headers. Make sure to put `licenseHeader` *after* `ktlint`.
* Added `skipLinesMatching` option to `licenseHeader` to support formats where license header cannot be immediately added to the top of the file (e.g. xml, sh). ([#1441](https://github.com/diffplug/spotless/pull/1441))
* Add JSON support ([#1446](https://github.com/diffplug/spotless/pull/1446))
* Add YAML support through Jackson ([#1478](https://github.com/diffplug/spotless/pull/1478))
### Fixed
* Support `ktlint` 0.48+ new rule disabling syntax ([#1456](https://github.com/diffplug/spotless/pull/1456)) fixes ([#1444](https://github.com/diffplug/spotless/issues/1444))
* Added support for npm-based [ESLint](https://eslint.org/)-formatter for javascript and typescript ([#1453](https://github.com/diffplug/spotless/pull/1453))
Expand Down
38 changes: 37 additions & 1 deletion plugin-maven/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ user@machine repo % mvn spotless:check
- [Typescript](#typescript) ([tsfmt](#tsfmt), [prettier](#prettier), [ESLint](#eslint-typescript))
- [Javascript](#javascript) ([prettier](#prettier), [ESLint](#eslint-javascript))
- [JSON](#json)
- [YAML](#yaml)
- Multiple languages
- [Prettier](#prettier) ([plugins](#prettier-plugins), [npm detection](#npm-detection), [`.npmrc` detection](#npmrc-detection))
- [eclipse web tools platform](#eclipse-web-tools-platform)
Expand Down Expand Up @@ -852,7 +853,7 @@ For details, see the [npm detection](#npm-detection) and [`.npmrc` detection](#n

## JSON

- `com.diffplug.spotless.maven.json.Json` [code](https://github.com/diffplug/spotless/blob/main/plugin-maven/src/main/java/com/diffplug/spotless/maven/json/json.java)
- `com.diffplug.spotless.maven.json.Json` [code](https://github.com/diffplug/spotless/blob/main/plugin-maven/src/main/java/com/diffplug/spotless/maven/json/Json.java)

```xml
<configuration>
Expand Down Expand Up @@ -899,6 +900,41 @@ for details.

<a name="applying-prettier-to-javascript--flow--typescript--css--scss--less--jsx--graphql--yaml--etc"></a>


## YAML

- `com.diffplug.spotless.maven.FormatterFactory.addStepFactory(FormatterStepFactory)` [code](https://github.com/diffplug/spotless/blob/main/plugin-maven/src/main/java/com/diffplug/spotless/maven/yaml/Yaml.java)

```xml
<configuration>
<yaml>
<includes> <!-- You have to set the target manually -->
<include>src/**/*.yaml</include>
</includes>

<jackson /> <!-- has its own section below -->
</yaml>
</configuration>
```

### jackson

Uses Jackson and YAMLFactory to pretty print objects:

```xml
<jackson>
<version>2.14.1</version> <!-- optional: The version of 'com.fasterxml.jackson.dataformat:jackson-dataformat-yaml' to be used -->
<enabledFeatures> <!-- optional: Customize the set of enabled features -->
<enabledFeature>INDENT_OUTPUT<enabledFeature/>
</enabledFeatures>
<disabledFeatures> <!-- optional: Customize the set of disabled features -->
<disabledFeature>DEFAULT_HAS_NO_DISABLED_FEATURE<disabledFeature/>
</disabledFeatures>
</jackson>
```

<a name="applying-prettier-to-javascript--flow--typescript--css--scss--less--jsx--graphql--yaml--etc"></a>

## Prettier

[homepage](https://prettier.io/). [changelog](https://github.com/prettier/prettier/blob/master/CHANGELOG.md). [official plugins](https://prettier.io/docs/en/plugins.html#official-plugins). [community plugins](https://prettier.io/docs/en/plugins.html#community-plugins). Prettier is a formatter that can format almost every anything - JavaScript, JSX, Angular, Vue, Flow, TypeScript, CSS, Less, SCSS, HTML, JSON, GraphQL, Markdown (including GFM and MDX), and YAML. It can format even more [using plugins](https://prettier.io/docs/en/plugins.html) (PHP, Ruby, Swift, XML, Apex, Elm, Java (!!), Kotlin, pgSQL, .properties, solidity, svelte, toml, shellscript, ...).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,13 +65,15 @@
import com.diffplug.spotless.maven.incremental.UpToDateChecking;
import com.diffplug.spotless.maven.java.Java;
import com.diffplug.spotless.maven.javascript.Javascript;
import com.diffplug.spotless.maven.json.Json;
import com.diffplug.spotless.maven.kotlin.Kotlin;
import com.diffplug.spotless.maven.markdown.Markdown;
import com.diffplug.spotless.maven.pom.Pom;
import com.diffplug.spotless.maven.python.Python;
import com.diffplug.spotless.maven.scala.Scala;
import com.diffplug.spotless.maven.sql.Sql;
import com.diffplug.spotless.maven.typescript.Typescript;
import com.diffplug.spotless.maven.yaml.Yaml;

public abstract class AbstractSpotlessMojo extends AbstractMojo {
private static final String DEFAULT_INDEX_FILE_NAME = "spotless-index";
Expand Down Expand Up @@ -171,6 +173,12 @@ public abstract class AbstractSpotlessMojo extends AbstractMojo {
@Parameter
private Markdown markdown;

@Parameter
private Json json;

@Parameter
private Yaml yaml;

@Parameter(property = "spotlessFiles")
private String filePatterns;

Expand Down Expand Up @@ -335,7 +343,7 @@ private FileLocator getFileLocator() {
}

private List<FormatterFactory> getFormatterFactories() {
return Stream.concat(formats.stream(), Stream.of(groovy, java, scala, kotlin, cpp, typescript, javascript, antlr4, pom, sql, python, markdown))
return Stream.concat(formats.stream(), Stream.of(groovy, java, scala, kotlin, cpp, typescript, javascript, antlr4, pom, sql, python, markdown, json, yaml))
.filter(Objects::nonNull)
.collect(toList());
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
* 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.yaml;

import java.util.Arrays;
import java.util.List;

import org.apache.maven.plugins.annotations.Parameter;

import com.diffplug.spotless.FormatterStep;
import com.diffplug.spotless.maven.FormatterStepConfig;
import com.diffplug.spotless.maven.FormatterStepFactory;
import com.diffplug.spotless.yaml.YamlJacksonStep;

public class Jackson implements FormatterStepFactory {

@Parameter
private String version = YamlJacksonStep.defaultVersion();

@Parameter
private String[] enabledFeatures = new String[]{"INDENT_OUTPUT"};

@Parameter
private String[] disabledFeatures = new String[0];

@Override
public FormatterStep newFormatterStep(FormatterStepConfig stepConfig) {
List<String> enabledFeaturesAsList = Arrays.asList(enabledFeatures);
List<String> disabledFeaturesAsList = Arrays.asList(disabledFeatures);
return YamlJacksonStep
.create(enabledFeaturesAsList, disabledFeaturesAsList, version, stepConfig.getProvisioner());
}
}
Loading