Colm Donelan | e40cc83 | 2021-03-02 10:30:34 +0000 | [diff] [blame] | 1 | #!/bin/bash |
| 2 | # |
| 3 | # Copyright © 2021-2023 Arm Ltd. All rights reserved. |
| 4 | # SPDX-License-Identifier: MIT |
| 5 | # |
| 6 | |
| 7 | # |
| 8 | # Usage: clang-format.sh [path to file or directory] |
| 9 | # |
| 10 | # Formats all git-tracked files in the repository according to clang-format rules. |
| 11 | # |
| 12 | # Takes an optional parameter to limit the scope to a specific directory or file. |
| 13 | # |
| 14 | # The clang-format rules can be found in the top level directory: .clang-format |
| 15 | # To prevent clang-format on a section of code, use the following: |
| 16 | # // clang-format off |
| 17 | # my code that i dont want to be clang-formatted goes here |
| 18 | # // clang-format on |
| 19 | # |
| 20 | |
| 21 | # Check that clang-format is available. |
| 22 | CLANG_FORMAT=`command -v clang-format` |
| 23 | if [ -z $CLANG_FORMAT ]; then |
| 24 | # Maybe path isn't set. Try a well known location. |
| 25 | CLANG_FORMAT=/usr/bin/clang-format |
| 26 | if [ ! -x "$CLANG_FORMAT" ]; then |
| 27 | echo "Unable to locate clang-format. Try installing it: sudo apt-get install clang-format" |
| 28 | fi |
| 29 | fi |
| 30 | |
| 31 | # Find all hpp and cpp files excluding some directories. |
| 32 | files=$(git ls-files ${1} | egrep -v '^(build-tool|docker|docs|generated|third-party)' | egrep '\.[ch](pp)?$') |
| 33 | |
| 34 | num_files_changed=0 |
| 35 | |
| 36 | for file in $files; do |
| 37 | echo "[CLANG-FORMAT] ${file}" |
| 38 | # Run clang-format in-place to update the file |
| 39 | $CLANG_FORMAT -style=file ${file} -i |
| 40 | if [ $? -ne 0 ]; then |
| 41 | echo "Error: Execution of $CLANG_FORMAT failed." |
| 42 | exit -1 |
| 43 | else |
| 44 | ((num_files_changed++)) |
| 45 | fi |
| 46 | done |
| 47 | |
| 48 | echo "${num_files_changed} file(s) changed" |
| 49 | exit ${num_files_changed} |