I'd like to run an auto-formatting tool (e.g. Prettier, go fmt, clang-format, terraform fmt ...) on all commits in a branch. I could manually edit each commit in the branch using an interactive rebase (git rebase -i) but that is quite tedious if there are a lot of commits on the branch.
How do I automatically apply the auto-formatting to each commit in the branch?
You can use git rebase --exec like so:
git rebase \
--strategy-option=theirs \
--exec '<formatting/linting command here>; git add --update; git commit --amend --no-edit' <base branch, e.g. "main" or "master">
Using multiple --exec flags is mostly not workable as every --exec needs to run both git add and git commit for it to apply and not stop the rebase. To see the effect of the --exec flag pass --interactive (or -i for short) and you'll see the interactive rebase that it's doing under the hood (and shows why multiline strings in --exec are not allowed).
Source: https://blog.scottlogic.com/2019/03/04/retroactively-applying-prettier-to-existing-branches.html
Note: This is also possible using git filter-branch --tree-filter but that command is now discouraged and produces a warning when invoked on the command-line. The suggested alternative git-repo-filter cannot do this directly, but contains an example lint-history-command which is able to do this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With