-
-
Notifications
You must be signed in to change notification settings - Fork 7.5k
Generate merge spec #14387
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
Generate merge spec #14387
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
151 changes: 151 additions & 0 deletions
151
...es/openapi-generator/src/main/java/org/openapitools/codegen/config/MergedSpecBuilder.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,151 @@ | ||
| package org.openapitools.codegen.config; | ||
|
|
||
| import java.io.File; | ||
| import java.io.IOException; | ||
| import java.nio.file.Files; | ||
| import java.nio.file.Path; | ||
| import java.nio.file.Paths; | ||
| import java.nio.file.StandardOpenOption; | ||
| import java.util.ArrayList; | ||
| import java.util.Collections; | ||
| import java.util.HashMap; | ||
| import java.util.List; | ||
| import java.util.Locale; | ||
| import java.util.Map; | ||
| import java.util.Set; | ||
| import java.util.stream.Collectors; | ||
|
|
||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
|
|
||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||
| import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; | ||
| import com.google.common.collect.ImmutableMap; | ||
|
|
||
| import io.swagger.parser.OpenAPIParser; | ||
| import io.swagger.v3.oas.models.OpenAPI; | ||
| import io.swagger.v3.parser.core.models.ParseOptions; | ||
|
|
||
| public class MergedSpecBuilder { | ||
|
|
||
| private static final Logger LOGGER = LoggerFactory.getLogger(MergedSpecBuilder.class); | ||
|
|
||
| private final String inputSpecRootDirectory; | ||
| private final String mergeFileName; | ||
|
|
||
| public MergedSpecBuilder(final String rootDirectory, final String mergeFileName) { | ||
| this.inputSpecRootDirectory = rootDirectory; | ||
| this.mergeFileName = mergeFileName; | ||
| } | ||
|
|
||
| public String buildMergedSpec() { | ||
| deleteMergedFileFromPreviousRun(); | ||
| List<String> specRelatedPaths = getAllSpecFilesInDirectory(); | ||
| if (specRelatedPaths.isEmpty()) { | ||
| throw new RuntimeException("Spec directory doesn't contains any specification"); | ||
| } | ||
| LOGGER.info("In spec root directory {} found specs {}", inputSpecRootDirectory, specRelatedPaths); | ||
|
|
||
| String openapiVersion = null; | ||
| boolean isJson = false; | ||
| ParseOptions options = new ParseOptions(); | ||
| options.setResolve(true); | ||
| List<SpecWithPaths> allPaths = new ArrayList<>(); | ||
|
|
||
| for (String specRelatedPath : specRelatedPaths) { | ||
| String specPath = inputSpecRootDirectory + File.separator + specRelatedPath; | ||
| try { | ||
| LOGGER.info("Reading spec: {}", specPath); | ||
|
|
||
| OpenAPI result = new OpenAPIParser() | ||
| .readLocation(specPath, new ArrayList<>(), options) | ||
| .getOpenAPI(); | ||
|
|
||
| if (openapiVersion == null) { | ||
| openapiVersion = result.getOpenapi(); | ||
| if (specRelatedPath.toLowerCase(Locale.ROOT).endsWith(".json")) { | ||
| isJson = true; | ||
| } | ||
| } | ||
| allPaths.add(new SpecWithPaths(specRelatedPath, result.getPaths().keySet())); | ||
| } catch (Exception e) { | ||
| LOGGER.error("Failed to read file: {}. It would be ignored", specPath); | ||
| } | ||
| } | ||
|
|
||
| Map<String, Object> mergedSpec = generatedMergedSpec(openapiVersion, allPaths); | ||
| String mergedFilename = this.mergeFileName + (isJson ? ".json" : ".yaml"); | ||
| Path mergedFilePath = Paths.get(inputSpecRootDirectory, mergedFilename); | ||
|
|
||
| try { | ||
| ObjectMapper objectMapper = isJson ? new ObjectMapper() : new ObjectMapper(new YAMLFactory()); | ||
| Files.write(mergedFilePath, objectMapper.writeValueAsBytes(mergedSpec), StandardOpenOption.CREATE, StandardOpenOption.WRITE); | ||
| } catch (IOException e) { | ||
| throw new RuntimeException(e); | ||
| } | ||
|
|
||
| return mergedFilePath.toString(); | ||
| } | ||
|
|
||
| private static Map<String, Object> generatedMergedSpec(String openapiVersion, List<SpecWithPaths> allPaths) { | ||
| Map<String, Object> spec = generateHeader(openapiVersion); | ||
| Map<String, Object> paths = new HashMap<>(); | ||
| spec.put("paths", paths); | ||
|
|
||
| for(SpecWithPaths specWithPaths : allPaths) { | ||
| for (String path : specWithPaths.paths) { | ||
| String specRelatedPath = "./" + specWithPaths.specRelatedPath + "#/paths/" + path.replace("/", "~1"); | ||
| paths.put(path, ImmutableMap.of( | ||
| "$ref", specRelatedPath | ||
| )); | ||
| } | ||
| } | ||
|
|
||
| return spec; | ||
| } | ||
|
|
||
| private static Map<String, Object> generateHeader(String openapiVersion) { | ||
| Map<String, Object> map = new HashMap<>(); | ||
| map.put("openapi", openapiVersion); | ||
| map.put("info", ImmutableMap.of( | ||
| "title", "merged spec", | ||
| "description", "merged spec", | ||
| "version", "1.0.0" | ||
| )); | ||
| map.put("servers", Collections.singleton( | ||
| ImmutableMap.of("url", "http://localhost:8080") | ||
| )); | ||
| return map; | ||
| } | ||
|
|
||
| private List<String> getAllSpecFilesInDirectory() { | ||
| Path rootDirectory = new File(inputSpecRootDirectory).toPath(); | ||
| try { | ||
| return Files.walk(rootDirectory) | ||
| .filter(path -> !Files.isDirectory(path)) | ||
| .map(path -> rootDirectory.relativize(path).toString()) | ||
| .collect(Collectors.toList()); | ||
| } catch (IOException e) { | ||
| throw new RuntimeException("Exception while listing files in spec root directory: " + inputSpecRootDirectory, e); | ||
| } | ||
| } | ||
|
|
||
| private void deleteMergedFileFromPreviousRun() { | ||
| try { | ||
| Files.deleteIfExists(Paths.get(inputSpecRootDirectory + File.separator + mergeFileName + ".json")); | ||
| } catch (IOException e) { } | ||
| try { | ||
| Files.deleteIfExists(Paths.get(inputSpecRootDirectory + File.separator + mergeFileName + ".yaml")); | ||
| } catch (IOException e) { } | ||
| } | ||
|
|
||
| private static class SpecWithPaths { | ||
| private final String specRelatedPath; | ||
| private final Set<String> paths; | ||
|
|
||
| private SpecWithPaths(final String specRelatedPath, final Set<String> paths) { | ||
| this.specRelatedPath = specRelatedPath; | ||
| this.paths = paths; | ||
| } | ||
| } | ||
| } | ||
95 changes: 95 additions & 0 deletions
95
...penapi-generator/src/test/java/org/openapitools/codegen/config/MergedSpecBuilderTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| package org.openapitools.codegen.config; | ||
|
|
||
| import java.io.File; | ||
| import java.io.IOException; | ||
| import java.nio.file.Files; | ||
| import java.nio.file.Paths; | ||
| import java.util.Map; | ||
| import java.util.function.Function; | ||
| import java.util.stream.Collectors; | ||
|
|
||
| import org.openapitools.codegen.ClientOptInput; | ||
| import org.openapitools.codegen.DefaultGenerator; | ||
| import org.openapitools.codegen.java.assertions.JavaFileAssert; | ||
| import org.openapitools.codegen.languages.SpringCodegen; | ||
| import org.testng.annotations.Test; | ||
|
|
||
| import com.google.common.collect.ImmutableMap; | ||
|
|
||
| import io.swagger.parser.OpenAPIParser; | ||
| import io.swagger.v3.oas.models.OpenAPI; | ||
| import io.swagger.v3.parser.core.models.ParseOptions; | ||
|
|
||
| public class MergedSpecBuilderTest { | ||
|
|
||
| @Test | ||
| public void shouldMergeYamlSpecs() throws IOException { | ||
| mergeSpecs("yaml"); | ||
| } | ||
|
|
||
| @Test | ||
| public void shouldMergeJsonSpecs() throws IOException { | ||
| mergeSpecs("json"); | ||
| } | ||
|
|
||
| private void mergeSpecs(String fileExt) throws IOException { | ||
| File output = Files.createTempDirectory("spec-directory").toFile().getCanonicalFile(); | ||
| output.deleteOnExit(); | ||
|
|
||
| Files.copy(Paths.get("src/test/resources/bugs/mergerTest/spec1." + fileExt), output.toPath().resolve("spec1." + fileExt)); | ||
| Files.copy(Paths.get("src/test/resources/bugs/mergerTest/spec2." + fileExt), output.toPath().resolve("spec2." + fileExt)); | ||
|
|
||
| String outputPath = output.getAbsolutePath().replace('\\', '/'); | ||
|
|
||
| String mergedSpec = new MergedSpecBuilder(outputPath, "_merged_file") | ||
| .buildMergedSpec(); | ||
|
|
||
| assertFilesFromMergedSpec(mergedSpec); | ||
| } | ||
|
|
||
| private void assertFilesFromMergedSpec(String mergedSpec) throws IOException { | ||
| File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); | ||
| output.deleteOnExit(); | ||
|
|
||
| ParseOptions parseOptions = new ParseOptions(); | ||
| parseOptions.setResolve(true); | ||
| OpenAPI openAPI = new OpenAPIParser() | ||
| .readLocation(mergedSpec, null, parseOptions).getOpenAPI(); | ||
|
|
||
| SpringCodegen codegen = new SpringCodegen(); | ||
| codegen.setOutputDir(output.getAbsolutePath()); | ||
|
|
||
| ClientOptInput input = new ClientOptInput(); | ||
| input.openAPI(openAPI); | ||
| input.config(codegen); | ||
|
|
||
| DefaultGenerator generator = new DefaultGenerator(); | ||
| Map<String, File> files = generator.opts(input).generate().stream() | ||
| .collect(Collectors.toMap(File::getName, Function.identity())); | ||
|
|
||
| JavaFileAssert.assertThat(files.get("Spec1Api.java")) | ||
| .assertMethod("spec1Operation").hasReturnType("ResponseEntity<Spec1Model>") | ||
|
|
||
| .toFileAssert() | ||
|
|
||
| .assertMethod("spec1OperationComplex") | ||
| .hasReturnType("ResponseEntity<Spec1Model>") | ||
| .assertMethodAnnotations() | ||
| .containsWithNameAndAttributes("RequestMapping", ImmutableMap.of("value", "\"/spec1/complex/{param1}/path\"")) | ||
| .toMethod() | ||
| .hasParameter("param1") | ||
| .withType("String") | ||
| .assertParameterAnnotations() | ||
| .containsWithNameAndAttributes("PathVariable", ImmutableMap.of("value", "\"param1\"")); | ||
|
|
||
| JavaFileAssert.assertThat(files.get("Spec2Api.java")) | ||
| .assertMethod("spec2Operation").hasReturnType("ResponseEntity<Spec2Model>"); | ||
|
|
||
| JavaFileAssert.assertThat(files.get("Spec1Model.java")) | ||
| .assertMethod("getSpec1Field").hasReturnType("String"); | ||
|
|
||
| JavaFileAssert.assertThat(files.get("Spec2Model.java")) | ||
| .assertMethod("getSpec2Field").hasReturnType("BigDecimal"); | ||
| } | ||
|
|
||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hi, why not include the servers array from one or more of the input files?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I have abandoned this plugin and use redocly
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Doing the merge explicitly is not that hard and offers more flexibility, but I guess it's useful to have a built-in one that does the job for many use cases. @borsch