1#!/bin/bash
2
3# This script reformats source files using the clang-format utility.
4#
5# Files are changed in-place, so make sure you don't have anything open in an
6# editor, and you may want to commit before formatting in case of awryness.
7#
8# This must be run on a clean repository to succeed
9#
10# Input parmameter must be full path to git repo to scan
11
12DIR=$1
13cd ${DIR}
14
15set -e
16
17echo "Formatting code under $DIR/"
18
19if [[ -f "setup.cfg" ]]; then
20  pycodestyle --show-source .
21  rc=$?
22  if [[ ${rc} -ne 0 ]]; then
23    exit ${rc}
24  fi
25fi
26
27# Allow called scripts to know which clang format we are using
28export CLANG_FORMAT="clang-format-8"
29IGNORE_FILE=".clang-ignore"
30declare -a IGNORE_LIST
31
32if [[ -f "${IGNORE_FILE}" ]]; then
33  readarray -t IGNORE_LIST < "${IGNORE_FILE}"
34fi
35
36ignorepaths=""
37ignorefiles=""
38
39for path in "${IGNORE_LIST[@]}"; do
40  # Check for comment, line starting with space, or zero-length string.
41  # Checking for [[:space:]] checks all options.
42  if [[ -z "${path}" ]] || [[ "${path}" =~ ^(#|[[:space:]]).*$ ]]; then
43    continue
44  fi
45
46  # All paths must start with ./ for find's path prune expectation.
47  if [[ "${path}" =~ ^\.\/.+$ ]]; then
48    ignorepaths+=" -o -path ${path} -prune"
49  else
50    ignorefiles+=" -not -name ${path}"
51  fi
52done
53
54if [[ -f ".clang-format" ]]; then
55  find . \( -regextype sed -regex ".*\.[hc]\(pp\)\?" ${ignorepaths} \) \
56    -not -name "*mako*" ${ignorefiles} -not -type d -print0 |\
57    xargs -0 "${CLANG_FORMAT}" -i
58  git --no-pager diff --exit-code
59fi
60
61# Sometimes your situation is terrible enough that you need the flexibility.
62# For example, phosphor-mboxd.
63if [[ -f "format-code.sh" ]]; then
64  ./format-code.sh
65  git --no-pager diff --exit-code
66fi
67