git-compat-util: add a FREE_AND_NULL() wrapper around free(ptr); ptr = NULL
[alt-git.git] / builtin / symbolic-ref.c
blob70addef158b347488366f6c5787d326c3657adcd
1 #include "builtin.h"
2 #include "cache.h"
3 #include "refs.h"
4 #include "parse-options.h"
6 static const char * const git_symbolic_ref_usage[] = {
7 N_("git symbolic-ref [<options>] <name> [<ref>]"),
8 N_("git symbolic-ref -d [-q] <name>"),
9 NULL
12 static int check_symref(const char *HEAD, int quiet, int shorten, int print)
14 unsigned char sha1[20];
15 int flag;
16 const char *refname = resolve_ref_unsafe(HEAD, 0, sha1, &flag);
18 if (!refname)
19 die("No such ref: %s", HEAD);
20 else if (!(flag & REF_ISSYMREF)) {
21 if (!quiet)
22 die("ref %s is not a symbolic ref", HEAD);
23 else
24 return 1;
26 if (print) {
27 if (shorten)
28 refname = shorten_unambiguous_ref(refname, 0);
29 puts(refname);
31 return 0;
34 int cmd_symbolic_ref(int argc, const char **argv, const char *prefix)
36 int quiet = 0, delete = 0, shorten = 0, ret = 0;
37 const char *msg = NULL;
38 struct option options[] = {
39 OPT__QUIET(&quiet,
40 N_("suppress error message for non-symbolic (detached) refs")),
41 OPT_BOOL('d', "delete", &delete, N_("delete symbolic ref")),
42 OPT_BOOL(0, "short", &shorten, N_("shorten ref output")),
43 OPT_STRING('m', NULL, &msg, N_("reason"), N_("reason of the update")),
44 OPT_END(),
47 git_config(git_default_config, NULL);
48 argc = parse_options(argc, argv, prefix, options,
49 git_symbolic_ref_usage, 0);
50 if (msg && !*msg)
51 die("Refusing to perform update with empty message");
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 if (!strcmp(argv[0], "HEAD"))
60 die("deleting '%s' is not allowed", argv[0]);
61 return delete_ref(NULL, argv[0], NULL, REF_NODEREF);
64 switch (argc) {
65 case 1:
66 ret = check_symref(argv[0], quiet, shorten, 1);
67 break;
68 case 2:
69 if (!strcmp(argv[0], "HEAD") &&
70 !starts_with(argv[1], "refs/"))
71 die("Refusing to point HEAD outside of refs/");
72 ret = !!create_symref(argv[0], argv[1], msg);
73 break;
74 default:
75 usage_with_options(git_symbolic_ref_usage, options);
77 return ret;