t5541: run "used receive-pack service" test earlier
[git/debian.git] / builtin / symbolic-ref.c
blobe00768a8b7ec48b04f670087730495b50353787e
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 [-m <reason>] <name> <ref>"),
9 N_("git symbolic-ref [-q] [--short] [--no-recurse] <name>"),
10 N_("git symbolic-ref --delete [-q] <name>"),
11 NULL
14 static int check_symref(const char *HEAD, int quiet, int shorten, int recurse, int print)
16 int resolve_flags, flag;
17 const char *refname;
19 resolve_flags = (recurse ? 0 : RESOLVE_REF_NO_RECURSE);
20 refname = resolve_ref_unsafe(HEAD, resolve_flags, NULL, &flag);
22 if (!refname)
23 die("No such ref: %s", HEAD);
24 else if (!(flag & REF_ISSYMREF)) {
25 if (!quiet)
26 die("ref %s is not a symbolic ref", HEAD);
27 else
28 return 1;
30 if (print) {
31 char *to_free = NULL;
32 if (shorten)
33 refname = to_free = shorten_unambiguous_ref(refname, 0);
34 puts(refname);
35 free(to_free);
37 return 0;
40 int cmd_symbolic_ref(int argc, const char **argv, const char *prefix)
42 int quiet = 0, delete = 0, shorten = 0, recurse = 1, ret = 0;
43 const char *msg = NULL;
44 struct option options[] = {
45 OPT__QUIET(&quiet,
46 N_("suppress error message for non-symbolic (detached) refs")),
47 OPT_BOOL('d', "delete", &delete, N_("delete symbolic ref")),
48 OPT_BOOL(0, "short", &shorten, N_("shorten ref output")),
49 OPT_BOOL(0, "recurse", &recurse, N_("recursively dereference (default)")),
50 OPT_STRING('m', NULL, &msg, N_("reason"), N_("reason of the update")),
51 OPT_END(),
54 git_config(git_default_config, NULL);
55 argc = parse_options(argc, argv, prefix, options,
56 git_symbolic_ref_usage, 0);
57 if (msg && !*msg)
58 die("Refusing to perform update with empty message");
60 if (delete) {
61 if (argc != 1)
62 usage_with_options(git_symbolic_ref_usage, options);
63 ret = check_symref(argv[0], 1, 0, 0, 0);
64 if (ret)
65 die("Cannot delete %s, not a symbolic ref", argv[0]);
66 if (!strcmp(argv[0], "HEAD"))
67 die("deleting '%s' is not allowed", argv[0]);
68 return delete_ref(NULL, argv[0], NULL, REF_NO_DEREF);
71 switch (argc) {
72 case 1:
73 ret = check_symref(argv[0], quiet, shorten, recurse, 1);
74 break;
75 case 2:
76 if (!strcmp(argv[0], "HEAD") &&
77 !starts_with(argv[1], "refs/"))
78 die("Refusing to point HEAD outside of refs/");
79 if (check_refname_format(argv[1], REFNAME_ALLOW_ONELEVEL) < 0)
80 die("Refusing to set '%s' to invalid ref '%s'", argv[0], argv[1]);
81 ret = !!create_symref(argv[0], argv[1], msg);
82 break;
83 default:
84 usage_with_options(git_symbolic_ref_usage, options);
86 return ret;