#!/bin/sh
#
# An example hook script to transform a patch taken from an email
# by git am.
#
# The hook should exit with non-zero status after issuing an
# appropriate message if it wants to stop the commit.  The hook is
# allowed to edit the patch file.
#
# To enable this hook, rename this file to "applypatch-transform".
#
# This example changes the path of Lib/unittest/mock.py to mock.py
# Lib/unittest/tests/testmock to tests and Misc/NEWS to NEWS, and
# finally skips any patches that did not alter mock.py or its tests.

set -eux

patch_path=$1

# Pull out mock.py
filterdiff --clean --strip 3 --addprefix=a/mock/ -i 'a/Lib/unittest/mock.py' -i 'b/Lib/unittest/mock.py' $patch_path > $patch_path.mock
# And the tests
filterdiff --clean --strip 5 --addprefix=a/mock/tests/ -i 'a/Lib/unittest/test/testmock/*.py' -i 'b/Lib/unittest/test/testmock/*.py' $patch_path > $patch_path.tests
# Lastly we want to pick up any NEWS entries.
filterdiff --strip 2 --addprefix=a/ -i a/Misc/NEWS -i b/Misc/NEWS $patch_path > $patch_path.NEWS
cp $patch_path $patch_path.orig
# bash
cat $patch_path.mock $patch_path.tests > $patch_path
filtered=$(cat $patch_path)
if [ -n "${filtered}" ]; then
  cat $patch_path.NEWS >> $patch_path
  exitcode=0
else
  exitcode=1
fi

rm $patch_path.mock $patch_path.tests $patch_path.NEWS
exit $exitcode
