f2506fa9762bd9d868076710f38dfc9137186828
1#include "cache.h"
2#include "refs.h"
3#include "builtin.h"
4
5static const char git_update_ref_usage[] =
6"git-update-ref [-m <reason>] (-d <refname> <value> | <refname> <value> [<oldval>])";
7
8int 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;
14
15 delete = 0;
16 setup_ident();
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 continue;
27 }
28 if (!strcmp("-d", argv[i])) {
29 delete = 1;
30 continue;
31 }
32 if (!refname) {
33 refname = argv[i];
34 continue;
35 }
36 if (!value) {
37 value = argv[i];
38 continue;
39 }
40 if (!oldval) {
41 oldval = argv[i];
42 continue;
43 }
44 }
45 if (!refname || !value)
46 usage(git_update_ref_usage);
47
48 if (get_sha1(value, sha1))
49 die("%s: not a valid SHA1", value);
50
51 if (delete) {
52 if (oldval)
53 usage(git_update_ref_usage);
54 return delete_ref(refname, sha1);
55 }
56
57 hashclr(oldsha1);
58 if (oldval && *oldval && get_sha1(oldval, oldsha1))
59 die("%s: not a valid old SHA1", oldval);
60
61 lock = lock_any_ref_for_update(refname, oldval ? oldsha1 : NULL);
62 if (!lock)
63 return 1;
64 if (write_ref_sha1(lock, sha1, msg) < 0)
65 return 1;
66
67 /* write_ref_sha1 always unlocks the ref, no need to do it explicitly */
68 return 0;
69}