Merge branch 'jl/submodule-rm'
[git] / builtin / symbolic-ref.c
1 #include "builtin.h"
2 #include "cache.h"
3 #include "refs.h"
4 #include "parse-options.h"
5
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
10 };
11
12 static int check_symref(const char *HEAD, int quiet, int shorten, int print)
13 {
14         unsigned char sha1[20];
15         int flag;
16         const char *refname = resolve_ref_unsafe(HEAD, sha1, 0, &flag);
17
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;
25         }
26         if (print) {
27                 if (shorten)
28                         refname = shorten_unambiguous_ref(refname, 0);
29                 puts(refname);
30         }
31         return 0;
32 }
33
34 int cmd_symbolic_ref(int argc, const char **argv, const char *prefix)
35 {
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(),
45         };
46
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");
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
62         switch (argc) {
63         case 1:
64                 ret = check_symref(argv[0], quiet, shorten, 1);
65                 break;
66         case 2:
67                 if (!strcmp(argv[0], "HEAD") &&
68                     prefixcmp(argv[1], "refs/"))
69                         die("Refusing to point HEAD outside of refs/");
70                 create_symref(argv[0], argv[1], msg);
71                 break;
72         default:
73                 usage_with_options(git_symbolic_ref_usage, options);
74         }
75         return ret;
76 }