From 46eb449cbefac461659c42c4ba4b36de1959e7ca Mon Sep 17 00:00:00 2001
From: Johannes Schindelin <Johannes.Schindelin@gmx.de>
Date: Wed, 17 Oct 2007 03:23:10 +0100
Subject: [PATCH] filter-branch: update current branch when rewritten

Earlier, "git filter-branch --<options> HEAD" would not update the
working tree after rewriting the branch.  This commit fixes it.

Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.de>
Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
---
 git-filter-branch.sh     | 15 +++++++++++++++
 t/t7003-filter-branch.sh |  4 +++-
 2 files changed, 18 insertions(+), 1 deletion(-)

diff --git a/git-filter-branch.sh b/git-filter-branch.sh
index a12f6c2d4..ffcc408ee 100755
--- a/git-filter-branch.sh
+++ b/git-filter-branch.sh
@@ -94,6 +94,10 @@ USAGE="[--env-filter <command>] [--tree-filter <command>] \
 
 . git-sh-setup
 
+git diff-files --quiet &&
+	git diff-index --cached --quiet HEAD ||
+	die "Cannot rewrite branch(es) with a dirty working directory."
+
 tempdir=.git-rewrite
 filter_env=
 filter_tree=
@@ -196,6 +200,9 @@ do
 	esac
 done < "$tempdir"/backup-refs
 
+ORIG_GIT_DIR="$GIT_DIR"
+ORIG_GIT_WORK_TREE="$GIT_WORK_TREE"
+ORIG_GIT_INDEX_FILE="$GIT_INDEX_FILE"
 export GIT_DIR GIT_WORK_TREE=.
 
 # These refs should be updated if their heads were rewritten
@@ -413,4 +420,12 @@ echo
 test $count -gt 0 && echo "These refs were rewritten:"
 git show-ref | grep ^"$orig_namespace"
 
+unset GIT_DIR GIT_WORK_TREE GIT_INDEX_FILE
+test -z "$ORIG_GIT_DIR" || GIT_DIR="$ORIG_GIT_DIR" && export GIT_DIR
+test -z "$ORIG_GIT_WORK_TREE" || GIT_WORK_TREE="$ORIG_GIT_WORK_TREE" &&
+	export GIT_WORK_TREE
+test -z "$ORIG_GIT_INDEX_FILE" || GIT_INDEX_FILE="$ORIG_GIT_INDEX_FILE" &&
+	export GIT_INDEX_FILE
+git read-tree -u -m HEAD
+
 exit $ret
diff --git a/t/t7003-filter-branch.sh b/t/t7003-filter-branch.sh
index e935b2000..2089351f7 100755
--- a/t/t7003-filter-branch.sh
+++ b/t/t7003-filter-branch.sh
@@ -41,7 +41,9 @@ test_expect_success 'rewrite, renaming a specific file' '
 '
 
 test_expect_success 'test that the file was renamed' '
-	test d = $(git show HEAD:doh)
+	test d = $(git show HEAD:doh) &&
+	test -f doh &&
+	test d = $(cat doh)
 '
 
 git tag oldD HEAD~4
-- 
2.26.2