1#! /bin/bash
2# Run given scripted change and commit the changes.
3#
4# Assumes that the current directory is the top-level directory of
5# the Android source code, created with 'repo init', and that 'repo'
6# tool is on the path.
7# For each of the given repo git repositories:
8# 1. Checks there are neither modified not untracked files in it.
9# 2. Runs the given script, which is supposed to change some files
10# 3. Creates a development branch if necessary
11# 4. Commits changed files. The commit message is extracted from the
12#    script and contains all the lines in it starting with ##CL
13#
14# As an example, running
15#   build/bazel/mk2rbc/apply_scripted_change.sh build/bazel/mk2rbc/replace_is_board_platform.sh hardware/qcom/media
16# replaces the old is-board-platform calls with the new is-board-platform2 calls.
17
18set -eu
19
20function die() { format=$1; shift; printf "$format\n" $@; exit 1; }
21function usage() { die "Usage: %s script git-repo ..."  ${0##*/}; }
22
23(($#>=2)) || usage
24declare -r script=$(realpath $1); shift
25rc=0
26
27[[ -x $script ]] || die "%s is not an executable script" $script
28declare -r bugid="$(sed -nr 's/^##CL (Bug:|Fixes:) +([0-9]+)$/\2/p' $script)"
29[[ -n "$bugid" ]] || die "$script contains neither '##CL Bug: ' nor '##CL Fixes: 'tag"
30
31
32for gr in $@; do
33    [[  -d $gr/.git ]] || { echo $gr is not a Git directory; rc=1; continue; }
34    out=$(git -C $gr status --porcelain --untracked-files=no) || { die "so skipping $gr because of the above"; rc=1; continue; }
35    [[ -z "$out" ]] || { echo  $gr contains uncommitted changes:; echo "$out" >&2; rc=1; continue; }
36    (cd $gr && $script)
37    modified="$(git -C $gr status --porcelain | sed -nr 's/^ M (.*)/\1/p')"
38    [[ -n "$modified" ]] || { echo no files changed in $gr; continue; }
39    [[ -z "$(repo status -q $gr 2>/dev/null)" ]] || repo start b$bugid $gr
40    git -C $gr add $modified
41    git -C $gr commit -q \
42      -F <(sed -nr 's/^##CL *//p' $script; echo -e '\nThis change has been generated by the following script:\n\n```'; grep -vP '^##CL' $script; echo '```')
43done
44
45exit $rc
46