Repository: franzbecker/gradle-lombok Branch: master Commit: 71dc34ae71ba Files: 50 Total size: 79.4 KB Directory structure: gitextract_eyctld9_/ ├── .gitignore ├── .travis.yml ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── examples/ │ ├── .travis-run-examples.sh │ ├── README.md │ ├── build.gradle │ ├── delombok-gradle-groovy/ │ │ ├── build.gradle │ │ └── src/ │ │ └── main/ │ │ └── java/ │ │ └── com/ │ │ └── example/ │ │ └── Greeting.java │ ├── delombok-gradle-kotlin/ │ │ ├── build.gradle.kts │ │ └── src/ │ │ └── main/ │ │ └── java/ │ │ └── com/ │ │ └── example/ │ │ └── Greeting.java │ ├── gradle/ │ │ └── wrapper/ │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties │ ├── gradlew │ ├── gradlew.bat │ ├── hello-world/ │ │ └── src/ │ │ ├── main/ │ │ │ └── java/ │ │ │ └── com/ │ │ │ └── example/ │ │ │ ├── Greeting.java │ │ │ ├── HelloWorld.java │ │ │ └── SneakyHelloWorld.java │ │ └── test/ │ │ └── java/ │ │ └── com/ │ │ └── example/ │ │ ├── GreetingTest.java │ │ └── SneakyHelloWorldTest.java │ └── settings.gradle └── gradle-lombok-plugin/ ├── .travis-publishOnRelease.sh ├── build.gradle ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── settings.gradle ├── src/ │ ├── main/ │ │ ├── groovy/ │ │ │ └── io/ │ │ │ └── franzbecker/ │ │ │ └── gradle/ │ │ │ └── lombok/ │ │ │ ├── LombokPlugin.groovy │ │ │ ├── LombokPluginExtension.groovy │ │ │ └── task/ │ │ │ ├── DelombokTask.groovy │ │ │ ├── InstallLombokTask.groovy │ │ │ └── VerifyLombokTask.groovy │ │ ├── java/ │ │ │ └── io/ │ │ │ └── franzbecker/ │ │ │ └── gradle/ │ │ │ └── lombok/ │ │ │ └── util/ │ │ │ └── HashUtil.java │ │ └── resources/ │ │ └── META-INF/ │ │ └── gradle-plugins/ │ │ └── io.franzbecker.gradle-lombok.properties │ └── test/ │ ├── groovy/ │ │ └── io/ │ │ └── franzbecker/ │ │ └── gradle/ │ │ └── lombok/ │ │ ├── AbstractIntegrationTest.groovy │ │ ├── CompatibilityIntegrationTest.groovy │ │ ├── LombokPluginIntegrationTest.groovy │ │ ├── LombokPluginSpec.groovy │ │ ├── task/ │ │ │ ├── AbstractJavaExecTaskSpec.groovy │ │ │ ├── DelombokTaskIntegrationTest.groovy │ │ │ ├── DelombokTaskSpec.groovy │ │ │ ├── InstallLombokTaskSpec.groovy │ │ │ ├── VerifyLombokTaskIntegrationTest.groovy │ │ │ └── VerifyLombokTaskSpec.groovy │ │ └── util/ │ │ └── HashUtilSpec.groovy │ └── resources/ │ └── dummy.txt └── update-lombok.sh ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ ### Gradle ### .gradle build/ gradle-app.setting !gradle-wrapper.jar ### Intellij ### *.iml .idea/ *.ipr *.iws out/ ### Eclipse ### .settings/ .metadata .gradle bin/ .classpath .project ================================================ FILE: .travis.yml ================================================ language: groovy sudo: false dist: trusty before_cache: - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock - rm -fr $HOME/.gradle/caches/*/plugin-resolution/ cache: directories: - $HOME/.gradle/caches/ - $HOME/.gradle/wrapper/ env: - PLUGIN_BUILD_DIR=$TRAVIS_BUILD_DIR/gradle-lombok-plugin before_install: - jdk_switcher use openjdk8 - cd $PLUGIN_BUILD_DIR script: - ./gradlew check - $TRAVIS_BUILD_DIR/examples/.travis-run-examples.sh - jdk_switcher use openjdk8 after_success: - bash <(curl -s https://codecov.io/bash) - ./.travis-publishOnRelease.sh ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing Please feel free to contribute using pull requests. All contributions must be licensed under the [Apache License 2.0](LICENSE) or compatible. ## Testing IDEs locally All features should be covered by unit and integration tests. Still, since we don't have automated IDE tests it might be necessary to test your contribution manually for IDE compatibility. Perform the following Gradle command to publish the plugin to your local Maven repository: ``` ./gradlew publishToMavenLocal ``` A simple sample build.gradle using that will look like: ``` buildscript { repositories { mavenLocal() } dependencies { classpath 'io.franzbecker:gradle-lombok:+' } } apply plugin: 'java' apply plugin: 'io.franzbecker.gradle-lombok' ``` ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # gradle-lombok [![License](http://img.shields.io/badge/license-Apache_2.0-blue.svg?style=flat)](https://www.apache.org/licenses/LICENSE-2.0.html) [![Build Status](https://app.travis-ci.com/franzbecker/gradle-lombok.svg?branch=master)](https://app.travis-ci.com/franzbecker/gradle-lombok) [![codecov.io](http://codecov.io/github/franzbecker/gradle-lombok/coverage.svg?branch=master)](http://codecov.io/github/franzbecker/gradle-lombok?branch=master) A Gradle plugin for project [Lombok](https://projectlombok.org) support. __Maintenance mode.__ Only critical bugs will be fixed and there won't be any more feature from my side. Please feel free to continue contributing and open PRs, I will still review them in a timely manner. # Usage The plugin is included in the [central plugin repository](https://plugins.gradle.org/plugin/io.franzbecker.gradle-lombok/5.0.0). A minimal `build.gradle` looks like this: plugins { id 'io.franzbecker.gradle-lombok' version '5.0.0' id 'java' } repositories { jcenter() // or Maven central, required for Lombok dependency } After applying the plugin, the Lombok annotations can be used directly in any Java code and the Lombok Eclipse installer can be called via `gradlew installLombok`. The Lombok version can be configured using the following syntax: lombok { // optional: values below are the defaults version = "1.18.12" sha256 = "49381508ecb02b3c173368436ef71b24c0d4418ad260e6cc98becbcf4b345406" } If the verifcation of the integrity shall be skipped, the `sha256` value needs to be set to null or an empty string: lombok { sha256 = "" // skip verifyLombok task } Some examples can be found in the [examples](https://github.com/franzbecker/gradle-lombok/tree/master/examples) folder. # Motivation When using Lombok in your Gradle project, you should consider using this plugin because * it adds the Lombok dependency to the classpath * it simplifies the Eclipse IDE installation * it offers support for delomboking ## Adding the Lombok dependency This plugin adds the Lombok dependency to `compileOnly` and `testCompileOnly`. Starting with Gradle 4.6 also `annotationProcessor` and `testAnnotationProcessor`. Note that for using Gradle prior to version 2.12 please use this plugin in version "1.11" which is the last version that supports Gradle < 2.12. ## Simplifying Eclipse IDE installation The project Lombok website states: > NOTE: You'll still need to download lombok, or doubleclick on the lombok.jar file downloaded by maven / ivy / gradle, to install lombok into your eclipse installation. When using Lombok in teams with no automated Eclipse provisioning this is quite a pain. Every developer has to retrieve the JAR in the right version, verify its integrity (some won't) and call `java -jar lombok.jar`. This plugin adds a task called `installLombok` to your Gradle build that uses the dependency that has already been added to the compile-only scope, verifies its integrity using SHA-256 and finally invokes the main class of the JAR. This greatly simplifies the installation process for each developer and makes sure that the same version is used across the team. ## Delombok support The plugin offers basic support for delomboking. The `DelombokTask` is a simple `JavaExec` task that calls `delombok` on Lombok's main class and simplifies the setup of such a task in the build process. It is not a ready to use task. Examples can be found at: [examples/delombok-gradle-groovy/build.gradle](examples/delombok-gradle-groovy/build.gradle) and
[examples/delombok-gradle-kotlin/build.gradle.kts](examples/delombok-gradle-kotlin/build.gradle.kts) ================================================ FILE: examples/.travis-run-examples.sh ================================================ #!/bin/bash function cleanup { cd $PLUGIN_BUILD_DIR } trap cleanup EXIT # Install JDK 11 cd $TRAVIS_BUILD_DIR wget -q https://github.com/sormuras/bach/raw/master/install-jdk.sh && chmod +x install-jdk.sh JAVA_HOME=~/jdk-11 && ./install-jdk.sh --feature 11 --target $JAVA_HOME && PATH=$JAVA_HOME/bin:$PATH # Run the examples cd examples ./gradlew build ================================================ FILE: examples/README.md ================================================ # Examples This folder contains examples on how to use Lombok with this Gradle plugin. ## hello-world Simple project demonstrating `@Data`, `@SneakyThrows` and `val`. Run it with: ./gradlew :hello-world:build ## delombok-gradle-groovy Demonstrates how the delombok task can be used to generate JavaDoc with Groovy as the Gradle script language. Run it with: ./gradlew :delombok-gradle-groovy:javadoc And open up [Greeting.html](delombok-gradle-groovy/build/docs/javadoc/com/example/Greeting.html) in your browser. ## delombok-gradle-kotlin Demonstrates how the delombok task can be used to generate JavaDoc with Kotlin as the Gradle script language. Run it with: ./gradlew :delombok-gradle-kotlin:javadoc And open up [Greeting.html](delombok-gradle-kotlin/build/docs/javadoc/com/example/Greeting.html) in your browser. ================================================ FILE: examples/build.gradle ================================================ buildscript { repositories { maven { url 'https://plugins.gradle.org/m2/' } } dependencies { classpath 'io.franzbecker:gradle-lombok:2.0' } } allprojects { repositories { jcenter() } } subprojects { apply plugin: 'java' apply plugin: 'io.franzbecker.gradle-lombok' dependencies { testCompile 'org.assertj:assertj-core:3.11.1' testCompile 'org.junit.jupiter:junit-jupiter-api:5.3.2' testCompile 'org.junit.jupiter:junit-jupiter-params:5.3.2' testRuntime 'org.junit.jupiter:junit-jupiter-engine:5.3.2' } test { useJUnitPlatform() testLogging { events "passed", "skipped", "failed" } } } ================================================ FILE: examples/delombok-gradle-groovy/build.gradle ================================================ import io.franzbecker.gradle.lombok.task.DelombokTask task delombok(type: DelombokTask, dependsOn: compileJava) { ext.outputDir = file("$buildDir/delombok") outputs.dir(outputDir) sourceSets.main.java.srcDirs.each { inputs.dir(it) args(it, "-d", outputDir) } doFirst { outputDir.deleteDir() } } javadoc { dependsOn delombok source = delombok.outputDir failOnError = false } ================================================ FILE: examples/delombok-gradle-groovy/src/main/java/com/example/Greeting.java ================================================ package com.example; import lombok.Data; @Data public class Greeting { private String message; } ================================================ FILE: examples/delombok-gradle-kotlin/build.gradle.kts ================================================ import io.franzbecker.gradle.lombok.task.DelombokTask tasks { val delombok by registering(DelombokTask::class) { dependsOn(compileJava) val outputDir by extra { file("$buildDir/delombok") } outputs.dir(outputDir) sourceSets["main"].java.srcDirs.forEach { inputs.dir(it) args(it, "-d", outputDir) } doFirst { outputDir.delete() } } javadoc { dependsOn(delombok) val outputDir: File by delombok.get().extra source = fileTree(outputDir) isFailOnError = false } } ================================================ FILE: examples/delombok-gradle-kotlin/src/main/java/com/example/Greeting.java ================================================ package com.example; import lombok.Data; @Data public class Greeting { private String message; } ================================================ FILE: examples/gradle/wrapper/gradle-wrapper.properties ================================================ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-all.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists ================================================ FILE: examples/gradlew ================================================ #!/usr/bin/env sh ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Attempt to set APP_HOME # Resolve links: $0 may be a link PRG="$0" # Need this for relative symlinks. while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done SAVED="`pwd`" cd "`dirname \"$PRG\"`/" >/dev/null APP_HOME="`pwd -P`" cd "$SAVED" >/dev/null APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m"' # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" warn () { echo "$*" } die () { echo echo "$*" echo exit 1 } # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD="java" which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add options to specify how the application appears in the dock if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi # For Cygwin, switch paths to Windows format before running java if $cygwin ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` JAVACMD=`cygpath --unix "$JAVACMD"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=$((i+1)) done case $i in (0) set -- ;; (1) set -- "$args0" ;; (2) set -- "$args0" "$args1" ;; (3) set -- "$args0" "$args1" "$args2" ;; (4) set -- "$args0" "$args1" "$args2" "$args3" ;; (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi # Escape application args save () { for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done echo " " } APP_ARGS=$(save "$@") # Collect all arguments for the java command, following the shell quoting and substitution rules eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then cd "$(dirname "$0")" fi exec "$JAVACMD" "$@" ================================================ FILE: examples/gradlew.bat ================================================ @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS="-Xmx64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto init echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto init echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :init @rem Get command-line arguments, handling Windows variants if not "%OS%" == "Windows_NT" goto win9xME_args :win9xME_args @rem Slurp the command line arguments. set CMD_LINE_ARGS= set _SKIP=2 :win9xME_args_slurp if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ================================================ FILE: examples/hello-world/src/main/java/com/example/Greeting.java ================================================ package com.example; import lombok.Data; @Data public class Greeting { private String message; } ================================================ FILE: examples/hello-world/src/main/java/com/example/HelloWorld.java ================================================ package com.example; import lombok.val; public class HelloWorld { public static void main(String[] args) { val greeting = new Greeting(); greeting.setMessage("Hello world!"); System.out.println(greeting.getMessage()); } } ================================================ FILE: examples/hello-world/src/main/java/com/example/SneakyHelloWorld.java ================================================ package com.example; import lombok.SneakyThrows; public class SneakyHelloWorld { @SneakyThrows() public byte[] throwingStuff() { return "test".getBytes("unsupported"); } } ================================================ FILE: examples/hello-world/src/test/java/com/example/GreetingTest.java ================================================ package com.example; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; class GreetingTest { @Test void canSetMessage() { // given Greeting greeting = new Greeting(); // when greeting.setMessage("test"); // then assertThat(greeting.getMessage()).isEqualTo("test"); } } ================================================ FILE: examples/hello-world/src/test/java/com/example/SneakyHelloWorldTest.java ================================================ package com.example; import lombok.val; import org.junit.jupiter.api.Test; import java.io.UnsupportedEncodingException; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; class SneakyHelloWorldTest { @Test void throwsException() { // given val sneaky = new SneakyHelloWorld(); // when + then assertThatExceptionOfType(UnsupportedEncodingException.class) .isThrownBy(() -> sneaky.throwingStuff()); } } ================================================ FILE: examples/settings.gradle ================================================ // this defines a composite build - you won't need this in your project includeBuild '../gradle-lombok-plugin' rootProject.name = 'examples' include 'hello-world' include 'delombok-gradle-groovy' include 'delombok-gradle-kotlin' ================================================ FILE: gradle-lombok-plugin/.travis-publishOnRelease.sh ================================================ #!/bin/bash # Execute only on tag builds where the tag starts with 'v' if [[ -n "$TRAVIS_TAG" && "$TRAVIS_TAG" == v* ]]; then echo "Publishing version: $TRAVIS_TAG" echo "gradle.publish.key=$GRADLE_PUBLISH_KEY" >> gradle.properties echo "gradle.publish.secret=$GRADLE_PUBLISH_SECRET" >> gradle.properties ./gradlew publishPlugins fi ================================================ FILE: gradle-lombok-plugin/build.gradle ================================================ plugins { id 'com.gradle.plugin-publish' version '0.11.0' id 'net.researchgate.release' version '2.8.1' id 'pl.droidsonroids.jacoco.testkit' version '1.0.3' // required until https://github.com/gradle/gradle/issues/1465 is resolved id 'java-gradle-plugin' id 'groovy' id 'maven' id 'jacoco' id 'maven-publish' } group 'io.franzbecker' sourceCompatibility = 1.8 targetCompatibility = 1.8 repositories { jcenter() } dependencies { testCompile 'junit:junit:4.12' testCompile gradleTestKit() testCompile 'com.netflix.nebula:nebula-test:6.1.2' } task sourcesJar(type: Jar, dependsOn: classes) { classifier 'sources' from sourceSets.main.allSource } artifacts { archives sourcesJar } jacoco { toolVersion = "0.8.3" } jacocoTestReport { reports { xml.enabled = true html.enabled = true } } check.dependsOn jacocoTestReport gradlePlugin { plugins { lombokPlugin { id = 'io.franzbecker.gradle-lombok' displayName = 'Gradle Lombok plugin' description = 'A gradle plugin that simplifies the usage of the Lombok annotation processor.' implementationClass = 'io.franzbecker.gradle.lombok.LombokPlugin' } } } pluginBundle { website = 'https://github.com/franzbecker/gradle-lombok' vcsUrl = 'https://github.com/franzbecker/gradle-lombok.git' tags = ['gradle', 'lombok'] plugins { lombokPlugin { id = 'io.franzbecker.gradle-lombok' } } mavenCoordinates { groupId = 'io.franzbecker' artifactId = 'gradle-lombok' } } task updateReadmeVersion { doLast { def versionPattern = /\d+.\d+(.\d+)?/ def encoding = 'UTF-8' File file = new File("../README.md") // String replacements - Readme isn't long enough to justify advanced code ;) String text = file.getText(encoding) text = text.replaceAll("gradle-lombok' version '${versionPattern}'", "gradle-lombok' version '${project.version}'") text = text.replaceAll("gradle-lombok/${versionPattern}", "gradle-lombok/${project.version}") file.setText(text, encoding) } } updateReadmeVersion.shouldRunAfter tasks.getByName('confirmReleaseVersion') /* * Configure release plugin. * Remove tasks "updateVersion" and "commitNewVersion" as we don't want the new SNAPSHOT * version commit on the master branch. */ tasks.release.tasks -= ["updateVersion", "commitNewVersion"] release { preTagCommitMessage = '[release] ' tagCommitMessage = '[release] ' tagTemplate = 'v${version}' } tasks.getByName('preTagCommit').dependsOn updateReadmeVersion publishing { publications { mavenJava(MavenPublication) { from components.java } } } ================================================ FILE: gradle-lombok-plugin/gradle/wrapper/gradle-wrapper.properties ================================================ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists ================================================ FILE: gradle-lombok-plugin/gradle.properties ================================================ version=5.0.0 ================================================ FILE: gradle-lombok-plugin/gradlew ================================================ #!/usr/bin/env sh ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Attempt to set APP_HOME # Resolve links: $0 may be a link PRG="$0" # Need this for relative symlinks. while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done SAVED="`pwd`" cd "`dirname \"$PRG\"`/" >/dev/null APP_HOME="`pwd -P`" cd "$SAVED" >/dev/null APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m"' # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" warn () { echo "$*" } die () { echo echo "$*" echo exit 1 } # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD="java" which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add options to specify how the application appears in the dock if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi # For Cygwin, switch paths to Windows format before running java if $cygwin ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` JAVACMD=`cygpath --unix "$JAVACMD"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=$((i+1)) done case $i in (0) set -- ;; (1) set -- "$args0" ;; (2) set -- "$args0" "$args1" ;; (3) set -- "$args0" "$args1" "$args2" ;; (4) set -- "$args0" "$args1" "$args2" "$args3" ;; (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi # Escape application args save () { for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done echo " " } APP_ARGS=$(save "$@") # Collect all arguments for the java command, following the shell quoting and substitution rules eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then cd "$(dirname "$0")" fi exec "$JAVACMD" "$@" ================================================ FILE: gradle-lombok-plugin/gradlew.bat ================================================ @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS="-Xmx64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto init echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto init echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :init @rem Get command-line arguments, handling Windows variants if not "%OS%" == "Windows_NT" goto win9xME_args :win9xME_args @rem Slurp the command line arguments. set CMD_LINE_ARGS= set _SKIP=2 :win9xME_args_slurp if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ================================================ FILE: gradle-lombok-plugin/settings.gradle ================================================ rootProject.name = 'gradle-lombok' ================================================ FILE: gradle-lombok-plugin/src/main/groovy/io/franzbecker/gradle/lombok/LombokPlugin.groovy ================================================ package io.franzbecker.gradle.lombok import io.franzbecker.gradle.lombok.task.InstallLombokTask import io.franzbecker.gradle.lombok.task.VerifyLombokTask import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.plugins.JavaPlugin import org.gradle.util.GradleVersion import static org.gradle.api.plugins.JavaPlugin.* /** * Plugin for project Lombok support. * * The main responsibility is to add Lombok as a "provided" dependency which is * only required during compilation and should not leave any trace on the resulting artifact. * * Furthermore, this plugin provides support for easy installation of Lombok into the IDE. * For this purpose, it verifies the JAR it adds as dependency (using its SHA-256 hash) and * the invokes it in order to call the default Lombok UI. * * @see https://projectlombok.org */ class LombokPlugin implements Plugin { static final String NAME = "io.franzbecker.gradle-lombok" static final String LOMBOK_CONFIGURATION_NAME = COMPILE_ONLY_CONFIGURATION_NAME static final String VERIFY_LOMBOK_CLASSPATH_CONFIGURATION_NAME = COMPILE_CLASSPATH_CONFIGURATION_NAME @Override void apply(Project project) { project.extensions.create(LombokPluginExtension.NAME, LombokPluginExtension) project.plugins.withType(JavaPlugin) { project.afterEvaluate { addLombokDependency(project) } configureTasks(project) } } private void addLombokDependency(Project project) { addLombokDependency(project, COMPILE_ONLY_CONFIGURATION_NAME) addLombokDependency(project, TEST_COMPILE_ONLY_CONFIGURATION_NAME) boolean atLeastGradle4_6 = GradleVersion.version(project.gradle.gradleVersion) >= GradleVersion.version('4.6') if (atLeastGradle4_6) { addLombokDependency(project, ANNOTATION_PROCESSOR_CONFIGURATION_NAME) addLombokDependency(project, TEST_ANNOTATION_PROCESSOR_CONFIGURATION_NAME) } } private void addLombokDependency(Project project, String configurationName) { project.dependencies.add( configurationName, "org.projectlombok:lombok:${project.lombok.version}", { transitive = false } ) } /** * Adds {@link VerifyLombokTask} and {@link InstallLombokTask} and lets installLombok * depend on verifyLombok. */ private void configureTasks(Project project) { def extension = project.extensions.findByType(LombokPluginExtension) // Add VerifyLombokTask def verifyLombok = project.task(type: VerifyLombokTask, VerifyLombokTask.NAME) verifyLombok.outputs.upToDateWhen { !extension.sha256 } // Add InstallLombokTask project.task(type: InstallLombokTask, InstallLombokTask.NAME).with { outputs.upToDateWhen { false } dependsOn verifyLombok group = "IDE" } } } ================================================ FILE: gradle-lombok-plugin/src/main/groovy/io/franzbecker/gradle/lombok/LombokPluginExtension.groovy ================================================ package io.franzbecker.gradle.lombok /** * Configuration for the plugin. */ class LombokPluginExtension { static final String NAME = "lombok" static final String DEFAULT_VERSION = "1.18.12" static final String DEFAULT_VERSION_HASH = "49381508ecb02b3c173368436ef71b24c0d4418ad260e6cc98becbcf4b345406" /** The version of Lombok to use. */ String version = DEFAULT_VERSION /** The SHA-256 hash of the JAR. */ String sha256 = DEFAULT_VERSION_HASH /** The main class to call when invoking {@linkplain InstallLombokTask#NAME}. */ String main = "lombok.launch.Main" } ================================================ FILE: gradle-lombok-plugin/src/main/groovy/io/franzbecker/gradle/lombok/task/DelombokTask.groovy ================================================ package io.franzbecker.gradle.lombok.task import io.franzbecker.gradle.lombok.LombokPluginExtension import org.gradle.api.Task import org.gradle.api.plugins.JavaPlugin import org.gradle.api.tasks.Input import org.gradle.api.tasks.JavaExec /** * Task type for delomboking. Not added to the project by default, * has to be instantiated and configured in the using gradle build. */ class DelombokTask extends JavaExec { @Input String compileConfigurationName = JavaPlugin.COMPILE_CLASSPATH_CONFIGURATION_NAME DelombokTask() { super() args "delombok" } @Override Task configure(Closure closure) { setMain(project.extensions.findByType(LombokPluginExtension).main) return super.configure(closure) } @Override void exec() { classpath(project.configurations.getByName(compileConfigurationName)) super.exec() } } ================================================ FILE: gradle-lombok-plugin/src/main/groovy/io/franzbecker/gradle/lombok/task/InstallLombokTask.groovy ================================================ package io.franzbecker.gradle.lombok.task import io.franzbecker.gradle.lombok.LombokPlugin import io.franzbecker.gradle.lombok.LombokPluginExtension import org.gradle.api.Task import org.gradle.api.tasks.JavaExec /** * Invokes the Lombok UI so that the user can install it into the IDE. */ class InstallLombokTask extends JavaExec { static final String NAME = "installLombok" @Override Task configure(Closure closure) { setMain(project.extensions.findByType(LombokPluginExtension).main) return super.configure(closure) } @Override void exec() { // Configure JavaExec setIgnoreExitValue(true) setClasspath(project.configurations.getByName(LombokPlugin.LOMBOK_CONFIGURATION_NAME)) super.exec() } } ================================================ FILE: gradle-lombok-plugin/src/main/groovy/io/franzbecker/gradle/lombok/task/VerifyLombokTask.groovy ================================================ package io.franzbecker.gradle.lombok.task import io.franzbecker.gradle.lombok.LombokPlugin import io.franzbecker.gradle.lombok.LombokPluginExtension import io.franzbecker.gradle.lombok.util.HashUtil import org.gradle.api.DefaultTask import org.gradle.api.artifacts.Configuration import org.gradle.api.resources.ResourceException import org.gradle.api.tasks.Internal import org.gradle.api.tasks.TaskAction /** * Task that verifies the integrity of the Lombok dependency. */ class VerifyLombokTask extends DefaultTask { static final String NAME = "verifyLombok" @Internal HashUtil hashUtil = new HashUtil() @TaskAction void verifyLombok() { // Retrieve extension and configuration def extension = project.extensions.findByType(LombokPluginExtension) def configuration = project.configurations.getByName(LombokPlugin.VERIFY_LOMBOK_CLASSPATH_CONFIGURATION_NAME) verifyLombok(extension, configuration) } protected verifyLombok(LombokPluginExtension extension, Configuration configuration) { if (extension.sha256) { // Lookup JAR and verify it def lombokJar = getLombokJar(extension.version, configuration) verifyIntegrity(extension.sha256, lombokJar) } else { logger.info("Skipping verification of Lombok since SHA-256 was not configured.") } } /** * Retrieves the JAR from the dependencies. * * @throws org.gradle.api.resources.ResourceException if the JAR cannot be resolved */ protected File getLombokJar(String lombokVersion, Configuration configuration) { // Retrieve file def lombokFileName = "lombok-${lombokVersion}.jar" logger.debug("Searching for '${lombokFileName}' in dependencies of configuration '${configuration.name}'.") def lombokJar = configuration.files.find { File file -> file.name == lombokFileName } if (!lombokJar) { throw new ResourceException("Could not find '${lombokFileName}' in dependencies of configuration '${configuration.name}'.") } logger.debug("Found '${lombokJar}'.") return lombokJar } /** * Verifies the hash code of the passed file as configured. */ protected void verifyIntegrity(String expectedSha256, File lombokJar) { def actualSha256 = hashUtil.calculateSha256(lombokJar) if (expectedSha256 != actualSha256) { def message = """\ Verification of Lombok JAR failed! Local JAR file: ${lombokJar} Expected checksum: ${expectedSha256} Actual checksum: ${actualSha256} """.stripIndent() throw new ResourceException(message) } logger.debug("Calculates matching hash '${actualSha256}' for '${lombokJar}'.") } } ================================================ FILE: gradle-lombok-plugin/src/main/java/io/franzbecker/gradle/lombok/util/HashUtil.java ================================================ package io.franzbecker.gradle.lombok.util; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * Calculate SHA-256 hash for a given file. *

* Gradle supports only an internal API for this (@link{org.gradle.internal.hash.HashUtil}). */ public class HashUtil { /** * Calculates the SHA-256 to a given file. * * @param file the file * @return the SHA-256 */ public String calculateSha256(File file) { try (RandomAccessFile inputStream = new RandomAccessFile(file, "r"); FileChannel channel = inputStream.getChannel()) { // Calculate SHA-256 MessageDigest sha256 = MessageDigest.getInstance("SHA-256"); MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size()); sha256.update(buffer); // Convert to String byte digest[] = sha256.digest(); StringBuilder result = new StringBuilder(); for (int i = 0; i < digest.length; i++) { String hex = Integer.toHexString(0xff & digest[i]); if (hex.length() == 1) { result.append('0'); } result.append(hex); } return result.toString(); } catch (NoSuchAlgorithmException | IOException e) { throw new RuntimeException("Could not calculate SHA-256 hash of file: " + file, e); } } } ================================================ FILE: gradle-lombok-plugin/src/main/resources/META-INF/gradle-plugins/io.franzbecker.gradle-lombok.properties ================================================ implementation-class=io.franzbecker.gradle.lombok.LombokPlugin ================================================ FILE: gradle-lombok-plugin/src/test/groovy/io/franzbecker/gradle/lombok/AbstractIntegrationTest.groovy ================================================ package io.franzbecker.gradle.lombok import org.gradle.testkit.runner.BuildResult import org.gradle.testkit.runner.GradleRunner import org.gradle.testkit.runner.TaskOutcome import org.junit.Rule import org.junit.rules.TemporaryFolder import spock.lang.Specification /** * Abstract base class for integration tests. */ abstract class AbstractIntegrationTest extends Specification { @Rule TemporaryFolder testProjectDir File projectDir File buildFile File propertiesFile def setup() { projectDir = testProjectDir.root buildFile = createFile('build.gradle') writeDefaultBuildFileContents() propertiesFile = createFile('gradle.properties') configureJacoco() } protected void writeDefaultBuildFileContents() { buildFile << """\ plugins { id 'java' id '${LombokPlugin.NAME}' } repositories { jcenter() } """.stripIndent() } /** see https://github.com/koral--/jacoco-gradle-testkit-plugin */ private void configureJacoco() { propertiesFile << this.class.classLoader.getResourceAsStream('testkit-gradle.properties') } protected GradleRunner createGradleRunner() { def runner = GradleRunner.create() .withPluginClasspath() .withProjectDir(projectDir) return runner } BuildResult runBuild(String... arguments) { def runner = createGradleRunner() return runner.withArguments(arguments).build() } BuildResult runBuildAndFail(String... arguments) { def runner = createGradleRunner() return runner.withArguments(arguments).buildAndFail() } BuildResult runTaskAndFail(String task) { def result = runBuildAndFail(task) def buildTask = result.getTasks().first() assert buildTask.path == ":$task" assert buildTask.outcome == TaskOutcome.FAILED return result } File createFile(String path) { File file = new File(projectDir, path) file.getParentFile().mkdirs() file.createNewFile() return file } protected void createSimpleTestCase() { createSimpleTestCase("testCompile") } protected void createSimpleTestCase(String testConfigurationName) { // build configuration supporting JUnit buildFile << """ dependencies { ${testConfigurationName} 'junit:junit:4.12' } """.stripIndent() // source code to compile and test createJavaSource() createTestSource() } private void createJavaSource() { def file = createFile("src/main/java/com/example/HelloWorld.java") file << """\ package com.example; import lombok.Data; @Data public class HelloWorld { private String id; } """.stripIndent() } private void createTestSource() { def file = createFile("src/test/java/com/example/HelloWorldTest.java") file << """\ package com.example; import java.util.UUID; import org.junit.Test; import org.junit.Assert; public class HelloWorldTest { @Test public void testHelloWorld() { // Given HelloWorld obj = new HelloWorld(); String id = UUID.randomUUID().toString(); // When obj.setId(id); // Then Assert.assertEquals(id, obj.getId()); } } """.stripIndent() } } ================================================ FILE: gradle-lombok-plugin/src/test/groovy/io/franzbecker/gradle/lombok/CompatibilityIntegrationTest.groovy ================================================ package io.franzbecker.gradle.lombok import org.gradle.testkit.runner.GradleRunner import spock.lang.Unroll @Unroll class CompatibilityIntegrationTest extends AbstractIntegrationTest { String theGradleVersion @Override protected GradleRunner createGradleRunner() { def runner = super.createGradleRunner() return runner.withGradleVersion(theGradleVersion) } def "Gradle #gradleVersion - can compile and test @Data annotation"() { given: theGradleVersion = gradleVersion createSimpleTestCase(testConfigurationName) when: "calling gradle test" runBuild('test') then: "build is successful and both class file exist" noExceptionThrown() new File(projectDir, "$classesPath/main/com/example/HelloWorld.class").exists() new File(projectDir, "$classesPath/test/com/example/HelloWorldTest.class").exists() where: gradleVersion || classesPath || testConfigurationName '2.12' || 'build/classes' || 'testCompile' '2.14.1' || 'build/classes' || 'testCompile' '3.5' || 'build/classes' || 'testCompile' '4.2.1' || 'build/classes/java' || 'testCompile' '4.7' || 'build/classes/java' || 'testCompile' '5.4' || 'build/classes/java' || 'testCompile' '6.4' || 'build/classes/java' || 'testCompile' '6.4' || 'build/classes/java' || 'testImplementation' '7.0' || 'build/classes/java' || 'testImplementation' } def "Gradle #gradleVersion - can run verifyLombok"() { given: theGradleVersion = gradleVersion createSimpleTestCase(testConfigurationName) when: "calling gradle verifyLombok" runBuild('verifyLombok') then: "no exception is thrown" noExceptionThrown() where: gradleVersion || classesPath || testConfigurationName '2.12' || 'build/classes' || 'testCompile' '2.14.1' || 'build/classes' || 'testCompile' '3.5' || 'build/classes' || 'testCompile' '4.2.1' || 'build/classes/java' || 'testCompile' '4.7' || 'build/classes/java' || 'testCompile' '5.4' || 'build/classes/java' || 'testCompile' '6.4' || 'build/classes/java' || 'testCompile' '7.0' || 'build/classes/java' || 'testImplementation' } } ================================================ FILE: gradle-lombok-plugin/src/test/groovy/io/franzbecker/gradle/lombok/LombokPluginIntegrationTest.groovy ================================================ package io.franzbecker.gradle.lombok import groovy.util.slurpersupport.GPathResult /** * Integration tests for {@link LombokPlugin}. */ class LombokPluginIntegrationTest extends AbstractIntegrationTest { /** * Creates a Java class with a method annotated with @SneakyThrows and tests if the * annotation is applied properly. */ def "Can compile and test code with @SneakyThrows annotation."() { given: "a valid build configuration" buildFile << """ dependencies { testCompile 'junit:junit:4.12' } """.stripIndent() and: "source code with @SneakyThrows to compile and test" createSneakyThrowsJavaSource() createSneakyThrowsTestCode() when: "calling gradle test" runBuild('test') then: "build is successful and both class file exist" noExceptionThrown() new File(projectDir, "build/classes/java/main/com/example/SneakyHelloWorld.class").exists() new File(projectDir, "build/classes/java/test/com/example/SneakyHelloWorldTest.class").exists() } def "Can compile test code with Lombok depenceny"() { given: buildFile << """ dependencies { testCompile 'junit:junit:4.12' } """.stripIndent() and: createTestCodeWithLombokDependency() when: runBuild('test') then: noExceptionThrown() new File(projectDir, "build/classes/java/test/com/example/SneakyHelloWorldTest.class").exists() } def "Works with the java-library plugin"() { given: buildFile.text = buildFile.text.replace("id 'java'", "id 'java-library'") createSimpleTestCase() when: runBuild('test') then: noExceptionThrown() new File(projectDir, "build/classes/java/main/com/example/HelloWorld.class").exists() new File(projectDir, "build/classes/java/test/com/example/HelloWorldTest.class").exists() } def "Dependency does not occur in generated POM using the 'maven' plugin"() { given: "a valid build configuration" buildFile << """ apply plugin: 'maven' dependencies { testCompile 'junit:junit:4.12' } """.stripIndent() when: "calling gradle install" runBuild('install') then: "Parse POM and retrieve object" def parsedXml = findAndParsePom("build/poms/pom-default.xml") def dependencies = parsedXml.dependencies assert dependencies.size() == 1 assert dependencies.dependency.find { it.artifactId.text() == 'junit' } assert !dependencies.dependency.find { it.artifactId.text() == 'lombok' } } def "Dependency does not occur in generated POM using the 'maven-publish' plugin"() { given: buildFile << ''' apply plugin: 'maven-publish' dependencies { compile 'javax.inject:javax.inject:1' } publishing { publications { mavenJava(MavenPublication) { from components.java } } } model { tasks.generatePomFileForMavenJavaPublication { destination = file("$buildDir/generated-pom.xml") } } '''.stripIndent() when: runBuild('generatePomFileForMavenJavaPublication') then: def parsedXml = findAndParsePom("build/generated-pom.xml") def dependencies = parsedXml.dependencies assert dependencies.size() == 1 assert dependencies.dependency.find { it.artifactId.text() == 'javax.inject' } assert !dependencies.dependency.find { it.artifactId.text() == 'lombok' } } private GPathResult findAndParsePom(String path) { def pom = new File(projectDir, path) assert pom.exists() return new XmlSlurper().parseText(pom.text) } /** * Verifies that the Lombok dependency is on the Eclipse classpath. */ def "Lombok dependency is on Eclipse classpath"() { given: buildFile << """ apply plugin: 'eclipse' """.stripIndent() when: runBuild('eclipse') then: "verify that the .classpath file exists" def dotClasspath = new File(projectDir, ".classpath") dotClasspath.exists() and: "verify the lombok JAR is included" def classpath = new XmlSlurper().parse(dotClasspath) def lombokEntry = classpath.classpathentry.find { node -> node.@kind == "lib" && node.@path.text().contains("lombok-${LombokPluginExtension.DEFAULT_VERSION}.jar") } assert lombokEntry } /** * Verifies that the Lombok dependency is on the IntelliJ classpath. */ def "Lombok dependency is on IntelliJ classpath"() { given: buildFile << """ apply plugin: 'idea' """.stripIndent() when: runBuild('idea') then: "verify that the .iml file exists" File imlFile = getImlFile() and: "verify the lombok JAR is included" def module = new XmlSlurper().parse(imlFile) def provided = module.component.orderEntry.find { it.@type == "module-library" } assert provided def lombokEntry = provided.library.CLASSES.root.find { it.@url.text().contains("lombok-${LombokPluginExtension.DEFAULT_VERSION}.jar") } assert lombokEntry } private File getImlFile() { FilenameFilter filter = { dir, name -> name.endsWith(".iml") } File[] imlFiles = projectDir.listFiles(filter) assert imlFiles.size() == 1 return imlFiles[0] } private void createSneakyThrowsJavaSource() { def file = createFile("src/main/java/com/example/SneakyHelloWorld.java") file << """ package com.example; import lombok.SneakyThrows; import java.io.UnsupportedEncodingException; // checked exception public class SneakyHelloWorld { @SneakyThrows(UnsupportedEncodingException.class) public byte[] throwingStuff() { return "test".getBytes("unsupported"); } } """.stripIndent() } private void createSneakyThrowsTestCode() { def file = createFile("src/test/java/com/example/SneakyHelloWorldTest.java") file << """ package com.example; import org.junit.Assert; import org.junit.Test; import java.io.UnsupportedEncodingException; public class SneakyHelloWorldTest { @Test(expected = UnsupportedEncodingException.class) public void testThrowingStuff() { SneakyHelloWorld instance = new SneakyHelloWorld(); instance.throwingStuff(); } } """.stripIndent() } private void createTestCodeWithLombokDependency() { def file = createFile("src/test/java/com/example/SneakyHelloWorldTest.java") file << ''' package com.example; import org.junit.Assert; import org.junit.Test; import lombok.SneakyThrows; import java.io.UnsupportedEncodingException; public class SneakyHelloWorldTest { @Test(expected = UnsupportedEncodingException.class) @SneakyThrows public void testThrowingStuff() { "test".getBytes("unsupported"); } } '''.stripIndent() } } ================================================ FILE: gradle-lombok-plugin/src/test/groovy/io/franzbecker/gradle/lombok/LombokPluginSpec.groovy ================================================ package io.franzbecker.gradle.lombok import io.franzbecker.gradle.lombok.task.InstallLombokTask import io.franzbecker.gradle.lombok.task.VerifyLombokTask import nebula.test.PluginProjectSpec /** * Unit tests for {@link LombokPlugin}. */ class LombokPluginSpec extends PluginProjectSpec { @Override String getPluginName() { return LombokPlugin.NAME } private def applyJavaAndLombok() { project.apply plugin: "java" project.apply plugin: pluginName } def "Does not create new tasks if Java plugin is not applied"() { given: def beforeTaskMap = project.tasks.getAsMap().collect() when: project.apply plugin: pluginName then: def afterTaskMap = project.tasks.getAsMap().collect() assert afterTaskMap == beforeTaskMap } def "Does not add Lombok configuration if Java plugin is not applied"() { when: project.apply plugin: pluginName then: assert !project.configurations.findByName(LombokPlugin.LOMBOK_CONFIGURATION_NAME) } def "Add Lombok configuration if Java plugin is applied"() { when: applyJavaAndLombok() then: assert project.configurations.findByName(LombokPlugin.LOMBOK_CONFIGURATION_NAME) } def "Lombok dependency is added"() { when: applyJavaAndLombok() project.evaluate() then: def lombokConfiguration = project.configurations.findByName(LombokPlugin.LOMBOK_CONFIGURATION_NAME) def dependency = lombokConfiguration.getDependencies().first() dependency.group == "org.projectlombok" dependency.name == "lombok" } def "Added dependencies are not transitive"() { when: applyJavaAndLombok() project.evaluate() then: def lombokConfiguration = project.configurations.findByName(LombokPlugin.LOMBOK_CONFIGURATION_NAME) lombokConfiguration.getDependencies().each { assert !it.isTransitive() } } def "Add tasks if Java plugin is applied and installLombok depends on verifyLombok"() { when: applyJavaAndLombok() then: VerifyLombokTask verifyLombok = project.tasks[VerifyLombokTask.NAME] InstallLombokTask installLombok = project.tasks[InstallLombokTask.NAME] verifyLombok in installLombok.getDependsOn() installLombok.group == "IDE" } } ================================================ FILE: gradle-lombok-plugin/src/test/groovy/io/franzbecker/gradle/lombok/task/AbstractJavaExecTaskSpec.groovy ================================================ package io.franzbecker.gradle.lombok.task import io.franzbecker.gradle.lombok.LombokPlugin import org.gradle.api.Project import org.gradle.api.artifacts.Configuration import org.gradle.api.tasks.JavaExec import org.gradle.process.internal.JavaExecAction import org.gradle.testfixtures.ProjectBuilder import spock.lang.Specification /** * Base class for unit testing tasks of type JavaExec. */ abstract class AbstractJavaExecTaskSpec extends Specification { Project project void setup() { project = ProjectBuilder.builder().build() project.apply plugin: 'java' project.apply plugin: LombokPlugin.NAME } /** * Sets the private field "javaExecHandleBuilder" of the passed task * to a mock and returns that mock. * * @param task the task * @return the mock */ JavaExecAction mockJavaExecAction(JavaExec task) { JavaExecAction execAction = Mock() def field = JavaExec.getDeclaredField("javaExecHandleBuilder") field.accessible = true field.set(task, execAction) return execAction } } ================================================ FILE: gradle-lombok-plugin/src/test/groovy/io/franzbecker/gradle/lombok/task/DelombokTaskIntegrationTest.groovy ================================================ package io.franzbecker.gradle.lombok.task import io.franzbecker.gradle.lombok.AbstractIntegrationTest /** * Integration tests for {@link DelombokTask}. */ class DelombokTaskIntegrationTest extends AbstractIntegrationTest { def "Calling delombok with --help throws no exception."() { given: buildFile << """ import io.franzbecker.gradle.lombok.task.DelombokTask task delombokHelp(type: DelombokTask) { args "--help" } """.stripIndent() when: runBuild("delombokHelp") then: noExceptionThrown() } def "Delombok on directory produced proper output"() { given: createSourceForDelombok() and: buildFile << """ dependencies { implementation 'org.slf4j:slf4j-api:1.7.12' } ${delombokTask()} """.stripIndent() when: runBuild("delombok") then: File file = new File(projectDir, "build/delombok/com/example/HelloWorld.java") file.exists() String contents = file.text !contents.contains("import lombok.Data") contents.contains("// Generated by delombok") contents.contains("public String getId() {") } def "Delombok classpath can be extended"() { given: def testFile = createFile("src/main/java/com/example/Example.java") testFile << """ package com.example; import com.google.common.annotations.VisibleForTesting; public class Example { @VisibleForTesting protected void doSomething() { } } """.stripIndent() and: buildFile << """ dependencies { // TODO this doesn't make sense any more compileOnly "com.google.guava:guava:20.0" // 20.0 for Java 7 support } ${delombokTask("classpath += project.configurations.compileOnly")} """ when: runBuild("delombok") then: File file = new File(projectDir, "build/delombok/com/example/Example.java") file.exists() } private void createSourceForDelombok() { def file = createFile("src/main/java/com/example/HelloWorld.java") file << """ package com.example; import lombok.Data; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Data public class HelloWorld { private static final Logger logger = LoggerFactory.getLogger(HelloWorld.class); private String id; } """.stripIndent() } private String delombokTask(String additionalConfig = "") { return """ import io.franzbecker.gradle.lombok.task.DelombokTask task delombok(type: DelombokTask, dependsOn: compileJava) { ext.outputDir = file("\$buildDir/delombok") outputs.dir(outputDir) sourceSets.main.java.srcDirs.each { inputs.dir(it) args(it, "-d", outputDir) } $additionalConfig // Redirect the output of the process standardOutput = new ByteArrayOutputStream() errorOutput = new ByteArrayOutputStream() doLast { // Fail the build if there was any error output if (!errorOutput.toString().isEmpty()) { throw new GradleException(errorOutput.toString()) } } } """ } } ================================================ FILE: gradle-lombok-plugin/src/test/groovy/io/franzbecker/gradle/lombok/task/DelombokTaskSpec.groovy ================================================ package io.franzbecker.gradle.lombok.task import org.gradle.api.plugins.JavaPlugin /** * Unit tests for {@link DelombokTask}. */ class DelombokTaskSpec extends AbstractJavaExecTaskSpec { def "delombok calls JavaExec"() { given: "a newly created DelombokTask" def task = project.task(type: DelombokTask, "delombok") def execAction = mockJavaExecAction(task) def expectedClasspath = project.configurations.getByName(JavaPlugin.COMPILE_CLASSPATH_CONFIGURATION_NAME) when: "task executes" task.configure {} task.exec() then: "Delombok main is called" 1 * execAction.setMain('lombok.launch.Main') 1 * execAction.classpath(expectedClasspath) 1 * execAction.execute() } def "delombok argument is set"() { when: def task = project.task(type: DelombokTask, "delombok") then: "delombok" in task.args } } ================================================ FILE: gradle-lombok-plugin/src/test/groovy/io/franzbecker/gradle/lombok/task/InstallLombokTaskSpec.groovy ================================================ package io.franzbecker.gradle.lombok.task import io.franzbecker.gradle.lombok.LombokPlugin /** * Unit tests for {@link InstallLombokTask}. */ class InstallLombokTaskSpec extends AbstractJavaExecTaskSpec { def "installLombok calls JavaExec properly"() { given: InstallLombokTask task = project.tasks.getByName(InstallLombokTask.NAME) def execAction = mockJavaExecAction(task) def expectedClasspath = project.configurations.getByName(LombokPlugin.LOMBOK_CONFIGURATION_NAME) when: task.configure {} task.exec() then: 1 * execAction.setMain('lombok.launch.Main') 1 * execAction.setIgnoreExitValue(true) 1 * execAction.setClasspath(expectedClasspath) 1 * execAction.execute() } } ================================================ FILE: gradle-lombok-plugin/src/test/groovy/io/franzbecker/gradle/lombok/task/VerifyLombokTaskIntegrationTest.groovy ================================================ package io.franzbecker.gradle.lombok.task import io.franzbecker.gradle.lombok.AbstractIntegrationTest import org.gradle.testkit.runner.TaskOutcome /** * Integration tests for {@link VerifyLombokTask}. */ class VerifyLombokTaskIntegrationTest extends AbstractIntegrationTest { def "Task succeeds if hash is valid"() { given: "a properly configured hash" buildFile << """ lombok { version = "1.16.4" sha256 = "3ca225ce3917eac8bf4b7d2186845df4e70dcdede356dca8537b6d78a535c91e" } """.stripIndent() when: "invoking the task" runBuild(VerifyLombokTask.NAME) then: "task succeeded without exception" noExceptionThrown() } def "Task succeeds with the default configuration"() { when: "invoking the task" runBuild(VerifyLombokTask.NAME) then: "task succeeded without exception" noExceptionThrown() } def "Task succeeds with non-default Lombok version"() { given: "a properly configured hash" buildFile << """ lombok { version = "1.16.6" sha256 = "e0a471be03e1e6b02bf019480cec7a3ac9801702bf7bf62f15d077ad4df8dd5d" } """.stripIndent() when: "invoking the task" runBuild(VerifyLombokTask.NAME) then: "task succeeded without exception" noExceptionThrown() } def "Task fails if hash is invalid"() { given: "a badly configured hash" buildFile << """ lombok { version = "1.16.4" sha256 = "wrongHash" } """.stripIndent() when: "invoking the task" def result = runTaskAndFail(VerifyLombokTask.NAME) then: "expect a failure" result.output.contains("Expected checksum: wrongHash") } def "Task succeeds if hash is null"() { given: "an unset hash" buildFile << """ lombok { version = "1.16.4" sha256 = null } """.stripIndent() when: "invoking the task" runBuild(VerifyLombokTask.NAME) then: "task succeeded without exception" noExceptionThrown() } def "Task succeeds if hash is empty"() { given: "an unset hash" buildFile << """ lombok { version = "1.16.4" sha256 = "" } """.stripIndent() when: "invoking the task" runBuild(VerifyLombokTask.NAME) then: "task succeeded without exception" noExceptionThrown() } def "Task is up-to-date when hash is empty"() { given: "an unset hash" buildFile << """ lombok { version = "1.16.4" sha256 = "" } """.stripIndent() when: "invoking the task two times" // there is no build history on the first run, so it is never up-to-date runBuild(VerifyLombokTask.NAME) def result = runBuild(VerifyLombokTask.NAME) then: "second run was up-to-date" result.tasks(TaskOutcome.UP_TO_DATE).first().path == ":$VerifyLombokTask.NAME" } def "Task is never up-to-date when hash is set"() { given: "a properly configured hash" buildFile << """ lombok { version = "1.16.4" sha256 = "3ca225ce3917eac8bf4b7d2186845df4e70dcdede356dca8537b6d78a535c91e" } """.stripIndent() when: "invoking the task multiple times" def result1 = runBuild(VerifyLombokTask.NAME) def result2 = runBuild(VerifyLombokTask.NAME) then: "both runs were not up-to-date" result1.tasks(TaskOutcome.UP_TO_DATE).empty result2.tasks(TaskOutcome.UP_TO_DATE).empty } } ================================================ FILE: gradle-lombok-plugin/src/test/groovy/io/franzbecker/gradle/lombok/task/VerifyLombokTaskSpec.groovy ================================================ package io.franzbecker.gradle.lombok.task import io.franzbecker.gradle.lombok.LombokPlugin import io.franzbecker.gradle.lombok.LombokPluginExtension import io.franzbecker.gradle.lombok.util.HashUtilSpec import org.gradle.api.GradleException import org.gradle.api.Project import org.gradle.api.artifacts.Configuration import org.gradle.testfixtures.ProjectBuilder import spock.lang.Specification /** * Unit tests for {@link VerifyLombokTask}. */ class VerifyLombokTaskSpec extends Specification { VerifyLombokTask task Configuration configuration = Mock() /** * Perform a minimal project setup that lets us retrieve the task. */ void setup() { Project project = ProjectBuilder.builder().build() project.apply plugin: 'java' project.apply plugin: LombokPlugin.NAME task = project.tasks.getByName(VerifyLombokTask.NAME) configuration.iterator() >> Mock(Iterator) configuration.getName() >> LombokPlugin.VERIFY_LOMBOK_CLASSPATH_CONFIGURATION_NAME } def "Fails if Lombok JAR is not found"() { given: def version = "1.16.4" when: task.getLombokJar(version, configuration) then: GradleException e = thrown() e.message == "Could not find 'lombok-${version}.jar' in dependencies of configuration 'compileClasspath'." } def "Does not fail if file integrity is fulfilled"() { given: def file = new File(getClass().getClassLoader().getResource("dummy.txt").path) assert file.exists() when: task.verifyIntegrity(HashUtilSpec.DUMMY_TXT_HASH, file) then: noExceptionThrown() } def "Fails if file integrity is not fulfilled"() { given: def file = new File(getClass().getClassLoader().getResource("dummy.txt").path) assert file.exists() when: task.verifyIntegrity("wrongHash", file) then: GradleException e = thrown() e.message.contains("Expected checksum: wrongHash") e.message.contains("Actual checksum: ${HashUtilSpec.DUMMY_TXT_HASH}") } def "Skips the check if no hash has been configured"() { given: def extension = new LombokPluginExtension() extension.sha256 = '' when: task.verifyLombok(extension, configuration) then: noExceptionThrown() } } ================================================ FILE: gradle-lombok-plugin/src/test/groovy/io/franzbecker/gradle/lombok/util/HashUtilSpec.groovy ================================================ package io.franzbecker.gradle.lombok.util import spock.lang.Specification /** * Simple test for {@link HashUtil}. */ class HashUtilSpec extends Specification { static final DUMMY_TXT_HASH = "c626d18d337f2937a83bf82581e8b22796f345736f94a2ed60b0294b4705c203" HashUtil hashUtil = new HashUtil() def "Calculates dummy.txt hash correctly"() { given: def file = new File(getClass().getClassLoader().getResource("dummy.txt").path) assert file.exists() when: def hash = hashUtil.calculateSha256(file) then: hash == DUMMY_TXT_HASH } def "Throws RuntimeException if file is not found"() { given: def file = new File("unknown") assert !file.exists() when: hashUtil.calculateSha256(file) then: thrown(RuntimeException) } } ================================================ FILE: gradle-lombok-plugin/src/test/resources/dummy.txt ================================================ This is a file with a known SHA-256 hash. ================================================ FILE: gradle-lombok-plugin/update-lombok.sh ================================================ #!/bin/bash wget https://projectlombok.org/downloads/lombok.jar version=$( java -jar lombok.jar --version | sed -n 's/v\([0-9\.]*\).*/\1/p' ) hash=$( shasum -a 256 lombok.jar | cut -d ' ' -f 1 ) echo "Updating to Lombok $version with hash: $hash" sed -i '' -e "s/\(DEFAULT_VERSION = \"\)[0-9\.]*/\1$version/g" src/main/groovy/io/franzbecker/gradle/lombok/LombokPluginExtension.groovy sed -i '' -e "s/\(DEFAULT_VERSION_HASH = \"\)[^\"]*/\1$hash/g" src/main/groovy/io/franzbecker/gradle/lombok/LombokPluginExtension.groovy sed -i '' -e "s/\(version = \"\)[0-9\.]*/\1$version/g" ../README.md sed -i '' -e "s/\(sha256 = \"\)[^\"][^\"]*/\1$hash/g" ../README.md git add src/main/groovy/io/franzbecker/gradle/lombok/LombokPluginExtension.groovy git add ../README.md git commit -m "Update the default Lombok version to $version" rm lombok.jar