简体   繁体   中英

How to apply eslint/prettier auto-fixes in git-hook

I am wondering how can I apply eslint and prettier auto fixes in git-hook pre-push phase. I tried something like this:

./node_modules/.bin/eslint index.js --fix
git add .
git commit --amend --no-edit

It fixes problems in my local repo but doesn't push it to the remote. Then also after I type git status it is written that I have 1 and 1 different commits each, respectively and I have to use git pull to fix my problems. This generates super mess in the repo.

Do you have any idea how can I achieve this ?

Part of your mess comes from the git commit --amend : with --amend , git always rewrites the HEAD commit, so your HEAD commit after you have run git push will always be different than what it was before.

One other part of the mess is that, since your hook runs git add . (instead of trying to selectively choose files, or chunks), it will always add everything in your worktree. No more git add <subdir>/ or git add -p ... for you : you pre-push hook will always add all that's on your disk.


Hooks (pre-commit and pre-push) are IMHO better suited to be read only actions, with the ability to cancel the action if necessary.

Eg : you can have a lint script, with a check mode (check lint rules and exit with non zero code if rules are not respected) and a update mode (apply known fixes for the rules). Note that, depending on your linters, some rules may need some manual action anyway.

Use the check mode in your pre-push hook, and possibly include the update mode in a script that will additionally git add your files ; at least, you will re-gain the opportunity to review what you have committed before pushing.

As suggested, you can also use the check mode in a hook on the server side to reject commits that don't adhere to the lint rules you chose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM