summaryrefslogtreecommitdiff
path: root/misc/format-files
blob: 6671f8e1d0cb952a99e929f135e1a256663d71e8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#!/bin/sh

set -eu

tmp_file=$(mktemp)
trap "rm $tmp_file" EXIT

all=
check=

for arg in "$@"; do
    case $arg in
        --all)
            all=$arg
            ;;
        --check)
            check=$arg
            ;;
        *)
            break
            ;;
    esac
    shift
done

if [ -n "$all" ]; then
    exec sh "$0" $check $(git ls-files '*.[ch]' '*.[ch]pp' ':!:src/third_party')
fi

clang_format="$(dirname "$0")/clang-format"
[ -t 1 ] && cf_color="--color=always" || cf_color=""

if [ -n "${VERBOSE:-}" ]; then
    "$clang_format" --version
fi

status=0
for file in "$@"; do
    "$clang_format" "$file" >"$tmp_file"
    if cmp -s "$file" "$tmp_file"; then
        continue
    fi

    if [ -n "$check" ]; then
        status=1
        echo "Error: $file not formatted with Clang-Format"
        echo
        echo 'Please run "make format" (or "ninja format"), or apply this diff:'
        echo
        git diff $cf_color --no-index "$file" "$tmp_file" \
            | sed -E -e "s!^---.*!--- a/$file!" \
                     -e "s!^\+\+\+.*!+++ b/$file!" \
                     -e "/diff --/d" -e "/index /d" \
                     -e "s/.[0-9]*.clang-format.tmp//"
    else
        echo "Reformatted $file"
        cp "$tmp_file" "$file"
    fi
done

exit $status