check-ref-format --branch: strip refs/heads/ using skip_prefix

The expansion returned from strbuf_check_branch_ref always starts with "refs/heads/" by construction, but there is nothing about its name or advertised API making that obvious. This command is used to process human-supplied input from the command line and is usually not the inner loop, so we can spare some cycles to be more defensive. Instead of hard-coding the offset strlen("refs/heads/") to skip, verify that the expansion actually starts with refs/heads/. [jn: split out from a larger patch, added explanation] Signed-off-by: Junio C Hamano <gitster@pobox.com> Signed-off-by: Jonathan Nieder <jrnieder@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Junio C Hamano committed Oct 17, 2017 at 00:10 UTC 7ccc94ff4590cd035b7f78dfd9debbd7e692f3e6
1 file changed +4 -2
builtin/check-ref-format.c
+4 -2
@@ -39,12 +39,14 @@ static char *collapse_slashes(const char *refname)
39 static int check_ref_format_branch(const char *arg)
40 {
41 struct strbuf sb = STRBUF_INIT;
42 + const char *name;
43 int nongit;
44
45 setup_git_directory_gently(&nongit);
45 - if (strbuf_check_branch_ref(&sb, arg))
46 + if (strbuf_check_branch_ref(&sb, arg) ||
47 + !skip_prefix(sb.buf, "refs/heads/", &name))
48 die("'%s' is not a valid branch name", arg);
47 - printf("%s\n", sb.buf + 11);
49 + printf("%s\n", name);
50 return 0;
51 }
52