Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Gradle pre-commit hook to docs #6892

Open
wants to merge 12 commits into
base: main
Choose a base branch
from
83 changes: 80 additions & 3 deletions website/docs/gettingstarted/git-pre-commit-hook.md
Expand Up @@ -40,11 +40,88 @@ 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
## Only run on staged files - Gradle
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This part should be moved before the CLI, as the initial script suggests to use ./gradlew.

So this page will look like:

  1. Run gradlew on everything
  2. Run gradlew only on modified files
  3. Run CLI only on modified files

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved to the top


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.
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.

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.
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
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) }
}
}
```

Then we need to configure `Detekt` task and change its `source` from the entire `src` foler (by default) to only set of
matejdro marked this conversation as resolved.
Show resolved Hide resolved
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 {
if (project.hasProperty("precommit")) {
dependsOn(gitPreCommitFileList)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this needed? And, if so, where is this task defined?

Copy link
Contributor Author

@matejdro matejdro Apr 23, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, forgot to remove this one. Will delete it. Good catch.


val rootDir = project.rootDir
val projectDir = projectDir

val fileCollection = files()

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

fileCollection.setFrom(*stagedFilesFromThisProject.toTypedArray())

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.

Expand Down
@@ -1,7 +1,7 @@
---
title: "Run detekt using a Git pre-commit hook"
keywords: [detekt, static, analysis, code, kotlin]
sidebar:
sidebar:
permalink: git-pre-commit-hook.html
folder: gettingstarted
summary:
Expand Down Expand Up @@ -33,20 +33,97 @@ rm $OUTPUT

The shell script can be installed by copying the content over to `<<your-repo>>/.git/hooks/pre-commit`.
This pre-commit hook needs to be executable, so you may need to change the permission (`chmod +x pre-commit`).
More information about Git hooks and how to install them can be found in
More information about Git hooks and how to install them can be found in
[Atlassian's tutorial](https://www.atlassian.com/git/tutorials/git-hooks).

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
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
## Only run on staged files - Gradle

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.
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.

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.
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`:

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.
```kotlin
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) }
}
}
```

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`:

```kotlin
tasks.withType<io.gitlab.arturbosch.detekt.Detekt>().configureEach {
if (project.hasProperty("precommit")) {
dependsOn(gitPreCommitFileList)

val rootDir = project.rootDir
val projectDir = projectDir

val fileCollection = files()

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

fileCollection.setFrom(*stagedFilesFromThisProject.toTypedArray())

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:

Expand Down
@@ -1,7 +1,7 @@
---
title: "Run detekt using a Git pre-commit hook"
keywords: [detekt, static, analysis, code, kotlin]
sidebar:
sidebar:
permalink: git-pre-commit-hook.html
folder: gettingstarted
summary:
Expand Down Expand Up @@ -33,20 +33,97 @@ rm $OUTPUT

The shell script can be installed by copying the content over to `<<your-repo>>/.git/hooks/pre-commit`.
This pre-commit hook needs to be executable, so you may need to change the permission (`chmod +x pre-commit`).
More information about Git hooks and how to install them can be found in
More information about Git hooks and how to install them can be found in
[Atlassian's tutorial](https://www.atlassian.com/git/tutorials/git-hooks).

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
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
## Only run on staged files - Gradle

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.
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.

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.
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`:

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.
```kotlin
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) }
}
}
```

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`:

```kotlin
tasks.withType<io.gitlab.arturbosch.detekt.Detekt>().configureEach {
if (project.hasProperty("precommit")) {
dependsOn(gitPreCommitFileList)

val rootDir = project.rootDir
val projectDir = projectDir

val fileCollection = files()

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

fileCollection.setFrom(*stagedFilesFromThisProject.toTypedArray())

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:

Expand Down