SHARE
TWEET

Untitled

a guest Apr 20th, 2019 101 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/bin/bash
  2.  
  3. # ------------------------------------------------------------
  4. # Recursive cpp code formatter based on clang-format
  5. # For base work there is you need to have .clang-format file
  6. #
  7. # USAGE code_format.sh [clang-format-options] [<file|dir> ...]
  8. #
  9. # clang-format-options passes through to clang-format
  10. # ------------------------------------------------------------
  11.  
  12. # check if we have .clang-format
  13. FILENAME=".clang-format"
  14. if ! [[ -f "$FILENAME" ]]; then
  15.     echo "Failed \".clang-format\" file does not exist"
  16.     exit 1
  17. fi
  18.  
  19. #get clang-format arguments
  20. CLANG_FORMAT_ARGS=()
  21. for var in "$@"
  22. do
  23.     if [[ $var == -* ]]; then
  24.         CLANG_FORMAT_ARGS+=("$var")
  25.     else
  26.         break
  27.     fi
  28. done
  29.  
  30. if [[ 1 > $(($# - ${#CLANG_FORMAT_ARGS[@]})) ]]; then
  31.     echo "Wrong arguments: code_format.sh [clang-format-options] [<file|dir> ...]"
  32.     exit 1
  33. fi
  34.  
  35. handle_file () {
  36.     if [[ $1 == *.cpp ]] || [[ $1 == *.c   ]] || \
  37.        [[ $1 == *.cc  ]] || [[ $1 == *.c++ ]] || \
  38.        [[ $1 == *.cp  ]] || [[ $1 == *.cxx ]] || \
  39.        [[ $1 == *.h   ]] || [[ $1 == *.hp  ]] || \
  40.        [[ $1 == *.hpp ]] || [[ $1 == *.hxx ]] || \
  41.        [[ $1 == *.h++ ]] || [[ $1 == *.icc ]] || \
  42.        [[ $1 == *.inl ]] || [[ $1 == *.hh  ]]; then
  43.         echo $'\n'"Formating file: $1";
  44.         /usr/bin/clang-format -i ${CLANG_FORMAT_ARGS[@]} $1 > /dev/null
  45.         echo "File handled $1"$'\n';
  46.     #else
  47.         #echo "$1 has wrong extension.";
  48.     fi
  49. }
  50.  
  51. handle_dir () {
  52.     for f in $(/usr/bin/find $1 -type f);
  53.     do
  54.         handle_file $f;
  55.     done
  56. }
  57.  
  58. #setup timer and start
  59. START=$SECONDS
  60. echo "Start formatting using \"clang-format ${CLANG_FORMAT_ARGS[@]}\""
  61.  
  62. #iterate over all input files and directories
  63. for (( i=${#CLANG_FORMAT_ARGS[@]}; i <= $#; i++ ))
  64. do
  65.     PATH=${!i}
  66.     if [ -f "${PATH}" ]; then
  67.         handle_file ${PATH};
  68.     else
  69.     if [ -d "${PATH}" ]; then
  70.         handle_dir ${PATH};
  71.     else
  72.         echo "${PATH} is not valid";
  73.     fi
  74. fi
  75. done
  76.  
  77. echo "Formatting ended in $(( SECONDS - START )) sec."
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top