symbolic-ref: propagate error code from create_symref()
[git/git.git] / builtin / symbolic-ref.c
CommitLineData
640ce105 1#include "builtin.h"
8098a178 2#include "cache.h"
8da19775 3#include "refs.h"
78558614 4#include "parse-options.h"
8098a178 5
78558614 6static const char * const git_symbolic_ref_usage[] = {
9c9b4f2f
AH
7 N_("git symbolic-ref [<options>] <name> [<ref>]"),
8 N_("git symbolic-ref -d [-q] <name>"),
78558614
PH
9 NULL
10};
8098a178 11
9ab55daa 12static int check_symref(const char *HEAD, int quiet, int shorten, int print)
8098a178
JH
13{
14 unsigned char sha1[20];
8da19775 15 int flag;
7695d118 16 const char *refname = resolve_ref_unsafe(HEAD, 0, sha1, &flag);
ed378ec7 17
42b00599 18 if (!refname)
8098a178 19 die("No such ref: %s", HEAD);
a0f4280f
JH
20 else if (!(flag & REF_ISSYMREF)) {
21 if (!quiet)
22 die("ref %s is not a symbolic ref", HEAD);
23 else
9ab55daa
JH
24 return 1;
25 }
26 if (print) {
27 if (shorten)
28 refname = shorten_unambiguous_ref(refname, 0);
29 puts(refname);
a0f4280f 30 }
9ab55daa 31 return 0;
8098a178
JH
32}
33
640ce105 34int cmd_symbolic_ref(int argc, const char **argv, const char *prefix)
8098a178 35{
9ab55daa 36 int quiet = 0, delete = 0, shorten = 0, ret = 0;
8b5157e4 37 const char *msg = NULL;
78558614 38 struct option options[] = {
8c839683 39 OPT__QUIET(&quiet,
b10bf3fa 40 N_("suppress error message for non-symbolic (detached) refs")),
9ab55daa 41 OPT_BOOL('d', "delete", &delete, N_("delete symbolic ref")),
b10bf3fa
NTND
42 OPT_BOOL(0, "short", &shorten, N_("shorten ref output")),
43 OPT_STRING('m', NULL, &msg, N_("reason"), N_("reason of the update")),
78558614
PH
44 OPT_END(),
45 };
a0f4280f 46
ef90d6d4 47 git_config(git_default_config, NULL);
37782920
SB
48 argc = parse_options(argc, argv, prefix, options,
49 git_symbolic_ref_usage, 0);
c01499ef 50 if (msg && !*msg)
78558614 51 die("Refusing to perform update with empty message");
9ab55daa
JH
52
53 if (delete) {
54 if (argc != 1)
55 usage_with_options(git_symbolic_ref_usage, options);
56 ret = check_symref(argv[0], 1, 0, 0);
57 if (ret)
58 die("Cannot delete %s, not a symbolic ref", argv[0]);
59 return delete_ref(argv[0], NULL, REF_NODEREF);
60 }
61
8098a178 62 switch (argc) {
78558614 63 case 1:
9ab55daa 64 ret = check_symref(argv[0], quiet, shorten, 1);
8098a178 65 break;
78558614 66 case 2:
afe5d3d5 67 if (!strcmp(argv[0], "HEAD") &&
59556548 68 !starts_with(argv[1], "refs/"))
e9cc02f0 69 die("Refusing to point HEAD outside of refs/");
3e4068ed 70 ret = !!create_symref(argv[0], argv[1], msg);
8098a178
JH
71 break;
72 default:
78558614 73 usage_with_options(git_symbolic_ref_usage, options);
8098a178 74 }
9ab55daa 75 return ret;
8098a178 76}