diff --git a/website/versioned_docs/version-1.23.1/gettingstarted/git-pre-commit-hook.md b/website/versioned_docs/version-1.23.1/gettingstarted/git-pre-commit-hook.md index 7e123d756fc..48b26f4d48f 100644 --- a/website/versioned_docs/version-1.23.1/gettingstarted/git-pre-commit-hook.md +++ b/website/versioned_docs/version-1.23.1/gettingstarted/git-pre-commit-hook.md @@ -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> { - return gitStagedListFile.map { - try { - it.asFile.readLines() +fun Project.getGitStagedFiles(rootDir: File): Provider> { + 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("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().configureEach { @@ -116,22 +77,37 @@ tasks.withType().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` diff --git a/website/versioned_docs/version-1.23.3/gettingstarted/git-pre-commit-hook.md b/website/versioned_docs/version-1.23.3/gettingstarted/git-pre-commit-hook.md index 2f8ae0d87ea..48b26f4d48f 100644 --- a/website/versioned_docs/version-1.23.3/gettingstarted/git-pre-commit-hook.md +++ b/website/versioned_docs/version-1.23.3/gettingstarted/git-pre-commit-hook.md @@ -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> { - return gitStagedListFile.map { - try { - it.asFile.readLines() +fun Project.getGitStagedFiles(rootDir: File): Provider> { + 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("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().configureEach { @@ -156,29 +77,76 @@ tasks.withType().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 diff --git a/website/versioned_docs/version-1.23.4/gettingstarted/git-pre-commit-hook.md b/website/versioned_docs/version-1.23.4/gettingstarted/git-pre-commit-hook.md index 0879d3b0fdf..48b26f4d48f 100644 --- a/website/versioned_docs/version-1.23.4/gettingstarted/git-pre-commit-hook.md +++ b/website/versioned_docs/version-1.23.4/gettingstarted/git-pre-commit-hook.md @@ -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: @@ -33,117 +33,38 @@ rm $OUTPUT The shell script can be installed by copying the content over to `<>/.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 - 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> { - return gitStagedListFile.map { - try { - it.asFile.readLines() +fun Project.getGitStagedFiles(rootDir: File): Provider> { + 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("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().configureEach { @@ -156,29 +77,76 @@ tasks.withType().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 diff --git a/website/versioned_docs/version-1.23.5/gettingstarted/git-pre-commit-hook.md b/website/versioned_docs/version-1.23.5/gettingstarted/git-pre-commit-hook.md index 0879d3b0fdf..48b26f4d48f 100644 --- a/website/versioned_docs/version-1.23.5/gettingstarted/git-pre-commit-hook.md +++ b/website/versioned_docs/version-1.23.5/gettingstarted/git-pre-commit-hook.md @@ -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: @@ -33,117 +33,38 @@ rm $OUTPUT The shell script can be installed by copying the content over to `<>/.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 - 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> { - return gitStagedListFile.map { - try { - it.asFile.readLines() +fun Project.getGitStagedFiles(rootDir: File): Provider> { + 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("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().configureEach { @@ -156,29 +77,76 @@ tasks.withType().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 diff --git a/website/versioned_docs/version-1.23.6/gettingstarted/git-pre-commit-hook.md b/website/versioned_docs/version-1.23.6/gettingstarted/git-pre-commit-hook.md index db157c7d366..48b26f4d48f 100644 --- a/website/versioned_docs/version-1.23.6/gettingstarted/git-pre-commit-hook.md +++ b/website/versioned_docs/version-1.23.6/gettingstarted/git-pre-commit-hook.md @@ -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: @@ -33,117 +33,38 @@ rm $OUTPUT The shell script can be installed by copying the content over to `<>/.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 - 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> { - return gitStagedListFile.map { - try { - it.asFile.readLines() +fun Project.getGitStagedFiles(rootDir: File): Provider> { + 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("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().configureEach { @@ -156,29 +77,76 @@ tasks.withType().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 @@ -188,4 +156,4 @@ if [ $EXIT_CODE -ne 0 ]; then echo "***********************************************" exit $EXIT_CODE fi -``` \ No newline at end of file +```