├── .gitignore ├── LICENSE ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── src ├── main ├── groovy │ └── com │ │ └── github │ │ └── nullstress │ │ ├── ArtifactMapBuilder.groovy │ │ ├── ArtifactResolver.groovy │ │ ├── DependencyAnalysisPlugin.groovy │ │ ├── asm │ │ ├── ASMDependencyAnalyzer.java │ │ └── SourceSetScanner.java │ │ ├── model │ │ └── Artifact.groovy │ │ └── tasks │ │ └── AnalyzeTask.groovy └── resources │ └── META-INF │ └── gradle-plugins │ └── dependencyAnalysis.properties └── test ├── groovy └── com │ └── github │ └── nullstress │ ├── ArtifactMapBuilderTest.groovy │ ├── ArtifactResolverTest.groovy │ ├── DependencyAnalysisTest.groovy │ └── asm │ └── SourceSetScannerTest.java └── resources ├── commons-cli-1.0.jar ├── fake.jar ├── notajar ├── test.class └── testclassdir └── test.class /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | build/ 3 | *.iml 4 | *.iws 5 | *.ipr 6 | .idea/ 7 | out/ 8 | target/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Deprecated 2 | 3 | Please use https://github.com/nebula-plugins/gradle-lint-plugin/wiki/Unused-Dependency-Rule 4 | 5 | # Gradle-dependency-analysis-plugin 6 | 7 | A gradle dependency analysis plugin inspired by the maven dependency plugin and https://gist.github.com/kellyrob99/4334483. -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'nu.studer.plugindev' version '1.0.3' 3 | } 4 | apply plugin: 'groovy' 5 | apply plugin: 'idea' 6 | apply plugin: 'maven' 7 | 8 | group = 'com.github.nullstress' 9 | version = '1.0.3' 10 | 11 | def compatibilityVersion = 1.6 12 | sourceCompatibility = compatibilityVersion 13 | targetCompatibility = compatibilityVersion 14 | 15 | repositories { 16 | mavenCentral() 17 | } 18 | 19 | dependencies { 20 | compile localGroovy() 21 | compile gradleApi() 22 | compile 'org.ow2.asm:asm:4.2' 23 | compile 'commons-io:commons-io:2.4' 24 | 25 | testCompile 'junit:junit:4.11' 26 | testCompile 'org.mockito:mockito-core:1.9.5' 27 | testCompile 'com.cyrusinnovation:mockito-groovy-support:1.3' 28 | } 29 | 30 | task wrapper(type: Wrapper) { 31 | gradleVersion = '2.2.1' 32 | } 33 | 34 | plugindev { 35 | pluginId = 'com.github.nullstress' 36 | pluginImplementationClass 'com.github.nullstress.DependencyAnalysisPlugin' 37 | pluginDescription 'Gradle plugin that finds unused dependencies, declared and transitive.' 38 | pluginLicenses 'Apache-2.0' 39 | pluginTags 'dependencies', 'analysis' 40 | authorId 'nullStress' 41 | authorName 'Kristian Lund' 42 | authorEmail 'klund1986@gmail.com' 43 | projectUrl 'https://github.com/NullStress/gradle-dependency-analysis-plugin' 44 | projectIssuesUrl 'https://github.com/NullStress/gradle-dependency-analysis-plugin/issues' 45 | projectVcsUrl 'https://github.com/NullStress/gradle-dependency-analysis-plugin.git' 46 | projectInceptionYear '2014' 47 | done() 48 | } 49 | 50 | bintray { 51 | user = 'nullstress' 52 | key = '7612fe6ad55731712d1a4cd58af79e8309c0541e' 53 | pkg { 54 | repo = 'plugin' 55 | } 56 | } 57 | 58 | 59 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NullStress/gradle-dependency-analysis-plugin/715acda8ed560d60b947537302d98d75f85b6dad/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Dec 22 00:10:15 CET 2014 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-bin.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /src/main/groovy/com/github/nullstress/ArtifactMapBuilder.groovy: -------------------------------------------------------------------------------- 1 | package com.github.nullstress 2 | 3 | import com.github.nullstress.asm.SourceSetScanner 4 | import com.github.nullstress.model.Artifact 5 | import org.gradle.api.Project 6 | import org.slf4j.Logger 7 | import org.slf4j.LoggerFactory 8 | 9 | /** 10 | * Created with IntelliJ IDEA. 11 | * User: Kristian 12 | * Date: 02.08.14 13 | * Time: 18:09 14 | */ 15 | class ArtifactMapBuilder { 16 | Logger logger = LoggerFactory.getLogger('gradle-logger') 17 | 18 | Set findArtifactClasses(Artifact artifact) throws IOException { 19 | File file = artifact.getAbsoluteFile() 20 | if (file.name.endsWith('.jar')) { 21 | def scanner = new SourceSetScanner() 22 | return scanner.analyzeJar(file.toURI().toURL()) 23 | } else { 24 | return null; 25 | } 26 | } 27 | 28 | void buildUsedArtifacts(Set artifacts, Set dependencyClasses) { 29 | dependencyClasses.each { String className -> 30 | logger.debug("Checking for classname: *$className*") 31 | 32 | artifacts.each { 33 | Artifact artifact -> 34 | if(artifact.containedClasses.contains(className + ".class")) { 35 | logger.info("match for artifact " + artifact.name) 36 | artifact.setIsUsed(true) 37 | } 38 | } 39 | 40 | } 41 | } 42 | 43 | Collection analyzeClassDependencies(Project project) { 44 | return project.sourceSets*.output.classesDir?.collect {File file -> 45 | logger.debug("Analyzing: " + file.name) 46 | def scanner = new SourceSetScanner() 47 | scanner.analyze(file.toURI()) 48 | }?.flatten()?.unique() 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/groovy/com/github/nullstress/ArtifactResolver.groovy: -------------------------------------------------------------------------------- 1 | package com.github.nullstress 2 | 3 | import com.github.nullstress.model.Artifact 4 | import org.gradle.api.Project 5 | import org.gradle.api.artifacts.ResolvedDependency 6 | 7 | /** 8 | * Created with IntelliJ IDEA. 9 | * User: Kristian 10 | * Date: 22.11.14 11 | * Time: 22:52 12 | */ 13 | class ArtifactResolver { 14 | 15 | Project project 16 | ArtifactMapBuilder artifactMapBuilder 17 | 18 | ArtifactResolver(Project project, ArtifactMapBuilder artifactMapBuilder) { 19 | this.project = project 20 | this.artifactMapBuilder = artifactMapBuilder 21 | } 22 | 23 | Set findUnusedArtifact(Set artifacts, String typeOfArtifactSet) { 24 | Set unusedArtifacts = artifacts.findAll { 25 | Artifact artifact -> 26 | !artifact.isUsed 27 | } 28 | project.logger.quiet "unused$typeOfArtifactSet Artifacts" 29 | unusedArtifacts.each {project.logger.quiet(it.name)} 30 | return unusedArtifacts 31 | } 32 | 33 | Set resolveArtifacts(Set dependencyArtifacts, String typeOfArtifactSet) { 34 | dependencyArtifacts.each { 35 | Artifact artifact -> 36 | artifact.setContainedClasses(artifactMapBuilder.findArtifactClasses(artifact)) 37 | } 38 | 39 | Set dependencyClasses = artifactMapBuilder.analyzeClassDependencies(project) 40 | project.logger.info "dependencyClasses = $dependencyClasses" 41 | 42 | artifactMapBuilder.buildUsedArtifacts(dependencyArtifacts, dependencyClasses) 43 | Set usedArtifacts = dependencyArtifacts.findAll { 44 | Artifact artifact -> 45 | artifact.isUsed 46 | } 47 | project.logger.quiet "used$typeOfArtifactSet Artifacts" 48 | usedArtifacts.each {project.logger.quiet(it.name)} 49 | 50 | return usedArtifacts 51 | } 52 | 53 | Set getTransitiveDependencies(Set firstLevelModuleDependencies) { 54 | Set transitiveDeps = new HashSet<>() 55 | firstLevelModuleDependencies.each { 56 | ResolvedDependency resolvedDependency -> 57 | transitiveDeps.addAll(unionMinusIntersectionOfResolvedDependencySets(transitiveDeps, resolvedDependency.children)) 58 | } as Set 59 | return transitiveDeps 60 | } 61 | 62 | Set unionMinusIntersectionOfResolvedDependencySets(Set transitiveCollection, Set children) { 63 | Set toBeAdded = new HashSet<>() 64 | Set names = new HashSet<>() 65 | transitiveCollection.each { 66 | names.add(it.name) 67 | } 68 | children.each { 69 | project.logger.quiet("names = $names") 70 | if(!names.contains(it.name)) { 71 | project.logger.quiet("adding " + it.name) 72 | toBeAdded.add(it) 73 | names.add(it.name) 74 | } 75 | } 76 | return toBeAdded 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /src/main/groovy/com/github/nullstress/DependencyAnalysisPlugin.groovy: -------------------------------------------------------------------------------- 1 | package com.github.nullstress 2 | 3 | /* 4 | * Licensed to the Apache Software Foundation (ASF) under one 5 | * or more contributor license agreements. See the NOTICE file 6 | * distributed with this work for additional information 7 | * regarding copyright ownership. The ASF licenses this file 8 | * to you under the Apache License, Version 2.0 (the 9 | * "License"); you may not use this file except in compliance 10 | * with the License. You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, 15 | * software distributed under the License is distributed on an 16 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 | * KIND, either express or implied. See the License for the 18 | * specific language governing permissions and limitations 19 | * under the License. 20 | */ 21 | 22 | import com.github.nullstress.tasks.AnalyzeTask 23 | import org.gradle.api.Plugin 24 | import org.gradle.api.Project 25 | 26 | /** 27 | * Created with IntelliJ IDEA. 28 | * User: Kristian 29 | * Date: 10.07.14 30 | * Time: 00:18 31 | */ 32 | class DependencyAnalysisPlugin implements Plugin { 33 | 34 | void apply(Project project) { 35 | project.tasks.create("analyze", AnalyzeTask) 36 | } 37 | } -------------------------------------------------------------------------------- /src/main/groovy/com/github/nullstress/asm/ASMDependencyAnalyzer.java: -------------------------------------------------------------------------------- 1 | package com.github.nullstress.asm; 2 | 3 | /* 4 | * Licensed to the Apache Software Foundation (ASF) under one 5 | * or more contributor license agreements. See the NOTICE file 6 | * distributed with this work for additional information 7 | * regarding copyright ownership. The ASF licenses this file 8 | * to you under the Apache License, Version 2.0 (the 9 | * "License"); you may not use this file except in compliance 10 | * with the License. You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, 15 | * software distributed under the License is distributed on an 16 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 | * KIND, either express or implied. See the License for the 18 | * specific language governing permissions and limitations 19 | * under the License. 20 | */ 21 | 22 | import org.objectweb.asm.*; 23 | 24 | import java.util.HashSet; 25 | import java.util.Set; 26 | 27 | public class ASMDependencyAnalyzer extends ClassVisitor implements Opcodes { 28 | 29 | private Set classes; 30 | 31 | ASMDependencyAnalyzer() { 32 | super(ASM4); 33 | classes = new HashSet(); 34 | } 35 | 36 | 37 | public void visit(int version, int access, String name, 38 | String signature, String superName, String[] interfaces) { 39 | if (signature == null) { 40 | addName( superName ); 41 | addNames( interfaces ); 42 | } 43 | else { 44 | addSignature( signature ); 45 | } 46 | } 47 | public void visitSource(String source, String debug) { 48 | } 49 | 50 | public void visitOuterClass(String owner, String name, String desc) { 51 | } 52 | 53 | public AnnotationVisitor visitAnnotation(String desc, boolean visible) { 54 | addDesc( desc ); 55 | return null; 56 | } 57 | 58 | @Override 59 | public void visitAttribute(Attribute attribute) { 60 | } 61 | 62 | public void visitInnerClass(String name, String outerName, 63 | String innerName, int access) { 64 | } 65 | 66 | public FieldVisitor visitField(int access, String name, String desc, 67 | String signature, Object value) { 68 | if (signature == null) { 69 | addDesc( desc ); 70 | } else { 71 | addTypeSignature( signature ); 72 | } 73 | 74 | if (value instanceof Type) { 75 | addType( (Type) value ); 76 | } 77 | return null; 78 | } 79 | public MethodVisitor visitMethod(int access, String name, 80 | String desc, String signature, String[] exceptions) { 81 | if (signature == null) { 82 | addMethodDesc( desc ); 83 | } else { 84 | addSignature(signature); 85 | } 86 | 87 | addNames( exceptions ); 88 | return null; 89 | } 90 | public void visitEnd() { 91 | } 92 | 93 | public Set getClasses() { 94 | return classes; 95 | } 96 | 97 | // private methods -------------------------------------------------------- 98 | 99 | private void addName( String name ) 100 | { 101 | if (name == null) { 102 | return; 103 | } 104 | 105 | // decode arrays 106 | if (name.startsWith( "[L" ) && name.endsWith( ";" )) { 107 | name = name.substring( 2, name.length() - 1 ); 108 | } 109 | 110 | // decode internal representation 111 | name = name.replace( '/', '.' ); 112 | 113 | classes.add( name ); 114 | } 115 | 116 | private void addNames(final String[] names) { 117 | if (names == null) { 118 | return; 119 | } 120 | 121 | for (String name : names) { 122 | addName( name ); 123 | } 124 | } 125 | 126 | private void addDesc(final String desc) { 127 | addType( Type.getType( desc ) ); 128 | } 129 | 130 | private void addMethodDesc(final String desc) { 131 | addType(Type.getReturnType(desc)); 132 | Type[] types = Type.getArgumentTypes(desc); 133 | 134 | for (Type type : types) { 135 | addType(type); 136 | } 137 | } 138 | 139 | private void addType(final Type t) { 140 | switch (t.getSort()) { 141 | case Type.ARRAY: 142 | addType( t.getElementType() ); 143 | break; 144 | 145 | case Type.OBJECT: 146 | addName( t.getClassName().replace( '.', '/' ) ); 147 | break; 148 | } 149 | } 150 | 151 | private void addSignature(final String signature) { 152 | if (signature != null) { 153 | // new SignatureReader( signature ).accept( this ); 154 | } 155 | } 156 | 157 | private void addTypeSignature(final String signature) { 158 | if (signature != null) { 159 | // new SignatureReader( signature ).acceptType( this ); 160 | } 161 | } 162 | 163 | } 164 | -------------------------------------------------------------------------------- /src/main/groovy/com/github/nullstress/asm/SourceSetScanner.java: -------------------------------------------------------------------------------- 1 | package com.github.nullstress.asm; 2 | 3 | /* 4 | * Licensed to the Apache Software Foundation (ASF) under one 5 | * or more contributor license agreements. See the NOTICE file 6 | * distributed with this work for additional information 7 | * regarding copyright ownership. The ASF licenses this file 8 | * to you under the Apache License, Version 2.0 (the 9 | * "License"); you may not use this file except in compliance 10 | * with the License. You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, 15 | * software distributed under the License is distributed on an 16 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 | * KIND, either express or implied. See the License for the 18 | * specific language governing permissions and limitations 19 | * under the License. 20 | */ 21 | 22 | import org.apache.commons.io.FileUtils; 23 | import org.objectweb.asm.ClassReader; 24 | 25 | import java.io.File; 26 | import java.io.IOException; 27 | import java.io.InputStream; 28 | import java.net.URI; 29 | import java.net.URL; 30 | import java.util.Collection; 31 | import java.util.HashSet; 32 | import java.util.Set; 33 | import java.util.jar.JarEntry; 34 | import java.util.jar.JarInputStream; 35 | 36 | /** 37 | * Created with IntelliJ IDEA. 38 | * User: Kristian 39 | * Date: 13.07.14 40 | * Time: 11:57 41 | */ 42 | public class SourceSetScanner { 43 | 44 | public Set analyzeJar(URL url) { 45 | Set dependencies = new HashSet(); 46 | try { 47 | JarInputStream in = new JarInputStream(url.openStream()); 48 | JarEntry entry; 49 | 50 | while (( entry = in.getNextJarEntry()) != null ) { 51 | String name = entry.getName(); 52 | 53 | if (name.endsWith( ".class" )){ 54 | dependencies.add(name.replaceAll("/", ".")); 55 | } 56 | } 57 | in.close(); 58 | } catch (IOException e){ 59 | e.printStackTrace(); 60 | } 61 | return dependencies; 62 | } 63 | 64 | public Set analyze(URI uri) { 65 | Set dependencies = new HashSet(); 66 | try { 67 | File startDir = new File(uri); 68 | if(!startDir.isDirectory()) { 69 | return dependencies; 70 | } 71 | Collection files = FileUtils.listFiles(startDir, new String[]{"class"}, true); 72 | for(File file : files) { 73 | dependencies.addAll(scanFile(FileUtils.openInputStream(file))); 74 | } 75 | } catch (IOException e) { 76 | e.printStackTrace(); 77 | } 78 | return dependencies; 79 | } 80 | 81 | protected Set scanFile(InputStream inputStream){ 82 | Set dependencies = new HashSet(); 83 | try { 84 | ClassReader reader = new ClassReader(inputStream); 85 | ASMDependencyAnalyzer visitor = new ASMDependencyAnalyzer(); 86 | 87 | reader.accept( visitor, 0 ); 88 | dependencies.addAll( visitor.getClasses() ); 89 | } 90 | catch (IOException exception) { 91 | exception.printStackTrace(); 92 | } 93 | catch (IndexOutOfBoundsException e) { 94 | // some bug inside ASM causes an IOB exception. Log it and move on? 95 | // this happens when the class isn't valid. 96 | // System.out.println( "Unable to process: stream" ); 97 | } 98 | return dependencies; 99 | } 100 | 101 | 102 | 103 | 104 | } 105 | -------------------------------------------------------------------------------- /src/main/groovy/com/github/nullstress/model/Artifact.groovy: -------------------------------------------------------------------------------- 1 | package com.github.nullstress.model 2 | 3 | /** 4 | * Created with IntelliJ IDEA. 5 | * User: Kristian 6 | * Date: 19.10.14 7 | * Time: 16:14 8 | */ 9 | class Artifact { 10 | 11 | private File absoluteFile; 12 | private String name; 13 | private Set containedClasses; 14 | private boolean isUsed; 15 | 16 | Artifact(File absoluteFile, String name) { 17 | this.absoluteFile = absoluteFile 18 | this.name = name 19 | isUsed = false 20 | } 21 | 22 | File getAbsoluteFile() { 23 | return absoluteFile 24 | } 25 | 26 | String getName() { 27 | return name 28 | } 29 | 30 | Set getContainedClasses() { 31 | return containedClasses 32 | } 33 | 34 | void setContainedClasses(Set containedClasses) { 35 | this.containedClasses = containedClasses 36 | } 37 | 38 | boolean getIsUsed() { 39 | return isUsed 40 | } 41 | 42 | void setIsUsed(boolean used) { 43 | isUsed = used 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/groovy/com/github/nullstress/tasks/AnalyzeTask.groovy: -------------------------------------------------------------------------------- 1 | package com.github.nullstress.tasks 2 | 3 | import com.github.nullstress.ArtifactMapBuilder 4 | import com.github.nullstress.ArtifactResolver 5 | import com.github.nullstress.asm.SourceSetScanner 6 | import com.github.nullstress.model.Artifact 7 | import org.gradle.api.DefaultTask 8 | import org.gradle.api.GradleException 9 | 10 | /* 11 | * Licensed to the Apache Software Foundation (ASF) under one 12 | * or more contributor license agreements. See the NOTICE file 13 | * distributed with this work for additional information 14 | * regarding copyright ownership. The ASF licenses this file 15 | * to you under the Apache License, Version 2.0 (the 16 | * "License"); you may not use this file except in compliance 17 | * with the License. You may obtain a copy of the License at 18 | * 19 | * http://www.apache.org/licenses/LICENSE-2.0 20 | * 21 | * Unless required by applicable law or agreed to in writing, 22 | * software distributed under the License is distributed on an 23 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 24 | * KIND, either express or implied. See the License for the 25 | * specific language governing permissions and limitations 26 | * under the License. 27 | */ 28 | 29 | import org.gradle.api.artifacts.Configuration 30 | import org.gradle.api.artifacts.ModuleVersionIdentifier 31 | import org.gradle.api.artifacts.ResolvedDependency 32 | import org.gradle.api.tasks.TaskAction 33 | 34 | /** 35 | * Created with IntelliJ IDEA. 36 | * User: Kristian 37 | * Date: 10.07.14 38 | * Time: 00:00 39 | */ 40 | 41 | class AnalyzeTask extends DefaultTask { 42 | 43 | SourceSetScanner dependencyAnalyzer 44 | ArtifactMapBuilder artifactMapBuilder 45 | ArtifactResolver artifactResolver 46 | 47 | AnalyzeTask() { 48 | this.dependencyAnalyzer = new SourceSetScanner() 49 | this.artifactMapBuilder = new ArtifactMapBuilder() 50 | this.artifactResolver = new ArtifactResolver(project, artifactMapBuilder) 51 | } 52 | 53 | @TaskAction 54 | void analyze() { 55 | if (!project.plugins.hasPlugin('java')) { 56 | throw new IllegalStateException("Project does not have the java plugin applied.") 57 | } 58 | 59 | project.configurations.each { 60 | if(it.name.toLowerCase().contains("compile")) { 61 | project.logger.quiet("Dependencies for configuration " + it.name) 62 | Set firstLevelDeps = getFirstLevelDependencies(it) 63 | Set transitiveDeps = artifactResolver.getTransitiveDependencies(firstLevelDeps) 64 | 65 | Set dependencyArtifacts = findModuleArtifactFiles(firstLevelDeps) 66 | Set transitiveDependencyArtifacts = findModuleArtifactFiles(transitiveDeps) 67 | 68 | Set usedArtifacts = artifactResolver.resolveArtifacts(dependencyArtifacts, "Declared") 69 | Set usedTransitiveArtifacts = artifactResolver.resolveArtifacts(transitiveDependencyArtifacts, "Transitive") 70 | 71 | Set unusedArtifacts = artifactResolver.findUnusedArtifact(dependencyArtifacts, "Declared") 72 | Set unusedTransitiveArtifacts = artifactResolver.findUnusedArtifact(transitiveDependencyArtifacts, "Transitive") 73 | 74 | if(!unusedArtifacts.empty) { 75 | throw new GradleException("The project has unused declared artifacts") 76 | } 77 | } 78 | } 79 | } 80 | 81 | Set getFirstLevelDependencies(Configuration configuration) { 82 | configuration.resolvedConfiguration.firstLevelModuleDependencies 83 | } 84 | 85 | Set findModuleArtifactFiles(Set dependencies) { 86 | Set artifactSet = new LinkedHashSet<>() 87 | dependencies*.moduleArtifacts*.each { 88 | String classifier = it.getClassifier() ? ":${it.getClassifier()}" : "" 89 | ModuleVersionIdentifier identifier = it.getModuleVersion().getId() 90 | artifactSet.add(new Artifact(it.getFile(), identifier.group + ":" + identifier.name + ":" + identifier.version + classifier + "." + it.getExtension())) 91 | } 92 | return artifactSet 93 | } 94 | 95 | } 96 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/gradle-plugins/dependencyAnalysis.properties: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright 2010 the original author or authors. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | implementation-class=com.github.nullstress.DependencyAnalysisPlugin -------------------------------------------------------------------------------- /src/test/groovy/com/github/nullstress/ArtifactMapBuilderTest.groovy: -------------------------------------------------------------------------------- 1 | package com.github.nullstress 2 | 3 | import com.github.nullstress.asm.SourceSetScanner 4 | import com.github.nullstress.model.Artifact 5 | import org.junit.After 6 | import org.junit.Before 7 | import org.junit.Test 8 | 9 | import static org.junit.Assert.*; 10 | 11 | /** 12 | * Created with IntelliJ IDEA. 13 | * User: Kristian 14 | * Date: 02.08.14 15 | * Time: 18:11 16 | */ 17 | class ArtifactMapBuilderTest { 18 | 19 | SourceSetScanner scanner 20 | 21 | Set dependencyClasses 22 | File file = new File('src/test/resources/commons-cli-1.0.jar') 23 | Artifact commonsArtifact = new Artifact(file, "commons-cli:commons-cli:1.0") 24 | 25 | @Before 26 | public void setup() { 27 | 28 | } 29 | 30 | @After 31 | public void tearDown() { 32 | scanner = null 33 | } 34 | 35 | @Test 36 | public void findArtifactClassesShouldReturn0ForEmptyJar() { 37 | ArtifactMapBuilder artifactMapBuilder = new ArtifactMapBuilder() 38 | 39 | Artifact artifact = new Artifact(new File('/fake-1.23.jar'), "fake.org:fake:1.23") 40 | 41 | Set result = artifactMapBuilder.findArtifactClasses(artifact) 42 | 43 | assertEquals(0,result.size()) 44 | } 45 | 46 | @Test 47 | public void findArtifactClassesShouldReturn12CommonsCli() { 48 | ArtifactMapBuilder artifactMapBuilder = new ArtifactMapBuilder() 49 | Set result = artifactMapBuilder.findArtifactClasses(commonsArtifact) 50 | 51 | assertEquals(20,result.size()) 52 | } 53 | 54 | @Test 55 | public void buildUsedArtifactsShouldReturnArtifactOnMatch() { 56 | Artifact artifact = new Artifact(new File('/fake-1.23.jar'), "fake.org:fake:1.23") 57 | artifact.setContainedClasses(buildMatchingClassSet()) 58 | Set artifacts = new HashSet<>() 59 | artifacts.add(artifact) 60 | 61 | ArtifactMapBuilder artifactMapBuilder = new ArtifactMapBuilder() 62 | artifactMapBuilder.buildUsedArtifacts(artifacts, buildMatchingDependencyClassesSet()) 63 | assertTrue(artifact.isUsed) 64 | } 65 | 66 | @Test 67 | public void buildUsedArtifactsShouldNotReturnArtifactIfNoMatch() { 68 | Artifact artifact = new Artifact(new File('/fake-1.23.jar'), "fake.org:fake:1.23") 69 | Set stringSet = new HashSet<>() 70 | stringSet.add("fake.class") 71 | artifact.setContainedClasses(stringSet) 72 | Set artifacts = new HashSet<>() 73 | artifacts.add(artifact) 74 | 75 | ArtifactMapBuilder artifactMapBuilder = new ArtifactMapBuilder() 76 | artifactMapBuilder.buildUsedArtifacts(artifacts, buildNotMatchingDependencyClassesSet()) 77 | assertFalse(artifact.isUsed) 78 | } 79 | 80 | 81 | 82 | private Set buildMatchingDependencyClassesSet() { 83 | Set dependencySetThatShouldMatch = new HashSet<>() 84 | dependencySetThatShouldMatch.add("fake") 85 | return dependencySetThatShouldMatch 86 | } 87 | 88 | private Set buildNotMatchingDependencyClassesSet() { 89 | Set dependencySetThatShouldNotMatch = new HashSet<>() 90 | dependencySetThatShouldNotMatch.add("ShouldNotMatch") 91 | return dependencySetThatShouldNotMatch 92 | } 93 | 94 | private Set buildMatchingClassSet() { 95 | Set stringSet = new HashSet<>() 96 | stringSet.add("fake.class") 97 | stringSet.add("more.fake.class") 98 | return stringSet 99 | } 100 | 101 | } 102 | -------------------------------------------------------------------------------- /src/test/groovy/com/github/nullstress/ArtifactResolverTest.groovy: -------------------------------------------------------------------------------- 1 | package com.github.nullstress 2 | 3 | import com.github.nullstress.model.Artifact 4 | import org.gradle.api.artifacts.ResolvedDependency 5 | import org.gradle.api.internal.artifacts.DefaultModuleVersionIdentifier 6 | import org.gradle.api.internal.artifacts.DefaultResolvedDependency 7 | import org.gradle.testfixtures.ProjectBuilder 8 | import org.junit.Before 9 | import org.junit.Test 10 | 11 | import static org.mockito.Mockito.*; 12 | import static org.junit.Assert.*; 13 | 14 | 15 | 16 | /** 17 | * Created with IntelliJ IDEA. 18 | * User: Kristian 19 | * Date: 22.11.14 20 | * Time: 23:28 21 | */ 22 | class ArtifactResolverTest { 23 | 24 | Set artifacts = new HashSet<>() 25 | ArtifactResolver artifactResolver 26 | Set transitiveDeps 27 | Set children 28 | 29 | @Before 30 | public void setup() { 31 | Artifact usedArtifact = new Artifact(new File(".\testtrue"), "usedArtifact") 32 | usedArtifact.setIsUsed(true) 33 | Artifact notUsedArtifact = new Artifact(new File(".\testtrue"), "unusedArtifact") 34 | notUsedArtifact.setIsUsed(false) 35 | 36 | artifacts.add(usedArtifact) 37 | artifacts.add(notUsedArtifact) 38 | 39 | ArtifactMapBuilder artifactMapBuilder = mock(ArtifactMapBuilder.class) 40 | when(artifactMapBuilder.findArtifactClasses(any(Artifact.class))).thenReturn({""} as Set) 41 | 42 | ResolvedDependency resolvedDependency = new DefaultResolvedDependency(new DefaultModuleVersionIdentifier("test","test","test"), "Compile") 43 | ResolvedDependency resolvedDependency2 = new DefaultResolvedDependency(new DefaultModuleVersionIdentifier("test2","test2","test2"), "Compile") 44 | ResolvedDependency resolvedDependency3 = new DefaultResolvedDependency(new DefaultModuleVersionIdentifier("test3","test3","test3"), "Compile") 45 | ResolvedDependency resolvedDependency4 = new DefaultResolvedDependency(new DefaultModuleVersionIdentifier("test3","test3","test3"), "Compile") 46 | 47 | transitiveDeps = new HashSet<>() 48 | transitiveDeps.add(resolvedDependency3) 49 | 50 | children = new HashSet<>() 51 | children.add(resolvedDependency) 52 | children.add(resolvedDependency2) 53 | children.add(resolvedDependency4) 54 | 55 | // when(artifactMapBuilder.buildUsedArtifacts()).thenReturn() 56 | 57 | artifactResolver = new ArtifactResolver(ProjectBuilder.builder().build(), artifactMapBuilder) 58 | } 59 | 60 | @Test 61 | public void artifactResolverShouldFindUnusedArtifacts() { 62 | Set unusedArtifacts = artifactResolver.findUnusedArtifact(artifacts, "Compile") 63 | assertEquals(1, unusedArtifacts.size()) 64 | Artifact artifact = unusedArtifacts.iterator()[0] 65 | assertEquals("unusedArtifact", artifact.name) 66 | } 67 | 68 | @Test 69 | public void artifactResolverShouldFindUsedArtifacts() { 70 | Set usedArtifacts = artifactResolver.resolveArtifacts(artifacts, "Compile") 71 | assertEquals(1, usedArtifacts.size()) 72 | Artifact artifact = usedArtifacts.iterator()[0] 73 | assertEquals("usedArtifact", artifact.name) 74 | } 75 | 76 | @Test 77 | public void intersectionOfTwoSetsShouldBeFound() { 78 | Set intersection = artifactResolver.unionMinusIntersectionOfResolvedDependencySets(transitiveDeps, children) 79 | assertEquals(2, intersection.size()) 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/test/groovy/com/github/nullstress/DependencyAnalysisTest.groovy: -------------------------------------------------------------------------------- 1 | package com.github.nullstress 2 | 3 | import com.github.nullstress.asm.SourceSetScanner 4 | import com.github.nullstress.tasks.AnalyzeTask 5 | import org.gradle.api.Project 6 | import org.gradle.api.Task 7 | import org.gradle.testfixtures.ProjectBuilder 8 | import org.junit.Test 9 | import static org.junit.Assert.* 10 | 11 | class DependencyAnalysisTest { 12 | 13 | @Test 14 | public void dependencyAnalysisPluginAddsAnalyzeTaskToProject() { 15 | Project project = ProjectBuilder.builder().build() 16 | project.apply plugin: 'java' 17 | project.apply plugin: 'dependencyAnalysis' 18 | 19 | assertTrue(project.tasks.analyze instanceof AnalyzeTask) 20 | } 21 | 22 | @Test 23 | public void dependencyAnalysisPluginShouldLetJavaPluginBeAddedAfterDAPlugin() { 24 | Project project = ProjectBuilder.builder().build() 25 | project.apply plugin: 'dependencyAnalysis' 26 | project.apply plugin: 'java' 27 | 28 | assertTrue(project.tasks.analyze instanceof AnalyzeTask) 29 | } 30 | 31 | @Test 32 | public void analyzeTaskShouldWork() { 33 | Project project = ProjectBuilder.builder().build() 34 | project.apply plugin: 'dependencyAnalysis' 35 | project.apply plugin: 'java' 36 | 37 | Task analyze = project.tasks.analyze as AnalyzeTask 38 | assertTrue(analyze.dependencyAnalyzer instanceof SourceSetScanner) 39 | } 40 | 41 | @Test 42 | public void shouldWorkWithScalaPluginApplied() { 43 | Project project = ProjectBuilder.builder().build() 44 | project.apply plugin: 'dependencyAnalysis' 45 | project.apply plugin: 'scala' 46 | 47 | assertTrue(project.tasks.analyze instanceof AnalyzeTask) 48 | } 49 | } -------------------------------------------------------------------------------- /src/test/groovy/com/github/nullstress/asm/SourceSetScannerTest.java: -------------------------------------------------------------------------------- 1 | package com.github.nullstress.asm; 2 | 3 | import org.apache.commons.io.FileUtils; 4 | import org.junit.Test; 5 | 6 | import java.io.File; 7 | import java.io.IOException; 8 | import java.net.MalformedURLException; 9 | import java.net.URI; 10 | import java.util.Set; 11 | import static org.junit.Assert.*; 12 | 13 | /** 14 | * Created with IntelliJ IDEA. 15 | * User: Kristian 16 | * Date: 13.07.14 17 | * Time: 18:21 18 | */ 19 | public class SourceSetScannerTest { 20 | 21 | @Test 22 | public void sourceSetScannerShouldAddScanResultsToDependencies() throws IOException { 23 | SourceSetScanner sourceSetScanner = new SourceSetScanner(); 24 | File testClass = new File("src/test/resources/test.class"); 25 | Set dependencies = sourceSetScanner.scanFile(FileUtils.openInputStream(testClass)); 26 | 27 | assertEquals(1, dependencies.size()); 28 | assertTrue(dependencies.contains("javax.xml.stream.FactoryConfigurationError")); 29 | } 30 | 31 | @Test 32 | public void sourceSetScannerShouldResolveDirectoriesAndAnalyzeFiles() { 33 | SourceSetScanner sourceSetScanner = new SourceSetScanner(); 34 | File testClassFile = new File("src\\test\\resources"); 35 | URI testClassDir = testClassFile.toURI(); 36 | assertEquals(1, sourceSetScanner.analyze(testClassDir).size()); 37 | } 38 | 39 | @Test 40 | public void sourceSetScannerShouldReturnClassFilesFromJar() throws MalformedURLException { 41 | SourceSetScanner sourceSetScanner = new SourceSetScanner(); 42 | File jarFile = new File("src\\test\\resources\\commons-cli-1.0.jar"); 43 | assertEquals(20, sourceSetScanner.analyzeJar(jarFile.toURI().toURL()).size()); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/test/resources/commons-cli-1.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NullStress/gradle-dependency-analysis-plugin/715acda8ed560d60b947537302d98d75f85b6dad/src/test/resources/commons-cli-1.0.jar -------------------------------------------------------------------------------- /src/test/resources/fake.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NullStress/gradle-dependency-analysis-plugin/715acda8ed560d60b947537302d98d75f85b6dad/src/test/resources/fake.jar -------------------------------------------------------------------------------- /src/test/resources/notajar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NullStress/gradle-dependency-analysis-plugin/715acda8ed560d60b947537302d98d75f85b6dad/src/test/resources/notajar -------------------------------------------------------------------------------- /src/test/resources/test.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NullStress/gradle-dependency-analysis-plugin/715acda8ed560d60b947537302d98d75f85b6dad/src/test/resources/test.class -------------------------------------------------------------------------------- /src/test/resources/testclassdir/test.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NullStress/gradle-dependency-analysis-plugin/715acda8ed560d60b947537302d98d75f85b6dad/src/test/resources/testclassdir/test.class --------------------------------------------------------------------------------