|
1 | 1 | #!/bin/sh |
2 | 2 |
|
| 3 | +# Check dependencies |
| 4 | +check_command() { |
| 5 | + command -v "$1" > /dev/null 2>&1 || { echo "git-stats hook script requires the \`${1}\` binary in order to run." >&2; exit 1; } |
| 6 | +} |
| 7 | + |
| 8 | +check_command "perl" |
| 9 | +check_command "printf" |
| 10 | +check_command "git" |
| 11 | + |
3 | 12 | echo "Setting up git-stats hooks."; |
4 | 13 |
|
5 | 14 | # Create a new global templatedir if there are none |
6 | 15 | git_templates_dir=$(git config --global --get init.templatedir); |
7 | 16 | if [ $? -ne 0 ]; then |
| 17 | + # Create a new global templatedir if there are none |
8 | 18 | git_templates_dir="${HOME}/.git-templates" |
9 | | - git config --global init.templatedir "$git_templates_dir" |
| 19 | + git config --global init.templatedir "$git_templates_dir" && echo "Set new global git template dir at ${git_templates_dir}" |
10 | 20 | fi |
11 | | - |
12 | | -# Prepare some path variables |
13 | 21 | git_hooks_dir="${git_templates_dir}/hooks" |
14 | 22 | post_commit_path="${git_hooks_dir}/post-commit" |
15 | 23 |
|
16 | | -# Create the hook directory |
17 | 24 | mkdir -p "$git_hooks_dir" |
18 | 25 |
|
19 | 26 | # Create the post-commit file content |
20 | 27 | hook=$(cat <<EOF |
21 | | -
|
22 | 28 | ### git-stats hook (begin) ### |
23 | 29 | # Copy last commit hash to clipboard on commit |
24 | | -commit_hash=\`git rev-parse HEAD\` |
25 | | -repo_url=\`git config --get remote.origin.url\` |
26 | | -commit_date=\`git log -1 --format=%cd\` |
| 30 | +commit_hash=\$(git rev-parse HEAD) |
| 31 | +repo_url=\$(git config --get remote.origin.url) |
| 32 | +commit_date=\$(git log -1 --format=%cd) |
27 | 33 | commit_data="\"{ \"date\": \"\$commit_date\", \"url\": \"\$repo_url\", \"hash\": \"\$commit_hash\" }\"" |
28 | | -git-stats --record "\$commit_data" |
| 34 | +git-stats --record "\${commit_data}" |
29 | 35 | ### git-stats hook (end) ### |
30 | 36 | EOF |
31 | 37 | ); |
32 | 38 |
|
33 | | -# Does post-commit file exist? |
34 | 39 | if [ ! -f "$post_commit_path" ]; then |
35 | 40 | printf "#!/bin/sh\n%s" "$hook" > "$post_commit_path" \ |
36 | 41 | && chmod +x "$post_commit_path" \ |
37 | 42 | && echo "Successfully set up git-stats hook at ${post_commit_path}." \ |
38 | 43 | && exit 0 |
39 | 44 | else |
40 | | - printf "\n%s\n" "$hook" >> "$post_commit_path" \ |
| 45 | + # Remove any previous git-stats hook code blocks |
| 46 | + perl -i -0pe 's/(([ \t]*# Copy last commit hash to clipboard on commit\s*(\n.*){5}\s*git-stats --record "\$commit_data"\s*)|([ \t]*### git-stats hook \(begin\) ###\s*(\n.*){7}\s*### git-stats hook \(end\) ###\s*))//g' "$post_commit_path" |
| 47 | + printf "%s\n" "$hook" >> "$post_commit_path" \ |
41 | 48 | && echo "Successfully set up git-stats hook at ${post_commit_path}." \ |
42 | 49 | && exit 0 |
43 | 50 | fi |
|
0 commit comments