├── .github ├── FUNDING.yml └── workflows │ ├── build_master.yml │ ├── build_standard.yml │ └── release.yml ├── .gitignore ├── .java-version ├── LICENSE ├── README.md ├── build.gradle ├── codecov.yml ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main └── java │ └── org │ └── contextmapper │ └── cli │ ├── ContextMapperCLI.java │ └── commands │ ├── AbstractCliCommand.java │ ├── CliCommand.java │ ├── ContextMapperGenerator.java │ ├── GenerateCommand.java │ └── ValidateCommand.java └── test ├── java └── org │ └── contextmapper │ └── cli │ ├── ContextMapperCLITest.java │ └── commands │ ├── ContextMapperGeneratorTest.java │ ├── GenerateCommandTest.java │ └── ValidateCommandTest.java └── resources ├── test-with-error.cml ├── test.cml └── test.ftl /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: stefan-ka 2 | -------------------------------------------------------------------------------- /.github/workflows/build_master.yml: -------------------------------------------------------------------------------- 1 | name: Build (master) 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | tags-ignore: 8 | - '**' 9 | 10 | jobs: 11 | build_and_publish_snapshot: 12 | runs-on: ubuntu-latest 13 | 14 | steps: 15 | - uses: actions/checkout@v2 16 | with: 17 | fetch-depth: 0 18 | - name: Set up JDK 17 19 | uses: actions/setup-java@v1 20 | with: 21 | java-version: 17 22 | - name: Install Graphviz 23 | run: sudo apt-get -y install graphviz 24 | - name: Gradle caches 25 | uses: actions/cache@v4 26 | with: 27 | path: | 28 | ~/.gradle/caches 29 | ~/.gradle/wrapper 30 | key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }} 31 | restore-keys: | 32 | ${{ runner.os }}-gradle- 33 | - name: Configure GPG Key 34 | run: | 35 | mkdir -p ~/.gnupg/ 36 | printf "$GPG_SIGNING_KEY" | base64 --decode > ~/.gnupg/private.key 37 | gpg --import --batch ~/.gnupg/private.key 38 | env: 39 | GPG_SIGNING_KEY: ${{ secrets.GPG_SIGNING_KEY }} 40 | - name: Grant execute permission for gradlew 41 | run: chmod +x gradlew 42 | - name: Build with Gradle 43 | run: ./gradlew clean build snapshot publish -Psigning.keyId=${GPG_KEY_ID} -Psigning.password=${GPG_KEY_PASSPHRASE} -Psigning.secretKeyRingFile=/home/runner/.gnupg/private.key 44 | env: 45 | GPG_KEY_ID: ${{ secrets.GPG_KEY_ID }} 46 | GPG_KEY_PASSPHRASE: ${{ secrets.GPG_KEY_PASSPHRASE }} 47 | OSSRH_USERNAME: ${{ secrets.OSSRH_USERNAME }} 48 | OSSRH_PASSWORD: ${{ secrets.OSSRH_PASSWORD }} 49 | - name: Upload coverage to Codecov 50 | uses: codecov/codecov-action@v4 51 | -------------------------------------------------------------------------------- /.github/workflows/build_standard.yml: -------------------------------------------------------------------------------- 1 | name: Build (standard) 2 | 3 | on: 4 | push: 5 | branches-ignore: 6 | - master 7 | pull_request: 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - uses: actions/checkout@v2 15 | with: 16 | fetch-depth: 0 17 | - name: Set up JDK 11 18 | uses: actions/setup-java@v1 19 | with: 20 | java-version: 11 21 | - name: Install Graphviz 22 | run: sudo apt-get -y install graphviz 23 | - name: Gradle caches 24 | uses: actions/cache@v4 25 | with: 26 | path: | 27 | ~/.gradle/caches 28 | ~/.gradle/wrapper 29 | key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }} 30 | restore-keys: | 31 | ${{ runner.os }}-gradle- 32 | - name: Grant execute permission for gradlew 33 | run: chmod +x gradlew 34 | - name: Build with Gradle 35 | run: ./gradlew clean build snapshot 36 | - name: Upload coverage to Codecov 37 | uses: codecov/codecov-action@v4 38 | - name: Unpack tar 39 | run: mkdir ./out && tar -xf ./build/distributions/*.tar --strip-components 1 -C ./out 40 | - name: Upload build 41 | uses: actions/upload-artifact@v4 42 | with: 43 | name: build 44 | path: ./out 45 | if-no-files-found: error 46 | 47 | validate_java_11: 48 | runs-on: ubuntu-latest 49 | needs: 50 | - build 51 | steps: 52 | - name: Download build 53 | uses: actions/download-artifact@v4 54 | with: 55 | name: build 56 | path: ./out 57 | - name: Grant execute permission for cm 58 | run: chmod +x ./out/bin/cm 59 | - name: Set up JDK 11 60 | uses: actions/setup-java@v1 61 | with: 62 | java-version: 11 63 | - name: Execute to check if Java version is compatible 64 | run: ./out/bin/cm 65 | 66 | validate_java_17: 67 | runs-on: ubuntu-latest 68 | needs: 69 | - build 70 | steps: 71 | - name: Download build 72 | uses: actions/download-artifact@v4 73 | with: 74 | name: build 75 | path: ./out 76 | - name: Grant execute permission for cm 77 | run: chmod +x ./out/bin/cm 78 | - name: Set up JDK 17 79 | uses: actions/setup-java@v1 80 | with: 81 | java-version: 17 82 | - name: Execute to check if Java version is compatible 83 | run: ./out/bin/cm 84 | 85 | validate_java_21: 86 | runs-on: ubuntu-latest 87 | needs: 88 | - build 89 | steps: 90 | - name: Download build 91 | uses: actions/download-artifact@v4 92 | with: 93 | name: build 94 | path: ./out 95 | - name: Grant execute permission for cm 96 | run: chmod +x ./out/bin/cm 97 | - name: Set up JDK 21 98 | uses: actions/setup-java@v1 99 | with: 100 | java-version: 21 101 | - name: Execute to check if Java version is compatible 102 | run: ./out/bin/cm 103 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release Context Mapper CLI 2 | 3 | on: 4 | push: 5 | tags: 6 | - 'v*' 7 | 8 | jobs: 9 | release: 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | - uses: actions/checkout@v2 14 | with: 15 | fetch-depth: 0 16 | - name: Set up JDK 17 17 | uses: actions/setup-java@v1 18 | with: 19 | java-version: 17 20 | - name: Install Graphviz 21 | run: sudo apt-get -y install graphviz 22 | - name: Gradle caches 23 | uses: actions/cache@v4 24 | with: 25 | path: | 26 | ~/.gradle/caches 27 | ~/.gradle/wrapper 28 | key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }} 29 | restore-keys: | 30 | ${{ runner.os }}-gradle- 31 | - name: Configure GPG Key 32 | run: | 33 | mkdir -p ~/.gnupg/ 34 | printf "$GPG_SIGNING_KEY" | base64 --decode > ~/.gnupg/private.key 35 | gpg --import --batch ~/.gnupg/private.key 36 | env: 37 | GPG_SIGNING_KEY: ${{ secrets.GPG_SIGNING_KEY }} 38 | - name: Grant execute permission for gradlew 39 | run: chmod +x gradlew 40 | - name: Release with Gradle 41 | run: ./gradlew clean build publish -Prelease.useLastTag=true -Psigning.keyId=${GPG_KEY_ID} -Psigning.password=${GPG_KEY_PASSPHRASE} -Psigning.secretKeyRingFile=/home/runner/.gnupg/private.key 42 | env: 43 | GPG_KEY_ID: ${{ secrets.GPG_KEY_ID }} 44 | GPG_KEY_PASSPHRASE: ${{ secrets.GPG_KEY_PASSPHRASE }} 45 | OSSRH_USERNAME: ${{ secrets.OSSRH_USERNAME }} 46 | OSSRH_PASSWORD: ${{ secrets.OSSRH_PASSWORD }} 47 | - name: Upload coverage to Codecov 48 | uses: codecov/codecov-action@v4 49 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | **/target 4 | **/out 5 | 6 | # Build 7 | /build 8 | .gradle/ 9 | 10 | # Log file 11 | *.log 12 | 13 | # BlueJ files 14 | *.ctxt 15 | 16 | # Mobile Tools for Java (J2ME) 17 | .mtj.tmp/ 18 | 19 | # Package Files # 20 | *.jar 21 | *.war 22 | *.nar 23 | *.ear 24 | *.zip 25 | *.tar.gz 26 | *.rar 27 | 28 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 29 | hs_err_pid* 30 | 31 | # IntelliJ 32 | /.idea 33 | -------------------------------------------------------------------------------- /.java-version: -------------------------------------------------------------------------------- 1 | 17.0 2 | -------------------------------------------------------------------------------- /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 | ![Context Mapper](https://raw.githubusercontent.com/wiki/ContextMapper/context-mapper-dsl/logo/cm-logo-github-small.png) 2 | # Context Mapper CLI 3 | [![Build (master)](https://github.com/ContextMapper/context-mapper-cli/actions/workflows/build_master.yml/badge.svg)](https://github.com/ContextMapper/context-mapper-cli/actions) [![codecov](https://codecov.io/gh/ContextMapper/context-mapper-cli/branch/master/graph/badge.svg?token=OMqxkddZOJ)](https://codecov.io/gh/ContextMapper/context-mapper-cli) [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![Maven Central](https://img.shields.io/maven-central/v/org.contextmapper/context-mapper-cli.svg?label=Maven%20Central)](https://search.maven.org/search?q=g:%22org.contextmapper%22%20AND%20a:%22context-mapper-cli%22) 4 | 5 | This repository contains the Context Mapper CLI - a command line interface to validate CML files and call generators 6 | (currently PlantUML, Context Map, and generic text files via Freemarker template). 7 | 8 | ## Download 9 | The CLI can be downloaded under the following links: 10 | * [TAR](https://repo1.maven.org/maven2/org/contextmapper/context-mapper-cli/6.12.0/context-mapper-cli-6.12.0.tar) (Linux, Mac) 11 | * [ZIP](https://repo1.maven.org/maven2/org/contextmapper/context-mapper-cli/6.12.0/context-mapper-cli-6.12.0.zip) (Windows) 12 | 13 | In case you want to include Context Mapper in your Maven or Gradle build, you can use the CLI to call generators (for example with Maven exec plugin). 14 | 15 | **Gradle:** 16 | ```gradle 17 | implementation 'org.contextmapper:context-mapper-cli:6.12.0' 18 | ``` 19 | 20 | **Maven:** 21 | ```xml 22 | 23 | org.contextmapper 24 | context-mapper-cli 25 | 6.12.0 26 | 27 | ``` 28 | 29 | ## Validate Command Usage 30 | ```shell 31 | $ ./cm validate -h 32 | Context Mapper CLI 33 | usage: cm validate 34 | -h,--help Prints this message. 35 | -i,--input Path to the CML file which you want to validate. 36 | ``` 37 | 38 | ## Generate Command Usage 39 | ```shell 40 | $ ./cm generate -h 41 | Context Mapper CLI 42 | usage: cm generate 43 | -f,--outputFile The name of the file that shall be generated 44 | (only used by Freemarker generator, as we cannot 45 | know the file extension). 46 | -g,--generator The generator you want to call. Use one of the 47 | following values: context-map (Graphical DDD 48 | Context Map), plantuml (PlantUML class-, 49 | component-, and state diagrams.), generic 50 | (Generate generic text with Freemarker template) 51 | -h,--help Prints this message. 52 | -i,--input Path to the CML file for which you want to 53 | generate output. 54 | -o,--outputDir Path to the directory into which you want to 55 | generate. 56 | -t,--template Path to the Freemarker template you want to use. 57 | This parameter is only used if you pass 'generic' 58 | to the 'generator' (-g) parameter. 59 | ``` 60 | 61 | ## Usage examples 62 | The following examples illustrate the CLI usage. 63 | 64 | ### Validate *.cml File 65 | 66 | ```shell 67 | ./cm validate -i DDD-Sample.cml 68 | ``` 69 | 70 | ### Generate PlantUML 71 | 72 | ```shell 73 | ./cm generate -i DDD-Sample.cml -g plantuml -o ./output-directory 74 | ``` 75 | 76 | ### Generate Context Map 77 | 78 | ```shell 79 | ./cm generate -i DDD-Sample.cml -g context-map -o ./output-directory 80 | ``` 81 | 82 | ### Generate Arbitrary Text File with Freemarker Template 83 | 84 | ```shell 85 | ./cm generate -i DDD-Sample.cml -g generic -o ./output-directory -t template.md.ftl -f glossary.md 86 | ``` 87 | 88 | ## Development / Build 89 | If you want to contribute to this project you can create a fork and a pull request. The project is built with Gradle, so you can import it as Gradle project within Eclipse or IntelliJ IDEA (or any other IDE supporting Gradle). 90 | 91 | ```bash 92 | ./gradlew clean build 93 | ``` 94 | 95 | ## Contributing 96 | Contribution is always welcome! Here are some ways how you can contribute: 97 | * Create GitHub issues if you find bugs or just want to give suggestions for improvements. 98 | * This is an open source project: if you want to code, [create pull requests](https://help.github.com/articles/creating-a-pull-request/) from [forks of this repository](https://help.github.com/articles/fork-a-repo/). Please refer to a Github issue if you contribute this way. 99 | * If you want to contribute to our documentation and user guides on our website [https://contextmapper.org/](https://contextmapper.org/), create pull requests from forks of the corresponding page repo [https://github.com/ContextMapper/contextmapper.github.io](https://github.com/ContextMapper/contextmapper.github.io) or create issues [there](https://github.com/ContextMapper/contextmapper.github.io/issues). 100 | 101 | ## Licence 102 | ContextMapper is released under the [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0). 103 | 104 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'jacoco' 4 | id 'application' 5 | id 'maven-publish' 6 | id 'signing' 7 | id 'nebula.release' version '19.0.10' 8 | } 9 | 10 | group 'org.contextmapper' 11 | 12 | sourceCompatibility = '11' 13 | targetCompatibility = '11' 14 | 15 | repositories { 16 | mavenCentral() 17 | } 18 | 19 | dependencies { 20 | implementation "commons-cli:commons-cli:${commonsCliVersion}" 21 | implementation "org.contextmapper:context-mapper-dsl:${cmlVersion}" 22 | 23 | testImplementation "org.junit.jupiter:junit-jupiter-api:${jUnitVersion}" 24 | testImplementation "org.junit.jupiter:junit-jupiter-params:${jUnitVersion}" 25 | testImplementation "org.assertj:assertj-core:${assertJVersion}" 26 | testImplementation "org.mockito:mockito-core:${mockitoVersion}" 27 | testImplementation "org.mockito:mockito-junit-jupiter:${mockitoVersion}" 28 | testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:${jUnitVersion}" 29 | } 30 | 31 | application { 32 | mainClassName = 'org.contextmapper.cli.ContextMapperCLI' 33 | applicationName = 'context-mapper-cli' 34 | } 35 | startScripts { 36 | applicationName = 'cm' 37 | } 38 | jar { 39 | manifest { 40 | attributes ( 41 | 'Implementation-Title': 'Context Mapper Command Line Interface (CLI)', 42 | 'Implementation-Version': project.version, 43 | 'Main-Class': 'org.contextmapper.cli.ContextMapperCLI' 44 | ) 45 | } 46 | } 47 | 48 | if (!project.hasProperty('signing.secretKeyRingFile')) { 49 | project.ext.'signing.secretKeyRingFile' = "${rootDir}/secret-key.gpg" 50 | } 51 | 52 | test { 53 | useJUnitPlatform() 54 | 55 | testLogging { 56 | showExceptions true 57 | exceptionFormat "full" 58 | 59 | showCauses true 60 | showStackTraces true 61 | } 62 | } 63 | 64 | jacocoTestReport { 65 | reports { 66 | xml.required = true 67 | html.required = true 68 | } 69 | } 70 | 71 | check.dependsOn jacocoTestReport 72 | 73 | task sourcesJar(type: Jar) { 74 | from sourceSets.main.allJava 75 | archiveClassifier = 'sources' 76 | } 77 | 78 | task javadocJar(type: Jar) { 79 | from javadoc 80 | archiveClassifier = 'javadoc' 81 | } 82 | 83 | artifacts { 84 | archives javadocJar, sourcesJar 85 | } 86 | 87 | publishing { 88 | publications { 89 | mavenJava(MavenPublication) { 90 | artifactId = "${project.name}" 91 | groupId = "${project.group}" 92 | version = "${project.version}" 93 | from components.java 94 | artifact javadocJar 95 | artifact sourcesJar 96 | artifact distZip 97 | artifact distTar 98 | 99 | pom { 100 | name = 'Context Map Generator' 101 | description = 'Context Mapper Command Line Interface (CLI)' 102 | url = 'https://github.com/ContextMapper/context-mapper-cli' 103 | organization { 104 | name = 'Context Mapper' 105 | url = 'https://contextmapper.org/' 106 | } 107 | licenses { 108 | license { 109 | name = 'Apache License 2.0' 110 | url = 'https://github.com/ContextMapper/context-mapper-cli/blob/master/LICENSE' 111 | } 112 | } 113 | issueManagement { 114 | system = 'GitHub' 115 | url = 'https://github.com/ContextMapper/context-mapper-cli/issues' 116 | } 117 | scm { 118 | url = 'https://github.com/ContextMapper/context-mapper-cli' 119 | connection = 'scm:git:git://github.com/ContextMapper/context-mapper-cli.git' 120 | developerConnection = 'scm:git:ssh://git@github.com:ContextMapper/context-mapper-cli.git' 121 | } 122 | developers { 123 | developer { 124 | name = 'Stefan Kapferer' 125 | email = 'stefan@contextmapper.org' 126 | } 127 | } 128 | } 129 | } 130 | } 131 | repositories { 132 | maven { 133 | def releasesRepoUrl = "${ossReleaseStagingRepository}" 134 | def snapshotsRepoUrl = "${ossSnapshotRepository}" 135 | url = project.version.toString().endsWith('SNAPSHOT') ? snapshotsRepoUrl : releasesRepoUrl 136 | 137 | credentials { 138 | username = System.getenv('OSSRH_USERNAME') 139 | password = System.getenv('OSSRH_PASSWORD') 140 | } 141 | } 142 | } 143 | } 144 | 145 | signing { 146 | sign(publishing.publications) 147 | } 148 | 149 | tasks.withType(GenerateModuleMetadata) { 150 | enabled = false 151 | } 152 | 153 | tasks.withType(CreateStartScripts).each { task -> 154 | task.doLast { 155 | String text = task.windowsScript.text 156 | text = text.replaceFirst(/(set CLASSPATH=%APP_HOME%\\lib\\).*/, { "${it[1]}*" }) 157 | task.windowsScript.write text 158 | } 159 | } 160 | -------------------------------------------------------------------------------- /codecov.yml: -------------------------------------------------------------------------------- 1 | coverage: 2 | status: 3 | project: on 4 | patch: off 5 | precision: 1 6 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Publication repos 2 | ossSnapshotRepository=https://oss.sonatype.org/content/repositories/snapshots/ 3 | ossReleaseStagingRepository=https://oss.sonatype.org/service/local/staging/deploy/maven2/ 4 | 5 | # dependency versions 6 | jUnitVersion=5.9.1 7 | assertJVersion=3.19.0 8 | mockitoVersion=3.9.0 9 | 10 | commonsCliVersion=1.4 11 | cmlVersion=6.12.0 12 | 13 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ContextMapper/context-mapper-cli/0489e369049f75eeaf2c79dcb4eaac850ecb9c00/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-8.14-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /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 | # SPDX-License-Identifier: Apache-2.0 19 | # 20 | 21 | ############################################################################## 22 | # 23 | # Gradle start up script for POSIX generated by Gradle. 24 | # 25 | # Important for running: 26 | # 27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 28 | # noncompliant, but you have some other compliant shell such as ksh or 29 | # bash, then to run this script, type that shell name before the whole 30 | # command line, like: 31 | # 32 | # ksh Gradle 33 | # 34 | # Busybox and similar reduced shells will NOT work, because this script 35 | # requires all of these POSIX shell features: 36 | # * functions; 37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 39 | # * compound commands having a testable exit status, especially «case»; 40 | # * various built-in commands including «command», «set», and «ulimit». 41 | # 42 | # Important for patching: 43 | # 44 | # (2) This script targets any POSIX shell, so it avoids extensions provided 45 | # by Bash, Ksh, etc; in particular arrays are avoided. 46 | # 47 | # The "traditional" practice of packing multiple parameters into a 48 | # space-separated string is a well documented source of bugs and security 49 | # problems, so this is (mostly) avoided, by progressively accumulating 50 | # options in "$@", and eventually passing that to Java. 51 | # 52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 54 | # see the in-line comments for details. 55 | # 56 | # There are tweaks for specific operating systems such as AIX, CygWin, 57 | # Darwin, MinGW, and NonStop. 58 | # 59 | # (3) This script is generated from the Groovy template 60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 61 | # within the Gradle project. 62 | # 63 | # You can find Gradle at https://github.com/gradle/gradle/. 64 | # 65 | ############################################################################## 66 | 67 | # Attempt to set APP_HOME 68 | 69 | # Resolve links: $0 may be a link 70 | app_path=$0 71 | 72 | # Need this for daisy-chained symlinks. 73 | while 74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 75 | [ -h "$app_path" ] 76 | do 77 | ls=$( ls -ld "$app_path" ) 78 | link=${ls#*' -> '} 79 | case $link in #( 80 | /*) app_path=$link ;; #( 81 | *) app_path=$APP_HOME$link ;; 82 | esac 83 | done 84 | 85 | # This is normally unused 86 | # shellcheck disable=SC2034 87 | APP_BASE_NAME=${0##*/} 88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s 90 | ' "$PWD" ) || exit 91 | 92 | # Use the maximum available, or set MAX_FD != -1 to use that value. 93 | MAX_FD=maximum 94 | 95 | warn () { 96 | echo "$*" 97 | } >&2 98 | 99 | die () { 100 | echo 101 | echo "$*" 102 | echo 103 | exit 1 104 | } >&2 105 | 106 | # OS specific support (must be 'true' or 'false'). 107 | cygwin=false 108 | msys=false 109 | darwin=false 110 | nonstop=false 111 | case "$( uname )" in #( 112 | CYGWIN* ) cygwin=true ;; #( 113 | Darwin* ) darwin=true ;; #( 114 | MSYS* | MINGW* ) msys=true ;; #( 115 | NONSTOP* ) nonstop=true ;; 116 | esac 117 | 118 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 119 | 120 | 121 | # Determine the Java command to use to start the JVM. 122 | if [ -n "$JAVA_HOME" ] ; then 123 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 124 | # IBM's JDK on AIX uses strange locations for the executables 125 | JAVACMD=$JAVA_HOME/jre/sh/java 126 | else 127 | JAVACMD=$JAVA_HOME/bin/java 128 | fi 129 | if [ ! -x "$JAVACMD" ] ; then 130 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 131 | 132 | Please set the JAVA_HOME variable in your environment to match the 133 | location of your Java installation." 134 | fi 135 | else 136 | JAVACMD=java 137 | if ! command -v java >/dev/null 2>&1 138 | then 139 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 140 | 141 | Please set the JAVA_HOME variable in your environment to match the 142 | location of your Java installation." 143 | fi 144 | fi 145 | 146 | # Increase the maximum file descriptors if we can. 147 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 148 | case $MAX_FD in #( 149 | max*) 150 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 151 | # shellcheck disable=SC2039,SC3045 152 | MAX_FD=$( ulimit -H -n ) || 153 | warn "Could not query maximum file descriptor limit" 154 | esac 155 | case $MAX_FD in #( 156 | '' | soft) :;; #( 157 | *) 158 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 159 | # shellcheck disable=SC2039,SC3045 160 | ulimit -n "$MAX_FD" || 161 | warn "Could not set maximum file descriptor limit to $MAX_FD" 162 | esac 163 | fi 164 | 165 | # Collect all arguments for the java command, stacking in reverse order: 166 | # * args from the command line 167 | # * the main class name 168 | # * -classpath 169 | # * -D...appname settings 170 | # * --module-path (only if needed) 171 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 172 | 173 | # For Cygwin or MSYS, switch paths to Windows format before running java 174 | if "$cygwin" || "$msys" ; then 175 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 176 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 177 | 178 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 179 | 180 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 181 | for arg do 182 | if 183 | case $arg in #( 184 | -*) false ;; # don't mess with options #( 185 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 186 | [ -e "$t" ] ;; #( 187 | *) false ;; 188 | esac 189 | then 190 | arg=$( cygpath --path --ignore --mixed "$arg" ) 191 | fi 192 | # Roll the args list around exactly as many times as the number of 193 | # args, so each arg winds up back in the position where it started, but 194 | # possibly modified. 195 | # 196 | # NB: a `for` loop captures its iteration list before it begins, so 197 | # changing the positional parameters here affects neither the number of 198 | # iterations, nor the values presented in `arg`. 199 | shift # remove old arg 200 | set -- "$@" "$arg" # push replacement arg 201 | done 202 | fi 203 | 204 | 205 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 206 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 207 | 208 | # Collect all arguments for the java command: 209 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 210 | # and any embedded shellness will be escaped. 211 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 212 | # treated as '${Hostname}' itself on the command line. 213 | 214 | set -- \ 215 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 216 | -classpath "$CLASSPATH" \ 217 | org.gradle.wrapper.GradleWrapperMain \ 218 | "$@" 219 | 220 | # Stop when "xargs" is not available. 221 | if ! command -v xargs >/dev/null 2>&1 222 | then 223 | die "xargs is not available" 224 | fi 225 | 226 | # Use "xargs" to parse quoted args. 227 | # 228 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 229 | # 230 | # In Bash we could simply go: 231 | # 232 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 233 | # set -- "${ARGS[@]}" "$@" 234 | # 235 | # but POSIX shell has neither arrays nor command substitution, so instead we 236 | # post-process each arg (as a line of input to sed) to backslash-escape any 237 | # character that might be a shell metacharacter, then use eval to reverse 238 | # that process (while maintaining the separation between arguments), and wrap 239 | # the whole thing up as a single "set" statement. 240 | # 241 | # This will of course break if any of these variables contains a newline or 242 | # an unmatched quote. 243 | # 244 | 245 | eval "set -- $( 246 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 247 | xargs -n1 | 248 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 249 | tr '\n' ' ' 250 | )" '"$@"' 251 | 252 | exec "$JAVACMD" "$@" 253 | -------------------------------------------------------------------------------- /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 | @rem SPDX-License-Identifier: Apache-2.0 17 | @rem 18 | 19 | @if "%DEBUG%"=="" @echo off 20 | @rem ########################################################################## 21 | @rem 22 | @rem Gradle startup script for Windows 23 | @rem 24 | @rem ########################################################################## 25 | 26 | @rem Set local scope for the variables with windows NT shell 27 | if "%OS%"=="Windows_NT" setlocal 28 | 29 | set DIRNAME=%~dp0 30 | if "%DIRNAME%"=="" set DIRNAME=. 31 | @rem This is normally unused 32 | set APP_BASE_NAME=%~n0 33 | set APP_HOME=%DIRNAME% 34 | 35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 37 | 38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 40 | 41 | @rem Find java.exe 42 | if defined JAVA_HOME goto findJavaFromJavaHome 43 | 44 | set JAVA_EXE=java.exe 45 | %JAVA_EXE% -version >NUL 2>&1 46 | if %ERRORLEVEL% equ 0 goto execute 47 | 48 | echo. 1>&2 49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 50 | echo. 1>&2 51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 52 | echo location of your Java installation. 1>&2 53 | 54 | goto fail 55 | 56 | :findJavaFromJavaHome 57 | set JAVA_HOME=%JAVA_HOME:"=% 58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 59 | 60 | if exist "%JAVA_EXE%" goto execute 61 | 62 | echo. 1>&2 63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 64 | echo. 1>&2 65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 66 | echo location of your Java installation. 1>&2 67 | 68 | goto fail 69 | 70 | :execute 71 | @rem Setup the command line 72 | 73 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 74 | 75 | 76 | @rem Execute Gradle 77 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 78 | 79 | :end 80 | @rem End local scope for the variables with windows NT shell 81 | if %ERRORLEVEL% equ 0 goto mainEnd 82 | 83 | :fail 84 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 85 | rem the _cmd.exe /c_ return code! 86 | set EXIT_CODE=%ERRORLEVEL% 87 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 88 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 89 | exit /b %EXIT_CODE% 90 | 91 | :mainEnd 92 | if "%OS%"=="Windows_NT" endlocal 93 | 94 | :omega 95 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'context-mapper-cli' 2 | 3 | -------------------------------------------------------------------------------- /src/main/java/org/contextmapper/cli/ContextMapperCLI.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 The Context Mapper Project Team 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.contextmapper.cli; 17 | 18 | import org.contextmapper.cli.commands.CliCommand; 19 | import org.contextmapper.cli.commands.GenerateCommand; 20 | import org.contextmapper.cli.commands.ValidateCommand; 21 | 22 | import java.util.Arrays; 23 | import java.util.Collections; 24 | import java.util.List; 25 | 26 | public class ContextMapperCLI { 27 | 28 | private static final int REQUIRED_JAVA_VERSION = 11; 29 | private static final String VALIDATE_COMMAND = "validate"; 30 | private static final String GENERATE_COMMAND = "generate"; 31 | 32 | private CliCommand generateCommand; 33 | private CliCommand validateCommand; 34 | 35 | public ContextMapperCLI() { 36 | this.generateCommand = new GenerateCommand(); 37 | this.validateCommand = new ValidateCommand(); 38 | } 39 | 40 | public static void main(String[] args) { 41 | int javaVersion = Runtime.version().feature(); 42 | 43 | if (Runtime.version().feature() >= REQUIRED_JAVA_VERSION) { 44 | new ContextMapperCLI().run(args); 45 | } else { 46 | System.out.printf("Invalid Java version '%s' (>=%s is required).", javaVersion, REQUIRED_JAVA_VERSION); 47 | System.exit(1); 48 | } 49 | } 50 | 51 | protected void run(String[] args) { 52 | System.out.println("Context Mapper CLI " + getVersion()); 53 | 54 | if (args == null || args.length == 0) { 55 | printUsages(); 56 | } else if (VALIDATE_COMMAND.equalsIgnoreCase(args[0])) { 57 | validateCommand.run(Arrays.copyOfRange(args, 1, args.length)); 58 | } else if (GENERATE_COMMAND.equalsIgnoreCase(args[0])) { 59 | generateCommand.run(Arrays.copyOfRange(args, 1, args.length)); 60 | } else { 61 | System.out.println("Invalid input"); 62 | System.exit(127); 63 | } 64 | } 65 | 66 | private void printUsages() { 67 | System.out.println("Usage: cm " + VALIDATE_COMMAND + "|" + GENERATE_COMMAND + " [options]"); 68 | } 69 | 70 | private String getVersion() { 71 | String implVersion = ContextMapperCLI.class.getPackage().getImplementationVersion(); 72 | return implVersion != null ? "v" + implVersion : "DEVELOPMENT VERSION"; 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/org/contextmapper/cli/commands/AbstractCliCommand.java: -------------------------------------------------------------------------------- 1 | package org.contextmapper.cli.commands; 2 | 3 | import java.io.File; 4 | 5 | public abstract class AbstractCliCommand implements CliCommand { 6 | 7 | protected boolean isInputFileValid(String inputPath) { 8 | File inputFile = new File(inputPath); 9 | if (!inputFile.exists()) { 10 | System.out.println("ERROR: The file '" + inputPath + "' does not exist."); 11 | return false; 12 | } 13 | if (!inputPath.endsWith(".cml")) { 14 | System.out.println("ERROR: Please provide a path to a CML (*.cml) file."); 15 | return false; 16 | } 17 | return true; 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/org/contextmapper/cli/commands/CliCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 The Context Mapper Project Team 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.contextmapper.cli.commands; 17 | 18 | public interface CliCommand { 19 | 20 | /** 21 | * Runs a CLI command. 22 | * 23 | * @param args the arguments passed in addition to the command 24 | */ 25 | void run(String[] args); 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/org/contextmapper/cli/commands/ContextMapperGenerator.java: -------------------------------------------------------------------------------- 1 | package org.contextmapper.cli.commands; 2 | 3 | import org.contextmapper.dsl.generator.ContextMapGenerator; 4 | import org.contextmapper.dsl.generator.GenericContentGenerator; 5 | import org.contextmapper.dsl.generator.PlantUMLGenerator; 6 | import org.eclipse.xtext.generator.IGenerator2; 7 | 8 | public enum ContextMapperGenerator { 9 | 10 | CONTEXT_MAP("context-map", "Graphical DDD Context Map"), 11 | PLANT_UML("plantuml", "PlantUML class-, component-, and state diagrams."), 12 | GENERIC("generic", "Generate generic text with Freemarker template"); 13 | 14 | private final String name; 15 | private final String description; 16 | 17 | ContextMapperGenerator(String name, String description) { 18 | this.name = name; 19 | this.description = description; 20 | } 21 | 22 | public String getName() { 23 | return name; 24 | } 25 | 26 | public String getDescription() { 27 | return description; 28 | } 29 | 30 | @Override 31 | public String toString() { 32 | return this.name + " (" + this.description + ")"; 33 | } 34 | 35 | public static ContextMapperGenerator byName(String name) { 36 | if (name == null || "".equals(name)) 37 | throw new IllegalArgumentException("Please provide a name for the generator."); 38 | 39 | for (ContextMapperGenerator generator : values()) { 40 | if (generator.getName().equals(name)) 41 | return generator; 42 | } 43 | 44 | throw new IllegalArgumentException("No generator found for the name '" + name + "'."); 45 | } 46 | 47 | public IGenerator2 getGenerator() { 48 | if (this == CONTEXT_MAP) 49 | return new ContextMapGenerator(); 50 | if (this == PLANT_UML) 51 | return new PlantUMLGenerator(); 52 | return new GenericContentGenerator(); 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/org/contextmapper/cli/commands/GenerateCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 The Context Mapper Project Team 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.contextmapper.cli.commands; 17 | 18 | import org.apache.commons.cli.*; 19 | import org.contextmapper.dsl.cml.CMLResource; 20 | import org.contextmapper.dsl.generator.GenericContentGenerator; 21 | import org.contextmapper.dsl.standalone.ContextMapperStandaloneSetup; 22 | import org.contextmapper.dsl.standalone.StandaloneContextMapperAPI; 23 | import org.eclipse.xtext.generator.IGenerator2; 24 | 25 | import java.io.File; 26 | import java.util.Arrays; 27 | import java.util.stream.Collectors; 28 | 29 | public class GenerateCommand extends AbstractCliCommand { 30 | 31 | private String outputDir = "./"; 32 | 33 | @Override 34 | public void run(String[] args) { 35 | Options options = createOptions(); 36 | 37 | CommandLineParser commandLineParser = new DefaultParser(); 38 | 39 | try { 40 | CommandLine cmd = commandLineParser.parse(options, args); 41 | 42 | if (cmd.hasOption("help") || cmd.hasOption("h")) { 43 | printHelp(options); 44 | } else { 45 | String inputPath = cmd.getOptionValue("input").trim(); 46 | if (!isInputFileValid(inputPath)) 47 | return; 48 | 49 | if (cmd.hasOption("outputDir")) 50 | this.outputDir = cmd.getOptionValue("outputDir"); 51 | 52 | if (doesOutputDirExist(this.outputDir)) { 53 | StandaloneContextMapperAPI cmAPI = ContextMapperStandaloneSetup.getStandaloneAPI(); 54 | CMLResource cmlResource = cmAPI.loadCML(inputPath); 55 | cmAPI.callGenerator(cmlResource, getGenerator(cmd), this.outputDir); 56 | System.out.println("Generated into '" + this.outputDir + "'."); 57 | } 58 | } 59 | } catch (ParseException e) { 60 | printHelp(options); 61 | } 62 | } 63 | 64 | private IGenerator2 getGenerator(CommandLine cmd) { 65 | final ContextMapperGenerator generator = ContextMapperGenerator.byName(cmd.getOptionValue("generator")); 66 | if (generator.getGenerator() instanceof GenericContentGenerator) { 67 | final GenericContentGenerator genericContentGenerator = (GenericContentGenerator) generator.getGenerator(); 68 | genericContentGenerator.setFreemarkerTemplateFile(new File(cmd.getOptionValue("template"))); 69 | genericContentGenerator.setTargetFileName(cmd.getOptionValue("outputFile")); 70 | return genericContentGenerator; 71 | } 72 | return generator.getGenerator(); 73 | } 74 | 75 | private Options createOptions() { 76 | Options options = new Options(); 77 | 78 | Option input = new Option("i", "input", true, "Path to the CML file for which you want to generate output."); 79 | input.setRequired(true); 80 | options.addOption(input); 81 | 82 | Option generator = new Option("g", "generator", true, 83 | "The generator you want to call. Use one of the following values: " + 84 | Arrays.stream(ContextMapperGenerator.values()).map(ContextMapperGenerator::toString).collect(Collectors.joining(", "))); 85 | generator.setRequired(true); 86 | options.addOption(generator); 87 | 88 | options.addOption(new Option("o", "outputDir", true, "Path to the directory into which you want to generate.")); 89 | options.addOption(new Option("t", "template", true, 90 | "Path to the Freemarker template you want to use. This parameter is only used if you pass 'generic' to the 'generator' (-g) parameter.")); 91 | options.addOption(new Option("f", "outputFile", true, 92 | "The name of the file that shall be generated (only used by Freemarker generator, as we cannot know the file extension).")); 93 | options.addOption(new Option("h", "help", false, "Prints this message.")); 94 | 95 | return options; 96 | } 97 | 98 | protected void printHelp(final Options options) { 99 | new HelpFormatter().printHelp("cm generate", options); 100 | } 101 | 102 | private boolean doesOutputDirExist(String outputDir) { 103 | if (outputDir == null || "".equals(outputDir)) { 104 | System.out.println("ERROR: '" + outputDir + "' is not a directory."); 105 | return false; 106 | } 107 | 108 | File dir = new File(outputDir); 109 | if (!dir.exists() || !dir.isDirectory()) { 110 | System.out.println("ERROR: '" + outputDir + "' is not a directory."); 111 | return false; 112 | } 113 | return true; 114 | } 115 | 116 | } 117 | -------------------------------------------------------------------------------- /src/main/java/org/contextmapper/cli/commands/ValidateCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 The Context Mapper Project Team 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.contextmapper.cli.commands; 17 | 18 | import org.apache.commons.cli.*; 19 | import org.contextmapper.dsl.cml.CMLResource; 20 | import org.contextmapper.dsl.standalone.ContextMapperStandaloneSetup; 21 | import org.contextmapper.dsl.standalone.StandaloneContextMapperAPI; 22 | import org.eclipse.emf.ecore.resource.Resource.Diagnostic; 23 | 24 | public class ValidateCommand extends AbstractCliCommand { 25 | 26 | @Override 27 | public void run(String[] args) { 28 | Options options = createOptions(); 29 | 30 | CommandLineParser commandLineParser = new DefaultParser(); 31 | 32 | try { 33 | CommandLine cmd = commandLineParser.parse(options, args); 34 | 35 | if (cmd.hasOption("help") || cmd.hasOption("h")) { 36 | printHelp(options); 37 | } else { 38 | // check that input CML files exists 39 | String inputPath = cmd.getOptionValue("input").trim(); 40 | if (!isInputFileValid(inputPath)) 41 | return; 42 | 43 | // load CML file 44 | StandaloneContextMapperAPI cmAPI = ContextMapperStandaloneSetup.getStandaloneAPI(); 45 | CMLResource cmlResource = cmAPI.loadCML(inputPath); 46 | 47 | // print validation errors/warnings 48 | printValidationMessages(cmlResource, inputPath); 49 | } 50 | } catch (ParseException e) { 51 | printHelp(options); 52 | } 53 | } 54 | 55 | private Options createOptions() { 56 | Options options = new Options(); 57 | 58 | Option help = new Option("h", "help", false, "Prints this message."); 59 | options.addOption(help); 60 | 61 | Option input = new Option("i", "input", true, "Path to the CML file which you want to validate."); 62 | input.setRequired(true); 63 | options.addOption(input); 64 | 65 | return options; 66 | } 67 | 68 | protected void printValidationMessages(final CMLResource cmlResource, final String filePath) { 69 | if (cmlResource.getErrors().isEmpty()) { 70 | System.out.println("The CML file '" + filePath + "' has been validated without errors."); 71 | } else { 72 | for (Diagnostic diagnostic : cmlResource.getErrors()) { 73 | System.out.println("ERROR in " + diagnostic.getLocation() + " on line " + diagnostic.getLine() + ":" 74 | + diagnostic.getMessage()); 75 | } 76 | } 77 | 78 | for (Diagnostic diagnostic : cmlResource.getWarnings()) { 79 | System.out.println("WARNING in " + diagnostic.getLocation() + " on line " + diagnostic.getLine() + ":" 80 | + diagnostic.getMessage()); 81 | } 82 | } 83 | 84 | protected void printHelp(final Options options) { 85 | new HelpFormatter().printHelp("cm validate", options); 86 | } 87 | 88 | } 89 | -------------------------------------------------------------------------------- /src/test/java/org/contextmapper/cli/ContextMapperCLITest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 The Context Mapper Project Team 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.contextmapper.cli; 17 | 18 | import org.contextmapper.cli.commands.GenerateCommand; 19 | import org.contextmapper.cli.commands.ValidateCommand; 20 | import org.junit.jupiter.api.AfterEach; 21 | import org.junit.jupiter.api.BeforeEach; 22 | import org.junit.jupiter.api.Test; 23 | import org.junit.jupiter.api.extension.ExtendWith; 24 | import org.mockito.InjectMocks; 25 | import org.mockito.Mock; 26 | import org.mockito.junit.jupiter.MockitoExtension; 27 | 28 | import java.io.ByteArrayOutputStream; 29 | import java.io.PrintStream; 30 | 31 | import static org.assertj.core.api.Assertions.assertThat; 32 | import static org.mockito.Mockito.verify; 33 | 34 | @ExtendWith(MockitoExtension.class) 35 | class ContextMapperCLITest { 36 | 37 | private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); 38 | private final ByteArrayOutputStream errContent = new ByteArrayOutputStream(); 39 | private final PrintStream originalOut = System.out; 40 | private final PrintStream originalErr = System.err; 41 | 42 | @Mock 43 | private ValidateCommand validateCommand; 44 | 45 | @Mock 46 | private GenerateCommand generateCommand; 47 | 48 | @InjectMocks 49 | private ContextMapperCLI contextMapperCLI; 50 | 51 | @BeforeEach 52 | public void setUpStreams() { 53 | System.setOut(new PrintStream(outContent)); 54 | System.setErr(new PrintStream(errContent)); 55 | } 56 | 57 | @AfterEach 58 | public void restoreStreams() { 59 | System.setOut(originalOut); 60 | System.setErr(originalErr); 61 | } 62 | 63 | @Test 64 | void main_WhenCalledWithoutCommand_ThenPrintUsage() { 65 | // given 66 | final String[] params = new String[]{}; 67 | 68 | // when 69 | ContextMapperCLI.main(params); 70 | 71 | // then 72 | assertThat(outContent.toString()).isEqualTo("Context Mapper CLI DEVELOPMENT VERSION" + System.lineSeparator() + 73 | "Usage: cm validate|generate [options]" + System.lineSeparator()); 74 | } 75 | 76 | @Test 77 | void run_WhenCalledWithoutCommand_ThenPrintUsage() { 78 | // given 79 | final String[] params = new String[]{}; 80 | 81 | // when 82 | contextMapperCLI.run(params); 83 | 84 | // then 85 | assertThat(outContent.toString()).isEqualTo("Context Mapper CLI DEVELOPMENT VERSION" + System.lineSeparator() + 86 | "Usage: cm validate|generate [options]" + System.lineSeparator()); 87 | } 88 | 89 | @Test 90 | void run_WhenCalledWithValidate_ThenCallValidateCommand() { 91 | // given 92 | final String[] params = new String[]{"validate"}; 93 | 94 | // when 95 | contextMapperCLI.run(params); 96 | 97 | // then 98 | verify(validateCommand).run(new String[]{}); 99 | } 100 | 101 | @Test 102 | void run_WhenCalledWithValidateAndAdditionalParams_ThenCallValidateCommandWithParams() { 103 | // given 104 | final String[] params = new String[]{"validate", "test-param"}; 105 | 106 | // when 107 | contextMapperCLI.run(params); 108 | 109 | // then 110 | verify(validateCommand).run(new String[]{"test-param"}); 111 | } 112 | 113 | @Test 114 | void run_WhenCalledWithGenerate_ThenCallGenerateCommand() { 115 | // given 116 | final String[] params = new String[]{"generate"}; 117 | 118 | // when 119 | contextMapperCLI.run(params); 120 | 121 | // then 122 | verify(generateCommand).run(new String[]{}); 123 | } 124 | 125 | @Test 126 | void run_WhenCalledWithGenerateAndAdditionalParams_ThenCallGenerateCommandWithParams() { 127 | // given 128 | final String[] params = new String[]{"generate", "plantuml"}; 129 | 130 | // when 131 | contextMapperCLI.run(params); 132 | 133 | // then 134 | verify(generateCommand).run(new String[]{"plantuml"}); 135 | } 136 | 137 | } 138 | -------------------------------------------------------------------------------- /src/test/java/org/contextmapper/cli/commands/ContextMapperGeneratorTest.java: -------------------------------------------------------------------------------- 1 | package org.contextmapper.cli.commands; 2 | 3 | import org.eclipse.xtext.generator.IGenerator2; 4 | import org.junit.jupiter.api.Test; 5 | import org.junit.jupiter.params.ParameterizedTest; 6 | import org.junit.jupiter.params.provider.ValueSource; 7 | 8 | import static org.assertj.core.api.Assertions.assertThat; 9 | import static org.assertj.core.api.Assertions.assertThatExceptionOfType; 10 | 11 | class ContextMapperGeneratorTest { 12 | 13 | @ParameterizedTest 14 | @ValueSource(strings = {"CONTEXT_MAP", "PLANT_UML", "GENERIC"}) 15 | void getName_WhenUsingGeneratorEnumValue_ThenCanGetGeneratorName(final String enumValueAsString) { 16 | // given 17 | final ContextMapperGenerator generator = ContextMapperGenerator.valueOf(enumValueAsString); 18 | 19 | // when 20 | final String name = generator.getName(); 21 | 22 | // then 23 | assertThat(name) 24 | .isNotNull() 25 | .isNotEmpty(); 26 | } 27 | 28 | @ParameterizedTest 29 | @ValueSource(strings = {"CONTEXT_MAP", "PLANT_UML", "GENERIC"}) 30 | void getDescription_WhenUsingGeneratorEnumValue_ThenCanGetGeneratorDescription(final String enumValueAsString) { 31 | // given 32 | final ContextMapperGenerator generator = ContextMapperGenerator.valueOf(enumValueAsString); 33 | 34 | // when 35 | final String description = generator.getDescription(); 36 | 37 | // then 38 | assertThat(description) 39 | .isNotNull() 40 | .isNotEmpty(); 41 | } 42 | 43 | @ParameterizedTest 44 | @ValueSource(strings = {"CONTEXT_MAP", "PLANT_UML", "GENERIC"}) 45 | void toString_WhenUsingGeneratorEnumValue_ThenCanGetStringRepresentation(final String enumValueAsString) { 46 | // given 47 | final ContextMapperGenerator generator = ContextMapperGenerator.valueOf(enumValueAsString); 48 | 49 | // when 50 | final String stringRepresentation = generator.toString(); 51 | 52 | // then 53 | assertThat(stringRepresentation) 54 | .isNotNull() 55 | .isNotEmpty(); 56 | } 57 | 58 | @ParameterizedTest 59 | @ValueSource(strings = {"context-map", "plantuml", "generic"}) 60 | void byName_WhenWithValidName_ThenReturnGenerator(final String validGeneratorKey) { 61 | // when 62 | final ContextMapperGenerator generator = ContextMapperGenerator.byName(validGeneratorKey); 63 | 64 | // then 65 | assertThat(generator).isNotNull(); 66 | } 67 | 68 | @Test 69 | void byName_WhenWithoutName_ThenThrowIllegalArgumentException() { 70 | assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> 71 | ContextMapperGenerator.byName(null)); 72 | } 73 | 74 | @Test 75 | void byName_WhenWithEmptyName_ThenThrowIllegalArgumentException() { 76 | assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> 77 | ContextMapperGenerator.byName("")); 78 | } 79 | 80 | @Test 81 | void byName_WhenWithInvalidName_ThenThrowIllegalArgumentException() { 82 | assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> 83 | ContextMapperGenerator.byName("just a string")); 84 | } 85 | 86 | @ParameterizedTest 87 | @ValueSource(strings = {"CONTEXT_MAP", "PLANT_UML", "GENERIC"}) 88 | void getGenerator_WhenCalled_ThenReturnGeneratorImplementation(final String enumValueAsString) { 89 | // given 90 | final ContextMapperGenerator generator = ContextMapperGenerator.valueOf(enumValueAsString); 91 | 92 | // when 93 | final IGenerator2 generatorImpl = generator.getGenerator(); 94 | 95 | // then 96 | assertThat(generatorImpl).isNotNull(); 97 | } 98 | 99 | } 100 | -------------------------------------------------------------------------------- /src/test/java/org/contextmapper/cli/commands/GenerateCommandTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 The Context Mapper Project Team 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.contextmapper.cli.commands; 17 | 18 | import org.junit.jupiter.api.AfterEach; 19 | import org.junit.jupiter.api.BeforeEach; 20 | import org.junit.jupiter.api.Test; 21 | import org.junit.jupiter.api.extension.ExtendWith; 22 | import org.junit.jupiter.params.ParameterizedTest; 23 | import org.junit.jupiter.params.provider.ValueSource; 24 | import org.mockito.junit.jupiter.MockitoExtension; 25 | 26 | import java.io.ByteArrayOutputStream; 27 | import java.io.File; 28 | import java.io.IOException; 29 | import java.io.PrintStream; 30 | import java.nio.file.Files; 31 | import java.nio.file.Path; 32 | import java.util.Comparator; 33 | 34 | import static org.assertj.core.api.Assertions.assertThat; 35 | import static org.mockito.Mockito.*; 36 | 37 | @ExtendWith(MockitoExtension.class) 38 | class GenerateCommandTest { 39 | 40 | private static final String TEST_OUT_DIR = "build/test-out"; 41 | 42 | private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); 43 | private final ByteArrayOutputStream errContent = new ByteArrayOutputStream(); 44 | private final PrintStream originalOut = System.out; 45 | private final PrintStream originalErr = System.err; 46 | 47 | private File testOutDir; 48 | 49 | @BeforeEach 50 | public void setUpStreams() throws IOException { 51 | testOutDir = new File(TEST_OUT_DIR); 52 | if (testOutDir.exists()) { 53 | Files.walk(testOutDir.toPath()) 54 | .sorted(Comparator.reverseOrder()) 55 | .map(Path::toFile) 56 | .forEach(File::delete); 57 | } 58 | testOutDir.mkdir(); 59 | 60 | System.setOut(new PrintStream(outContent)); 61 | System.setErr(new PrintStream(errContent)); 62 | } 63 | 64 | @AfterEach 65 | public void restoreStreams() { 66 | System.setOut(originalOut); 67 | System.setErr(originalErr); 68 | } 69 | 70 | @ParameterizedTest 71 | @ValueSource(strings = {"-h", "--help", "-i some-file.cml -g plantuml -h", "-i some-file.cml -g plantuml --help"}) 72 | void run_WhenCalledWithHelp_ThenPrintHelp(final String params) { 73 | // given 74 | final GenerateCommand command = spy(new GenerateCommand()); 75 | 76 | // when 77 | command.run(params.split(" ")); 78 | 79 | // then 80 | verify(command).printHelp(any()); 81 | } 82 | 83 | @Test 84 | void run_WhenCalledWithNonExistingOutDir_ThenPrintError() { 85 | // given 86 | final GenerateCommand command = spy(new GenerateCommand()); 87 | 88 | // when 89 | command.run(new String[]{"-i", "src/test/resources/test.cml", "-g", "plantuml", "-o", "/just-some-dir-that-hopefully-not-exists"}); 90 | 91 | // then 92 | assertThat(outContent.toString()).contains("ERROR: '/just-some-dir-that-hopefully-not-exists' is not a directory."); 93 | } 94 | 95 | @Test 96 | void run_WhenCalledWithNonExistingInputFile_ThenPrintError() { 97 | // given 98 | final GenerateCommand command = spy(new GenerateCommand()); 99 | 100 | // when 101 | command.run(new String[]{"-i", "just-a-file.cml", "-g", "plantuml", "-o", "/build"}); 102 | 103 | // then 104 | assertThat(outContent.toString()).contains("ERROR: The file 'just-a-file.cml' does not exist."); 105 | } 106 | 107 | @Test 108 | void run_WhenCalledWithPlantUMLParam_ThenGeneratePlantUMLFiles() { 109 | // given 110 | final GenerateCommand command = spy(new GenerateCommand()); 111 | new File("build/test-out").mkdir(); 112 | 113 | // when 114 | command.run(new String[]{"-i", "src/test/resources/test.cml", "-g", "plantuml", "-o", "build/test-out"}); 115 | 116 | // then 117 | assertThat(outContent.toString()).contains("Generated into 'build/test-out'."); 118 | assertThat(new File("build/test-out/test_BC_CargoBookingContext.puml").exists()).isTrue(); 119 | assertThat(new File("build/test-out/test_BC_LocationContext.puml").exists()).isTrue(); 120 | assertThat(new File("build/test-out/test_BC_VoyagePlanningContext.puml").exists()).isTrue(); 121 | assertThat(new File("build/test-out/test_ContextMap.puml").exists()).isTrue(); 122 | } 123 | 124 | @Test 125 | void run_WhenCalledWithContextMapParam_ThenGenerateContextMapFiles() { 126 | // given 127 | final GenerateCommand command = spy(new GenerateCommand()); 128 | new File("build/test-out").mkdir(); 129 | 130 | // when 131 | command.run(new String[]{"-i", "src/test/resources/test.cml", "-g", "context-map", "-o", "build/test-out"}); 132 | 133 | // then 134 | assertThat(outContent.toString()).contains("Generated into 'build/test-out'."); 135 | assertThat(new File("build/test-out/test_ContextMap.gv").exists()).isTrue(); 136 | assertThat(new File("build/test-out/test_ContextMap.png").exists()).isTrue(); 137 | assertThat(new File("build/test-out/test_ContextMap.svg").exists()).isTrue(); 138 | } 139 | 140 | @Test 141 | void run_WhenCalledWithGenericParam_ThenGenerateGenericOutput() { 142 | // given 143 | final GenerateCommand command = spy(new GenerateCommand()); 144 | new File("build/test-out").mkdir(); 145 | 146 | // when 147 | command.run(new String[]{"-i", "src/test/resources/test.cml", "-g", "generic", "-o", "build/test-out", "-t", "src/test/resources/test.ftl", "-f", "test.md"}); 148 | 149 | // then 150 | assertThat(outContent.toString()).contains("Generated into 'build/test-out'."); 151 | assertThat(new File("build/test-out/test.md").exists()).isTrue(); 152 | } 153 | 154 | } 155 | -------------------------------------------------------------------------------- /src/test/java/org/contextmapper/cli/commands/ValidateCommandTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 The Context Mapper Project Team 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.contextmapper.cli.commands; 17 | 18 | import org.junit.jupiter.api.AfterEach; 19 | import org.junit.jupiter.api.BeforeEach; 20 | import org.junit.jupiter.api.Test; 21 | import org.junit.jupiter.api.extension.ExtendWith; 22 | import org.junit.jupiter.params.ParameterizedTest; 23 | import org.junit.jupiter.params.provider.ValueSource; 24 | import org.mockito.junit.jupiter.MockitoExtension; 25 | 26 | import java.io.ByteArrayOutputStream; 27 | import java.io.PrintStream; 28 | 29 | import static org.assertj.core.api.Assertions.assertThat; 30 | import static org.mockito.Mockito.*; 31 | 32 | @ExtendWith(MockitoExtension.class) 33 | class ValidateCommandTest { 34 | 35 | private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); 36 | private final ByteArrayOutputStream errContent = new ByteArrayOutputStream(); 37 | private final PrintStream originalOut = System.out; 38 | private final PrintStream originalErr = System.err; 39 | 40 | @BeforeEach 41 | public void setUpStreams() { 42 | System.setOut(new PrintStream(outContent)); 43 | System.setErr(new PrintStream(errContent)); 44 | } 45 | 46 | @AfterEach 47 | public void restoreStreams() { 48 | System.setOut(originalOut); 49 | System.setErr(originalErr); 50 | } 51 | 52 | @ParameterizedTest 53 | @ValueSource(strings = {"-h", "--help", "-i some-file.cml -h", "-i some-file.cml --help"}) 54 | void run_WhenCalledWithHelp_ThenPrintHelp(final String params) { 55 | // given 56 | final ValidateCommand command = spy(new ValidateCommand()); 57 | 58 | // when 59 | command.run(params.split(" ")); 60 | 61 | // then 62 | verify(command).printHelp(any()); 63 | } 64 | 65 | @Test 66 | void run_WhenWithValidCMLFile_ThenValidateWithoutErrors() { 67 | // given 68 | final ValidateCommand command = spy(new ValidateCommand()); 69 | 70 | // when 71 | command.run(new String[]{"-i src/test/resources/test.cml"}); 72 | 73 | // then 74 | verify(command).printValidationMessages(any(), any()); 75 | assertThat(outContent.toString()).contains("The CML file 'src/test/resources/test.cml' has been validated without errors."); 76 | } 77 | 78 | @Test 79 | void run_WhenWithInvalidCMLFile_ThenPrintError() { 80 | // given 81 | final ValidateCommand command = spy(new ValidateCommand()); 82 | 83 | // when 84 | command.run(new String[]{"-i src/test/resources/test-with-error.cml"}); 85 | 86 | // then 87 | verify(command).printValidationMessages(any(), any()); 88 | assertThat(outContent.toString()).contains("ERROR in null on line 2:mismatched input '' expecting RULE_CLOSE"); 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /src/test/resources/test-with-error.cml: -------------------------------------------------------------------------------- 1 | 2 | ContextMap DDDSampleMap { 3 | -------------------------------------------------------------------------------- /src/test/resources/test.cml: -------------------------------------------------------------------------------- 1 | /* The DDD Cargo sample application modeled in CML. Note that we split the application into multiple bounded contexts. */ 2 | ContextMap DDDSampleMap { 3 | contains CargoBookingContext 4 | contains VoyagePlanningContext 5 | contains LocationContext 6 | 7 | /* As Evans mentions in his book (Bounded Context chapter): The voyage planning can be seen as 8 | * separated bounded context. However, it still shares code with the booking application (CargoBookingContext). 9 | * Thus, they are in a 'Shared-Kernel' relationship. 10 | */ 11 | CargoBookingContext [SK]<->[SK] VoyagePlanningContext 12 | 13 | /* Note that the splitting of the LocationContext is not mentioned in the original DDD sample of Evans. 14 | * However, locations and the management around them, can somehow be seen as a separated concept which is used by other 15 | * bounded contexts. But this is just an example, since we want to demonstrate our DSL with multiple bounded contexts. 16 | */ 17 | CargoBookingContext <- LocationContext 18 | 19 | VoyagePlanningContext <- LocationContext 20 | 21 | } 22 | 23 | /* The original booking application context */ 24 | BoundedContext CargoBookingContext 25 | 26 | /* We split the Voyage Planning into a separate bounded context as Evans proposes it in his book. */ 27 | BoundedContext VoyagePlanningContext 28 | 29 | /* Separate bounded context for managing the locations. */ 30 | BoundedContext LocationContext 31 | -------------------------------------------------------------------------------- /src/test/resources/test.ftl: -------------------------------------------------------------------------------- 1 | <#if boundedContexts?has_content> 2 | <#list boundedContexts as bc> 3 | * ${bc.name}<#lt> 4 | 5 | --------------------------------------------------------------------------------