Last active
April 12, 2018 16:29
-
-
Save joeljeske/cf0b7e458e9f2a8d48fd6722b4141a73 to your computer and use it in GitHub Desktop.
Lint Staged Handle Partially Staged Files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
NPM_COMMAND=$1 | |
STAGED_FILE=$2 | |
IS_PARTIALLY_STAGED=$(git diff --name-only "$STAGED_FILE") | |
if [[ "$IS_PARTIALLY_STAGED" != "" ]]; | |
then | |
# If the file is partially changed, we need get the hash so we can see if it changed later | |
PRE_LINT_HASH=$(git hash-object "$STAGED_FILE") | |
fi | |
# Do the actual linting fixing | |
npm run "$NPM_COMMAND" "$STAGED_FILE" | |
if [[ "$?" != "0" ]]; | |
then | |
echo "Error occurred in npm run $NPM_COMMAND. Exitting..." | |
exit 1 | |
fi | |
if [[ "$IS_PARTIALLY_STAGED" != "" ]]; | |
then | |
# If it was partially staged, compare it to the file on disk before linting to see if it changed | |
POST_LINT_HASH=$(git hash-object "$STAGED_FILE") | |
if [[ "$POST_LINT_HASH" != "$PRE_LINT_HASH" ]]; | |
then | |
echo "A partially staged file was fixed during linting precommit hook. $STAGED_FILE" | |
echo "Please re-stage the file hunks and retry commit" | |
exit 1 | |
fi | |
else | |
# If the entire file was previously staged, we should simply re-add the linting changes to this commit | |
git add "$STAGED_FILE" | |
fi |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
// ... | |
"scripts": { | |
"lint:fix": " ... " | |
}, | |
"lint-staged": { | |
"src/**/*.js": [ | |
"./lint-staged-precommit.sh lint:fix" | |
] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I use this to handle the case when partially staged files are modified during "lint-staged". This allows me to "re-think" my commit. If I take no action and simply run again, everything passes since my files were not modified again.