5 static const char git_update_ref_usage[] = "git-update-ref <refname> <value> [<oldval>]";
9 static const char *resolve_ref(const char *path, unsigned char *sha1)
11 int depth = MAXDEPTH, len;
22 /* Special case: non-existing file */
23 if (lstat(path, &st) < 0) {
30 /* Follow "normalized" - ie "refs/.." symlinks by hand */
31 if (S_ISLNK(st.st_mode)) {
32 len = readlink(path, buffer, sizeof(buffer)-1);
33 if (len >= 5 && !memcmp("refs/", buffer, 5)) {
34 path = git_path("%.*s", len, buffer);
40 * Anything else, just open it and try to use it as
43 fd = open(path, O_RDONLY);
46 len = read(fd, buffer, sizeof(buffer)-1);
50 * Is it a symbolic ref?
52 if (len < 4 || memcmp("ref:", buffer, 4))
56 while (len && isspace(*buf))
58 while (len && isspace(buf[len-1]))
60 path = git_path("%.*s", len, buf);
62 if (len < 40 || get_sha1_hex(buffer, sha1))
67 static int re_verify(const char *path, unsigned char *oldsha1, unsigned char *currsha1)
70 int fd = open(path, O_RDONLY), nr;
73 nr = read(fd, buf, 40);
75 if (nr != 40 || get_sha1_hex(buf, currsha1) < 0)
77 return memcmp(oldsha1, currsha1, 20) ? -1 : 0;
80 int main(int argc, char **argv)
83 const char *refname, *value, *oldval, *path, *lockpath;
84 unsigned char sha1[20], oldsha1[20], currsha1[20];
87 setup_git_directory();
88 if (argc < 3 || argc > 4)
89 usage(git_update_ref_usage);
94 if (get_sha1(value, sha1) < 0)
95 die("%s: not a valid SHA1", value);
96 memset(oldsha1, 0, 20);
97 if (oldval && get_sha1(oldval, oldsha1) < 0)
98 die("%s: not a valid old SHA1", oldval);
100 path = resolve_ref(git_path("%s", refname), currsha1);
102 die("No such ref: %s", refname);
105 if (memcmp(currsha1, oldsha1, 20))
106 die("Ref %s changed to %s", refname, sha1_to_hex(currsha1));
108 if (!memcmp(oldsha1, sha1, 20))
112 lockpath = mkpath("%s.lock", path);
114 fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
116 die("Unable to create %s", lockpath);
117 hex = sha1_to_hex(sha1);
119 written = write(fd, hex, 41);
123 die("Unable to write to %s", lockpath);
127 * Re-read the ref after getting the lock to verify
129 if (oldval && re_verify(path, oldsha1, currsha1) < 0) {
131 die("Ref lock failed");
135 * Finally, replace the old ref with the new one
137 if (rename(lockpath, path) < 0) {
139 die("Unable to create %s", path);