Skip to content

Commit 3f59481

Browse files
jrngitster
authored andcommitted
branch: allow a no-op "branch -M <current-branch> HEAD"
Overwriting the current branch with a different commit is forbidden, as it will make the status recorded in the index and the working tree out of sync with respect to the HEAD. There however is no reason to forbid it if the current branch is renamed to itself, which admittedly is something only an insane user would do, but is handy for scripts. Test script is by Conrad Irwin. Reported-by: Soeren Sonnenburg <[email protected]> Reported-by: Josh Chia (谢任中) Signed-off-by: Jonathan Nieder <[email protected]> Signed-off-by: Conrad Irwin <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 017d1e1 commit 3f59481

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

builtin/branch.c

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -568,6 +568,7 @@ static void rename_branch(const char *oldname, const char *newname, int force)
568568
unsigned char sha1[20];
569569
struct strbuf oldsection = STRBUF_INIT, newsection = STRBUF_INIT;
570570
int recovery = 0;
571+
int clobber_head_ok;
571572

572573
if (!oldname)
573574
die(_("cannot rename the current branch while not on any."));
@@ -583,7 +584,13 @@ static void rename_branch(const char *oldname, const char *newname, int force)
583584
die(_("Invalid branch name: '%s'"), oldname);
584585
}
585586

586-
validate_new_branchname(newname, &newref, force, 0);
587+
/*
588+
* A command like "git branch -M currentbranch currentbranch" cannot
589+
* cause the worktree to become inconsistent with HEAD, so allow it.
590+
*/
591+
clobber_head_ok = !strcmp(oldname, newname);
592+
593+
validate_new_branchname(newname, &newref, force, clobber_head_ok);
587594

588595
strbuf_addf(&logmsg, "Branch: renamed %s to %s",
589596
oldref.buf, newref.buf);

t/t3200-branch.sh

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,22 @@ test_expect_success 'git branch -M baz bam should succeed when baz is checked ou
115115
git branch -M baz bam
116116
'
117117

118+
test_expect_success 'git branch -M master should work when master is checked out' '
119+
git checkout master &&
120+
git branch -M master
121+
'
122+
123+
test_expect_success 'git branch -M master master should work when master is checked out' '
124+
git checkout master &&
125+
git branch -M master master
126+
'
127+
128+
test_expect_success 'git branch -M master2 master2 should work when master is checked out' '
129+
git checkout master &&
130+
git branch master2 &&
131+
git branch -M master2 master2
132+
'
133+
118134
test_expect_success 'git branch -v -d t should work' '
119135
git branch t &&
120136
test_path_is_file .git/refs/heads/t &&

0 commit comments

Comments
 (0)