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

1

6

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://mcmap.net/q/570988/-why-are-my-changes-gone-after-a-cancelled-git-commit-and-how-do-i-recover-them.

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?

Beriosova answered 17/9, 2021 at 20:20 Comment(3)
Don't use those particular hooks? Don't use that workflow? Those seem to be the options here...Posy
@Posy I'm pretty new to git, and set all this up using tutorials. Coming from the .NET world, this seems much less straightforward compared to the code analysis errors we'd used to deal with. I'd welcome other suggestions because I don't know how else to set this up. I just want to prevent linting errors in the code base without hoops for devs to jump through or lost changes.Beriosova
It's possible that the Husky and ESLint people are aware of Git's staging area and do have a solution for this. Or, perhaps they aren't and don't. The ability to stage only parts of files is what causes this kind of headache. The author of pre-commit (see pre-commit.com) is aware and has some way to work with it better. I haven't used those hooks either, but at least I know he knows. :-)Posy
B
0

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.

Beriosova answered 11/12, 2023 at 21:56 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.