symbolic-ref --short: abbreviate the output unambiguously

It can be helpful to resolve a symbolic ref and output the result in a shortened form, such as for use in shell prompts. Add a "--short" option to do so. Signed-off-by: Jan Krüger <jk@jk.gs> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Jan Krüger committed Feb 27, 2012 at 23:10 UTC 42b00599be684e20462c431a718f86c2b6fce575
2 files changed +14 -4
Documentation/git-symbolic-ref.txt
+6 -1
@@ -8,7 +8,8 @@ git-symbolic-ref - Read and modify symbolic refs
8 SYNOPSIS
9 --------
10 [verse]
11 -'git symbolic-ref' [-q] [-m <reason>] <name> [<ref>]
11 +'git symbolic-ref' [-m <reason>] <name> <ref>
12 +'git symbolic-ref' [-q] [--short] <name>
13
14 DESCRIPTION
15 -----------
@@ -33,6 +34,10 @@ OPTIONS
34 symbolic ref but a detached HEAD; instead exit with
35 non-zero status silently.
36
37 +--short::
38 + When showing the value of <name> as a symbolic ref, try to shorten the
39 + value, e.g. from `refs/heads/master` to `master`.
40 +
41 -m::
42 Update the reflog for <name> with <reason>. This is valid only
43 when creating or updating a symbolic ref.
builtin/symbolic-ref.c
+8 -3
@@ -8,13 +8,15 @@ static const char * const git_symbolic_ref_usage[] = {
8 NULL
9 };
10
11 +static int shorten;
12 +
13 static void check_symref(const char *HEAD, int quiet)
14 {
15 unsigned char sha1[20];
16 int flag;
15 - const char *refs_heads_master = resolve_ref_unsafe(HEAD, sha1, 0, &flag);
17 + const char *refname = resolve_ref_unsafe(HEAD, sha1, 0, &flag);
18
17 - if (!refs_heads_master)
19 + if (!refname)
20 die("No such ref: %s", HEAD);
21 else if (!(flag & REF_ISSYMREF)) {
22 if (!quiet)
@@ -22,7 +24,9 @@ static void check_symref(const char *HEAD, int quiet)
24 else
25 exit(1);
26 }
25 - puts(refs_heads_master);
27 + if (shorten)
28 + refname = shorten_unambiguous_ref(refname, 0);
29 + puts(refname);
30 }
31
32 int cmd_symbolic_ref(int argc, const char **argv, const char *prefix)
@@ -32,6 +36,7 @@ int cmd_symbolic_ref(int argc, const char **argv, const char *prefix)
36 struct option options[] = {
37 OPT__QUIET(&quiet,
38 "suppress error message for non-symbolic (detached) refs"),
39 + OPT_BOOL(0, "short", &shorten, "shorten ref output"),
40 OPT_STRING('m', NULL, &msg, "reason", "reason of the update"),
41 OPT_END(),
42 };