Add yapf-diff.sh

This tiny script can be used as a hook script in PREUPLOAD.cfg:
| [Hook Scripts]
| yapf-diff = yapf-diff.sh

The script runs yapf-diff on the commit that will be uploaded (i.e. format only
python lines that are touched by the commit). Format suggestions are printed to
the screen (no file is changed). If there are any format suggestions the script
fails. To apply changes one can run the script manually with '-i', and then
amend the commit.

Change-Id: I221355408dd6490b554cd5c63d376bf0f3c1f952
diff --git a/preupload-hooks/GLOBAL-PREUPLOAD.cfg b/preupload-hooks/GLOBAL-PREUPLOAD.cfg
index b87fdec..1ae4480 100644
--- a/preupload-hooks/GLOBAL-PREUPLOAD.cfg
+++ b/preupload-hooks/GLOBAL-PREUPLOAD.cfg
@@ -11,3 +11,8 @@
 
 [Builtin Hooks Options]
 clang_format = --commit ${PREUPLOAD_COMMIT} --style file --extensions c,h,cc,cpp
+
+[Hook Scripts]
+yapf-diff = ${REPO_ROOT}/scripts/preupload-hooks/yapf-diff.sh ${PREUPLOAD_COMMIT}
+# Add the following line to a project-local config file to bypass yapf-diff:
+# yapf-diff = ${REPO_ROOT}/scripts/preupload-hooks/yapf-diff.sh --bypass
diff --git a/preupload-hooks/yapf-diff.sh b/preupload-hooks/yapf-diff.sh
new file mode 100755
index 0000000..a0d22bf
--- /dev/null
+++ b/preupload-hooks/yapf-diff.sh
@@ -0,0 +1,30 @@
+#! /bin/bash
+# Wrapper to run yapf-diff for repo preupload.
+# Usage: if the first argument is --bypass, do nothing (exit 0). If the first
+# argument is a git hash, run yapf-diff on that commit, otherwise run yapf-diff
+# on the last commit. Any other arguments are passed to yapf-diff.
+# The script fails if yapf-diff produces any output.
+
+COMMIT="$(git log --format='%H' -1)"
+
+if [ $# -gt 0 ] ; then
+    if [ "$1" == "--bypass" ] ; then
+        exit 0
+    fi
+
+    if [[ ! "$1" =~ ^- ]] ; then
+        COMMIT="$1"
+        shift
+    fi
+fi
+
+if git show -U0 --no-color "${COMMIT}" | yapf-diff "$@" | grep --color=never . ; then
+    cat <<EOF
+
+
+Please fix the formatting issues above before uploading.
+You can apply the changes above by running:
+$0 $COMMIT -i
+EOF
+    exit 1
+fi
diff --git a/python-requirements.txt b/python-requirements.txt
index b8e0d81..24e6f1c 100644
--- a/python-requirements.txt
+++ b/python-requirements.txt
@@ -19,3 +19,4 @@
 setuptools
 tempita
 wget
+yapf