├── .editorconfig ├── .gitattributes ├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.yml │ └── feature_request.yml ├── pull_request_template.md └── 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 │ │ │ └── git │ │ │ └── hooks │ │ │ ├── AbstractScriptContext.kt │ │ │ ├── CommitMsgScriptContext.kt │ │ │ ├── CommonScriptContext.kt │ │ │ ├── ConventionalCommitsContext.kt │ │ │ ├── GitHooksExtension.kt │ │ │ ├── GradleGitHooksPlugin.kt │ │ │ └── ScriptContext.kt │ │ └── gradle │ │ └── kotlin │ │ └── dsl │ │ └── GradleGitHooksExtensions.kt └── sh │ └── org │ └── danilopianini │ └── gradle │ └── git │ └── hooks │ └── conventional-commit-message.sh └── test ├── kotlin └── org │ └── danilopianini │ └── gradle │ └── git │ └── hooks │ └── test │ ├── TestingDSL.kt │ └── Tests.kt └── resources └── org └── danilopianini └── gradle └── git └── hooks └── test ├── test-issue-248 ├── settings.gradle.kts └── test.yaml ├── test-issue-396 ├── git-config ├── settings.gradle.kts └── test.yaml ├── test-issue-88 ├── commit_message ├── settings.gradle.kts └── test.yaml └── test0 ├── settings.gradle.kts └── test.yaml /.editorconfig: -------------------------------------------------------------------------------- 1 | [*.{kt,kts}] 2 | max_line_length=120 3 | -------------------------------------------------------------------------------- /.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/ISSUE_TEMPLATE/bug_report.yml: -------------------------------------------------------------------------------- 1 | name: Bug report 2 | description: You've found a bug with the project. 3 | labels: ['bug', 'triage needed'] 4 | body: 5 | - type: markdown 6 | attributes: 7 | value: | 8 | Before you begin to fill out the form, make sure you have actually found a bug. 9 | 10 | - type: dropdown 11 | id: regression-error 12 | attributes: 13 | label: Was this something which used to work for you, and then stopped? 14 | options: 15 | - 'It used to work, and then stopped' 16 | - 'I never saw this working' 17 | validations: 18 | required: true 19 | 20 | - type: textarea 21 | id: describe-bug 22 | attributes: 23 | label: Describe the bug 24 | validations: 25 | required: true 26 | 27 | - type: textarea 28 | id: build-config 29 | attributes: 30 | label: Your configuration 31 | description: | 32 | Please paste the plugin configuration you are using 33 | value: | 34 |
Gradle Settings 35 | 36 | ```kotlin 37 | Copy/paste your settings.gradle.kts here, between the starting and ending backticks 38 | ``` 39 | 40 |
41 | 42 |
Gradle Build Config 43 | 44 | ```kotlin 45 | Copy/paste your build.gradle.kts here, between the starting and ending backticks 46 | ``` 47 | 48 |
49 | validations: 50 | required: true 51 | 52 | - type: textarea 53 | id: build-scan 54 | attributes: 55 | label: Gradle build scan and relevant logs 56 | description: | 57 | Please attach a build scan of the bug happening when running Gradle. 58 | You can obtain build scan link by using the `--scan` option 59 | value: | 60 | [Gradle build scan](LINK HERE) 61 | 62 |
Further relevant logs 63 | 64 | ``` 65 | Copy/paste the relevant log(s) here, between the starting and ending backticks 66 | ``` 67 | 68 |
69 | validations: 70 | required: true 71 | 72 | - type: dropdown 73 | id: minimal-reproduction-repository 74 | attributes: 75 | label: Have you created a minimal reproduction repository? 76 | options: 77 | - 'I have linked to a minimal reproduction repository in the bug description' 78 | - 'No reproduction, but I have linked to a public repo where it occurs' 79 | - 'No reproduction repository' 80 | validations: 81 | required: true 82 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.yml: -------------------------------------------------------------------------------- 1 | name: Feature request 2 | description: Suggest an idea for this project. 3 | labels: ['enhancement', 'needs triage'] 4 | body: 5 | - type: textarea 6 | id: what-would-you-like-to-be-able-to-do 7 | attributes: 8 | label: What would you like to be able to do? 9 | description: Tell us what requirements you need solving, and be sure to mention too if this is part of any bigger problem you're trying to solve. 10 | validations: 11 | required: true 12 | 13 | - type: textarea 14 | id: implementation-idea-textbox 15 | attributes: 16 | label: If you have any ideas on how this should be implemented, please tell us here. 17 | description: | 18 | In case you've already dug into existing options or source code and have ideas, mention them here. 19 | Try to keep implementation ideas separate from requirements. 20 | validations: 21 | required: true 22 | 23 | - type: dropdown 24 | id: interested-in-implementing-the-feature 25 | attributes: 26 | label: Is this a feature you are interested in implementing yourself? 27 | options: 28 | - 'Yes' 29 | - 'Maybe' 30 | - 'No, I could but I do not have time or will to' 31 | - 'No, I do not have the skills yet to do it' 32 | validations: 33 | required: true 34 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | ## Changes 2 | 3 | 4 | 5 | ## Context 6 | 7 | 8 | 9 | 10 | ## Documentation (please check one with an [x]) 11 | 12 | - [ ] I have updated the README.md file, or 13 | - [ ] No documentation update is required 14 | 15 | ## How I've tested my work (please tick one) 16 | 17 | I have verified these changes via: 18 | 19 | - [ ] Code inspection only, or 20 | - [ ] No unit tests but ran on a real Gradle project, or 21 | - [ ] Newly added/modified unit tests 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /.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, macos, ubuntu] 12 | runs-on: ${{ matrix.os }}-latest 13 | steps: 14 | - name: Checkout 15 | uses: DanySK/action-checkout@0.2.22 16 | - uses: DanySK/build-check-deploy-gradle-action@4.0.1 17 | with: 18 | deploy-command: >- 19 | ./gradlew 20 | uploadAll 21 | closeStaging 22 | dropStaging 23 | should-run-codecov: ${{ runner.os == 'Linux' }} 24 | codecov-token: ${{ secrets.CODECOV_TOKEN }} 25 | should-deploy: >- 26 | ${{ 27 | runner.os == 'Linux' 28 | && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) 29 | }} 30 | maven-central-username: ${{ secrets.MAVEN_CENTRAL_USERNAME }} 31 | maven-central-password: ${{ secrets.MAVEN_CENTRAL_PASSWORD }} 32 | signing-key: ${{ secrets.SIGNING_KEY }} 33 | signing-password: ${{ secrets.SIGNING_PASSWORD }} 34 | release: 35 | needs: 36 | - build 37 | runs-on: ubuntu-latest 38 | if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository 39 | concurrency: 40 | group: release 41 | steps: 42 | - name: Checkout 43 | uses: actions/checkout@v4.2.2 44 | with: 45 | token: ${{ secrets.DEPLOYMENT_TOKEN }} 46 | - name: Install Node 47 | uses: actions/setup-node@v4.4.0 48 | with: 49 | node-version-file: package.json 50 | - uses: DanySK/build-check-deploy-gradle-action@4.0.1 51 | with: 52 | retries-on-failure: '1' 53 | build-command: true 54 | check-command: true 55 | deploy-command: | 56 | npm install 57 | npx semantic-release 58 | should-run-codecov: false 59 | should-deploy: true 60 | should-validate-wrapper: false 61 | github-token: ${{ github.token }} 62 | gradle-publish-secret: ${{ secrets.GRADLE_PUBLISH_SECRET }} 63 | gradle-publish-key: ${{ secrets.GRADLE_PUBLISH_KEY }} 64 | maven-central-username: ${{ secrets.MAVEN_CENTRAL_USERNAME }} 65 | maven-central-password: ${{ secrets.MAVEN_CENTRAL_PASSWORD }} 66 | signing-key: ${{ secrets.SIGNING_KEY }} 67 | signing-password: ${{ secrets.SIGNING_PASSWORD }} 68 | success: 69 | runs-on: ubuntu-latest 70 | needs: 71 | - build 72 | - release 73 | if: >- 74 | always() && ( 75 | contains(join(needs.*.result, ','), 'failure') 76 | || !contains(join(needs.*.result, ','), 'cancelled') 77 | ) 78 | steps: 79 | - name: Verify that the workflow executed and there were no failures 80 | run: ${{ !contains(join(needs.*.result, ','), 'failure') }} 81 | -------------------------------------------------------------------------------- /.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 | jobs: 17 | dispatcher: 18 | runs-on: ubuntu-latest 19 | if: >- 20 | github.event_name != 'pull_request' 21 | || github.event.pull_request.head.repo.full_name != github.repository 22 | || startsWith(github.head_ref, 'refs/heads/dependabot/') 23 | steps: 24 | - run: 'true' 25 | ci-cd: 26 | needs: 27 | - dispatcher 28 | uses: ./.github/workflows/build-and-deploy.yml 29 | secrets: inherit 30 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle/ 2 | build/ 3 | .idea/ 4 | node_modules/ 5 | .kotlin 6 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DanySK/gradle-pre-commit-git-hooks/331619ac52dc0b5c306ac9d6e0d488cbaa41dac1/.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 2022 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 | # Gradle pre-commit Git Hooks 2 | 3 | A Gradle plugin enforcing pre-commit and commit-msg Git hooks configuration. Conventional-commits-ready. 4 | 5 | Hooks are created upfront, before the execution of any task. 6 | This implies that even when importing the project into a gradle-aware IDE, 7 | the hooks are generated automatically. 8 | 9 | ## Usage 10 | 11 | This plugin must be applied to `settings.gradle.kts`. 12 | 13 | ```kotlin 14 | plugins { 15 | id("org.danilopianini.gradle-pre-commit-git-hooks") version "" 16 | } 17 | 18 | gitHooks { 19 | // Configuration 20 | createHooks() // actual hooks creation 21 | } 22 | ``` 23 | 24 | The Groovy syntax is not officially supported. 25 | However, since Groovy can call Kotlin, it is still possible 26 | (though pretty cumbersome) 27 | to use the plugin from a Groovy `settings.gradle` file: 28 | 29 | ```groovy 30 | plugins { 31 | id('org.danilopianini.gradle-pre-commit-git-hooks') version '' 32 | } 33 | 34 | gitHooks { extension -> 35 | extension.with { 36 | commitMsg { context -> 37 | context.with { 38 | conventionalCommits { conventionalCommits -> 39 | conventionalCommits.with { 40 | defaultTypes() 41 | } 42 | } 43 | } 44 | } 45 | createHooks(true) 46 | } 47 | } 48 | ``` 49 | 50 | ### Contexts 51 | 52 | The plugin has special support for `commit-msg` and `pre-commit` hooks, which are the ones most frequently used. 53 | Conventional commits are enforced at the `commit-msg` level. 54 | Custom hooks can still be specified. 55 | 56 | ```kotlin 57 | gitHooks { 58 | preCommit { 59 | // Configuration for pre-commit 60 | } 61 | hook("pre-merge-commit") { 62 | // Configuration for pre-merge-commit 63 | } 64 | hook("foo") { 65 | // Configuration for foo 66 | } 67 | commitMsg { 68 | // Configuration, with conventional commits support 69 | } 70 | createHooks() 71 | } 72 | ``` 73 | 74 | ### Configuration options available to every hook 75 | 76 | Every script can be initialized by writing its code in form of `String` 77 | or by downloading it from a `URL`. 78 | Resource loading from classpath returns `URL`s and can thus be used transparently. 79 | These cases require the method `from`. 80 | 81 | The script can be enriched with more code by calling `appendScript`. 82 | 83 | Finally, the script can be required to run gradle tasks, 84 | either requiring their success or not, through `tasks` 85 | 86 | ```kotlin 87 | gitHooks { 88 | repoRoot = file("some/folder") // custom git repository location, defaults to the local project and scans the parents 89 | preCommit { 90 | // Script from a source, can be a String, URL or File 91 | from("https://my.repo/pre-commit.sh") 92 | // Content can be added at the bottom of the script 93 | appendScript { 94 | """ 95 | echo additional lines 96 | """ 97 | } 98 | } 99 | hook("pre-merge-commit") { 100 | from { // Creates a fresh script with a bash shebang line 101 | """ 102 | echo some bash code 103 | """ 104 | } 105 | // Content can be added at the bottom of the script 106 | appendScript { 107 | """ 108 | echo additional lines 109 | """ 110 | } 111 | } 112 | hook("foo") { 113 | from("#!/usr/bin/env ruby") { // Custom shebang line 114 | """ 115 | puts "Hello, world" 116 | """ 117 | } 118 | tasks("baz", "gra") // also runs tasks baz and gra, requiring their success 119 | } 120 | hook("baz") { 121 | tasks("zin", "pla", requireSuccess = false) // runs tasks zin and pla, ignoring failure 122 | tasks("wab") // then, runs task wab, requiring success 123 | } 124 | createHooks() 125 | } 126 | ``` 127 | 128 | ### Conventional commits 129 | 130 | Conventional commits receive special treatment, 131 | they can get configured succinctly inside the `commitMsg` block. 132 | 133 | The Default configuration supports the following commit types: 134 | `fix`, `feat`, `build`, `chore`, `ci`, `docs`, `perf`, `refactor`, `revert`, `style`, `test`. 135 | 136 | ```kotlin 137 | gitHooks { 138 | commitMsg { conventionalCommits() } // Applies the default conventional commits configuration 139 | createHooks() 140 | } 141 | ``` 142 | 143 | The base configuration supports only `fix` and `feat` 144 | 145 | ```kotlin 146 | gitHooks { 147 | commitMsg { 148 | conventionalCommits { } // Only feat and fix 149 | } 150 | createHooks() 151 | } 152 | ``` 153 | 154 | The following shows a custom configuration, 155 | adding custom types `foo`, `bar`, and `baz` to `fix` and `feat` 156 | 157 | ```kotlin 158 | gitHooks { 159 | commitMsg { 160 | conventionalCommits { 161 | types("foo", "bar") 162 | types("baz") 163 | } 164 | } 165 | createHooks() 166 | } 167 | ``` 168 | 169 | The following custom configuration instead extends the default configuration, 170 | adding custom types `foo` and `bar`. 171 | 172 | ```kotlin 173 | gitHooks { 174 | commitMsg { 175 | conventionalCommits { 176 | defaultTypes() 177 | types("foo", "bar") 178 | } 179 | } 180 | createHooks() 181 | } 182 | ``` 183 | 184 | If you want to be able to always overwrite your hook changes pass `true` to the createHooks() method 185 | ```kotlin 186 | gitHooks { 187 | preCommit { 188 | from { // Creates a fresh script with a bash shebang line 189 | """ 190 | echo some bash code you have changed 191 | """ 192 | } 193 | } 194 | createHooks(true) 195 | } 196 | ``` 197 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | @file:Suppress("UnstableApiUsage") 2 | 3 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompilationTask 4 | 5 | @Suppress("DSL_SCOPE_VIOLATION") 6 | plugins { 7 | `java-gradle-plugin` 8 | alias(libs.plugins.dokka) 9 | alias(libs.plugins.gitSemVer) 10 | alias(libs.plugins.gradlePluginPublish) 11 | alias(libs.plugins.kotlin.jvm) 12 | alias(libs.plugins.kotlin.qa) 13 | alias(libs.plugins.publishOnCentral) 14 | alias(libs.plugins.multiJvmTesting) 15 | alias(libs.plugins.taskTree) 16 | } 17 | 18 | /* 19 | * Project information 20 | */ 21 | group = "org.danilopianini" 22 | description = "A Gradle plugin enforcing pre-commit and commit-msg Git hooks configuration. Conventional-commits-ready." 23 | 24 | class ProjectInfo { 25 | val longName = "Gradle pre-commit Git Hooks" 26 | val website = "https://github.com/DanySK/$name" 27 | val vcsUrl = "$website.git" 28 | val scm = "scm:git:$website.git" 29 | val pluginImplementationClass = "$group.gradle.git.hooks.GradleGitHooksPlugin" 30 | val tags = listOf("git", "hook", "git hooks", "conventional commits") 31 | } 32 | val info = ProjectInfo() 33 | 34 | gitSemVer { 35 | buildMetadataSeparator.set("-") 36 | } 37 | 38 | repositories { 39 | mavenCentral() 40 | } 41 | 42 | multiJvm { 43 | maximumSupportedJvmVersion.set(latestJavaSupportedByGradle) 44 | } 45 | 46 | dependencies { 47 | api(gradleApi()) 48 | api(gradleKotlinDsl()) 49 | api(kotlin("stdlib-jdk8")) 50 | testImplementation(gradleTestKit()) 51 | testImplementation(libs.konf.yaml) 52 | testImplementation(libs.classgraph) 53 | testImplementation(libs.bundles.kotlin.testing) 54 | } 55 | 56 | sourceSets { 57 | main { 58 | resources { 59 | srcDir("src/main/sh") 60 | } 61 | } 62 | } 63 | 64 | tasks.withType>().configureEach { 65 | compilerOptions { 66 | allWarningsAsErrors = true 67 | freeCompilerArgs = listOf("-opt-in=kotlin.RequiresOptIn") 68 | } 69 | } 70 | 71 | tasks.withType { 72 | useJUnitPlatform() 73 | testLogging { 74 | showStandardStreams = true 75 | showCauses = true 76 | showStackTraces = true 77 | events( 78 | *org.gradle.api.tasks.testing.logging.TestLogEvent 79 | .values(), 80 | ) 81 | exceptionFormat = org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL 82 | } 83 | } 84 | 85 | signing { 86 | if (System.getenv()["CI"].equals("true", ignoreCase = true)) { 87 | val signingKey: String? by project 88 | val signingPassword: String? by project 89 | useInMemoryPgpKeys(signingKey, signingPassword) 90 | } 91 | } 92 | 93 | /* 94 | * Publication on Maven Central and the Plugin portal 95 | */ 96 | publishOnCentral { 97 | projectLongName.set(info.longName) 98 | projectDescription.set(description ?: TODO("Missing description")) 99 | projectUrl.set(info.website) 100 | scmConnection.set(info.scm) 101 | repository("https://maven.pkg.github.com/DanySK/${rootProject.name}".lowercase(), name = "github") { 102 | user.set("danysk") 103 | password.set(System.getenv("GITHUB_TOKEN")) 104 | } 105 | publishing { 106 | publications { 107 | withType { 108 | pom { 109 | developers { 110 | developer { 111 | name.set("Danilo Pianini") 112 | email.set("danilo.pianini@gmail.com") 113 | url.set("http://www.danilopianini.org/") 114 | } 115 | } 116 | } 117 | } 118 | } 119 | } 120 | } 121 | 122 | gradlePlugin { 123 | website.set(info.website) 124 | vcsUrl.set(info.vcsUrl) 125 | plugins { 126 | create("gitHooks") { 127 | id = "$group.${project.name}" 128 | displayName = info.longName 129 | description = project.description 130 | implementationClass = info.pluginImplementationClass 131 | tags.set(info.tags) 132 | } 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | org.gradle.jvmargs=-XX:MaxMetaspaceSize=512m 2 | kotlin.code.style=official 3 | -------------------------------------------------------------------------------- /gradle/libs.versions.toml: -------------------------------------------------------------------------------- 1 | [versions] 2 | dokka = "2.0.0" 3 | konf = "1.1.2" 4 | kotest = "5.9.1" 5 | kotlin = "2.1.21" 6 | 7 | [libraries] 8 | classgraph = "io.github.classgraph:classgraph:4.8.179" 9 | konf-yaml = { module = "com.uchuhimo:konf-yaml", version.ref = "konf" } 10 | kotest-junit5-jvm = { module = "io.kotest:kotest-runner-junit5-jvm", version.ref = "kotest" } 11 | kotest-assertions-core-jvm = { module = "io.kotest:kotest-assertions-core-jvm", version.ref = "kotest" } 12 | 13 | [bundles] 14 | kotlin-testing = [ "kotest-junit5-jvm", "kotest-assertions-core-jvm" ] 15 | 16 | [plugins] 17 | dokka = { id = "org.jetbrains.dokka", version.ref = "dokka" } 18 | gitSemVer = { id = "org.danilopianini.git-sensitive-semantic-versioning", version = "5.1.4" } 19 | gradlePluginPublish = { id = "com.gradle.plugin-publish", version = "1.3.1" } 20 | kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" } 21 | kotlin-qa = { id = "org.danilopianini.gradle-kotlin-qa", version = "0.89.1" } 22 | multiJvmTesting = { id = "org.danilopianini.multi-jvm-test-plugin", version = "3.5.1" } 23 | publishOnCentral = { id = "org.danilopianini.publish-on-central", version = "8.0.7" } 24 | taskTree = { id = "com.dorongold.task-tree", version = "4.0.1" } 25 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DanySK/gradle-pre-commit-git-hooks/331619ac52dc0b5c306ac9d6e0d488cbaa41dac1/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.2-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\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 | git tag -a -f \${nextRelease.version} \${nextRelease.version} -F CHANGELOG.md 3 | git push --force origin \${nextRelease.version} 4 | ./gradlew uploadAll releaseStagingRepositoryOnMavenCentral || exit 1 5 | ./gradlew \ 6 | publishPlugins \ 7 | -Pgradle.publish.key=$GRADLE_PUBLISH_KEY \ 8 | -Pgradle.publish.secret=$GRADLE_PUBLISH_SECRET || exit 2 9 | ./gradlew publishAllToGithubRepository || true 10 | ` 11 | import config from 'semantic-release-preconfigured-conventional-commits' with { type: "json" }; 12 | config.plugins.push( 13 | [ 14 | "@semantic-release/exec", 15 | { 16 | "publishCmd": publishCmd, 17 | } 18 | ], 19 | "@semantic-release/github", 20 | "@semantic-release/git", 21 | ) 22 | export default config 23 | -------------------------------------------------------------------------------- /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() 21 | } 22 | 23 | rootProject.name = "gradle-pre-commit-git-hooks" 24 | -------------------------------------------------------------------------------- /src/main/kotlin/org/danilopianini/gradle/git/hooks/AbstractScriptContext.kt: -------------------------------------------------------------------------------- 1 | package org.danilopianini.gradle.git.hooks 2 | 3 | /** 4 | * Pre-implements [tasks]. 5 | */ 6 | abstract class AbstractScriptContext : ScriptContext { 7 | final override fun tasks( 8 | first: Any, 9 | vararg others: Any, 10 | requireSuccess: Boolean, 11 | ) = processTasks(first, *others, requireSuccess = requireSuccess) 12 | 13 | protected abstract fun processTasks( 14 | vararg tasks: Any, 15 | requireSuccess: Boolean, 16 | ) 17 | } 18 | -------------------------------------------------------------------------------- /src/main/kotlin/org/danilopianini/gradle/git/hooks/CommitMsgScriptContext.kt: -------------------------------------------------------------------------------- 1 | package org.danilopianini.gradle.git.hooks 2 | 3 | import java.net.URL 4 | 5 | /** 6 | * Specialized hook context for commit-msg. 7 | */ 8 | class CommitMsgScriptContext : CommonScriptContext("commit-msg") { 9 | /** 10 | * Pre-configures the commit-msg script to check for a valid 11 | * [conventional commit](https://www.conventionalcommits.org/) 12 | * message. 13 | */ 14 | fun conventionalCommits(configuration: ConventionalCommitsContext.() -> Unit = { defaultTypes() }) { 15 | val types = 16 | object : ConventionalCommitsContext { 17 | override var types = super.types 18 | 19 | override fun types(otherTypes: Set) { 20 | types = types + otherTypes 21 | } 22 | }.apply(configuration).types 23 | from("") { 24 | val script: URL = 25 | requireNotNull(Thread.currentThread().contextClassLoader.getResource(SCRIPT_PATH)) { 26 | "Unable to load $SCRIPT_PATH, this is likely a bug in the ${GitHooksExtension.NAME} plugin" 27 | } 28 | script.readText().replace("# INJECT_TYPES", types.joinToString(separator = " ")) 29 | } 30 | } 31 | 32 | private companion object { 33 | private const val SCRIPT_PATH = "org/danilopianini/gradle/git/hooks/conventional-commit-message.sh" 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/kotlin/org/danilopianini/gradle/git/hooks/CommonScriptContext.kt: -------------------------------------------------------------------------------- 1 | package org.danilopianini.gradle.git.hooks 2 | 3 | import org.gradle.api.Task 4 | import org.gradle.api.tasks.TaskProvider 5 | 6 | /** 7 | * Implements a Script DSL valid for any hook. 8 | */ 9 | open class CommonScriptContext( 10 | override val name: String, 11 | ) : AbstractScriptContext() { 12 | final override var script: String = "" 13 | private set 14 | 15 | override fun appendScript(script: () -> String) { 16 | require(this.script.isNotEmpty()) { 17 | """ 18 | An append was requested to an uninitialized script $name. Configure as follows, instead: 19 | gitHooks { 20 | { 21 | from { 22 | 23 | } 24 | 25 | } 26 | } 27 | """.trimIndent() 28 | } 29 | this.script += script() + '\n' 30 | } 31 | 32 | final override fun from( 33 | shebang: String?, 34 | script: () -> String, 35 | ) { 36 | require(this.script.isEmpty()) { 37 | """ 38 | The $name git hook is being defined twice, and this is likely an error. Formerly: 39 | 40 | ${this.script} 41 | 42 | then: 43 | 44 | ${ 45 | runCatching { script() } 46 | .getOrElse { "Something whose evaluation this error:\n${it.stackTraceToString()}" } 47 | } 48 | """.trimIndent() 49 | } 50 | this.script = (shebang?.takeIf { it.isNotBlank() }?.let { "$it\n" }.orEmpty()) + script() 51 | } 52 | 53 | final override fun processTasks( 54 | vararg tasks: Any, 55 | requireSuccess: Boolean, 56 | ) { 57 | val names = 58 | tasks.map { task -> 59 | when (task) { 60 | is String -> task 61 | is Task -> task.name 62 | is TaskProvider<*> -> task.name 63 | else -> 64 | error( 65 | "Object '$task' with type '${task::class.simpleName}' cannot produce valid task names", 66 | ) 67 | } 68 | } 69 | if (script.isEmpty()) { 70 | from { "" } 71 | } 72 | appendScript { 73 | """ 74 | ${ if (requireSuccess) "set -e" else "" } 75 | ./gradlew ${names.joinToString(separator = " ")} 76 | ${ if (requireSuccess) "set +e" else "" } 77 | """.trimIndent() 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/main/kotlin/org/danilopianini/gradle/git/hooks/ConventionalCommitsContext.kt: -------------------------------------------------------------------------------- 1 | package org.danilopianini.gradle.git.hooks 2 | 3 | /** 4 | * Specialized DSL element for dealing with [conventional commits](https://www.conventionalcommits.org/). 5 | */ 6 | interface ConventionalCommitsContext { 7 | /** 8 | * The selected valid commit types. 9 | */ 10 | val types: Set get() = baseTypes 11 | 12 | /** 13 | * Adds new supported types. 14 | */ 15 | fun types(vararg otherTypes: String): Unit = types(otherTypes.toSet()) 16 | 17 | /** 18 | * Adds a new supported types. 19 | */ 20 | fun types(otherTypes: Set) 21 | 22 | /** 23 | * configures all the types in [Companion.defaultTypes]. 24 | */ 25 | fun defaultTypes() = types(defaultTypes) 26 | 27 | /** 28 | * Container for the default types. 29 | */ 30 | companion object { 31 | /** 32 | * Base types: `fix` and `feat`. 33 | */ 34 | val baseTypes = setOf("fix", "feat") 35 | 36 | /** 37 | * Additional types, as listed in the [conventional commits](https://www.conventionalcommits.org/) webpage, 38 | * plus `refactor`, which is commonly used. 39 | */ 40 | val defaultTypes: Set = 41 | baseTypes + 42 | setOf( 43 | "build", 44 | "chore", 45 | "ci", 46 | "docs", 47 | "perf", 48 | "refactor", 49 | "revert", 50 | "style", 51 | "test", 52 | ) 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/kotlin/org/danilopianini/gradle/git/hooks/GitHooksExtension.kt: -------------------------------------------------------------------------------- 1 | package org.danilopianini.gradle.git.hooks 2 | 3 | import org.gradle.api.initialization.Settings 4 | import org.gradle.api.logging.Logging 5 | import java.io.File 6 | import java.io.Serializable 7 | 8 | /** 9 | * DSL entry point, to be applied to [settings].gradle.kts. 10 | */ 11 | open class GitHooksExtension( 12 | val settings: Settings, 13 | ) : Serializable { 14 | private var hooks: Map = emptyMap() 15 | private var pathHasBeenManuallySet = false 16 | 17 | /** 18 | * The git repository root. If unset, it will be searched recursively from the project root towards the 19 | * filesystem root. 20 | */ 21 | var repoRoot: File = settings.settingsDir 22 | set(value) { 23 | require(value.isGitRoot()) { 24 | "${value.absolutePath} is not a valid git root (it must contain a .git folder)" 25 | } 26 | pathHasBeenManuallySet = true 27 | field = value 28 | } 29 | get() = 30 | field.takeIf { pathHasBeenManuallySet } 31 | ?: generateSequence(field) { it.parentFile }.find { it.isGitRoot() } 32 | ?: error( 33 | """ 34 | No git root could be found in ${field.absolutePath} or any of its parent directories. 35 | You may want to set it manually with: 36 | gitHooks { 37 | repoRoot = File("") 38 | } 39 | """.trimIndent(), 40 | ) 41 | 42 | private val gitDir get() = File(repoRoot, ".git") 43 | 44 | private inline fun hook( 45 | context: H, 46 | configuration: H.() -> Unit, 47 | ) { 48 | require(!hooks.containsKey(context.name)) { 49 | "it looks like the hook ${context.name} is being defined twice" 50 | } 51 | hooks = hooks + (context.name to context.apply(configuration).script) 52 | } 53 | 54 | /** 55 | * Defines a new hook with an arbitrary name. 56 | */ 57 | fun hook( 58 | hookName: String, 59 | configuration: ScriptContext.() -> Unit, 60 | ) = hook(CommonScriptContext(hookName), configuration) 61 | 62 | /** 63 | * Pre-commit hook. 64 | */ 65 | fun preCommit(configuration: ScriptContext.() -> Unit) = hook("pre-commit", configuration) 66 | 67 | /** 68 | * Commit-msg hook. 69 | */ 70 | fun commitMsg(configuration: CommitMsgScriptContext.() -> Unit): Unit = 71 | hook(CommitMsgScriptContext(), configuration) 72 | 73 | /** 74 | * To be called to force the hook creation in case of necessity. 75 | * If passed `true`, overwrites in case the script is already present and different than expected. 76 | */ 77 | fun createHooks(overwriteExisting: Boolean = false) { 78 | if (gitDir.isFile && "gitdir:" in gitDir.readText()) { 79 | // gets a logger from the settings object 80 | Logging.getLogger(GitHooksExtension::class.java).warn( 81 | """ 82 | |The git root does not contain a .git folder, but a .git file with a gitdir: directive. 83 | |This is typically an indication that the git repository is a detached worktree. 84 | |Hooks generation in detached worktrees is not supported, see: 85 | |https://github.com/DanySK/gradle-pre-commit-git-hooks/issues/396 86 | """.trimMargin().replace(Regex("\\R"), "\n"), 87 | ) 88 | } else { 89 | actuallyCreateHooks(overwriteExisting) 90 | } 91 | } 92 | 93 | private fun actuallyCreateHooks(overwriteExisting: Boolean) { 94 | if (gitDir.isFile) { 95 | error( 96 | """ 97 | ${gitDir.absolutePath} exists but it is not a directory. It contains: 98 | ${gitDir.readText()} 99 | If you are working on a detached worktree, this is likely a regression of issue #396, see: 100 | https://github.com/DanySK/gradle-pre-commit-git-hooks/issues/396 101 | """.trimIndent(), 102 | ) 103 | } 104 | val hooksFolder = File(gitDir, "hooks") 105 | if (!hooksFolder.exists()) { 106 | check(hooksFolder.mkdirs()) { 107 | "Directory ${hooksFolder.absolutePath} does not exist and can not be created" 108 | } 109 | } 110 | check(hooksFolder.exists()) { 111 | "${hooksFolder.absolutePath} should have been initialized, but it does not exist" 112 | } 113 | check(hooksFolder.isDirectory) { 114 | "${hooksFolder.absolutePath} has been initialized, but it is a file, not a directory" 115 | } 116 | hooks.forEach { (name, script) -> 117 | val hook = File(hooksFolder, name) 118 | if (!hook.exists()) { 119 | require(hook.createNewFile()) { "Cannot create file ${hook.absolutePath}" } 120 | hook.writeScript(script) 121 | } else { 122 | val oldScript = hook.readText() 123 | if (oldScript != script) { 124 | println( 125 | """ 126 | |The hook $name exists, but its content differs from the one generated by the git-hooks plugin. 127 | | 128 | |Original content: 129 | ${oldScript.withMargins()} 130 | | 131 | |New content: 132 | ${script.withMargins()} 133 | | 134 | |If you want to overwrite this file on every change add true to the createHooks(true) 135 | |method in your settings.gradle.kts 136 | """.trimMargin().lines().joinToString(separator = "\n") { 137 | "WARNING: $it" 138 | }, 139 | ) 140 | if (overwriteExisting) { 141 | println("WARNING: Overwriting git hook $name") 142 | hook.writeScript(script) 143 | } 144 | } 145 | } 146 | } 147 | } 148 | 149 | internal companion object { 150 | private const val serialVersionUID = 2L 151 | 152 | /** 153 | * Extension name. 154 | */ 155 | internal const val NAME: String = "gitHooks" 156 | 157 | private fun String.withMargins() = lines().joinToString(separator = "\n|", prefix = "|") 158 | 159 | private fun File.writeScript(script: String) { 160 | writeText(script) 161 | setExecutable(true) 162 | } 163 | 164 | private fun File.isGitRoot(): Boolean = 165 | listFiles() 166 | ?.any { file -> file.name == ".git" } 167 | ?: false 168 | } 169 | } 170 | -------------------------------------------------------------------------------- /src/main/kotlin/org/danilopianini/gradle/git/hooks/GradleGitHooksPlugin.kt: -------------------------------------------------------------------------------- 1 | package org.danilopianini.gradle.git.hooks 2 | 3 | import org.gradle.api.Plugin 4 | import org.gradle.api.initialization.Settings 5 | import org.gradle.kotlin.dsl.create 6 | 7 | /** 8 | * Creates support for the hooks. 9 | */ 10 | open class GradleGitHooksPlugin : Plugin { 11 | override fun apply(settings: Any) { 12 | require(settings is Settings) { 13 | """ 14 | ${this::class.simpleName} is not meant to be applied manually. It should be applied to settings.gradle.kts: 15 | plugins { 16 | id("org.danilopianini.gradle-pre-commit-git-hooks") version "" 17 | } 18 | gitHooks { 19 | ... 20 | createHooks() 21 | } 22 | """.trimIndent() 23 | } 24 | settings.extensions.create(GitHooksExtension.NAME, settings) 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/kotlin/org/danilopianini/gradle/git/hooks/ScriptContext.kt: -------------------------------------------------------------------------------- 1 | package org.danilopianini.gradle.git.hooks 2 | 3 | import org.gradle.api.Task 4 | import org.gradle.api.tasks.TaskProvider 5 | import java.io.File 6 | import java.net.URL 7 | 8 | /** 9 | * Collects the DSL elements for defining scripts. 10 | */ 11 | interface ScriptContext { 12 | /** 13 | * Hook name. 14 | */ 15 | val name: String 16 | 17 | /** 18 | * Script content. To be fetched only when the configuration is complete. 19 | */ 20 | val script: String 21 | 22 | /** 23 | * Appends the result of the provided function to the existing script. 24 | */ 25 | fun appendScript(script: () -> String) 26 | 27 | /** 28 | * Generates a script from the provided [file]. 29 | */ 30 | fun from(file: File) = from("") { file.readText() } 31 | 32 | /** 33 | * Generates a script from the provided [url]. 34 | */ 35 | fun from(url: URL) = from("") { url.readText() } 36 | 37 | /** 38 | * Generates a script from the provided [url]. 39 | */ 40 | fun from(url: String) = from(URL(url)) 41 | 42 | /** 43 | * Generates a script with either the provided [shebang] or with a shebang invoking bash, 44 | * and with the result of the provided function. 45 | */ 46 | fun from( 47 | shebang: String? = "#!/usr/bin/env bash", 48 | script: () -> String, 49 | ) 50 | 51 | /** 52 | * Adds the provided tasks to the script, by invoking `./gradlew `. 53 | * By default, a failure of the task implies a failure of the commit. 54 | * To run a task without considering the failure critical, pass `[requireSuccess] = false`. 55 | */ 56 | fun tasks( 57 | name: String, 58 | vararg otherNames: String, 59 | requireSuccess: Boolean = true, 60 | ) = tasks(name as Any, *otherNames, requireSuccess = requireSuccess) 61 | 62 | /** 63 | * Adds the provided tasks to the script, by invoking `./gradlew `. 64 | * By default, a failure of the task implies a failure of the commit. 65 | * To run a task without considering the failure critical, pass `[requireSuccess] = false`. 66 | */ 67 | fun tasks( 68 | task: Task, 69 | vararg otherTasks: Task, 70 | requireSuccess: Boolean = true, 71 | ) = tasks(task as Any, *otherTasks, requireSuccess = requireSuccess) 72 | 73 | /** 74 | * Adds the provided tasks to the script, by invoking `./gradlew `. 75 | * By default, a failure of the task implies a failure of the commit. 76 | * To run a task without considering the failure critical, pass `[requireSuccess] = false`. 77 | */ 78 | fun tasks( 79 | task: TaskProvider<*>, 80 | vararg otherTasks: TaskProvider<*>, 81 | requireSuccess: Boolean = true, 82 | ) = tasks(task as Any, *otherTasks, requireSuccess = requireSuccess) 83 | 84 | /** 85 | * Adds the provided tasks to the script, by invoking `./gradlew `. 86 | * By default, a failure of the task implies a failure of the commit. 87 | * To run a task without considering the failure critical, pass `[requireSuccess] = false`. 88 | */ 89 | fun tasks( 90 | first: Any, 91 | vararg others: Any, 92 | requireSuccess: Boolean = true, 93 | ) 94 | } 95 | -------------------------------------------------------------------------------- /src/main/kotlin/org/gradle/kotlin/dsl/GradleGitHooksExtensions.kt: -------------------------------------------------------------------------------- 1 | package org.gradle.kotlin.dsl 2 | 3 | import org.danilopianini.gradle.git.hooks.GitHooksExtension 4 | import org.gradle.api.initialization.Settings 5 | 6 | /** 7 | * DSL entry point for the git hooks commits. 8 | * This function is needed because Gradle doesn't generate accessors for settings extensions. 9 | */ 10 | inline fun Settings.gitHooks(configure: GitHooksExtension.() -> Unit) { 11 | extensions.getByType().configure() 12 | } 13 | -------------------------------------------------------------------------------- /src/main/sh/org/danilopianini/gradle/git/hooks/conventional-commit-message.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # list of Conventional Commits types 4 | types=( 5 | # INJECT_TYPES 6 | ) 7 | 8 | # the commit message file is the only argument 9 | msg_file="$1" 10 | 11 | # join types with | to form regex ORs 12 | r_types="($(IFS='|'; echo "${types[*]}"))" 13 | # optional (scope) 14 | r_scope="(\([[:alnum:] \/-]+\))?" 15 | # optional breaking change indicator and colon delimiter 16 | r_delim='!?:' 17 | # subject line, body, footer 18 | r_subject=" [[:graph:]].+" 19 | # the full regex pattern 20 | pattern="^$r_types$r_scope$r_delim$r_subject$" 21 | 22 | # Check if commit is conventional commit 23 | if grep -Eq "$pattern" "$msg_file"; then 24 | exit 0 25 | fi 26 | 27 | if test -t 1 && test -n "$(tput colors)"; then 28 | RED='\033[0;31m' 29 | GREEN='\033[0;32m' 30 | BLUE='\033[0;34m' 31 | PURPLE='\033[0;35m' 32 | NC='\033[0m' 33 | fi 34 | 35 | echo -e "${RED}ERROR: Invalid commit message${NC}: 36 | ${PURPLE}$( cat "$msg_file" )${NC} 37 | " 38 | echo -e " 39 | Your commit message does ${RED}not${NC} follow ${PURPLE}Conventional Commits${NC} formatting: ${BLUE}https://www.conventionalcommits.org/${NC} 40 | Conventional Commits start with one of the following types: 41 | ${GREEN}$(IFS=' '; echo "${types[*]}")${NC} 42 | followed by an ${PURPLE}optional scope within parentheses${NC}, 43 | followed by an ${RED}exclamation mark${NC} (${RED}!${NC}) in case of ${RED}breaking change${NC}, 44 | followed by a colon (:), 45 | followed by the commit message. 46 | Example commit message fixing a bug non-breaking backwards compatibility: 47 | ${GREEN}fix(module): fix bug #42${NC} 48 | Example commit message adding a non-breaking feature: 49 | ${GREEN}feat(module): add new API${NC} 50 | Example commit message with a breaking change: 51 | ${GREEN}refactor(module)!: remove infinite loop${NC} 52 | " 53 | exit 1 54 | -------------------------------------------------------------------------------- /src/test/kotlin/org/danilopianini/gradle/git/hooks/test/TestingDSL.kt: -------------------------------------------------------------------------------- 1 | package org.danilopianini.gradle.git.hooks.test 2 | 3 | import com.uchuhimo.konf.ConfigSpec 4 | import org.gradle.internal.impldep.org.apache.commons.lang.StringUtils 5 | import java.io.File 6 | 7 | object Root : ConfigSpec("") { 8 | val tests by required>() 9 | } 10 | 11 | data class Test( 12 | val description: String, 13 | val configuration: Configuration, 14 | val expectation: Expectation, 15 | ) 16 | 17 | @Suppress("ConstructorParameterNaming") 18 | data class Configuration( 19 | val tasks: List, 20 | val options: List = emptyList(), 21 | val pre_run_script: List = emptyList(), 22 | val post_run_script: List = emptyList(), 23 | ) 24 | 25 | @Suppress("ConstructorParameterNaming") 26 | data class Expectation( 27 | val file_exists: List = emptyList(), 28 | val success: List = emptyList(), 29 | val failure: List = emptyList(), 30 | val output_contains: List = emptyList(), 31 | ) 32 | 33 | enum class Permission( 34 | private val hasPermission: File.() -> Boolean, 35 | ) { 36 | R(File::canRead), 37 | W(File::canWrite), 38 | X(File::canExecute), 39 | ; 40 | 41 | fun requireOnFile(file: File) = 42 | require(file.hasPermission()) { 43 | "File ${file.absolutePath} must have permission $name, but it does not." 44 | } 45 | } 46 | 47 | data class ExistingFile( 48 | val name: String, 49 | val findRegex: String? = null, 50 | val content: String? = null, 51 | val trim: Boolean = false, 52 | val permissions: List = emptyList(), 53 | ) { 54 | fun validate(actualFile: File): Unit = 55 | with(actualFile) { 56 | require(exists()) { 57 | "File $name does not exist." 58 | } 59 | if (content != null) { 60 | val text = readText() 61 | require(text.trim() == content.trim()) { 62 | """ 63 | |Content of $name does not match expectations. 64 | | 65 | |Expected: 66 | |${content.replace(Regex("\\R"), "\n|")} 67 | | 68 | |Actual: 69 | |${text.replace(Regex("\\R"), "\n|")} 70 | | 71 | |Difference starts at index ${StringUtils.indexOfDifference(content, text)}: 72 | |${StringUtils.difference(content, text).replace(Regex("\\R"), "\n|")} 73 | """.trimMargin() 74 | } 75 | } 76 | if (findRegex != null) { 77 | val regex = Regex(findRegex) 78 | requireNotNull(readLines().find { regex.matches(it) }) { 79 | """ 80 | None of the lines in $name matches the regular expression $findRegex. File content: 81 | ${readText()} 82 | """.trimIndent() 83 | } 84 | } 85 | permissions.forEach { it.requireOnFile(this) } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/test/kotlin/org/danilopianini/gradle/git/hooks/test/Tests.kt: -------------------------------------------------------------------------------- 1 | package org.danilopianini.gradle.git.hooks.test 2 | 3 | import com.uchuhimo.konf.Config 4 | import com.uchuhimo.konf.source.yaml 5 | import io.github.classgraph.ClassGraph 6 | import io.kotest.core.spec.style.StringSpec 7 | import io.kotest.matchers.file.shouldBeAFile 8 | import io.kotest.matchers.file.shouldExist 9 | import io.kotest.matchers.shouldBe 10 | import io.kotest.matchers.string.shouldContain 11 | import org.gradle.internal.hash.Hashing 12 | import org.gradle.internal.impldep.org.junit.rules.TemporaryFolder 13 | import org.gradle.testkit.runner.BuildResult 14 | import org.gradle.testkit.runner.GradleRunner 15 | import org.gradle.testkit.runner.TaskOutcome 16 | import org.slf4j.Logger 17 | import org.slf4j.LoggerFactory 18 | import java.io.File 19 | import java.util.concurrent.TimeUnit 20 | import java.util.regex.Pattern 21 | 22 | class Tests : 23 | StringSpec( 24 | { 25 | val scan = 26 | ClassGraph() 27 | .enableAllInfo() 28 | .acceptPackages(Tests::class.java.`package`.name) 29 | .scan() 30 | scan 31 | .getResourcesWithLeafName("test.yaml") 32 | .flatMap { resource -> 33 | log.debug("Found test list in {}", resource) 34 | val yamlFile = File(resource.classpathElementFile.absolutePath + "/" + resource.path) 35 | val testConfiguration = 36 | Config { 37 | addSpec(Root) 38 | }.from.yaml.inputStream(resource.open()) 39 | testConfiguration[Root.tests].map { it to yamlFile.parentFile } 40 | }.forEach { (test, location) -> 41 | log.debug("Test to be executed: {} from {}", test, location) 42 | val testFolder = 43 | folder { 44 | location.copyRecursively(this.root) 45 | } 46 | log.debug("Test has been copied into {} and is ready to get executed", testFolder) 47 | test.description { 48 | test.configuration.pre_run_script.runCommandsIn(testFolder) 49 | val result = 50 | GradleRunner 51 | .create() 52 | .withProjectDir(testFolder.root) 53 | .withArguments(test.configuration.tasks + test.configuration.options) 54 | .withPluginClasspath() 55 | .run { if (test.expectation.failure.isEmpty()) build() else buildAndFail() } 56 | println(result.tasks) 57 | println(result.output) 58 | test.expectation.output_contains.forEach { 59 | result.output shouldContain it 60 | } 61 | test.expectation.success.forEach { 62 | result.outcomeOf(it) shouldBe TaskOutcome.SUCCESS 63 | } 64 | test.expectation.failure.forEach { 65 | result.outcomeOf(it) shouldBe TaskOutcome.FAILED 66 | } 67 | test.expectation.file_exists.forEach { 68 | val file = 69 | File("${testFolder.root.absolutePath}/${it.name}").apply { 70 | shouldExist() 71 | shouldBeAFile() 72 | } 73 | it.validate(file) 74 | } 75 | test.configuration.post_run_script.runCommandsIn(testFolder) 76 | } 77 | } 78 | }, 79 | ) { 80 | companion object { 81 | val log: Logger = LoggerFactory.getLogger(Tests::class.java) 82 | private val shells = listOf("sh", "bash", "zsh", "fish", "csh", "ksh") 83 | 84 | private fun BuildResult.outcomeOf(name: String) = 85 | requireNotNull(task(":$name")) { 86 | "Task $name was not present among the executed tasks" 87 | }.outcome 88 | 89 | private fun folder(closure: TemporaryFolder.() -> Unit) = 90 | TemporaryFolder().apply { 91 | create() 92 | closure() 93 | } 94 | 95 | private fun findShell(): String? { 96 | val paths = System.getenv("PATH").split(Regex(Pattern.quote(File.pathSeparator))) 97 | return shells.find { shell -> 98 | paths.any { path -> 99 | val executable = File(File(path), shell) 100 | executable.exists() && executable.canExecute() 101 | } 102 | } 103 | } 104 | 105 | private fun List.runCommandsIn(testFolder: TemporaryFolder) { 106 | findShell()?.also { shell -> 107 | forEach { postRun -> 108 | val hash = Hashing.sha512().hashString(postRun) 109 | val fileName = "script-$hash.sh" 110 | with(File(testFolder.root, fileName)) { 111 | writeText(postRun) 112 | setExecutable(true) 113 | } 114 | val process = 115 | ProcessBuilder() 116 | .directory(testFolder.root) 117 | .command(shell, fileName) 118 | .start() 119 | val finished = process.waitFor(10, TimeUnit.SECONDS) 120 | finished shouldBe true 121 | log.debug(process.inputStream.bufferedReader().use { it.readText() }) 122 | process.exitValue() shouldBe 0 123 | } 124 | } ?: log.warn( 125 | "No known Unix shell available on this system! Tests with scripts won't be executed", 126 | ) 127 | } 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /src/test/resources/org/danilopianini/gradle/git/hooks/test/test-issue-248/settings.gradle.kts: -------------------------------------------------------------------------------- 1 | import com.lordcodes.turtle.shellRun 2 | import org.gradle.kotlin.dsl.gitHooks 3 | 4 | buildscript { 5 | repositories { 6 | mavenCentral() 7 | } 8 | 9 | dependencies { 10 | classpath("com.lordcodes.turtle:turtle:0.8.0") 11 | } 12 | } 13 | 14 | plugins { 15 | id("org.danilopianini.gradle-pre-commit-git-hooks") 16 | } 17 | 18 | shellRun(rootProject.projectDir) { 19 | git.gitInit() 20 | } 21 | 22 | gitHooks { 23 | commitMsg { 24 | from("#!/bin/sh") { "true" } 25 | } 26 | createHooks() 27 | shellRun(rootProject.projectDir) { 28 | command("git", listOf("add", "settings.gradle.kts")) 29 | command("git", listOf("config", "user.name", "test user")) 30 | command("git", listOf("config", "user.email", "no-reply@github.com")) 31 | git.commit("this commit should be possible") 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/test/resources/org/danilopianini/gradle/git/hooks/test/test-issue-248/test.yaml: -------------------------------------------------------------------------------- 1 | tests: 2 | - description: "Empty msg hooks should be working" 3 | configuration: 4 | tasks: tasks 5 | expectation: 6 | success: 7 | - tasks 8 | file_exists: 9 | - name: .git/hooks/commit-msg 10 | content: | 11 | #!/bin/sh 12 | true 13 | 14 | permissions: X 15 | -------------------------------------------------------------------------------- /src/test/resources/org/danilopianini/gradle/git/hooks/test/test-issue-396/git-config: -------------------------------------------------------------------------------- 1 | gitdir: /datadisk/danysk/Downloads/org.danilopianini.gradle-pre-commit-git-hooks_repro/.git/worktrees/repro-detached 2 | -------------------------------------------------------------------------------- /src/test/resources/org/danilopianini/gradle/git/hooks/test/test-issue-396/settings.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.gradle.kotlin.dsl.gitHooks 2 | 3 | plugins { 4 | id("org.danilopianini.gradle-pre-commit-git-hooks") 5 | } 6 | 7 | gitHooks { 8 | val target = file("git-config") 9 | check(target.exists()) { 10 | "${target.absolutePath} does not exist" 11 | } 12 | val destination = file(".git") 13 | check(target.renameTo(destination)) { 14 | "could not rename ${target.absolutePath} to ${destination.absolutePath}" 15 | } 16 | commitMsg { 17 | conventionalCommits() 18 | } 19 | createHooks() 20 | } 21 | -------------------------------------------------------------------------------- /src/test/resources/org/danilopianini/gradle/git/hooks/test/test-issue-396/test.yaml: -------------------------------------------------------------------------------- 1 | tests: 2 | - description: "Hooks should be created" 3 | configuration: 4 | tasks: tasks 5 | options: --stacktrace 6 | pre_run_script: git config --global commit.gpgsign false 7 | expectation: 8 | success: 9 | - tasks 10 | file_exists: 11 | - name: .git 12 | findRegex: "gitdir: .*" 13 | -------------------------------------------------------------------------------- /src/test/resources/org/danilopianini/gradle/git/hooks/test/test-issue-88/commit_message: -------------------------------------------------------------------------------- 1 | fix(trigger): `use` trigger not work correctly 2 | 3 | - `predicateService` not injected 4 | - `Slot#offer` won't replace item 5 | - `ServerWorld` not in the `Cause` 6 | -------------------------------------------------------------------------------- /src/test/resources/org/danilopianini/gradle/git/hooks/test/test-issue-88/settings.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.gradle.kotlin.dsl.gitHooks 2 | 3 | plugins { 4 | id("org.danilopianini.gradle-pre-commit-git-hooks") 5 | } 6 | 7 | gitHooks { 8 | file(".git").mkdirs() 9 | commitMsg { 10 | conventionalCommits() 11 | } 12 | createHooks() 13 | } 14 | -------------------------------------------------------------------------------- /src/test/resources/org/danilopianini/gradle/git/hooks/test/test-issue-88/test.yaml: -------------------------------------------------------------------------------- 1 | tests: 2 | - description: "Commit message from https://github.com/DanySK/gradle-pre-commit-git-hooks/issues/88 should be valid" 3 | configuration: 4 | tasks: tasks 5 | pre_run_script: git config --global commit.gpgsign false 6 | post_run_script: | 7 | git init 8 | git config user.name "Gradle Test bot" 9 | git config user.email "noreply@danysk.github.io" 10 | touch foo 11 | git add foo 12 | git commit -F commit_message 13 | expectation: 14 | file_exists: 15 | - name: .git/hooks/commit-msg 16 | findRegex: .*list of Conventional Commits types$ 17 | permissions: X 18 | - name: .git/hooks/commit-msg 19 | findRegex: .*fix feat build chore ci docs perf refactor revert style test.* 20 | permissions: X 21 | -------------------------------------------------------------------------------- /src/test/resources/org/danilopianini/gradle/git/hooks/test/test0/settings.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | id("org.danilopianini.gradle-pre-commit-git-hooks") 3 | } 4 | 5 | gitHooks { 6 | file(".git").mkdirs() 7 | preCommit { tasks("ktlintCheck") } 8 | commitMsg { conventionalCommits() } 9 | createHooks() 10 | } 11 | -------------------------------------------------------------------------------- /src/test/resources/org/danilopianini/gradle/git/hooks/test/test0/test.yaml: -------------------------------------------------------------------------------- 1 | tests: 2 | - description: "Hooks should be created" 3 | configuration: 4 | tasks: tasks 5 | pre_run_script: git config --global commit.gpgsign false 6 | expectation: 7 | file_exists: 8 | - name: .git/hooks/commit-msg 9 | findRegex: .*list of Conventional Commits types$ 10 | permissions: X 11 | - name: .git/hooks/commit-msg 12 | findRegex: .*fix feat build chore ci docs perf refactor revert style test.* 13 | permissions: X 14 | - name: .git/hooks/pre-commit 15 | content: | 16 | #!/usr/bin/env bash 17 | set -e 18 | ./gradlew ktlintCheck 19 | set +e 20 | permissions: X 21 | - name: .git/hooks/pre-commit 22 | findRegex: ^#!/usr/bin/env bash$ 23 | permissions: X 24 | --------------------------------------------------------------------------------