run git hook before adding files to staging area

Viewed 18

I have a project that uses prettier for formatting. I want my remote code repository to have files that have a consistent format. For this reason, I added a script in package.json file that will format the whole code base in one line of command(npm run format)

package.json file

This works! But the problem is that I may sometimes forget to format my code before git push to a remote repository. And I am not okay with cluttering my git history with unnecessary commits for the sake of formatting the code.

I resolved to automation and opting for git hooks that will format my code base with the command: npm run format every time I add file(s) to the staging area. But I seem not to find a git hook for my use case.

Is there a hook that can run before staging files?

1 Answers

There is no such Git hook. However, you have two options if you want to handle formatting.

One is to use a pre-commit hook to check your files before committing. This won't prevent you from adding them, but it will prevent you from committing them. However, pre-commit hooks can be very burdensome if you use some advanced workflows which use many temporary and fixup commits.

Another option is to use a clean filter. You can create a pattern in your .git/info/attributes file like this:

src/**/*.js filter=prettier

and then you can add the following to .git/config:

[filter "prettier"]
smudge = cat
clean = "YOUR-PRETTIER-COMMAND-HERE"

You'd replace YOUR-PRETTIER-COMMAND-HERE with a command that reads the file from standard input and writes it in an appropriate format to standard output. (It is not possible to use a program that formats in place on the file system.) That will automatically run JavaScript files through that filter when running git add and store them in the repository with proper formatting.

Related