1#!/bin/bash
2#
3# Inspired by https://github.com/antiagainst/SPIRV-Tools/commit/c4f1bf8ddf7764b7c11fed1ce18ceb1d36b2eaf6
4#
5# Script to determine if source code in a diff is properly formatted. On
6# GitHub, a commit range is provided which corresponds to the commit range of
7#   1) commits associated with a pull request, or
8#   2) commits on a branch which are not also part of master, or
9#   3) commits since last push to master.
10#
11# Exits with non 0 exit code if formatting is needed.
12#
13# This script assumes to be invoked at the project root directory.
14
15COMMIT_RANGE="${1}"
16
17if [ -z "${COMMIT_RANGE}" ]; then
18    >&2 echo "Empty commit range, missing parameter"
19    exit 1
20fi
21
22>&2 echo "Commit range $COMMIT_RANGE"
23
24FILES_TO_CHECK="$(git diff --name-only "$COMMIT_RANGE" | grep -e '\.c$' -e '\.h$' || true)"
25CFV="${CLANG_FORMAT_VERSION:--6.0}"
26
27if [ -z "${FILES_TO_CHECK}" ]; then
28    >&2 echo "No source code to check for formatting"
29    exit 0
30fi
31
32FORMAT_DIFF=$(git diff -U0 ${COMMIT_RANGE} -- ${FILES_TO_CHECK} | clang-format-diff$CFV -p1)
33
34if [ -z "${FORMAT_DIFF}" ]; then
35    >&2 echo "All source code in the diff is properly formatted"
36    exit 0
37else
38    >&2 echo -e "Found formatting errors\n"
39    echo "${FORMAT_DIFF}"
40    >&2 echo -e "\nYou can save the diff above and apply it with 'git apply -p0 my_diff'"
41    exit 1
42fi
43