Skip to content

Add file output parameters to Maven plugin #502

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

Merged
merged 10 commits into from
Jul 25, 2023
Merged
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,48 @@
package org.openapitools.openapidiff.core.utils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.apache.commons.lang3.StringUtils;
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 (StringUtils.isEmpty(fileName)) {
logger.debug("File name cannot be null or empty.");
return;
}

final Path filePath;
try {
filePath = Paths.get(fileName);
if (Files.exists(filePath)) {
logger.warn("File {} already exists. Skip writing to file.", fileName);
return;
}
} catch (final InvalidPathException invalidPathException) {
throw new IllegalArgumentException("File name is an invalid path.");
}

try (final FileOutputStream outputStream = new FileOutputStream(filePath.toFile());
final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream)) {
render.render(diff, outputStreamWriter);
} catch (final IOException ioException) {
logger.error("Exception while writing to file {}", fileName);
}
}
}
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,72 @@
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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

class FileUtilsTest {

private static final Logger logger = LoggerFactory.getLogger(FileUtilsTest.class);

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_contentIsNull_doesNothing(@TempDir Path tempDir) throws IOException {
Path path = tempDir.resolve("output.txt");
Files.write(path, "Test".getBytes(StandardCharsets.UTF_8));

assertDoesNotThrow(() -> FileUtils.writeToFile(null, changedOpenApi, path.toString()));
assertThat(path).exists().content().isEqualTo("Test");
}

@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_doesNothing(@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().isEqualTo("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();
}
}
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