-
-
Save cntrump/c22de2483622a831043c06800ba3434c to your computer and use it in GitHub Desktop.
clang-format files recursively
This file contains 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
#!/usr/bin/env bash | |
set -e | |
# Variable that will hold the name of the clang-format command | |
FMT="" | |
# Some distros just call it clang-format. Others (e.g. Ubuntu) are insistent | |
# that the version number be part of the command. We prefer clang-format if | |
# that's present, otherwise we work backwards from highest version to lowest | |
# version. | |
for clangfmt in clang-format{,-{4,3}.{9,8,7,6,5,4,3,2,1,0}}; do | |
if which "$clangfmt" &>/dev/null; then | |
FMT="$clangfmt" | |
break | |
fi | |
done | |
# Check if we found a working clang-format | |
if [ -z "$FMT" ]; then | |
echo "failed to find clang-format" | |
exit 1 | |
fi | |
function format_file() { | |
file_path=${1} | |
echo "format ${file_path}"; | |
${FMT} -style=file -i "${file_path}" | |
} | |
function format_dir() { | |
oldIFS=$IFS | |
IFS=$'\n' | |
for f in $(find $@ -type d \ | |
-not \( -path */Carthage -prune \) \ | |
-not \( -path */Pods -prune \) \ | |
-not \( -path */.swiftpm -prune \) \ | |
-not \( -path *.framework -prune \) \ | |
-not \( -path *.xcframework -prune \) \ | |
-name '*.pch' -or \ | |
-name '*.h' -or \ | |
-name '*.m' -or \ | |
-name '*.mm' -or \ | |
-name '*.c' -or \ | |
-name '*.cc' -or \ | |
-name '*.cpp'); do | |
format_file "${f}"; | |
done | |
IFS=$oldIFS | |
echo "~~~ $@ Done ~~~"; | |
} | |
# Check all of the arguments first to make sure they're all directories | |
for x in $@; do | |
if [ -f "${x}" ]; then | |
format_file "${x}" | |
elif [ -d "${x}" ]; then | |
format_dir "${x}"; | |
else | |
echo "Invalid path: ${x}" | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment