Repository: JakeWharton/hugo Branch: master Commit: 50ee96dc07cd Files: 29 Total size: 46.3 KB Directory structure: gitextract_og_p6yd9/ ├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── LICENSE.txt ├── README.md ├── RELEASING.md ├── build.gradle ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── hugo-annotations/ │ ├── build.gradle │ └── src/ │ └── main/ │ └── java/ │ └── hugo/ │ └── weaving/ │ └── DebugLog.java ├── hugo-example/ │ ├── build.gradle │ └── src/ │ └── main/ │ ├── AndroidManifest.xml │ └── java/ │ └── com/ │ └── example/ │ └── hugo/ │ └── HugoActivity.java ├── hugo-plugin/ │ ├── build.gradle │ └── src/ │ └── main/ │ ├── groovy/ │ │ └── hugo/ │ │ └── weaving/ │ │ └── plugin/ │ │ ├── HugoExtension.groovy │ │ └── HugoPlugin.groovy │ └── resources/ │ └── META-INF/ │ └── gradle-plugins/ │ ├── com.jakewharton.hugo.properties │ └── hugo.properties ├── hugo-runtime/ │ ├── build.gradle │ ├── gradle.properties │ └── src/ │ ├── main/ │ │ ├── AndroidManifest.xml │ │ └── java/ │ │ └── hugo/ │ │ └── weaving/ │ │ └── internal/ │ │ ├── Hugo.java │ │ └── Strings.java │ └── test/ │ └── java/ │ └── hugo/ │ └── weaving/ │ └── internal/ │ └── StringsTest.java └── settings.gradle ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ .gradle local.properties .DS_Store .idea build *.iml ================================================ FILE: .travis.yml ================================================ language: android jdk: - oraclejdk7 - oraclejdk8 android: components: - build-tools-23.0.1 - android-23 # Update Android SDK Tools - tools branches: except: - gh-pages notifications: email: false ================================================ FILE: CHANGELOG.md ================================================ Change Log ========== Version 1.2.1 *(2015-02-17)* ---------------------------- * Fix: Enforce Java 1.7 compatibility for the plugin. Version 1.2.0 *(2015-02-12)* ---------------------------- * Plugin ID is now 'com.jakewharton.hugo' (instead of just 'hugo'). * Support annotating entire classes with `@DebugLog`. * Include thread names for non-main threads in the log. * Lower the minimum supported runtime to API 7. Woooo Eclair! * Log using verbose level. * Fix: Escape unprintable characters. * Fix: Eliminate intermittent VerifyError occurrences. Version 1.1.0 *(2014-04-05)* ---------------------------- * Support the 0.10.x Android plugin. Version 1.0.1 *(2013-12-08)* ---------------------------- * Support for printing primitive arrays. * Invocation time is now displayed before return value for convenience. * Logging is now enabled for all builds marked as debuggable. Version 1.0.0 *(2013-12-02)* ---------------------------- Initial release. ================================================ FILE: LICENSE.txt ================================================ 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 ================================================ Hugo ==== Annotation-triggered method call logging for your debug builds. As a programmer, you often add log statements to print method calls, their arguments, their return values, and the time it took to execute. This is not a question. Every one of you does this. Shouldn't it be easier? Simply add `@DebugLog` to your methods and you will automatically get all of the things listed above logged for free. ```java @DebugLog public String getName(String first, String last) { SystemClock.sleep(15); // Don't ever really do this! return first + " " + last; } ``` ``` V/Example: ⇢ getName(first="Jake", last="Wharton") V/Example: ⇠ getName [16ms] = "Jake Wharton" ``` The logging will only happen in debug builds and the annotation itself is never present in the compiled class file for any build type. This means you can keep the annotation and check it into source control. It has zero effect on non-debug builds. Add it to your project today! ```groovy buildscript { repositories { mavenCentral() } dependencies { classpath 'com.jakewharton.hugo:hugo-plugin:1.2.1' } } apply plugin: 'com.android.application' apply plugin: 'com.jakewharton.hugo' ``` Disable logging temporarily by adding the following: ```groovy hugo { enabled false } ``` If you want to toggle logging at runtime, use `Hugo.setEnabled(true|false)` Local Development ----------------- Working on this project? Here's some helpful Gradle tasks: * `install` - Install plugin, runtime, and annotations into local repo. * `cleanExample` - Clean the example project build. * `assembleExample` - Build the example project. Must run `install` first. * `installExample` - Build and install the example project debug APK onto a device. License -------- Copyright 2013 Jake Wharton 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: RELEASING.md ================================================ Release Process =============== 1. Update the `CHANGELOG.md` file with relevant info and date. 2. Update version number in `gradle.properties` file. 3. Update version number in `hugo-example/build.gradle` file. 4. Update version numbers in `HugoPlugin.groovy` file. 5. Update version number in `README.md` file. 6. Commit: `git commit -am "Prepare version X.Y.Z."` 7. Tag: `git tag -a X.Y.Z -m "Version X.Y.Z"` 8. Release: `./gradlew clean assemble uploadArchives` 9. Update version number in `gradle.properties` file to next "SNAPSHOT" version. 10. Update version number in `hugo-example/build.gradle` file to next "SNAPSHOT" version. 11. Update version numbers in `HugoPlugin.groovy` file to next "SNAPSHOT" version. 12. Commit: `git commit -am "Prepare next development version."` 13. Push: `git push && git push --tags` 14. Write a script for steps 2 - 13. *(Optional)* ================================================ FILE: build.gradle ================================================ buildscript { repositories { mavenCentral() jcenter() } dependencies { classpath 'org.gradle.api.plugins:gradle-nexus-plugin:0.7' classpath 'com.android.tools.build:gradle:1.3.1' classpath 'org.aspectj:aspectjtools:1.8.6' classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3' } } allprojects { repositories { mavenCentral() } group = GROUP version = VERSION_NAME apply plugin: 'maven' } ext { compileSdkVersion = 23 buildToolsVersion = '23.0.1' } task cleanExample(type: Exec) { executable = '../gradlew' workingDir = project.file('hugo-example') args = [ 'clean' ] } task assembleExample(type: Exec) { executable = '../gradlew' workingDir = project.file('hugo-example') args = [ 'assemble' ] } task installExample(type: Exec) { executable = '../gradlew' workingDir = project.file('hugo-example') args = [ 'installDebug' ] } ================================================ FILE: gradle/wrapper/gradle-wrapper.properties ================================================ #Mon Dec 08 15:44:09 PST 2014 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-2.8-all.zip ================================================ FILE: gradle.properties ================================================ VERSION_NAME=1.2.2-SNAPSHOT GROUP=com.jakewharton.hugo POM_DESCRIPTION=Annotation-triggered method call logging for your debug builds. POM_URL=https://github.com/JakeWharton/hugo/ POM_SCM_URL=https://github.com/JakeWharton/hugo/ POM_SCM_CONNECTION=scm:git@github.com/JakeWharton/hugo.git POM_SCM_DEV_CONNECTION=scm:git@github.com:JakeWharton/hugo.git POM_LICENCE_NAME=The Apache Software License, Version 2.0 POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt POM_LICENCE_DIST=repo POM_DEVELOPER_ID=jakewharton POM_DEVELOPER_NAME=Jake Wharton ================================================ FILE: gradlew ================================================ #!/usr/bin/env bash ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS="" APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # 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 case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; esac # For Cygwin, ensure paths are in UNIX format before anything is touched. if $cygwin ; then [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` fi # 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\"`/" >&- APP_HOME="`pwd -P`" cd "$SAVED" >&- 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" ] ; 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"` # 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 # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules function splitJvmOpts() { JVM_OPTS=("$@") } eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" ================================================ FILE: 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 @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= set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @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 Windowz variants if not "%OS%" == "Windows_NT" goto win9xME_args if "%@eval[2+2]" == "4" goto 4NT_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=%* goto execute :4NT_args @rem Get arguments from the 4NT Shell from JP Software 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: hugo-annotations/build.gradle ================================================ apply plugin: 'java' apply plugin: 'nexus' targetCompatibility = JavaVersion.VERSION_1_6 sourceCompatibility = JavaVersion.VERSION_1_6 modifyPom { project { name "Hugo Annotations" description POM_DESCRIPTION url POM_URL scm { url POM_SCM_URL connection POM_SCM_CONNECTION developerConnection POM_SCM_DEV_CONNECTION } licenses { license { name POM_LICENCE_NAME url POM_LICENCE_URL distribution POM_LICENCE_DIST } } developers { developer { id POM_DEVELOPER_ID name POM_DEVELOPER_NAME } } } } ================================================ FILE: hugo-annotations/src/main/java/hugo/weaving/DebugLog.java ================================================ package hugo.weaving; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.CONSTRUCTOR; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.CLASS; @Target({TYPE, METHOD, CONSTRUCTOR}) @Retention(CLASS) public @interface DebugLog { } ================================================ FILE: hugo-example/build.gradle ================================================ buildscript { dependencies { repositories { mavenCentral() // NOTE: This is only needed when developing the plugin! mavenLocal() } classpath 'com.android.tools.build:gradle:1.3.1' classpath 'com.jakewharton.hugo:hugo-plugin:1.2.2-SNAPSHOT' } } apply plugin: 'com.android.application' apply plugin: 'hugo' dependencies { repositories { mavenCentral() // NOTE: This is only needed when developing the plugin! mavenLocal() } } android { compileSdkVersion 23 buildToolsVersion '23.0.1' compileOptions { sourceCompatibility JavaVersion.VERSION_1_7 targetCompatibility JavaVersion.VERSION_1_7 } buildTypes { dev { applicationIdSuffix '.dev' } } } ================================================ FILE: hugo-example/src/main/AndroidManifest.xml ================================================ ================================================ FILE: hugo-example/src/main/java/com/example/hugo/HugoActivity.java ================================================ package com.example.hugo; import android.app.Activity; import android.os.Bundle; import android.os.SystemClock; import android.util.Log; import android.widget.TextView; import hugo.weaving.DebugLog; public class HugoActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv = new TextView(this); tv.setText("Check logcat!"); setContentView(tv); printArgs("The", "Quick", "Brown", "Fox"); Log.i("Fibonacci", "fibonacci's 4th number is " + fibonacci(4)); Greeter greeter = new Greeter("Jake"); Log.d("Greeting", greeter.sayHello()); Charmer charmer = new Charmer("Jake"); Log.d("Charming", charmer.askHowAreYou()); startSleepyThread(); } @DebugLog private void printArgs(String... args) { for (String arg : args) { Log.i("Args", arg); } } @DebugLog private int fibonacci(int number) { if (number <= 0) { throw new IllegalArgumentException("Number must be greater than zero."); } if (number == 1 || number == 2) { return 1; } // NOTE: Don't ever do this. Use the iterative approach! return fibonacci(number - 1) + fibonacci(number - 2); } private void startSleepyThread() { new Thread(new Runnable() { private static final long SOME_POINTLESS_AMOUNT_OF_TIME = 50; @Override public void run() { sleepyMethod(SOME_POINTLESS_AMOUNT_OF_TIME); } @DebugLog private void sleepyMethod(long milliseconds) { SystemClock.sleep(milliseconds); } }, "I'm a lazy thr.. bah! whatever!").start(); } @DebugLog static class Greeter { private final String name; Greeter(String name) { this.name = name; } private String sayHello() { return "Hello, " + name; } } @DebugLog static class Charmer { private final String name; private Charmer(String name) { this.name = name; } public String askHowAreYou() { return "How are you " + name + "?"; } } } ================================================ FILE: hugo-plugin/build.gradle ================================================ apply plugin: 'groovy' apply plugin: 'nexus' targetCompatibility = JavaVersion.VERSION_1_7 sourceCompatibility = JavaVersion.VERSION_1_7 dependencies { compile gradleApi() compile localGroovy() compile 'com.android.tools.build:gradle:1.3.1' compile 'org.aspectj:aspectjtools:1.8.6' compile 'org.aspectj:aspectjrt:1.8.6' } modifyPom { project { name "Hugo Plugin" description POM_DESCRIPTION url POM_URL scm { url POM_SCM_URL connection POM_SCM_CONNECTION developerConnection POM_SCM_DEV_CONNECTION } licenses { license { name POM_LICENCE_NAME url POM_LICENCE_URL distribution POM_LICENCE_DIST } } developers { developer { id POM_DEVELOPER_ID name POM_DEVELOPER_NAME } } } } ================================================ FILE: hugo-plugin/src/main/groovy/hugo/weaving/plugin/HugoExtension.groovy ================================================ package hugo.weaving.plugin class HugoExtension { def enabled = true def setEnabled(boolean enabled) { this.enabled = enabled } def getEnabled() { return enabled; } } ================================================ FILE: hugo-plugin/src/main/groovy/hugo/weaving/plugin/HugoPlugin.groovy ================================================ package hugo.weaving.plugin import com.android.build.gradle.AppPlugin import com.android.build.gradle.LibraryPlugin import org.aspectj.bridge.IMessage import org.aspectj.bridge.MessageHandler import org.aspectj.tools.ajc.Main import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.tasks.compile.JavaCompile class HugoPlugin implements Plugin { @Override void apply(Project project) { def hasApp = project.plugins.withType(AppPlugin) def hasLib = project.plugins.withType(LibraryPlugin) if (!hasApp && !hasLib) { throw new IllegalStateException("'android' or 'android-library' plugin required.") } final def log = project.logger final def variants if (hasApp) { variants = project.android.applicationVariants } else { variants = project.android.libraryVariants } project.dependencies { debugCompile 'com.jakewharton.hugo:hugo-runtime:1.2.2-SNAPSHOT' // TODO this should come transitively debugCompile 'org.aspectj:aspectjrt:1.8.6' compile 'com.jakewharton.hugo:hugo-annotations:1.2.2-SNAPSHOT' } project.extensions.create('hugo', HugoExtension) variants.all { variant -> if (!variant.buildType.isDebuggable()) { log.debug("Skipping non-debuggable build type '${variant.buildType.name}'.") return; } else if (!project.hugo.enabled) { log.debug("Hugo is not disabled.") return; } JavaCompile javaCompile = variant.javaCompile javaCompile.doLast { String[] args = [ "-showWeaveInfo", "-1.5", "-inpath", javaCompile.destinationDir.toString(), "-aspectpath", javaCompile.classpath.asPath, "-d", javaCompile.destinationDir.toString(), "-classpath", javaCompile.classpath.asPath, "-bootclasspath", project.android.bootClasspath.join(File.pathSeparator) ] log.debug "ajc args: " + Arrays.toString(args) MessageHandler handler = new MessageHandler(true); new Main().run(args, handler); for (IMessage message : handler.getMessages(null, true)) { switch (message.getKind()) { case IMessage.ABORT: case IMessage.ERROR: case IMessage.FAIL: log.error message.message, message.thrown break; case IMessage.WARNING: log.warn message.message, message.thrown break; case IMessage.INFO: log.info message.message, message.thrown break; case IMessage.DEBUG: log.debug message.message, message.thrown break; } } } } } } ================================================ FILE: hugo-plugin/src/main/resources/META-INF/gradle-plugins/com.jakewharton.hugo.properties ================================================ implementation-class=hugo.weaving.plugin.HugoPlugin ================================================ FILE: hugo-plugin/src/main/resources/META-INF/gradle-plugins/hugo.properties ================================================ implementation-class=hugo.weaving.plugin.HugoPlugin ================================================ FILE: hugo-runtime/build.gradle ================================================ import org.aspectj.bridge.IMessage import org.aspectj.bridge.MessageHandler import org.aspectj.tools.ajc.Main apply plugin: 'com.android.library' apply plugin: 'com.github.dcendents.android-maven' dependencies { compile 'org.aspectj:aspectjrt:1.8.6' compile project(':hugo-annotations') testCompile 'junit:junit:4.12' } android { compileSdkVersion rootProject.ext.compileSdkVersion buildToolsVersion rootProject.ext.buildToolsVersion compileOptions { sourceCompatibility JavaVersion.VERSION_1_7 targetCompatibility JavaVersion.VERSION_1_7 } } android.libraryVariants.all { variant -> JavaCompile javaCompile = variant.javaCompile javaCompile.doLast { String[] args = [ "-showWeaveInfo", "-1.5", "-inpath", javaCompile.destinationDir.toString(), "-aspectpath", javaCompile.classpath.asPath, "-d", javaCompile.destinationDir.toString(), "-classpath", javaCompile.classpath.asPath, "-bootclasspath", android.bootClasspath.join(File.pathSeparator) ] MessageHandler handler = new MessageHandler(true); new Main().run(args, handler) def log = project.logger for (IMessage message : handler.getMessages(null, true)) { switch (message.getKind()) { case IMessage.ABORT: case IMessage.ERROR: case IMessage.FAIL: log.error message.message, message.thrown break; case IMessage.WARNING: case IMessage.INFO: log.info message.message, message.thrown break; case IMessage.DEBUG: log.debug message.message, message.thrown break; } } } } ================================================ FILE: hugo-runtime/gradle.properties ================================================ POM_NAME=Hugo Runtime POM_ARTIFACT_ID=hugo-runtime POM_PACKAGING=aar ================================================ FILE: hugo-runtime/src/main/AndroidManifest.xml ================================================ ================================================ FILE: hugo-runtime/src/main/java/hugo/weaving/internal/Hugo.java ================================================ package hugo.weaving.internal; import android.os.Build; import android.os.Looper; import android.os.Trace; import android.util.Log; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.Signature; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.CodeSignature; import org.aspectj.lang.reflect.MethodSignature; import java.util.concurrent.TimeUnit; @Aspect public class Hugo { private static volatile boolean enabled = true; @Pointcut("within(@hugo.weaving.DebugLog *)") public void withinAnnotatedClass() {} @Pointcut("execution(!synthetic * *(..)) && withinAnnotatedClass()") public void methodInsideAnnotatedType() {} @Pointcut("execution(!synthetic *.new(..)) && withinAnnotatedClass()") public void constructorInsideAnnotatedType() {} @Pointcut("execution(@hugo.weaving.DebugLog * *(..)) || methodInsideAnnotatedType()") public void method() {} @Pointcut("execution(@hugo.weaving.DebugLog *.new(..)) || constructorInsideAnnotatedType()") public void constructor() {} public static void setEnabled(boolean enabled) { Hugo.enabled = enabled; } @Around("method() || constructor()") public Object logAndExecute(ProceedingJoinPoint joinPoint) throws Throwable { enterMethod(joinPoint); long startNanos = System.nanoTime(); Object result = joinPoint.proceed(); long stopNanos = System.nanoTime(); long lengthMillis = TimeUnit.NANOSECONDS.toMillis(stopNanos - startNanos); exitMethod(joinPoint, result, lengthMillis); return result; } private static void enterMethod(JoinPoint joinPoint) { if (!enabled) return; CodeSignature codeSignature = (CodeSignature) joinPoint.getSignature(); Class cls = codeSignature.getDeclaringType(); String methodName = codeSignature.getName(); String[] parameterNames = codeSignature.getParameterNames(); Object[] parameterValues = joinPoint.getArgs(); StringBuilder builder = new StringBuilder("\u21E2 "); builder.append(methodName).append('('); for (int i = 0; i < parameterValues.length; i++) { if (i > 0) { builder.append(", "); } builder.append(parameterNames[i]).append('='); builder.append(Strings.toString(parameterValues[i])); } builder.append(')'); if (Looper.myLooper() != Looper.getMainLooper()) { builder.append(" [Thread:\"").append(Thread.currentThread().getName()).append("\"]"); } Log.v(asTag(cls), builder.toString()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { final String section = builder.toString().substring(2); Trace.beginSection(section); } } private static void exitMethod(JoinPoint joinPoint, Object result, long lengthMillis) { if (!enabled) return; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { Trace.endSection(); } Signature signature = joinPoint.getSignature(); Class cls = signature.getDeclaringType(); String methodName = signature.getName(); boolean hasReturnType = signature instanceof MethodSignature && ((MethodSignature) signature).getReturnType() != void.class; StringBuilder builder = new StringBuilder("\u21E0 ") .append(methodName) .append(" [") .append(lengthMillis) .append("ms]"); if (hasReturnType) { builder.append(" = "); builder.append(Strings.toString(result)); } Log.v(asTag(cls), builder.toString()); } private static String asTag(Class cls) { if (cls.isAnonymousClass()) { return asTag(cls.getEnclosingClass()); } return cls.getSimpleName(); } } ================================================ FILE: hugo-runtime/src/main/java/hugo/weaving/internal/Strings.java ================================================ package hugo.weaving.internal; import java.util.Arrays; import java.util.HashSet; import java.util.Locale; import java.util.Set; final class Strings { static String toString(Object obj) { if (obj == null) { return "null"; } if (obj instanceof CharSequence) { return '"' + printableToString(obj.toString()) + '"'; } Class cls = obj.getClass(); if (Byte.class == cls) { return byteToString((Byte) obj); } if (cls.isArray()) { return arrayToString(cls.getComponentType(), obj); } return obj.toString(); } private static String printableToString(String string) { int length = string.length(); StringBuilder builder = new StringBuilder(length); for (int i = 0; i < length;) { int codePoint = string.codePointAt(i); switch (Character.getType(codePoint)) { case Character.CONTROL: case Character.FORMAT: case Character.PRIVATE_USE: case Character.SURROGATE: case Character.UNASSIGNED: switch (codePoint) { case '\n': builder.append("\\n"); break; case '\r': builder.append("\\r"); break; case '\t': builder.append("\\t"); break; case '\f': builder.append("\\f"); break; case '\b': builder.append("\\b"); break; default: builder.append("\\u").append(String.format("%04x", codePoint).toUpperCase(Locale.US)); break; } break; default: builder.append(Character.toChars(codePoint)); break; } i += Character.charCount(codePoint); } return builder.toString(); } private static String arrayToString(Class cls, Object obj) { if (byte.class == cls) { return byteArrayToString((byte[]) obj); } if (short.class == cls) { return Arrays.toString((short[]) obj); } if (char.class == cls) { return Arrays.toString((char[]) obj); } if (int.class == cls) { return Arrays.toString((int[]) obj); } if (long.class == cls) { return Arrays.toString((long[]) obj); } if (float.class == cls) { return Arrays.toString((float[]) obj); } if (double.class == cls) { return Arrays.toString((double[]) obj); } if (boolean.class == cls) { return Arrays.toString((boolean[]) obj); } return arrayToString((Object[]) obj); } /** A more human-friendly version of Arrays#toString(byte[]) that uses hex representation. */ private static String byteArrayToString(byte[] bytes) { StringBuilder builder = new StringBuilder("["); for (int i = 0; i < bytes.length; i++) { if (i > 0) { builder.append(", "); } builder.append(byteToString(bytes[i])); } return builder.append(']').toString(); } private static String byteToString(Byte b) { if (b == null) { return "null"; } return "0x" + String.format("%02x", b).toUpperCase(Locale.US); } private static String arrayToString(Object[] array) { StringBuilder buf = new StringBuilder(); arrayToString(array, buf, new HashSet()); return buf.toString(); } private static void arrayToString(Object[] array, StringBuilder builder, Set seen) { if (array == null) { builder.append("null"); return; } seen.add(array); builder.append('['); for (int i = 0; i < array.length; i++) { if (i > 0) { builder.append(", "); } Object element = array[i]; if (element == null) { builder.append("null"); } else { Class elementClass = element.getClass(); if (elementClass.isArray() && elementClass.getComponentType() == Object.class) { Object[] arrayElement = (Object[]) element; if (seen.contains(arrayElement)) { builder.append("[...]"); } else { arrayToString(arrayElement, builder, seen); } } else { builder.append(toString(element)); } } } builder.append(']'); seen.remove(array); } private Strings() { throw new AssertionError("No instances."); } } ================================================ FILE: hugo-runtime/src/test/java/hugo/weaving/internal/StringsTest.java ================================================ package hugo.weaving.internal; import java.math.BigInteger; import org.junit.Test; import static org.junit.Assert.assertEquals; public final class StringsTest { @Test public void nullValue() { assertEquals("null", Strings.toString(null)); } @Test public void string() { assertEquals("\"String\"", Strings.toString("String")); } @Test public void unprintableCharacters() { assertEquals("\"Str\\ning\"", Strings.toString("Str\ning")); assertEquals("\"\\n\\r\\t\\f\\b\\u202C\"", Strings.toString("\n\r\t\f\b\u202C")); } @Test public void objects() { assertEquals("1", Strings.toString(new BigInteger("1"))); } @Test public void byteValue() { byte primitive = (byte) 0xAB; assertEquals("0xAB", Strings.toString(primitive)); Byte boxed = primitive; assertEquals("0xAB", Strings.toString(boxed)); } @Test public void byteArrays() { byte[] primitive = { (byte) 0xAB, (byte) 0xBC, (byte) 0xCD, (byte) 0xDE, (byte) 0xEF }; assertEquals("[0xAB, 0xBC, 0xCD, 0xDE, 0xEF]", Strings.toString(primitive)); Byte[] boxed = { (byte) 0xAB, (byte) 0xBC, null, (byte) 0xDE, (byte) 0xEF }; assertEquals("[0xAB, 0xBC, null, 0xDE, 0xEF]", Strings.toString(boxed)); } @Test public void shortArrays() { short[] primitive = { 1, 2, 3, 4, 5 }; assertEquals("[1, 2, 3, 4, 5]", Strings.toString(primitive)); Short[] boxed = { 1, 2, null, 4, 5 }; assertEquals("[1, 2, null, 4, 5]", Strings.toString(boxed)); } @Test public void charArrays() { char[] primitive = { 'a', 'b', 'c', 'd', 'e' }; assertEquals("[a, b, c, d, e]", Strings.toString(primitive)); Character[] boxed = { 'a', 'b', null, 'd', 'e' }; assertEquals("[a, b, null, d, e]", Strings.toString(boxed)); } @Test public void intArrays() { int[] primitive = { 1, 2, 3, 4, 5 }; assertEquals("[1, 2, 3, 4, 5]", Strings.toString(primitive)); Integer[] boxed = { 1, 2, null, 4, 5 }; assertEquals("[1, 2, null, 4, 5]", Strings.toString(boxed)); } @Test public void longArrays() { long[] primitive = { 1, 2, 3, 4, 5 }; assertEquals("[1, 2, 3, 4, 5]", Strings.toString(primitive)); Long[] boxed = { 1L, 2L, null, 4L, 5L }; assertEquals("[1, 2, null, 4, 5]", Strings.toString(boxed)); } @Test public void floatArrays() { float[] primitive = { 1.1f, 2.2f, 3.3f, 4.4f, 5.5f }; assertEquals("[1.1, 2.2, 3.3, 4.4, 5.5]", Strings.toString(primitive)); Float[] boxed = { 1.1f, 2.2f, null, 4.4f, 5.5f }; assertEquals("[1.1, 2.2, null, 4.4, 5.5]", Strings.toString(boxed)); } @Test public void doubleArrays() { double[] primitive = { 1.1d, 2.2d, 3.3d, 4.4d, 5.5d }; assertEquals("[1.1, 2.2, 3.3, 4.4, 5.5]", Strings.toString(primitive)); Double[] boxed = { 1.1d, 2.2d, null, 4.4d, 5.5d }; assertEquals("[1.1, 2.2, null, 4.4, 5.5]", Strings.toString(boxed)); } @Test public void booleanArrays() { boolean[] primitive = { true, false, true, false, true }; assertEquals("[true, false, true, false, true]", Strings.toString(primitive)); Boolean[] boxed = { true, false, null, false, true }; assertEquals("[true, false, null, false, true]", Strings.toString(boxed)); } @Test public void objectArray() { Object[] array = { 1, true, "String", 1.1f, null, new BigInteger("1") }; assertEquals("[1, true, \"String\", 1.1, null, 1]", Strings.toString(array)); } @Test public void deepObjectArray() { Object[] array = { 1, true, "String", new Object[] { 1.1f, "Nested" } }; assertEquals("[1, true, \"String\", [1.1, \"Nested\"]]", Strings.toString(array)); } @Test public void recursiveObjectArray() { Object[] array = { 1, 2, 3, null }; array[3] = array; assertEquals("[1, 2, 3, [...]]", Strings.toString(array)); } } ================================================ FILE: settings.gradle ================================================ include ':hugo-annotations' include ':hugo-plugin' include ':hugo-runtime'