├── .gitignore ├── CODE_OF_CONDUCT.adoc ├── LICENSE ├── README.md ├── build.gradle.kts ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── openapi-merger-app ├── build.gradle.kts └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── rameshkp │ │ │ └── openapi │ │ │ └── merger │ │ │ └── app │ │ │ └── utils │ │ │ └── OpenAPIConverter.java │ └── kotlin │ │ └── com │ │ └── rameshkp │ │ └── openapi │ │ └── merger │ │ └── app │ │ ├── OpenApiMergerApp.kt │ │ ├── exceptions │ │ └── OpenApiDataInvalidException.kt │ │ ├── mergers │ │ ├── ComponentsMerger.kt │ │ ├── ListMerger.kt │ │ ├── MapMerger.kt │ │ ├── Mergeable.kt │ │ ├── OpenApiMerger.kt │ │ ├── PathItemMerger.kt │ │ └── PathsMerger.kt │ │ └── models │ │ ├── Contact.kt │ │ ├── ExternalDocs.kt │ │ ├── Info.kt │ │ ├── License.kt │ │ ├── OpenApi.kt │ │ └── Server.kt │ └── test │ └── kotlin │ └── com │ └── rameshkp │ └── openapi │ └── merger │ └── app │ ├── OpenApiMergerAppTest.kt │ ├── mergers │ ├── PathItemMergerTest.kt │ └── PathsMergerTest.kt │ └── models │ └── ServerTest.kt ├── openapi-merger-gradle-plugin ├── README.md ├── build.gradle.kts └── src │ ├── main │ └── kotlin │ │ └── com │ │ └── rameshkp │ │ └── openapi │ │ └── merger │ │ └── gradle │ │ ├── extensions │ │ ├── ContactExtension.kt │ │ ├── ExternalDocsExtension.kt │ │ ├── InfoExtension.kt │ │ ├── LicenseExtension.kt │ │ ├── OpenApiExtension.kt │ │ ├── OpenApiMergerExtension.kt │ │ ├── OutputExtension.kt │ │ └── ServerExtension.kt │ │ ├── plugin │ │ └── OpenApiMergerGradlePlugin.kt │ │ ├── task │ │ └── OpenApiMergerTask.kt │ │ └── utils │ │ └── Constants.kt │ └── test │ └── kotlin │ └── com │ └── rameshkp │ └── openapi │ └── merger │ └── gradle │ └── plugin │ └── OpenApiMergerGradlePluginTest.kt ├── openapi-merger-maven-plugin ├── README.md ├── build.gradle.kts └── src │ └── main │ ├── java │ └── com │ │ └── rameshkp │ │ └── openapi │ │ └── merger │ │ └── maven │ │ ├── models │ │ └── OpenApiFileFormat.java │ │ └── plugin │ │ └── OpenApiMergerMojo.java │ └── resources │ └── settings.xml └── settings.gradle.kts /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | **/build/ 3 | 4 | # Ignore Gradle GUI config 5 | gradle-app.setting 6 | 7 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 8 | !gradle-wrapper.jar 9 | 10 | # Cache of project 11 | .gradletasknamecache 12 | 13 | # # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 14 | # gradle/wrapper/gradle-wrapper.properties 15 | .idea 16 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.adoc: -------------------------------------------------------------------------------- 1 | = Contributor Code of Conduct 2 | 3 | As contributors and maintainers of this project, and in the interest of fostering an open 4 | and welcoming community, we pledge to respect all people who contribute through reporting 5 | issues, posting feature requests, updating documentation, submitting pull requests or 6 | patches, and other activities. 7 | 8 | We are committed to making participation in this project a harassment-free experience for 9 | everyone, regardless of level of experience, gender, gender identity and expression, 10 | sexual orientation, disability, personal appearance, body size, race, ethnicity, age, 11 | religion, or nationality. 12 | 13 | Examples of unacceptable behavior by participants include: 14 | 15 | * The use of sexualized language or imagery 16 | * Personal attacks 17 | * Trolling or insulting/derogatory comments 18 | * Public or private harassment 19 | * Publishing other's private information, such as physical or electronic addresses, 20 | without explicit permission 21 | * Other unethical or unprofessional conduct 22 | 23 | Project maintainers have the right and responsibility to remove, edit, or reject comments, 24 | commits, code, wiki edits, issues, and other contributions that are not aligned to this 25 | Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors 26 | that they deem inappropriate, threatening, offensive, or harmful. 27 | 28 | By adopting this Code of Conduct, project maintainers commit themselves to fairly and 29 | consistently applying these principles to every aspect of managing this project. Project 30 | maintainers who do not follow or enforce the Code of Conduct may be permanently removed 31 | from the project team. 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an 34 | individual is representing the project or its community. 35 | 36 | 37 | This Code of Conduct is adapted from the 38 | https://contributor-covenant.org[Contributor Covenant], version 1.3.0, available at 39 | https://contributor-covenant.org/version/1/3/0/[contributor-covenant.org/version/1/3/0/] and https://github.com/spring-projects/spring-boot/blob/master/CODE_OF_CONDUCT.adoc[spring-boot Contributor Code of Conduct] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # openapi-merger-plugin 2 | A plugin to merge OpenAPI-3 specification files into a single file <> 3 | 4 | what does the plugin do 5 | ------------------ 6 | 7 | Consider the following open api v3 schema files color.yaml and book.yaml 8 | 9 | color.yaml 10 | ```yaml 11 | openapi: 3.0.1 12 | info: 13 | title: OpenAPI definition 14 | version: v0 15 | servers: 16 | - url: http://localhost:8080 17 | description: Generated server url 18 | paths: 19 | /api/color/{name}: 20 | get: 21 | tags: 22 | - color-controller 23 | operationId: getColor 24 | parameters: 25 | - name: name 26 | in: path 27 | required: true 28 | schema: 29 | type: string 30 | responses: 31 | "200": 32 | description: OK 33 | content: 34 | '*/*': 35 | schema: 36 | $ref: '#/components/schemas/Color' 37 | components: 38 | schemas: 39 | Color: 40 | type: object 41 | properties: 42 | name: 43 | type: string 44 | red: 45 | type: integer 46 | format: int32 47 | green: 48 | type: integer 49 | format: int32 50 | blue: 51 | type: integer 52 | format: int32 53 | ``` 54 | 55 | book.yaml 56 | ```yaml 57 | openapi: 3.0.1 58 | info: 59 | title: OpenAPI definition 60 | version: v0 61 | servers: 62 | - url: http://localhost:8080 63 | description: Generated server url 64 | paths: 65 | /api/book/{name}: 66 | get: 67 | tags: 68 | - book-controller 69 | operationId: getBook 70 | parameters: 71 | - name: name 72 | in: path 73 | required: true 74 | schema: 75 | type: string 76 | responses: 77 | "200": 78 | description: OK 79 | content: 80 | '*/*': 81 | schema: 82 | $ref: '#/components/schemas/Book' 83 | components: 84 | schemas: 85 | Book: 86 | type: object 87 | properties: 88 | name: 89 | type: string 90 | iban: 91 | type: string 92 | ``` 93 | 94 | Using the plugin user can merge these files into a single file 95 | 96 | merged.yaml 97 | ```yaml 98 | openapi: 3.0.1 99 | info: 100 | title: My title 101 | version: 1.0.0-SNAPSHOT 102 | servers: 103 | - url: http://localhost:8080 104 | description: Generated server url 105 | paths: 106 | /api/book/{name}: 107 | get: 108 | tags: 109 | - book-controller 110 | operationId: getBook 111 | parameters: 112 | - name: name 113 | in: path 114 | required: true 115 | style: simple 116 | explode: false 117 | schema: 118 | type: string 119 | responses: 120 | "200": 121 | description: OK 122 | content: 123 | '*/*': 124 | schema: 125 | $ref: '#/components/schemas/Book' 126 | /api/color/{name}: 127 | get: 128 | tags: 129 | - color-controller 130 | operationId: getColor 131 | parameters: 132 | - name: name 133 | in: path 134 | required: true 135 | style: simple 136 | explode: false 137 | schema: 138 | type: string 139 | responses: 140 | "200": 141 | description: OK 142 | content: 143 | '*/*': 144 | schema: 145 | $ref: '#/components/schemas/Color' 146 | components: 147 | schemas: 148 | Book: 149 | type: object 150 | properties: 151 | name: 152 | type: string 153 | iban: 154 | type: string 155 | Color: 156 | type: object 157 | properties: 158 | name: 159 | type: string 160 | red: 161 | type: integer 162 | format: int32 163 | green: 164 | type: integer 165 | format: int32 166 | blue: 167 | type: integer 168 | format: int32 169 | ``` 170 | OpenAPI objects 171 | ---------------- 172 | 173 | [Root Objects Open API v3 Specification](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#openapi-object) 174 | 175 | The plugin will merge the following Root OpenAPI objects and all its sub object from the input files 176 | 177 | | S.NO | Field Name | 178 | |------|------------| 179 | | 1 | servers | 180 | | 2 | paths | 181 | | 3 | components | 182 | | 4 | security | 183 | | 5 | tags | 184 | 185 | The plugin will **ignore** following Root OpenAPI objects and all its sub object from the input files. 186 | 187 | | S.NO | Field Name | 188 | |------|--------------| 189 | | 1 | openapi | 190 | | 2 | info | 191 | | 3 | externalDocs | 192 | 193 | However, the plugin allows the user to configure the above object as input properties that will be placed in the merged file. 194 | 195 | Supported File formats 196 | ------------------- 197 | 1. json 198 | 2. yaml 199 | 200 | Plugin inputs 201 | ------------- 202 | The plugin expects a directory as input which can contain any number of openapi specification files. Input directory can contain both yaml and json open api specification files, and the plugin can process them all. 203 | 204 | Plugin outputs 205 | ------------- 206 | The plugin can output the merged file either in json or yaml format, but not both. 207 | 208 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | `maven-publish` 3 | kotlin("jvm") version "1.4.20" apply false 4 | id("net.researchgate.release") version "2.8.1" 5 | id("io.kotest") version "0.2.6" apply false 6 | id("org.jetbrains.dokka") version "1.4.10.2" apply false 7 | } 8 | 9 | val localRepository = "$buildDir/openapi-repo" 10 | 11 | allprojects { 12 | apply(plugin = "maven-publish") 13 | 14 | project.extra["localRepository"] = localRepository 15 | 16 | repositories { 17 | mavenCentral() 18 | jcenter() 19 | } 20 | 21 | publishing { 22 | repositories { 23 | maven { 24 | name = "central" 25 | gradle.taskGraph.whenReady { 26 | url = uri ( 27 | when { 28 | hasTask(":afterReleaseBuild") -> { 29 | val mavenCentralStagingUrl: String by project.extra 30 | mavenCentralStagingUrl 31 | } 32 | project.hasProperty("publishToCentral") && project.version.toString().contains("SNAPSHOT") -> { 33 | val mavenCentralSnapshotUrl: String by project.extra 34 | mavenCentralSnapshotUrl 35 | } 36 | else -> { 37 | "$buildDir/localRepo" 38 | } 39 | } 40 | ) 41 | if (hasTask(":afterReleaseBuild") || project.hasProperty("publishToCentral")) { 42 | val mavenCentralUsername: String by project.extra 43 | val mavenCentralPassword: String by project.extra 44 | credentials { 45 | username = mavenCentralUsername 46 | password = mavenCentralPassword 47 | } 48 | } 49 | } 50 | } 51 | maven { 52 | name = "local" 53 | url = uri(localRepository) 54 | } 55 | } 56 | } 57 | } 58 | 59 | subprojects { 60 | apply(plugin = "java") 61 | configure { 62 | sourceCompatibility = JavaVersion.VERSION_1_8 63 | targetCompatibility = JavaVersion.VERSION_1_8 64 | } 65 | } 66 | 67 | val publishMergerApp = project(":openapi-merger-app").tasks.named("publish") 68 | val publishGradlePlugin = project(":openapi-merger-gradle-plugin").tasks.named("publish") 69 | val publishMavenPlugin = project(":openapi-merger-maven-plugin").tasks.named("publish") 70 | val build by tasks.registering { 71 | dependsOn(publishMergerApp) 72 | dependsOn(publishGradlePlugin) 73 | dependsOn(publishMavenPlugin) 74 | } 75 | 76 | val afterReleaseBuild by tasks.existing { 77 | dependsOn(build) 78 | } 79 | project(":openapi-merger-gradle-plugin").afterEvaluate { 80 | afterReleaseBuild { 81 | dependsOn(project(":openapi-merger-gradle-plugin").tasks.named("publishPlugins")) 82 | } 83 | } 84 | 85 | val clean by tasks.registering(Delete::class) { 86 | delete = setOf(buildDir) 87 | } 88 | 89 | release { 90 | (getProperty("git") as net.researchgate.release.GitAdapter.GitConfig).apply { 91 | requireBranch = "main" 92 | } 93 | } -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | kotlin.code.style=official 2 | 3 | group=com.rameshkp 4 | version=1.0.6-SNAPSHOT 5 | 6 | # maven repositories 7 | mavenCentralSnapshotUrl=https://oss.sonatype.org/content/repositories/snapshots 8 | mavenCentralStagingUrl=https://oss.sonatype.org/service/local/staging/deploy/maven2 9 | 10 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kpramesh2212/openapi-merger-plugin/14171141a36c9f8d605de765e847b0c9d45b7c0f/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.9.3-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /openapi-merger-app/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | kotlin("jvm") 3 | `maven-publish` 4 | signing 5 | id("io.kotest") 6 | id("org.jetbrains.dokka") 7 | } 8 | 9 | java { 10 | withJavadocJar() 11 | withSourcesJar() 12 | } 13 | 14 | dependencies { 15 | implementation(kotlin(module = "stdlib")) 16 | implementation(group = "io.swagger.parser.v3", name = "swagger-parser", version = "2.0.23") 17 | implementation(group = "org.slf4j", name = "slf4j-api", version = "1.7.30") 18 | 19 | implementation(group = "javax.validation", name = "validation-api", version = "2.0.0.Final") 20 | runtimeOnly(group = "org.hibernate.validator", name = "hibernate-validator", version = "6.0.2.Final") 21 | runtimeOnly(group = "org.hibernate.validator", name = "hibernate-validator-annotation-processor", version = "6.0.2.Final") 22 | runtimeOnly(group = "javax.el", name = "javax.el-api", version = "3.0.0") 23 | runtimeOnly(group = "org.glassfish.web", name = "javax.el", version = "2.2.6") 24 | 25 | testImplementation(group = "io.kotest", name = "kotest-assertions-core-jvm", version = "4.3.1") 26 | testImplementation(group = "io.kotest", name = "kotest-framework-engine-jvm", version = "4.3.1") 27 | testImplementation(group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-core", version = "1.4.1") 28 | testImplementation(group = "io.mockk", name = "mockk", version = "1.12.2") 29 | 30 | } 31 | 32 | publishing { 33 | publications { 34 | create("openApiMergerApp") { 35 | from(components["java"]) 36 | 37 | pom { 38 | name.set("Open API V3 Merger Application") 39 | description.set("A Kotlin app to merge open api v3 specification files") 40 | url.set("https://github.com/kpramesh2212/openapi-merger-plugin") 41 | 42 | licenses { 43 | license { 44 | name.set("The Apache License, Version 2.0") 45 | url.set("http://www.apache.org/licenses/LICENSE-2.0.txt") 46 | } 47 | } 48 | 49 | developers { 50 | developer { 51 | id.set("rameshkp") 52 | name.set("Ramesh KP") 53 | email.set("kpramesh2212@gmail.com") 54 | } 55 | } 56 | scm { 57 | connection.set("scm:git:git://github.com:kpramesh2212/openapi-merger-plugin.git") 58 | developerConnection.set("scm:git:ssh://github.com:kpramesh2212/openapi-merger-plugin.git") 59 | url.set("https://github.com/kpramesh2212/openapi-merger-plugin") 60 | } 61 | 62 | } 63 | 64 | } 65 | } 66 | } 67 | 68 | tasks { 69 | compileKotlin { 70 | kotlinOptions.jvmTarget = "1.8" 71 | } 72 | compileTestKotlin { 73 | kotlinOptions.jvmTarget = "1.8" 74 | } 75 | } 76 | 77 | signing { 78 | sign(publishing.publications["openApiMergerApp"]) 79 | } 80 | 81 | val dokkaJavadoc by tasks.existing 82 | val javadocJar by tasks.existing(Jar::class) { 83 | dependsOn(dokkaJavadoc) 84 | from("$buildDir/dokka/javadoc") 85 | } -------------------------------------------------------------------------------- /openapi-merger-app/src/main/java/com/rameshkp/openapi/merger/app/utils/OpenAPIConverter.java: -------------------------------------------------------------------------------- 1 | package com.rameshkp.openapi.merger.app.utils; 2 | 3 | import com.fasterxml.jackson.core.JsonProcessingException; 4 | import io.swagger.v3.core.util.Json; 5 | import io.swagger.v3.core.util.Yaml; 6 | import io.swagger.v3.oas.models.OpenAPI; 7 | 8 | /** 9 | This is just a work around. 10 | Implementing the below methods in kotlin is causing a weired issue where json and yaml are not serialized properly 11 | */ 12 | public class OpenAPIConverter { 13 | /** 14 | * Provided an open api object this method converts it to a json string 15 | * @param openAPI object to convert 16 | * @return json string of the object 17 | * @throws JsonProcessingException when json parsing fails 18 | */ 19 | public static String toJson(OpenAPI openAPI) throws JsonProcessingException { 20 | return Json.pretty().writeValueAsString(openAPI); 21 | } 22 | 23 | /** 24 | * Provided an open api object this method converts it to a json string 25 | * @param openAPI object to convert 26 | * @return yaml string of the object 27 | * @throws JsonProcessingException when yaml parsing fails 28 | */ 29 | public static String toYaml(OpenAPI openAPI) throws JsonProcessingException { 30 | return Yaml.pretty().writeValueAsString(openAPI); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /openapi-merger-app/src/main/kotlin/com/rameshkp/openapi/merger/app/OpenApiMergerApp.kt: -------------------------------------------------------------------------------- 1 | package com.rameshkp.openapi.merger.app 2 | 3 | import com.rameshkp.openapi.merger.app.exceptions.OpenApiDataInvalidException 4 | import com.rameshkp.openapi.merger.app.mergers.OpenApiMerger 5 | import com.rameshkp.openapi.merger.app.models.OpenApi 6 | import com.rameshkp.openapi.merger.app.utils.OpenAPIConverter 7 | 8 | import io.swagger.v3.oas.models.ExternalDocumentation 9 | import io.swagger.v3.oas.models.info.Contact 10 | import io.swagger.v3.oas.models.info.Info 11 | import io.swagger.v3.oas.models.info.License 12 | import io.swagger.v3.oas.models.servers.Server 13 | import io.swagger.v3.parser.OpenAPIV3Parser 14 | import io.swagger.v3.parser.core.models.ParseOptions 15 | import org.slf4j.LoggerFactory 16 | import java.io.File 17 | import java.util.stream.Collectors 18 | import javax.validation.Validation 19 | 20 | /** 21 | * The class that helps in merging multiple open api v3 files into a single file 22 | */ 23 | class OpenApiMergerApp { 24 | private val log = LoggerFactory.getLogger(javaClass) 25 | private val validFileExtension = listOf("yaml", "json", "yml") 26 | private val parseOptions = ParseOptions() 27 | private val openApiMerger = OpenApiMerger() 28 | 29 | fun merge(inputDir: File, outputFile: File, openApi: OpenApi?) { 30 | validate(openApi) 31 | 32 | // Walk the input directory and merge all files into one 33 | inputDir.walk().filter { 34 | validFileExtension.contains(it.extension) 35 | }.sortedBy { 36 | it 37 | }.forEach { 38 | log.debug("Parsing OpenAPI file {}", it.absolutePath) 39 | parseOptions.isResolve = true 40 | val openAPI = OpenAPIV3Parser().read(it.absolutePath, null, parseOptions) 41 | openApiMerger.merge(openAPI) 42 | } 43 | 44 | // Convert the server object to open api server objects 45 | val servers = openApi!!.servers.map { 46 | val s = Server() 47 | s.url = it.url 48 | s.description = it.description 49 | s 50 | } 51 | 52 | // Set the relevant data for merged files 53 | val merged = openApiMerger.get() 54 | merged?.run { 55 | log.debug("Constructing the OpenApi model") 56 | // Set the openapi model object values to merged file 57 | openApi.let { openApiModel -> 58 | openapi = openApiModel.version 59 | // Set the info object 60 | info = openApiModel.info?.let { infoModelObj -> 61 | val info = Info() 62 | info.title = infoModelObj.title 63 | info.version = infoModelObj.version 64 | info.description = infoModelObj.description 65 | info.termsOfService = infoModelObj.termsOfService 66 | 67 | // set contact 68 | info.contact = infoModelObj.contact?.let { contactModelObj -> 69 | val contact = Contact() 70 | contact.url = contactModelObj.url 71 | contact.email = contactModelObj.email 72 | contact.name = contactModelObj.name 73 | contact 74 | } 75 | 76 | // Set license 77 | info.license = infoModelObj.license?.let { licenseModelObj -> 78 | val license = License() 79 | license.url = licenseModelObj.url 80 | license.name = licenseModelObj.name 81 | license 82 | } 83 | info 84 | } 85 | externalDocs = openApiModel.externalDocs?.let { externalDocsModelObj -> 86 | val externalDocs = ExternalDocumentation() 87 | externalDocs.url = externalDocsModelObj.url 88 | externalDocs.description = externalDocsModelObj.description 89 | externalDocs 90 | } 91 | 92 | if (servers.isNotEmpty()) { 93 | this.servers = servers 94 | } 95 | } 96 | 97 | // Get convert the object and get it as string 98 | val out = when(outputFile.extension) { 99 | "json" -> OpenAPIConverter.toJson(this) 100 | "yaml", "yml" -> OpenAPIConverter.toYaml(this) 101 | else -> "" 102 | } 103 | 104 | // Write it the output file 105 | log.debug("Writing the merged output file {}", outputFile.absolutePath) 106 | outputFile.writeText(out, Charsets.UTF_8) 107 | } 108 | } 109 | 110 | private fun validate(openApi: OpenApi?) { 111 | if (openApi == null) { 112 | throw OpenApiDataInvalidException("OpenApi Model parameter cannot be null.") 113 | } 114 | val validationFactory = Validation.buildDefaultValidatorFactory() 115 | val errorMessage = validationFactory.validator.validate(openApi) 116 | .stream() 117 | .map { a -> a.message} 118 | .collect(Collectors.joining("\n")) 119 | if (!errorMessage.isNullOrBlank()) { 120 | log.error("Validation error has occurred. errorMessage {}", errorMessage) 121 | throw OpenApiDataInvalidException(errorMessage) 122 | } 123 | } 124 | 125 | } -------------------------------------------------------------------------------- /openapi-merger-app/src/main/kotlin/com/rameshkp/openapi/merger/app/exceptions/OpenApiDataInvalidException.kt: -------------------------------------------------------------------------------- 1 | package com.rameshkp.openapi.merger.app.exceptions 2 | 3 | /** 4 | * An exception to denote when open api model data is invalid 5 | */ 6 | class OpenApiDataInvalidException(message: String): Exception(message) -------------------------------------------------------------------------------- /openapi-merger-app/src/main/kotlin/com/rameshkp/openapi/merger/app/mergers/ComponentsMerger.kt: -------------------------------------------------------------------------------- 1 | package com.rameshkp.openapi.merger.app.mergers 2 | 3 | import io.swagger.v3.oas.models.Components 4 | import io.swagger.v3.oas.models.callbacks.Callback 5 | import io.swagger.v3.oas.models.examples.Example 6 | import io.swagger.v3.oas.models.headers.Header 7 | import io.swagger.v3.oas.models.links.Link 8 | import io.swagger.v3.oas.models.media.Schema 9 | import io.swagger.v3.oas.models.parameters.Parameter 10 | import io.swagger.v3.oas.models.parameters.RequestBody 11 | import io.swagger.v3.oas.models.responses.ApiResponse 12 | import io.swagger.v3.oas.models.security.SecurityScheme 13 | 14 | /** 15 | * A class to merge open api Components object 16 | */ 17 | class ComponentsMerger: Mergeable { 18 | private val components = Components() 19 | 20 | private val schemasMerger = MapMerger>() 21 | private val responsesMerger = MapMerger() 22 | private val parametersMerger = MapMerger() 23 | private val examplesMerger = MapMerger() 24 | private val requestBodiesMerger = MapMerger() 25 | private val headersMerger = MapMerger
() 26 | private val securitySchemasMerger = MapMerger() 27 | private val linksMerger = MapMerger() 28 | private val callbacksMerger = MapMerger() 29 | 30 | override fun merge(from: Components?) { 31 | from?.run { 32 | schemasMerger.merge(this.schemas) 33 | responsesMerger.merge(this.responses) 34 | parametersMerger.merge(this.parameters) 35 | examplesMerger.merge(this.examples) 36 | requestBodiesMerger.merge(this.requestBodies) 37 | headersMerger.merge(this.headers) 38 | securitySchemasMerger.merge(this.securitySchemes) 39 | linksMerger.merge(this.links) 40 | callbacksMerger.merge(this.callbacks) 41 | } 42 | } 43 | 44 | override fun get(): Components? { 45 | components.schemas = schemasMerger.get() 46 | components.responses = responsesMerger.get() 47 | components.parameters = parametersMerger.get() 48 | components.examples = examplesMerger.get() 49 | components.requestBodies = requestBodiesMerger.get() 50 | components.headers = headersMerger.get() 51 | components.securitySchemes = securitySchemasMerger.get() 52 | components.links = linksMerger.get() 53 | components.callbacks = callbacksMerger.get() 54 | return components 55 | } 56 | } -------------------------------------------------------------------------------- /openapi-merger-app/src/main/kotlin/com/rameshkp/openapi/merger/app/mergers/ListMerger.kt: -------------------------------------------------------------------------------- 1 | package com.rameshkp.openapi.merger.app.mergers 2 | 3 | import org.slf4j.LoggerFactory 4 | 5 | /** 6 | * A class to merge a list of components of type T 7 | */ 8 | class ListMerger: Mergeable> { 9 | private val log = LoggerFactory.getLogger(javaClass) 10 | private val list = ArrayList() 11 | 12 | override fun merge(from: List?) { 13 | from?.run { 14 | forEach { t -> 15 | if (list.contains(t)) { 16 | log.warn("List already contains {}. Hence Skipping", t) 17 | } else { 18 | list.add(t) 19 | } 20 | } 21 | } 22 | } 23 | 24 | override fun get(): List? { 25 | return if (list.size > 0) list else null 26 | } 27 | } -------------------------------------------------------------------------------- /openapi-merger-app/src/main/kotlin/com/rameshkp/openapi/merger/app/mergers/MapMerger.kt: -------------------------------------------------------------------------------- 1 | package com.rameshkp.openapi.merger.app.mergers 2 | 3 | import org.slf4j.LoggerFactory 4 | import java.util.* 5 | 6 | /** 7 | * A class to merge a Map with string keys and value T 8 | */ 9 | open class MapMerger: Mergeable> { 10 | private val log = LoggerFactory.getLogger(javaClass) 11 | protected val map = TreeMap() 12 | 13 | override fun merge(from: Map?) { 14 | from?.run { 15 | forEach { entry -> 16 | if (map.containsKey(entry.key)) { 17 | whenKeyExists(entry.key, entry.value) 18 | } else { 19 | map[entry.key] = entry.value 20 | } 21 | } 22 | } 23 | } 24 | 25 | open fun whenKeyExists(key: String, value: T) { 26 | log.warn("{} already exist in the map. Hence skipping", key) 27 | } 28 | 29 | override fun get(): Map? { 30 | return if (map.size > 0) map else null 31 | } 32 | } -------------------------------------------------------------------------------- /openapi-merger-app/src/main/kotlin/com/rameshkp/openapi/merger/app/mergers/Mergeable.kt: -------------------------------------------------------------------------------- 1 | package com.rameshkp.openapi.merger.app.mergers 2 | 3 | /** 4 | * Interface that can merge objects of type T 5 | */ 6 | interface Mergeable { 7 | /** 8 | * A method to merge an object of type T 9 | */ 10 | fun merge(from: T?) 11 | 12 | /** 13 | * Return the merged object of type T 14 | */ 15 | fun get(): T? 16 | } 17 | -------------------------------------------------------------------------------- /openapi-merger-app/src/main/kotlin/com/rameshkp/openapi/merger/app/mergers/OpenApiMerger.kt: -------------------------------------------------------------------------------- 1 | package com.rameshkp.openapi.merger.app.mergers 2 | 3 | import io.swagger.v3.oas.models.OpenAPI 4 | import io.swagger.v3.oas.models.security.SecurityRequirement 5 | import io.swagger.v3.oas.models.servers.Server 6 | import io.swagger.v3.oas.models.tags.Tag 7 | import org.slf4j.LoggerFactory 8 | 9 | /** 10 | * A class to merge open api object 11 | */ 12 | class OpenApiMerger: Mergeable { 13 | private val log = LoggerFactory.getLogger(javaClass) 14 | private val openAPI = OpenAPI() 15 | 16 | private val serversMerger = ListMerger() 17 | private val tagsMerger = ListMerger() 18 | private val securityMerger = ListMerger() 19 | private val pathsMerger = PathsMerger() 20 | private val componentsMerger = ComponentsMerger() 21 | 22 | override fun merge(from: OpenAPI?) { 23 | from?.run { 24 | // Merge the server 25 | log.info("Merging servers") 26 | serversMerger.merge(this.servers) 27 | 28 | // Merge the paths 29 | log.info("Merging paths") 30 | pathsMerger.merge(this.paths) 31 | 32 | // Merge the components 33 | log.info("Merging components") 34 | componentsMerger.merge(this.components) 35 | 36 | // Merge security 37 | log.info("Merging Security") 38 | securityMerger.merge(this.security) 39 | 40 | // Merge tags 41 | log.info("Merging tags") 42 | tagsMerger.merge(this.tags) 43 | } 44 | } 45 | 46 | override fun get(): OpenAPI? { 47 | openAPI.servers = serversMerger.get() 48 | openAPI.paths = pathsMerger.get() 49 | openAPI.components = componentsMerger.get() 50 | openAPI.security = securityMerger.get() 51 | openAPI.tags = tagsMerger.get() 52 | return openAPI 53 | } 54 | } -------------------------------------------------------------------------------- /openapi-merger-app/src/main/kotlin/com/rameshkp/openapi/merger/app/mergers/PathItemMerger.kt: -------------------------------------------------------------------------------- 1 | package com.rameshkp.openapi.merger.app.mergers 2 | 3 | import io.swagger.v3.oas.models.PathItem 4 | import org.slf4j.LoggerFactory 5 | 6 | class PathItemMerger(private val path: String, private val pathItem: PathItem): Mergeable { 7 | private val log = LoggerFactory.getLogger(javaClass) 8 | 9 | override fun merge(from: PathItem?) { 10 | from?.apply { 11 | pathItem.setIfMissing("description", { pathItem -> pathItem.description}, { pathItem -> pathItem.description = description }) 12 | pathItem.setIfMissing("summary", { pathItem -> pathItem.summary}, { pathItem -> pathItem.summary = summary }) 13 | pathItem.setIfMissing("get", { pathItem -> pathItem.get}, { pathItem -> pathItem.get = get }) 14 | pathItem.setIfMissing("put", { pathItem -> pathItem.put}, { pathItem -> pathItem.put = put }) 15 | pathItem.setIfMissing("post", { pathItem -> pathItem.post}, { pathItem -> pathItem.post = post }) 16 | pathItem.setIfMissing("delete", { pathItem -> pathItem.delete}, { pathItem -> pathItem.delete = delete }) 17 | pathItem.setIfMissing("options", { pathItem -> pathItem.options}, { pathItem -> pathItem.options = options }) 18 | pathItem.setIfMissing("head", { pathItem -> pathItem.head}, { pathItem -> pathItem.head = head }) 19 | pathItem.setIfMissing("patch", { pathItem -> pathItem.patch}, { pathItem -> pathItem.patch = patch }) 20 | pathItem.setIfMissing("trace", { pathItem -> pathItem.trace}, { pathItem -> pathItem.trace = trace }) 21 | pathItem.setIfMissing("servers", { pathItem -> pathItem.servers}, { pathItem -> pathItem.servers = servers }) 22 | pathItem.setIfMissing("parameters", { pathItem -> pathItem.parameters}, { pathItem -> pathItem.parameters = parameters }) 23 | pathItem.setIfMissing("ref", { pathItem -> pathItem.`$ref`}, { pathItem -> pathItem.`$ref` = `$ref` }) 24 | pathItem.setIfMissing("extensions", { pathItem -> pathItem.extensions}, { pathItem -> pathItem.extensions = extensions }) 25 | } 26 | } 27 | 28 | override fun get(): PathItem { 29 | return pathItem 30 | } 31 | 32 | private fun PathItem.setIfMissing(propertyName: String, getProperty: (pathItem: PathItem) -> T?, setProperty: (pathItem: PathItem) -> Unit) { 33 | val property = getProperty(this) 34 | if (property != null) log.warn("{} in path item for path {} already exists. Hence skipping", propertyName, path) else setProperty(this) 35 | } 36 | 37 | } -------------------------------------------------------------------------------- /openapi-merger-app/src/main/kotlin/com/rameshkp/openapi/merger/app/mergers/PathsMerger.kt: -------------------------------------------------------------------------------- 1 | package com.rameshkp.openapi.merger.app.mergers 2 | 3 | import io.swagger.v3.oas.models.PathItem 4 | import io.swagger.v3.oas.models.Paths 5 | 6 | class PathsMerger: MapMerger() { 7 | override fun whenKeyExists(key: String, value: PathItem) { 8 | val existingPathItem = map.getValue(key) 9 | PathItemMerger(key, existingPathItem).merge(value) 10 | } 11 | 12 | override fun get(): Paths { 13 | val path = Paths() 14 | map.forEach { (key, value) -> path.addPathItem(key, value)} 15 | return path 16 | } 17 | } -------------------------------------------------------------------------------- /openapi-merger-app/src/main/kotlin/com/rameshkp/openapi/merger/app/models/Contact.kt: -------------------------------------------------------------------------------- 1 | package com.rameshkp.openapi.merger.app.models 2 | 3 | data class Contact(var name: String? = null, var url: String? = null, var email: String? = null) -------------------------------------------------------------------------------- /openapi-merger-app/src/main/kotlin/com/rameshkp/openapi/merger/app/models/ExternalDocs.kt: -------------------------------------------------------------------------------- 1 | package com.rameshkp.openapi.merger.app.models 2 | 3 | import javax.validation.constraints.NotBlank 4 | 5 | data class ExternalDocs(@field:NotBlank(message = "ExternalDocs Url cannot be blank") var url: String? = null, var description: String? = null) -------------------------------------------------------------------------------- /openapi-merger-app/src/main/kotlin/com/rameshkp/openapi/merger/app/models/Info.kt: -------------------------------------------------------------------------------- 1 | package com.rameshkp.openapi.merger.app.models 2 | 3 | import javax.validation.Valid 4 | import javax.validation.constraints.NotBlank 5 | 6 | data class Info(@field:NotBlank(message = "OpenApi Info Title cannot be blank") var title: String? = null, 7 | var description: String? = null, 8 | var termsOfService: String? = null, 9 | @field:NotBlank(message = "OpenApi Info Version cannot be blank") var version: String? = null, 10 | var contact: Contact? = null, 11 | @field:Valid var license: License? = null) -------------------------------------------------------------------------------- /openapi-merger-app/src/main/kotlin/com/rameshkp/openapi/merger/app/models/License.kt: -------------------------------------------------------------------------------- 1 | package com.rameshkp.openapi.merger.app.models 2 | 3 | import javax.validation.constraints.NotBlank 4 | 5 | data class License(@field:NotBlank(message = "License name cannot be blank") var name: String? = null, var url: String? = null) -------------------------------------------------------------------------------- /openapi-merger-app/src/main/kotlin/com/rameshkp/openapi/merger/app/models/OpenApi.kt: -------------------------------------------------------------------------------- 1 | package com.rameshkp.openapi.merger.app.models 2 | 3 | import javax.validation.Valid 4 | import javax.validation.constraints.NotBlank 5 | import javax.validation.constraints.NotNull 6 | 7 | data class OpenApi(@field:NotBlank(message = "OpenApi version cannot be blank") var version: String? = null, 8 | @field:NotNull(message = "OpenApi Info object cannot be null") @field:Valid var info: Info? = null, 9 | @field:Valid var externalDocs: ExternalDocs? = null, @field:Valid var servers: List = emptyList()) -------------------------------------------------------------------------------- /openapi-merger-app/src/main/kotlin/com/rameshkp/openapi/merger/app/models/Server.kt: -------------------------------------------------------------------------------- 1 | package com.rameshkp.openapi.merger.app.models 2 | 3 | import javax.validation.constraints.NotBlank 4 | 5 | data class Server(@field:NotBlank(message = "server url cannot be blank") var url: String? = null, var description: String? = null) -------------------------------------------------------------------------------- /openapi-merger-app/src/test/kotlin/com/rameshkp/openapi/merger/app/OpenApiMergerAppTest.kt: -------------------------------------------------------------------------------- 1 | package com.rameshkp.openapi.merger.app 2 | 3 | import com.rameshkp.openapi.merger.app.exceptions.OpenApiDataInvalidException 4 | import com.rameshkp.openapi.merger.app.models.* 5 | import io.kotest.assertions.throwables.shouldThrow 6 | import io.kotest.core.spec.style.BehaviorSpec 7 | import io.kotest.matchers.shouldBe 8 | import io.kotest.matchers.string.shouldContain 9 | 10 | 11 | internal class OpenApiMergerAppTest: BehaviorSpec({ 12 | val openApiMergerApp = OpenApiMergerApp() 13 | val inputDir = createTempDir(suffix = "input") 14 | val outputDir = createTempDir(suffix = "output") 15 | 16 | given("An open api object") { 17 | `when`("Its null") { 18 | then("should throw OpenApiDataInvalidException") { 19 | val e = shouldThrow { 20 | openApiMergerApp.merge(inputDir, outputDir, null) 21 | } 22 | e.message shouldBe "OpenApi Model parameter cannot be null." 23 | } 24 | } 25 | 26 | `when`("Info object is absent") { 27 | then("should throw OpenApiDataInvalidationException") { 28 | val e = shouldThrow { 29 | openApiMergerApp.merge(inputDir, outputDir, OpenApi()) 30 | } 31 | e.message shouldContain "OpenApi Info object cannot be null" 32 | } 33 | } 34 | 35 | `when`("All sub-objects not null and all fields null") { 36 | then("should throw OpenApiDataInvalidationException") { 37 | val openApi = OpenApi() 38 | val info = Info() 39 | openApi.info = info 40 | openApi.externalDocs = ExternalDocs() 41 | info.contact = Contact() 42 | info.license = License() 43 | 44 | val e = shouldThrow { 45 | openApiMergerApp.merge(inputDir, outputDir, openApi) 46 | } 47 | e.message shouldContain "OpenApi Info Version cannot be blank" 48 | e.message shouldContain "OpenApi Info Title cannot be blank" 49 | e.message shouldContain "OpenApi version cannot be blank" 50 | e.message shouldContain "License name cannot be blank" 51 | e.message shouldContain "ExternalDocs Url cannot be blank" 52 | } 53 | } 54 | 55 | `when`("Info object is present") { 56 | val openApi = OpenApi() 57 | openApi.version = "3.0.3" 58 | 59 | and("all fields are null") { 60 | then("should throw OpenApiDataInvalidationException") { 61 | openApi.info = Info() 62 | val e = shouldThrow { 63 | openApiMergerApp.merge(inputDir, outputDir, openApi) 64 | } 65 | e.message shouldContain "OpenApi Info Version cannot be blank" 66 | e.message shouldContain "OpenApi Info Title cannot be blank" 67 | } 68 | } 69 | 70 | and("title is null") { 71 | then("should throw OpenApiDataInvalidationException") { 72 | val info = Info() 73 | openApi.info = info 74 | info.version = "3.3.3" 75 | val e = shouldThrow { 76 | openApiMergerApp.merge(inputDir, outputDir, openApi) 77 | } 78 | e.message shouldBe "OpenApi Info Title cannot be blank" 79 | } 80 | } 81 | 82 | and("version is null") { 83 | then("should throw OpenApiDataInvalidationException") { 84 | val info = Info() 85 | openApi.info = info 86 | info.title = "A valid title" 87 | val e = shouldThrow { 88 | openApiMergerApp.merge(inputDir, outputDir, openApi) 89 | } 90 | e.message shouldBe "OpenApi Info Version cannot be blank" 91 | } 92 | } 93 | } 94 | 95 | } 96 | }) -------------------------------------------------------------------------------- /openapi-merger-app/src/test/kotlin/com/rameshkp/openapi/merger/app/mergers/PathItemMergerTest.kt: -------------------------------------------------------------------------------- 1 | package com.rameshkp.openapi.merger.app.mergers 2 | 3 | import io.kotest.core.spec.style.BehaviorSpec 4 | import io.kotest.matchers.shouldBe 5 | import io.kotest.matchers.shouldNotBe 6 | import io.mockk.mockk 7 | import io.swagger.v3.oas.models.PathItem 8 | 9 | class PathItemMergerTest: BehaviorSpec({ 10 | given("for a path /a with 2 path items p1 and p2") { 11 | val path = "/a" 12 | val p1 = PathItem() 13 | p1.description = "p1 description" 14 | p1.get = mockk() 15 | val p2 = PathItem() 16 | p2.description = "p2 description" 17 | p2.post = mockk() 18 | 19 | `when`("PathMerger('/a', p1).merge(p2)") { 20 | PathItemMerger(path, p1).merge(p2) 21 | 22 | then("all non null property value of p1 should not be replaced") { 23 | p1.description shouldBe "p1 description" 24 | } 25 | then("all null property value of p1 should be replaced with corresponding p2 property value") { 26 | p1.post shouldNotBe null 27 | } 28 | } 29 | } 30 | }) -------------------------------------------------------------------------------- /openapi-merger-app/src/test/kotlin/com/rameshkp/openapi/merger/app/mergers/PathsMergerTest.kt: -------------------------------------------------------------------------------- 1 | package com.rameshkp.openapi.merger.app.mergers 2 | 3 | import io.kotest.core.spec.style.BehaviorSpec 4 | import io.kotest.matchers.shouldBe 5 | import io.kotest.matchers.shouldNotBe 6 | import io.mockk.mockk 7 | import io.swagger.v3.oas.models.PathItem 8 | import io.swagger.v3.oas.models.Paths 9 | 10 | internal class PathsMergerTest : BehaviorSpec({ 11 | given("2 paths object with same name and with same scheme") { 12 | `when`("merged using paths merger") { 13 | then("the result should contain one paths object with 1 schema") { 14 | val paths1 = Paths() 15 | val paths2 = Paths() 16 | 17 | val pathItem1 = PathItem() 18 | pathItem1.get = mockk() 19 | val pathItem2 = PathItem() 20 | pathItem1.get = mockk() 21 | 22 | paths1["/a"] = pathItem1 23 | paths2["/a"] = pathItem2 24 | 25 | 26 | val pathMerger = PathsMerger() 27 | pathMerger.merge(paths1) 28 | pathMerger.merge(paths2) 29 | 30 | val path = pathMerger.get() 31 | path.size shouldBe 1 32 | path["/a"] shouldNotBe null 33 | path["/a"]?.get shouldNotBe null 34 | } 35 | } 36 | } 37 | given("2 paths object with same name and with different schema") { 38 | `when`("merged using path merger") { 39 | then("the result should contain one paths object with 2 schema") { 40 | val paths1 = Paths() 41 | val paths2 = Paths() 42 | 43 | val pathItem1 = PathItem() 44 | pathItem1.get = mockk() 45 | val pathItem2 = PathItem() 46 | pathItem1.post = mockk() 47 | 48 | paths1["/a"] = pathItem1 49 | paths2["/a"] = pathItem2 50 | 51 | 52 | val pathMerger = PathsMerger() 53 | pathMerger.merge(paths1) 54 | pathMerger.merge(paths2) 55 | 56 | val path = pathMerger.get() 57 | path.size shouldBe 1 58 | path["/a"] shouldNotBe null 59 | path["/a"]?.get shouldNotBe null 60 | path["/a"]?.post shouldNotBe null 61 | } 62 | } 63 | } 64 | }) -------------------------------------------------------------------------------- /openapi-merger-app/src/test/kotlin/com/rameshkp/openapi/merger/app/models/ServerTest.kt: -------------------------------------------------------------------------------- 1 | package com.rameshkp.openapi.merger.app.models 2 | 3 | import io.kotest.core.spec.style.BehaviorSpec 4 | import io.kotest.matchers.ints.shouldBeExactly 5 | import io.kotest.matchers.shouldBe 6 | import javax.validation.Validation 7 | 8 | 9 | internal class ServerTest: BehaviorSpec({ 10 | val validator = Validation.buildDefaultValidatorFactory().validator 11 | 12 | given("A server object") { 13 | val server = Server() 14 | `when`("url is null") { 15 | then("constraint validation should fail") { 16 | val constraints = validator.validate(server) 17 | constraints.size shouldBeExactly 1 18 | constraints.first().message shouldBe "server url cannot be blank" 19 | } 20 | } 21 | `when`("description is null and url is not null") { 22 | then("constraint validation should pass") { 23 | server.url = "http://localhost:8080" 24 | val constraints = validator.validate(server) 25 | constraints.size shouldBeExactly 0 26 | } 27 | } 28 | } 29 | }) -------------------------------------------------------------------------------- /openapi-merger-gradle-plugin/README.md: -------------------------------------------------------------------------------- 1 | # **Introduction to openapi-merger-gradle-plugin** 2 | 3 | Open API Merger Gradle Plugin - Merges multiple OpenAPI-3 specification file into a single file. 4 | 5 | This Gradle plugin provides the capability to merge multiple open api v3 specification file into a single file from a Gradle build. 6 | 7 | Compatibility Notes 8 | ------------------- 9 | 10 | The plugin is build on gradle version 6.9.3 11 | 12 | The Java version used to compile the plugin 1.8 13 | 14 | How To Use 15 | ---------- 16 | 17 | Gradle Groovy DSL 18 | 19 | ```groovy 20 | plugins { 21 | id "com.rameshkp.openapi-merger-gradle-plugin" version "1.0.5" 22 | } 23 | ``` 24 | 25 | Gradle Kotlin DSL 26 | ```kotlin 27 | plugins { 28 | id("com.rameshkp.openapi-merger-gradle-plugin") version "1.0.5" 29 | } 30 | ``` 31 | 32 | Note: For latest versions of the plugins please check the gradle plugin portal 33 | 34 | What does this plugin do 35 | ----------------------- 36 | 37 | [open api merger plugin readme](https://github.com/kpramesh2212/openapi-merger-plugin/blob/main/README.md) 38 | 39 | How the plugin works 40 | ------------ 41 | 42 | When the user adds this plugin to their build file 43 | 44 | The plugin creates a task and an extension 45 | 46 | 1. mergeOpenApiFiles - Task 47 | 48 | 2. openApiMerger - Extension 49 | 50 | Running the task mergeOpenApiFiles will merge multiple openapi v3 files into a single file 51 | 52 | ```bash 53 | gradle mergeOpenApiFiles 54 | ``` 55 | 56 | Using openApiMerger extension users can perform customization as explained below 57 | 58 | Customization 59 | ------------- 60 | 61 | The following customizations can be done on the task mergeOpenApiFiles using extension openApiMerger as follows 62 | 63 | ```kotlin 64 | openApiMerger { 65 | inputDirectory.set(file("openapi-files")) 66 | 67 | output { 68 | directory.set(buildDir) 69 | fileName.set("openapi") 70 | fileExtension.set("json") 71 | } 72 | 73 | openApi { 74 | openApiVersion.set("3.0.1") 75 | info { 76 | title.set("Open API Merger") 77 | description.set("All files merged by open api merger") 78 | version.set("1.0.0-SNAPSHOT") 79 | termsOfService.set("https://openapimerger.com/terms-of-service") 80 | contact { 81 | name.set("OpenApiMerger Team") 82 | email.set("openapi@sample.com") 83 | url.set("https://openapimerger.com") 84 | } 85 | license { 86 | name.set("Apache License v2.0") 87 | url.set("https://apache.org/v2") 88 | } 89 | } 90 | externalDocs { 91 | description.set("External docs description") 92 | url.set("https://external-docs.com/uri") 93 | } 94 | servers { 95 | register("production") { 96 | url.set("https://prod.com:9090") 97 | description.set("production environment") 98 | } 99 | register("testing") { 100 | url.set("https://localhost:8080") 101 | description.set("test environment") 102 | } 103 | } 104 | } 105 | } 106 | ``` 107 | #### openApiMerger block 108 | | Parameter | Description | Required | Default | 109 | |------------------|----------------------------------------------------------------------------------------------------------------------------------------|----------|--------------------| 110 | | `inputDirectory` | The input directory containing the openapi v3 specification files. The input directory can contain files in both yaml and json format. | Yes | N/A | 111 | | `output(Block)` | The output block is used to customize the output of the open api merger plugin | No | Check output block | 112 | | `openApi(Block)` | The openApi block is used to customize the common openApi object for the merged file. | Yes | N/A | 113 | 114 | #### output block 115 | | Parameter | Description | Required | Default | 116 | |-----------------|--------------------------------------------------------------------------|----------|-----------------| 117 | | `directory` | The output directory to place the merged open api v3 specification file. | No | build/open-api/ | 118 | | `fileName` | Name of the merged output openapi v3 specification file | No | openapi | 119 | | `fileExtension` | The format of the output. Can either be one of yaml or json | No | yaml | 120 | 121 | #### openApi block 122 | | Parameter | Description | Required | Default | 123 | |-----------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------|---------| 124 | | `openApiVersion` | The version of open api. | Yes | N/A | 125 | | `info(block)` | [See Info object in open api v3 specification for explanation](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#info-object) | Yes | N/A | 126 | | `externalDocs(block)` | [See External Documentation object in open api v3 specification for explanation](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#external-documentation-object) | No | null | 127 | 128 | #### info block 129 | | Parameter | Description | Required | Default | 130 | |------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------|----------|---------| 131 | | `title` | The title of the API. | Yes | N/A | 132 | | `description` | A short description of the API | No | null | 133 | | `termsOfService` | URL to the Terms of Service for the API | No | null | 134 | | `version` | The version of the OpenAPI document | Yes | N/A | 135 | | `contact(block)` | [See Contact object in open api v3 specification for explanation](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#contact-object) | No | null | 136 | | `license(block)` | [See License object in open api v3 specification for explanation](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#licenseObject) | No | null | 137 | 138 | #### contact block 139 | | Parameter | Description | Required | Default | 140 | |-----------|--------------------------------------------------------------------------------------------------|----------|---------| 141 | | `name` | The identifying name of the contact person/organization. | No | null | 142 | | `url` | The URL pointing to the contact information. MUST be in the format of a URL. | No | null | 143 | | `email` | The email address of the contact person/organization. MUST be in the format of an email address. | No | null | 144 | 145 | #### license block 146 | | Parameter | Description | Required | Default | 147 | |-----------|------------------------------------------------------------------------|----------|---------| 148 | | `name` | The license name used for the API. | Yes | N/A | 149 | | `url` | A URL to the license used for the API. MUST be in the format of a URL. | No | null | 150 | 151 | #### externalDocs block 152 | | Parameter | Description | Required | Default | 153 | |---------------|-----------------------------------------------------------------------|----------|---------| 154 | | `description` | A short description of the target documentation. | No | null | 155 | | `url` | The URL for the target documentation. MUST be in the format of a URL. | Yes | N/A | 156 | 157 | #### servers block 158 | A list of server blocks 159 | 160 | #### server block 161 | | Parameter | Description | Required | Default | 162 | |---------------|---------------------------------------------------------|----------|---------| 163 | | `description` | A short description of the server. | No | null | 164 | | `url` | The URL for the server. MUST be in the format of a URL. | Yes | N/A | 165 | 166 | # Building the plugin 167 | 168 | TODO -------------------------------------------------------------------------------- /openapi-merger-gradle-plugin/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | `java-gradle-plugin` 3 | kotlin("jvm") 4 | `maven-publish` 5 | id("io.kotest") 6 | id("com.gradle.plugin-publish") version "0.12.0" 7 | id("org.jetbrains.dokka") 8 | signing 9 | } 10 | 11 | java { 12 | withJavadocJar() 13 | withSourcesJar() 14 | } 15 | 16 | dependencies { 17 | implementation(kotlin(module = "stdlib")) 18 | implementation(project(":openapi-merger-app")) 19 | 20 | testImplementation(group = "io.kotest", name = "kotest-assertions-core-jvm", version = "4.3.1") 21 | testImplementation(group = "io.kotest", name = "kotest-framework-engine-jvm", version = "4.3.1") 22 | testImplementation(group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-core", version = "1.4.1") 23 | } 24 | 25 | pluginBundle { 26 | website = "https://github.com/kpramesh2212/openapi-merger-plugin" 27 | vcsUrl = "https://github.com/kpramesh2212/openapi-merger-plugin.git" 28 | tags = listOf("openapi-3.0", "merger") 29 | } 30 | 31 | gradlePlugin { 32 | plugins { 33 | create("openapi-merger-gradle-plugin") { 34 | id = "com.rameshkp.openapi-merger-gradle-plugin" 35 | displayName = "OpenAPI 3 merger gradle plugin" 36 | description = "A gradle plugin to merge multiple openapi files" 37 | implementationClass = "com.rameshkp.openapi.merger.gradle.plugin.OpenApiMergerGradlePlugin" 38 | } 39 | } 40 | } 41 | 42 | tasks { 43 | compileKotlin { 44 | kotlinOptions.jvmTarget = "1.8" 45 | } 46 | compileTestKotlin { 47 | kotlinOptions.jvmTarget = "1.8" 48 | } 49 | } 50 | val dokkaJavadoc by tasks.existing 51 | val javadocJar by tasks.existing(Jar::class) { 52 | dependsOn(dokkaJavadoc) 53 | from("$buildDir/dokka/javadoc") 54 | } 55 | project.afterEvaluate { 56 | val publishPluginJavaDocsJar by tasks.existing(Jar::class) { 57 | dependsOn(dokkaJavadoc) 58 | from("$buildDir/dokka/javadoc") 59 | } 60 | } 61 | 62 | afterEvaluate { 63 | signing { 64 | sign(publishing.publications["pluginMaven"]) 65 | sign(publishing.publications["openapi-merger-gradle-pluginPluginMarkerMaven"]) 66 | } 67 | 68 | publishing { 69 | publications { 70 | named("pluginMaven") { 71 | setPomDetails(this) 72 | } 73 | named("openapi-merger-gradle-pluginPluginMarkerMaven") { 74 | setPomDetails(this) 75 | } 76 | } 77 | } 78 | } 79 | 80 | fun setPomDetails(mavenPublication: MavenPublication) { 81 | mavenPublication.pom { 82 | name.set("Open API V3 Merger gradle plugin") 83 | description.set("A gradle plugin to merge open api v3 specification files") 84 | url.set("https://github.com/kpramesh2212/openapi-merger-plugin") 85 | 86 | licenses { 87 | license { 88 | name.set("The Apache License, Version 2.0") 89 | url.set("http://www.apache.org/licenses/LICENSE-2.0.txt") 90 | } 91 | } 92 | 93 | developers { 94 | developer { 95 | id.set("rameshkp") 96 | name.set("Ramesh KP") 97 | email.set("kpramesh2212@gmail.com") 98 | } 99 | } 100 | scm { 101 | connection.set("git@github.com:kpramesh2212/openapi-merger-plugin.git") 102 | developerConnection.set("git@github.com:kpramesh2212/openapi-merger-plugin.git") 103 | url.set("https://github.com/kpramesh2212/openapi-merger-plugin") 104 | } 105 | } 106 | } -------------------------------------------------------------------------------- /openapi-merger-gradle-plugin/src/main/kotlin/com/rameshkp/openapi/merger/gradle/extensions/ContactExtension.kt: -------------------------------------------------------------------------------- 1 | package com.rameshkp.openapi.merger.gradle.extensions 2 | 3 | import org.gradle.api.model.ObjectFactory 4 | import org.gradle.api.provider.Property 5 | import javax.inject.Inject 6 | 7 | /** 8 | * An extension class for contact 9 | */ 10 | open class ContactExtension @Inject constructor(objectFactory: ObjectFactory) { 11 | val name: Property = objectFactory.property(String::class.java) 12 | val url: Property = objectFactory.property(String::class.java) 13 | val email: Property = objectFactory.property(String::class.java) 14 | } -------------------------------------------------------------------------------- /openapi-merger-gradle-plugin/src/main/kotlin/com/rameshkp/openapi/merger/gradle/extensions/ExternalDocsExtension.kt: -------------------------------------------------------------------------------- 1 | package com.rameshkp.openapi.merger.gradle.extensions 2 | 3 | import org.gradle.api.model.ObjectFactory 4 | import org.gradle.api.provider.Property 5 | import javax.inject.Inject 6 | 7 | /** 8 | * An extension class for External docs 9 | */ 10 | open class ExternalDocsExtension @Inject constructor(objectFactory: ObjectFactory) { 11 | val url: Property = objectFactory.property(String::class.java) 12 | val description: Property = objectFactory.property(String::class.java) 13 | } -------------------------------------------------------------------------------- /openapi-merger-gradle-plugin/src/main/kotlin/com/rameshkp/openapi/merger/gradle/extensions/InfoExtension.kt: -------------------------------------------------------------------------------- 1 | package com.rameshkp.openapi.merger.gradle.extensions 2 | 3 | import org.gradle.api.Action 4 | import org.gradle.api.model.ObjectFactory 5 | import org.gradle.api.provider.Property 6 | import javax.inject.Inject 7 | 8 | /** 9 | * An extension class for Info class 10 | */ 11 | open class InfoExtension @Inject constructor(objectFactory: ObjectFactory) { 12 | val title: Property = objectFactory.property(String::class.java) 13 | val description: Property = objectFactory.property(String::class.java) 14 | val termsOfService: Property = objectFactory.property(String::class.java) 15 | val version: Property = objectFactory.property(String::class.java) 16 | internal val contact: ContactExtension = objectFactory.newInstance(ContactExtension::class.java, objectFactory) 17 | internal val license: LicenseExtension = objectFactory.newInstance(LicenseExtension::class.java, objectFactory) 18 | 19 | /** 20 | * Invoke the contact extension 21 | */ 22 | fun contact(action: Action) { 23 | action.execute(contact) 24 | } 25 | 26 | /** 27 | * Invoke the license extension 28 | */ 29 | fun license(action: Action) { 30 | action.execute(license) 31 | } 32 | } -------------------------------------------------------------------------------- /openapi-merger-gradle-plugin/src/main/kotlin/com/rameshkp/openapi/merger/gradle/extensions/LicenseExtension.kt: -------------------------------------------------------------------------------- 1 | package com.rameshkp.openapi.merger.gradle.extensions 2 | 3 | import org.gradle.api.model.ObjectFactory 4 | import org.gradle.api.provider.Property 5 | import javax.inject.Inject 6 | 7 | /** 8 | * An extension for license object 9 | */ 10 | open class LicenseExtension @Inject constructor(objectFactory: ObjectFactory) { 11 | val name: Property = objectFactory.property(String::class.java) 12 | val url: Property = objectFactory.property(String::class.java) 13 | } -------------------------------------------------------------------------------- /openapi-merger-gradle-plugin/src/main/kotlin/com/rameshkp/openapi/merger/gradle/extensions/OpenApiExtension.kt: -------------------------------------------------------------------------------- 1 | package com.rameshkp.openapi.merger.gradle.extensions 2 | 3 | import org.gradle.api.Action 4 | import org.gradle.api.NamedDomainObjectContainer 5 | import org.gradle.api.Project 6 | import org.gradle.api.provider.Property 7 | import javax.inject.Inject 8 | 9 | /** 10 | * An extension for open api object 11 | */ 12 | open class OpenApiExtension @Inject constructor(project: Project) { 13 | val openApiVersion: Property = project.objects.property(String::class.java) 14 | val info: InfoExtension = project.objects.newInstance(InfoExtension::class.java) 15 | internal val externalDocs: ExternalDocsExtension = project.objects.newInstance(ExternalDocsExtension::class.java) 16 | val servers: NamedDomainObjectContainer = project.container(ServerExtension::class.java) { 17 | ServerExtension(it, project.objects) 18 | } 19 | 20 | /** 21 | * Invoke the info extension 22 | */ 23 | fun info(action: Action) { 24 | action.execute(info) 25 | } 26 | 27 | /** 28 | * Invoke the external Docs extension 29 | */ 30 | fun externalDocs(action: Action) { 31 | action.execute(externalDocs) 32 | } 33 | } -------------------------------------------------------------------------------- /openapi-merger-gradle-plugin/src/main/kotlin/com/rameshkp/openapi/merger/gradle/extensions/OpenApiMergerExtension.kt: -------------------------------------------------------------------------------- 1 | package com.rameshkp.openapi.merger.gradle.extensions 2 | 3 | import org.gradle.api.Action 4 | import org.gradle.api.Project 5 | import org.gradle.api.file.DirectoryProperty 6 | import javax.inject.Inject 7 | 8 | /** 9 | * An extension for open api merger object 10 | */ 11 | open class OpenApiMergerExtension @Inject constructor(project: Project) { 12 | val inputDirectory: DirectoryProperty = project.objects.directoryProperty() 13 | internal val openApi: OpenApiExtension = project.objects.newInstance(OpenApiExtension::class.java, project) 14 | internal val output: OutputExtension = project.objects.newInstance(OutputExtension::class.java, project.objects) 15 | 16 | /** 17 | * Invoke the openApi extension action 18 | */ 19 | fun openApi(action: Action) { 20 | action.execute(openApi) 21 | } 22 | 23 | /** 24 | * Invoke the output extension 25 | */ 26 | fun output(action: Action) { 27 | action.execute(output) 28 | } 29 | } -------------------------------------------------------------------------------- /openapi-merger-gradle-plugin/src/main/kotlin/com/rameshkp/openapi/merger/gradle/extensions/OutputExtension.kt: -------------------------------------------------------------------------------- 1 | package com.rameshkp.openapi.merger.gradle.extensions 2 | 3 | import org.gradle.api.file.DirectoryProperty 4 | import org.gradle.api.model.ObjectFactory 5 | import org.gradle.api.provider.Property 6 | import javax.inject.Inject 7 | 8 | /** 9 | * An extension class for output 10 | */ 11 | open class OutputExtension @Inject constructor(objectFactory: ObjectFactory) { 12 | val directory: DirectoryProperty = objectFactory.directoryProperty() 13 | val fileName: Property = objectFactory.property(String::class.java) 14 | val fileExtension: Property = objectFactory.property(String::class.java) 15 | } -------------------------------------------------------------------------------- /openapi-merger-gradle-plugin/src/main/kotlin/com/rameshkp/openapi/merger/gradle/extensions/ServerExtension.kt: -------------------------------------------------------------------------------- 1 | package com.rameshkp.openapi.merger.gradle.extensions 2 | 3 | import org.gradle.api.model.ObjectFactory 4 | import org.gradle.api.provider.Property 5 | import javax.inject.Inject 6 | 7 | open class ServerExtension @Inject constructor(val name: String, objectFactory: ObjectFactory) { 8 | val url: Property = objectFactory.property(String::class.java) 9 | val description: Property = objectFactory.property(String::class.java) 10 | } -------------------------------------------------------------------------------- /openapi-merger-gradle-plugin/src/main/kotlin/com/rameshkp/openapi/merger/gradle/plugin/OpenApiMergerGradlePlugin.kt: -------------------------------------------------------------------------------- 1 | package com.rameshkp.openapi.merger.gradle.plugin 2 | 3 | import com.rameshkp.openapi.merger.gradle.extensions.OpenApiMergerExtension 4 | import com.rameshkp.openapi.merger.gradle.task.OpenApiMergerTask 5 | import com.rameshkp.openapi.merger.gradle.utils.OPENAPI_EXTENSION_NAME 6 | import com.rameshkp.openapi.merger.gradle.utils.OPENAPI_TASK_NAME 7 | import org.gradle.api.Plugin 8 | import org.gradle.api.Project 9 | 10 | /** 11 | * The main plugin 12 | * 13 | * Creates an extension and a task 14 | */ 15 | class OpenApiMergerGradlePlugin: Plugin { 16 | 17 | override fun apply(project: Project) { 18 | project.extensions.create(OPENAPI_EXTENSION_NAME, OpenApiMergerExtension::class.java, project) 19 | project.tasks.register(OPENAPI_TASK_NAME, OpenApiMergerTask::class.java) 20 | } 21 | } -------------------------------------------------------------------------------- /openapi-merger-gradle-plugin/src/main/kotlin/com/rameshkp/openapi/merger/gradle/task/OpenApiMergerTask.kt: -------------------------------------------------------------------------------- 1 | package com.rameshkp.openapi.merger.gradle.task 2 | 3 | import com.rameshkp.openapi.merger.app.OpenApiMergerApp 4 | import com.rameshkp.openapi.merger.app.exceptions.OpenApiDataInvalidException 5 | import com.rameshkp.openapi.merger.app.models.* 6 | import com.rameshkp.openapi.merger.gradle.extensions.OpenApiMergerExtension 7 | import com.rameshkp.openapi.merger.gradle.utils.OPENAPI_EXTENSION_NAME 8 | import com.rameshkp.openapi.merger.gradle.utils.OPENAPI_GROUP_NAME 9 | import com.rameshkp.openapi.merger.gradle.utils.OPENAPI_TASK_DESCRIPTION 10 | import org.gradle.api.DefaultTask 11 | import org.gradle.api.GradleException 12 | import org.gradle.api.file.Directory 13 | import org.gradle.api.file.DirectoryProperty 14 | import org.gradle.api.file.RegularFileProperty 15 | import org.gradle.api.provider.Provider 16 | import org.gradle.api.tasks.InputDirectory 17 | import org.gradle.api.tasks.OutputFile 18 | import org.gradle.api.tasks.SkipWhenEmpty 19 | import org.gradle.api.tasks.TaskAction 20 | 21 | /** 22 | * Open Api Merger task to merge open api files 23 | */ 24 | open class OpenApiMergerTask : DefaultTask() { 25 | @get:SkipWhenEmpty 26 | @get:InputDirectory 27 | val inputDirectory: DirectoryProperty = project.objects.directoryProperty() 28 | @get:OutputFile 29 | val outputFileProperty: RegularFileProperty = project.objects.fileProperty() 30 | private val openApiMergerExtension: OpenApiMergerExtension 31 | 32 | private val validFileExtension = listOf("yaml", "json", "yml") 33 | 34 | private val defaultOutputDir: Provider = project.layout.buildDirectory.dir("open-api") 35 | private val defaultOutputFileName = "openapi" 36 | private val defaultOutputFileExtension = "yaml" 37 | 38 | init { 39 | group = OPENAPI_GROUP_NAME 40 | description = OPENAPI_TASK_DESCRIPTION 41 | openApiMergerExtension = project.extensions.run { 42 | getByName(OPENAPI_EXTENSION_NAME) as OpenApiMergerExtension 43 | } 44 | inputDirectory.set(openApiMergerExtension.inputDirectory) 45 | validateAndSetValues() 46 | } 47 | 48 | private fun validateAndSetValues() { 49 | val outputFileExtension = openApiMergerExtension.output.fileExtension 50 | if (!outputFileExtension.isPresent) { 51 | outputFileExtension.set(defaultOutputFileExtension) 52 | } 53 | if (!validFileExtension.contains(outputFileExtension.get())) { 54 | throw GradleException("Invalid file extension ${outputFileExtension.get()}. Valid values are $validFileExtension") 55 | } 56 | // set the output 57 | val outputDir = openApiMergerExtension.output.directory.getOrElse(defaultOutputDir.get()) 58 | val outputFileName = openApiMergerExtension.output.fileName.getOrElse(defaultOutputFileName) 59 | 60 | outputFileProperty.set(project.file("${outputDir.asFile}/$outputFileName.${outputFileExtension.get()}")) 61 | } 62 | 63 | @TaskAction 64 | fun execute() { 65 | 66 | val outputFile = outputFileProperty.asFile.get() 67 | outputFile.parentFile.mkdirs() 68 | 69 | // Construct your model. 70 | val openApiExtension = openApiMergerExtension.openApi 71 | val openApi = OpenApi().run { 72 | version = openApiExtension.openApiVersion.orNull 73 | 74 | info = Info().let { info -> 75 | val infoExtension = openApiExtension.info 76 | info.title = infoExtension.title.orNull 77 | info.description = infoExtension.description.orNull 78 | info.version = infoExtension.version.orNull 79 | info.termsOfService = infoExtension.termsOfService.orNull 80 | 81 | val contactUrl = infoExtension.contact.url.orNull 82 | val contactName = infoExtension.contact.name.orNull 83 | val contactEmail = infoExtension.contact.email.orNull 84 | if (isAnyValueNotNull(arrayOf(contactUrl, contactName, contactEmail))) { 85 | info.contact = Contact().let { contact -> 86 | contact.url = contactUrl 87 | contact.email = contactEmail 88 | contact.name = contactName 89 | contact 90 | } 91 | } 92 | 93 | val licenseName = infoExtension.license.name.orNull 94 | val licenseUrl = infoExtension.license.url.orNull 95 | if (isAnyValueNotNull(arrayOf(licenseName, licenseUrl))) { 96 | info.license = License().let { license -> 97 | license.name = licenseName 98 | license.url = licenseUrl 99 | license 100 | } 101 | } 102 | 103 | info 104 | } 105 | 106 | val externalDocsUrl = openApiExtension.externalDocs.url.orNull 107 | val externalDocsDescription = openApiExtension.externalDocs.description.orNull 108 | if (isAnyValueNotNull(arrayOf(externalDocsUrl, externalDocsDescription))) { 109 | externalDocs = ExternalDocs().let { eDocs -> 110 | eDocs.url = externalDocsUrl 111 | eDocs.description = externalDocsDescription 112 | eDocs 113 | } 114 | } 115 | 116 | val servers = ArrayList() 117 | openApiExtension.servers.all { 118 | servers.add(Server(it.url.orNull, it.description.orNull)) 119 | } 120 | 121 | this.servers = servers 122 | 123 | this 124 | } 125 | 126 | // external docs 127 | val openApiMergerApp = OpenApiMergerApp() 128 | try { 129 | openApiMergerApp.merge( 130 | inputDir = inputDirectory.get().asFile, 131 | outputFile = outputFile, 132 | openApi = openApi 133 | ) 134 | } catch (e: OpenApiDataInvalidException) { 135 | logger.error("Error merging openapi files", e) 136 | throw GradleException("Error merging openapi files. Reason=\n${e.message}") 137 | } 138 | } 139 | 140 | private fun isAnyValueNotNull(array: Array): Boolean { 141 | return array.filterNotNull().isNotEmpty() 142 | } 143 | } -------------------------------------------------------------------------------- /openapi-merger-gradle-plugin/src/main/kotlin/com/rameshkp/openapi/merger/gradle/utils/Constants.kt: -------------------------------------------------------------------------------- 1 | package com.rameshkp.openapi.merger.gradle.utils 2 | 3 | const val OPENAPI_GROUP_NAME = "Open Api Merger" 4 | const val OPENAPI_TASK_NAME = "mergeOpenApiFiles" 5 | const val OPENAPI_TASK_DESCRIPTION = "Task to merge multiple openapi files" 6 | const val OPENAPI_EXTENSION_NAME = "openApiMerger" -------------------------------------------------------------------------------- /openapi-merger-gradle-plugin/src/test/kotlin/com/rameshkp/openapi/merger/gradle/plugin/OpenApiMergerGradlePluginTest.kt: -------------------------------------------------------------------------------- 1 | package com.rameshkp.openapi.merger.gradle.plugin 2 | 3 | import com.rameshkp.openapi.merger.gradle.extensions.OpenApiMergerExtension 4 | import com.rameshkp.openapi.merger.gradle.task.OpenApiMergerTask 5 | import io.kotest.assertions.throwables.shouldThrow 6 | import io.kotest.core.spec.style.WordSpec 7 | import io.kotest.matchers.shouldBe 8 | import io.kotest.matchers.shouldNotBe 9 | import org.gradle.api.GradleException 10 | import org.gradle.api.Task 11 | import org.gradle.testfixtures.ProjectBuilder 12 | 13 | 14 | internal class OpenApiMergerGradlePluginTest: WordSpec({ 15 | val builder = ProjectBuilder.builder() 16 | 17 | "Using the Plugin ID" should { 18 | "Apply the Plugin" { 19 | val project = builder.build() 20 | project.pluginManager.apply("com.rameshkp.openapi-merger-gradle-plugin") 21 | project.plugins.getPlugin(OpenApiMergerGradlePlugin::class.java) shouldNotBe null 22 | } 23 | } 24 | 25 | "Applying the Plugin" should { 26 | val project = builder.build() 27 | project.pluginManager.apply(OpenApiMergerGradlePlugin::class.java) 28 | 29 | "Register an extension with name 'openApiMerger'" { 30 | project.extensions.getByName("openApiMerger") shouldNotBe null 31 | } 32 | "Register a task with name 'mergeOpenApiFiles'" { 33 | val mergeOpenApiFilesTask = project.tasks.first() as Task 34 | mergeOpenApiFilesTask shouldNotBe null 35 | mergeOpenApiFilesTask.name shouldBe "mergeOpenApiFiles" 36 | mergeOpenApiFilesTask.description shouldBe "Task to merge multiple openapi files" 37 | mergeOpenApiFilesTask.group shouldBe "Open Api Merger" 38 | } 39 | } 40 | 41 | "Running the 'openApiMerger' task" should { 42 | val project = builder.build() 43 | project.pluginManager.apply(OpenApiMergerGradlePlugin::class.java) 44 | val openApiMergerExtension = project.extensions.getByName("openApiMerger") as OpenApiMergerExtension 45 | val openApiMerger = project.tasks.getByName("mergeOpenApiFiles") as OpenApiMergerTask 46 | openApiMergerExtension.inputDirectory.set(project.buildDir) 47 | 48 | "Throw exception when open api version is missing" { 49 | openApiMergerExtension.openApi.info.title.set("Title") 50 | openApiMergerExtension.openApi.info.version.set("version") 51 | val exception = shouldThrow { 52 | openApiMerger.execute() 53 | } 54 | exception.message shouldBe """ 55 | Error merging openapi files. Reason= 56 | OpenApi version cannot be blank 57 | """.trimIndent() 58 | } 59 | "Throw exception when open api info title is missing" { 60 | openApiMergerExtension.openApi.openApiVersion.set("3.0.3") 61 | openApiMergerExtension.openApi.info.version.set("version") 62 | openApiMergerExtension.openApi.info.title.set("") 63 | val exception = shouldThrow { 64 | openApiMerger.execute() 65 | } 66 | exception.message shouldBe """ 67 | Error merging openapi files. Reason= 68 | OpenApi Info Title cannot be blank 69 | """.trimIndent() 70 | } 71 | "Throw exception when open api info version is missing" { 72 | openApiMergerExtension.openApi.openApiVersion.set("3.0.3") 73 | openApiMergerExtension.openApi.info.title.set("Title") 74 | openApiMergerExtension.openApi.info.version.set("") 75 | val exception = shouldThrow { 76 | openApiMerger.execute() 77 | } 78 | exception.message shouldBe """ 79 | Error merging openapi files. Reason= 80 | OpenApi Info Version cannot be blank 81 | """.trimIndent() 82 | } 83 | } 84 | 85 | "Running the 'openApiMerger' task with invalid file extension" should { 86 | "Throw exception" { 87 | val project = builder.build() 88 | project.pluginManager.apply(OpenApiMergerGradlePlugin::class.java) 89 | val openApiMergerExtension = project.extensions.getByName("openApiMerger") as OpenApiMergerExtension 90 | openApiMergerExtension.inputDirectory.set(project.buildDir) 91 | 92 | openApiMergerExtension.openApi.openApiVersion.set("3.0.3") 93 | openApiMergerExtension.openApi.info.title.set("Title") 94 | openApiMergerExtension.openApi.info.version.set("version") 95 | openApiMergerExtension.output.fileExtension.set("txt") 96 | 97 | val exception = shouldThrow { 98 | val openApiMerger = project.tasks.getByName("mergeOpenApiFiles") as OpenApiMergerTask 99 | openApiMerger.execute() 100 | } 101 | exception.message shouldBe "Could not create task ':mergeOpenApiFiles'." 102 | } 103 | } 104 | 105 | }) -------------------------------------------------------------------------------- /openapi-merger-maven-plugin/README.md: -------------------------------------------------------------------------------- 1 | # **Introduction to openapi-merger-maven-plugin** 2 | 3 | Open API Merger Maven Plugin - Merges multiple OpenAPI-3 specification file into a single file. 4 | 5 | This Maven plugin provides the capability to merge multiple open api v3 specification file into a single file from a Maven build. 6 | 7 | Compatibility Notes 8 | ------------------- 9 | 10 | The plugin is build on maven version 3.6.3 11 | 12 | The Java version used to compile the plugin 1.8 13 | 14 | How To Use 15 | ---------- 16 | 17 | ```xml 18 | 19 | 20 | 21 | com.rameshkp 22 | openapi-merger-maven-plugin 23 | 1.0.5 24 | 25 | 26 | 27 | ``` 28 | 29 | Note: For latest versions of the plugins please check the maven central portal 30 | 31 | What does this plugin do 32 | ----------------------- 33 | 34 | [open api merger plugin readme](https://github.com/kpramesh2212/openapi-merger-plugin/blob/main/README.md) 35 | 36 | How the plugin works 37 | ------------ 38 | 39 | Add this plugin to the pom.xml as shown above and then run 40 | 41 | ```bash 42 | mvn openapi-merger:merge 43 | ``` 44 | 45 | Using configuration block users can perform customization as explained below 46 | 47 | Customization 48 | ------------- 49 | 50 | The following customizations can be done using the configuration block as follows 51 | 52 | ```xml 53 | 54 | open-api-files 55 | target/my-custom-dir 56 | JSON 57 | open 58 | 59 | 3.0.3 60 | 61 | 1.0.0-SNAPSHOT 62 | Merged Title 63 | A short description of the title 64 | "https://openapi-merger.com/terms-of-service" 65 | 66 | ContactName 67 | contact@openapi.merger.com 68 | https://openapimerger.com 69 | 70 | 71 | Apache License v2.0 72 | https://apache.org/v2 73 | 74 | 75 | 76 | External Docs 77 | https://external-docs.com/url 78 | 79 | 80 | 81 | ``` 82 | #### openApiMerger block 83 | | Parameter | Description | Required | Default | 84 | |--------------------|----------------------------------------------------------------------------------------------------------------------------------------|----------|------------------| 85 | | `inputDir` | The input directory containing the openapi v3 specification files. The input directory can contain files in both yaml and json format. | Yes | N/A | 86 | | `outputDir` | The output directory to place the merged open api v3 specification file. | No | target/open-api/ | 87 | | `outputFileName` | Name of the merged output openapi v3 specification file | No | openapi | 88 | | `outputFileFormat` | The format of the output. Can either be one of YAML or JSON | No | YAML | 89 | | `openApi(Block)` | The openApi block is used to customize the common openApi object for the merged file. | Yes | N/A | 90 | 91 | #### openApi block 92 | | Parameter | Description | Required | Default | 93 | |-----------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------|---------| 94 | | `version` | The version of open api. | Yes | N/A | 95 | | `info(block)` | [See Info object in open api v3 specification for explanation](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#info-object) | Yes | N/A | 96 | | `externalDocs(block)` | [See External Documentation object in open api v3 specification for explanation](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#external-documentation-object) | No | null | 97 | 98 | #### info block 99 | | Parameter | Description | Required | Default | 100 | |------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------|----------|---------| 101 | | `title` | The title of the API. | Yes | N/A | 102 | | `description` | A short description of the API | No | null | 103 | | `termsOfService` | URL to the Terms of Service for the API | No | null | 104 | | `version` | The version of the OpenAPI document | Yes | N/A | 105 | | `contact(block)` | [See Contact object in open api v3 specification for explanation](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#contact-object) | No | null | 106 | | `license(block)` | [See License object in open api v3 specification for explanation](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#licenseObject) | No | null | 107 | 108 | #### contact block 109 | | Parameter | Description | Required | Default | 110 | |-----------|--------------------------------------------------------------------------------------------------|----------|---------| 111 | | `name` | The identifying name of the contact person/organization. | No | null | 112 | | `url` | The URL pointing to the contact information. MUST be in the format of a URL. | No | null | 113 | | `email` | The email address of the contact person/organization. MUST be in the format of an email address. | No | null | 114 | 115 | #### license block 116 | | Parameter | Description | Required | Default | 117 | |-----------|------------------------------------------------------------------------|----------|---------| 118 | | `name` | The license name used for the API. | Yes | N/A | 119 | | `url` | A URL to the license used for the API. MUST be in the format of a URL. | No | null | 120 | 121 | #### externalDocs block 122 | | Parameter | Description | Required | Default | 123 | |---------------|-----------------------------------------------------------------------|----------|---------| 124 | | `description` | A short description of the target documentation. | No | null | 125 | | `url` | The URL for the target documentation. MUST be in the format of a URL. | Yes | N/A | 126 | 127 | # Building the plugin 128 | 129 | TODO -------------------------------------------------------------------------------- /openapi-merger-maven-plugin/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | java 3 | maven 4 | `maven-publish` 5 | signing 6 | } 7 | 8 | val localRepository: String by project.extra 9 | val localM2Repository = "$buildDir/m2Repo" 10 | 11 | val mavenCliRuntime: Configuration by configurations.creating { 12 | isVisible = false 13 | isCanBeConsumed = false 14 | isCanBeResolved = true 15 | } 16 | 17 | java { 18 | withSourcesJar() 19 | withJavadocJar() 20 | } 21 | 22 | repositories { 23 | mavenCentral() 24 | } 25 | 26 | val mavenVersion = "3.6.3" 27 | val mavenPluginVersion = "3.6.0" 28 | val eclipseAetherVersion = "1.1.0" 29 | val mavenWagonVersion = "3.4.1" 30 | val lombokVersion = "1.18.16" 31 | 32 | dependencies { 33 | compileOnly(group = "org.projectlombok", name = "lombok", version = lombokVersion) 34 | annotationProcessor(group = "org.projectlombok", name = "lombok", version = lombokVersion) 35 | 36 | implementation(project(":openapi-merger-app")) 37 | implementation(group = "org.apache.maven", name = "maven-core", version = mavenVersion) 38 | implementation(group = "org.apache.maven", name = "maven-plugin-api", version = mavenVersion) 39 | implementation(group = "org.apache.maven.plugin-tools", name = "maven-plugin-annotations", version = mavenPluginVersion) 40 | 41 | mavenCliRuntime(group = "org.apache.maven", name = "maven-embedder", version = mavenVersion) 42 | mavenCliRuntime(group = "org.apache.maven", name = "maven-embedder", version = mavenVersion) 43 | mavenCliRuntime(group = "org.apache.maven", name = "maven-compat", version = mavenVersion) 44 | mavenCliRuntime(group = "org.slf4j", name = "slf4j-simple", version = "1.7.30") 45 | mavenCliRuntime(group = "org.eclipse.aether", name = "aether-connector-basic", version = eclipseAetherVersion) 46 | mavenCliRuntime(group = "org.eclipse.aether", name = "aether-transport-wagon", version = eclipseAetherVersion) 47 | mavenCliRuntime(group = "org.apache.maven.wagon", name = "wagon-http", version = mavenWagonVersion, classifier = "shaded") 48 | mavenCliRuntime(group = "org.apache.maven.wagon", name = "wagon-file", version = mavenWagonVersion) 49 | mavenCliRuntime(group = "org.apache.maven.wagon", name = "wagon-provider-api", version = mavenWagonVersion) 50 | 51 | 52 | testImplementation("junit", "junit", "4.12") 53 | } 54 | 55 | val publish by project(":openapi-merger-app").tasks.existing 56 | 57 | val generatePluginDescriptor by tasks.registering(JavaExec::class) { 58 | dependsOn(publish) 59 | val settingsFile = sourceSets["main"].resources.srcDirs.first().path.plus("/settings.xml") 60 | val javaOutputDir = sourceSets["main"].java.classesDirectory 61 | val pomFile = "$buildDir/pom.xml" 62 | val pluginDescriptorFile = javaOutputDir.map { 63 | it.file("META-INF/maven/plugin.xml") 64 | } 65 | inputs.dir(sourceSets["main"].java.outputDir) 66 | outputs.file(pluginDescriptorFile) 67 | 68 | classpath = mavenCliRuntime 69 | main = "org.apache.maven.cli.MavenCli" 70 | systemProperties = mapOf( 71 | "maven.multiModuleProjectDirectory" to projectDir, 72 | "localM2Repository" to localM2Repository 73 | ) 74 | args = listOf( 75 | "--errors", 76 | "--batch-mode", 77 | "--settings", settingsFile, 78 | "--file", pomFile, 79 | "org.apache.maven.plugins:maven-plugin-plugin:$mavenPluginVersion:descriptor" 80 | ) 81 | 82 | doFirst { 83 | maven.pom { 84 | packaging = "maven-plugin" 85 | withXml { 86 | asNode().appendNode("build").apply { 87 | appendNode("directory", buildDir) 88 | appendNode("outputDirectory", "${javaOutputDir.get()}") 89 | } 90 | asNode().appendNode("repositories").apply { 91 | appendNode("repository").apply { 92 | appendNode("id", "local-repository") 93 | appendNode("name", "Local File Based Repository") 94 | appendNode("url", "file://$localRepository") 95 | } 96 | } 97 | } 98 | }.writeTo(pomFile) 99 | assert(file(pomFile).exists()) { 100 | "$pomFile was not generated. Check errors" 101 | } 102 | logger.info("POM is generated and placed at location $pomFile") 103 | } 104 | doLast { 105 | assert(pluginDescriptorFile.get().asFile.exists()) { 106 | "${pluginDescriptorFile.get()} was not generated. Check erros" 107 | } 108 | logger.info("Plugin descriptor file is generated and placed in ${pluginDescriptorFile.get().asFile.absoluteFile}") 109 | } 110 | } 111 | 112 | val jar by tasks.existing { 113 | dependsOn(generatePluginDescriptor) 114 | } 115 | 116 | publishing { 117 | publications { 118 | create("openApiMergerMavenPlugin") { 119 | from(components["java"]) 120 | 121 | pom { 122 | name.set("Open API V3 Merger maven plugin") 123 | description.set("A Maven plugin to merge open api v3 specification files") 124 | url.set("https://github.com/kpramesh2212/openapi-merger-plugin") 125 | 126 | licenses { 127 | license { 128 | name.set("The Apache License, Version 2.0") 129 | url.set("http://www.apache.org/licenses/LICENSE-2.0.txt") 130 | } 131 | } 132 | 133 | developers { 134 | developer { 135 | id.set("rameshkp") 136 | name.set("Ramesh KP") 137 | email.set("kpramesh2212@gmail.com") 138 | } 139 | } 140 | scm { 141 | connection.set("git@github.com:kpramesh2212/openapi-merger-plugin.git") 142 | developerConnection.set("git@github.com:kpramesh2212/openapi-merger-plugin.git") 143 | url.set("https://github.com/kpramesh2212/openapi-merger-plugin") 144 | } 145 | } 146 | } 147 | } 148 | } 149 | 150 | signing { 151 | sign(publishing.publications["openApiMergerMavenPlugin"]) 152 | } 153 | -------------------------------------------------------------------------------- /openapi-merger-maven-plugin/src/main/java/com/rameshkp/openapi/merger/maven/models/OpenApiFileFormat.java: -------------------------------------------------------------------------------- 1 | package com.rameshkp.openapi.merger.maven.models; 2 | 3 | /** 4 | * An enum to represent the output file format 5 | */ 6 | public enum OpenApiFileFormat { 7 | JSON, 8 | YAML 9 | } 10 | -------------------------------------------------------------------------------- /openapi-merger-maven-plugin/src/main/java/com/rameshkp/openapi/merger/maven/plugin/OpenApiMergerMojo.java: -------------------------------------------------------------------------------- 1 | package com.rameshkp.openapi.merger.maven.plugin; 2 | 3 | import com.rameshkp.openapi.merger.app.OpenApiMergerApp; 4 | import com.rameshkp.openapi.merger.app.models.OpenApi; 5 | import com.rameshkp.openapi.merger.maven.models.OpenApiFileFormat; 6 | import org.apache.maven.plugin.AbstractMojo; 7 | import org.apache.maven.plugin.MojoExecutionException; 8 | import org.apache.maven.plugin.MojoFailureException; 9 | import org.apache.maven.plugin.logging.Log; 10 | import org.apache.maven.plugins.annotations.Mojo; 11 | import org.apache.maven.plugins.annotations.Parameter; 12 | 13 | import java.io.File; 14 | 15 | /** 16 | * The plugin mojo class 17 | */ 18 | @Mojo(name = "merge") 19 | public class OpenApiMergerMojo extends AbstractMojo { 20 | /** 21 | * Input directory containing openapi schema files 22 | */ 23 | @Parameter 24 | private File inputDir; 25 | 26 | /** 27 | * Output directory to place the merged schema file 28 | */ 29 | @Parameter(defaultValue = "target/open-api") 30 | private File outputDir; 31 | 32 | /** 33 | * Name of the merged file 34 | */ 35 | @Parameter(defaultValue = "openapi") 36 | private String outputFileName; 37 | 38 | /** 39 | * Output format of the merged file 40 | */ 41 | @Parameter(defaultValue = "YAML") 42 | private OpenApiFileFormat outputFileFormat; 43 | 44 | /** 45 | * OpenApiInfo Object 46 | */ 47 | @Parameter 48 | private OpenApi openApi; 49 | 50 | @Override 51 | public void execute() throws MojoExecutionException, MojoFailureException { 52 | Log log = getLog(); 53 | 54 | log.debug("Starting validation"); 55 | validate(); 56 | 57 | File outputFile = getOutputFile(log); 58 | 59 | log.debug("Attempting to merge the open api schema files"); 60 | OpenApiMergerApp apiMergerApp = new OpenApiMergerApp(); 61 | try { 62 | apiMergerApp.merge(inputDir, outputFile, openApi); 63 | log.info("Completed Open API file merging. output " + outputFile.getAbsolutePath()); 64 | } catch (Exception e) { 65 | log.error(e); 66 | throw new MojoFailureException(e.getMessage(), e); 67 | } 68 | } 69 | 70 | private File getOutputFile(Log log) { 71 | boolean created = outputDir.mkdirs(); 72 | log.debug("Create the output directory " + created); 73 | 74 | String fileExtension = ""; 75 | if (outputFileFormat == OpenApiFileFormat.JSON) { 76 | fileExtension = ".json"; 77 | } else { 78 | fileExtension = ".yaml"; 79 | } 80 | String outFileWithExtension = outputFileName + fileExtension; 81 | return new File(outputDir, outFileWithExtension); 82 | } 83 | 84 | // Later do this via validators 85 | private void validate() throws MojoFailureException { 86 | if (inputDir == null || !inputDir.isDirectory()) { 87 | throw new MojoFailureException("Invalid InputDir: Provide a valid directory containing open api schema files"); 88 | } 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /openapi-merger-maven-plugin/src/main/resources/settings.xml: -------------------------------------------------------------------------------- 1 | 3 | ${localM2Repository} 4 | 5 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "openapi-merger-plugin" 2 | 3 | pluginManagement { 4 | repositories { 5 | gradlePluginPortal() 6 | jcenter() 7 | } 8 | } 9 | 10 | include("openapi-merger-gradle-plugin") 11 | include("openapi-merger-maven-plugin") 12 | include("openapi-merger-app") --------------------------------------------------------------------------------