Skip to content

Instantly share code, notes, and snippets.

@ArturGajowy
Created April 27, 2020 13:52
Show Gist options
  • Save ArturGajowy/548393e42e63a25fed1515ef097a3645 to your computer and use it in GitHub Desktop.
Save ArturGajowy/548393e42e63a25fed1515ef097a3645 to your computer and use it in GitHub Desktop.
Formatting commit hooks done right
#!/bin/bash
set -e -x
if [ -a .commit ]
then
rm .commit
# We format partially-staged files in the pre-commit hook, as that's the only safe way.
# If a partially-staged file needed reformatting, it's been re-formatted in pre-commit,
# and the commit has been cancelled so that the user can re-add the re-formmatted hunks.
# Including partially-staged files below would include the user's unstaged changes in the reformatting commit.
FULLY_STAGED=$( comm -23 <(git diff --name-only HEAD^..HEAD | sort) <(git diff --name-only | sort) )
FULLY_STAGED_SCALA=$( echo "${FULLY_STAGED[*]}" | grep -E '\.scala$|\.sbt$' || true )
if [ -n "$FULLY_STAGED_SCALA" ]
then
echo "$FULLY_STAGED_SCALA" | xargs -d '\n' time scalafmt --non-interactive || true
AUTHOR="Scalafmt / $( git config user.name ) <$( git config user.email )>"
git diff --exit-code --quiet || \
echo "$FULLY_STAGED_SCALA" | xargs -d '\n' git commit --fixup=HEAD --no-verify --author "$AUTHOR" --
fi
fi
exit
#!/bin/bash
set -e -x
#TODO add scalafmt version check to ensure fast execution
# If a partially-staged file gets reformatted, there's no way to tell what part
# of the reformatted file should make it into the commit. In that case, we ask the user
# to re-do the commit using the reformatted file.
PARTIALLY_STAGED=$( comm -12 <(git diff --name-only | sort) <(git diff --name-only --cached | sort) )
if [ -n "$PARTIALLY_STAGED" ]
then
PATIALLY_STAGED_SCALA=$(echo "${PARTIALLY_STAGED[*]}" | grep -E '\.scala$|\.sbt$' || true)
if [ -n "$PATIALLY_STAGED_SCALA" ]
then
PRE_DIFF=$( echo "$PATIALLY_STAGED_SCALA" | xargs -d '\n' git diff HEAD -- )
echo "$PATIALLY_STAGED_SCALA" | xargs -d '\n' scalafmt --non-interactive > /dev/null || true
POST_DIFF=$( echo "$PATIALLY_STAGED_SCALA" | xargs -d '\n' git diff HEAD -- )
if [ "$PRE_DIFF" != "$POST_DIFF" ]
then
echo "One of partially-staged files was re-formatted."
echo "You'll need to do the commit again :("
exit 1
fi
fi
fi
touch .commit
exit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment