-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
pre-commit
executable file
·77 lines (61 loc) · 2.34 KB
/
pre-commit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/bin/sh
set -e
runKtlint () {
# Following code was generated automatically by running ./gradlew addKtlintFormatGitPreCommitHook
# for reference, see https://github.com/JLLeitschuh/ktlint-gradle#additional-helper-tasks
# and for the implementation, https://github.com/JLLeitschuh/ktlint-gradle/blob/master/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/GitHook.kt
# The only change made was replacing "exit" for "return", as this is running inside a function
######## KTLINT-GRADLE HOOK START ########
CHANGED_FILES="$(git --no-pager diff --name-status --no-color --cached | awk '$1 != "D" && $NF ~ /\.kts?$/ { print $NF }')"
if [ -z "$CHANGED_FILES" ]; then
echo "No Kotlin staged files."
return 0
fi;
echo "Running ktlint over these files:"
echo "$CHANGED_FILES"
diff=.git/unstaged-ktlint-git-hook.diff
git diff --color=never > $diff
if [ -s $diff ]; then
git apply -R $diff
fi
./gradlew --quiet ktlintFormat -PinternalKtlintGitFilter="$CHANGED_FILES"
gradle_command_exit_code=$?
echo "Completed ktlint run."
echo "$CHANGED_FILES" | while read -r file; do
if [ -f $file ]; then
git add $file
fi
done
if [ -s $diff ]; then
git apply --ignore-whitespace $diff
fi
rm $diff
unset diff
echo "Completed ktlint hook."
exit $gradle_command_exit_code
######## KTLINT-GRADLE HOOK END ########
}
runPrettier () {
# check if npx is installed, else skip runPrettier
if ! command -v npx &> /dev/null
then
echo "npx could not be found. Hence, skipping pre-commit Prettier run."
return 0
fi
CHANGED_JS_FILES="$(git --no-pager diff --name-status --no-color --cached | awk '$1 != "D" && $2 ~ /\.js/ { print $2 }')"
if [ -z "$CHANGED_JS_FILES" ]; then
echo "No Javascript staged files. Hence, skipping pre-commit Prettier run."
return 0
fi;
# Prettify changed files
echo "$CHANGED_JS_FILES" | xargs npx prettier --ignore-unknown --write
echo "Completed npx prettier run."
echo "$CHANGED_JS_FILES" | while read -r file; do
if [ -f "$file" ]; then
git add "$file"
fi
done
}
runKtlint
runPrettier || :; # || to avoid cancelling the commit if there is an error with Prettier
echo "Completed the pre-commit hook."