Skip to content

Commit

Permalink
✨ Add hook for prettier
Browse files Browse the repository at this point in the history
  • Loading branch information
sergei-maertens committed May 24, 2022
1 parent 5a61569 commit cc4d5ab
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions pre-commit.d/prettier.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
#!/bin/bash

# Run prettier on the files in the diff.
#
# Tests if prettier exists

formatter=${PRETTIER_BIN:-./node_modules/.bin/prettier}

if [ ! -f "$formatter" ]; then
exit 0
fi

STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM -- '*.js' | sed 's| |\\ |g')

CHANGED_UNSTAGED_FILES=$(git diff --name-only)

if [ ! -z "$STAGED_FILES" ]; then
if [ ! -z "$CHANGED_UNSTAGED_FILES" ]; then
# if there's changed stuff that isn't staged, we dont want to format the unstaged stuff too
git stash --keep-index
fi

# Format all selected files
echo "$STAGED_FILES" | xargs "$formatter" --write

# Check for the exit code
if [ $? -ne 0 ]; then
exit 1
fi

# Add back the modified/prettified files to staging
echo "$STAGED_FILES" | xargs git add -u


if [ ! -z "$CHANGED_UNSTAGED_FILES" ]; then
# put everything back in its place, hopefully without any merge conflicts...
git stash pop
fi
fi

0 comments on commit cc4d5ab

Please sign in to comment.