├── .gitignore ├── LICENSE ├── README.MD ├── build.gradle.kts ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── media └── resources-library.svg ├── settings.gradle.kts └── src └── main └── kotlin └── io └── github └── terrakok └── KmpHierarchyPlugin.kt /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | .idea 4 | .kotlin 5 | .DS_Store 6 | build 7 | */build 8 | captures 9 | local.properties 10 | secret.properties 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Konstantin Tskhovrebov 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -------------------------------------------------------------------------------- /README.MD: -------------------------------------------------------------------------------- 1 | # KMP-hierarchy 2 | ### Gradle Plugin to investigate KMP project's hierarchy 3 | 4 | -------------- 5 | This open-source Gradle plugin aims to help developers investigate 6 | the HMPP structure of Kotlin Multiplatform (KMP) source sets with ease. 7 | By graphically visualizing the relationships between source sets and clearly indicating their hierarchy, 8 | the plugin simplifies understanding and maintaining complex KMP projects. 9 | 10 | -------------- 11 | ## Features 12 | - Graphical visualization of dependencies between source sets 13 | - Seamless Integration with Gradle builds 14 | - Full compatibility with any KMP project 15 | - Various output formats (SVG, PNG, JSON, DOT etc) 16 | 17 | -------------- 18 | ## Installation 19 | To use KMP-hierarchy plugin, include the following in your build.gradle(.kts) file: 20 | ```kotlin 21 | plugins { 22 | id("io.github.terrakok.kmp-hierarchy").version("1.1") 23 | } 24 | ``` 25 | 26 | -------------- 27 | ## Usage 28 | After successful installation, the plugin will be ready to use. 29 | ```text 30 | ./gradlew :printHierarchy 31 | ``` 32 | Example of SVG output for [compose-multiplatform/components/resources/library](https://github.com/JetBrains/compose-multiplatform/blob/master/components/resources/library/build.gradle.kts) module: 33 | ![](https://raw.githubusercontent.com/terrakok/kmp-hierarchy/master/media/resources-library.svg) 34 | 35 | -------------- 36 | ## Configuration 37 | 38 | ```kotlin 39 | plugins { 40 | id("org.jetbrains.kotlin.multiplatform").version("1.9.23") 41 | id("io.github.terrakok.kmp-hierarchy").version("1.1") 42 | } 43 | 44 | kotlin { 45 | //... 46 | printHierarchy { 47 | //Sets the formats to be used for generating output files. 48 | formats(Format.SVG) 49 | 50 | //Boolean variable indicating whether to include test hierarchy in the generated output. 51 | withTestHierarchy = false 52 | 53 | //The output directory where the generated files will be saved. 54 | outputDir.set(layout.buildDirectory.dir("kmp-hierarchy")) 55 | } 56 | } 57 | ``` 58 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | kotlin("jvm") version "1.9.23" 3 | `java-gradle-plugin` 4 | id("com.gradle.plugin-publish") version "1.2.1" 5 | } 6 | 7 | dependencies { 8 | compileOnly(kotlin("gradle-plugin")) 9 | implementation("guru.nidi:graphviz-java:0.18.1") 10 | implementation("org.graalvm.js:js:20.0.0") 11 | } 12 | 13 | group = "io.github.terrakok" 14 | version = "1.1" 15 | 16 | gradlePlugin { 17 | website = "https://github.com/terrakok/kmp-hierarchy" 18 | vcsUrl = "https://github.com/terrakok/kmp-hierarchy" 19 | plugins { 20 | create("KmpHierarchyPlugin") { 21 | id = "io.github.terrakok.kmp-hierarchy" 22 | displayName = "KMP hierarchy plugin" 23 | description = "Simple gradle plugin for printing KMP source sets hierarchy." 24 | tags = listOf("kotlin", "kmp", "multiplatform", "debug", "build") 25 | implementationClass = "io.github.terrakok.KmpHierarchyPlugin" 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/terrakok/kmp-hierarchy/f8c4df596e82ccca486c0bc492e7731f5a88c251/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit 88 | 89 | # Use the maximum available, or set MAX_FD != -1 to use that value. 90 | MAX_FD=maximum 91 | 92 | warn () { 93 | echo "$*" 94 | } >&2 95 | 96 | die () { 97 | echo 98 | echo "$*" 99 | echo 100 | exit 1 101 | } >&2 102 | 103 | # OS specific support (must be 'true' or 'false'). 104 | cygwin=false 105 | msys=false 106 | darwin=false 107 | nonstop=false 108 | case "$( uname )" in #( 109 | CYGWIN* ) cygwin=true ;; #( 110 | Darwin* ) darwin=true ;; #( 111 | MSYS* | MINGW* ) msys=true ;; #( 112 | NONSTOP* ) nonstop=true ;; 113 | esac 114 | 115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 116 | 117 | 118 | # Determine the Java command to use to start the JVM. 119 | if [ -n "$JAVA_HOME" ] ; then 120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 121 | # IBM's JDK on AIX uses strange locations for the executables 122 | JAVACMD=$JAVA_HOME/jre/sh/java 123 | else 124 | JAVACMD=$JAVA_HOME/bin/java 125 | fi 126 | if [ ! -x "$JAVACMD" ] ; then 127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 128 | 129 | Please set the JAVA_HOME variable in your environment to match the 130 | location of your Java installation." 131 | fi 132 | else 133 | JAVACMD=java 134 | if ! command -v java >/dev/null 2>&1 135 | then 136 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | fi 142 | 143 | # Increase the maximum file descriptors if we can. 144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 145 | case $MAX_FD in #( 146 | max*) 147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 148 | # shellcheck disable=SC2039,SC3045 149 | MAX_FD=$( ulimit -H -n ) || 150 | warn "Could not query maximum file descriptor limit" 151 | esac 152 | case $MAX_FD in #( 153 | '' | soft) :;; #( 154 | *) 155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 156 | # shellcheck disable=SC2039,SC3045 157 | ulimit -n "$MAX_FD" || 158 | warn "Could not set maximum file descriptor limit to $MAX_FD" 159 | esac 160 | fi 161 | 162 | # Collect all arguments for the java command, stacking in reverse order: 163 | # * args from the command line 164 | # * the main class name 165 | # * -classpath 166 | # * -D...appname settings 167 | # * --module-path (only if needed) 168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 169 | 170 | # For Cygwin or MSYS, switch paths to Windows format before running java 171 | if "$cygwin" || "$msys" ; then 172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 174 | 175 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 176 | 177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 178 | for arg do 179 | if 180 | case $arg in #( 181 | -*) false ;; # don't mess with options #( 182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 183 | [ -e "$t" ] ;; #( 184 | *) false ;; 185 | esac 186 | then 187 | arg=$( cygpath --path --ignore --mixed "$arg" ) 188 | fi 189 | # Roll the args list around exactly as many times as the number of 190 | # args, so each arg winds up back in the position where it started, but 191 | # possibly modified. 192 | # 193 | # NB: a `for` loop captures its iteration list before it begins, so 194 | # changing the positional parameters here affects neither the number of 195 | # iterations, nor the values presented in `arg`. 196 | shift # remove old arg 197 | set -- "$@" "$arg" # push replacement arg 198 | done 199 | fi 200 | 201 | 202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 204 | 205 | # Collect all arguments for the java command: 206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 207 | # and any embedded shellness will be escaped. 208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 209 | # treated as '${Hostname}' itself on the command line. 210 | 211 | set -- \ 212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 213 | -classpath "$CLASSPATH" \ 214 | org.gradle.wrapper.GradleWrapperMain \ 215 | "$@" 216 | 217 | # Stop when "xargs" is not available. 218 | if ! command -v xargs >/dev/null 2>&1 219 | then 220 | die "xargs is not available" 221 | fi 222 | 223 | # Use "xargs" to parse quoted args. 224 | # 225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 226 | # 227 | # In Bash we could simply go: 228 | # 229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 230 | # set -- "${ARGS[@]}" "$@" 231 | # 232 | # but POSIX shell has neither arrays nor command substitution, so instead we 233 | # post-process each arg (as a line of input to sed) to backslash-escape any 234 | # character that might be a shell metacharacter, then use eval to reverse 235 | # that process (while maintaining the separation between arguments), and wrap 236 | # the whole thing up as a single "set" statement. 237 | # 238 | # This will of course break if any of these variables contains a newline or 239 | # an unmatched quote. 240 | # 241 | 242 | eval "set -- $( 243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 244 | xargs -n1 | 245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 246 | tr '\n' ' ' 247 | )" '"$@"' 248 | 249 | exec "$JAVACMD" "$@" 250 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 1>&2 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 48 | echo. 1>&2 49 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 50 | echo location of your Java installation. 1>&2 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 1>&2 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 62 | echo. 1>&2 63 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 64 | echo location of your Java installation. 1>&2 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 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 %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 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 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /media/resources-library.svg: -------------------------------------------------------------------------------- 1 | 3 | 4 | resources-library 5 | 6 | 7 | 8 | commonMain 9 | 10 | commonMain 11 | 12 | 13 | 14 | skikoMain 15 | 16 | skikoMain 17 | 18 | 19 | 20 | commonMain--skikoMain 21 | 22 | 23 | 24 | 25 | blockingMain 26 | 27 | blockingMain 28 | 29 | 30 | 31 | commonMain--blockingMain 32 | 33 | 34 | 35 | 36 | nativeMain 37 | 38 | nativeMain 39 | 40 | 41 | 42 | skikoMain--nativeMain 43 | 44 | 45 | 46 | 47 | desktopMain 48 | 49 | desktopMain 50 | 51 | 52 | 53 | skikoMain--desktopMain 54 | 55 | 56 | 57 | 58 | webMain 59 | 60 | webMain 61 | 62 | 63 | 64 | skikoMain--webMain 65 | 66 | 67 | 68 | 69 | blockingMain--nativeMain 70 | 71 | 72 | 73 | 74 | jvmAndAndroidMain 75 | 76 | jvmAndAndroidMain 77 | 78 | 79 | 80 | blockingMain--jvmAndAndroidMain 81 | 82 | 83 | 84 | 85 | appleMain 86 | 87 | appleMain 88 | 89 | 90 | 91 | nativeMain--appleMain 92 | 93 | 94 | 95 | 96 | jvmAndAndroidMain--desktopMain 97 | 98 | 99 | 100 | 101 | androidMain 102 | 103 | androidMain 104 | 105 | 106 | 107 | jvmAndAndroidMain--androidMain 108 | 109 | 110 | 111 | 112 | wasmJsMain 113 | 114 | wasmJsMain 115 | 116 | 117 | 118 | webMain--wasmJsMain 119 | 120 | 121 | 122 | 123 | jsMain 124 | 125 | jsMain 126 | 127 | 128 | 129 | webMain--jsMain 130 | 131 | 132 | 133 | 134 | macosMain 135 | 136 | macosMain 137 | 138 | 139 | 140 | appleMain--macosMain 141 | 142 | 143 | 144 | 145 | iosMain 146 | 147 | iosMain 148 | 149 | 150 | 151 | appleMain--iosMain 152 | 153 | 154 | 155 | 156 | macosX64Main 157 | 158 | macosX64Main 159 | 160 | 161 | 162 | macosMain--macosX64Main 163 | 164 | 165 | 166 | 167 | macosArm64Main 168 | 169 | macosArm64Main 170 | 171 | 172 | 173 | macosMain--macosArm64Main 174 | 175 | 176 | 177 | 178 | iosX64Main 179 | 180 | iosX64Main 181 | 182 | 183 | 184 | iosMain--iosX64Main 185 | 186 | 187 | 188 | 189 | iosSimulatorArm64Main 190 | 191 | iosSimulatorArm64Main 192 | 193 | 194 | 195 | iosMain--iosSimulatorArm64Main 196 | 197 | 198 | 199 | 200 | iosArm64Main 201 | 202 | iosArm64Main 203 | 204 | 205 | 206 | iosMain--iosArm64Main 207 | 208 | 209 | 210 | 211 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "kmp-hierarchy" 2 | 3 | pluginManagement { 4 | repositories { 5 | gradlePluginPortal() 6 | mavenCentral() 7 | } 8 | } 9 | 10 | dependencyResolutionManagement { 11 | repositories { 12 | mavenCentral() 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/kotlin/io/github/terrakok/KmpHierarchyPlugin.kt: -------------------------------------------------------------------------------- 1 | package io.github.terrakok 2 | 3 | import guru.nidi.graphviz.engine.Format 4 | import guru.nidi.graphviz.engine.Graphviz 5 | import guru.nidi.graphviz.model.Factory.graph 6 | import guru.nidi.graphviz.model.Factory.node 7 | import org.gradle.api.DefaultTask 8 | import org.gradle.api.Plugin 9 | import org.gradle.api.Project 10 | import org.gradle.api.file.DirectoryProperty 11 | import org.gradle.api.plugins.ExtensionAware 12 | import org.gradle.api.provider.ListProperty 13 | import org.gradle.api.provider.Property 14 | import org.gradle.api.provider.SetProperty 15 | import org.gradle.api.tasks.Input 16 | import org.gradle.api.tasks.OutputDirectory 17 | import org.gradle.api.tasks.TaskAction 18 | import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension 19 | import org.jetbrains.kotlin.gradle.plugin.KotlinCompilation 20 | import org.jetbrains.kotlin.gradle.plugin.KotlinPlatformType 21 | import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet 22 | import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinAndroidTarget 23 | import java.io.File 24 | import java.io.Serializable 25 | import javax.inject.Inject 26 | 27 | class KmpHierarchyPlugin : Plugin { 28 | override fun apply(target: Project) { 29 | val project = target 30 | project.pluginManager.withPlugin("org.jetbrains.kotlin.multiplatform") { 31 | val kotlinExt = project.extensions.getByType(KotlinMultiplatformExtension::class.java) 32 | 33 | val configDsl = (kotlinExt as ExtensionAware).extensions.create( 34 | "printHierarchy", 35 | KmpHierarchyConfig::class.java 36 | ) 37 | 38 | val config = project.provider { configDsl } 39 | 40 | project.tasks.register("printHierarchy", PrintHmppTask::class.java) { task -> 41 | task.graphName.set(project.path.replace(':', '-').removePrefix("-")) 42 | task.fileFormats.set(config.map { it.formats }) 43 | task.withTestHierarchy.set(config.map { it.withTestHierarchy }) 44 | task.targetHierarchy.set( 45 | project.provider { 46 | kotlinExt.targets 47 | .filter { target -> target.platformType != KotlinPlatformType.common } 48 | .flatMap { t -> t.compilations } 49 | .map { compilation -> 50 | TargetInfo( 51 | compilation.target.targetName, 52 | compilation.name, 53 | compilation.allKotlinSourceSets 54 | .filterNot { sourceSet -> isSpecificAndroidSourceSet(compilation, sourceSet) } 55 | .reversed() 56 | .associate { sourceSet -> sourceSet.name to sourceSet.parents() } 57 | ) 58 | } 59 | } 60 | ) 61 | task.outputDir.set(config.flatMap { it.outputDir }) 62 | } 63 | } 64 | } 65 | } 66 | 67 | private fun KotlinSourceSet.parents(): Set { 68 | val current = this.name 69 | return this.dependsOn 70 | .map { it.name } 71 | .toMutableSet().apply { 72 | remove(current) 73 | if (size > 1) { 74 | remove(KotlinSourceSet.COMMON_MAIN_SOURCE_SET_NAME) 75 | remove(KotlinSourceSet.COMMON_TEST_SOURCE_SET_NAME) 76 | } 77 | } 78 | } 79 | 80 | private val onlyCommon = setOf(KotlinSourceSet.COMMON_MAIN_SOURCE_SET_NAME, KotlinSourceSet.COMMON_TEST_SOURCE_SET_NAME) 81 | private fun isSpecificAndroidSourceSet(compilation: KotlinCompilation<*>, sourceSet: KotlinSourceSet): Boolean { 82 | if (compilation.target !is KotlinAndroidTarget) return false 83 | if (sourceSet != compilation.defaultSourceSet) return false 84 | val parents = sourceSet.parents() 85 | return parents.size == 1 && parents.single() in onlyCommon 86 | } 87 | 88 | abstract class KmpHierarchyConfig @Inject constructor(project: Project) { 89 | internal var formats: Set = setOf(Format.SVG) 90 | 91 | /** 92 | * Sets the formats to be used for generating output files. 93 | * 94 | * @param formats the formats to be used 95 | */ 96 | fun formats(vararg formats: Format) { 97 | this.formats = formats.toSet() 98 | } 99 | 100 | /** 101 | * Boolean variable indicating whether to include test hierarchy in the generated output. 102 | */ 103 | var withTestHierarchy: Boolean = false 104 | 105 | /** 106 | * The output directory where the generated files will be saved. 107 | */ 108 | abstract val outputDir: DirectoryProperty 109 | 110 | init { 111 | outputDir.convention(project.layout.buildDirectory.dir("kmp-hierarchy")) 112 | } 113 | } 114 | 115 | internal data class TargetInfo( 116 | val targetName: String, 117 | val compilationName: String, 118 | val sourceSetsHierarchy: Map> 119 | ) : Serializable { 120 | val isTest = compilationName.contains("test", ignoreCase = true) 121 | } 122 | 123 | internal abstract class PrintHmppTask : DefaultTask() { 124 | @get:Input 125 | abstract val targetHierarchy: ListProperty 126 | 127 | @get:Input 128 | abstract val fileFormats: SetProperty 129 | 130 | @get:Input 131 | abstract val withTestHierarchy: Property 132 | 133 | @get:Input 134 | abstract val graphName: Property 135 | 136 | @get:OutputDirectory 137 | abstract val outputDir: DirectoryProperty 138 | 139 | @TaskAction 140 | fun run() { 141 | val graphName = graphName.get() 142 | val formats = fileFormats.get() 143 | val withTest = withTestHierarchy.get() 144 | 145 | val hierarchy = targetHierarchy.get().filter { info -> withTest || !info.isTest } 146 | 147 | val dir = outputDir.get().asFile 148 | dir.deleteRecursively() 149 | dir.mkdirs() 150 | 151 | val g = graph(graphName).with( 152 | hierarchy.flatMap { targetInfo -> 153 | targetInfo.sourceSetsHierarchy.flatMap { (s, d) -> 154 | d.map { node(it).link(s) } 155 | } 156 | } 157 | ) 158 | 159 | formats.forEach { format -> 160 | val file = File(dir, graphName + ".${format.fileExtension.lowercase()}") 161 | Graphviz.fromGraph(g).render(format).toFile(file) 162 | logger.lifecycle("$graphName hierarchy ${format.name}: ${file.toURI()}") 163 | } 164 | } 165 | } --------------------------------------------------------------------------------