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

Adds Collapse Spec Options to Maven Plugin #17714

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions modules/openapi-generator-maven-plugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ mvn clean compile
| `gitHost` | `openapi.generator.maven.plugin.gitHost` | The git host, e.g. gitlab.com
| `gitUserId` | `openapi.generator.maven.plugin.gitUserId` | sets git information of the project
| `gitRepoId` | `openapi.generator.maven.plugin.gitRepoId` | sets the repo ID (e.g. openapi-generator)
| `collapsedSpec` | `openapi.generator.maven.plugin.collapsedSpec` | sets the path to the collapsed single-file representation of the OpenAPI spec
| `includeCollapsedSpecInArtifacts` | `openapi.generator.maven.plugin.publishCollapsedSpec` | includes the collapsed spec in the Maven artifacts (`false` by default)
| `templateDirectory` | `openapi.generator.maven.plugin.templateDirectory` | directory with mustache templates
| `templateResourcePath` | `openapi.generator.maven.plugin.templateResourcePath` | directory with mustache templates via resource path. This option will overwrite any option defined in `templateDirectory`.
| `engine` | `openapi.generator.maven.plugin.engine` | The name of templating engine to use, "mustache" (default) or "handlebars" (beta)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
import static org.openapitools.codegen.config.CodegenConfiguratorUtils.*;

import io.swagger.v3.core.util.Json;
import io.swagger.v3.core.util.Yaml;
import io.swagger.v3.parser.OpenAPIResolver;
import io.swagger.v3.parser.OpenAPIV3Parser;
import io.swagger.v3.parser.core.models.AuthorizationValue;
import java.io.File;
import java.io.FileOutputStream;
Expand All @@ -33,13 +37,17 @@
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import com.google.common.io.ByteSource;
import com.google.common.io.CharSource;
import io.swagger.v3.parser.core.models.ParseOptions;
import io.swagger.v3.parser.util.ClasspathHelper;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
Expand All @@ -52,6 +60,7 @@
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.project.MavenProject;

import org.apache.maven.project.MavenProjectHelper;
import org.openapitools.codegen.CliOption;
import org.openapitools.codegen.ClientOptInput;
import org.openapitools.codegen.CodegenConfig;
Expand Down Expand Up @@ -139,6 +148,18 @@ public class CodeGenMojo extends AbstractMojo {
@Parameter(name = "gitRepoId", property = "openapi.generator.maven.plugin.gitRepoId")
private String gitRepoId;

/**
* The path to the collapsed single-file representation of the OpenAPI spec.
*/
@Parameter(name = "collapsedSpec", property = "openapi.generator.maven.plugin.collapsedSpec")
private String collapsedSpec;

/**
* Includes the collapsed spec in the Maven artifacts.
*/
@Parameter(name = "includeCollapsedSpecInArtifacts", property = "openapi.generator.maven.plugin.publishCollapsedSpec", defaultValue = "false")
private boolean includeCollapsedSpecInArtifacts;

/**
* Folder containing the template files.
*/
Expand Down Expand Up @@ -509,6 +530,18 @@ public class CodeGenMojo extends AbstractMojo {
@Parameter(property = "codegen.configHelp")
private boolean configHelp = false;

/**
* The Maven project context.
*/
@Parameter(defaultValue = "${project}", required = true, readonly = true)
MavenProject mavenProject;

/**
* Maven ProjectHelper used to manage build artifacts.
*/
@Component
MavenProjectHelper mavenProjectHelper;

@Parameter(defaultValue = "${mojoExecution}", readonly = true)
private MojoExecution mojo;

Expand Down Expand Up @@ -538,6 +571,17 @@ public void execute() throws MojoExecutionException {
"generated-test-sources/openapi" : "generated-sources/openapi");
}

if (collapsedSpec != null) {
final var collapsedSpecPath = createCollapsedSpec();
if (includeCollapsedSpecInArtifacts) {
mavenProjectHelper.attachArtifact(
mavenProject,
collapsedSpecPath.toString().toLowerCase(Locale.ROOT).endsWith(".json") ? "json" : "yaml",
collapsedSpec,
collapsedSpecPath.toFile());
}
}

addCompileSourceRootIfConfigured();

try {
Expand Down Expand Up @@ -1094,4 +1138,27 @@ private void adjustAdditionalProperties(final CodegenConfig config) {
}
}
}

private Path createCollapsedSpec() throws MojoExecutionException {
// Merge the OpenAPI spec file.
final var parseOptions = new ParseOptions();
parseOptions.setResolve(true);
final var openApiMerged = new OpenAPIResolver(new OpenAPIV3Parser().readLocation(inputSpec, null, parseOptions).getOpenAPI()).resolve();

// Switch based on JSON or YAML.
final var extension = inputSpec.toLowerCase(Locale.ROOT).endsWith(".json") ? ".json" : ".yaml";
final var mapper = inputSpec.toLowerCase(Locale.ROOT).endsWith(".json") ? Json.mapper() : Yaml.mapper();

// Write the merged spec to the output file.
final var collapsedSpecPath = output.toPath().resolve(collapsedSpec + extension).toAbsolutePath();
try {
final var openApiString = mapper.writeValueAsString(openApiMerged);
FileUtils.writeStringToFile(collapsedSpecPath.toFile(), openApiString, StandardCharsets.UTF_8);
} catch (final IOException e) {
throw new MojoExecutionException(new MessageFormat("Failed to write collapsed spec {0}", Locale.ROOT).format(collapsedSpecPath), e);
}

// Return the path to the collapsed spec file.
return collapsedSpecPath;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,12 @@
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.io.FileUtils;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.execution.DefaultMavenExecutionRequest;
import org.apache.maven.execution.MavenExecutionRequest;
import org.apache.maven.execution.MavenSession;
Expand Down Expand Up @@ -150,6 +153,34 @@ public void testSkipRegenerationForClasspathSpecFileWithChange() throws Exceptio

}

public void testCollapsedSpecProduced() throws Exception {
// GIVEN
Path folder = Files.createTempDirectory("test");
CodeGenMojo mojo = loadMojo(folder.toFile(), "src/test/resources/default", "executionId");

// WHEN
mojo.execute();

// THEN
File collapseSpecFile = folder.resolve("target/generated-sources/common-maven/remote-openapi/petstore-full-spec.yaml").toFile();
assertTrue(collapseSpecFile.exists());
}

public void testCollapsedSpecAddedToArtifacts() throws Exception {
// GIVEN
Path folder = Files.createTempDirectory("test");
CodeGenMojo mojo = loadMojo(folder.toFile(), "src/test/resources/default", "executionId");

// WHEN
mojo.execute();

// THEN
List<Artifact> matchingArtifacts = mojo.mavenProject.getAttachedArtifacts().stream()
.filter(artifact -> artifact.getFile().getName().equals("petstore-full-spec.yaml"))
.collect(Collectors.toList());
assertEquals(1, matchingArtifacts.size());
}

protected CodeGenMojo loadMojo(File temporaryFolder, String projectRoot) throws Exception {
return loadMojo(temporaryFolder, projectRoot, "default");
}
Expand Down
Loading
Loading