1#!/usr/bin/env bash
2
3################################################################################
4# Runs bazel build for proto files in cirq/google/api/* that have changed.
5#
6# If any BUILD file for the proto has changed, all targets in that BUILD
7# file will be built.
8#
9# Usage:
10#     check/build-changed-protos [BASE_REVISION]
11#
12# You can specify a base git revision to compare against (i.e. to use when
13# determining whether or not a line is considered to have "changed"). For
14# example, you can compare against 'origin/master' or 'HEAD~1'.
15#
16# If you don't specify a base revision, the following defaults will be tried, in
17# order, until one exists:
18#
19#     1. upstream/master
20#     2. origin/master
21#     3. master
22#
23# If none exists, the script fails.
24#
25# See build-protos for building all protos.
26################################################################################
27
28# Get the working directory to the repo root.
29cd "$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
30cd "$(git rev-parse --show-toplevel)"
31
32# Figure out which revision to compare against.
33if [ ! -z "$1" ] && [[ $1 != -* ]]; then
34    if [ "$(git cat-file -t $1 2> /dev/null)" != "commit" ]; then
35        echo -e "\033[31mNo revision '$1'.\033[0m" >&2
36        exit 1
37    fi
38    rev=$1
39elif [ "$(git cat-file -t upstream/master 2> /dev/null)" == "commit" ]; then
40    rev=upstream/master
41elif [ "$(git cat-file -t origin/master 2> /dev/null)" == "commit" ]; then
42    rev=origin/master
43elif [ "$(git cat-file -t master 2> /dev/null)" == "commit" ]; then
44    rev=master
45else
46    echo -e "\033[31mNo default revision found to compare against. Argument #1 must be what to diff against (e.g. 'origin/master' or 'HEAD~1').\033[0m" >&2
47    exit 1
48fi
49base="$(git merge-base ${rev} HEAD)"
50if [ "$(git rev-parse ${rev})" == "${base}" ]; then
51    echo -e "Comparing against revision '${rev}'." >&2
52else
53    echo -e "Comparing against revision '${rev}' (merge base ${base})." >&2
54    rev="${base}"
55fi
56
57# All the protos.
58echo "Building protos in $(pwd)"
59
60dev_tools/build-protos.sh
61
62# Filenames with spaces will be ugly (each part will be listed separately)
63# but the error logic will still work.
64uncommitted=$(git status --porcelain 2>/dev/null | grep -E "^?? cirq-google" | cut -d " " -f 3)
65
66if [[ ! -z "$uncommitted" ]]; then
67    echo -e "\033[31mERROR: Uncommitted generated files found! Please generate and commit these files using dev_tools/build-protos.sh:\033[0m"
68    for generated in $uncommitted
69    do
70        echo -e "\033[31m   ${generated}\033[0m"
71    done
72    exit 1
73fi
74