TSK-1587: Pre-commit hook to ensure that all java files are formatted properly

This commit is contained in:
SebastianRoseneck 2021-04-14 11:30:16 +02:00 committed by Mustapha Zorgati
parent 2c5f97927b
commit 61d8ef65c8
3 changed files with 31 additions and 0 deletions

3
.gitignore vendored
View File

@ -64,3 +64,6 @@ Thumbs.db
# jenv on mac
/.java-version
# java-format
.java-format-cache

View File

@ -32,6 +32,7 @@
<!-- build dependencies -->
<version.checkstyle>8.41.1</version.checkstyle>
<version.google-java-format>1.10.0</version.google-java-format>
<version.maven.checkstyle>3.1.2</version.maven.checkstyle>
<version.maven.jar>3.2.0</version.maven.jar>
<version.maven.compiler>3.8.1</version.maven.compiler>
@ -98,6 +99,12 @@
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- Only necessary to automatically update the version for the pre-commit hook -->
<dependency>
<groupId>com.google.googlejavaformat</groupId>
<artifactId>google-java-format</artifactId>
<version>${version.google-java-format}</version>
</dependency>
</dependencies>
</dependencyManagement>

21
qa/hooks/pre-commit Normal file
View File

@ -0,0 +1,21 @@
#!/bin/bash
set -e # fail fast
VERSION=$( [[ "$(grep "<version.google-java-format>" < "pom.xml")" =~ .*\>([^\<]+)\<.* ]] && echo "${BASH_REMATCH[1]}" )
[[ -z "$VERSION" ]] && echo "Could not find version. Aborting commit." && exit 1
REPOSITORY_URL="https://github.com/google/google-java-format/releases/download/v${VERSION}/"
JAR_NAME="google-java-format-${VERSION}-all-deps.jar"
JAR_DOWNLOAD_URL="$REPOSITORY_URL$JAR_NAME"
CACHE_DIR=".java-format-cache"
mkdir -p "$CACHE_DIR"
[[ ! -f "$CACHE_DIR/$JAR_NAME" ]] && curl -LJf "$JAR_DOWNLOAD_URL" -o "$CACHE_DIR/$JAR_NAME"
changed_java_files=$(git diff --cached --name-only --diff-filter=ACMR | grep ".*java$" || true)
if [ -n "$changed_java_files" ]
then
java -jar "$CACHE_DIR/$JAR_NAME" --replace --skip-sorting-imports $changed_java_files;
git add $changed_java_files;
fi