1#!/bin/bash 2# Copyright (c) 2017 Google Inc. 3 4# Licensed under the Apache License, Version 2.0 (the "License"); 5# you may not use this file except in compliance with the License. 6# You may obtain a copy of the License at 7# 8# http://www.apache.org/licenses/LICENSE-2.0 9# 10# Unless required by applicable law or agreed to in writing, software 11# distributed under the License is distributed on an "AS IS" BASIS, 12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13# See the License for the specific language governing permissions and 14# limitations under the License. 15 16# This script determines if the source code in a Pull Request is properly formatted. 17# Exits with non 0 exit code if formatting is needed. 18# Assumptions: 19# - git and python3 are on the path 20# - Runs from the project root diretory. 21# - 'clang-format' is on the path, or env var CLANG_FORMAT points to it. 22# - 'clang-format-diff.py' is in the utils directory, or env var 23# points to it.CLANG_FORMAT_DIFF 24 25BASE_BRANCH=${1:-main} 26 27CLANG_FORMAT=${CLANG_FORMAT:-clang-format} 28if [ ! -f "$CLANG_FORMAT" ]; then 29 echo missing clang-format: set CLANG_FORMAT or put clang-format in the PATH 30 exit 1 31fi 32 33# Find clang-format-diff.py from an environment variable, or use a default 34CLANG_FORMAT_DIFF=${CLANG_FORMAT_DIFF:-./utils/clang-format-diff.py} 35if [ ! -f "$CLANG_FORMAT_DIFF" ]; then 36 echo missing clang-format-diffy.py: set CLANG_FORMAT_DIFF or put it in ./utils/clang-format-diff.py 37 exit 1 38fi 39 40echo "Comparing "$(git rev-parse HEAD)" against $BASE_BRANCH" 41echo Using $("$CLANG_FORMAT" --version) 42 43FILES_TO_CHECK=$(git diff --name-only ${BASE_BRANCH} | grep -E ".*\.(cpp|cc|c\+\+|cxx|c|h|hpp)$") 44 45if [ -z "${FILES_TO_CHECK}" ]; then 46 echo "No source code to check for formatting." 47 exit 0 48fi 49 50FORMAT_DIFF=$(git diff -U0 ${BASE_BRANCH} -- ${FILES_TO_CHECK} | python3 "${CLANG_FORMAT_DIFF}" -p1 -style=file -binary "$CLANG_FORMAT") 51 52if [ -z "${FORMAT_DIFF}" ]; then 53 echo "All source code in PR properly formatted." 54 exit 0 55else 56 echo "Found formatting errors!" 57 echo "${FORMAT_DIFF}" 58 exit 1 59fi 60