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

Document pre-commit hook for staged files #4711

Merged
merged 5 commits into from Apr 24, 2022
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
46 changes: 45 additions & 1 deletion docs/pages/gettingstarted/git-pre-commit-hook.md
Expand Up @@ -10,7 +10,7 @@ summary:
Detekt can be integrated into your development workflow by using a Git pre-commit hook.
For that reason Git supports to run custom scripts automatically, when a specific action occurs.
The mentioned pre-commit hook can be setup locally on your dev-machine.
The following client-side detekt hook is triggered by a commit operation.
The following client-side detekt hook is triggered by a commit operation, and checks all files via the gradle task.

```bash
#!/usr/bin/env bash
Expand Down Expand Up @@ -38,3 +38,47 @@ More information about Git hooks and how to install them can be found in
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

It is also possible to use [the CLI](cli.md) 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](type-resolution.md) 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:
cortinico marked this conversation as resolved.
Show resolved Hide resolved

```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="/tmp/detekt-$(date +%s)"
detekt --input "$detektInput" > $OUTPUT
EXIT_CODE=$?
if [ $EXIT_CODE -ne 0 ]; then
cat $OUTPUT
rm $OUTPUT
echo "***********************************************"
echo " Detekt failed "
echo " Please fix the above issues before committing "
echo "***********************************************"
exit $EXIT_CODE
fi
rm $OUTPUT
```