Search code examples
githuskygit-huskylint-staged

Pending git changes are lost when commit fails due to linting error (husky + lint-staged)


I have an Angular app using git and Visual Studio Code. I set up ESLint and am using husky to run lint-staged in a pre-commit hook, so that changes with linting errors cannot be committed.

When I first set it up, the pending changes in failed commits would just disappear, and I learned that they were getting stashed: https://stackoverflow.com/a/60335168/11991371.

I don't understand why it would default to stashing my changes away, rather than letting me just correct the linting error and try the commit again. It seems bizarre, quite frankly. It's going to panic every developer who ever runs into it. So I added the --no-stash flag so it wouldn't do that.

/.husky/pre-commit:

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npx lint-staged --no-stash

But now I stumbled on another problem case. Steps:

  1. Make a change in a file and accidentally leave in a linting error.
  2. Stage this file.
  3. Make another change in the same file (but don't stage it).
  4. Try to commit the staged changes. It will fail due to the linting error, and the second change will be lost.

If you happen to have the file open, you may be able to recover your changes via 'Undo' in the IDE, but this is a big problem. How can I prevent ever losing work due to rejected commits, while also not having work automatically stashed?


Solution

  • Looks like this will be fixed in lint-staged v15.2.0!

    From my testing, for files that have both staged and un-staged changes, it will now add the un-staged changes to the already-staged version of the file. Which is not ideal either, but a lot better than just losing the changes altogether. At least the developer has a chance to recover.

    My running advice would be to try to avoid this situation altogether by not editing files after they have been staged.