The eleventh batch
[git/gitster.git] / builtin / symbolic-ref.c
blob299d23d76a83f3962bd00e7f8d515bb8438bff3d
1 #define USE_THE_REPOSITORY_VARIABLE
2 #include "builtin.h"
3 #include "config.h"
4 #include "gettext.h"
5 #include "refs.h"
6 #include "parse-options.h"
7 #include "strbuf.h"
9 static const char * const git_symbolic_ref_usage[] = {
10 N_("git symbolic-ref [-m <reason>] <name> <ref>"),
11 N_("git symbolic-ref [-q] [--short] [--no-recurse] <name>"),
12 N_("git symbolic-ref --delete [-q] <name>"),
13 NULL
16 static int check_symref(const char *HEAD, int quiet, int shorten, int recurse, int print)
18 int resolve_flags, flag;
19 const char *refname;
21 resolve_flags = (recurse ? 0 : RESOLVE_REF_NO_RECURSE);
22 refname = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
23 HEAD, resolve_flags, NULL, &flag);
25 if (!refname)
26 die("No such ref: %s", HEAD);
27 else if (!(flag & REF_ISSYMREF)) {
28 if (!quiet)
29 die("ref %s is not a symbolic ref", HEAD);
30 else
31 return 1;
33 if (print) {
34 char *to_free = NULL;
35 if (shorten)
36 refname = to_free = refs_shorten_unambiguous_ref(get_main_ref_store(the_repository),
37 refname,
38 0);
39 puts(refname);
40 free(to_free);
42 return 0;
45 int cmd_symbolic_ref(int argc,
46 const char **argv,
47 const char *prefix,
48 struct repository *repo UNUSED)
50 int quiet = 0, delete = 0, shorten = 0, recurse = 1, ret = 0;
51 const char *msg = NULL;
52 struct option options[] = {
53 OPT__QUIET(&quiet,
54 N_("suppress error message for non-symbolic (detached) refs")),
55 OPT_BOOL('d', "delete", &delete, N_("delete symbolic ref")),
56 OPT_BOOL(0, "short", &shorten, N_("shorten ref output")),
57 OPT_BOOL(0, "recurse", &recurse, N_("recursively dereference (default)")),
58 OPT_STRING('m', NULL, &msg, N_("reason"), N_("reason of the update")),
59 OPT_END(),
62 git_config(git_default_config, NULL);
63 argc = parse_options(argc, argv, prefix, options,
64 git_symbolic_ref_usage, 0);
65 if (msg && !*msg)
66 die("Refusing to perform update with empty message");
68 if (delete) {
69 if (argc != 1)
70 usage_with_options(git_symbolic_ref_usage, options);
71 ret = check_symref(argv[0], 1, 0, 0, 0);
72 if (ret)
73 die("Cannot delete %s, not a symbolic ref", argv[0]);
74 if (!strcmp(argv[0], "HEAD"))
75 die("deleting '%s' is not allowed", argv[0]);
76 return refs_delete_ref(get_main_ref_store(the_repository),
77 NULL, argv[0], NULL, REF_NO_DEREF);
80 switch (argc) {
81 case 1:
82 ret = check_symref(argv[0], quiet, shorten, recurse, 1);
83 break;
84 case 2:
85 if (!strcmp(argv[0], "HEAD") &&
86 !starts_with(argv[1], "refs/"))
87 die("Refusing to point HEAD outside of refs/");
88 if (check_refname_format(argv[1], REFNAME_ALLOW_ONELEVEL) < 0)
89 die("Refusing to set '%s' to invalid ref '%s'", argv[0], argv[1]);
90 ret = !!refs_update_symref(get_main_ref_store(the_repository),
91 argv[0], argv[1], msg);
92 break;
93 default:
94 usage_with_options(git_symbolic_ref_usage, options);
96 return ret;