- if (de->d_name[0] == '.')
- continue;
- namelen = strlen(de->d_name);
- if (namelen > 255)
- continue;
- memcpy(path + baselen, de->d_name, namelen+1);
- if (lstat(path, &st) < 0)
- continue;
- if (S_ISDIR(st.st_mode)) {
- path[baselen + namelen] = '/';
- path[baselen + namelen + 1] = 0;
- write_head_info(path, nr, match);
- continue;
- }
- if (read_ref(path, sha1) < 0)
- continue;
- if (nr && !path_match(path, nr, match))
- continue;
- show_ref(path, sha1);
- }
- free(path);
- closedir(dir);
+static void update(const char *name, unsigned char *old_sha1, unsigned char *new_sha1)
+{
+ char new_hex[60], *old_hex, *lock_name;
+ int newfd, namelen, written;
+
+ namelen = strlen(name);
+ lock_name = xmalloc(namelen + 10);
+ memcpy(lock_name, name, namelen);
+ memcpy(lock_name + namelen, ".lock", 6);
+
+ strcpy(new_hex, sha1_to_hex(new_sha1));
+ old_hex = sha1_to_hex(old_sha1);
+ if (!has_sha1_file(new_sha1))
+ die("unpack should have generated %s, but I can't find it!", new_hex);
+
+ newfd = open(lock_name, O_CREAT | O_EXCL | O_WRONLY, 0666);
+ if (newfd < 0)
+ die("unable to create %s (%s)", lock_name, strerror(errno));
+
+ /* Write the ref with an ending '\n' */
+ new_hex[40] = '\n';
+ new_hex[41] = 0;
+ written = write(newfd, new_hex, 41);
+ /* Remove the '\n' again */
+ new_hex[40] = 0;
+
+ close(newfd);
+ if (written != 41) {
+ unlink(lock_name);
+ die("unable to write %s", lock_name);
+ }
+ if (verify_old_ref(name, old_hex) < 0) {
+ unlink(lock_name);
+ die("%s changed during push", name);
+ }
+ if (rename(lock_name, name) < 0) {
+ unlink(lock_name);
+ die("unable to replace %s", name);