Skip to content

Commit

Permalink
Add file output parameters to Maven plugin (#502)
Browse files Browse the repository at this point in the history
Co-authored-by: Jochen Schalanda <[email protected]>

Closes #501
  • Loading branch information
studur authored Jul 25, 2023
1 parent 85a5265 commit 2bd7351
Show file tree
Hide file tree
Showing 11 changed files with 282 additions and 30 deletions.
19 changes: 10 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,12 @@ Add openapi-diff to your POM to show diffs when you test your Maven project. You
<failOnIncompatible>true</failOnIncompatible>
<!-- Fail if API changed (default: false) -->
<failOnChanged>true</failOnChanged>
<!-- Supply file path for console output to file if desired. -->
<consoleOutputFileName>${project.basedir}/../maven/target/diff.txt</consoleOutputFileName>
<!-- Supply file path for json output to file if desired. -->
<jsonOutputFileName>${project.basedir}/../maven/target/diff.json</jsonOutputFileName>
<!-- Supply file path for markdown output to file if desired. -->
<markdownOutputFileName>${project.basedir}/../maven/target/diff.md</markdownOutputFileName>
</configuration>
</execution>
</executions>
Expand All @@ -167,6 +173,7 @@ public class Main {
```
### Render difference
---
#### HTML
Expand All @@ -176,11 +183,9 @@ String html = new HtmlRender("Changelog",
.render(diff);
try {
FileWriter fw = new FileWriter(
"testNewApi.html");
FileWriter fw = new FileWriter("testNewApi.html");
fw.write(html);
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
Expand All @@ -191,11 +196,9 @@ try {
```java
String render = new MarkdownRender().render(diff);
try {
FileWriter fw = new FileWriter(
"testDiff.md");
FileWriter fw = new FileWriter("testDiff.md");
fw.write(render);
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
Expand All @@ -207,11 +210,9 @@ try {
```java
String render = new JsonRender().render(diff);
try {
FileWriter fw = new FileWriter(
"testDiff.json");
FileWriter fw = new FileWriter("testDiff.json");
fw.write(render);
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@

public class ChangedUtils {

private ChangedUtils() {}
private ChangedUtils() {
throw new UnsupportedOperationException("Utility class. Do not instantiate");
}

public static boolean isUnchanged(Changed changed) {
return changed == null || changed.isUnchanged();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@

public class Copy {

private Copy() {}
private Copy() {
throw new UnsupportedOperationException("Utility class. Do not instantiate");
}

public static <K, V> Map<K, V> copyMap(Map<K, V> map) {
if (map == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@

public class EndpointUtils {

private EndpointUtils() {}
private EndpointUtils() {
throw new UnsupportedOperationException("Utility class. Do not instantiate");
}

public static Collection<Endpoint> convert2Endpoints(
String pathUrl, Map<PathItem.HttpMethod, Operation> map) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package org.openapitools.openapidiff.core.utils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.openapitools.openapidiff.core.model.ChangedOpenApi;
import org.openapitools.openapidiff.core.output.Render;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class FileUtils {
private static final Logger logger = LoggerFactory.getLogger(FileUtils.class);

private FileUtils() {
throw new UnsupportedOperationException("Utility class. Do not instantiate");
}

public static void writeToFile(
final Render render, final ChangedOpenApi diff, final String fileName) {
if (fileName == null || fileName.isEmpty()) {
logger.debug("File name cannot be null or empty.");
return;
}

final Path filePath = Paths.get(fileName);
try (final FileOutputStream outputStream = new FileOutputStream(filePath.toFile());
final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream)) {
render.render(diff, outputStreamWriter);
} catch (final IOException e) {
logger.error("Exception while writing to file {}", fileName, e);
}
}
}
11 changes: 11 additions & 0 deletions core/src/main/resources/logback.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>

<root level="debug">
<appender-ref ref="STDOUT"/>
</root>
</configuration>
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package org.openapitools.openapidiff.core.utils;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.openapitools.openapidiff.core.model.ChangedOpenApi;
import org.openapitools.openapidiff.core.output.ConsoleRender;

class FileUtilsTest {
private ChangedOpenApi changedOpenApi;

@BeforeEach
void setup() {
changedOpenApi = new ChangedOpenApi();
changedOpenApi.setChangedSchemas(Collections.emptyList());
changedOpenApi.setChangedOperations(Collections.emptyList());
changedOpenApi.setNewEndpoints(Collections.emptyList());
changedOpenApi.setMissingEndpoints(Collections.emptyList());
}

@Test
void writeToFile_filenameIsNull_doesNothing() {
assertDoesNotThrow(() -> FileUtils.writeToFile(new ConsoleRender(), changedOpenApi, null));
}

@Test
void writeToFile_filenameIsEmpty_doesNothing() {
assertDoesNotThrow(
() -> FileUtils.writeToFile(new ConsoleRender(), changedOpenApi, StringUtils.EMPTY));
}

@Test
void writeToFile_fileExists_overwrites_file(@TempDir Path tempDir) throws IOException {
final Path path = tempDir.resolve("output.txt");
Files.write(path, "Test".getBytes(StandardCharsets.UTF_8));

assertDoesNotThrow(
() -> FileUtils.writeToFile(new ConsoleRender(), changedOpenApi, path.toString()));
assertThat(path).exists().content().isNotEqualTo("Test");
}

@Test
void writeToFile_fileDoesNotExist_createsFile(@TempDir Path tempDir) {
final Path path = tempDir.resolve("output.txt");
assertDoesNotThrow(
() -> FileUtils.writeToFile(new ConsoleRender(), changedOpenApi, path.toString()));
assertThat(path).exists().content().isNotBlank();
}
}
3 changes: 3 additions & 0 deletions maven-example/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@
<oldSpec>${project.basedir}/../maven/src/test/resources/oldspec.yaml</oldSpec>
<newSpec>${project.basedir}/../maven/src/test/resources/newspec.yaml</newSpec>
<failOnIncompatible>true</failOnIncompatible>
<consoleOutputFileName>${project.basedir}/../maven/target/diff.txt</consoleOutputFileName>
<jsonOutputFileName>${project.basedir}/../maven/target/diff.json</jsonOutputFileName>
<markdownOutputFileName>${project.basedir}/../maven/target/diff.md</markdownOutputFileName>
</configuration>
</execution>
</executions>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
package org.openapitools.openapidiff.maven;

import static org.openapitools.openapidiff.core.utils.FileUtils.writeToFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UncheckedIOException;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
Expand All @@ -11,10 +15,13 @@
import org.openapitools.openapidiff.core.OpenApiCompare;
import org.openapitools.openapidiff.core.model.ChangedOpenApi;
import org.openapitools.openapidiff.core.output.ConsoleRender;
import org.openapitools.openapidiff.core.output.JsonRender;
import org.openapitools.openapidiff.core.output.MarkdownRender;

/** A Maven Mojo that diffs two OpenAPI specifications and reports on differences. */
@Mojo(name = "diff", defaultPhase = LifecyclePhase.TEST)
public class OpenApiDiffMojo extends AbstractMojo {

@Parameter(property = "oldSpec")
String oldSpec;

Expand All @@ -30,6 +37,15 @@ public class OpenApiDiffMojo extends AbstractMojo {
@Parameter(property = "skip", defaultValue = "false")
Boolean skip = false;

@Parameter(property = "consoleOutputFileName")
String consoleOutputFileName;

@Parameter(property = "jsonOutputFileName")
String jsonOutputFileName;

@Parameter(property = "markdownOutputFileName")
String markdownOutputFileName;

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
if (Boolean.TRUE.equals(skip)) {
Expand All @@ -39,10 +55,18 @@ public void execute() throws MojoExecutionException, MojoFailureException {

try {
final ChangedOpenApi diff = OpenApiCompare.fromLocations(oldSpec, newSpec);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
new ConsoleRender().render(diff, outputStreamWriter);
getLog().info(outputStream.toString());

try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream)) {
new ConsoleRender().render(diff, outputStreamWriter);
getLog().info(outputStream.toString());
} catch (IOException e) {
throw new UncheckedIOException(e);
}

writeDiffAsTextToFile(diff);
writeDiffAsJsonToFile(diff);
writeDiffAsMarkdownToFile(diff);

if (failOnIncompatible && diff.isIncompatible()) {
throw new BackwardIncompatibilityException("The API changes broke backward compatibility");
Expand All @@ -55,4 +79,16 @@ public void execute() throws MojoExecutionException, MojoFailureException {
throw new MojoExecutionException("Unexpected error", e);
}
}

private void writeDiffAsTextToFile(final ChangedOpenApi diff) {
writeToFile(new ConsoleRender(), diff, consoleOutputFileName);
}

private void writeDiffAsJsonToFile(final ChangedOpenApi diff) {
writeToFile(new JsonRender(), diff, jsonOutputFileName);
}

private void writeDiffAsMarkdownToFile(final ChangedOpenApi diff) {
writeToFile(new MarkdownRender(), diff, markdownOutputFileName);
}
}
Loading

0 comments on commit 2bd7351

Please sign in to comment.