Prettier using pre-commit(.com) does not re-stage changes

2.7k views Asked by At

I started using Prettier + eslint using pretty-quick & husky (option 2). It behaves as-expected, i.e., reformats code during a commit (or amend) and includes the changes in the commit.

My monorepo needed (several) more pre-commit hooks, so I ended up migrating to pre-commit.com (option 3). Now, when I commit or amend, Prettier modifies the files and returns Failed status. This creates for a rather annoying workflow where I am forced to add the files and attempt to commit the changes again.

Is there some way to re-stage the changes as part of the commit?

3

There are 3 answers

2
anthony sottile On BEST ANSWER

pre-commit intentionally never touches the staging area. silently changing what is being committed is dangerous. the tool always gives you an opportunity to validate what the hooks do before committing

you can read more about this in the issue tracker:

My recommendation if you want to fire from the hip is to run git add -u && !! immediately afterwards -- this will stage the changed files and rerun the command you just ran

if you want to venture into unsupported territory, you can run this as part of the command (as demonstrated in one of the issues) -- but this subtly breaks a lot of the guarantees that the tool has

  - id: yapf
    entry: bash -c 'yapf "$@"; git add -u' --

disclaimer: I am the author of pre-commit

0
Daniel Sottile On

I'm sure my older brother, the creator of Pre-commit will confirm this, but this is the intended behavior of pre-commit. It should fail because it is directly modifying your files. I use this exact setup using Prettier for myself actually, and while it is annoying, it's just one of those things you gotta change. I like making a git commit -m called 'format' or something and then a commit for the actual change.

edit: he sniped me before I could answer, his answer goes much more in depth

0
tin_nqn On

Assuming you understand the reasons given above to don't do this blindy, I'd like to share a simple rule script I wrote for the wonderful fuck which automatically updates the staging area and retry the commit command.

So, the usage looks like this:

$ git commit -m "..."
[pre-commit modifies some files and abort the commit]
$ fuck