Merge branch 'tb/save-keep-pack-during-geometric-repack'
[git/debian.git] / builtin / symbolic-ref.c
blob590ed17dd3f52934ff5cd3bcdd4070ac3d015105
1 #include "builtin.h"
2 #include "config.h"
3 #include "cache.h"
4 #include "refs.h"
5 #include "parse-options.h"
7 static const char * const git_symbolic_ref_usage[] = {
8 N_("git symbolic-ref [<options>] <name> [<ref>]"),
9 N_("git symbolic-ref -d [-q] [--no-recurse] <name>"),
10 NULL
13 static int check_symref(const char *HEAD, int quiet, int shorten, int recurse, int print)
15 int resolve_flags, flag;
16 const char *refname;
18 resolve_flags = (recurse ? 0 : RESOLVE_REF_NO_RECURSE);
19 refname = resolve_ref_unsafe(HEAD, resolve_flags, NULL, &flag);
21 if (!refname)
22 die("No such ref: %s", HEAD);
23 else if (!(flag & REF_ISSYMREF)) {
24 if (!quiet)
25 die("ref %s is not a symbolic ref", HEAD);
26 else
27 return 1;
29 if (print) {
30 char *to_free = NULL;
31 if (shorten)
32 refname = to_free = shorten_unambiguous_ref(refname, 0);
33 puts(refname);
34 free(to_free);
36 return 0;
39 int cmd_symbolic_ref(int argc, const char **argv, const char *prefix)
41 int quiet = 0, delete = 0, shorten = 0, recurse = 1, ret = 0;
42 const char *msg = NULL;
43 struct option options[] = {
44 OPT__QUIET(&quiet,
45 N_("suppress error message for non-symbolic (detached) refs")),
46 OPT_BOOL('d', "delete", &delete, N_("delete symbolic ref")),
47 OPT_BOOL(0, "short", &shorten, N_("shorten ref output")),
48 OPT_BOOL(0, "recurse", &recurse, N_("recursively dereference (default)")),
49 OPT_STRING('m', NULL, &msg, N_("reason"), N_("reason of the update")),
50 OPT_END(),
53 git_config(git_default_config, NULL);
54 argc = parse_options(argc, argv, prefix, options,
55 git_symbolic_ref_usage, 0);
56 if (msg && !*msg)
57 die("Refusing to perform update with empty message");
59 if (delete) {
60 if (argc != 1)
61 usage_with_options(git_symbolic_ref_usage, options);
62 ret = check_symref(argv[0], 1, 0, 0, 0);
63 if (ret)
64 die("Cannot delete %s, not a symbolic ref", argv[0]);
65 if (!strcmp(argv[0], "HEAD"))
66 die("deleting '%s' is not allowed", argv[0]);
67 return delete_ref(NULL, argv[0], NULL, REF_NO_DEREF);
70 switch (argc) {
71 case 1:
72 ret = check_symref(argv[0], quiet, shorten, recurse, 1);
73 break;
74 case 2:
75 if (!strcmp(argv[0], "HEAD") &&
76 !starts_with(argv[1], "refs/"))
77 die("Refusing to point HEAD outside of refs/");
78 if (check_refname_format(argv[1], REFNAME_ALLOW_ONELEVEL) < 0)
79 die("Refusing to set '%s' to invalid ref '%s'", argv[0], argv[1]);
80 ret = !!create_symref(argv[0], argv[1], msg);
81 break;
82 default:
83 usage_with_options(git_symbolic_ref_usage, options);
85 return ret;