diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..40e2383 --- /dev/null +++ b/.gitignore @@ -0,0 +1,16 @@ +# Gradle +.gradle/ + +# generated files +build/ +out/ +local.properties + +# Mac +.DS_Store + +#intellij +*.iml +*.ipr +*.iws +.idea/ diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..4f7d7ac --- /dev/null +++ b/.travis.yml @@ -0,0 +1,24 @@ +language: android +os: linux +dist: trusty +jdk: openjdk11 +android: + components: + - tools + - android-29 + - build-tools-29.0.2 +script: + - rm -Rf $HOME/.m2/repository/com/ibotta/gradle/aop/ + - ./publishLocal.sh + - ./gradlew build + +install: skip + +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/ \ No newline at end of file diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..25b8d87 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,46 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at osscompliance@ibotta.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + 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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..6555317 --- /dev/null +++ b/README.md @@ -0,0 +1,151 @@ + +[![Build Status](https://travis-ci.com/Ibotta/gradle-aspectj-pipeline-plugin.svg?token=zc5xrZhgTx8xgzKxeSun&branch=main)](https://travis-ci.com/Ibotta/gradle-aspectj-pipeline-plugin) + +# Android AspectJ Gradle Plugin +A Gradle plugin for Kotlin/Java Android projects which performs AspectJ weaving using Android's bytcode manipulation pipeline. + +# Table Of Contents +- [Who This Is For?](#who-this-is-for) +- [How This Project Came Into Existence?](#how-this-project-came-into-existence) +- [How Is This Implementation Different?](#how-is-this-implementation-different) +- [How Do I Use This Plugin?](#how-do-i-use-this-plugin) +- [We Have Sample Apps!](#we-have-sample-apps) +- [How To Build The Project](#how-to-build-the-project) + +# Who This Is For? +This plugin may be suitable for anyone looking to leverage the power of AOP in their Android projects, regardless of whether you use Kotlin, Java, or a mix of languages. It is _especially_ for those of you who have tried many similar plugins, but have failed to get them to work (like us). + +If you are unfamiliar with AspectJ and/or AOP weaving in general, you will want to familiarize yourself with the concepts: + +- [I Want My AOP](https://www.infoworld.com/article/2073918/i-want-my-aop---part-1.html) +- [AspectJ](https://www.baeldung.com/aspectj) + + +# How This Project Came Into Existence? +There are several libraries out there that aim to solve the problem of AspectJ weaving on Android. We've tried all of them, but they simply didn't work for us. There were many reasons this could have been. Maybe our internal projects are just too complex with all of the Gradle plugins we depend on, causing some incompatibility. Sometimes the library we'd try was just too far out of date, and incompatible with the latest versions of Kotlin, Android, Gradle, etc. Whatever the cause, we ended up writing our own solution. + +Our requirements were simple. *We needed a tool that could perform AspectJ weaving of our mixed Kotlin/Java Android project. And we should be able to verify that woven code is executing as expected with unit tests.* + +At the start of this project, we had little to no experience writing Gradle Plugins. We were fortunate enough to have a relationship with some members of the Gradle team, who aided us in accomplishing our goals. Rather than fumble our way to a solution, we ended up with one that was guided by the Gradle team's expertise in their own tooling. + +# How Is This Implementation Different? +This plugin leverages a mechanism in the Android build which we were introduced to as the "bytecode manipulation pipeline". Essentially, the plugin registers itself with the build as something that will manipulate bytecode, thus making it a formal part of the overall build. Unfortunately, documentation on this mechanism seems to be scarce. The relevant hook for doing this registration can be found here, though: https://android.googlesource.com/platform/tools/base/+/refs/heads/mirror-goog-studio-master-dev/build-system/gradle-core/src/main/java/com/android/build/gradle/api/BaseVariant.java#600 + +The AOP weaving occurs after compilation of Java, Kotlin, or both (in the case of a "mixed" project). And then the AspectJ output is provided to the build for subsequent packaging, etc. From our experience reading through the source code of similar projects, this appears to be a simpler approach to solving the problem. And it works well! The overall footprint of the plugin is miniscule. + +# How Do I Use This Plugin? + +### Step 1 - Update your root project's Gradle build script to depend on the plugin: + +#### Groovy syntax `build.gradle` file: +``` +buildscript { + ... + repositories { + ... + maven { url "https://plugins.gradle.org/m2/" } + ... + } + + dependencies { + ... + classpath "com.ibotta:plugin:1.0.7" + ... + } +} + +... +``` + +#### Kotlin syntax `build.gradle.kts` file: +``` +buildscript { + ... + repositories { + ... + maven("https://plugins.gradle.org/m2/") + ... + } + + dependencies { + ... + classpath("com.ibotta:plugin:1.0.7") + ... + } +} + +... +``` + +### Step 2 - Update your Android sub-project's Gradle build script to apply and configure the plugin: + +#### Groovy syntax `build.gradle` file: +``` +plugins { + ... + id 'com.ibotta.gradle.aop' + ... +} + +android { + ... +} + +dependencies { + ... +} + +// This block is optional, but recommended. The "filter" will be used to limit the scope of classes +// that AspectJ will look at. For performance reasons, and to avoid accidentally picking up AspectJ +// annotations from other libraries, specify a filter which will target only your code. +aopWeave { + filter = "com/example/myapp" +} + +... +``` + +#### Kotlin syntax `build.gradle.kts` file: +``` +plugins { + ... + id("com.ibotta.gradle.aop") + ... +} + +android { + ... +} + +dependencies { + ... +} + +// This block is optional, but recommended. The "filter" will be used to limit the scope of classes +// that AspectJ will look at. For performance reasons, and to avoid accidentally picking up AspectJ +// annotations from other libraries, specify a filter which will target only your code. +aopWeave { + filter = "com/example/myapp" +} + +... +``` + + +# We Have Sample Apps! +In this project, you will find a few sample apps that use this plugin to perform some simple AOP weaving. They include tests to help prove that the weaving occurred, and is running as expected. Maybe you have a Kotlin only project, or Java only, or a mix! We have examples of each: + + - [Kotlin Only Sample App](sample-kotlin) + - [Java Only Sample App](sample-java) + - [Mixed Java/Kotlin Sample App](sample-mixed) + +# How To Build The Project +If you've made no code changes to the project, and simply want to build it, then you can just run the following command from the root of the project: `./gradlew build` + +If you've made changes to one of the sample projects, ***but not the plugin source code,*** you can simply build the sample project and run it. For example (building): `./gradlew :sample-mixed:build` + +If you've made changes to the plugin's source code, and would like to test them using one of the sample applications, then you will want to do the following: + +1. Update the `Dependencies.kt` file by incrementing the `VERSION` variable to the next minor value (or, something unique, that has not been used before). This will make sure a new version of the plugin is constructed before publishing it to Maven local. +2. Execute the `./publishLocal.sh` script in the root director. This will push the plugin, as an artifact, to the Maven local repository. +3. Finally, build and run the sample project you're testing with. The sample projects reference the same `VERSION` variable which you updated in step number 1. It should automatically pick up the version of the plugin published to Maven local in step number 2. \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..9b5ba62 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,35 @@ +import org.jetbrains.kotlin.gradle.tasks.KotlinCompile + +plugins { + id("java-gradle-plugin") + id("org.jetbrains.kotlin.jvm") version Versions.KOTLIN_VERSION + id("org.gradle.kotlin.kotlin-dsl") version Versions.KOTLIN_DSL_VERSION + id("com.android.application") version Versions.ANDROID_BUILD_TOOLS_VERSION apply false + kotlin("android") version Versions.KOTLIN_VERSION apply false + kotlin("plugin.serialization") version Versions.KOTLIN_VERSION apply false +} + +allprojects { + repositories { + google() + jcenter() + mavenCentral() + mavenLocal() + maven("https://plugins.gradle.org/m2/") + } + + tasks.withType { + useJUnitPlatform() + } + + tasks.withType { + kotlinOptions { + jvmTarget = Plugin.JVM_TARGET + } + } + + tasks.withType { + sourceCompatibility = Plugin.JVM_TARGET + targetCompatibility = Plugin.JVM_TARGET + } +} diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts new file mode 100644 index 0000000..15b61a2 --- /dev/null +++ b/buildSrc/build.gradle.kts @@ -0,0 +1,6 @@ +plugins { + `kotlin-dsl` +} +repositories { + jcenter() +} \ No newline at end of file diff --git a/buildSrc/src/main/kotlin/Dependencies.kt b/buildSrc/src/main/kotlin/Dependencies.kt new file mode 100644 index 0000000..d27a2de --- /dev/null +++ b/buildSrc/src/main/kotlin/Dependencies.kt @@ -0,0 +1,68 @@ +object Plugin { + const val GROUP = "com.ibotta" + const val PLUGIN_ID = "$GROUP.gradle.aop" + const val NAME = "aopWeaverPipeline" + const val IMPLEMENTATION_CLASS = "$PLUGIN_ID.PipelineAopWeaverPlugin" + const val WEBSITE = "https://github.com/Ibotta/gradle-aspectj-pipeline-plugin" + const val DESCRIPTION = "A Gradle plugin for Android projects which performs AspectJ weaving using Android's bytcode manipulation pipeline." + const val DISPLAY_NAME = "Android AspectJ Gradle Plugin" + const val JVM_TARGET = "1.8" + private const val BUILD_NUMBER = "" // Dynamically updated by publishLocal.sh on Travis. Otherwise left as-is. + const val VERSION = "1.0.7$BUILD_NUMBER" + val TAGS = listOf("Gradle", "Plugin", "Android", "AspectJ", "Kotlin", "Java") +} + +object SampleAppCommon { + const val APP_VERSION_CODE = 1 + const val APP_VERSION_NAME = "1.0.0" + const val FILTER = "com/ibotta/gradle/aop" +} + +object MixedApp { + const val APP_ID = "com.ibotta.gradle.aop.mixed" +} + +object KotlinApp { + const val APP_ID = "com.ibotta.gradle.aop.kotlin" +} + +object JavaApp { + const val APP_ID = "com.ibotta.gradle.aop.java" +} + +object Sdk { + const val MIN_SDK_VERSION = 21 + const val TARGET_SDK_VERSION = 29 + const val COMPILE_SDK_VERSION = 29 +} + +object Versions { + const val ANDROID_BUILD_TOOLS_VERSION = "4.1.0" + const val APPCOMPAT_VERSION = "1.1.0" + const val ASPECTJ_VERSION = "1.9.6" + const val GRADLE_PLUGIN_PUBLISH_VERSION = "0.12.0" + const val JACOCO_ANDROID_VERSION = "0.2" + const val JUNIT_VERSION = "5.7.0" + const val KOTLIN_VERSION = "1.4.10" + const val KOTLIN_DSL_VERSION = "1.4.1" + const val KOTLINX_SERIALIZATION_RUNTIME_VERSION = "0.20.0" + const val MOCKITO_CORE_VERSION = "3.5.13" + const val MOCKK_VERSION = "1.10.2" +} + +object SupportLibs { + const val ANDROIDX_APPCOMPAT = "androidx.appcompat:appcompat:${Versions.APPCOMPAT_VERSION}" +} + +object Dependencies { + const val ANDROID_BUILD_TOOLS = "com.android.tools.build:gradle:${Versions.ANDROID_BUILD_TOOLS_VERSION}" + const val KOTLIN_GRADLE_PLUGIN = "org.jetbrains.kotlin:kotlin-gradle-plugin:${Versions.KOTLIN_VERSION}" + const val KOTLIN_SERIALIZATION_RUNTIME = "org.jetbrains.kotlinx:kotlinx-serialization-runtime:${Versions.KOTLINX_SERIALIZATION_RUNTIME_VERSION}" + const val ASPECT_J_TOOLS = "org.aspectj:aspectjtools:${Versions.ASPECTJ_VERSION}" + const val ASPECT_J_RUNTIME = "org.aspectj:aspectjrt:${Versions.ASPECTJ_VERSION}" + const val JACOCO_ANDROID = "com.hiya:jacoco-android:${Versions.JACOCO_ANDROID_VERSION}" + const val JUNIT_BOM = "org.junit:junit-bom:${Versions.JUNIT_VERSION}" + const val JUNIT_JUPITER = "org.junit.jupiter:junit-jupiter:${Versions.JUNIT_VERSION}" + const val MOCKITO = "org.mockito:mockito-core:${Versions.MOCKITO_CORE_VERSION}" + const val MOCKK = "io.mockk:mockk:${Versions.MOCKK_VERSION}" +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..c84841b --- /dev/null +++ b/gradle.properties @@ -0,0 +1,4 @@ +org.gradle.jvmargs=-Xmx1536m +android.useAndroidX=true +android.enableJetifier=true +kotlin.code.style=official \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..87b738c Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..12d38de --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.6.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..af6708f --- /dev/null +++ b/gradlew @@ -0,0 +1,172 @@ +#!/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" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..0f8d593 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,84 @@ +@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 diff --git a/plugin/build.gradle.kts b/plugin/build.gradle.kts new file mode 100644 index 0000000..3cb056c --- /dev/null +++ b/plugin/build.gradle.kts @@ -0,0 +1,35 @@ +plugins { + id("org.gradle.kotlin.kotlin-dsl") + id("maven-publish") + kotlin("plugin.serialization") + `java-gradle-plugin` + id("com.gradle.plugin-publish") version Versions.GRADLE_PLUGIN_PUBLISH_VERSION +} + +dependencies { + implementation(Dependencies.ANDROID_BUILD_TOOLS) + implementation(Dependencies.KOTLIN_GRADLE_PLUGIN) + implementation(Dependencies.KOTLIN_SERIALIZATION_RUNTIME) + implementation(Dependencies.ASPECT_J_TOOLS) + implementation(Dependencies.JACOCO_ANDROID) +} + +pluginBundle { + website = Plugin.WEBSITE + vcsUrl = Plugin.WEBSITE + tags = Plugin.TAGS + group = Plugin.GROUP +} + +gradlePlugin { + plugins { + create(Plugin.NAME) { + id = Plugin.PLUGIN_ID + group = Plugin.GROUP + displayName = Plugin.DISPLAY_NAME + description = Plugin.DESCRIPTION + version = Plugin.VERSION + implementationClass = Plugin.IMPLEMENTATION_CLASS + } + } +} diff --git a/plugin/src/main/kotlin/com/ibotta/gradle/aop/AopWeaveExtension.kt b/plugin/src/main/kotlin/com/ibotta/gradle/aop/AopWeaveExtension.kt new file mode 100644 index 0000000..908cc12 --- /dev/null +++ b/plugin/src/main/kotlin/com/ibotta/gradle/aop/AopWeaveExtension.kt @@ -0,0 +1,9 @@ +package com.ibotta.gradle.aop + +open class AopWeaveExtension { + companion object { + const val AOP_WEAVE_EXTENSION = "aopWeave" + } + + var filter = "" +} \ No newline at end of file diff --git a/plugin/src/main/kotlin/com/ibotta/gradle/aop/AopWeaveTask.kt b/plugin/src/main/kotlin/com/ibotta/gradle/aop/AopWeaveTask.kt new file mode 100644 index 0000000..ae56388 --- /dev/null +++ b/plugin/src/main/kotlin/com/ibotta/gradle/aop/AopWeaveTask.kt @@ -0,0 +1,99 @@ +package com.ibotta.gradle.aop + +import org.gradle.api.DefaultTask +import org.gradle.api.GradleException +import org.gradle.api.file.FileCollection +import org.gradle.api.internal.tasks.TaskStateInternal +import org.gradle.api.logging.Logger +import org.gradle.api.tasks.CacheableTask +import org.gradle.api.tasks.Classpath +import org.gradle.api.tasks.Input +import org.gradle.api.tasks.InputFiles +import org.gradle.api.tasks.Internal +import org.gradle.api.tasks.OutputDirectory +import org.gradle.api.tasks.PathSensitive +import org.gradle.api.tasks.PathSensitivity +import org.gradle.api.tasks.TaskAction +import java.io.File + +@CacheableTask +open class AopWeaveTask : DefaultTask() { + // Using this as a Gradle cache busting strategy. Increment this value if needed to prevent an older weave cache + // entry from getting picked up, despite new logic existing. + @Input + var version: Long = 1L + + @InputFiles + @PathSensitive(PathSensitivity.RELATIVE) + var inPath: FileCollection? = null + + @Internal + var aspectPathResolver: () -> FileCollection? = { null } + + @Classpath + var aspectPath: FileCollection? = null + get() = aspectPathResolver() + set(value) { field = value } + + @Internal + var classPathResolver: () -> FileCollection? = { null } + + @Classpath + var classPath: FileCollection? = null + get() = classPathResolver() + set(value) { field = value } + + @Classpath + var bootClassPath: FileCollection? = null + + @OutputDirectory + var outputDir: File? = null + + @Internal + var logPath: File? = null + + @TaskAction + fun weave() { + if (inPath!!.isEmpty()) { + project.aopLog("No classes found. Will skip.") + return + } + + AspectJExecutor( + inPath = inPath!!.asPath, + aspectPath = aspectPath!!.asPath, + outputDir = outputDir!!.absolutePath, + logPath = logPath!!.absolutePath, + classPath = classPath!!.asPath, + bootClassPath = bootClassPath!!.asPath, + logger = logger + ).execute() + + inPath!!.forEach { + copyNonClassFiles(it, outputDir!!) + } + } + + /** + * Copies all non .class files over from the pre-weave directory, to the weave output directory. This makes sure + * things like resources and the MANIFEST make it over. + */ + private fun copyNonClassFiles(from: File, to: File) { + if (!from.exists()) { + return + } else if (!from.isDirectory) { + throw GradleException("Expected a directory: from=$from, to=$to") + } + + from.listFiles { file -> file.isDirectory } + .forEach { fromDir -> + val toDir = File(to, fromDir.name).also { if (!it.exists()) it.mkdirs() } + copyNonClassFiles(fromDir, toDir) + } + + from.listFiles { file -> (!file.isDirectory && !file.name.endsWith(".class")) } + .forEach { fromFile -> + fromFile.copyTo(File(to, fromFile.name), true) + } + } +} \ No newline at end of file diff --git a/plugin/src/main/kotlin/com/ibotta/gradle/aop/AspectJExecutor.kt b/plugin/src/main/kotlin/com/ibotta/gradle/aop/AspectJExecutor.kt new file mode 100644 index 0000000..2a81687 --- /dev/null +++ b/plugin/src/main/kotlin/com/ibotta/gradle/aop/AspectJExecutor.kt @@ -0,0 +1,79 @@ +package com.ibotta.gradle.aop + +import org.aspectj.bridge.IMessage +import org.aspectj.bridge.IMessageHandler +import org.aspectj.bridge.MessageHandler +import org.aspectj.tools.ajc.Main +import org.gradle.api.logging.Logger +import java.util.concurrent.locks.ReentrantLock +import kotlin.concurrent.withLock + +/** + * A wrapper around the AspectJ weaver to make it a little easier to work with. + */ +class AspectJExecutor( + private val inPath: String, + private val aspectPath: String, + private val outputDir: String, + private val logPath: String, + private val classPath: String, + private val bootClassPath: String, + private val logger: Logger +) { + companion object { + private const val CMD_IN_PATH = "-inpath" + private const val CMD_ASPECT_PATH = "-aspectpath" + private const val CMD_OUTPUT_DIR = "-d" + private const val CMD_CLASS_PATH = "-classpath" + private const val CMD_BOOT_CLASS_PATH = "-bootclasspath" + private const val CMD_LOG = "-log" + private const val CMD_SHOW_WEAVE_INFO = "-showWeaveInfo" + private const val CMD_JAVA_1_8 = "-1.8" + private val lock = ReentrantLock() + } + + fun execute() { + val args = arrayOf( + CMD_SHOW_WEAVE_INFO, + CMD_JAVA_1_8, + // This path should include classes that the Aspects might act on. For us, + // this means files that use our own AOP annotations. + CMD_IN_PATH, + inPath, + // This path should include classes that have Aspects. + CMD_ASPECT_PATH, + aspectPath, + // Weave output directory. + CMD_OUTPUT_DIR, + outputDir, + // The classpath can just be the same as the one used to compile our files. + CMD_CLASS_PATH, + classPath, + // Useful log output! Will show weaving issues (if any), and will tell the + // story of what classes were woven. Look for this log in + // /build. + CMD_LOG, + logPath, + // I think this is the classpath that the ajc (AspectJ compiler) needs to + // do its thing. DON'T CHANGE. + CMD_BOOT_CLASS_PATH, + bootClassPath + ) + + // Use a lock to prevent concurrent AspectJ runs from occurring. AspectJ does not appear to be thread safe, + // and concurrency was causing random build failures as well as weaving failures. + lock.withLock { + val handler = MessageHandler(true) + Main().run(args, handler) + + handler.getMessages(null, true).forEach { + when (it.kind) { + IMessage.ABORT, IMessage.ERROR, IMessage.FAIL -> logger.error(it.message, it.thrown) + IMessage.WARNING -> logger.warn(it.message, it.thrown) + IMessage.INFO -> logger.info(it.message, it.thrown) + IMessage.DEBUG -> logger.debug(it.message, it.thrown) + } + } + } + } +} \ No newline at end of file diff --git a/plugin/src/main/kotlin/com/ibotta/gradle/aop/ExtFunctions.kt b/plugin/src/main/kotlin/com/ibotta/gradle/aop/ExtFunctions.kt new file mode 100644 index 0000000..dd0c36a --- /dev/null +++ b/plugin/src/main/kotlin/com/ibotta/gradle/aop/ExtFunctions.kt @@ -0,0 +1,75 @@ +package com.ibotta.gradle.aop + +import com.hiya.plugins.JacocoAndroidUnitTestReportExtension +import org.gradle.api.Project +import org.gradle.api.Task +import org.gradle.api.UnknownDomainObjectException +import org.gradle.api.provider.Provider +import org.gradle.api.tasks.TaskContainer +import org.gradle.api.tasks.TaskProvider +import org.gradle.api.tasks.compile.AbstractCompile +import org.gradle.testing.jacoco.tasks.JacocoReport +import java.io.File + +private const val JAVA_COMPILE_TASK_TEMPLATE = "compile%sJavaWithJavac" +private const val KOTLIN_COMPILE_TASK_TEMPLATE = "compile%sKotlin" +private const val JACOCO_REPORT_TASK_TEMPLATE = "jacocoTest%sUnitTestReport" +private const val JACOCO_ANDROID_REPORT_EXTENSION = "jacocoAndroidUnitTestReport" +const val LANG_JAVA = "Java" +const val LANG_KOTLIN = "Kotlin" + +fun Project.aopLog(msg: String) = logger.warn("/** Ibotta AOP **/: $msg") + +fun Project.javaCompileTask(variantName: String): AbstractCompile? = + compileTask(JAVA_COMPILE_TASK_TEMPLATE.format(variantName)) + +fun Project.kotlinCompileTask(variantName: String): AbstractCompile? = + compileTask(KOTLIN_COMPILE_TASK_TEMPLATE.format(variantName)) + +private fun Project.compileTask(taskName: String): AbstractCompile? { + val firstTask = firstTask(taskName) + + return if (firstTask != null) { + firstTask as AbstractCompile + } else { + null + } +} + +fun Project.javaCompileTaskProvider(variantName: String) = + tasks.namedOrNull(JAVA_COMPILE_TASK_TEMPLATE.format(variantName)) + +fun Project.kotlinCompileTaskProvider(variantName: String) = + tasks.namedOrNull(KOTLIN_COMPILE_TASK_TEMPLATE.format(variantName)) + +fun Project.jacocoReportTaskProvider(variantName: String): TaskProvider? { + val jacocoTask = tasks.namedOrNull(JACOCO_REPORT_TASK_TEMPLATE.format(variantName)) + + return if (jacocoTask != null) { + jacocoTask as TaskProvider + } else { + null + } +} + +fun Project.jacocoAndroidReportExtension(): JacocoAndroidUnitTestReportExtension? { + val jacocoExt = extensions.findByName(JACOCO_ANDROID_REPORT_EXTENSION) + + return if (jacocoExt != null) { + jacocoExt as JacocoAndroidUnitTestReportExtension + } else { + null + } +} + +fun Project.firstTask(taskName: String) = getTasksByName(taskName, false).firstOrNull() + +fun TaskContainer.namedOrNull(taskName: String): TaskProvider? { + return try { + named(taskName) + } catch (e: UnknownDomainObjectException) { + null + } +} + +fun File?.isEmpty() = ((this == null) || (list() == null) || list().isEmpty()) diff --git a/plugin/src/main/kotlin/com/ibotta/gradle/aop/PipelineAopWeaverPlugin.kt b/plugin/src/main/kotlin/com/ibotta/gradle/aop/PipelineAopWeaverPlugin.kt new file mode 100644 index 0000000..a33de81 --- /dev/null +++ b/plugin/src/main/kotlin/com/ibotta/gradle/aop/PipelineAopWeaverPlugin.kt @@ -0,0 +1,296 @@ +package com.ibotta.gradle.aop + +import com.android.build.gradle.AppExtension +import com.android.build.gradle.AppPlugin +import com.android.build.gradle.BaseExtension +import com.android.build.gradle.LibraryExtension +import com.android.build.gradle.LibraryPlugin +import com.hiya.plugins.JacocoAndroidUnitTestReportExtension +import org.gradle.api.GradleException +import org.gradle.api.Plugin +import org.gradle.api.Project +import org.gradle.api.Task +import org.gradle.api.file.ConfigurableFileCollection +import org.gradle.api.file.Directory +import org.gradle.api.provider.Provider +import org.gradle.api.tasks.TaskProvider +import org.gradle.api.tasks.compile.AbstractCompile +import org.gradle.testing.jacoco.tasks.JacocoReport + +/** + * A Gradle plugin that performs AOP weaving using a technique recommended by Gradle reps. It taps into Android's + * bytcode manipulation pipeline which is a far more logical approach. + * + * The basic idea is: + * 1. Change the Kotlin and Java compile output directories. + * 2. Copy the Kotlin/Java compiled output to one directory. + * 3. Weave the combined Kotlin/Java classes. + * 4. Be registered as a bytcode generator so that Android recognizes the custom AOP weaving as a formal step + * in the build pipeline. + */ +class PipelineAopWeaverPlugin : Plugin { + private companion object { + private const val MISSING_PLUGIN_ERROR = "'com.android.application' or 'com.android.library' plugin required." + private const val ANDROID_EXTENSION_NAME = "android" + private const val ANDROID_JAR_TEMPLATE = "%s/platforms/%s/android.jar" + private const val PRE_WEAVE_DIR_TEMPLATE = "preWeave/%s/%s" + private const val POST_WEAVE_DIR_TEMPLATE = "postWeave/%s" + private const val AOP_WEAVE_TASK = "aopWeave%s" + private const val AOP_LOG = "aop.log" + } + + override fun apply(project: Project) { + val isAndroid = project.plugins.hasPlugin(AppPlugin::class.java) + val isLibrary = project.plugins.hasPlugin(LibraryPlugin::class.java) + + if (!isAndroid && !isLibrary) { + throw GradleException(MISSING_PLUGIN_ERROR) + } + + project.aopLog("Plugin started.") + + val extension = project.extensions.create(AopWeaveExtension.AOP_WEAVE_EXTENSION, AopWeaveExtension::class.java) + val android = project.extensions.findByName(ANDROID_EXTENSION_NAME) as BaseExtension + + project.afterEvaluate { + val variants = if (isAndroid) { + (android as AppExtension).applicationVariants + } else { + (android as LibraryExtension).libraryVariants + } + + variants.forEach { variant -> + // Various strings in different case forms which we'll need when creating directories, or finding + // tasks. + val javaLangLowercase = LANG_JAVA.toLowerCase() + val kotlinLangLowercase = LANG_KOTLIN.toLowerCase() + val variantNameLowercase = variant.name + val variantNameCapitalized = variant.name.capitalize() + + // We will configure the Kotlin and Java compilation tasks to output classes into "pre-weave" + // directories. + val preWeaveJavaDir = project.layout + .buildDirectory + .dir(PRE_WEAVE_DIR_TEMPLATE.format(variantNameLowercase, javaLangLowercase)) + val preWeaveKotlinDir = project.layout + .buildDirectory + .dir(PRE_WEAVE_DIR_TEMPLATE.format(variantNameLowercase, kotlinLangLowercase)) + + // This is where we will output woven Kotlin and Java classes. + val postWeaveDir = project.layout + .buildDirectory + .dir(POST_WEAVE_DIR_TEMPLATE.format(variantNameLowercase)) + + // Now we'll acquire the Task providers for the compilation steps, as well as our own custom weave + // task. Task providers allow to tell Gradle how we will want the tasks to be configured and executed, + // before the tasks exists. + val kotlinCompileProvider = project.kotlinCompileTaskProvider(variantNameCapitalized) + val javaCompileProvider = project.javaCompileTaskProvider(variantNameCapitalized) + val aopWeaveProvider = project.tasks + .register(AOP_WEAVE_TASK.format(variantNameCapitalized), AopWeaveTask::class.java) + val jacocoReportTaskProvider = project.jacocoReportTaskProvider(variantNameCapitalized) + + // We'll need to configure the Kotlin/Java tasks to output compiled classes to a different directory + // than what it uses by default. + if (kotlinCompileProvider != null) { + configureKotlinCompileTask(kotlinCompileProvider, preWeaveKotlinDir) + } + if (javaCompileProvider != null) { + configureJavaCompileTask(project, javaCompileProvider, preWeaveKotlinDir, preWeaveJavaDir) + } + + // Set up the configuration for the JacocoReport task in case the build requires it. + if (jacocoReportTaskProvider != null) { + configureJacocoReportTask(jacocoReportTaskProvider, postWeaveDir) + } + + // We'll need this jar for weaving. + val androidJarPath = ANDROID_JAR_TEMPLATE.format( + android.sdkDirectory.absolutePath, + android.compileSdkVersion + ) + + // Finally, we can configure our AOP weaving task. + configureAopWeaveTask( + project = project, + extension = extension, + variantNameCapitalized = variantNameCapitalized, + javaCompileProvider = javaCompileProvider, + kotlinCompileProvider = kotlinCompileProvider, + aopWeaveProvider = aopWeaveProvider, + androidJarPath = androidJarPath, + preWeaveJavaDir = preWeaveJavaDir, + preWeaveKotlinDir = preWeaveKotlinDir, + postWeaveDir = postWeaveDir + ) + + // The last step is to let the Android build logic know it should expect bytecode-modified classes. + // This is a mechanism that allows us to add our own work to a pipeline before final module assembly. + variant.registerPostJavacGeneratedBytecode(project.files(aopWeaveProvider.map { it.outputDir!! })) + } + } + } + + /** + * Configure the JacocoReport task's class directories to include the post-weave directory we've defined here. + * Our Jacoco plugin, [JacocoAndroidUnitTestReportExtension], uses the class directories to generate it's report. + * When our post-weave directories are not included, the generated report is empty. + */ + private fun configureJacocoReportTask( + jacocoReportTaskProvider: TaskProvider, + postWeaveDir: Provider + ) { + jacocoReportTaskProvider.configure { + val jacocoExt = project.jacocoAndroidReportExtension() + + if (jacocoExt != null) { + // This file tree represents the post-weave directory we've + // defined, along with the excludes we set for the Jacoco project + val postWeaveFiltered = project.fileTree(postWeaveDir).apply { + setExcludes(jacocoExt.excludes) + } + // Re-set the Jacoco task's class directories to include our post-weave directory with our desired + // excludes + classDirectories.setFrom(classDirectories + postWeaveFiltered) + } + } + } + + /** + * Configure the Kotlin compiler to output to the pre-weave directory. We will also hook up some actions that will + * move compiled classes around. This is done to retain incremental build functionality, and to prepare for AOP + * weaving. + */ + private fun configureKotlinCompileTask( + kotlinCompileProvider: TaskProvider, + preWeaveKotlinDir: Provider + ) { + kotlinCompileProvider.configure { + outputs.dir(preWeaveKotlinDir) + + doFirst { restoreIncrementalBehaviorAction(this as AbstractCompile, preWeaveKotlinDir) } + doLast { cleanUpAfterWeaving(this as AbstractCompile, preWeaveKotlinDir) } + } + } + + /** + * Configure the Java compiler to output to the pre-weave directory. We will also hook up some actions that will + * move compiled classes around. This is done to retain incremental build functionality, and to prepare for AOP + * weaving. + */ + private fun configureJavaCompileTask( + project: Project, + javaCompileProvider: TaskProvider, + preWeaveKotlinDir: Provider, + preWeaveJavaDir: Provider + ) { + javaCompileProvider.configure { + (this as AbstractCompile).classpath += project.files(preWeaveKotlinDir) + outputs.dir(preWeaveJavaDir) + + doFirst { restoreIncrementalBehaviorAction(this as AbstractCompile, preWeaveJavaDir) } + doLast { cleanUpAfterWeaving(this as AbstractCompile, preWeaveJavaDir) } + } + } + + private fun configureAopWeaveTask( + project: Project, + extension: AopWeaveExtension, + variantNameCapitalized: String, + javaCompileProvider: TaskProvider?, + kotlinCompileProvider: TaskProvider?, + aopWeaveProvider: TaskProvider, + androidJarPath: String, + preWeaveJavaDir: Provider, + preWeaveKotlinDir: Provider, + postWeaveDir: Provider + ) { + aopWeaveProvider.configure { + inPath = project.files(preWeaveJavaDir.get().asFile, preWeaveKotlinDir.get().asFile) + aspectPathResolver = { + project.files(gatherAspectPaths(project, variantNameCapitalized, preWeaveJavaDir, preWeaveKotlinDir)) + .also { + if (extension.filter.isNotEmpty()) { + project.aopLog("Weaving filter in ${project.name} is: ${extension.filter}") + } + } + .filter { file -> + file.canonicalPath.contains(extension.filter) + } + } + classPathResolver = { gatherClasspaths(project, variantNameCapitalized) } + bootClassPath = project.files(androidJarPath) + outputDir = postWeaveDir.get().asFile + logPath = project.layout.buildDirectory.file(AOP_LOG).get().asFile + + val dependencies = when { + ((javaCompileProvider != null) && (kotlinCompileProvider != null)) -> { + arrayOf(javaCompileProvider, kotlinCompileProvider) + } + (javaCompileProvider != null) -> arrayOf(javaCompileProvider) + (kotlinCompileProvider != null) -> arrayOf(kotlinCompileProvider) + else -> throw RuntimeException("Either Java, Kotlin, or both types of compile task must be present.") + } + + dependsOn(dependencies) + } + } + + private fun restoreIncrementalBehaviorAction(compileTask: AbstractCompile, preWeaveDir: Provider) { + if (!preWeaveDir.get().asFile.isEmpty()) { + compileTask.apply { + project.copy { + from(preWeaveDir) + into(destinationDirectory) + } + } + } + } + + private fun cleanUpAfterWeaving(compileTask: AbstractCompile, preWeaveDir: Provider) { + compileTask.apply { + project.copy { + from(destinationDirectory) + into(preWeaveDir) + } + project.delete(destinationDir) + } + } + + private fun gatherAspectPaths( + project: Project, + variantNameCapitalized: String, + preWeaveJavaDir: Provider, + preWeaveKotlinDir: Provider + ): ConfigurableFileCollection { + val javaCompileTask = project.javaCompileTask(variantNameCapitalized) + val kotlinCompileTask = project.kotlinCompileTask(variantNameCapitalized) + + return when { + ((javaCompileTask != null) && (kotlinCompileTask != null)) -> project.files( + javaCompileTask.classpath, + kotlinCompileTask.classpath, + preWeaveJavaDir.get().asFile, + preWeaveKotlinDir.get().asFile + ) + (javaCompileTask != null) -> project.files(javaCompileTask.classpath, preWeaveJavaDir.get().asFile) + (kotlinCompileTask != null) -> project.files(kotlinCompileTask.classpath, preWeaveKotlinDir.get().asFile) + else -> throw RuntimeException("Either Java, Kotlin, or both types of compile task must be present.") + } + } + + private fun gatherClasspaths(project: Project, variantNameCapitalized: String): ConfigurableFileCollection { + val javaCompileTask = project.javaCompileTask(variantNameCapitalized) + val kotlinCompileTask = project.kotlinCompileTask(variantNameCapitalized) + + return when { + ((javaCompileTask != null) && (kotlinCompileTask != null)) -> project.files( + javaCompileTask.classpath, + kotlinCompileTask.classpath + ) + (javaCompileTask != null) -> project.files(javaCompileTask.classpath) + (kotlinCompileTask != null) -> project.files(kotlinCompileTask.classpath) + else -> throw RuntimeException("Either Java, Kotlin, or both types of compile task must be present.") + } + } +} \ No newline at end of file diff --git a/publish.sh b/publish.sh new file mode 100755 index 0000000..0da0078 --- /dev/null +++ b/publish.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +./gradlew publishPlugins -DpublishMode=true \ No newline at end of file diff --git a/publishLocal.sh b/publishLocal.sh new file mode 100755 index 0000000..18f22c8 --- /dev/null +++ b/publishLocal.sh @@ -0,0 +1,8 @@ +#!/bin/bash + +if [[ -n $TRAVIS_BUILD_NUMBER ]]; then + echo Updating plugin version with build number: $TRAVIS_BUILD_NUMBER + sed -i -e 's/BUILD_NUMBER = ""/BUILD_NUMBER = ".'$TRAVIS_BUILD_NUMBER'"/g' buildSrc/src/main/kotlin/Dependencies.kt + rm buildSrc/src/main/kotlin/Dependencies.kt-e +fi +./gradlew publishToMavenLocal -DpublishMode=true \ No newline at end of file diff --git a/sample-java/build.gradle.kts b/sample-java/build.gradle.kts new file mode 100644 index 0000000..9d2d979 --- /dev/null +++ b/sample-java/build.gradle.kts @@ -0,0 +1,60 @@ +import com.ibotta.gradle.aop.AopWeaveExtension + +plugins { + id("com.android.application") + id(Plugin.PLUGIN_ID) version Plugin.VERSION apply false +} + +apply(plugin = Plugin.PLUGIN_ID) + +android { + compileSdkVersion(Sdk.COMPILE_SDK_VERSION) + + defaultConfig { + minSdkVersion(Sdk.MIN_SDK_VERSION) + targetSdkVersion(Sdk.TARGET_SDK_VERSION) + + applicationId = JavaApp.APP_ID + versionCode = SampleAppCommon.APP_VERSION_CODE + versionName = SampleAppCommon.APP_VERSION_NAME + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + } + buildTypes { + getByName("release") { + isMinifyEnabled = false + proguardFiles( + getDefaultProguardFile("proguard-android-optimize.txt"), + "proguard-rules.pro" + ) + } + } + + lintOptions { + isWarningsAsErrors = true + isAbortOnError = true + } + + sourceSets.getByName("main") { + java.srcDir("src/main/java") + resources.srcDir("src/main/res") + } + sourceSets.getByName("test") { + java.srcDir("src/test/java") + } +} + +dependencies { + implementation(Dependencies.ASPECT_J_RUNTIME) + implementation(SupportLibs.ANDROIDX_APPCOMPAT) + + testImplementation(platform(Dependencies.JUNIT_BOM)) + testImplementation(Dependencies.JUNIT_JUPITER) + testImplementation(Dependencies.MOCKITO) +} + +configure { + filter = SampleAppCommon.FILTER +} \ No newline at end of file diff --git a/sample-java/proguard-rules.pro b/sample-java/proguard-rules.pro new file mode 100644 index 0000000..ff59496 --- /dev/null +++ b/sample-java/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle.kts. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile \ No newline at end of file diff --git a/sample-java/src/main/AndroidManifest.xml b/sample-java/src/main/AndroidManifest.xml new file mode 100644 index 0000000..0de598b --- /dev/null +++ b/sample-java/src/main/AndroidManifest.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/sample-java/src/main/java/com/ibotta/gradle/aop/java/CallerType.java b/sample-java/src/main/java/com/ibotta/gradle/aop/java/CallerType.java new file mode 100644 index 0000000..d6d2a03 --- /dev/null +++ b/sample-java/src/main/java/com/ibotta/gradle/aop/java/CallerType.java @@ -0,0 +1,7 @@ +package com.ibotta.gradle.aop.java; + +public enum CallerType { + BEFORE_HOOK, + AFTER_HOOK, + TARGET +} diff --git a/sample-java/src/main/java/com/ibotta/gradle/aop/java/JavaAspect.java b/sample-java/src/main/java/com/ibotta/gradle/aop/java/JavaAspect.java new file mode 100644 index 0000000..e52956f --- /dev/null +++ b/sample-java/src/main/java/com/ibotta/gradle/aop/java/JavaAspect.java @@ -0,0 +1,21 @@ +package com.ibotta.gradle.aop.java; + +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.After; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; + +@Aspect +public class JavaAspect { + @Before("execution(* demonstrateJavaAOP(..))") + public void before(JoinPoint joinPoint) { + MessageListener messageListener = (MessageListener) joinPoint.getArgs()[0]; + messageListener.onMessage("Java AOP before hook triggered.", CallerType.BEFORE_HOOK); + } + + @After("execution(* demonstrateJavaAOP(..))") + public void after(JoinPoint joinPoint) { + MessageListener messageListener = (MessageListener) joinPoint.getArgs()[0]; + messageListener.onMessage("Java AOP after hook triggered.", CallerType.AFTER_HOOK); + } +} diff --git a/sample-java/src/main/java/com/ibotta/gradle/aop/java/JavaTargetExample.java b/sample-java/src/main/java/com/ibotta/gradle/aop/java/JavaTargetExample.java new file mode 100644 index 0000000..1706850 --- /dev/null +++ b/sample-java/src/main/java/com/ibotta/gradle/aop/java/JavaTargetExample.java @@ -0,0 +1,8 @@ +package com.ibotta.gradle.aop.java; + + +public class JavaTargetExample { + public void demonstrateJavaAOP(MessageListener messageListener) { + messageListener.onMessage("Java method with AOP attached is executed.", CallerType.TARGET); + } +} diff --git a/sample-java/src/main/java/com/ibotta/gradle/aop/java/MainActivity.java b/sample-java/src/main/java/com/ibotta/gradle/aop/java/MainActivity.java new file mode 100644 index 0000000..d96c6b7 --- /dev/null +++ b/sample-java/src/main/java/com/ibotta/gradle/aop/java/MainActivity.java @@ -0,0 +1,32 @@ +package com.ibotta.gradle.aop.java; + +import android.os.Bundle; +import android.widget.Button; +import android.widget.TextView; + +import androidx.annotation.Nullable; +import androidx.appcompat.app.AppCompatActivity; + +public class MainActivity extends AppCompatActivity implements MessageListener { + private Button bButtonJava; + private TextView tvMessage; + + @Override + protected void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_main); + + bButtonJava = findViewById(R.id.b_button_java); + tvMessage = findViewById(R.id.tv_message); + + bButtonJava.setOnClickListener(view -> { + tvMessage.setText(""); + new JavaTargetExample().demonstrateJavaAOP(MainActivity.this); + }); + } + + @Override + public void onMessage(String message, CallerType callerType) { + tvMessage.append(message + "\n"); + } +} diff --git a/sample-java/src/main/java/com/ibotta/gradle/aop/java/MessageListener.java b/sample-java/src/main/java/com/ibotta/gradle/aop/java/MessageListener.java new file mode 100644 index 0000000..2d68f8d --- /dev/null +++ b/sample-java/src/main/java/com/ibotta/gradle/aop/java/MessageListener.java @@ -0,0 +1,5 @@ +package com.ibotta.gradle.aop.java; + +public interface MessageListener { + void onMessage(String message, CallerType callerType); +} diff --git a/sample-java/src/main/res/drawable-v24/ic_launcher_foreground.xml b/sample-java/src/main/res/drawable-v24/ic_launcher_foreground.xml new file mode 100644 index 0000000..6348baa --- /dev/null +++ b/sample-java/src/main/res/drawable-v24/ic_launcher_foreground.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + diff --git a/sample-java/src/main/res/drawable/ic_launcher_background.xml b/sample-java/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..867f14a --- /dev/null +++ b/sample-java/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,74 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sample-java/src/main/res/layout/activity_main.xml b/sample-java/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..10ea343 --- /dev/null +++ b/sample-java/src/main/res/layout/activity_main.xml @@ -0,0 +1,18 @@ + + + +