-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpre-commit
executable file
·108 lines (87 loc) · 2.52 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#! /bin/bash
######## CONFIGURABLES ########
mapfile PROHIBITEDNAMES < <(echo -e ".*secrets.nix")
SECTION_HEADER="\033[0;36m====\033[0m%s\033[0;36m====\033[0m\n"
######## SETUP ##########
GITPATH=$( git rev-parse --show-toplevel )
# Get path to secrets, and do detection/error handling for that.
mapfile SECRETPATH < <( find $GITPATH -name secrets.nix )
if [[ "${#SECRETPATH[@]}" -ne 1 ]] then
echo "Error. More than one filepath with name 'secrets.nix' found."
for p in ${SECRETPATH[@]}; do echo ">" $p; done
exit 1
fi
# Get all paths staged for commit.
mapfile STAGED < <(\
git diff --name-only --cached |
xargs -I{} echo -n "$GITPATH/{} "
)
# If run as 'pre-commit all', add everything except the prohibited files.
if [[ $1 == "all" ]]; then
declare -a TOCHECK
for TF in $(git ls-files $GITPATH); do
for PF in ${PROHIBITEDNAMES[@]}; do
if [[ "$TF" =~ $PF ]]; then
SKIP=1
fi
done
if [[ -n $SKIP ]]; then
unset SKIP
else
TOCHECK+=($TF)
fi
done
else
# Otherwise, just check staged files
TOCHECK=("${STAGED[@]}")
fi
# Load and format variables from nixfile
mapfile NIXVARS < <( echo -e $( nix eval --impure --expr "
let l = (import <nixpkgs> {}).lib;
in l.strings.concatMapStringsSep \"\\n\" toString (
l.lists.flatten(
l.collect ( a: !builtins.isAttrs a) (import $SECRETPATH {})
)
)
" ) | tr -d '"' )
##### CHECKING #####
EXIT=0
printf $SECTION_HEADER "FORBIDDEN FILE CHECK"
for PF in ${PROHIBITEDNAMES[@]}; do
for SF in ${TOCHECK[@]}; do
if [[ "$SF" =~ $PF ]]; then
echo -e "File path '$SF' matched regex \033[1;31m$PF\033[0m"
FAIL=1
else
#echo " $SF != $PF"
true
fi
done
done
if [[ -n $FAIL ]]; then
EXIT=1
unset FAIL
else
echo -e "\033[1;32mPASS\033[1;0m"
fi
printf $SECTION_HEADER "SECRET STRING CHECK"
for FILE in ${TOCHECK[@]}; do
for VAR in ${NIXVARS[@]}; do
if [[ $(grep -c "$VAR" "$FILE") -ne 0 ]]; then
echo -e "\nFound prohibited string \033[1;31m$VAR\033[0m in $FILE"
echo "grep results: "
echo -e "\033[0;36m======\033[0m"
grep -n -C 3 --group-separator='======' --color=always \
"$VAR" "$FILE"
echo -e "\033[0;36m======\033[0m"
FAIL=1
fi
done
done
if [[ -n $FAIL ]]; then
EXIT=1
unset FAIL
else
echo -e "\033[1;32mPASS\033[1;0m"
fi
exit $EXIT