Skip to content

Instantly share code, notes, and snippets.

@steelbrain
Last active August 23, 2017 05:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save steelbrain/b0b6bb34f84cef391494087fe707c1a9 to your computer and use it in GitHub Desktop.
Save steelbrain/b0b6bb34f84cef391494087fe707c1a9 to your computer and use it in GitHub Desktop.
Fancy git commit
#!/bin/bash
# Author: Steel Brain <i@steelbrain.me>
# Name: Git Commit
# Steps:
# - Check if jq is installed or not (need it for parsing package.json)
# - Shows unstaged files
# - Shows staged files
# - Confirms the user they want to proceed
# - Execute the build step and check in any files it modifies
# - Invoke git commit with provided args
function color {
local COLOR=$1
local TEXT=$2
printf "$(tput setaf $COLOR)$TEXT$(tput sgr0)"
}
function indent {
echo "$1" | sed 's/^/ /'
}
function invoke_pre_commit {
${@:2} | sed "s/^/[$1] /"
if [ "${PIPESTATUS[0]}" != "0" ]; then
color 1 "The step '$1' exited with non-zero code\n"
exit 1
fi
}
function get_unstaged_files {
git diff --name-only
}
function get_staged_files {
git diff --name-only --cached
}
if [ "$(which jq)" = "" ]; then
echo "You don't have jq installed on your system"
echo "Do 'brew install jq' if you're on a mac or 'sudo apt install -y jq' if on Ubuntu"
exit 1
fi
UNSTAGED_FILES=$(get_unstaged_files)
if [ "$UNSTAGED_FILES" != "" ]; then
printf "These files have not yet been staged\n\n"
color 1 "$(indent "$UNSTAGED_FILES")\n\n"
fi
STAGED_FILES=$(get_staged_files)
if [ "$STAGED_FILES" != "" ]; then
printf "These files have been staged\n\n"
color 2 "$(indent "$STAGED_FILES")\n\n"
fi
if [ "$STAGED_FILES" != "" ] || [ "$UNSTAGED_FILES" != "" ]; then
read -n 1 -r -p "$(color 5 "Are you sure you want to continue?") "
printf "\n"
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
color 3 "The operation was cancelled\n"
exit 1
fi
fi
if [ -f package.json ] && [ "$(jq -r '.scripts.build' < package.json)" != "null" ]; then
color 3 "Executing build script\n"
UNSTAGED_FILES_BEFORE="$(get_unstaged_files)"
invoke_pre_commit build npm run build
UNSTAGED_FILES_AFTER="$(get_unstaged_files)"
UNSTAGED_FILES_BETWEEN="$(echo ${UNSTAGED_FILES_BEFORE[@]} ${UNSTAGED_FILES_AFTER[@]} | tr ' ' '\n' | sort | uniq -u)"
if [ "$UNSTAGED_FILES_BETWEEN" != "" ]; then
color 3 "The following new files have been checked in following build step:\n"
indent "$UNSTAGED_FILES_BETWEEN"
git add ${UNSTAGED_FILES_BETWEEN[@]}
fi
fi
git commit "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment