Skip to content

Instantly share code, notes, and snippets.

@joeljeske
Last active April 12, 2018 16:29
Show Gist options
  • Save joeljeske/cf0b7e458e9f2a8d48fd6722b4141a73 to your computer and use it in GitHub Desktop.
Save joeljeske/cf0b7e458e9f2a8d48fd6722b4141a73 to your computer and use it in GitHub Desktop.
Lint Staged Handle Partially Staged Files
#!/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
{
// ...
"scripts": {
"lint:fix": " ... "
},
"lint-staged": {
"src/**/*.js": [
"./lint-staged-precommit.sh lint:fix"
]
}
}
@joeljeske
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment