Merge branch 'gb/idx'
[git] / builtin-update-ref.c
1 #include "cache.h"
2 #include "refs.h"
3 #include "builtin.h"
4
5 static const char git_update_ref_usage[] =
6 "git-update-ref [-m <reason>] (-d <refname> <value> | [--no-deref] <refname> <value> [<oldval>])";
7
8 int cmd_update_ref(int argc, const char **argv, const char *prefix)
9 {
10         const char *refname=NULL, *value=NULL, *oldval=NULL, *msg=NULL;
11         struct ref_lock *lock;
12         unsigned char sha1[20], oldsha1[20];
13         int i, delete, ref_flags;
14
15         delete = 0;
16         ref_flags = 0;
17         git_config(git_default_config);
18
19         for (i = 1; i < argc; i++) {
20                 if (!strcmp("-m", argv[i])) {
21                         if (i+1 >= argc)
22                                 usage(git_update_ref_usage);
23                         msg = argv[++i];
24                         if (!*msg)
25                                 die("Refusing to perform update with empty message.");
26                         if (strchr(msg, '\n'))
27                                 die("Refusing to perform update with \\n in message.");
28                         continue;
29                 }
30                 if (!strcmp("-d", argv[i])) {
31                         delete = 1;
32                         continue;
33                 }
34                 if (!strcmp("--no-deref", argv[i])) {
35                         ref_flags |= REF_NODEREF;
36                         continue;
37                 }
38                 if (!refname) {
39                         refname = argv[i];
40                         continue;
41                 }
42                 if (!value) {
43                         value = argv[i];
44                         continue;
45                 }
46                 if (!oldval) {
47                         oldval = argv[i];
48                         continue;
49                 }
50         }
51         if (!refname || !value)
52                 usage(git_update_ref_usage);
53
54         if (get_sha1(value, sha1))
55                 die("%s: not a valid SHA1", value);
56
57         if (delete) {
58                 if (oldval)
59                         usage(git_update_ref_usage);
60                 return delete_ref(refname, sha1);
61         }
62
63         hashclr(oldsha1);
64         if (oldval && *oldval && get_sha1(oldval, oldsha1))
65                 die("%s: not a valid old SHA1", oldval);
66
67         lock = lock_any_ref_for_update(refname, oldval ? oldsha1 : NULL, ref_flags);
68         if (!lock)
69                 die("%s: cannot lock the ref", refname);
70         if (write_ref_sha1(lock, sha1, msg) < 0)
71                 die("%s: cannot update the ref", refname);
72         return 0;
73 }