Skip to content

Commit

Permalink
quality(style): add task that installs a precommit hook that format code
Browse files Browse the repository at this point in the history
`./gradlew installPrecommitHook` backs up existing hook
The hook formats all changed files (staged or unstaged) and outputs a
warning about other files that do not conform to google code style
  • Loading branch information
Frey, David | Nemo authored and NemoOudeis committed Aug 21, 2018
1 parent 8cc3dc6 commit 429e02a
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
23 changes: 22 additions & 1 deletion quality/checkstyle/java.gradle
@@ -1,9 +1,13 @@
apply plugin: 'checkstyle'

import java.nio.file.Paths
import java.nio.file.Files
import java.nio.file.StandardCopyOption

// see https://docs.gradle.org/current/dsl/org.gradle.api.plugins.quality.CheckstyleExtension.html
checkstyle {
toolVersion '8.10' // see https://github.com/checkstyle/checkstyle/releases
configDir rootProject.file('config/quality/checkstyle')
configDir rootProject.file(Paths.get('config', 'quality', 'checkstyle'))
ignoreFailures false
showViolations true
maxErrors 0
Expand Down Expand Up @@ -33,3 +37,20 @@ task reformatJavaSources(
outputs.files(sources)
}

task installPrecommitHook {
doLast {
def hookFile = file(Paths.get(rootDir.absolutePath, '.git', 'hooks', 'pre-commit'))
if(hookFile.exists()) {
Files.copy(
Paths.get(hookFile.absolutePath),
Paths.get(hookFile.parent, "${hookFile.name}.${new Date().format('yyyymmdd-HH:mm')}.backup")
)
}
Files.copy(
Paths.get(rootDir.absolutePath, 'config', 'quality', 'checkstyle', 'pre-commit'),
Paths.get(hookFile.absolutePath),
StandardCopyOption.REPLACE_EXISTING
)
hookFile.setExecutable(true)
}
}
27 changes: 27 additions & 0 deletions quality/checkstyle/pre-commit
@@ -0,0 +1,27 @@
#!/bin/sh

# Git pre commit hook that reformats all staged and unstaged java files before commit.
# Files that do not comply to the code format but were staged or unstagd warned but ignored..
# The rationale is to enforce code style without creating "format all files" commits
# accidentally because that cleanup should be separate in a separate commit.

staged_files=$(git diff --name-only --cached)
unstaged_files=$(git diff --name-only)

# echo $unstaged_files | xargs git stash push -q
./gradlew reformatJavaSources
echo $staged_files | xargs git add # add all touched & reformatted files

changed_files=$(git ls-files -m)
# offenders = changed_files - unstaged_files
union="$(echo "$changed_files" ; echo "$unstaged_files")"
offenders="$(echo "$union" | sort | uniq -u)"
if [[ $offenders ]]; then
echo "😬 The following files are not conforming to our style guide, commit them separately after running ./gradlew reformatJavaSources\n"
echo "$offenders"
echo ""
fi

echo $offenders | xargs git checkout # discard reformat of untouched files

exit 0

0 comments on commit 429e02a

Please sign in to comment.