Created
August 13, 2019 10:44
-
-
Save cxkoda/47c1766136586e61b920f0146840bf2f to your computer and use it in GitHub Desktop.
Clang-format all staged changes in a git repository
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| blobs=$(mktemp) | |
| git status --porcelain=v2 -uno > $blobs | |
| while read _ _ _ _ _ filemode oldHash newHash filename; do | |
| # Skip the file if the staged blob has not changed | |
| if [ $oldHash == $newHash ]; then | |
| continue | |
| fi | |
| # Skip the file if it is not a c++ source file | |
| if [[ ! $filename =~ ^.*[.cpp|.hpp] ]]; then | |
| continue | |
| fi | |
| # Dump the source file | |
| oldContent=$(mktemp) | |
| git cat-file -p $newHash > $oldContent | |
| # Format the source file | |
| newContent=$(mktemp) | |
| clang-format -style=file $oldContent > $newContent | |
| # Go to the next file, if the code was already formatted correctly | |
| if cmp $oldContent $newContent; then | |
| continue | |
| fi | |
| # Print the changes | |
| # git --no-pager diff --no-index $oldContent $newContent | |
| # Register the formatted source file in the repository | |
| newHash2=$(git hash-object -w $newContent) | |
| # Update the stage to the new blob | |
| git update-index --add --cacheinfo $filemode $newHash2 $filename | |
| echo "Changed file $filename" | |
| done < $blobs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment