Skip to content

Commit

Permalink
Merge pull request #1 from mtrakal/feature/mermaid
Browse files Browse the repository at this point in the history
Feature/mermaid
  • Loading branch information
mtrakal authored Mar 12, 2024
2 parents 8be6a22 + 87dfe8a commit 276d389
Show file tree
Hide file tree
Showing 27 changed files with 633 additions and 251 deletions.
48 changes: 42 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,37 @@ plugins {
### Configuration
Rules are applied on the Gradle module and its `api` and `implementation` dependencies by default. Typically you would want to apply this in your final app module, however configuration for any module is possible. [Example](https://github.com/jraska/github-client/blob/master/app/build.gradle#L141)

```groovy
```kotlin
moduleGraphAssert {
maxHeight = 4
allowed = [':.* -> :core', ':feature.* -> :lib.*'] // regex to match module names
restricted = [':feature-[a-z]* -X> :forbidden-to-depend-on'] // regex to match module names
configurations = ['api', 'implementation'] // Dependency configurations to look. ['api', 'implementation'] is the default
assertOnAnyBuild = false // true value will run the assertions as part of any build without need to run the assert* tasks, false is default
// maxHeight = 4
// regex to match module names
allowed = setOf(".* -> :core", ":feature.* -> :lib.*")
// regex to match module names
restricted = setOf(":feature-[a-z]* -X> :forbidden-to-depend-on")
// Dependency configurations to look. ['api', 'implementation'] is the default
configurations = setOf("api", "implementation")
// true value will run the assertions as part of any build without need to run the assert* tasks, false is default
assertOnAnyBuild = true

// Output format for generated file (default is OutputFormat.GRAPHWIZ)
outputFormat = OutputFormat.MERMAID
// Output file path for generated graph file
outputFilePath = "$rootDir/dependency-graph.md"
}
```
<details>
<summary>Deprecated Groovy format</summary>

```groovy
moduleGraphAssert {
maxHeight = 4
allowed = [':.* -> :core', ':feature.* -> :lib.*'] // regex to match module names
restricted = [':feature-[a-z]* -X> :forbidden-to-depend-on'] // regex to match module names
configurations = ['api', 'implementation'] // Dependency configurations to look. ['api', 'implementation'] is the default
assertOnAnyBuild = false // true value will run the assertions as part of any build without need to run the assert* tasks, false is default
}
```
</details>

### Module name alias
- You don't have to rely on module names and set a property `ext.moduleNameAssertAlias = "ThisWillBeAssertedOn"`
Expand Down Expand Up @@ -87,6 +109,20 @@ moduleGraphAssert {
./gradlew generateModulesGraphvizText -Pmodules.graph.output.gv=all_modules
```

### Mermaid Graph Export
- Visualising the graph could be useful to help find your dependency issues, therefore a helper `generateModulesMermaidText` task is included.
- This generates a graph of dependent modules when the plugin is applied.
- The longest path of the project is in red.
- If you utilise [Configuration on demand](https://docs.gradle.org/current/userguide/multi_project_builds.html#sec:configuration_on_demand) Gradle feature, please use `--no-configure-on-demand` flag along the `generateModulesMermaidText` task.
- You can set the `modules.graph.of.module` parameter if you are only interested in a sub-graph of the module graph.
```
./gradlew --no-configure-on-demand generateModulesMermaidText -P "modules.graph.of.module=:feature-one"
```
- Adding the parameter `modules.graph.output.mermaid` saves the mermaid file to the specified path
```
./gradlew --no-configure-on-demand generateModulesMermaidText -P "modules.graph.output.mermaid=all_modules"
```

### Graph statistics
- Executing the task `generateModulesGraphStatistics` prints the information about the graph.
- Statistics printed: Modules Count, [Edges Count](https://en.wikipedia.org/wiki/Glossary_of_graph_theory_terms#edge), [Height](https://en.wikipedia.org/wiki/Glossary_of_graph_theory_terms#height) and [Longest Path](https://en.wikipedia.org/wiki/Longest_path_problem)
Expand Down
Binary file modified gradle/wrapper/gradle-wrapper.jar
Binary file not shown.
3 changes: 2 additions & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
22 changes: 13 additions & 9 deletions gradlew
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,8 @@ done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit

# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
Expand Down Expand Up @@ -130,26 +131,29 @@ 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.
if ! command -v java >/dev/null 2>&1
then
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
fi

# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
Expand Down Expand Up @@ -198,11 +202,11 @@ fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'

# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.

set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
Expand Down
20 changes: 10 additions & 10 deletions gradlew.bat
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,11 @@ set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute

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.
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2

goto fail

Expand All @@ -57,11 +57,11 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe

if exist "%JAVA_EXE%" goto execute

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.
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2

goto fail

Expand Down
8 changes: 4 additions & 4 deletions plugin/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,19 @@ repositories {

dependencies {
implementation gradleApi()
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"

testImplementation 'junit:junit:4.13.2'
}

compileKotlin {
kotlinOptions {
jvmTarget = "11"
jvmTarget = "17"
}
}
compileTestKotlin {
kotlinOptions {
jvmTarget = "11"
jvmTarget = "17"
}
}

Expand All @@ -36,7 +36,7 @@ gradlePlugin {
plugins {
modulesGraphAssert {
id = 'com.jraska.module.graph.assertion'
version = '2.5.0'
version = '3.0.0'
displayName = 'Modules Graph Assert'
description = 'Gradle plugin to keep your modules graph healthy and lean.'
implementationClass = 'com.jraska.module.graph.assertion.ModuleGraphAssertionsPlugin'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package com.jraska.module.graph.assertion

object Api {
object Tasks {
const val GROUP = "module graph assert"
const val GENERATE_GRAPHVIZ = "generateModulesGraphvizText"
const val GENERATE_MERMAID = "generateModulesMermaidText"
const val GENERATE_GRAPH_STATISTICS = "generateModulesGraphStatistics"

const val ASSERT_ALL = "assertModuleGraph"
Expand All @@ -14,6 +16,7 @@ object Api {
object Parameters {
const val PRINT_ONLY_MODULE = "modules.graph.of.module"
const val OUTPUT_PATH = "modules.graph.output.gv"
const val OUTPUT_PATH_MERMAID = "modules.graph.output.mermaid"
}

object Properties {
Expand All @@ -22,6 +25,5 @@ object Api {

const val EXTENSION_ROOT = "moduleGraphAssert"

val API_IMPLEMENTATON_CONFIGURATIONS = setOf("api", "implementation")
val API_IMPLEMENTATION_CONFIGURATIONS = setOf("api", "implementation")
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package com.jraska.module.graph.assertion

import com.jraska.module.graph.DependencyGraph
import org.gradle.api.Project
import java.io.File

class GenerateModulesGraph(
var aliases: Map<String, String>,
var onlyModuleToPrint: String? = null,
var dependencyGraph: DependencyGraph.SerializableGraph,
var outputFilePath: String? = null,
var outputFile: File? = null,
var outputFormat: OutputFormat = OutputFormat.GRAPHVIZ,
) {
fun run(path: String) {
val dependencyGraph =
DependencyGraph.create(dependencyGraph).let {
if (onlyModuleToPrint == null) {
it
} else {
it.subTree(onlyModuleToPrint!!)
}
}

val writer = outputFormat.writer.objectInstance
if (writer == null) {
print("No writer found for $outputFormat")
return
}

val graph = writer.toGraph(dependencyGraph, aliases)

if (outputFilePath != null) {
val file = File(outputFilePath!!)
file.writeText(graph)
outputFile = file
println("Graph saved to $path")
} else {
println(graph)
}
}

companion object {
internal fun outputFilePath(
project: Project,
outputFormat: OutputFormat,
): String? {
return when {
project.hasProperty(Api.Parameters.OUTPUT_PATH) && outputFormat.isGraphviz -> {
project.property(Api.Parameters.OUTPUT_PATH).toString()
}

project.hasProperty(Api.Parameters.OUTPUT_PATH_MERMAID) && outputFormat.isMermaid -> {
project.property(Api.Parameters.OUTPUT_PATH_MERMAID).toString()
}

else -> null
}
}

internal fun onlyModule(project: Project): String? {
if (project.hasProperty(Api.Parameters.PRINT_ONLY_MODULE)) {
return project.property(Api.Parameters.PRINT_ONLY_MODULE) as String?
} else {
return null
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,27 @@ package com.jraska.module.graph.assertion

open class GraphRulesExtension {
var maxHeight: Int = 0
var restricted = emptyArray<String>() // each restriction in format "regexp -X> regexp" e.g.: ":feature-[a-z]* -X> :forbidden-lib"
var allowed = emptyArray<String>() // each allowance in format "regexp -> regexp" e.g.: ":feature-[a-z]* -> :forbidden-lib"
var configurations: Set<String> = Api.API_IMPLEMENTATON_CONFIGURATIONS

/**
* each restriction in format "regexp -X> regexp" e.g.: ":feature-[a-z]* -X> :forbidden-lib"
*/
var restricted = emptySet<String>()

/**
* each allowance in format "regexp -> regexp" e.g.: ":feature-[a-z]* -> :forbidden-lib"
*/
var allowed = emptySet<String>()
var configurations: Set<String> = Api.API_IMPLEMENTATION_CONFIGURATIONS
var assertOnAnyBuild: Boolean = false

var outputFormat: OutputFormat = OutputFormat.GRAPHVIZ

/**
* When set, graph will be stored to this file in [outputFormat].
*/
var outputFilePath: String? = null

internal fun shouldAssertHeight() = maxHeight > 0

internal fun shouldAssertRestricted() = restricted.isNotEmpty()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package com.jraska.module.graph.assertion
class ModuleDependency(
val dependencyPair: Pair<String, String>,
private val fromAlias: String?,
private val toAlias: String?
private val toAlias: String?,
) {
private val from get() = dependencyPair.first
private val to get() = dependencyPair.second
Expand All @@ -21,18 +21,18 @@ class ModuleDependency(

if (fromAlias != null) {
stringBuilder.append("\"$fromAlias\"")
stringBuilder.append("('${from}')")
stringBuilder.append("('$from')")
} else {
stringBuilder.append("'${from}'")
stringBuilder.append("'$from'")
}

stringBuilder.append(" -> ")

if (toAlias != null) {
stringBuilder.append("\"$toAlias\"")
stringBuilder.append("('${to}')")
stringBuilder.append("('$to')")
} else {
stringBuilder.append("'${to}'")
stringBuilder.append("'$to'")
}

return stringBuilder.toString()
Expand All @@ -46,11 +46,27 @@ class ModuleDependency(
}
}

fun toDocText() : String {
fun toDocText(): String {
return if (toAlias != null) {
"$to('$toAlias')"
} else {
to
}
}

fun fromDocTextMermaid(): String {
return if (fromAlias != null) {
"$from($fromAlias)"
} else {
"$from($from)"
}
}

fun toDocTextMermaid(): String {
return if (toAlias != null) {
"$to($toAlias)"
} else {
"$to($to)"
}
}
}
Loading

0 comments on commit 276d389

Please sign in to comment.