Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
clang-format wrapper for multifile ussage [cpp]
#!/bin/bash
# ------------------------------------------------------------
# Recursive cpp code formatter based on clang-format
# For base work there is you need to have .clang-format file
#
# USAGE code_format.sh [clang-format-options] [<file|dir> ...]
#
# clang-format-options passes through to clang-format
# ------------------------------------------------------------
# check if we have .clang-format
FILENAME=".clang-format"
if ! [[ -f "$FILENAME" ]]; then
echo "Failed \".clang-format\" file does not exist"
exit 1
fi
#get clang-format arguments
CLANG_FORMAT_ARGS=()
for var in "$@"
do
if [[ $var == -* ]]; then
CLANG_FORMAT_ARGS+=("$var")
else
break
fi
done
if [[ 1 > $(($# - ${#CLANG_FORMAT_ARGS[@]})) ]]; then
echo "Wrong arguments: code_format.sh [clang-format-options] [<file|dir> ...]"
exit 1
fi
handle_file () {
if [[ $1 == *.cpp ]] || [[ $1 == *.hpp ]] || \
[[ $1 == *.c ]] || [[ $1 == *.h ]] || \
[[ $1 == *.cc ]] || [[ $1 == *.hh ]] || \
[[ $1 == *.c++ ]] || [[ $1 == *.h++ ]] || \
[[ $1 == *.cxx ]] || [[ $1 == *.hxx ]] || \
[[ $1 == *.cp ]] || [[ $1 == *.hp ]] || \
[[ $1 == *.icc ]] || [[ $1 == *.inl ]]; then
echo $'\n'"Formating file: $1";
clang-format -i ${CLANG_FORMAT_ARGS[@]} $1 > /dev/null
echo "File handled $1"$'\n';
#else
#echo "$1 has wrong extension.";
fi
}
handle_dir () {
for f in $(/usr/bin/find $1 -type f);
do
handle_file $f;
done
}
#setup timer and start
START=$SECONDS
echo "Start formatting using \"clang-format ${CLANG_FORMAT_ARGS[@]}\""
#iterate over all input files and directories
for (( i=${#CLANG_FORMAT_ARGS[@]}; i <= $#; i++ ))
do
PATH=${!i}
if [ -f "${PATH}" ]; then
handle_file ${PATH};
else
if [ -d "${PATH}" ]; then
handle_dir ${PATH};
else
echo "${PATH} is not valid";
fi
fi
done
echo "Formatting ended in $(( SECONDS - START )) sec."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment