diff --git a/.gitignore b/.gitignore index 1a95765d37..138bb77159 100644 --- a/.gitignore +++ b/.gitignore @@ -121,3 +121,6 @@ nbdist/ nbactions.xml nb-configuration.xml .nb-gradle/ + +# MacOS jenv +.java-version diff --git a/CHANGES.md b/CHANGES.md index c66b451f08..1c6f0781ef 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -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)) diff --git a/lib/build.gradle b/lib/build.gradle index 115d27195f..3ef2064765 100644 --- a/lib/build.gradle +++ b/lib/build.gradle @@ -14,7 +14,8 @@ def NEEDS_GLUE = [ 'ktlint', 'flexmark', 'diktat', - 'scalafmt' + 'scalafmt', + 'jackson' ] for (glue in NEEDS_GLUE) { sourceSets.register(glue) { @@ -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 diff --git a/lib/src/jackson/java/com/diffplug/spotless/glue/yaml/YamlJacksonFormatterFunc.java b/lib/src/jackson/java/com/diffplug/spotless/glue/yaml/YamlJacksonFormatterFunc.java new file mode 100644 index 0000000000..30cf538159 --- /dev/null +++ b/lib/src/jackson/java/com/diffplug/spotless/glue/yaml/YamlJacksonFormatterFunc.java @@ -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 enabledFeatures; + private List disabledFeatures; + + public YamlJacksonFormatterFunc(List enabledFeatures, List 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 + // 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 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 {} +} diff --git a/lib/src/main/java/com/diffplug/spotless/yaml/YamlJacksonStep.java b/lib/src/main/java/com/diffplug/spotless/yaml/YamlJacksonStep.java new file mode 100644 index 0000000000..db2525ab97 --- /dev/null +++ b/lib/src/main/java/com/diffplug/spotless/yaml/YamlJacksonStep.java @@ -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 enabledFeatures, + List 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 enabledFeatures; + private final List disabledFeatures; + + private final JarState jarState; + + private State(List enabledFeatures, + List 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); + } + } +} diff --git a/plugin-maven/CHANGES.md b/plugin-maven/CHANGES.md index bef392ca4d..ed87752a98 100644 --- a/plugin-maven/CHANGES.md +++ b/plugin-maven/CHANGES.md @@ -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)) diff --git a/plugin-maven/README.md b/plugin-maven/README.md index 3ec338bf10..c5c5cf0ac3 100644 --- a/plugin-maven/README.md +++ b/plugin-maven/README.md @@ -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) @@ -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 @@ -899,6 +900,41 @@ for details. + +## 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 + + + + src/**/*.yaml + + + + + +``` + +### jackson + +Uses Jackson and YAMLFactory to pretty print objects: + +```xml + + 2.14.1 + + INDENT_OUTPUT + + + DEFAULT_HAS_NO_DISABLED_FEATURE + + +``` + + + ## 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, ...). 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 5ad96ece46..e594c724ef 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 @@ -65,6 +65,7 @@ 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; @@ -72,6 +73,7 @@ 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"; @@ -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; @@ -335,7 +343,7 @@ private FileLocator getFileLocator() { } private List 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()); } diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/yaml/Jackson.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/yaml/Jackson.java new file mode 100644 index 0000000000..2bc7617a38 --- /dev/null +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/yaml/Jackson.java @@ -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 enabledFeaturesAsList = Arrays.asList(enabledFeatures); + List disabledFeaturesAsList = Arrays.asList(disabledFeatures); + return YamlJacksonStep + .create(enabledFeaturesAsList, disabledFeaturesAsList, version, stepConfig.getProvisioner()); + } +} 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 new file mode 100644 index 0000000000..6cba1b2ebd --- /dev/null +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/yaml/Yaml.java @@ -0,0 +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.yaml; + +import java.util.Collections; +import java.util.Set; + +import com.diffplug.spotless.maven.FormatterFactory; + +/** + * A {@link FormatterFactory} implementation that corresponds to {@code ...} configuration element. + */ +public class Yaml extends FormatterFactory { + @Override + public Set defaultIncludes() { + return Collections.emptySet(); + } + + @Override + public String licenseHeaderDelimiter() { + return null; + } + + public void addJackson(Jackson jackson) { + addStepFactory(jackson); + } + +} 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 33d63296c4..e37bb0f13d 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 @@ -164,6 +164,10 @@ protected void writePomWithJsonSteps(String... steps) throws IOException { writePom(groupWithSteps("json", including("**/*.json"), steps)); } + protected void writePomWithYamlSteps(String... steps) throws IOException { + writePom(groupWithSteps("yaml", including("**/*.yaml"), steps)); + } + protected void writePom(String... configuration) throws IOException { writePom(null, configuration, null); } diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/json/JsonTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/json/JsonTest.java index fe6560cbec..e492109faa 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/json/JsonTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/json/JsonTest.java @@ -16,25 +16,60 @@ package com.diffplug.spotless.maven.json; import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import com.diffplug.spotless.maven.MavenIntegrationHarness; public class JsonTest extends MavenIntegrationHarness { + private static final Logger LOGGER = LoggerFactory.getLogger(JsonTest.class); + @Test - public void testFormatJson_WithSimple_defaultConfig() throws Exception { - writePomWithJsonSteps(""); + public void testFormatJson_WithSimple_defaultConfig_sortByKeys() throws Exception { + writePomWithJsonSteps(""); setFile("json_test.json").toResource("json/sortByKeysBefore.json"); - mavenRunner().withArguments("spotless:apply").runNoError().error(); - assertFile("json_test.json").sameAsResource("json/sortByKeysAfterDisabled.json"); + mavenRunner().withArguments("spotless:apply").runNoError(); + assertFile("json_test.json").sameAsResource("json/sortByKeysAfterDisabled_Simple.json"); } @Test - public void testFormatJson_WithGson_defaultConfig() throws Exception { - writePomWithJsonSteps(""); + public void testFormatJson_WithSimple_defaultConfig_nestedObject() throws Exception { + writePomWithJsonSteps(""); + + setFile("json_test.json").toResource("json/nestedObjectBefore.json"); + mavenRunner().withArguments("spotless:apply").runNoError(); + assertFile("json_test.json").sameAsResource("json/nestedObjectAfter.json"); + } + + @Test + public void testFormatJson_WithGson_defaultConfig_sortByKeys() throws Exception { + writePomWithJsonSteps(""); setFile("json_test.json").toResource("json/sortByKeysBefore.json"); - mavenRunner().withArguments("spotless:apply").runNoError().error(); + mavenRunner().withArguments("spotless:apply").runNoError(); assertFile("json_test.json").sameAsResource("json/sortByKeysAfterDisabled.json"); } + + @Test + public void testFormatJson_WithGson_sortByKeys() throws Exception { + writePomWithJsonSteps("true"); + + setFile("json_test.json").toResource("json/sortByKeysBefore.json"); + + String output = mavenRunner().withArguments("spotless:apply").runNoError().output(); + LOGGER.error(output); + System.err.println(output); + assertFile("json_test.json").sameAsResource("json/sortByKeysAfter.json"); + } + + @Test + public void testFormatJson_WithGson_defaultConfig_nestedObject() throws Exception { + writePomWithJsonSteps(""); + + setFile("json_test.json").toResource("json/nestedObjectBefore.json"); + mavenRunner().withArguments("spotless:apply").runNoError(); + assertFile("json_test.json").sameAsResource("json/nestedObjectAfter.json"); + } + } diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/yaml/YamlTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/yaml/YamlTest.java new file mode 100644 index 0000000000..b5a417c536 --- /dev/null +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/yaml/YamlTest.java @@ -0,0 +1,59 @@ +/* + * 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 static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.diffplug.spotless.maven.MavenIntegrationHarness; +import com.diffplug.spotless.maven.MavenRunner.Result; + +public class YamlTest extends MavenIntegrationHarness { + private static final Logger LOGGER = LoggerFactory.getLogger(YamlTest.class); + + @Test + public void testFormatYaml_WithJackson_defaultConfig_separatorComments() throws Exception { + writePomWithYamlSteps(""); + + setFile("yaml_test.yaml").toResource("yaml/separator_comments.yaml"); + Result runNoError = mavenRunner().withArguments("spotless:apply").runNoError(); + LOGGER.error("result: {}", runNoError); + assertThat(runNoError.exitValue()).as("Run without error %s", runNoError).isEqualTo(0); + LOGGER.error("GOGO"); + assertFile("yaml_test.yaml").sameAsResource("yaml/separator_comments.clean.yaml"); + } + + @Test + public void testFormatYaml_WithJackson_defaultConfig_arrayBrackets() throws Exception { + writePomWithYamlSteps(""); + + setFile("yaml_test.yaml").toResource("yaml/array_with_bracket.yaml"); + mavenRunner().withArguments("spotless:apply").runNoError(); + assertFile("yaml_test.yaml").sameAsResource("yaml/array_with_bracket.clean.yaml"); + } + + @Test + public void testFormatYaml_WithJackson_defaultConfig_multipleDocuments() throws Exception { + writePomWithYamlSteps(""); + + setFile("yaml_test.yaml").toResource("yaml/multiple_documents.yaml"); + mavenRunner().withArguments("spotless:apply").runNoError(); + assertFile("yaml_test.yaml").sameAsResource("yaml/multiple_documents.clean.jackson.yaml"); + } +} diff --git a/testlib/src/main/resources/json/sortByKeysAfterDisabled_Simple.json b/testlib/src/main/resources/json/sortByKeysAfterDisabled_Simple.json new file mode 100644 index 0000000000..d2d3612fbd --- /dev/null +++ b/testlib/src/main/resources/json/sortByKeysAfterDisabled_Simple.json @@ -0,0 +1,19 @@ +{ + "A": 1, + "a": 3, + "c": 4, + "x": 5, + "X": 2, + "z": { + "A": 1, + "a": 3, + "c": 4, + "x": 5, + "X": 2 + }, + "_arraysNotSorted": [ + 3, + 2, + 1 + ] +} diff --git a/testlib/src/main/resources/yaml/array_with_bracket.clean.yaml b/testlib/src/main/resources/yaml/array_with_bracket.clean.yaml new file mode 100644 index 0000000000..c6f891b9de --- /dev/null +++ b/testlib/src/main/resources/yaml/array_with_bracket.clean.yaml @@ -0,0 +1,12 @@ +--- +episodes: +- 1 +- 2 +- 3 +- 4 +- 5 +- 6 +- 7 +best-jedi: + name: "Obi-Wan" + side: "light" \ No newline at end of file diff --git a/testlib/src/main/resources/yaml/array_with_bracket.yaml b/testlib/src/main/resources/yaml/array_with_bracket.yaml new file mode 100644 index 0000000000..e28373163d --- /dev/null +++ b/testlib/src/main/resources/yaml/array_with_bracket.yaml @@ -0,0 +1,5 @@ +episodes: [1, 2, 3, 4, 5, 6, 7] + + + +best-jedi: {name: Obi-Wan, side: light} \ No newline at end of file diff --git a/testlib/src/main/resources/yaml/multiple_documents.clean.jackson.yaml b/testlib/src/main/resources/yaml/multiple_documents.clean.jackson.yaml new file mode 100644 index 0000000000..aa731919b4 --- /dev/null +++ b/testlib/src/main/resources/yaml/multiple_documents.clean.jackson.yaml @@ -0,0 +1,2 @@ +--- +document: "this is document 1" diff --git a/testlib/src/main/resources/yaml/multiple_documents.clean.yaml b/testlib/src/main/resources/yaml/multiple_documents.clean.yaml new file mode 100644 index 0000000000..45e0b0916b --- /dev/null +++ b/testlib/src/main/resources/yaml/multiple_documents.clean.yaml @@ -0,0 +1,8 @@ +--- +document: this is document 1 + +--- +document: this is document 2 + +--- +document: this is document 3 \ No newline at end of file diff --git a/testlib/src/main/resources/yaml/multiple_documents.yaml b/testlib/src/main/resources/yaml/multiple_documents.yaml new file mode 100644 index 0000000000..51f14a5862 --- /dev/null +++ b/testlib/src/main/resources/yaml/multiple_documents.yaml @@ -0,0 +1,10 @@ +document: this is document 1 +--- + +document: this is document 2 + + +--- + + +document: this is document 3 \ No newline at end of file diff --git a/testlib/src/main/resources/yaml/separator_comments.clean.yaml b/testlib/src/main/resources/yaml/separator_comments.clean.yaml new file mode 100644 index 0000000000..35bb8717dd --- /dev/null +++ b/testlib/src/main/resources/yaml/separator_comments.clean.yaml @@ -0,0 +1,7 @@ +--- +hr: +- "Mark McGwire" +- "Sammy Sosa" +rbi: +- "SS" +- "Ken Griffey" \ No newline at end of file diff --git a/testlib/src/main/resources/yaml/separator_comments.yaml b/testlib/src/main/resources/yaml/separator_comments.yaml new file mode 100644 index 0000000000..0213e66406 --- /dev/null +++ b/testlib/src/main/resources/yaml/separator_comments.yaml @@ -0,0 +1,9 @@ + +--- +hr: + - Mark McGwire + # Following node labeled SS + - &SS Sammy Sosa +rbi: + - *SS # Subsequent occurrence + - Ken Griffey \ No newline at end of file