From 8619b9c584c34028033a7f6bf9cbcbdbf576de63 Mon Sep 17 00:00:00 2001 From: Sergei Maertens Date: Tue, 24 May 2022 15:41:01 +0200 Subject: [PATCH] :sparkles: Add hook for prettier --- pre-commit.d/prettier.sh | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100755 pre-commit.d/prettier.sh diff --git a/pre-commit.d/prettier.sh b/pre-commit.d/prettier.sh new file mode 100755 index 0000000..d264bc3 --- /dev/null +++ b/pre-commit.d/prettier.sh @@ -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' '*.scss' | 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