├── .gitattributes ├── .github ├── dco.yml ├── dependabot.yml └── workflows │ ├── build-verification.yml │ └── combine-dependabot-prs.yml ├── .gitignore ├── .mvn ├── develocity-custom-user-data.groovy ├── develocity.xml ├── extensions.xml ├── jvm.config ├── maven.config └── wrapper │ └── maven-wrapper.properties ├── LICENSE ├── README.md ├── mvnw ├── mvnw.cmd ├── pom.xml ├── release ├── changes.md └── distribution │ └── NOTICE └── src ├── main ├── java │ └── com │ │ └── gradle │ │ ├── CiUtils.java │ │ ├── CommonCustomUserDataDevelocityListener.java │ │ ├── CommonCustomUserDataDevelocityLogger.java │ │ ├── CommonCustomUserDataGradleEnterpriseListener.java │ │ ├── CommonCustomUserDataListener.java │ │ ├── CustomBuildScanEnhancements.java │ │ ├── CustomConfigurationSpec.java │ │ ├── CustomDevelocityConfig.java │ │ ├── GroovyScriptUserData.java │ │ └── Utils.java └── resources │ └── META-INF │ └── plexus │ └── components.xml └── test └── java └── com └── gradle └── UtilsTest.java /.gitattributes: -------------------------------------------------------------------------------- 1 | *.bat text eol=crlf 2 | -------------------------------------------------------------------------------- /.github/dco.yml: -------------------------------------------------------------------------------- 1 | # Disable sign-off check for members of the Gradle GitHub organization 2 | require: 3 | members: false 4 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "maven" 4 | directory: "/" 5 | schedule: 6 | interval: "daily" 7 | time: "02:00" 8 | - package-ecosystem: "github-actions" 9 | directory: "/" 10 | schedule: 11 | interval: "daily" 12 | time: "02:00" 13 | -------------------------------------------------------------------------------- /.github/workflows/build-verification.yml: -------------------------------------------------------------------------------- 1 | name: Verify Build 2 | 3 | on: [ push, pull_request, workflow_dispatch ] 4 | 5 | jobs: 6 | verification: 7 | name: Verification 8 | runs-on: ubuntu-latest 9 | steps: 10 | - name: Checkout 11 | uses: actions/checkout@v4 12 | - name: Set up JDK 8 13 | uses: actions/setup-java@v4 14 | with: 15 | java-version: '8' 16 | distribution: 'temurin' 17 | - name: Build with Maven 18 | run: ./mvnw clean verify -B 19 | env: 20 | DEVELOCITY_ACCESS_KEY: ${{ secrets.DV_SOLUTIONS_ACCESS_KEY }} 21 | -------------------------------------------------------------------------------- /.github/workflows/combine-dependabot-prs.yml: -------------------------------------------------------------------------------- 1 | name: Combine Dependabot PRs 2 | 3 | on: 4 | schedule: 5 | - cron: '0 4 * * *' 6 | workflow_dispatch: 7 | 8 | # The minimum permissions required to run this Action 9 | permissions: 10 | contents: write 11 | pull-requests: write 12 | checks: read 13 | 14 | jobs: 15 | combine-dependabot-prs: 16 | if: github.repository == 'gradle/common-custom-user-data-maven-extension' 17 | runs-on: ubuntu-latest 18 | steps: 19 | - name: combine-dependabot-prs 20 | uses: github/combine-prs@v5.2.0 21 | with: 22 | branch_regex: ^(dependa|wrapper)bot\/.*$ 23 | github_token: ${{ secrets.GH_BOT_GITHUB_TOKEN }} 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | .gradle/ 3 | .tmp/ 4 | out/ 5 | build/ 6 | target/ 7 | *.DS_Store 8 | /dependency-reduced-pom.xml 9 | /.mvn/.develocity/develocity-workspace-id 10 | .vscode/ 11 | -------------------------------------------------------------------------------- /.mvn/develocity-custom-user-data.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | Example of extending the core functionality of the Common Custom User Data Maven Extension with a Groovy script. 3 | */ 4 | 5 | // Log a debug message to the build output 6 | log.debug('Evaluating my custom Groovy script') 7 | 8 | // Add a build scan tag with the project name 9 | buildScan.tag(project.name) 10 | 11 | // Add a custom value based on a property of the `Session` 12 | buildScan.value('parallel', session.parallel as String) 13 | 14 | // Enable local build caching 15 | buildCache.local.enabled = true 16 | -------------------------------------------------------------------------------- /.mvn/develocity.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | 7 | https://ge.solutions-team.gradle.com 8 | false 9 | 10 | 11 | #{isFalse(env['CI'])} 12 | 13 | 14 | 15 | 16 | 17 | 18 | #{{'0.0.0.0'}} 19 | 20 | 21 | 22 | 23 | true 24 | 25 | 26 | #{isTrue(env['CI']) and isTrue(env['DEVELOCITY_ACCESS_KEY'])} 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /.mvn/extensions.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | com.gradle 5 | develocity-maven-extension 6 | 2.0.1 7 | 8 | 9 | com.gradle 10 | common-custom-user-data-maven-extension 11 | 2.0.3 12 | 13 | 14 | -------------------------------------------------------------------------------- /.mvn/jvm.config: -------------------------------------------------------------------------------- 1 | -Duser.language=en -Duser.country=US -Dfile.encoding=UTF-8 -Xmx512M 2 | -------------------------------------------------------------------------------- /.mvn/maven.config: -------------------------------------------------------------------------------- 1 | -T0.5C 2 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | wrapperVersion=3.3.2 18 | distributionType=only-script 19 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.10/apache-maven-3.9.10-bin.zip 20 | -------------------------------------------------------------------------------- /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 2024 Gradle Inc. 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 | > _This repository is maintained by the Develocity Solutions team, as one of several publicly available repositories:_ 2 | > - _[Android Cache Fix Gradle Plugin][android-cache-fix-plugin]_ 3 | > - _[Common Custom User Data Gradle Plugin][ccud-gradle-plugin]_ 4 | > - _[Common Custom User Data Maven Extension][ccud-maven-extension] (this repository)_ 5 | > - _[Develocity Build Configuration Samples][develocity-build-config-samples]_ 6 | > - _[Develocity Build Validation Scripts][develocity-build-validation-scripts]_ 7 | > - _[Develocity Open Source Projects][develocity-oss-projects]_ 8 | > - _[Quarkus Build Caching Extension][quarkus-build-caching-extension]_ 9 | 10 | # Common Custom User Data Maven Extension 11 | 12 | [![Verify Build](https://github.com/gradle/common-custom-user-data-maven-extension/actions/workflows/build-verification.yml/badge.svg?branch=main)](https://github.com/gradle/common-custom-user-data-maven-extension/actions/workflows/build-verification.yml) 13 | [![Maven Central](https://img.shields.io/maven-central/v/com.gradle/common-custom-user-data-maven-extension)](https://search.maven.org/artifact/com.gradle/common-custom-user-data-maven-extension) 14 | [![Revved up by Develocity](https://img.shields.io/badge/Revved%20up%20by-Develocity-06A0CE?logo=Gradle&labelColor=02303A)](https://ge.solutions-team.gradle.com/scans) 15 | 16 | The Common Custom User Data Maven extension for Develocity enhances published build scans 17 | by adding a set of tags, links and custom values that have proven to be useful for many projects building with Develocity. 18 | 19 | You can leverage this extension for your project in one of two ways: 20 | 1. [Apply the published extension](#applying-the-published-extension) directly in your `.mvn/extensions.xml` and immediately benefit from enhanced build scans 21 | 2. Copy this repository and [develop a customized version of the extension](#developing-a-customized-version-of-the-extension) to standardize Develocity usage across multiple projects 22 | 23 | ## Applying the published extension 24 | 25 | The Common Custom User Data Maven extension is available in [Maven Central](https://search.maven.org/artifact/com.gradle/common-custom-user-data-maven-extension). This extension 26 | requires the [Develocity Maven extension](https://search.maven.org/artifact/com.gradle/develocity-maven-extension) to also be applied in your build in order to have 27 | an effect. 28 | 29 | In order for the Common Custom User Data Maven extension to become active, you need to register it in the `.mvn/extensions.xml` file in your root project. The `extensions.xml` file 30 | is the same file where you have already declared the Develocity Maven extension. 31 | 32 | See [here](.mvn/extensions.xml) for an example. 33 | 34 | ### Version compatibility 35 | 36 | This table details the version compatibility of the Common Custom User Data Maven extension with the Develocity Maven extension. 37 | 38 | | Common Custom User Data Maven extension versions | Develocity Maven extension versions | 39 | | ------------------------------------------------ | ------------------------------------------ | 40 | | `1.8+` | `1.11+` | 41 | | `1.7` - `1.7.3` | `1.10.1+` | 42 | | `1.3` - `1.6` | `1.6.5+` | 43 | | `1.0` - `1.2` | `1.0+` | 44 | 45 | The above chart captures the minimum compatible versions. For the best experience with the Develocity Maven extension 1.21 or higher, we recommend using the Common Custom User Data Maven extension 2.0 or higher. 46 | 47 | ## Captured data 48 | 49 | The additional tags, links and custom values captured by this extension include: 50 | - A tag representing the operating system 51 | - A tag representing how the build was invoked, be that from your IDE (IDEA, Eclipse) or from the command-line 52 | - A tag representing builds run on CI, together with a set of tags, links and custom values specific to the CI server running the build 53 | - For Git repositories, information on the commit id, branch name, status, and whether the checkout is dirty or not 54 | 55 | See [CustomBuildScanEnhancements.java](./src/main/java/com/gradle/CustomBuildScanEnhancements.java) for details on what data is 56 | captured and under which conditions. 57 | 58 | ## Capturing additional tags, links and values in your build scans 59 | 60 | You can apply additional configuration beyond what is contributed by the Common Custom User Data Maven extension by default. The additional configuration happens in a specific 61 | Groovy script. This is a good intermediate step before creating your own extension. 62 | 63 | The Common Custom User Data Maven extension checks for a `.mvn/develocity-custom-user-data.groovy` or `.mvn/gradle-enterprise-custom-user-data.groovy` Groovy script in your root project. If the file exists, it evaluates 64 | the script with the following bindings: 65 | 66 | - `develocity/gradleEnterprise` (type: [DevelocityAdapter](https://github.com/gradle/develocity-agent-adapters/blob/main/develocity-maven-extension-adapters/src/compatibilityApi/java/com/gradle/develocity/agent/maven/adapters/DevelocityAdapter.java)): _configure Develocity_ 67 | - `buildScan` (type: [BuildScanApiAdapter](https://github.com/gradle/develocity-agent-adapters/blob/main/develocity-maven-extension-adapters/src/compatibilityApi/java/com/gradle/develocity/agent/maven/adapters/BuildScanApiAdapter.java)): _configure build scan publishing and enhance build scans_ 68 | - `buildCache` (type: [BuildCacheApiAdapter](https://github.com/gradle/develocity-agent-adapters/blob/main/develocity-maven-extension-adapters/src/compatibilityApi/java/com/gradle/develocity/agent/maven/adapters/BuildCacheApiAdapter.java)): _configure build cache_ 69 | - `log` (type: [`Logger`](http://www.slf4j.org/apidocs/org/slf4j/Logger.html)): _write to the build log_ 70 | - `project` (type: [`MavenProject`](https://maven.apache.org/ref/current/maven-core/apidocs/org/apache/maven/project/MavenProject.html)): _the top-level Maven project_ 71 | - `session` (type: [`MavenSession`](https://maven.apache.org/ref/current/maven-core/apidocs/org/apache/maven/execution/MavenSession.html)): _the Maven session_ 72 | 73 | See [here](.mvn/develocity-custom-user-data.groovy) for an example. 74 | 75 | ## Developing a customized version of the extension 76 | 77 | For more flexibility, we recommend creating a copy of this repository so that you may develop a customized version of the extension and publish it internally for your projects to consume. 78 | 79 | This approach has a number of benefits: 80 | - Tailor the build scan enhancements to exactly the set of tags, links and custom values you require 81 | - Standardize the configuration for connecting to Develocity and the remote build cache in your organization, removing the need for each project to specify this configuration 82 | 83 | If your customized extension provides all required Develocity configuration, then a consumer project will get all the benefits of Develocity simply by applying the extension. The 84 | project sources provide a good template to get started with your own extension. 85 | 86 | Refer to the [Javadoc](https://docs.gradle.com/enterprise/maven-extension/api/) for more details on the key types available for use. 87 | 88 | ## Changelog 89 | 90 | Refer to the [release history](https://github.com/gradle/common-custom-user-data-maven-extension/releases) to see detailed changes on the versions. 91 | 92 | ## Breaking API changes 93 | 94 | When updating to the Common Custom User Data Maven extension 2.0, please take care of the following. 95 | 96 | 1. Rename the `.mvn/gradle-enterprise-custom-user-data.groovy` to `.mvn/develocity-custom-user-data.groovy`. 97 | 2. Use `BuildScanApiAdapter` instead of `BuildScanApi`. See the example below: 98 | 99 | `gradle-enterprise-custom-user-data.groovy` 100 | ``` 101 | import com.gradle.maven.extension.api.scan.BuildScanApi 102 | 103 | buildScan.executeOnce('top-level-project') { BuildScanApi buildScanApi -> } 104 | ``` 105 | `develocity-custom-user-data.groovy` 106 | ``` 107 | import com.gradle.develocity.agent.maven.adapters.BuildScanApiAdapter 108 | 109 | buildScan.executeOnce('top-level-project') { BuildScanApiAdapter buildScanApi -> } 110 | ``` 111 | 112 | ## Learn more 113 | 114 | Visit our website to learn more about [Develocity][develocity]. 115 | 116 | ## License 117 | 118 | The Develocity Common Custom User Data Maven extension is open-source software released under the [Apache 2.0 License][apache-license]. 119 | 120 | [android-cache-fix-plugin]: https://github.com/gradle/android-cache-fix-gradle-plugin 121 | [ccud-gradle-plugin]: https://github.com/gradle/common-custom-user-data-gradle-plugin 122 | [ccud-maven-extension]: https://github.com/gradle/common-custom-user-data-maven-extension 123 | [develocity-build-config-samples]: https://github.com/gradle/develocity-build-config-samples 124 | [develocity-build-validation-scripts]: https://github.com/gradle/develocity-build-validation-scripts 125 | [develocity-oss-projects]: https://github.com/gradle/develocity-oss-projects 126 | [quarkus-build-caching-extension]: https://github.com/gradle/quarkus-build-caching-extension 127 | [develocity]: https://gradle.com/develocity 128 | [apache-license]: https://www.apache.org/licenses/LICENSE-2.0.html 129 | -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Apache Maven Wrapper startup batch script, version 3.3.2 23 | # 24 | # Optional ENV vars 25 | # ----------------- 26 | # JAVA_HOME - location of a JDK home dir, required when download maven via java source 27 | # MVNW_REPOURL - repo url base for downloading maven distribution 28 | # MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven 29 | # MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output 30 | # ---------------------------------------------------------------------------- 31 | 32 | set -euf 33 | [ "${MVNW_VERBOSE-}" != debug ] || set -x 34 | 35 | # OS specific support. 36 | native_path() { printf %s\\n "$1"; } 37 | case "$(uname)" in 38 | CYGWIN* | MINGW*) 39 | [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" 40 | native_path() { cygpath --path --windows "$1"; } 41 | ;; 42 | esac 43 | 44 | # set JAVACMD and JAVACCMD 45 | set_java_home() { 46 | # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched 47 | if [ -n "${JAVA_HOME-}" ]; then 48 | if [ -x "$JAVA_HOME/jre/sh/java" ]; then 49 | # IBM's JDK on AIX uses strange locations for the executables 50 | JAVACMD="$JAVA_HOME/jre/sh/java" 51 | JAVACCMD="$JAVA_HOME/jre/sh/javac" 52 | else 53 | JAVACMD="$JAVA_HOME/bin/java" 54 | JAVACCMD="$JAVA_HOME/bin/javac" 55 | 56 | if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then 57 | echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 58 | echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 59 | return 1 60 | fi 61 | fi 62 | else 63 | JAVACMD="$( 64 | 'set' +e 65 | 'unset' -f command 2>/dev/null 66 | 'command' -v java 67 | )" || : 68 | JAVACCMD="$( 69 | 'set' +e 70 | 'unset' -f command 2>/dev/null 71 | 'command' -v javac 72 | )" || : 73 | 74 | if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then 75 | echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 76 | return 1 77 | fi 78 | fi 79 | } 80 | 81 | # hash string like Java String::hashCode 82 | hash_string() { 83 | str="${1:-}" h=0 84 | while [ -n "$str" ]; do 85 | char="${str%"${str#?}"}" 86 | h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) 87 | str="${str#?}" 88 | done 89 | printf %x\\n $h 90 | } 91 | 92 | verbose() { :; } 93 | [ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } 94 | 95 | die() { 96 | printf %s\\n "$1" >&2 97 | exit 1 98 | } 99 | 100 | trim() { 101 | # MWRAPPER-139: 102 | # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. 103 | # Needed for removing poorly interpreted newline sequences when running in more 104 | # exotic environments such as mingw bash on Windows. 105 | printf "%s" "${1}" | tr -d '[:space:]' 106 | } 107 | 108 | # parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties 109 | while IFS="=" read -r key value; do 110 | case "${key-}" in 111 | distributionUrl) distributionUrl=$(trim "${value-}") ;; 112 | distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; 113 | esac 114 | done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" 115 | [ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" 116 | 117 | case "${distributionUrl##*/}" in 118 | maven-mvnd-*bin.*) 119 | MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ 120 | case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in 121 | *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; 122 | :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; 123 | :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; 124 | :Linux*x86_64*) distributionPlatform=linux-amd64 ;; 125 | *) 126 | echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 127 | distributionPlatform=linux-amd64 128 | ;; 129 | esac 130 | distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" 131 | ;; 132 | maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; 133 | *) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; 134 | esac 135 | 136 | # apply MVNW_REPOURL and calculate MAVEN_HOME 137 | # maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ 138 | [ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" 139 | distributionUrlName="${distributionUrl##*/}" 140 | distributionUrlNameMain="${distributionUrlName%.*}" 141 | distributionUrlNameMain="${distributionUrlNameMain%-bin}" 142 | MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" 143 | MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" 144 | 145 | exec_maven() { 146 | unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : 147 | exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" 148 | } 149 | 150 | if [ -d "$MAVEN_HOME" ]; then 151 | verbose "found existing MAVEN_HOME at $MAVEN_HOME" 152 | exec_maven "$@" 153 | fi 154 | 155 | case "${distributionUrl-}" in 156 | *?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; 157 | *) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; 158 | esac 159 | 160 | # prepare tmp dir 161 | if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then 162 | clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } 163 | trap clean HUP INT TERM EXIT 164 | else 165 | die "cannot create temp dir" 166 | fi 167 | 168 | mkdir -p -- "${MAVEN_HOME%/*}" 169 | 170 | # Download and Install Apache Maven 171 | verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." 172 | verbose "Downloading from: $distributionUrl" 173 | verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" 174 | 175 | # select .zip or .tar.gz 176 | if ! command -v unzip >/dev/null; then 177 | distributionUrl="${distributionUrl%.zip}.tar.gz" 178 | distributionUrlName="${distributionUrl##*/}" 179 | fi 180 | 181 | # verbose opt 182 | __MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' 183 | [ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v 184 | 185 | # normalize http auth 186 | case "${MVNW_PASSWORD:+has-password}" in 187 | '') MVNW_USERNAME='' MVNW_PASSWORD='' ;; 188 | has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; 189 | esac 190 | 191 | if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then 192 | verbose "Found wget ... using wget" 193 | wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" 194 | elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then 195 | verbose "Found curl ... using curl" 196 | curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" 197 | elif set_java_home; then 198 | verbose "Falling back to use Java to download" 199 | javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" 200 | targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" 201 | cat >"$javaSource" <<-END 202 | public class Downloader extends java.net.Authenticator 203 | { 204 | protected java.net.PasswordAuthentication getPasswordAuthentication() 205 | { 206 | return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); 207 | } 208 | public static void main( String[] args ) throws Exception 209 | { 210 | setDefault( new Downloader() ); 211 | java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); 212 | } 213 | } 214 | END 215 | # For Cygwin/MinGW, switch paths to Windows format before running javac and java 216 | verbose " - Compiling Downloader.java ..." 217 | "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" 218 | verbose " - Running Downloader.java ..." 219 | "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" 220 | fi 221 | 222 | # If specified, validate the SHA-256 sum of the Maven distribution zip file 223 | if [ -n "${distributionSha256Sum-}" ]; then 224 | distributionSha256Result=false 225 | if [ "$MVN_CMD" = mvnd.sh ]; then 226 | echo "Checksum validation is not supported for maven-mvnd." >&2 227 | echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 228 | exit 1 229 | elif command -v sha256sum >/dev/null; then 230 | if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then 231 | distributionSha256Result=true 232 | fi 233 | elif command -v shasum >/dev/null; then 234 | if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then 235 | distributionSha256Result=true 236 | fi 237 | else 238 | echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 239 | echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 240 | exit 1 241 | fi 242 | if [ $distributionSha256Result = false ]; then 243 | echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 244 | echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 245 | exit 1 246 | fi 247 | fi 248 | 249 | # unzip and move 250 | if command -v unzip >/dev/null; then 251 | unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" 252 | else 253 | tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" 254 | fi 255 | printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" 256 | mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" 257 | 258 | clean || : 259 | exec_maven "$@" 260 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | <# : batch portion 2 | @REM ---------------------------------------------------------------------------- 3 | @REM Licensed to the Apache Software Foundation (ASF) under one 4 | @REM or more contributor license agreements. See the NOTICE file 5 | @REM distributed with this work for additional information 6 | @REM regarding copyright ownership. The ASF licenses this file 7 | @REM to you under the Apache License, Version 2.0 (the 8 | @REM "License"); you may not use this file except in compliance 9 | @REM with the License. You may obtain a copy of the License at 10 | @REM 11 | @REM http://www.apache.org/licenses/LICENSE-2.0 12 | @REM 13 | @REM Unless required by applicable law or agreed to in writing, 14 | @REM software distributed under the License is distributed on an 15 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | @REM KIND, either express or implied. See the License for the 17 | @REM specific language governing permissions and limitations 18 | @REM under the License. 19 | @REM ---------------------------------------------------------------------------- 20 | 21 | @REM ---------------------------------------------------------------------------- 22 | @REM Apache Maven Wrapper startup batch script, version 3.3.2 23 | @REM 24 | @REM Optional ENV vars 25 | @REM MVNW_REPOURL - repo url base for downloading maven distribution 26 | @REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven 27 | @REM MVNW_VERBOSE - true: enable verbose log; others: silence the output 28 | @REM ---------------------------------------------------------------------------- 29 | 30 | @IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) 31 | @SET __MVNW_CMD__= 32 | @SET __MVNW_ERROR__= 33 | @SET __MVNW_PSMODULEP_SAVE=%PSModulePath% 34 | @SET PSModulePath= 35 | @FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( 36 | IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) 37 | ) 38 | @SET PSModulePath=%__MVNW_PSMODULEP_SAVE% 39 | @SET __MVNW_PSMODULEP_SAVE= 40 | @SET __MVNW_ARG0_NAME__= 41 | @SET MVNW_USERNAME= 42 | @SET MVNW_PASSWORD= 43 | @IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) 44 | @echo Cannot start maven from wrapper >&2 && exit /b 1 45 | @GOTO :EOF 46 | : end batch / begin powershell #> 47 | 48 | $ErrorActionPreference = "Stop" 49 | if ($env:MVNW_VERBOSE -eq "true") { 50 | $VerbosePreference = "Continue" 51 | } 52 | 53 | # calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties 54 | $distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl 55 | if (!$distributionUrl) { 56 | Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" 57 | } 58 | 59 | switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { 60 | "maven-mvnd-*" { 61 | $USE_MVND = $true 62 | $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" 63 | $MVN_CMD = "mvnd.cmd" 64 | break 65 | } 66 | default { 67 | $USE_MVND = $false 68 | $MVN_CMD = $script -replace '^mvnw','mvn' 69 | break 70 | } 71 | } 72 | 73 | # apply MVNW_REPOURL and calculate MAVEN_HOME 74 | # maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ 75 | if ($env:MVNW_REPOURL) { 76 | $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } 77 | $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" 78 | } 79 | $distributionUrlName = $distributionUrl -replace '^.*/','' 80 | $distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' 81 | $MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" 82 | if ($env:MAVEN_USER_HOME) { 83 | $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" 84 | } 85 | $MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' 86 | $MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" 87 | 88 | if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { 89 | Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" 90 | Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" 91 | exit $? 92 | } 93 | 94 | if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { 95 | Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" 96 | } 97 | 98 | # prepare tmp dir 99 | $TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile 100 | $TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" 101 | $TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null 102 | trap { 103 | if ($TMP_DOWNLOAD_DIR.Exists) { 104 | try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } 105 | catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } 106 | } 107 | } 108 | 109 | New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null 110 | 111 | # Download and Install Apache Maven 112 | Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." 113 | Write-Verbose "Downloading from: $distributionUrl" 114 | Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" 115 | 116 | $webclient = New-Object System.Net.WebClient 117 | if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { 118 | $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) 119 | } 120 | [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 121 | $webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null 122 | 123 | # If specified, validate the SHA-256 sum of the Maven distribution zip file 124 | $distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum 125 | if ($distributionSha256Sum) { 126 | if ($USE_MVND) { 127 | Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." 128 | } 129 | Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash 130 | if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { 131 | Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." 132 | } 133 | } 134 | 135 | # unzip and move 136 | Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null 137 | Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null 138 | try { 139 | Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null 140 | } catch { 141 | if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { 142 | Write-Error "fail to move MAVEN_HOME" 143 | } 144 | } finally { 145 | try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } 146 | catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } 147 | } 148 | 149 | Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" 150 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | com.gradle 5 | common-custom-user-data-maven-extension 6 | 2.0.4-SNAPSHOT 7 | jar 8 | 9 | Develocity Common Custom User Data Maven Extension 10 | A Maven extension to capture common custom user data used for Maven Build Scans in Develocity 11 | https://github.com/gradle/common-custom-user-data-maven-extension 12 | 13 | 14 | UTF-8 15 | 16 | 17 | 18 | scm:git:https://github.com/gradle/common-custom-user-data-maven-extension.git 19 | https://github.com/gradle/common-custom-user-data-maven-extension 20 | HEAD 21 | 22 | 23 | 24 | 25 | Apache-2.0 26 | https://www.apache.org/licenses/LICENSE-2.0.txt 27 | 28 | 29 | 30 | 31 | 32 | Documentation 33 | https://docs.gradle.com 34 | 35 | 36 | 37 | 38 | 39 | The Gradle team 40 | Gradle Inc. 41 | https://gradle.com 42 | 43 | 44 | 45 | 46 | 47 | org.apache.maven 48 | maven-core 49 | 3.9.10 50 | provided 51 | 52 | 53 | 54 | com.gradle 55 | gradle-enterprise-maven-extension 56 | 1.20.1 57 | provided 58 | 59 | 60 | 61 | com.gradle 62 | develocity-maven-extension 63 | 2.0.1 64 | provided 65 | 66 | 67 | com.gradle 68 | develocity-maven-extension-adapters 69 | 1.0 70 | 71 | 72 | org.apache.groovy 73 | groovy 74 | 4.0.27 75 | 76 | 77 | org.apache.ivy 78 | ivy 79 | 2.5.3 80 | 81 | 82 | org.junit.jupiter 83 | junit-jupiter 84 | 5.13.0 85 | test 86 | 87 | 88 | 89 | 90 | 91 | 92 | org.apache.maven.plugins 93 | maven-compiler-plugin 94 | 3.14.0 95 | 96 | 1.8 97 | 1.8 98 | 99 | 100 | org.eclipse.sisu 101 | org.eclipse.sisu.inject 102 | 0.3.5 103 | 104 | 105 | 106 | 107 | 108 | org.apache.maven.plugins 109 | maven-surefire-plugin 110 | 3.5.3 111 | 112 | 113 | org.apache.maven.plugins 114 | maven-shade-plugin 115 | 3.6.0 116 | 117 | 118 | 119 | com.gradle:develocity-maven-extension-adapters 120 | 121 | META-INF/MANIFEST.MF 122 | 123 | 124 | 125 | org.codehaus.groovy:groovy 126 | 127 | META-INF/LICENSE 128 | META-INF/MANIFEST.MF 129 | META-INF/NOTICE 130 | 131 | 132 | 133 | org.apache.ivy:ivy 134 | 135 | META-INF/LICENSE 136 | META-INF/MANIFEST.MF 137 | META-INF/NOTICE 138 | 139 | 140 | 141 | 142 | 143 | 144 | package 145 | 146 | shade 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | ${project.basedir}/src/main/resources 155 | 156 | 157 | ${project.basedir}/release/distribution 158 | 159 | 160 | ${project.basedir} 161 | 162 | LICENSE 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | release 171 | 172 | 173 | 174 | org.apache.maven.plugins 175 | maven-release-plugin 176 | 3.1.1 177 | 178 | -Dscan=false 179 | 180 | 181 | 182 | org.apache.maven.plugins 183 | maven-source-plugin 184 | 3.3.1 185 | 186 | 187 | attach-sources 188 | 189 | jar-no-fork 190 | 191 | 192 | 193 | 194 | 195 | org.apache.maven.plugins 196 | maven-javadoc-plugin 197 | 3.11.2 198 | 199 | 200 | attach-javadocs 201 | 202 | jar 203 | 204 | 205 | 206 | 207 | 8 208 | 209 | 210 | 211 | org.apache.maven.plugins 212 | maven-site-plugin 213 | 3.21.0 214 | 215 | true 216 | true 217 | 218 | 219 | 220 | org.simplify4u.plugins 221 | sign-maven-plugin 222 | 1.1.0 223 | 224 | 225 | sign 226 | 227 | sign 228 | 229 | 230 | 231 | 232 | false 233 | 234 | 235 | 236 | org.sonatype.central 237 | central-publishing-maven-plugin 238 | 0.7.0 239 | true 240 | 241 | ossrh 242 | true 243 | published 244 | Common Custom User Data Maven Extension 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | -------------------------------------------------------------------------------- /release/changes.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gradle/common-custom-user-data-maven-extension/eca2ea3ec6666a0186210b6b240f0a2b039e0a0f/release/changes.md -------------------------------------------------------------------------------- /release/distribution/NOTICE: -------------------------------------------------------------------------------- 1 | The following copyright statements and licenses apply to various third party open 2 | source software packages (or portions thereof) that are distributed with 3 | this content. 4 | 5 | TABLE OF CONTENTS 6 | ================= 7 | 8 | The following is a listing of the open source components detailed in this 9 | document. This list is provided for your convenience; please read further if 10 | you wish to review the copyright notice(s) and the full text of the license 11 | associated with each component. 12 | 13 | 14 | **SECTION 1: Apache License, V2.0** 15 | * Develocity Maven Extension Adapters 16 | * com.gradle:develocity-maven-extension-adapters 17 | * Groovy 18 | * org.codehaus.groovy:groovy 19 | * Ivy 20 | * org.apache.ivy:ivy 21 | 22 | SECTION 1: Apache License, V2.0 23 | ================================ 24 | 25 | Develocity Maven Extension Adapters 26 | ----------------------------------- 27 | 28 | Copyright 2024 Gradle, Inc. 29 | 30 | Licensed under the Apache License, Version 2.0 (the "License"); 31 | you may not use this file except in compliance with the License. 32 | You may obtain a copy of the License at 33 | 34 | http://www.apache.org/licenses/LICENSE-2.0 35 | 36 | Unless required by applicable law or agreed to in writing, software 37 | distributed under the License is distributed on an "AS IS" BASIS, 38 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 39 | See the License for the specific language governing permissions and 40 | limitations under the License. 41 | 42 | Groovy 43 | ------ 44 | 45 | Copyright 2023 The Apache Software Foundation 46 | 47 | Licensed under the Apache License, Version 2.0 (the "License"); 48 | you may not use this file except in compliance with the License. 49 | You may obtain a copy of the License at 50 | 51 | http://www.apache.org/licenses/LICENSE-2.0 52 | 53 | Unless required by applicable law or agreed to in writing, software 54 | distributed under the License is distributed on an "AS IS" BASIS, 55 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 56 | See the License for the specific language governing permissions and 57 | limitations under the License. 58 | 59 | Ivy 60 | --- 61 | 62 | Copyright 2023 The Apache Software Foundation 63 | 64 | Licensed under the Apache License, Version 2.0 (the "License"); 65 | you may not use this file except in compliance with the License. 66 | You may obtain a copy of the License at 67 | 68 | http://www.apache.org/licenses/LICENSE-2.0 69 | 70 | Unless required by applicable law or agreed to in writing, software 71 | distributed under the License is distributed on an "AS IS" BASIS, 72 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 73 | See the License for the specific language governing permissions and 74 | limitations under the License. 75 | -------------------------------------------------------------------------------- /src/main/java/com/gradle/CiUtils.java: -------------------------------------------------------------------------------- 1 | package com.gradle; 2 | 3 | final class CiUtils { 4 | 5 | private CiUtils() { 6 | } 7 | 8 | static boolean isCi() { 9 | return isGenericCI() 10 | || isJenkins() 11 | || isHudson() 12 | || isTeamCity() 13 | || isCircleCI() 14 | || isBamboo() 15 | || isGitHubActions() 16 | || isGitLab() 17 | || isTravis() 18 | || isBitrise() 19 | || isGoCD() 20 | || isAzurePipelines() 21 | || isBuildkite(); 22 | } 23 | 24 | static boolean isGenericCI() { 25 | return Utils.envVariable("CI").isPresent() 26 | || Utils.sysProperty("CI").isPresent(); 27 | } 28 | 29 | static boolean isJenkins() { 30 | return Utils.envVariable("JENKINS_URL").isPresent(); 31 | } 32 | 33 | static boolean isHudson() { 34 | return Utils.envVariable("HUDSON_URL").isPresent(); 35 | } 36 | 37 | static boolean isTeamCity() { 38 | return Utils.envVariable("TEAMCITY_VERSION").isPresent(); 39 | } 40 | 41 | static boolean isCircleCI() { 42 | return Utils.envVariable("CIRCLE_BUILD_URL").isPresent(); 43 | } 44 | 45 | static boolean isBamboo() { 46 | return Utils.envVariable("bamboo_resultsUrl").isPresent(); 47 | } 48 | 49 | static boolean isGitHubActions() { 50 | return Utils.envVariable("GITHUB_ACTIONS").isPresent(); 51 | } 52 | 53 | static boolean isGitLab() { 54 | return Utils.envVariable("GITLAB_CI").isPresent(); 55 | } 56 | 57 | static boolean isTravis() { 58 | return Utils.envVariable("TRAVIS_JOB_ID").isPresent(); 59 | } 60 | 61 | static boolean isBitrise() { 62 | return Utils.envVariable("BITRISE_BUILD_URL").isPresent(); 63 | } 64 | 65 | static boolean isGoCD() { 66 | return Utils.envVariable("GO_SERVER_URL").isPresent(); 67 | } 68 | 69 | static boolean isAzurePipelines() { 70 | return Utils.envVariable("TF_BUILD").isPresent(); 71 | } 72 | 73 | static boolean isBuildkite() { 74 | return Utils.envVariable("BUILDKITE").isPresent(); 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/com/gradle/CommonCustomUserDataDevelocityListener.java: -------------------------------------------------------------------------------- 1 | package com.gradle; 2 | 3 | import com.gradle.develocity.agent.maven.adapters.develocity.DevelocityApiAdapter; 4 | import com.gradle.develocity.agent.maven.api.DevelocityApi; 5 | import com.gradle.develocity.agent.maven.api.DevelocityListener; 6 | import org.apache.maven.MavenExecutionException; 7 | import org.apache.maven.execution.MavenSession; 8 | 9 | public final class CommonCustomUserDataDevelocityListener extends CommonCustomUserDataListener implements DevelocityListener { 10 | 11 | @Override 12 | public void configure(DevelocityApi api, MavenSession session) throws MavenExecutionException { 13 | super.configure(new DevelocityApiAdapter(api), session, CustomConfigurationSpec.DEVELOCITY); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/gradle/CommonCustomUserDataDevelocityLogger.java: -------------------------------------------------------------------------------- 1 | package com.gradle; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | 6 | public final class CommonCustomUserDataDevelocityLogger { 7 | 8 | public static final Logger LOGGER = LoggerFactory.getLogger(CommonCustomUserDataDevelocityLogger.class); 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/gradle/CommonCustomUserDataGradleEnterpriseListener.java: -------------------------------------------------------------------------------- 1 | package com.gradle; 2 | 3 | import com.gradle.develocity.agent.maven.adapters.enterprise.GradleEnterpriseApiAdapter; 4 | import com.gradle.maven.extension.api.GradleEnterpriseApi; 5 | import com.gradle.maven.extension.api.GradleEnterpriseListener; 6 | import org.apache.maven.MavenExecutionException; 7 | import org.apache.maven.execution.MavenSession; 8 | 9 | public final class CommonCustomUserDataGradleEnterpriseListener extends CommonCustomUserDataListener implements GradleEnterpriseListener { 10 | 11 | @Override 12 | public void configure(GradleEnterpriseApi api, MavenSession session) throws MavenExecutionException { 13 | super.configure(new GradleEnterpriseApiAdapter(api), session, CustomConfigurationSpec.GRADLE_ENTERPRISE); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/gradle/CommonCustomUserDataListener.java: -------------------------------------------------------------------------------- 1 | package com.gradle; 2 | 3 | import com.gradle.develocity.agent.maven.adapters.BuildCacheApiAdapter; 4 | import com.gradle.develocity.agent.maven.adapters.BuildScanApiAdapter; 5 | import com.gradle.develocity.agent.maven.adapters.DevelocityAdapter; 6 | import org.apache.maven.MavenExecutionException; 7 | import org.apache.maven.execution.MavenSession; 8 | 9 | import static com.gradle.CommonCustomUserDataDevelocityLogger.LOGGER; 10 | 11 | abstract class CommonCustomUserDataListener { 12 | 13 | protected void configure(DevelocityAdapter api, MavenSession session, CustomConfigurationSpec customConfigurationSpec) throws MavenExecutionException { 14 | LOGGER.debug("Executing extension: " + getClass().getSimpleName()); 15 | CustomDevelocityConfig customDevelocityConfig = new CustomDevelocityConfig(); 16 | 17 | LOGGER.debug("Configuring {}", customConfigurationSpec.displayName); 18 | customDevelocityConfig.configureDevelocity(api); 19 | LOGGER.debug("Finished configuring {}", customConfigurationSpec.displayName); 20 | 21 | LOGGER.debug("Configuring build scan publishing and applying build scan enhancements"); 22 | BuildScanApiAdapter buildScan = api.getBuildScan(); 23 | customDevelocityConfig.configureBuildScanPublishing(buildScan); 24 | new CustomBuildScanEnhancements(buildScan, session).apply(); 25 | LOGGER.debug("Finished configuring build scan publishing and applying build scan enhancements"); 26 | 27 | LOGGER.debug("Configuring build cache"); 28 | BuildCacheApiAdapter buildCache = api.getBuildCache(); 29 | customDevelocityConfig.configureBuildCache(buildCache); 30 | LOGGER.debug("Finished configuring build cache"); 31 | 32 | GroovyScriptUserData.evaluate(session, api, LOGGER, customConfigurationSpec); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/gradle/CustomBuildScanEnhancements.java: -------------------------------------------------------------------------------- 1 | package com.gradle; 2 | 3 | import com.gradle.develocity.agent.maven.adapters.BuildScanApiAdapter; 4 | import org.apache.maven.execution.MavenSession; 5 | 6 | import java.net.URI; 7 | import java.util.AbstractMap; 8 | import java.util.Arrays; 9 | import java.util.Comparator; 10 | import java.util.HashMap; 11 | import java.util.LinkedHashMap; 12 | import java.util.Map; 13 | import java.util.Optional; 14 | import java.util.Properties; 15 | import java.util.function.Consumer; 16 | import java.util.function.Function; 17 | import java.util.function.Supplier; 18 | import java.util.stream.Stream; 19 | 20 | import static com.gradle.CiUtils.isAzurePipelines; 21 | import static com.gradle.CiUtils.isBamboo; 22 | import static com.gradle.CiUtils.isBitrise; 23 | import static com.gradle.CiUtils.isBuildkite; 24 | import static com.gradle.CiUtils.isCi; 25 | import static com.gradle.CiUtils.isCircleCI; 26 | import static com.gradle.CiUtils.isGitHubActions; 27 | import static com.gradle.CiUtils.isGitLab; 28 | import static com.gradle.CiUtils.isGoCD; 29 | import static com.gradle.CiUtils.isHudson; 30 | import static com.gradle.CiUtils.isJenkins; 31 | import static com.gradle.CiUtils.isTeamCity; 32 | import static com.gradle.CiUtils.isTravis; 33 | import static com.gradle.Utils.appendIfMissing; 34 | import static com.gradle.Utils.envVariable; 35 | import static com.gradle.Utils.execAndCheckSuccess; 36 | import static com.gradle.Utils.execAndGetStdOut; 37 | import static com.gradle.Utils.isNotEmpty; 38 | import static com.gradle.Utils.projectProperty; 39 | import static com.gradle.Utils.readPropertiesFile; 40 | import static com.gradle.Utils.redactUserInfo; 41 | import static com.gradle.Utils.sysProperty; 42 | import static com.gradle.Utils.toWebRepoUri; 43 | import static com.gradle.Utils.urlEncode; 44 | 45 | /** 46 | * Adds a standard set of useful tags, links and custom values to all build scans published. 47 | */ 48 | final class CustomBuildScanEnhancements { 49 | 50 | private static final String SYSTEM_PROP_IDEA_VENDOR_NAME = "idea.vendor.name"; 51 | private static final String SYSTEM_PROP_IDEA_VERSION = "idea.version"; 52 | private static final String SYSTEM_PROP_ECLIPSE_BUILD_ID = "eclipse.buildId"; 53 | private static final String SYSTEM_PROP_IDEA_SYNC_ACTIVE = "idea.sync.active"; 54 | private static final String ENV_VAR_VSCODE_PID = "VSCODE_PID"; 55 | private static final String ENV_VAR_VSCODE_INJECTION = "VSCODE_INJECTION"; 56 | 57 | private final BuildScanApiAdapter buildScan; 58 | private final MavenSession mavenSession; 59 | 60 | CustomBuildScanEnhancements(BuildScanApiAdapter buildScan, MavenSession mavenSession) { 61 | this.buildScan = buildScan; 62 | this.mavenSession = mavenSession; 63 | } 64 | 65 | void apply() { 66 | captureOs(); 67 | captureIde(); 68 | captureCiOrLocal(); 69 | captureCiMetadata(); 70 | captureGitMetadata(); 71 | captureSkipTestsFlags(); 72 | } 73 | 74 | private void captureOs() { 75 | sysProperty("os.name").ifPresent(buildScan::tag); 76 | } 77 | 78 | private void captureIde() { 79 | if (!isCi()) { 80 | Map> ideProperties = new HashMap<>(); 81 | ideProperties.put(SYSTEM_PROP_IDEA_VENDOR_NAME, sysProperty(SYSTEM_PROP_IDEA_VENDOR_NAME)); 82 | ideProperties.put(SYSTEM_PROP_IDEA_VERSION, sysProperty(SYSTEM_PROP_IDEA_VERSION)); 83 | ideProperties.put(SYSTEM_PROP_ECLIPSE_BUILD_ID, sysProperty(SYSTEM_PROP_ECLIPSE_BUILD_ID)); 84 | ideProperties.put(SYSTEM_PROP_IDEA_SYNC_ACTIVE, sysProperty(SYSTEM_PROP_IDEA_SYNC_ACTIVE)); 85 | ideProperties.put(ENV_VAR_VSCODE_PID, envVariable(ENV_VAR_VSCODE_PID)); 86 | ideProperties.put(ENV_VAR_VSCODE_INJECTION, envVariable(ENV_VAR_VSCODE_INJECTION)); 87 | 88 | new CaptureIdeMetadataAction(buildScan, ideProperties).execute(); 89 | } 90 | } 91 | 92 | private static final class CaptureIdeMetadataAction { 93 | 94 | private final BuildScanApiAdapter buildScan; 95 | private final Map> props; 96 | 97 | private CaptureIdeMetadataAction(BuildScanApiAdapter buildScan, Map> props) { 98 | this.buildScan = buildScan; 99 | this.props = props; 100 | } 101 | 102 | private void execute() { 103 | if (props.get(SYSTEM_PROP_IDEA_VENDOR_NAME).isPresent()) { 104 | String ideaVendorNameValue = props.get(SYSTEM_PROP_IDEA_VENDOR_NAME).get(); 105 | if ("JetBrains".equals(ideaVendorNameValue)) { 106 | tagIde("IntelliJ IDEA", props.get(SYSTEM_PROP_IDEA_VERSION).orElse("")); 107 | } 108 | } else if (props.get(SYSTEM_PROP_IDEA_VERSION).isPresent()) { 109 | // this case should be handled by the ideaVendorName condition but keeping it for compatibility reason (ideaVendorName started with 2020.1) 110 | tagIde("IntelliJ IDEA", props.get(SYSTEM_PROP_IDEA_VERSION).get()); 111 | } else if (props.get(SYSTEM_PROP_ECLIPSE_BUILD_ID).isPresent()) { 112 | tagIde("Eclipse", props.get(SYSTEM_PROP_ECLIPSE_BUILD_ID).get()); 113 | } else if (props.get(ENV_VAR_VSCODE_PID).isPresent() || props.get(ENV_VAR_VSCODE_INJECTION).isPresent()) { 114 | tagIde("VS Code", ""); 115 | } else { 116 | buildScan.tag("Cmd Line"); 117 | } 118 | 119 | if (props.get(SYSTEM_PROP_IDEA_SYNC_ACTIVE).isPresent()) { 120 | buildScan.tag("IDE sync"); 121 | } 122 | } 123 | 124 | private void tagIde(String ideLabel, String version) { 125 | buildScan.tag(ideLabel); 126 | if (!version.isEmpty()) { 127 | buildScan.value(ideLabel + " version", version); 128 | } 129 | } 130 | 131 | } 132 | 133 | private void captureCiOrLocal() { 134 | buildScan.tag(isCi() ? "CI" : "LOCAL"); 135 | } 136 | 137 | private void captureCiMetadata() { 138 | if (isCi()) { 139 | new CaptureCiMetadataAction(buildScan).execute(); 140 | } 141 | } 142 | 143 | private static final class CaptureCiMetadataAction { 144 | private final BuildScanApiAdapter buildScan; 145 | 146 | public CaptureCiMetadataAction(BuildScanApiAdapter buildScan) { 147 | this.buildScan = buildScan; 148 | } 149 | 150 | private void execute() { 151 | if (isJenkins() || isHudson()) { 152 | String ciProvider = isJenkins() ? "Jenkins" : "Hudson"; 153 | String controllerUrlEnvVar = isJenkins() ? "JENKINS_URL" : "HUDSON_URL"; 154 | 155 | Optional buildUrl = envVariable("BUILD_URL"); 156 | Optional buildNumber = envVariable("BUILD_NUMBER"); 157 | Optional nodeName = envVariable("NODE_NAME"); 158 | Optional jobName = envVariable("JOB_NAME"); 159 | Optional stageName = envVariable("STAGE_NAME"); 160 | Optional controllerUrl = envVariable(controllerUrlEnvVar); 161 | 162 | buildScan.value("CI provider", ciProvider); 163 | buildUrl.ifPresent(url -> 164 | buildScan.link(isJenkins() ? "Jenkins build" : "Hudson build", url)); 165 | buildNumber.ifPresent(value -> 166 | buildScan.value("CI build number", value)); 167 | nodeName.ifPresent(value -> 168 | addCustomValueAndSearchLink(buildScan, "CI node", value)); 169 | jobName.ifPresent(value -> 170 | addCustomValueAndSearchLink(buildScan, "CI job", value)); 171 | stageName.ifPresent(value -> 172 | addCustomValueAndSearchLink(buildScan, "CI stage", value)); 173 | controllerUrl.ifPresent(value -> 174 | buildScan.value("CI controller", value)); 175 | 176 | jobName.ifPresent(j -> buildNumber.ifPresent(b -> { 177 | Map params = new LinkedHashMap<>(); 178 | params.put("CI job", j); 179 | params.put("CI build number", b); 180 | addSearchLink(buildScan, "CI pipeline", params); 181 | })); 182 | } 183 | 184 | if (isTeamCity()) { 185 | buildScan.value("CI provider", "TeamCity"); 186 | Optional teamcityBuildPropertiesFile = envVariable("TEAMCITY_BUILD_PROPERTIES_FILE"); 187 | if (teamcityBuildPropertiesFile.isPresent()) { 188 | Properties buildProperties = readPropertiesFile(teamcityBuildPropertiesFile.get()); 189 | 190 | String teamCityBuildId = buildProperties.getProperty("teamcity.build.id"); 191 | if (isNotEmpty(teamCityBuildId)) { 192 | String teamcityConfigFile = buildProperties.getProperty("teamcity.configuration.properties.file"); 193 | if (isNotEmpty(teamcityConfigFile)) { 194 | Properties configProperties = readPropertiesFile(teamcityConfigFile); 195 | 196 | String teamCityServerUrl = configProperties.getProperty("teamcity.serverUrl"); 197 | if (isNotEmpty(teamCityServerUrl)) { 198 | String buildUrl = appendIfMissing(teamCityServerUrl, "/") + "viewLog.html?buildId=" + urlEncode(teamCityBuildId); 199 | buildScan.link("TeamCity build", buildUrl); 200 | } 201 | } 202 | } 203 | 204 | String teamCityBuildNumber = buildProperties.getProperty("build.number"); 205 | if (isNotEmpty(teamCityBuildNumber)) { 206 | buildScan.value("CI build number", teamCityBuildNumber); 207 | } 208 | String teamCityBuildTypeId = buildProperties.getProperty("teamcity.buildType.id"); 209 | if (isNotEmpty(teamCityBuildTypeId)) { 210 | addCustomValueAndSearchLink(buildScan, "CI build config", teamCityBuildTypeId); 211 | } 212 | String teamCityAgentName = buildProperties.getProperty("agent.name"); 213 | if (isNotEmpty(teamCityAgentName)) { 214 | addCustomValueAndSearchLink(buildScan, "CI agent", teamCityAgentName); 215 | } 216 | } 217 | } 218 | 219 | if (isCircleCI()) { 220 | buildScan.value("CI provider", "CircleCI"); 221 | envVariable("CIRCLE_BUILD_URL").ifPresent(url -> 222 | buildScan.link("CircleCI build", url)); 223 | envVariable("CIRCLE_BUILD_NUM").ifPresent(value -> 224 | buildScan.value("CI build number", value)); 225 | envVariable("CIRCLE_JOB").ifPresent(value -> 226 | addCustomValueAndSearchLink(buildScan, "CI job", value)); 227 | envVariable("CIRCLE_WORKFLOW_ID").ifPresent(value -> 228 | addCustomValueAndSearchLink(buildScan, "CI workflow", value)); 229 | } 230 | 231 | if (isBamboo()) { 232 | buildScan.value("CI provider", "Bamboo"); 233 | envVariable("bamboo_resultsUrl").ifPresent(url -> 234 | buildScan.link("Bamboo build", url)); 235 | envVariable("bamboo_buildNumber").ifPresent(value -> 236 | buildScan.value("CI build number", value)); 237 | envVariable("bamboo_planName").ifPresent(value -> 238 | addCustomValueAndSearchLink(buildScan, "CI plan", value)); 239 | envVariable("bamboo_buildPlanName").ifPresent(value -> 240 | addCustomValueAndSearchLink(buildScan, "CI build plan", value)); 241 | envVariable("bamboo_agentId").ifPresent(value -> 242 | addCustomValueAndSearchLink(buildScan, "CI agent", value)); 243 | } 244 | 245 | if (isGitHubActions()) { 246 | buildScan.value("CI provider", "GitHub Actions"); 247 | Optional gitHubUrl = envVariable("GITHUB_SERVER_URL"); 248 | Optional gitRepository = envVariable("GITHUB_REPOSITORY"); 249 | Optional gitHubRunId = envVariable("GITHUB_RUN_ID"); 250 | if (gitHubUrl.isPresent() && gitRepository.isPresent() && gitHubRunId.isPresent()) { 251 | buildScan.link("GitHub Actions build", gitHubUrl.get() + "/" + gitRepository.get() + "/actions/runs/" + gitHubRunId.get()); 252 | } 253 | envVariable("GITHUB_WORKFLOW").ifPresent(value -> 254 | addCustomValueAndSearchLink(buildScan, "CI workflow", value)); 255 | envVariable("GITHUB_RUN_ID").ifPresent(value -> 256 | addCustomValueAndSearchLink(buildScan, "CI run", value)); 257 | envVariable("GITHUB_HEAD_REF").filter(value -> !value.isEmpty()).ifPresent(value -> 258 | buildScan.value("PR branch", value)); 259 | } 260 | 261 | if (isGitLab()) { 262 | buildScan.value("CI provider", "GitLab"); 263 | envVariable("CI_JOB_URL").ifPresent(url -> 264 | buildScan.link("GitLab build", url)); 265 | envVariable("CI_PIPELINE_URL").ifPresent(url -> 266 | buildScan.link("GitLab pipeline", url)); 267 | envVariable("CI_JOB_NAME").ifPresent(value -> 268 | addCustomValueAndSearchLink(buildScan, "CI job", value)); 269 | envVariable("CI_JOB_STAGE").ifPresent(value -> 270 | addCustomValueAndSearchLink(buildScan, "CI stage", value)); 271 | } 272 | 273 | if (isTravis()) { 274 | buildScan.value("CI provider", "Travis"); 275 | envVariable("TRAVIS_BUILD_WEB_URL").ifPresent(url -> 276 | buildScan.link("Travis build", url)); 277 | envVariable("TRAVIS_BUILD_NUMBER").ifPresent(value -> 278 | buildScan.value("CI build number", value)); 279 | envVariable("TRAVIS_JOB_NAME").ifPresent(value -> 280 | addCustomValueAndSearchLink(buildScan, "CI job", value)); 281 | envVariable("TRAVIS_EVENT_TYPE").ifPresent(buildScan::tag); 282 | } 283 | 284 | if (isBitrise()) { 285 | buildScan.value("CI provider", "Bitrise"); 286 | envVariable("BITRISE_BUILD_URL").ifPresent(url -> 287 | buildScan.link("Bitrise build", url)); 288 | envVariable("BITRISE_BUILD_NUMBER").ifPresent(value -> 289 | buildScan.value("CI build number", value)); 290 | } 291 | 292 | if (isGoCD()) { 293 | buildScan.value("CI provider", "GoCD"); 294 | Optional pipelineName = envVariable("GO_PIPELINE_NAME"); 295 | Optional pipelineNumber = envVariable("GO_PIPELINE_COUNTER"); 296 | Optional stageName = envVariable("GO_STAGE_NAME"); 297 | Optional stageNumber = envVariable("GO_STAGE_COUNTER"); 298 | Optional jobName = envVariable("GO_JOB_NAME"); 299 | Optional goServerUrl = envVariable("GO_SERVER_URL"); 300 | if (Stream.of(pipelineName, pipelineNumber, stageName, stageNumber, jobName, goServerUrl).allMatch(Optional::isPresent)) { 301 | //noinspection OptionalGetWithoutIsPresent 302 | String buildUrl = String.format("%s/tab/build/detail/%s/%s/%s/%s/%s", 303 | goServerUrl.get(), pipelineName.get(), 304 | pipelineNumber.get(), stageName.get(), stageNumber.get(), jobName.get()); 305 | buildScan.link("GoCD build", buildUrl); 306 | } else if (goServerUrl.isPresent()) { 307 | buildScan.link("GoCD", goServerUrl.get()); 308 | } 309 | pipelineName.ifPresent(value -> 310 | addCustomValueAndSearchLink(buildScan, "CI pipeline", value)); 311 | jobName.ifPresent(value -> 312 | addCustomValueAndSearchLink(buildScan, "CI job", value)); 313 | stageName.ifPresent(value -> 314 | addCustomValueAndSearchLink(buildScan, "CI stage", value)); 315 | } 316 | 317 | if (isAzurePipelines()) { 318 | buildScan.value("CI provider", "Azure Pipelines"); 319 | Optional azureServerUrl = envVariable("SYSTEM_TEAMFOUNDATIONCOLLECTIONURI"); 320 | Optional azureProject = envVariable("SYSTEM_TEAMPROJECT"); 321 | Optional buildId = envVariable("BUILD_BUILDID"); 322 | if (Stream.of(azureServerUrl, azureProject, buildId).allMatch(Optional::isPresent)) { 323 | //noinspection OptionalGetWithoutIsPresent 324 | String buildUrl = String.format("%s%s/_build/results?buildId=%s", 325 | azureServerUrl.get(), azureProject.get(), buildId.get()); 326 | buildScan.link("Azure Pipelines build", buildUrl); 327 | } else if (azureServerUrl.isPresent()) { 328 | buildScan.link("Azure Pipelines", azureServerUrl.get()); 329 | } 330 | 331 | buildId.ifPresent(value -> 332 | buildScan.value("CI build number", value)); 333 | } 334 | 335 | if (isBuildkite()) { 336 | buildScan.value("CI provider", "Buildkite"); 337 | envVariable("BUILDKITE_BUILD_URL").ifPresent(url -> 338 | buildScan.link("Buildkite build", url)); 339 | envVariable("BUILDKITE_COMMAND").ifPresent(command -> 340 | addCustomValueAndSearchLink(buildScan, "CI command", command)); 341 | envVariable("BUILDKITE_BUILD_ID").ifPresent(id -> 342 | buildScan.value("CI build ID", id)); 343 | 344 | Optional buildkitePrRepo = envVariable("BUILDKITE_PULL_REQUEST_REPO"); 345 | Optional buildkitePrNumber = envVariable("BUILDKITE_PULL_REQUEST"); 346 | if (buildkitePrRepo.isPresent() && buildkitePrNumber.isPresent()) { 347 | // Create a GitHub link with the pr number and full repo url 348 | String prNumber = buildkitePrNumber.get(); 349 | toWebRepoUri(buildkitePrRepo.get()).ifPresent(url -> 350 | buildScan.link("PR source", url + "/pull/" + prNumber)); 351 | } 352 | } 353 | } 354 | } 355 | 356 | private void captureGitMetadata() { 357 | // Run expensive computation in background 358 | buildScan.background(new CaptureGitMetadataAction()); 359 | } 360 | 361 | private static final class CaptureGitMetadataAction implements Consumer { 362 | 363 | @Override 364 | public void accept(BuildScanApiAdapter buildScan) { 365 | if (!isGitInstalled()) { 366 | return; 367 | } 368 | 369 | String gitRepo = execAndGetStdOut("git", "config", "--get", "remote.origin.url"); 370 | String gitCommitId = execAndGetStdOut("git", "rev-parse", "--verify", "HEAD"); 371 | String gitCommitShortId = execAndGetStdOut("git", "rev-parse", "--short=8", "--verify", "HEAD"); 372 | String gitBranchName = getGitBranchName(() -> execAndGetStdOut("git", "rev-parse", "--abbrev-ref", "HEAD")); 373 | String gitStatus = execAndGetStdOut("git", "status", "--porcelain"); 374 | 375 | if (isNotEmpty(gitRepo)) { 376 | redactUserInfo(gitRepo).ifPresent(redactedGitRepo -> buildScan.value("Git repository", redactedGitRepo)); 377 | } 378 | if (isNotEmpty(gitCommitId)) { 379 | buildScan.value("Git commit id", gitCommitId); 380 | } 381 | if (isNotEmpty(gitCommitShortId)) { 382 | addCustomValueAndSearchLink(buildScan, "Git commit id", "Git commit id short", gitCommitShortId); 383 | } 384 | if (isNotEmpty(gitBranchName)) { 385 | buildScan.tag(gitBranchName); 386 | buildScan.value("Git branch", gitBranchName); 387 | } 388 | if (isNotEmpty(gitStatus)) { 389 | buildScan.tag("Dirty"); 390 | buildScan.value("Git status", gitStatus); 391 | } 392 | 393 | Optional gitHubUrl = envVariable("GITHUB_SERVER_URL"); 394 | Optional gitRepository = envVariable("GITHUB_REPOSITORY"); 395 | if (gitHubUrl.isPresent() && gitRepository.isPresent() && isNotEmpty(gitCommitId)) { 396 | buildScan.link("GitHub source", gitHubUrl.get() + "/" + gitRepository.get() + "/tree/" + gitCommitId); 397 | } else if (isNotEmpty(gitRepo) && isNotEmpty(gitCommitId)) { 398 | Optional webRepoUri = toWebRepoUri(gitRepo); 399 | webRepoUri.ifPresent(uri -> { 400 | if (uri.getHost().contains("github")) { 401 | buildScan.link("GitHub source", uri + "/tree/" + gitCommitId); 402 | } else if (uri.getHost().contains("gitlab")) { 403 | buildScan.link("GitLab source", uri + "/-/commit/" + gitCommitId); 404 | } 405 | }); 406 | } 407 | } 408 | 409 | private boolean isGitInstalled() { 410 | return execAndCheckSuccess("git", "--version"); 411 | } 412 | 413 | private String getGitBranchName(Supplier gitCommand) { 414 | if (isJenkins() || isHudson()) { 415 | Optional branch = envVariable("BRANCH_NAME"); 416 | if (branch.isPresent()) { 417 | return branch.get(); 418 | } 419 | 420 | Optional gitBranch = envVariable("GIT_BRANCH"); 421 | if (gitBranch.isPresent()) { 422 | Optional localBranch = getLocalBranch(gitBranch.get()); 423 | if (localBranch.isPresent()) { 424 | return localBranch.get(); 425 | } 426 | } 427 | } else if (isGitLab()) { 428 | Optional branch = envVariable("CI_COMMIT_REF_NAME"); 429 | if (branch.isPresent()) { 430 | return branch.get(); 431 | } 432 | } else if (isAzurePipelines()) { 433 | Optional branch = envVariable("BUILD_SOURCEBRANCH"); 434 | if (branch.isPresent()) { 435 | return branch.get(); 436 | } 437 | } else if (isGitHubActions()) { 438 | Optional branch = envVariable("GITHUB_REF_NAME"); 439 | if (branch.isPresent()) { 440 | return branch.get(); 441 | } 442 | } 443 | return gitCommand.get(); 444 | } 445 | 446 | private static Optional getLocalBranch(String remoteBranch) { 447 | // This finds the longest matching remote name. This is because, for example, a local git clone could have 448 | // two remotes named `origin` and `origin/two`. In this scenario, we would want a remote branch of 449 | // `origin/two/main` to match to the `origin/two` remote, not to `origin` 450 | Function> findLongestMatchingRemote = remotes -> Arrays.stream(remotes.split("\\R")) 451 | .filter(remote -> remoteBranch.startsWith(remote + "/")) 452 | .max(Comparator.comparingInt(String::length)); 453 | 454 | return Optional.ofNullable(execAndGetStdOut("git", "remote")) 455 | .filter(Utils::isNotEmpty) 456 | .flatMap(findLongestMatchingRemote) 457 | .map(remote -> remoteBranch.replaceFirst("^" + remote + "/", "")); 458 | } 459 | } 460 | 461 | private void captureSkipTestsFlags() { 462 | addCustomValueWhenProjectPropertyResolvesToTrue("skipITs"); 463 | addCustomValueWhenProjectPropertyResolvesToTrue("skipTests"); 464 | addCustomValueWhenProjectPropertyResolvesToTrue("maven.test.skip"); 465 | } 466 | 467 | private void addCustomValueWhenProjectPropertyResolvesToTrue(String property) { 468 | projectProperty(mavenSession, property).ifPresent(value -> { 469 | if (value.isEmpty() || Boolean.valueOf(value).equals(Boolean.TRUE)) { 470 | buildScan.value("switches." + property, "On"); 471 | } 472 | }); 473 | } 474 | 475 | private static void addCustomValueAndSearchLink(BuildScanApiAdapter buildScan, String name, String value) { 476 | addCustomValueAndSearchLink(buildScan, name, name, value); 477 | } 478 | 479 | private static void addCustomValueAndSearchLink(BuildScanApiAdapter buildScan, String linkLabel, String name, String value) { 480 | // Set custom values immediately, but do not add custom links until 'buildFinished' since 481 | // creating customs links requires the server url to be fully configured 482 | buildScan.value(name, value); 483 | buildScan.buildFinished(result -> addSearchLink(buildScan, linkLabel, name, value)); 484 | } 485 | 486 | private static void addSearchLink(BuildScanApiAdapter buildScan, String linkLabel, Map values) { 487 | // the parameters for a link querying multiple custom values look like: 488 | // search.names=name1,name2&search.values=value1,value2 489 | // this reduction groups all names and all values together in order to properly generate the query 490 | values.entrySet().stream() 491 | .sorted(Map.Entry.comparingByKey()) // results in a deterministic order of link parameters 492 | .reduce((a, b) -> new AbstractMap.SimpleEntry<>(a.getKey() + "," + b.getKey(), a.getValue() + "," + b.getValue())) 493 | .ifPresent(x -> buildScan.buildFinished(result -> addSearchLink(buildScan, linkLabel, x.getKey(), x.getValue()))); 494 | } 495 | 496 | private static void addSearchLink(BuildScanApiAdapter buildScan, String linkLabel, String name, String value) { 497 | String server = buildScan.getServer(); 498 | if (server != null) { 499 | String searchParams = "search.names=" + urlEncode(name) + "&search.values=" + urlEncode(value); 500 | String url = appendIfMissing(server, "/") + "scans?" + searchParams + "#selection.buildScanB=" + urlEncode("{SCAN_ID}"); 501 | buildScan.link(linkLabel + " build scans", url); 502 | } 503 | } 504 | 505 | } -------------------------------------------------------------------------------- /src/main/java/com/gradle/CustomConfigurationSpec.java: -------------------------------------------------------------------------------- 1 | package com.gradle; 2 | 3 | import java.util.Optional; 4 | 5 | enum CustomConfigurationSpec { 6 | GRADLE_ENTERPRISE( 7 | "Gradle Enterprise", 8 | "gradle-enterprise-custom-user-data", 9 | "gradleEnterprise", 10 | Optional.empty() 11 | ), 12 | DEVELOCITY( 13 | "Develocity", 14 | "develocity-custom-user-data", 15 | "develocity", 16 | Optional.of(GRADLE_ENTERPRISE) 17 | ); 18 | 19 | final String displayName; 20 | final String groovyScriptName; 21 | final String apiVariableName; 22 | final Optional fallbackScript; 23 | 24 | CustomConfigurationSpec( 25 | String displayName, 26 | String groovyScriptName, 27 | String apiVariableName, 28 | Optional fallbackScript 29 | ) { 30 | this.displayName = displayName; 31 | this.groovyScriptName = groovyScriptName; 32 | this.apiVariableName = apiVariableName; 33 | this.fallbackScript = fallbackScript; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/gradle/CustomDevelocityConfig.java: -------------------------------------------------------------------------------- 1 | package com.gradle; 2 | 3 | import com.gradle.develocity.agent.maven.adapters.BuildCacheApiAdapter; 4 | import com.gradle.develocity.agent.maven.adapters.BuildScanApiAdapter; 5 | import com.gradle.develocity.agent.maven.adapters.DevelocityAdapter; 6 | 7 | /** 8 | * Provide standardized Develocity configuration. 9 | * By applying the extension, these settings will automatically be applied. 10 | */ 11 | final class CustomDevelocityConfig { 12 | 13 | void configureDevelocity(DevelocityAdapter develocity) { 14 | /* Example of Develocity configuration 15 | 16 | develocity.setServer("https://enterprise-samples.gradle.com"); 17 | develocity.setAllowUntrustedServer(false); 18 | 19 | */ 20 | } 21 | 22 | void configureBuildScanPublishing(BuildScanApiAdapter buildScans) { 23 | /* Example of build scan publishing configuration 24 | 25 | boolean isCiServer = System.getenv().containsKey("CI"); 26 | 27 | buildScans.publishAlways(); 28 | buildScans.capture(capture -> capture.setGoalInputFiles(true)); 29 | buildScans.setUploadInBackground(!isCiServer); 30 | 31 | */ 32 | } 33 | 34 | void configureBuildCache(BuildCacheApiAdapter buildCache) { 35 | /* Example of build cache configuration 36 | 37 | boolean isCiServer = System.getenv().containsKey("CI"); 38 | 39 | // Enable the local build cache for all local and CI builds 40 | // For short-lived CI agents, it makes sense to disable the local build cache 41 | buildCache.getLocal().setEnabled(true); 42 | 43 | // Only permit store operations to the remote build cache for CI builds 44 | // Local builds will only read from the remote build cache 45 | buildCache.getRemote().setEnabled(true); 46 | buildCache.getRemote().setStoreEnabled(isCiServer); 47 | 48 | */ 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/gradle/GroovyScriptUserData.java: -------------------------------------------------------------------------------- 1 | package com.gradle; 2 | 3 | import com.gradle.develocity.agent.maven.adapters.DevelocityAdapter; 4 | import groovy.lang.Binding; 5 | import groovy.lang.GroovyShell; 6 | import org.apache.maven.MavenExecutionException; 7 | import org.apache.maven.execution.MavenSession; 8 | import org.slf4j.Logger; 9 | 10 | import java.io.File; 11 | 12 | final class GroovyScriptUserData { 13 | 14 | static void evaluate(MavenSession session, DevelocityAdapter develocity, Logger logger, CustomConfigurationSpec customConfigurationSpec) throws MavenExecutionException { 15 | File script = getGroovyScript(session, customConfigurationSpec.groovyScriptName); 16 | if (script.exists()) { 17 | logger.debug("Evaluating custom user data Groovy script: {}", script); 18 | evaluateGroovyScript(session, develocity, logger, script, customConfigurationSpec.apiVariableName); 19 | } else if (!customConfigurationSpec.fallbackScript.isPresent()) { 20 | logger.debug("Skipping evaluation of custom user data Groovy script because it does not exist: " + script); 21 | } else { 22 | CustomConfigurationSpec fallbackSpec = customConfigurationSpec.fallbackScript.get(); 23 | File fallbackScript = getGroovyScript(session, fallbackSpec.groovyScriptName); 24 | if (fallbackScript.exists()) { 25 | logger.warn("Evaluating deprecated custom user data Groovy script: {}. Use '{}.groovy' scripts instead.", fallbackScript, customConfigurationSpec.groovyScriptName); 26 | evaluateGroovyScript(session, develocity, logger, fallbackScript, fallbackSpec.apiVariableName); 27 | } else { 28 | logger.debug("Skipping evaluation of custom user data Groovy script because it does not exist: " + fallbackScript); 29 | } 30 | } 31 | } 32 | 33 | private static File getGroovyScript(MavenSession session, String scriptName) { 34 | File rootDir = session.getRequest().getMultiModuleProjectDirectory(); 35 | return new File(rootDir, ".mvn/" + scriptName + ".groovy"); 36 | } 37 | 38 | private static void evaluateGroovyScript(MavenSession session, DevelocityAdapter develocity, Logger logger, File groovyScript, String apiVariableName) throws MavenExecutionException { 39 | try { 40 | Binding binding = prepareBinding(session, develocity, logger, apiVariableName); 41 | new GroovyShell(GroovyScriptUserData.class.getClassLoader(), binding).evaluate(groovyScript); 42 | } catch (Exception e) { 43 | throw new MavenExecutionException("Failed to evaluate custom user data Groovy script: " + groovyScript, e); 44 | } 45 | } 46 | 47 | private static Binding prepareBinding(MavenSession session, DevelocityAdapter develocity, Logger logger, String apiVariableName) { 48 | Binding binding = new Binding(); 49 | binding.setVariable("project", session.getTopLevelProject()); 50 | binding.setVariable("session", session); 51 | binding.setVariable(apiVariableName, develocity); 52 | binding.setVariable("buildScan", develocity.getBuildScan()); 53 | binding.setVariable("buildCache", develocity.getBuildCache()); 54 | binding.setVariable("log", logger); 55 | return binding; 56 | } 57 | 58 | private GroovyScriptUserData() { 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/gradle/Utils.java: -------------------------------------------------------------------------------- 1 | package com.gradle; 2 | 3 | import org.apache.maven.execution.MavenSession; 4 | 5 | import java.io.BufferedReader; 6 | import java.io.FileInputStream; 7 | import java.io.IOException; 8 | import java.io.InputStream; 9 | import java.io.InputStreamReader; 10 | import java.io.Reader; 11 | import java.io.UnsupportedEncodingException; 12 | import java.net.URI; 13 | import java.net.URISyntaxException; 14 | import java.net.URLEncoder; 15 | import java.nio.charset.Charset; 16 | import java.nio.charset.StandardCharsets; 17 | import java.time.Duration; 18 | import java.util.Optional; 19 | import java.util.Properties; 20 | import java.util.concurrent.TimeUnit; 21 | import java.util.regex.Matcher; 22 | import java.util.regex.Pattern; 23 | 24 | final class Utils { 25 | 26 | private static final Pattern GIT_REPO_URI_PATTERN = Pattern.compile("^(?:(?:https://|git://)(?:.+:.+@)?|(?:ssh)?.*?@)(.*?(?:github|gitlab).*?)(?:/|:[0-9]*?/|:)(.*?)(?:\\.git)?$"); 27 | 28 | static Optional envVariable(String name) { 29 | return Optional.ofNullable(System.getenv(name)); 30 | } 31 | 32 | static Optional projectProperty(MavenSession mavenSession, String name) { 33 | String value = mavenSession.getUserProperties().getProperty(name); 34 | return Optional.ofNullable(value); 35 | } 36 | 37 | static Optional sysProperty(String name) { 38 | return Optional.ofNullable(System.getProperty(name)); 39 | } 40 | 41 | static Optional booleanSysProperty(String name) { 42 | return sysProperty(name).map(Boolean::parseBoolean); 43 | } 44 | 45 | static Optional durationSysProperty(String name) { 46 | return sysProperty(name).map(Duration::parse); 47 | } 48 | 49 | static boolean isNotEmpty(String value) { 50 | return value != null && !value.isEmpty(); 51 | } 52 | 53 | static String appendIfMissing(String str, String suffix) { 54 | return str.endsWith(suffix) ? str : str + suffix; 55 | } 56 | 57 | static String urlEncode(String str) { 58 | try { 59 | return URLEncoder.encode(str, StandardCharsets.UTF_8.name()); 60 | } catch (UnsupportedEncodingException e) { 61 | throw new RuntimeException(e); 62 | } 63 | } 64 | 65 | static Optional redactUserInfo(String url) { 66 | if (!url.startsWith("http")) { 67 | return Optional.of(url); 68 | } 69 | 70 | try { 71 | URI uri = new URI(url); 72 | URI redactedUri = new URI( 73 | uri.getScheme(), 74 | uri.getUserInfo() == null || uri.getUserInfo().isEmpty() ? null : "******", 75 | uri.getHost(), 76 | uri.getPort(), 77 | uri.getRawPath(), 78 | uri.getRawQuery(), 79 | uri.getRawFragment()); 80 | return Optional.of(redactedUri.toString()); 81 | } catch (URISyntaxException e) { 82 | return Optional.empty(); 83 | } 84 | } 85 | 86 | static Properties readPropertiesFile(String name) { 87 | try (InputStream input = new FileInputStream(name)) { 88 | Properties properties = new Properties(); 89 | properties.load(input); 90 | return properties; 91 | } catch (IOException e) { 92 | throw new RuntimeException(e); 93 | } 94 | } 95 | 96 | static boolean execAndCheckSuccess(String... args) { 97 | Runtime runtime = Runtime.getRuntime(); 98 | Process process = null; 99 | try { 100 | process = runtime.exec(args); 101 | boolean finished = process.waitFor(10, TimeUnit.SECONDS); 102 | return finished && process.exitValue() == 0; 103 | } catch (IOException | InterruptedException ignored) { 104 | return false; 105 | } finally { 106 | if (process != null) { 107 | process.destroyForcibly(); 108 | } 109 | } 110 | } 111 | 112 | static String execAndGetStdOut(String... args) { 113 | Runtime runtime = Runtime.getRuntime(); 114 | Process process; 115 | try { 116 | process = runtime.exec(args); 117 | } catch (IOException e) { 118 | throw new RuntimeException(e); 119 | } 120 | 121 | try (Reader standard = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.defaultCharset()))) { 122 | try (Reader error = new BufferedReader(new InputStreamReader(process.getErrorStream(), Charset.defaultCharset()))) { 123 | String standardText = readFully(standard); 124 | String ignore = readFully(error); 125 | 126 | boolean finished = process.waitFor(10, TimeUnit.SECONDS); 127 | return finished && process.exitValue() == 0 ? trimAtEnd(standardText) : null; 128 | } 129 | } catch (IOException | InterruptedException e) { 130 | throw new RuntimeException(e); 131 | } finally { 132 | process.destroyForcibly(); 133 | } 134 | } 135 | 136 | /** 137 | * Construct a repo {@link URI} from a git URL in the format of 138 | * git://github.com/acme-inc/my-project.git. If the URL cannot be parsed, {@link Optional#empty()} is 139 | * returned. 140 | *

141 | * The scheme can be any of git://, https://, or ssh. 142 | */ 143 | static Optional toWebRepoUri(String gitRepoUri) { 144 | Matcher matcher = GIT_REPO_URI_PATTERN.matcher(gitRepoUri); 145 | if (matcher.matches()) { 146 | String scheme = "https"; 147 | String host = matcher.group(1); 148 | String path = matcher.group(2).startsWith("/") ? matcher.group(2) : "/" + matcher.group(2); 149 | return toUri(scheme, host, path); 150 | } else { 151 | return Optional.empty(); 152 | } 153 | } 154 | 155 | static Optional toUri(String scheme, String host, String path) { 156 | try { 157 | return Optional.of(new URI(scheme, host, path, null)); 158 | } catch (URISyntaxException e) { 159 | return Optional.empty(); 160 | } 161 | } 162 | 163 | private static String readFully(Reader reader) throws IOException { 164 | StringBuilder sb = new StringBuilder(); 165 | char[] buf = new char[1024]; 166 | int nRead; 167 | while ((nRead = reader.read(buf)) != -1) { 168 | sb.append(buf, 0, nRead); 169 | } 170 | return sb.toString(); 171 | } 172 | 173 | private static String trimAtEnd(String str) { 174 | return ('x' + str).trim().substring(1); 175 | } 176 | 177 | private Utils() { 178 | } 179 | 180 | } 181 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/plexus/components.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | com.gradle.develocity.agent.maven.api.DevelocityListener 5 | common-custom-user-data-develocity-listener 6 | com.gradle.CommonCustomUserDataDevelocityListener 7 | Captures common custom user data in Maven Build Scan 8 | false 9 | 10 | 11 | com.gradle.maven.extension.api.GradleEnterpriseListener 12 | common-custom-user-data-gradle-enterprise-listener 13 | com.gradle.CommonCustomUserDataGradleEnterpriseListener 14 | Captures common custom user data in Maven Build Scan 15 | false 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/test/java/com/gradle/UtilsTest.java: -------------------------------------------------------------------------------- 1 | package com.gradle; 2 | 3 | 4 | import org.junit.jupiter.api.extension.ExtensionContext; 5 | import org.junit.jupiter.params.ParameterizedTest; 6 | import org.junit.jupiter.params.provider.Arguments; 7 | import org.junit.jupiter.params.provider.ArgumentsProvider; 8 | import org.junit.jupiter.params.provider.ArgumentsSource; 9 | 10 | import java.net.URI; 11 | import java.util.HashMap; 12 | import java.util.Map; 13 | import java.util.Optional; 14 | import java.util.Set; 15 | import java.util.stream.Collectors; 16 | import java.util.stream.Stream; 17 | 18 | import static com.gradle.Utils.toWebRepoUri; 19 | import static org.junit.jupiter.api.Assertions.assertEquals; 20 | 21 | public class UtilsTest { 22 | 23 | @ParameterizedTest 24 | @ArgumentsSource(WebRepoUriArgumentsProvider.class) 25 | public void testToWebRepoUri(String repositoryHost, String repositoryUri) { 26 | URI expectedWebRepoUri = URI.create(String.format("https://%s.com/acme-inc/my-project", repositoryHost)); 27 | assertEquals(Optional.of(expectedWebRepoUri), toWebRepoUri(String.format(repositoryUri, repositoryHost))); 28 | } 29 | 30 | @ParameterizedTest 31 | @ArgumentsSource(EnterpriseWebRepoUriArgumentsProvider.class) 32 | public void testToWebRepoUri_enterpriseUri(String repositoryHost, String repositoryUri) { 33 | URI expectedWebRepoUri = URI.create(String.format("https://%s.acme.com/acme-inc/my-project", repositoryHost)); 34 | assertEquals(Optional.of(expectedWebRepoUri), toWebRepoUri(String.format(repositoryUri, repositoryHost))); 35 | } 36 | 37 | @ParameterizedTest 38 | @ArgumentsSource(UserInfoArgumentsProvider.class) 39 | public void testUserInfoRedacted(String inputUrl, String expectedRedactedUrl) { 40 | assertEquals(expectedRedactedUrl, Utils.redactUserInfo(inputUrl).orElse(null)); 41 | } 42 | 43 | private static class WebRepoUriArgumentsProvider implements ArgumentsProvider { 44 | 45 | @Override 46 | public Stream provideArguments(ExtensionContext context) { 47 | Set host = Stream.of("github", "gitlab").collect(Collectors.toSet()); 48 | Set remoteRepositoryUris = Stream.of( 49 | "https://%s.com/acme-inc/my-project", 50 | "https://%s.com:443/acme-inc/my-project", 51 | "https://user:secret@%s.com/acme-inc/my-project", 52 | "https://user:secret%%1Fpassword@%s.com/acme-inc/my-project", 53 | "https://user:secret%%1password@%s.com/acme-inc/my-project", 54 | "ssh://git@%s.com/acme-inc/my-project.git", 55 | "ssh://git@%s.com:22/acme-inc/my-project.git", 56 | "git://%s.com/acme-inc/my-project.git", 57 | "git@%s.com/acme-inc/my-project.git" 58 | ).collect(Collectors.toSet()); 59 | return host.stream().flatMap(h -> remoteRepositoryUris.stream().map(r -> Arguments.arguments(h, r))); 60 | } 61 | } 62 | 63 | private static class EnterpriseWebRepoUriArgumentsProvider implements ArgumentsProvider { 64 | 65 | @Override 66 | public Stream provideArguments(ExtensionContext context) { 67 | Set host = Stream.of("github", "gitlab").collect(Collectors.toSet()); 68 | Set remoteRepositoryUris = Stream.of( 69 | "https://%s.acme.com/acme-inc/my-project", 70 | "git@%s.acme.com/acme-inc/my-project.git" 71 | ).collect(Collectors.toSet()); 72 | return host.stream().flatMap(h -> remoteRepositoryUris.stream().map(r -> Arguments.arguments(h, r))); 73 | } 74 | } 75 | 76 | private static class UserInfoArgumentsProvider implements ArgumentsProvider { 77 | 78 | @Override 79 | public Stream provideArguments(ExtensionContext context) { 80 | Map cases = new HashMap<>(); 81 | cases.put("https://user:password@acme.com/acme-inc/my-project", "https://******@acme.com/acme-inc/my-project"); 82 | cases.put("https://user%1Fname:password@acme.com/acme-inc/my-project", "https://******@acme.com/acme-inc/my-project"); 83 | cases.put("https://user:secret%1Fpassword@acme.com/acme-inc/my-project", "https://******@acme.com/acme-inc/my-project"); 84 | cases.put("https://user:secret%1password@acme.com/acme-inc/my-project", null); 85 | cases.put("git@github.com:gradle/common-custom-user-data-gradle-plugin.git", "git@github.com:gradle/common-custom-user-data-gradle-plugin.git"); 86 | 87 | return cases.entrySet().stream() 88 | .map(entry -> Arguments.arguments(entry.getKey(), entry.getValue())); 89 | } 90 | } 91 | } 92 | --------------------------------------------------------------------------------