Skip to content

Commit

Permalink
Backport changes to old docs
Browse files Browse the repository at this point in the history
  • Loading branch information
matejdro committed Apr 22, 2024
1 parent 17f4f0e commit d234fd3
Show file tree
Hide file tree
Showing 5 changed files with 323 additions and 475 deletions.
Expand Up @@ -46,64 +46,25 @@ It is possible to configure Gradle to only run on staged files in pre-commit hoo
This has the advantage of speedier execution, by running on fewer files and
of lowered false positives by not scanning files that are not yet ready to be commited.

First, we need to declare `GitPreCommitFilesTask` task - a gradle task that will retrieve list of staged files
First, we need to declare a `getGitStagedFiles` function - a function task that will retrieve list of staged files
in a configuration-cache compatible way. Paste following into your project's `build.gradle.kts`:

```kotlin
abstract class GitPreCommitFilesTask : DefaultTask() {
@get:OutputFile
abstract val gitStagedListFile: RegularFileProperty

@TaskAction
fun taskAction() {
val gitProcess =
ProcessBuilder("git", "--no-pager", "diff", "--name-only", "--cached").start()
val error = gitProcess.errorStream.readBytes().decodeToString()
if (error.isNotBlank()) {
error("Git error : $error")
}

val gitVersion = gitProcess.inputStream.readBytes().decodeToString().trim()

gitStagedListFile.get().asFile.writeText(gitVersion)
}
}

fun GitPreCommitFilesTask.getStagedFiles(rootDir: File): Provider<List<File>> {
return gitStagedListFile.map {
try {
it.asFile.readLines()
fun Project.getGitStagedFiles(rootDir: File): Provider<List<File>> {
return providers.exec {
it.commandLine("git", "--no-pager", "diff", "--name-only", "--cached")
}.standardOutput.asText
.map { outputText ->
outputText.trim()
.split("\n")
.filter { it.isNotBlank() }
.map { File(rootDir, it) }
} catch (e: FileNotFoundException) {
// First build on configuration cache might fail
// see https://github.com/gradle/gradle/issues/19252
throw IllegalStateException(
"Failed to load git configuration. " +
"Please disable configuration cache for the first commit and " +
"try again",
e
)
}
}
}

val gitPreCommitFileList = tasks.register<GitPreCommitFilesTask>("gitPreCommitFileList") {
val targetFile = File(
project.layout.buildDirectory.asFile.get(),
"intermediates/gitPreCommitFileList/output"
)

targetFile.also {
it.parentFile.mkdirs()
gitStagedListFile.set(it)
}
outputs.upToDateWhen { false }
}
```

Then we need to configure `Detekt` task and change its `source` from the entire `src` foler (by default) to only set of
files that have been staged by git. Paste following into your project's `build.gradle.kts`::
files that have been staged by git. Paste following into your project's `build.gradle.kts`:

```kotlin
tasks.withType<io.gitlab.arturbosch.detekt.Detekt>().configureEach {
Expand All @@ -116,22 +77,37 @@ tasks.withType<io.gitlab.arturbosch.detekt.Detekt>().configureEach {
val fileCollection = files()

setSource(
gitPreCommitFileList.flatMap { task ->
task.getStagedFiles(rootDir)
.map { stagedFiles ->
val stagedFilesFromThisProject = stagedFiles
.filter { it.startsWith(projectDir) }
getGitStagedFiles(rootDir)
.map { stagedFiles ->
val stagedFilesFromThisProject = stagedFiles
.filter { it.startsWith(projectDir) }

fileCollection.setFrom(*stagedFilesFromThisProject.toTypedArray())
fileCollection.setFrom(*stagedFilesFromThisProject.toTypedArray())

fileCollection.asFileTree
}
}
fileCollection.asFileTree
}
)
}
}
```

Additionally, if your project uses `.gradle.kts` files and you want to use type resolution for pre-commit detekt checks,
you must exclude them from pre-commit hook. Otherwise, you will be unable to commit any changes to the
`.gradle.kts` files, since detekt pre-commit check would crash every time due to https://github.com/detekt/detekt/issues/5501:

```kotlin
afterEvaluate {
tasks.withType(Detekt::class.java).configureEach {
val typeResolutionEnabled = !classpath.isEmpty
if (typeResolutionEnabled && project.hasProperty("precommit")) {
// We must exclude kts files from pre-commit hook to prevent detekt from crashing
// This is a workaround for the https://github.com/detekt/detekt/issues/5501
exclude("*.gradle.kts")
}
}
}
```

Finally, we need to add `-Pprecommit=true` to the pre-commit script to tell Gradle to run detekt in "pre-commit mode".
For example, from above `detekt.sh`

Expand Down
Expand Up @@ -40,110 +40,31 @@ A special thanks goes to Mohit Sarveiya for providing this shell script.
You can watch his excellent talk about **Static Code Analysis For Kotlin** on
[YouTube](https://www.youtube.com/watch?v=LT6m5_LO2DQ).

## Only run on staged files - CLI

It is also possible to use [the CLI](/docs/gettingstarted/cli) to create a hook that only runs on staged files. This has the advantage of speedier execution, by running on fewer files and avoiding the warm-up time of the gradle daemon.

Please note, however, that a handful of checks requiring [type resolution](/docs/gettingstarted/type-resolution) will not work correctly with this approach. If you do adopt a partial hook, it is recommended that you still implement a full `detekt` check as part of your CI pipeline.

This example has been put together using [pre-commit](https://pre-commit.com/), but the same principle can be applied to any kind of hook.

Hook definition in pre-commit:

```yml
- id: detekt
name: detekt check
description: Runs `detekt` on modified .kt files.
language: script
entry: detekt.sh
files: \.kt
```

Script `detekt.sh`:

```bash
#!/bin/bash

echo "Running detekt check..."
fileArray=($@)
detektInput=$(IFS=,;printf "%s" "${fileArray[*]}")
echo "Input files: $detektInput"

OUTPUT=$(detekt --input "$detektInput" 2>&1)
EXIT_CODE=$?
if [ $EXIT_CODE -ne 0 ]; then
echo $OUTPUT
echo "***********************************************"
echo " detekt failed "
echo " Please fix the above issues before committing "
echo "***********************************************"
exit $EXIT_CODE
fi
```

## Only run on staged files - Gradle

If the CLI is not your cup of tea (you don't want to keep separate CLI binary set up, you want type resolution etc.),
you can also configure Gradle detekt to only run on staged files.
It is possible to configure Gradle to only run on staged files in pre-commit hook.
This has the advantage of speedier execution, by running on fewer files and
of lowered false positives by not scanning files that are not yet ready to be commited.

First, we need to declare `GitPreCommitFilesTask` task - a gradle task that will retrieve list of staged files
in a configuration-cache compatible way:
First, we need to declare a `getGitStagedFiles` function - a function task that will retrieve list of staged files
in a configuration-cache compatible way. Paste following into your project's `build.gradle.kts`:

```kotlin
abstract class GitPreCommitFilesTask : DefaultTask() {
@get:OutputFile
abstract val gitStagedListFile: RegularFileProperty

@TaskAction
fun taskAction() {
val gitProcess =
ProcessBuilder("git", "--no-pager", "diff", "--name-only", "--cached").start()
val error = gitProcess.errorStream.readBytes().decodeToString()
if (error.isNotBlank()) {
error("Git error : $error")
}

val gitVersion = gitProcess.inputStream.readBytes().decodeToString().trim()

gitStagedListFile.get().asFile.writeText(gitVersion)
}
}

fun GitPreCommitFilesTask.getStagedFiles(rootDir: File): Provider<List<File>> {
return gitStagedListFile.map {
try {
it.asFile.readLines()
fun Project.getGitStagedFiles(rootDir: File): Provider<List<File>> {
return providers.exec {
it.commandLine("git", "--no-pager", "diff", "--name-only", "--cached")
}.standardOutput.asText
.map { outputText ->
outputText.trim()
.split("\n")
.filter { it.isNotBlank() }
.map { File(rootDir, it) }
} catch (e: FileNotFoundException) {
// First build on configuration cache might fail
// see https://github.com/gradle/gradle/issues/19252
throw IllegalStateException(
"Failed to load git configuration. " +
"Please disable configuration cache for the first commit and " +
"try again",
e
)
}
}
}

val gitPreCommitFileList = tasks.register<GitPreCommitFilesTask>("gitPreCommitFileList") {
val targetFile = File(
project.layout.buildDirectory.asFile.get(),
"intermediates/gitPreCommitFileList/output"
)

targetFile.also {
it.parentFile.mkdirs()
gitStagedListFile.set(it)
}
outputs.upToDateWhen { false }
}
```

Then we need to configure `Detekt` task and change its `source` from the entire `src` foler (by default) to only set of
files that have been staged by git:
files that have been staged by git. Paste following into your project's `build.gradle.kts`:

```kotlin
tasks.withType<io.gitlab.arturbosch.detekt.Detekt>().configureEach {
Expand All @@ -156,29 +77,76 @@ tasks.withType<io.gitlab.arturbosch.detekt.Detekt>().configureEach {
val fileCollection = files()

setSource(
gitPreCommitFileList.flatMap { task ->
task.getStagedFiles(rootDir)
.map { stagedFiles ->
val stagedFilesFromThisProject = stagedFiles
.filter { it.startsWith(projectDir) }
getGitStagedFiles(rootDir)
.map { stagedFiles ->
val stagedFilesFromThisProject = stagedFiles
.filter { it.startsWith(projectDir) }

fileCollection.setFrom(*stagedFilesFromThisProject.toTypedArray())
fileCollection.setFrom(*stagedFilesFromThisProject.toTypedArray())

fileCollection.asFileTree
}
}
fileCollection.asFileTree
}
)
}
}
```

Additionally, if your project uses `.gradle.kts` files and you want to use type resolution for pre-commit detekt checks,
you must exclude them from pre-commit hook. Otherwise, you will be unable to commit any changes to the
`.gradle.kts` files, since detekt pre-commit check would crash every time due to https://github.com/detekt/detekt/issues/5501:

```kotlin
afterEvaluate {
tasks.withType(Detekt::class.java).configureEach {
val typeResolutionEnabled = !classpath.isEmpty
if (typeResolutionEnabled && project.hasProperty("precommit")) {
// We must exclude kts files from pre-commit hook to prevent detekt from crashing
// This is a workaround for the https://github.com/detekt/detekt/issues/5501
exclude("*.gradle.kts")
}
}
}
```

Finally, we need to add `-Pprecommit=true` to the pre-commit script to tell Gradle to run detekt in "pre-commit mode".
For example, from above `detekt.sh`

```bash
...
./gradlew -Pprecommit=true detekt > $OUTPUT
...
```

## Only run on staged files - CLI

It is also possible to use [the CLI](/docs/gettingstarted/cli) to create a hook that only runs on staged files. This has the advantage of speedier execution by avoiding the warm-up time of the gradle daemon.

Please note, however, that a handful of checks requiring [type resolution](/docs/gettingstarted/type-resolution) will not work correctly with this approach. If you do adopt a partial CLI hook, it is recommended that you still implement a full `detekt` check as part of your CI pipeline.

This example has been put together using [pre-commit](https://pre-commit.com/), but the same principle can be applied to any kind of hook.

Hook definition in pre-commit:

```yml
- id: detekt
name: detekt check
description: Runs `detekt` on modified .kt files.
language: script
entry: detekt.sh
files: \.kt
```

Script `detekt.sh`:

```bash
#!/bin/bash

echo "Running detekt check..."
OUTPUT=$(./gradlew -q --continue -Pprecommit=true detekt)
fileArray=($@)
detektInput=$(IFS=,;printf "%s" "${fileArray[*]}")
echo "Input files: $detektInput"

OUTPUT=$(detekt --input "$detektInput" 2>&1)
EXIT_CODE=$?
if [ $EXIT_CODE -ne 0 ]; then
echo $OUTPUT
Expand Down

0 comments on commit d234fd3

Please sign in to comment.