- DIR *dir = opendir(base);
-
- if (dir) {
- struct dirent *de;
- int baselen = strlen(base);
- char *path = xmalloc(baselen + 257);
- memcpy(path, base, baselen);
-
- while ((de = readdir(dir)) != NULL) {
- char sha1[20];
- struct stat st;
- int namelen;
-
- 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);
+ const char *name = cmd->ref_name;
+ unsigned char *old_sha1 = cmd->old_sha1;
+ unsigned char *new_sha1 = cmd->new_sha1;
+ char new_hex[60], *old_hex, *lock_name;
+ int newfd, namelen, written;
+
+ cmd->error_string = NULL;
+ if (!strncmp(name, "refs/", 5) && check_ref_format(name + 5)) {
+ cmd->error_string = "funny refname";
+ return error("refusing to create funny ref '%s' locally",
+ name);
+ }
+
+ 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)) {
+ cmd->error_string = "bad pack";
+ return error("unpack should have generated %s, "
+ "but I can't find it!", new_hex);
+ }
+ safe_create_leading_directories(lock_name);
+
+ newfd = open(lock_name, O_CREAT | O_EXCL | O_WRONLY, 0666);
+ if (newfd < 0) {
+ cmd->error_string = "can't lock";
+ return error("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);
+ cmd->error_string = "can't write";
+ return error("unable to write %s", lock_name);
+ }
+ if (verify_old_ref(name, old_hex) < 0) {
+ unlink(lock_name);
+ cmd->error_string = "raced";
+ return error("%s changed during push", name);
+ }
+ if (run_update_hook(name, old_hex, new_hex)) {
+ unlink(lock_name);
+ cmd->error_string = "hook declined";
+ return error("hook declined to update %s", name);
+ }
+ else if (rename(lock_name, name) < 0) {
+ unlink(lock_name);
+ cmd->error_string = "can't rename";
+ return error("unable to replace %s", name);
+ }
+ else {
+ fprintf(stderr, "%s: %s -> %s\n", name, old_hex, new_hex);
+ return 0;