b3d5470cc09ad35f7baa79bc618c8dda3be2f324
1 #include "cache.h"
2 #include "refs.h"
4 static const char *result_path, *lock_path;
6 static void remove_lock_file(void)
7 {
8 if (lock_path)
9 unlink(lock_path);
10 }
12 static int handle_one_ref(const char *path, const unsigned char *sha1, void *cb_data)
13 {
14 FILE *refs_file = cb_data;
16 fprintf(refs_file, "%s %s\n", sha1_to_hex(sha1), path);
17 return 0;
18 }
20 int cmd_pack_refs(int argc, const char **argv, const char *prefix)
21 {
22 int fd;
23 FILE *refs_file;
25 result_path = xstrdup(git_path("packed-refs"));
26 lock_path = xstrdup(mkpath("%s.lock", result_path));
28 fd = open(lock_path, O_CREAT | O_EXCL | O_WRONLY, 0666);
29 if (fd < 0)
30 die("unable to create new ref-pack file (%s)", strerror(errno));
31 atexit(remove_lock_file);
33 refs_file = fdopen(fd, "w");
34 if (!refs_file)
35 die("unable to create ref-pack file structure (%s)", strerror(errno));
36 for_each_ref(handle_one_ref, refs_file);
37 fsync(fd);
38 fclose(refs_file);
39 if (rename(lock_path, result_path) < 0)
40 die("unable to overwrite old ref-pack file (%s)", strerror(errno));
41 lock_path = NULL;
42 return 0;
43 }