Skip to content

Instantly share code, notes, and snippets.

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 subhamproject/da3c9f3584ebdbfe093032d719527abd to your computer and use it in GitHub Desktop.
Save subhamproject/da3c9f3584ebdbfe093032d719527abd to your computer and use it in GitHub Desktop.
BASH script used as GIT tree-filter to fix the coding style of all commits on the branch
#!/bin/sh
set -e
echo ""
# Copied from the git source code as the filter-branch map function is not exposed to scripts.
map()
{
# if it was not rewritten, take the original
if test -r "../map/$1"
then
cat "../map/$1"
else
echo "$1"
fi
}
DIR="$(dirname $0)"
# Get the old master commit hash.
OLD_MASTER=$( git rev-parse --quiet --verify master-before-codefix )
# Get the manual fixing commit on new master.
POST_FIX=$( git log --format="%H" --grep 'Post-fix on the code style rewritting.' master )
# Check if the current branch has been properly rebased.
if [ "$(git rev-parse $OLD_MASTER )" != "$(git merge-base $OLD_MASTER HEAD)" ]
then
echo ""
echo "ERROR: Please rebase branch onto master-before-codefix first."
echo ""
exit 1;
fi
# For some reason, I was not able to use grep here to filter .js files straight.
FILES=$( git ls-files )
if git rev-parse --quiet --verify $GIT_COMMIT^ >/dev/null
then
# If there is a previous commit, take the reference for the rewritten on.
PREVIOUS_ORI=$( git rev-list $GIT_COMMIT -n 1 --skip 1 )
PREVIOUS=$( map $PREVIOUS_ORI )
if [ $PREVIOUS == $OLD_MASTER ]
then
# Use master as the base if this is the first commit in the branch.
PREVIOUS="master"
fi
# Make a full copy of the parent commit.
git checkout $PREVIOUS -- .
# Get the list of changed files.
TOUCHED=$( git show --name-only --pretty="format:" $GIT_COMMIT | grep "[^\s]" )
else
# For the initial commit, all files are touched.
TOUCHED=$FILES
fi
for t in $TOUCHED
do
# Checkout touched files.
git checkout -f $GIT_COMMIT $t
# Fix JS files.
if [ -f "$t" ] && [ ${t##*.} == "js" ]
then
echo "Fixing JS file $t, from commit:`git log --pretty="%s" -1 $GIT_COMMIT`"
# 1. Run beautifier.
js-beautify -o $t $t
# 2. Apply manual fixes broken by beautifier.
CHANGED=$(git diff --name-only "$POST_FIX^" "$POST_FIX" $t)
if [ -n "$CHANGED" ];
then
git diff "$POST_FIX^" "$POST_FIX" $t | git apply
fi
fi
done
echo ""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment