├── .editorconfig ├── .gitattributes ├── .github └── workflows │ ├── build-and-deploy.yml │ └── dispatcher.yml ├── .gitignore ├── .gitmodules ├── .mergify.yml ├── CHANGELOG.md ├── LICENSE ├── README.md ├── build.gradle.kts ├── gradle.properties ├── gradle ├── libs.versions.toml └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── package-lock.json ├── package.json ├── release.config.mjs ├── renovate.json ├── settings.gradle.kts └── src ├── main ├── kotlin │ └── org │ │ └── danilopianini │ │ └── gradle │ │ └── gitsemver │ │ ├── GitSemVer.kt │ │ ├── GitSemVerExtension.kt │ │ ├── SemanticVersion.kt │ │ ├── UpdateType.kt │ │ └── source │ │ └── GitCommandValueSource.kt └── resources │ └── META-INF │ └── gradle-plugins │ └── org.danilopianini.git-semver.properties └── test └── kotlin └── org └── danilopianini └── gradle └── gitsemver └── test └── Tests.kt /.editorconfig: -------------------------------------------------------------------------------- 1 | [*.{kt,kts}] 2 | ktlint_code_style = intellij_idea 3 | max_line_length=120 4 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto eol=lf 2 | *.[cC][mM][dD] text eol=crlf 3 | *.[bB][aA][tT] text eol=crlf 4 | *.[pP][sS]1 text eol=crlf 5 | -------------------------------------------------------------------------------- /.github/workflows/build-and-deploy.yml: -------------------------------------------------------------------------------- 1 | name: CI/CD Process 2 | on: 3 | workflow_call: 4 | workflow_dispatch: 5 | 6 | jobs: 7 | build: 8 | strategy: 9 | fail-fast: false 10 | matrix: 11 | os: [windows-2025, macos-14, ubuntu-24.04] 12 | runs-on: ${{ matrix.os }} 13 | steps: 14 | - name: Checkout 15 | uses: DanySK/action-checkout@0.2.22 16 | - uses: DanySK/build-check-deploy-gradle-action@3.7.20 17 | with: 18 | deploy-command: >- 19 | ./gradlew 20 | uploadAllToMavenCentralNexus 21 | close 22 | dropStaging 23 | publishPlugins 24 | --parallel 25 | should-run-codecov: ${{ runner.os == 'Linux' }} 26 | codecov-token: ${{ secrets.CODECOV_TOKEN }} 27 | should-deploy: >- 28 | ${{ 29 | runner.os == 'Linux' 30 | && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) 31 | }} 32 | gradle-publish-secret: ${{ secrets.GRADLE_PUBLISH_SECRET }} 33 | gradle-publish-key: ${{ secrets.GRADLE_PUBLISH_KEY }} 34 | maven-central-username: ${{ secrets.MAVEN_CENTRAL_USERNAME }} 35 | maven-central-password: ${{ secrets.MAVEN_CENTRAL_PASSWORD }} 36 | signing-key: ${{ secrets.SIGNING_KEY }} 37 | signing-password: ${{ secrets.SIGNING_PASSWORD }} 38 | release: 39 | needs: 40 | - build 41 | runs-on: ubuntu-24.04 42 | if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository 43 | steps: 44 | - name: Checkout 45 | uses: actions/checkout@v4.2.2 46 | with: 47 | token: ${{ secrets.DEPLOYMENT_TOKEN }} 48 | - name: Setup Node 49 | uses: actions/setup-node@v4.4.0 50 | with: 51 | node-version-file: package.json 52 | - uses: DanySK/build-check-deploy-gradle-action@3.7.20 53 | with: 54 | retries-on-failure: '1' 55 | build-command: true 56 | check-command: true 57 | deploy-command: | 58 | npm install 59 | npx semantic-release 60 | should-run-codecov: false 61 | should-deploy: true 62 | should-validate-wrapper: false 63 | github-token: ${{ github.token }} 64 | gradle-publish-secret: ${{ secrets.GRADLE_PUBLISH_SECRET }} 65 | gradle-publish-key: ${{ secrets.GRADLE_PUBLISH_KEY }} 66 | maven-central-username: ${{ secrets.MAVEN_CENTRAL_USERNAME }} 67 | maven-central-password: ${{ secrets.MAVEN_CENTRAL_PASSWORD }} 68 | signing-key: ${{ secrets.SIGNING_KEY }} 69 | signing-password: ${{ secrets.SIGNING_PASSWORD }} 70 | success: 71 | runs-on: ubuntu-24.04 72 | needs: 73 | - build 74 | - release 75 | if: >- 76 | always() && ( 77 | contains(join(needs.*.result, ','), 'failure') 78 | || !contains(join(needs.*.result, ','), 'cancelled') 79 | ) 80 | steps: 81 | - name: Verify that the workflow executed and there were no failures 82 | run: ${{ !contains(join(needs.*.result, ','), 'failure') }} 83 | -------------------------------------------------------------------------------- /.github/workflows/dispatcher.yml: -------------------------------------------------------------------------------- 1 | name: CI/CD 2 | on: 3 | push: 4 | branches-ignore: 5 | - 'dependabot/**' 6 | paths-ignore: 7 | - '.gitignore' 8 | - '.mergify.yml' 9 | - 'CHANGELOG.md' 10 | - 'LICENSE' 11 | - 'README.md' 12 | - 'renovate.json' 13 | pull_request: 14 | workflow_dispatch: 15 | 16 | concurrency: 17 | group: ${{ github.workflow }}-${{ github.event.number || github.ref }} 18 | cancel-in-progress: ${{ github.ref != 'refs/heads/master' }} 19 | 20 | jobs: 21 | dispatcher: 22 | runs-on: ubuntu-24.04 23 | if: >- 24 | github.event_name != 'pull_request' 25 | || github.event.pull_request.head.repo.full_name != github.repository 26 | || startsWith(github.head_ref, 'dependabot/') 27 | steps: 28 | - run: 'true' 29 | ci-cd: 30 | needs: 31 | - dispatcher 32 | uses: ./.github/workflows/build-and-deploy.yml 33 | secrets: inherit 34 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | .kotlintest/ 3 | .gradle/ 4 | build/ 5 | node_modules/ 6 | out/ 7 | prepare_environment.sh 8 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DanySK/git-sensitive-semantic-versioning-gradle-plugin/204b7f8f518ecd2f780faac94b9d3180398d2130/.gitmodules -------------------------------------------------------------------------------- /.mergify.yml: -------------------------------------------------------------------------------- 1 | extends: mergify-config 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 2023 Danilo Pianini 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 | # Git sensitive Semantic Versioning (SemVer) Gradle Plugin 2 | A Gradle plugin for Git-sensitive Semantic Versioning 3 | 4 | ## Rationale 5 | [Semantic Versioning](https://semver.org/) introduces a way to meaningfully version software. 6 | At the same time, git carries the project history with it. 7 | It sounds rather reasonable to mix them together, and have the project react to the git status. 8 | 9 | This plugin assumes you use git tags to mark releases, by tagging your project with tag names such as `0.1.2`. 10 | It then uses git to compute the version, in terms of both git hash and distance from the latest tag. 11 | 12 | The plugin generates the following: 13 | 14 | * "Archeo" versions for the development before initializing git, in the form of `0.1.0-archeo+time` 15 | * "Pre-development" versions for the development before marking the first release, in the form of `0.1.0-dev+hash` 16 | * "Stable" versions if a tag is present, in the form `0.1.0` 17 | * "Development" versions for changes over a tag, in the form `0.1.1-dev01-hash`, with the number after `dev` counting the distance in commits since the last tag. 18 | 19 | ## Usage 20 | 21 | ### Importing the plugin 22 | 23 | ```kotlin 24 | plugins { 25 | id("org.danilopianini.git-sensitive-semantic-versioning") version "0.1.0" 26 | } 27 | // Rest of your buildscript using project.version 28 | ``` 29 | 30 | ### Plugin options 31 | 32 | ```kotlin 33 | import org.danilopianini.gradle.gitsemver.UpdateType 34 | ... 35 | gitSemVer { 36 | minimumVersion.set("0.1.0") 37 | developmentIdentifier.set("dev") 38 | noTagIdentifier.set("archeo") 39 | fullHash.set(false) // set to true if you want to use the full git hash 40 | maxVersionLength.set(Int.MAX_VALUE) // Useful to limit the maximum version length, e.g. Gradle Plugins have a limit on 20 41 | developmentCounterLength.set(2) // How many digits after `dev` 42 | enforceSemanticVersioning.set(true) // Whether the plugin should stop if the resulting version is not a valid SemVer, or just warn 43 | computeReleaseVersion.set(false) // You can decide whether the generated version should be for releases or pre-releases (default behaviour) 44 | // The separator for the pre-release block. 45 | // Changing it to something else than "+" may result in non-SemVer compatible versions 46 | preReleaseSeparator.set("-") 47 | // The separator for the build metadata block. 48 | // Some systems (notably, the Gradle plugin portal) do not support versions with a "+" symbol. 49 | // In these cases, changing it to "-" is appropriate. 50 | buildMetadataSeparator.set("+") 51 | distanceCounterRadix.set(36) // The radix for the commit-distance counter. Must be in the 2-36 range. 52 | // A prefix on tags that should be ignored when computing the Semantic Version. 53 | // Many project are versioned with tags named "vX.Y.Z", de-facto building valid SemVer versions but for the leading "v". 54 | // If it is the case for some project, setting this property to "v" would make these tags readable as SemVer tags. 55 | versionPrefix.set("") 56 | // This reproduces the behavior of the plugin at version 0.x.y: ignores non-annotated (lightweight) tags. 57 | excludeLightweightTags() 58 | // Compute the next upgrade type (major/minor/patch) based on commit messages; defaults to patch regardless of the commits. 59 | commitNameBasedUpdateStrategy { UpdateType.PATCH } 60 | } 61 | ``` 62 | 63 | ### Manually forcing the version computation early 64 | 65 | The plugin sets the project version by scheduling a call to the `assignGitSemanticVersion()` using `project.afterEvaluate`. 66 | This should be fine for most use cases, but you might need the version of the project to be set early in the configuration phase. 67 | If so, you can manually call `assignGitSemanticVersion()` from within the plugin configuration block *after* all options have been configured 68 | (if any configuration was performed): 69 | ```kotlin 70 | gitSemVer { 71 | // Your configuration 72 | assignGitSemanticVersion() 73 | } 74 | ``` 75 | 76 | Inside the configuration block is also available the `computeVersion()` is also available to recompute (but do not set) 77 | the version. 78 | 79 | ### Manually force the version 80 | 81 | The plugin allows the user to manually set the version via a gradle property that, if present, will be used as the version of the project. 82 | By default, the property name is `forceVersion`, but you can change the property name by setting the `forceVersionPropertyName` property of the plugin with a custom name. 83 | 84 | `./gradlew -PforceVersion=1.2.3 ` will result in the project version being set to `1.2.3`. 85 | 86 | If a custom property name is used, the plugin will look for the property with the given name: 87 | 88 | ```kotlin 89 | gitSemVer { 90 | forceVersionPropertyName.set("myCustomPropertyVersion") 91 | } 92 | ``` 93 | 94 | `./gradlew -PmyCustomPropertyVersion=1.2.3 ` will result in the project version being set to `1.2.3`. 95 | 96 | ### Compute the version for release 97 | 98 | By default, the extension calculates the version for pre-releases, but you can 99 | force the calculation of the version for releases by setting the `computeReleaseVersion` 100 | property to `true`. However, manually forcing the version (as described in 101 | [Manually force the version](#manually-force-the-version)) still takes priority 102 | over this property. 103 | 104 | Consider the following configuration example: 105 | 106 | ```kotlin 107 | // task that the release fulfils 108 | project.tasks.register("release") 109 | 110 | gitSemVer { 111 | computeReleaseVersion.set( 112 | project.tasks.named("release").map { 113 | project.gradle.taskGraph.hasTask(it) 114 | } 115 | ) 116 | } 117 | ``` 118 | 119 | With this configuration, the extension will calculate the pre-release version 120 | until you force the release by executing the ‘release’ task. As soon as you 121 | decide to release the project, the extension will calculate the release version 122 | for you. 123 | 124 | In combination with conventional commits, which will be described below, this 125 | almost completely frees you from manually determining the project version. You 126 | only have to decide what the ‘release’ task should do during execution. Probably 127 | `git commit ...` and `git tag ...`, using `project.version` for this, but that's 128 | up to you. 129 | 130 | ### Using conventional commits? 131 | 132 | This plugin can be configured to use the [conventional commits](https://www.conventionalcommits.org/en/v1.0.0/) to determine the next version 133 | through another plugin developed by [Andrea Brighi](https://github.com/AndreaBrighi). 134 | Visit the [conventional commits extension for git-sensitive-semantic-versioning-gradle-plugin](https://github.com/AndreaBrighi/conventional-commit-strategy-for-git-sensitive-semantic-versioning-gradle-plugin) to learn more. 135 | 136 | ## Contributing to the project 137 | 138 | I gladly review pull requests and I'm happy to improve the work. 139 | If the software was useful to you, please consider supporting my development activity 140 | [![paypal](https://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=5P4DSZE5DV4H2¤cy_code=EUR) 141 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | @file:Suppress("SuspiciousCollectionReassignment") 2 | 3 | import org.gradle.api.tasks.testing.logging.TestLogEvent 4 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile 5 | import org.jetbrains.kotlin.config.KotlinCompilerVersion.VERSION as KOTLIN_VERSION 6 | 7 | plugins { 8 | `java-gradle-plugin` 9 | alias(libs.plugins.dokka) 10 | alias(libs.plugins.gitSemVer) 11 | alias(libs.plugins.gradle.plugin.publish) 12 | alias(libs.plugins.kotlin.jvm) 13 | alias(libs.plugins.kotlin.qa) 14 | alias(libs.plugins.publishOnCentral) 15 | alias(libs.plugins.multiJvmTesting) 16 | alias(libs.plugins.taskTree) 17 | } 18 | 19 | group = "org.danilopianini" 20 | 21 | class ProjectInfo { 22 | val projectId = "$group.$name" 23 | val fullName = "Gradle Git-Sensitive Semantic Versioning Plugin" 24 | val projectDetails = "A Gradle plugin that forces semantic versioning and relies on git to detect the project state" 25 | val pluginImplementationClass = "org.danilopianini.gradle.gitsemver.GitSemVer" 26 | val websiteUrl = "https://github.com/DanySK/$name" 27 | val vcsUrl = "$websiteUrl.git" 28 | val scm = "scm:git:$websiteUrl.git" 29 | val tags = listOf("git", "semver", "semantic versioning", "vcs", "tag") 30 | } 31 | val info = ProjectInfo() 32 | 33 | gitSemVer { 34 | maxVersionLength.set(20) 35 | buildMetadataSeparator.set("-") 36 | } 37 | 38 | repositories { 39 | mavenCentral() 40 | gradlePluginPortal() 41 | } 42 | 43 | multiJvm { 44 | jvmVersionForCompilation = 11 45 | maximumSupportedJvmVersion = latestJavaSupportedByGradle 46 | } 47 | 48 | dependencies { 49 | api(gradleApi()) 50 | api(gradleKotlinDsl()) 51 | implementation(kotlin("stdlib-jdk8")) 52 | implementation(libs.caffeine) 53 | testImplementation(gradleTestKit()) 54 | testImplementation(libs.bundles.kotlin.testing) 55 | } 56 | 57 | // Enforce Kotlin version coherence 58 | configurations.matching { it.name != "detekt" }.all { 59 | resolutionStrategy.eachDependency { 60 | if (requested.group == "org.jetbrains.kotlin" && requested.name.startsWith("kotlin")) { 61 | useVersion(KOTLIN_VERSION) 62 | because("All Kotlin modules should use the same version, and compiler uses $KOTLIN_VERSION") 63 | } 64 | } 65 | } 66 | 67 | publishOnCentral { 68 | projectDescription.set(info.projectDetails) 69 | projectLongName.set(info.fullName) 70 | projectUrl.set(info.websiteUrl) 71 | scmConnection.set(info.scm) 72 | repository("https://maven.pkg.github.com/DanySK/${rootProject.name}".lowercase(), name = "github") { 73 | user.set("danysk") 74 | password.set(System.getenv("GITHUB_TOKEN")) 75 | } 76 | } 77 | 78 | tasks { 79 | withType { 80 | useJUnitPlatform() 81 | testLogging { 82 | showCauses = true 83 | showStackTraces = true 84 | showStandardStreams = true 85 | events(*TestLogEvent.values()) 86 | } 87 | } 88 | withType { 89 | kotlinOptions { 90 | allWarningsAsErrors = true 91 | freeCompilerArgs += listOf("-opt-in=kotlin.RequiresOptIn", "-Xinline-classes") 92 | } 93 | } 94 | } 95 | 96 | if ("true" == System.getenv("CI")) { 97 | signing { 98 | val signingKey: String? by project 99 | val signingPassword: String? by project 100 | useInMemoryPgpKeys(signingKey, signingPassword) 101 | } 102 | } 103 | 104 | publishing { 105 | publications { 106 | withType { 107 | pom { 108 | developers { 109 | developer { 110 | name.set("Danilo Pianini") 111 | email.set("danilo.pianini@gmail.com") 112 | url.set("http://www.danilopianini.org/") 113 | } 114 | } 115 | } 116 | } 117 | } 118 | } 119 | 120 | gradlePlugin { 121 | plugins { 122 | website.set(info.websiteUrl) 123 | vcsUrl.set(info.vcsUrl) 124 | create("long") { 125 | id = info.projectId 126 | displayName = info.fullName 127 | description = info.projectDetails 128 | implementationClass = info.pluginImplementationClass 129 | tags.set(info.tags) 130 | } 131 | create("short") { 132 | id = "$group.git-sensitive-semantic-versioning" 133 | displayName = info.fullName 134 | description = info.projectDetails 135 | implementationClass = info.pluginImplementationClass 136 | tags.set(info.tags) 137 | } 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | org.gradle.jvmargs=-XX:MaxMetaspaceSize=512m 2 | 3 | kotlin.code.style=official 4 | 5 | systemProp.org.gradle.internal.http.connectionTimeout=500000 6 | systemProp.org.gradle.internal.http.socketTimeout=500000 7 | -------------------------------------------------------------------------------- /gradle/libs.versions.toml: -------------------------------------------------------------------------------- 1 | [versions] 2 | dokka = "2.0.0" 3 | kotlin = "2.1.21" 4 | kotest = "6.0.0.M4" 5 | 6 | [libraries] 7 | caffeine = "com.github.ben-manes.caffeine:caffeine:3.2.0" 8 | kotest-junit5-jvm = { module = "io.kotest:kotest-runner-junit5-jvm", version.ref = "kotest" } 9 | kotest-assertions-core-jvm = { module = "io.kotest:kotest-assertions-core-jvm", version.ref = "kotest" } 10 | 11 | [bundles] 12 | kotlin-testing = [ "kotest-junit5-jvm", "kotest-assertions-core-jvm" ] 13 | 14 | [plugins] 15 | dokka = { id = "org.jetbrains.dokka", version.ref = "dokka" } 16 | gitSemVer = { id = "org.danilopianini.git-sensitive-semantic-versioning-gradle-plugin", version = "5.1.4" } 17 | gradle-plugin-publish = { id = "com.gradle.plugin-publish", version = "1.3.1" } 18 | kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" } 19 | kotlin-qa = { id = "org.danilopianini.gradle-kotlin-qa", version = "0.89.1" } 20 | multiJvmTesting = { id = "org.danilopianini.multi-jvm-test-plugin", version = "3.5.1" } 21 | publishOnCentral = { id = "org.danilopianini.publish-on-central", version = "8.0.7" } 22 | taskTree = { id = "com.dorongold.task-tree", version = "4.0.1" } 23 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DanySK/git-sensitive-semantic-versioning-gradle-plugin/204b7f8f518ecd2f780faac94b9d3180398d2130/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionSha256Sum=7197a12f450794931532469d4ff21a59ea2c1cd59a3ec3f89c035c3c420a6999 4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.2-bin.zip 5 | networkTimeout=10000 6 | validateDistributionUrl=true 7 | zipStoreBase=GRADLE_USER_HOME 8 | zipStorePath=wrapper/dists 9 | -------------------------------------------------------------------------------- /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\n' "$PWD" ) || exit 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="\\\"\\\"" 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 | if ! command -v java >/dev/null 2>&1 137 | then 138 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 139 | 140 | Please set the JAVA_HOME variable in your environment to match the 141 | location of your Java installation." 142 | fi 143 | fi 144 | 145 | # Increase the maximum file descriptors if we can. 146 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 147 | case $MAX_FD in #( 148 | max*) 149 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 150 | # shellcheck disable=SC2039,SC3045 151 | MAX_FD=$( ulimit -H -n ) || 152 | warn "Could not query maximum file descriptor limit" 153 | esac 154 | case $MAX_FD in #( 155 | '' | soft) :;; #( 156 | *) 157 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 158 | # shellcheck disable=SC2039,SC3045 159 | ulimit -n "$MAX_FD" || 160 | warn "Could not set maximum file descriptor limit to $MAX_FD" 161 | esac 162 | fi 163 | 164 | # Collect all arguments for the java command, stacking in reverse order: 165 | # * args from the command line 166 | # * the main class name 167 | # * -classpath 168 | # * -D...appname settings 169 | # * --module-path (only if needed) 170 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 171 | 172 | # For Cygwin or MSYS, switch paths to Windows format before running java 173 | if "$cygwin" || "$msys" ; then 174 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 175 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 176 | 177 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 178 | 179 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 180 | for arg do 181 | if 182 | case $arg in #( 183 | -*) false ;; # don't mess with options #( 184 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 185 | [ -e "$t" ] ;; #( 186 | *) false ;; 187 | esac 188 | then 189 | arg=$( cygpath --path --ignore --mixed "$arg" ) 190 | fi 191 | # Roll the args list around exactly as many times as the number of 192 | # args, so each arg winds up back in the position where it started, but 193 | # possibly modified. 194 | # 195 | # NB: a `for` loop captures its iteration list before it begins, so 196 | # changing the positional parameters here affects neither the number of 197 | # iterations, nor the values presented in `arg`. 198 | shift # remove old arg 199 | set -- "$@" "$arg" # push replacement arg 200 | done 201 | fi 202 | 203 | 204 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 205 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 206 | 207 | # Collect all arguments for the java command: 208 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 209 | # and any embedded shellness will be escaped. 210 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 211 | # treated as '${Hostname}' itself on the command line. 212 | 213 | set -- \ 214 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 215 | -classpath "$CLASSPATH" \ 216 | -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ 217 | "$@" 218 | 219 | # Stop when "xargs" is not available. 220 | if ! command -v xargs >/dev/null 2>&1 221 | then 222 | die "xargs is not available" 223 | fi 224 | 225 | # Use "xargs" to parse quoted args. 226 | # 227 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 228 | # 229 | # In Bash we could simply go: 230 | # 231 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 232 | # set -- "${ARGS[@]}" "$@" 233 | # 234 | # but POSIX shell has neither arrays nor command substitution, so instead we 235 | # post-process each arg (as a line of input to sed) to backslash-escape any 236 | # character that might be a shell metacharacter, then use eval to reverse 237 | # that process (while maintaining the separation between arguments), and wrap 238 | # the whole thing up as a single "set" statement. 239 | # 240 | # This will of course break if any of these variables contains a newline or 241 | # an unmatched quote. 242 | # 243 | 244 | eval "set -- $( 245 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 246 | xargs -n1 | 247 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 248 | tr '\n' ' ' 249 | )" '"$@"' 250 | 251 | exec "$JAVACMD" "$@" 252 | -------------------------------------------------------------------------------- /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= 74 | 75 | 76 | @rem Execute Gradle 77 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* 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 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "devDependencies": { 3 | "semantic-release-preconfigured-conventional-commits": "1.1.133" 4 | }, 5 | "engines": { 6 | "node": "22.16" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /release.config.mjs: -------------------------------------------------------------------------------- 1 | const publishCmd = ` 2 | ./gradlew uploadAllToMavenCentralNexus releaseStagingRepositoryOnMavenCentral --parallel || exit 1 3 | ./gradlew publishPlugins -Pgradle.publish.key=$GRADLE_PUBLISH_KEY -Pgradle.publish.secret=$GRADLE_PUBLISH_SECRET || exit 2 4 | ./gradlew publishKotlinMavenPublicationToGithubRepository || true 5 | `; 6 | import config from 'semantic-release-preconfigured-conventional-commits' with {type: 'json'}; 7 | config.plugins.push( 8 | [ 9 | "@semantic-release/exec", 10 | { 11 | "publishCmd": publishCmd, 12 | } 13 | ], 14 | "@semantic-release/github", 15 | "@semantic-release/git", 16 | ) 17 | export default config; 18 | -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "extends": [ 4 | "github>DanySK/renovate-config:gradle-plugin" 5 | ] 6 | } 7 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | id("com.gradle.develocity") version "4.0.2" 3 | id("org.danilopianini.gradle-pre-commit-git-hooks") version "2.0.26" 4 | id("org.gradle.toolchains.foojay-resolver-convention") version "1.0.0" 5 | } 6 | 7 | develocity { 8 | buildScan { 9 | termsOfUseUrl = "https://gradle.com/terms-of-service" 10 | termsOfUseAgree = "yes" 11 | uploadInBackground = !System.getenv("CI").toBoolean() 12 | } 13 | } 14 | 15 | gitHooks { 16 | preCommit { 17 | tasks("ktlintCheck") 18 | } 19 | commitMsg { conventionalCommits() } 20 | createHooks(true) 21 | } 22 | 23 | rootProject.name = "git-sensitive-semantic-versioning-gradle-plugin" 24 | -------------------------------------------------------------------------------- /src/main/kotlin/org/danilopianini/gradle/gitsemver/GitSemVer.kt: -------------------------------------------------------------------------------- 1 | package org.danilopianini.gradle.gitsemver 2 | 3 | import org.gradle.api.Plugin 4 | import org.gradle.api.Project 5 | import org.gradle.api.model.ObjectFactory 6 | import org.gradle.api.provider.ProviderFactory 7 | import javax.inject.Inject 8 | 9 | /** 10 | * A Plugin for comuting the project version based on the status of the local git repository. 11 | */ 12 | class GitSemVer 13 | @Inject 14 | constructor( 15 | private val providerFactory: ProviderFactory, 16 | private val objectFactory: ObjectFactory, 17 | ) : Plugin { 18 | override fun apply(project: Project): Unit = with(project) { 19 | val extension = createExtension( 20 | GitSemVerExtension.EXTENSION_NAME, 21 | this, 22 | providerFactory, 23 | objectFactory, 24 | projectDir, 25 | version, 26 | logger, 27 | ) 28 | afterEvaluate { 29 | extension.assignGitSemanticVersion() 30 | } 31 | tasks.register("printGitSemVer") { 32 | val forceVersion = properties[extension.forceVersionPropertyName.get()] 33 | it.doLast { 34 | println( 35 | "Version computed by ${GitSemVer::class.java.simpleName}: " + 36 | "${forceVersion ?: extension.computeVersion()}", 37 | ) 38 | } 39 | } 40 | } 41 | 42 | private companion object { 43 | private inline fun Project.createExtension(name: String, vararg args: Any?): T = 44 | project.extensions.create(name, T::class.java, *args) 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/kotlin/org/danilopianini/gradle/gitsemver/GitSemVerExtension.kt: -------------------------------------------------------------------------------- 1 | package org.danilopianini.gradle.gitsemver 2 | 3 | import com.github.benmanes.caffeine.cache.Caffeine 4 | import org.danilopianini.gradle.gitsemver.source.GitCommandValueSource 5 | import org.gradle.api.Project 6 | import org.gradle.api.model.ObjectFactory 7 | import org.gradle.api.provider.Property 8 | import org.gradle.api.provider.Provider 9 | import org.gradle.api.provider.ProviderFactory 10 | import org.slf4j.Logger 11 | import java.io.File 12 | import kotlin.time.Duration.Companion.minutes 13 | import kotlin.time.toJavaDuration 14 | 15 | /** 16 | * The plugin extension with the DSL. 17 | * 18 | * Supports the following properties: 19 | * - [minimumVersion], defaulting to 0.1.0 20 | * - [developmentIdentifier], the identifier for the in-development versions 21 | * - [noTagIdentifier], the identifier for early versions of the project, when no tags are available yet 22 | * - [fullHash], whether to use the full commit hash as build metadata 23 | * - [maxVersionLength], cuts the version to the specified length. Useful for some destinations, 24 | * e.g., the Gradle Plugin Portal, which limits version numbers to 20 chars. 25 | * - [developmentCounterLength], how many digits to use for the counter 26 | * - [enforceSemanticVersioning], whether the system should fail or just warn 27 | * in case a non-SemVer compatible version gets produced 28 | * - [computeReleaseVersion], determines whether the version is to be calculated for the release or pre-release 29 | * (default behavior) 30 | * - [preReleaseSeparator], how to separate the pre-relase information. 31 | * Changing this value may generate non-SemVer-compatible versions. 32 | * - [buildMetadataSeparator], how to separate the pre-relase information. 33 | * Some destinations (e.g., the Gradle Plugin Portal) do not support the default value '+'. 34 | * A reasonable alternative is using '-', lifting the build metadata to a pre-release segment. 35 | * - [distanceCounterRadix], the radix for the commit counter. Defaults to base 36. Bases from 2 to 36 allowed. 36 | * - [versionPrefix], to be used in case tags are prefixed with some symbols before the semantic version 37 | * (e.g., v1.0.0 is prefixed with "v"). 38 | * - [includeLightweightTags], to be used in case lightweight tags should be considered. 39 | * - [forceVersionPropertyName], the name of the property that, if set, will force the plugin to use the specified 40 | * version. By default the property name is "forceVersion". 41 | */ 42 | open class GitSemVerExtension 43 | @JvmOverloads 44 | constructor( 45 | private val project: Project, 46 | private val providerFactory: ProviderFactory, 47 | private val objectFactory: ObjectFactory, 48 | private val projectDir: File, 49 | private val version: String, 50 | private val logger: Logger, 51 | val minimumVersion: Property = objectFactory.propertyWithDefault("0.1.0"), 52 | val developmentIdentifier: Property = objectFactory.propertyWithDefault("dev"), 53 | val noTagIdentifier: Property = objectFactory.propertyWithDefault("archeo"), 54 | val fullHash: Property = objectFactory.propertyWithDefault(false), 55 | val maxVersionLength: Property = objectFactory.propertyWithDefault(Int.MAX_VALUE), 56 | val developmentCounterLength: Property = objectFactory.propertyWithDefault(2), 57 | val enforceSemanticVersioning: Property = objectFactory.propertyWithDefault(true), 58 | val computeReleaseVersion: Property = objectFactory.propertyWithDefault(false), 59 | val preReleaseSeparator: Property = objectFactory.propertyWithDefault("-"), 60 | val buildMetadataSeparator: Property = objectFactory.propertyWithDefault("+"), 61 | val distanceCounterRadix: Property = objectFactory.propertyWithDefault(DEFAULT_RADIX), 62 | val versionPrefix: Property = objectFactory.propertyWithDefault(""), 63 | val includeLightweightTags: Property = objectFactory.propertyWithDefault(true), 64 | val forceVersionPropertyName: Property = objectFactory.propertyWithDefault("forceVersion"), 65 | private var updateStrategy: (List) -> UpdateType = { _ -> UpdateType.PATCH }, 66 | ) { 67 | 68 | private val versions = Caffeine.newBuilder() 69 | .expireAfterAccess(1.minutes.toJavaDuration()) 70 | .build, String> { _ -> computeVersion() } 71 | 72 | /** 73 | * Sets the strategy to be used to compute the version increment 74 | * based on the commit messages since the last tag. 75 | * The default strategy is to increment the patch version. 76 | * 77 | * @param strategy a function that takes the list of commit messages since the last tag 78 | * and returns the update type 79 | */ 80 | fun commitNameBasedUpdateStrategy(strategy: (List) -> UpdateType) { 81 | updateStrategy = strategy 82 | } 83 | 84 | private fun computeMinVersion(): SemanticVersion { 85 | val minVersion = minimumVersion.get() 86 | val minSemVer = SemanticVersion.fromStringOrNull(minVersion)?.withoutBuildMetadata() 87 | requireNotNull(minSemVer) { 88 | "Invalid minimum version does not conform to Semantic Versioning 2.0: $minVersion" 89 | } 90 | if (!minSemVer.buildMetadata.isEmpty()) { 91 | logger.warn("Minimum version $minSemVer build metadata will be ignored.") 92 | } 93 | return minSemVer 94 | } 95 | 96 | /** 97 | * Finds the closest tag compatible with Semantic Version, or returns null if none is available. 98 | */ 99 | fun findClosestTag(): SemanticVersion? { 100 | val reachableCommits = runCommand("git", "rev-list", "HEAD")?.lines()?.toSet().orEmpty() 101 | val tagMatcher = 102 | Regex( 103 | """^(\w*)\s+(${ 104 | if (includeLightweightTags.get()) "commit|" else "" 105 | }tag)\s+refs/tags/${ 106 | versionPrefix.get() 107 | }(${ 108 | SemanticVersion.SEM_VER_REGEX_STRING 109 | })$""", 110 | ) 111 | logger.debug("Reachable commits: $reachableCommits") 112 | return runCommand("git", "for-each-ref", "refs/tags", "--sort=-version:refname") 113 | ?.lineSequence() 114 | ?.mapNotNull { tagMatcher.matchEntire(it)?.destructured } 115 | ?.mapNotNull { (commit, type: String, semVer, major, minor, patch, option, build) -> 116 | val actualRef = 117 | when (type) { 118 | "commit" -> commit 119 | "tag" -> runCommand("git", "rev-list", "-n1", versionPrefix.get() + semVer) 120 | else -> error("Unknown tag ref type '$type' (expected 'tag' or 'commit')") 121 | } 122 | actualRef.takeIf { it in reachableCommits }?.let { 123 | SemanticVersion(major, minor, patch, option, build) 124 | } 125 | }?.firstOrNull() 126 | } 127 | 128 | /** 129 | * Computes a valid Semantic Versioning 2.0 version based on the status of the current git repository. 130 | */ 131 | fun computeVersion(): String { 132 | val closestTag = findClosestTag() 133 | logger.debug("Closest SemVer tag: $closestTag") 134 | val fullHash = fullHash.get() 135 | val printCommitCommand = "git rev-parse ${if (fullHash) "" else "--short "}HEAD".split(" ") 136 | val hash = runCommand(*printCommitCommand.toTypedArray()) ?: System.currentTimeMillis().toString() 137 | return when (closestTag) { 138 | null -> { 139 | val base = computeMinVersion() 140 | val identifier = noTagIdentifier.orElse("").get() 141 | val computeReleaseVersion = computeReleaseVersion.get() 142 | val separator = if (identifier.isBlank()) "" else preReleaseSeparator.get() 143 | val buildSeparator = buildMetadataSeparator.get() 144 | 145 | if (computeReleaseVersion) { 146 | "$base".take(maxVersionLength.get()) 147 | } else { 148 | "$base$separator$identifier$buildSeparator$hash".take(maxVersionLength.get()) 149 | } 150 | } 151 | 152 | else -> { 153 | if (!closestTag.buildMetadata.isEmpty()) { 154 | logger.warn("Build metadata of closest tag $closestTag will be ignored.") 155 | } 156 | val distance = 157 | runCommand( 158 | "git", 159 | "rev-list", 160 | "--count", 161 | "${versionPrefix.get()}$closestTag..HEAD", 162 | )?.toLong() 163 | requireNotNull(distance) { 164 | "Bug in git SemVer plugin: [distance? $distance]. Please report at: " + 165 | "https://github.com/DanySK/git-sensitive-semantic-versioning-gradle-plugin/issues" 166 | } 167 | when (distance) { 168 | 0L -> closestTag.toString() 169 | else -> { 170 | val base: SemanticVersion = closestTag.withoutBuildMetadata() 171 | val lastCommits = 172 | runCommand( 173 | "git", 174 | "log", 175 | "--oneline", 176 | "-$distance", 177 | "--no-decorate", 178 | "--format=%s", 179 | )?.lines().orEmpty() 180 | val currentVersion = updateStrategy(lastCommits).incrementVersion(base) 181 | val devString = developmentIdentifier.get() 182 | val computeReleaseVersion = computeReleaseVersion.get() 183 | val separator = if (devString.isBlank()) "" else preReleaseSeparator.get() 184 | val distanceString = 185 | distance.withRadix( 186 | distanceCounterRadix.get(), 187 | developmentCounterLength.get(), 188 | ) 189 | val buildSeparator = buildMetadataSeparator.get() 190 | 191 | if (computeReleaseVersion) { 192 | "$currentVersion".take(maxVersionLength.get()) 193 | } else { 194 | "$currentVersion$separator$devString$distanceString$buildSeparator$hash" 195 | .take(maxVersionLength.get()) 196 | } 197 | } 198 | } 199 | } 200 | } 201 | } 202 | 203 | /** 204 | * modifies the version of the current project, assigning the value computed by [computeVersion]. 205 | */ 206 | fun assignGitSemanticVersion() { 207 | val forcedVersion = project.properties[forceVersionPropertyName.get()]?.toString() 208 | val computedVersion = when { 209 | forcedVersion != null -> { 210 | project.logger.lifecycle( 211 | "Forcing {} version to {} as per property '{}'", 212 | project.name, 213 | forcedVersion, 214 | forceVersionPropertyName.get(), 215 | ) 216 | forcedVersion 217 | } 218 | else -> { 219 | val repoLocation = runCommand("git", "rev-parse", "--show-toplevel") 220 | val headCommitHash = runCommand("git", "rev-list", "HEAD", "-n", "1") 221 | when { 222 | repoLocation != null && headCommitHash != null -> { 223 | versions[repoLocation to headCommitHash] 224 | } 225 | else -> { 226 | project.logger.warn( 227 | "Could not detect both the git repository location ({}) and the HEAD commit hash ({}). " + 228 | "The version will be forcibly recomputed.", 229 | repoLocation, 230 | headCommitHash, 231 | ) 232 | computeVersion() 233 | } 234 | } 235 | } 236 | } 237 | val resultingVersion = SemanticVersion.fromStringOrNull(computedVersion) 238 | project.version = if (resultingVersion == null) { 239 | val error = "Invalid Semantic Versioning 2.0 version: $version" 240 | if (enforceSemanticVersioning.get()) { 241 | error(error) 242 | } else { 243 | logger.warn(error) 244 | } 245 | computedVersion 246 | } else { 247 | resultingVersion.toString() 248 | } 249 | } 250 | 251 | /** 252 | * If called, the system will also consider non-annotated tags. 253 | */ 254 | fun excludeLightweightTags() { 255 | includeLightweightTags.set(false) 256 | } 257 | 258 | protected fun runCommand(vararg cmd: String) = processCommand(*cmd) 259 | 260 | private fun processCommand(vararg cmd: String) = createValueSourceProvider(*cmd) 261 | .get() 262 | .trim() 263 | .takeIf { it.isNotEmpty() } 264 | 265 | private fun createValueSourceProvider(vararg cmd: String): Provider = 266 | providerFactory.of(GitCommandValueSource::class.java) { 267 | it.parameters { params -> 268 | params.commands.set(objectFactory.listProperty(String::class.java).value(cmd.asList())) 269 | params.directory.set(projectDir) 270 | } 271 | } 272 | 273 | /** 274 | * The name of the extension, namely of the DSL entry-point. 275 | */ 276 | companion object { 277 | /** 278 | * The name of the extension, namely of the DSL entry-point. 279 | */ 280 | const val EXTENSION_NAME = "gitSemVer" 281 | 282 | private const val DEFAULT_RADIX = 36 283 | 284 | private inline fun ObjectFactory.propertyWithDefault(default: T): Property = 285 | property(T::class.java).apply { convention(default) } 286 | 287 | private fun Long.withRadix(radix: Int, digits: Int? = null) = toString(radix).let { 288 | if (digits == null || it.length >= digits) { 289 | it 290 | } else { 291 | it.padStart(digits, '0') 292 | } 293 | } 294 | } 295 | } 296 | -------------------------------------------------------------------------------- /src/main/kotlin/org/danilopianini/gradle/gitsemver/SemanticVersion.kt: -------------------------------------------------------------------------------- 1 | package org.danilopianini.gradle.gitsemver 2 | 3 | /** 4 | * A class representing semantic versions: 5 | * [major].[minor].[patch]-[preRelease]+[buildMetadata]. 6 | */ 7 | data class SemanticVersion( 8 | val major: ULong, 9 | val minor: ULong, 10 | val patch: ULong, 11 | val preRelease: PreReleaseIdentifier = PreReleaseIdentifier.EMPTY, 12 | val buildMetadata: PreReleaseIdentifier = PreReleaseIdentifier.EMPTY, 13 | ) : Comparable { 14 | /** 15 | * True if this version is in the form [major].[minor].[patch], with no further identifiers. 16 | */ 17 | val isStable: Boolean get() = preRelease.isEmpty() && buildMetadata.isEmpty() 18 | 19 | constructor( 20 | major: String, 21 | minor: String, 22 | patch: String, 23 | preRelease: String = "", 24 | buildMetadata: String = "", 25 | ) : this( 26 | major.toULong(), 27 | minor.toULong(), 28 | patch.toULong(), 29 | PreReleaseIdentifier("-", preRelease), 30 | PreReleaseIdentifier("+", buildMetadata), 31 | ) 32 | 33 | /** 34 | * Creates a new [SemanticVersion] with the [major] version increased by 1 and the [minor] and [patch] reset to 0. 35 | */ 36 | fun incrementMajor(): SemanticVersion = copy(major = major + 1u, minor = 0u, patch = 0u) 37 | 38 | /** 39 | * Creates a new [SemanticVersion] with the [minor] version increased by 1 and the [patch] reset to 0, while 40 | * keeping the [major] version. 41 | */ 42 | fun incrementMinor(): SemanticVersion = copy(minor = minor + 1u, patch = 0u) 43 | 44 | /** 45 | * Creates a new [SemanticVersion] with the [patch] version increased by 1, while keeping the [major] and [minor] 46 | * versions. 47 | */ 48 | fun incrementPatch(): SemanticVersion = copy(patch = patch + 1u) 49 | 50 | override fun toString() = "$major.$minor.$patch$preRelease$buildMetadata" 51 | 52 | /** 53 | * Creates the same SemanticVersion, but without build metadata. 54 | */ 55 | fun withoutBuildMetadata(): SemanticVersion = copy(buildMetadata = PreReleaseIdentifier("+", "")) 56 | 57 | /* 58 | * Precedence refers to how versions are compared to each other when ordered. 59 | * Precedence MUST be calculated by separating the version into major, minor, patch and pre-release identifiers 60 | * in that order (Build metadata does not figure into precedence). 61 | * Precedence is determined by the first difference when comparing each of these identifiers from left to right 62 | * as follows: Major, minor, and patch versions are always compared numerically. 63 | * - Example: 1.0.0 < 2.0.0 < 2.1.0 < 2.1.1. 64 | * 65 | */ 66 | override fun compareTo(other: SemanticVersion): Int = when { 67 | major != other.major -> major.compareTo(other.major) 68 | minor != other.minor -> minor.compareTo(other.minor) 69 | patch != other.patch -> patch.compareTo(other.patch) 70 | else -> 71 | preRelease.compareTo(other.preRelease).takeUnless { it == 0 } 72 | ?: buildMetadata.compareTo(buildMetadata) 73 | } 74 | 75 | /** 76 | * Constants and utilities for working with semantic versions. 77 | */ 78 | companion object { 79 | private const val MATCH_VERSION = 80 | """(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)""" 81 | private const val MATCH_OPTION = 82 | """(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?""" 83 | private const val MATCH_BUILD_INFO = 84 | """(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?""" 85 | 86 | /** 87 | * [String] version of a regular expression matching a SemVer. 88 | */ 89 | const val SEM_VER_REGEX_STRING = "$MATCH_VERSION$MATCH_OPTION$MATCH_BUILD_INFO" 90 | 91 | /** 92 | * A [Regex] matching a valid semantic version. 93 | */ 94 | val semVerRegex = Regex("^$SEM_VER_REGEX_STRING$") 95 | 96 | /** 97 | * Parses a [String] producing a [SemanticVersion], or null if the version can't be parsed. 98 | */ 99 | fun fromStringOrNull(input: String): SemanticVersion? = semVerRegex.matchEntire(input)?.let { match -> 100 | val (major, minor, patch, preRelease, buildInfo) = match.destructured 101 | SemanticVersion(major, minor, patch, preRelease, buildInfo) 102 | } 103 | } 104 | } 105 | 106 | /** 107 | * A SemVer 2.0 pre-release identifier, with a selectable [prefix]. 108 | */ 109 | data class PreReleaseIdentifier( 110 | val prefix: String = "-", 111 | private val segments: List = emptyList(), 112 | ) : Comparable { 113 | init { 114 | require(prefix in validPrefixes) { 115 | "Invalid prefix $prefix. Valid prefixes: $validPrefixes" 116 | } 117 | } 118 | 119 | constructor(prefix: String, identifier: String) : this( 120 | prefix, 121 | identifier 122 | .split(".") 123 | .filter { it.isNotBlank() } 124 | .map { segment -> 125 | segment 126 | .toULongOrNull() 127 | ?.let { DotSeparatedIdentifier.NumericIdentifier(it) } 128 | ?: DotSeparatedIdentifier.AlphanumericIdentifier(segment) 129 | }, 130 | ) 131 | 132 | /** 133 | * Whether this pre-release identifier contains anything. 134 | */ 135 | fun isEmpty(): Boolean = segments.isEmpty() 136 | 137 | override fun toString() = segments 138 | .takeIf { it.isNotEmpty() } 139 | ?.joinToString(separator = ".", prefix = prefix) 140 | .orEmpty() 141 | 142 | /* 143 | * Precedence for two pre-release versions with the same major, minor, and patch version MUST be determined by 144 | * comparing each dot separated identifier from left to right until a difference is found as follows: 145 | * - Identifiers consisting of only digits are compared numerically. 146 | * - Identifiers with letters or hyphens are compared lexically in ASCII sort order. 147 | * - Numeric identifiers always have lower precedence than non-numeric identifiers. 148 | * - A larger set of pre-release fields has a higher precedence than a smaller set, if all of the preceding 149 | * identifiers are equal. 150 | * 151 | * - Example: 152 | * 1.0.0-alpha < 1.0.0-alpha.1 < 1.0.0-alpha.beta < 1.0.0-beta 153 | * < 1.0.0-beta.2 < 1.0.0-beta.11 < 1.0.0-rc.1 < 1.0.0. 154 | */ 155 | override fun compareTo(other: PreReleaseIdentifier): Int = segments 156 | .asSequence() 157 | .zip(other.segments.asSequence()) 158 | .map { it.first.compareTo(it.second) } 159 | .find { it != 0 } 160 | ?: segments.size.compareTo(other.segments.size) 161 | 162 | /** 163 | * A dot-separated identifier. 164 | */ 165 | sealed class DotSeparatedIdentifier : Comparable { 166 | /** 167 | * Numeric [identifier]. 168 | */ 169 | data class NumericIdentifier(val identifier: ULong) : DotSeparatedIdentifier() { 170 | override fun toString() = identifier.toString() 171 | } 172 | 173 | /** 174 | * Alphanumeric [identifier]. 175 | */ 176 | data class AlphanumericIdentifier(val identifier: String) : DotSeparatedIdentifier() { 177 | init { 178 | require(!identifier.contains(".")) { 179 | "Sub-identifiers in semVer cannot contain dots. Error at: $identifier" 180 | } 181 | require(identifier.isNotBlank()) { 182 | "Sub-identifiers can't be empty or blank: '$identifier'." 183 | } 184 | } 185 | 186 | override fun toString() = identifier 187 | } 188 | 189 | override fun compareTo(other: DotSeparatedIdentifier) = when (this) { 190 | is NumericIdentifier -> { 191 | when (other) { 192 | is NumericIdentifier -> identifier.compareTo(other.identifier) 193 | else -> -1 194 | } 195 | } 196 | is AlphanumericIdentifier -> { 197 | when (other) { 198 | is AlphanumericIdentifier -> identifier.compareTo(other.identifier) 199 | else -> 1 200 | } 201 | } 202 | } 203 | } 204 | 205 | /** 206 | * Constants and utilities for working with pre-release identifiers. 207 | */ 208 | companion object { 209 | private val validPrefixes = listOf("+", "-") 210 | 211 | /** 212 | * An empty pre-release identifier. 213 | */ 214 | val EMPTY: PreReleaseIdentifier = PreReleaseIdentifier() 215 | } 216 | } 217 | -------------------------------------------------------------------------------- /src/main/kotlin/org/danilopianini/gradle/gitsemver/UpdateType.kt: -------------------------------------------------------------------------------- 1 | package org.danilopianini.gradle.gitsemver 2 | 3 | /** 4 | * The type of update that the commits represents. 5 | * The following types are supported: 6 | * 7 | * - [NONE] for commits that do not represent an update 8 | * - [PATCH] for bug fixes 9 | * - [MINOR] for new features 10 | * - [MAJOR] for breaking changes 11 | * 12 | * [NONE] < [PATCH] < [MINOR] < [MAJOR] 13 | */ 14 | enum class UpdateType { 15 | /** 16 | * No update. 17 | */ 18 | NONE, 19 | 20 | /** 21 | * A patch update. 22 | */ 23 | PATCH, 24 | 25 | /** 26 | * A minor update. 27 | */ 28 | MINOR, 29 | 30 | /** 31 | * A major update. 32 | */ 33 | MAJOR, 34 | 35 | ; 36 | 37 | /** 38 | * Increments the [version] according to the enum value. 39 | * If it is [UpdateType.NONE], the [version] is returned unchanged. 40 | * If it is [UpdateType.PATCH], the [version] is incremented as a patch. 41 | * If it is [UpdateType.MINOR], the [version] is incremented as a minor. 42 | * If it is [UpdateType.MAJOR], the [version] is incremented as a major. 43 | * 44 | * @param version the last tagged version 45 | */ 46 | fun incrementVersion(version: SemanticVersion): SemanticVersion = when (this) { 47 | NONE -> version 48 | PATCH -> version.incrementPatch() 49 | MINOR -> version.incrementMinor() 50 | MAJOR -> version.incrementMajor() 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/kotlin/org/danilopianini/gradle/gitsemver/source/GitCommandValueSource.kt: -------------------------------------------------------------------------------- 1 | package org.danilopianini.gradle.gitsemver.source 2 | 3 | import org.gradle.api.provider.ListProperty 4 | import org.gradle.api.provider.Property 5 | import org.gradle.api.provider.ValueSource 6 | import org.gradle.api.provider.ValueSourceParameters 7 | import org.gradle.process.ExecOperations 8 | import java.io.ByteArrayOutputStream 9 | import java.io.File 10 | import java.nio.charset.Charset 11 | import javax.inject.Inject 12 | 13 | /** 14 | * Value source for reading results of external git commands. 15 | */ 16 | abstract class GitCommandValueSource : ValueSource { 17 | /** 18 | * Execution operations instance to execute external process. 19 | */ 20 | @get:Inject 21 | abstract val execOperations: ExecOperations 22 | 23 | override fun obtain(): String { 24 | val output = ByteArrayOutputStream() 25 | 26 | execOperations.exec { 27 | it.apply { 28 | commandLine = parameters.commands.get() 29 | workingDir = parameters.directory.get() 30 | standardOutput = output 31 | isIgnoreExitValue = true 32 | } 33 | } 34 | return String(output.toByteArray(), Charset.defaultCharset()) 35 | } 36 | } 37 | 38 | /** 39 | * Parameters for passing down git command list. 40 | */ 41 | interface Parameters : ValueSourceParameters { 42 | /** 43 | * List of commands to execute in an external process. 44 | */ 45 | val commands: ListProperty 46 | 47 | /** 48 | * Working directory to execute external process in. 49 | */ 50 | val directory: Property 51 | } 52 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/gradle-plugins/org.danilopianini.git-semver.properties: -------------------------------------------------------------------------------- 1 | implementation-class=org.danilopianini.gradle.gitsemver.GitSemVer 2 | -------------------------------------------------------------------------------- /src/test/kotlin/org/danilopianini/gradle/gitsemver/test/Tests.kt: -------------------------------------------------------------------------------- 1 | package org.danilopianini.gradle.gitsemver.test 2 | 3 | import io.kotest.assertions.throwables.shouldThrowUnit 4 | import io.kotest.core.spec.style.StringSpec 5 | import io.kotest.matchers.shouldBe 6 | import io.kotest.matchers.shouldNotBe 7 | import io.kotest.matchers.string.shouldContain 8 | import io.kotest.matchers.string.shouldNotContain 9 | import org.gradle.internal.impldep.org.junit.rules.TemporaryFolder 10 | import org.gradle.testkit.runner.GradleRunner 11 | import org.gradle.testkit.runner.UnexpectedBuildFailure 12 | import java.util.concurrent.TimeUnit 13 | 14 | internal class Tests : 15 | StringSpec( 16 | { 17 | "minimal configuration" { 18 | val result = configuredPlugin().runGradle() 19 | println(result) 20 | result shouldContain "0.1.0-archeo+" 21 | } 22 | "simple usage of extension" { 23 | val result = configuredPlugin("noTagIdentifier.set(\"foo\")").runGradle() 24 | println(result) 25 | result shouldContain "0.1.0-foo+" 26 | } 27 | "git single commit" { 28 | val result = 29 | configuredPlugin("noTagIdentifier.set(\"foo\")") { 30 | initGit() 31 | }.runGradle() 32 | println(result) 33 | result shouldContain "0.1.0-foo" 34 | } 35 | "git tagged commit" { 36 | val result = 37 | configuredPlugin("noTagIdentifier.set(\"foo\")") { 38 | initGitWithTag() 39 | }.runGradle() 40 | println(result) 41 | result.lines().any { it matches Regex(""".*1\.2\.3$""") } shouldBe true 42 | } 43 | "git tagged commit with prefix" { 44 | val result = 45 | configuredPlugin( 46 | """ 47 | versionPrefix.set("v") 48 | """.trimIndent(), 49 | ) { 50 | initGitWithPrefixedTag() 51 | }.runGradle() 52 | println(result) 53 | result.lines().any { it matches Regex(""".*1\.2\.3$""") } shouldBe true 54 | } 55 | "git tagged + development" { 56 | val workingDirectory = 57 | configuredPlugin("developmentIdentifier.set(\"foodev\")") { 58 | initGitWithTag() 59 | file("something") { "something" } 60 | runCommand("git add something") 61 | runCommand("git", "commit", "-m", "\"Test commit 2\"") 62 | } 63 | val result = workingDirectory.runGradle() 64 | println(result) 65 | val expectedVersion = "1.2.4-foodev01+" 66 | result shouldContain expectedVersion 67 | with(workingDirectory) { 68 | runCommand("git", "tag", "-a", "test", "-m", "test tag") 69 | val newResult = runGradle() 70 | println(newResult) 71 | newResult shouldContain expectedVersion 72 | } 73 | with(workingDirectory) { 74 | runCommand("git", "tag", "-a", "1.2.4", "-m", "\"test\"") 75 | val newResult = runGradle() 76 | println(newResult) 77 | newResult.lineSequence().find { it.matches(".*1.2.4$".toRegex()) } shouldNotBe null 78 | } 79 | } 80 | "git tagged first release commit with release task" { 81 | val workingDirectory = 82 | configuredPlugin( 83 | """ 84 | computeReleaseVersion.set( 85 | project.tasks.named("release").map { 86 | project.gradle.taskGraph.hasTask(it) 87 | } 88 | ) 89 | """.trimIndent(), 90 | ) { 91 | initGit() 92 | } 93 | val result = workingDirectory.runGradle() 94 | println(result) 95 | val expectedVersion = "0.1.0" 96 | result.lines().any { it.endsWith(expectedVersion) } shouldBe false 97 | val newResult = workingDirectory.runGradle("release", "printGitSemVer", "--stacktrace") 98 | println(newResult) 99 | newResult.lines().any { it.endsWith(expectedVersion) } shouldBe true 100 | } 101 | "git tagged release commit" { 102 | val result = 103 | configuredPlugin("computeReleaseVersion.set(true)") { 104 | initGitWithTag() 105 | runCommand("git", "commit", "--allow-empty", "-m", "\"Test commit 2\"") 106 | }.runGradle() 107 | println(result) 108 | val expectedVersion = "1.2.4" 109 | result.lines().any { it.endsWith(expectedVersion) } shouldBe true 110 | } 111 | "manual assignment of version" { 112 | val workingDirectory = configuredPlugin("assignGitSemanticVersion()") 113 | val result = workingDirectory.runGradle() 114 | println(result) 115 | val expectedVersion = "0.1.0-archeo" 116 | result shouldContain expectedVersion 117 | } 118 | "regression for bug #2" { 119 | val workingDirectory = 120 | configuredPlugin( 121 | """ 122 | minimumVersion.set("0.1.0") 123 | developmentIdentifier.set("") // <--- NOTICE THIS 124 | noTagIdentifier.set("") // <--- NOTICE THIS 125 | developmentCounterLength.set(2) 126 | """.trimIndent(), 127 | ) 128 | val result = workingDirectory.runGradle() 129 | val expectedVersion = "0.1.0+" 130 | result shouldContain expectedVersion 131 | } 132 | "support for lightweight tags (#323)" { 133 | val workingDirectory = configuredPlugin() 134 | with(workingDirectory) { 135 | initGit() 136 | runCommand("git", "tag", "1.2.3") 137 | } 138 | workingDirectory.runGradle() shouldContain "1.2.3" 139 | } 140 | "exclusion of lightweight tags (#323)" { 141 | val workingDirectory = 142 | configuredPlugin( 143 | """ 144 | excludeLightweightTags() 145 | """.trimIndent(), 146 | ) 147 | with(workingDirectory) { 148 | initGit() 149 | runCommand("git", "tag", "1.2.3") 150 | } 151 | workingDirectory.runGradle() shouldNotContain "1.2.3" 152 | } 153 | "force the version" { 154 | val result = configuredPlugin().runGradle("-PforceVersion=1.2.3", "printGitSemVer", "--stacktrace") 155 | print(result) 156 | result shouldContain "1.2.3" 157 | } 158 | "force the version with a non compliant version" { 159 | shouldThrowUnit { 160 | configuredPlugin().runGradle("-PforceVersion=a.b.c", "printGitSemVer", "--stacktrace") 161 | } 162 | } 163 | "force the version with a custom property" { 164 | val result = 165 | configuredPlugin( 166 | """ 167 | forceVersionPropertyName.set("customVersion") 168 | """.trimIndent(), 169 | ).runGradle("-PcustomVersion=1.2.3", "printGitSemVer", "--stacktrace") 170 | print(result) 171 | result shouldContain "1.2.3" 172 | } 173 | "git tagged + development with change the version update strategy" { 174 | val workingDirectory = 175 | configuredPlugin( 176 | """ 177 | commitNameBasedUpdateStrategy { UpdateType.MAJOR } 178 | """, 179 | ) { 180 | initGitWithTag() 181 | file("something") { "something" } 182 | runCommand("git add something") 183 | runCommand("git", "commit", "-m", "\"Test commit 2\"") 184 | } 185 | val result = workingDirectory.runGradle() 186 | println(result) 187 | val expectedVersion = "2.0.0" 188 | result shouldContain expectedVersion 189 | } 190 | }, 191 | ) { 192 | companion object { 193 | fun folder(closure: TemporaryFolder.() -> Unit) = TemporaryFolder().apply { 194 | create() 195 | closure() 196 | } 197 | 198 | fun TemporaryFolder.file(name: String, content: () -> String) = newFile(name).writeText(content().trimIndent()) 199 | 200 | fun TemporaryFolder.runCommand(vararg command: String, wait: Long = 10) { 201 | val process = 202 | ProcessBuilder(*command) 203 | .directory(root) 204 | .redirectError(ProcessBuilder.Redirect.INHERIT) 205 | .redirectOutput(ProcessBuilder.Redirect.INHERIT) 206 | .apply { 207 | // git command isolation from the operating system environment 208 | environment().let { env -> 209 | env.clear() 210 | env["PATH"] = System.getenv("PATH") 211 | env["HOME"] = root.resolve(".git/.home.d/").absolutePath 212 | env["GIT_CONFIG_NOSYSTEM"] = "true" 213 | } 214 | } 215 | .start() 216 | process.waitFor(wait, TimeUnit.SECONDS) 217 | require(process.exitValue() == 0) { 218 | "command '${command.joinToString(" ")}' failed with exit value ${process.exitValue()}" 219 | } 220 | } 221 | 222 | fun TemporaryFolder.runCommand(command: String, wait: Long = 10) = runCommand( 223 | *command.split(" ").toTypedArray(), 224 | wait = wait, 225 | ) 226 | 227 | fun TemporaryFolder.initGit() { 228 | runCommand("git init") 229 | runCommand("git add .") 230 | runCommand("git config user.name gitsemver") 231 | runCommand("git config user.email none@test.com") 232 | runCommand("git config init.defaultBranch master") 233 | runCommand("git config commit.gpgsign no") 234 | runCommand("git", "commit", "-m", "\"Test commit\"") 235 | } 236 | 237 | fun TemporaryFolder.initGitWithTag() { 238 | initGit() 239 | runCommand("git", "tag", "-a", "1.2.3", "-m", "\"test\"") 240 | } 241 | 242 | fun TemporaryFolder.initGitWithPrefixedTag() { 243 | initGit() 244 | runCommand("git", "tag", "-a", "v1.2.3", "-m", "\"test\"") 245 | } 246 | 247 | fun TemporaryFolder.runGradle(vararg arguments: String = arrayOf("printGitSemVer", "--stacktrace")): String = 248 | GradleRunner 249 | .create() 250 | .withProjectDir(root) 251 | .withPluginClasspath() 252 | .withArguments(*arguments) 253 | .build() 254 | .output 255 | 256 | fun configuredPlugin( 257 | pluginConfiguration: String = "", 258 | otherChecks: TemporaryFolder.() -> Unit = {}, 259 | ): TemporaryFolder = folder { 260 | file("settings.gradle") { "rootProject.name = 'testproject'" } 261 | file("build.gradle.kts") { 262 | """ 263 | import org.danilopianini.gradle.gitsemver.* 264 | 265 | plugins { 266 | id("org.danilopianini.git-semver") 267 | } 268 | project.tasks.register("release") 269 | gitSemVer { 270 | $pluginConfiguration 271 | } 272 | """.trimIndent() 273 | } 274 | otherChecks() 275 | } 276 | } 277 | } 278 | --------------------------------------------------------------------------------