Skip to content

Instantly share code, notes, and snippets.

@nhoriguchi
Last active December 12, 2019 16:10
Show Gist options
  • Save nhoriguchi/79dbda89a7ffa5e9421341b6b899a1c7 to your computer and use it in GitHub Desktop.
Save nhoriguchi/79dbda89a7ffa5e9421341b6b899a1c7 to your computer and use it in GitHub Desktop.
#!/bin/bash
#
# Usage
# git-edit.sh [-h|--help] [-s|--split]
#
# Description
# カレントディレクトリを含むリポジトリの HEAD コミットを編集する。
# EDITOR で HEAD コミットが開くので、編集してエディタを閉じると反映される。
# -s オプションを与えた場合、HEAD コミットが二分割される。そこでは
# 編集後のパッチが前半、もともとの HEAD との差分が後半のパッチとなる。
#
show_help() {
sed -n 2,$[$BASH_LINENO-4]p $BASH_SOURCE | grep "^#" | sed 's/^#/ /'
}
SPLIT=
while [[ $# -gt 0 ]] ; do
key="$1"
case $key in
-s|--split)
SPLIT=true
shift 1
;;
-h|--help)
show_help
exit 0
;;
*) # end of options
break
;;
esac
done
TSTAMP="`date +%y%m%d_%H%M%S`"
mkdir -p /tmp/$(basename $BASH_SOURCE)
TMPD=$(mktemp -d /tmp/$(basename $BASH_SOURCE)/${TSTAMP}.XXXXXX)
git am --abort > /dev/null 2>&1
if ! git diff --quiet ; then
echo "Current working tree is dirty." >&2
exit 1
fi
if [ ! "$EDITOR" ] ; then
echo "You need set environment variable EDITOR to your favorite editor" >&2
exit 1
fi
NR_PARENT=$(git cat-file -p HEAD | grep ^parent | wc -l)
if [ "$NR_PARENT" -ne 1 ] ; then
echo "More than one parent or invalid tree" >&2
exit 1
fi
HEAD=$(git rev-parse HEAD)
if [ ! "$HEAD" ] ; then
echo "Failed to get commit ID of HEAD" >&2
exit 1
fi
PATCH=$(git format-patch --no-signature HEAD~1..HEAD)
if [ ! "$PATCH" ] ; then
exit 1
fi
if [ "$SPLIT" ] ; then
SECONDPATCH=${TMPD}/2nd.desc.txt
cat <<EOF > $SECONDPATCH
From: $(git config -z --get user.name) <$(git config -z --get user.email)>
description for 2nd-half
EOF
$EDITOR $SECONDPATCH $PATCH
else
$EDITOR $PATCH
fi
# diff check
CBRANCH=$(git rev-parse --abbrev-ref HEAD)
git checkout --detach HEAD~1 || exit 1
# apply editted patch
git am --ignore-whitespace --ignore-space-change $PATCH || exit 1
if [ "$SPLIT" ] ; then
git diff HEAD..$HEAD > ${TMPD}/2nd.diff
cat $SECONDPATCH > ${TMPD}/2nd.patch
echo >> ${TMPD}/2nd.patch
cat ${TMPD}/2nd.diff >> ${TMPD}/2nd.patch
git am --ignore-whitespace --ignore-space-change ${TMPD}/2nd.patch || exit 1
fi
git checkout -B $CBRANCH || exit 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment