5 static const char git_update_ref_usage[] = "git-update-ref <refname> <value> [<oldval>]";
9 const char *resolve_ref(const char *path, unsigned char *sha1)
11 int depth = MAXDEPTH, len;
21 /* Special case: non-existing file */
22 if (lstat(path, &st) < 0) {
29 /* Follow "normalized" - ie "refs/.." symlinks by hand */
30 if (S_ISLNK(st.st_mode)) {
31 len = readlink(path, buffer, sizeof(buffer)-1);
32 if (len >= 5 && !memcmp("refs/", buffer, 5)) {
33 path = git_path("%.*s", len, buffer);
39 * Anything else, just open it and try to use it as
42 fd = open(path, O_RDONLY);
45 len = read(fd, buffer, sizeof(buffer)-1);
49 if (len < 40 || get_sha1_hex(buffer, sha1))
54 static int re_verify(const char *path, unsigned char *oldsha1, unsigned char *currsha1)
57 int fd = open(path, O_RDONLY), nr;
60 nr = read(fd, buf, 40);
62 if (nr != 40 || get_sha1_hex(buf, currsha1) < 0)
64 return memcmp(oldsha1, currsha1, 20) ? -1 : 0;
67 int main(int argc, char **argv)
70 const char *refname, *value, *oldval, *path, *lockpath;
71 unsigned char sha1[20], oldsha1[20], currsha1[20];
74 setup_git_directory();
75 if (argc < 3 || argc > 4)
76 usage(git_update_ref_usage);
81 if (get_sha1(value, sha1) < 0)
82 die("%s: not a valid SHA1", value);
83 memset(oldsha1, 0, 20);
84 if (oldval && get_sha1(oldval, oldsha1) < 0)
85 die("%s: not a valid old SHA1", oldval);
87 path = resolve_ref(git_path("%s", refname), currsha1);
89 die("No such ref: %s", refname);
92 if (memcmp(currsha1, oldsha1, 20))
93 die("Ref %s changed to %s", refname, sha1_to_hex(currsha1));
95 if (!memcmp(oldsha1, sha1, 20))
99 lockpath = mkpath("%s.lock", path);
101 fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
103 die("Unable to create %s", lockpath);
104 hex = sha1_to_hex(sha1);
106 written = write(fd, hex, 41);
110 die("Unable to write to %s", lockpath);
114 * Re-read the ref after getting the lock to verify
116 if (oldval && re_verify(path, oldsha1, currsha1) < 0) {
118 die("Ref lock failed");
122 * Finally, replace the old ref with the new one
124 if (rename(lockpath, path) < 0) {
126 die("Unable to create %s", path);