branch: restrict @-expansions when deleting

We use strbuf_branchname() to expand the branch name from the command line, so you can delete the branch given by @{-1}, for example. However, we allow other nonsense like "@", and we do not respect our "-r" flag (so we may end up deleting an oddly-named local ref instead of a remote one). We can fix this by passing the appropriate "allowed" flag to strbuf_branchname(). Signed-off-by: Jeff King <peff@peff.net> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Jeff King committed Mar 2, 2017 at 03:23 UTC 6b145e016aaf512d0026cbd2c78fa28476f043b4
2 files changed +7 -4
builtin/branch.c
+4 -1
@@ -190,17 +190,20 @@ static int delete_branches(int argc, const char **argv, int force, int kinds,
190 int ret = 0;
191 int remote_branch = 0;
192 struct strbuf bname = STRBUF_INIT;
193 + unsigned allowed_interpret;
194
195 switch (kinds) {
196 case FILTER_REFS_REMOTES:
197 fmt = "refs/remotes/%s";
198 /* For subsequent UI messages */
199 remote_branch = 1;
200 + allowed_interpret = INTERPRET_BRANCH_REMOTE;
201
202 force = 1;
203 break;
204 case FILTER_REFS_BRANCHES:
205 fmt = "refs/heads/%s";
206 + allowed_interpret = INTERPRET_BRANCH_LOCAL;
207 break;
208 default:
209 die(_("cannot use -a with -d"));
@@ -215,7 +218,7 @@ static int delete_branches(int argc, const char **argv, int force, int kinds,
218 char *target = NULL;
219 int flags = 0;
220
218 - strbuf_branchname(&bname, argv[i], 0);
221 + strbuf_branchname(&bname, argv[i], allowed_interpret);
222 free(name);
223 name = mkpathdup(fmt, bname.buf);
224
t/t3204-branch-name-interpretation.sh
+3 -3
@@ -83,7 +83,7 @@ test_expect_success 'delete branch via remote @{upstream}' '
83 # Note that we create two oddly named local branches here. We want to make
84 # sure that we do not accidentally delete either of them, even if
85 # shorten_unambiguous_ref() tweaks the name to avoid ambiguity.
86 -test_expect_failure 'delete @{upstream} expansion matches -r option' '
86 +test_expect_success 'delete @{upstream} expansion matches -r option' '
87 git update-ref refs/remotes/origin/remote-del two &&
88 git branch --set-upstream-to=origin/remote-del &&
89 git update-ref refs/heads/origin/remote-del two &&
@@ -94,7 +94,7 @@ test_expect_failure 'delete @{upstream} expansion matches -r option' '
94 expect_branch refs/heads/remotes/origin/remote-del two
95 '
96
97 -test_expect_failure 'disallow deleting remote branch via @{-1}' '
97 +test_expect_success 'disallow deleting remote branch via @{-1}' '
98 git update-ref refs/remotes/origin/previous one &&
99
100 git checkout -b origin/previous two &&
@@ -114,7 +114,7 @@ test_expect_failure 'create branch named "@"' '
114 expect_branch refs/heads/@ one
115 '
116
117 -test_expect_failure 'delete branch named "@"' '
117 +test_expect_success 'delete branch named "@"' '
118 git update-ref refs/heads/@ two &&
119 git branch -D @ &&
120 expect_deleted refs/heads/@