|
1 | 1 | #!/bin/sh |
2 | 2 |
|
3 | | -git_templates_dir="$HOME/.git-templates" |
4 | | -git_hooks_dir="$git_templates_dir/hooks" |
5 | | -post_commit_path="$git_hooks_dir/post-commit" |
| 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 | +} |
6 | 7 |
|
7 | | -git config --global init.templatedir $git_templates_dir |
8 | | -mkdir -p $git_hooks_dir |
| 8 | +check_command "perl" |
| 9 | +check_command "printf" |
| 10 | +check_command "git" |
9 | 11 |
|
10 | | -cat << EOF > $post_commit_path |
11 | | -#!/bin/sh |
| 12 | +echo "Setting up git-stats hooks."; |
| 13 | + |
| 14 | +# Create a new global templatedir if there are none |
| 15 | +git_templates_dir=$(git config --global --get init.templatedir); |
| 16 | +if [ $? -ne 0 ]; then |
| 17 | + # Create a new global templatedir if there are none |
| 18 | + git_templates_dir="${HOME}/.git-templates" |
| 19 | + git config --global init.templatedir "$git_templates_dir" && echo "Set new global git template dir at ${git_templates_dir}" |
| 20 | +fi |
| 21 | +git_hooks_dir="${git_templates_dir}/hooks" |
| 22 | +post_commit_path="${git_hooks_dir}/post-commit" |
12 | 23 |
|
| 24 | +mkdir -p "$git_hooks_dir" |
| 25 | + |
| 26 | +# Create the post-commit file content |
| 27 | +hook=$(cat <<EOF |
| 28 | +### git-stats hook (begin) ### |
13 | 29 | # Copy last commit hash to clipboard on commit |
14 | | -commit_hash=\`git rev-parse HEAD\` |
15 | | -repo_url=\`git config --get remote.origin.url\` |
16 | | -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) |
17 | 33 | commit_data="\"{ \"date\": \"\$commit_date\", \"url\": \"\$repo_url\", \"hash\": \"\$commit_hash\" }\"" |
18 | | -git-stats --record "\$commit_data" |
| 34 | +git-stats --record "\${commit_data}" |
| 35 | +### git-stats hook (end) ### |
19 | 36 | EOF |
| 37 | +); |
| 38 | + |
| 39 | +if [ ! -f "$post_commit_path" ]; then |
| 40 | + printf "#!/bin/sh\n%s" "$hook" > "$post_commit_path" \ |
| 41 | + && chmod +x "$post_commit_path" \ |
| 42 | + && echo "Successfully set up git-stats hook at ${post_commit_path}." \ |
| 43 | + && exit 0 |
| 44 | +else |
| 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" \ |
| 48 | + && echo "Successfully set up git-stats hook at ${post_commit_path}." \ |
| 49 | + && exit 0 |
| 50 | +fi |
20 | 51 |
|
21 | | -chmod +x $post_commit_path |
| 52 | +echo "Couldn't set up git-stats hook." |
| 53 | +exit 1 |
0 commit comments